graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(spec): StructuredOutput + TerminalModes kernels — 10-kernel corpus, 3,642 cells
Rach Pradhan55a9c00b8f99
diff --git a/TUI/root.zig b/TUI/root.zigindex 11b85094..826bc6b9 100644--- a/TUI/root.zig+++ b/TUI/root.zig@@ -42,6 +42,7 @@ test {_ = @import("key.zig");_ = @import("key_orphan.zig");_ = @import("key_tests.zig");+ _ = @import("spec_terminal_modes_conformance.zig");_ = @import("key_loop_tests.zig");_ = @import("input.zig");_ = @import("keys.zig");diff --git a/TUI/run.zig b/TUI/run.zigindex 37c8de6c..5140a25f 100644--- a/TUI/run.zig+++ b/TUI/run.zig@@ -21,7 +21,7 @@ const Model = app.Model;// 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 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,diff --git a/TUI/spec_terminal_modes_conformance.zig b/TUI/spec_terminal_modes_conformance.zignew file mode 100644index 00000000..bd0caef7--- /dev/null+++ b/TUI/spec_terminal_modes_conformance.zig@@ -0,0 +1,130 @@+//! Impl half of TerminalModes: the LIVE enable/restore constants (run.zig+//! enable_seq, restore.zig seq) are parsed into mode ops and folded with a+//! mirror of the model; the fixture pins both the byte strings and the+//! folded outcomes, so drift in either the constants or the model trips.++const std = @import("std");+const Value = std.json.Value;+const run = @import("run.zig");+const restore = @import("restore.zig");++const fixtures_json = @embedFile("spec_terminal_modes");++const default_on = [_]u32{ 7, 25 };++const Fold = struct {+ // mode -> final op (true = h). Tiny domains; linear scan is fine.+ modes: [16]struct { n: u32, v: bool } = undefined,+ len: usize = 0,+ depth: u32 = 0,++ fn setFinal(self: *@This(), n: u32, v: bool) void {+ for (self.modes[0..self.len]) |*m| if (m.n == n) {+ m.v = v;+ return;+ };+ self.modes[self.len] = .{ .n = n, .v = v };+ self.len += 1;+ }++ fn isDefaultOn(n: u32) bool {+ for (default_on) |d| if (d == n) return true;+ return false;+ }++ fn deviations(self: *const @This(), out: []u32) []u32 {+ var k: usize = 0;+ for (self.modes[0..self.len]) |m| if (m.v != isDefaultOn(m.n)) {+ out[k] = m.n;+ k += 1;+ };+ std.mem.sort(u32, out[0..k], {}, std.sort.asc(u32));+ return out[0..k];+ }+};++/// Scan a byte stream for DEC private-mode ops and kitty push/pop, in order.+fn fold(stream: []const u8) Fold {+ var f: Fold = .{};+ var i: usize = 0;+ while (i + 2 < stream.len) : (i += 1) {+ if (stream[i] != 0x1b or stream[i + 1] != '[') continue;+ var j = i + 2;+ if (stream[j] == '?') {+ j += 1;+ while (j < stream.len and ((stream[j] >= '0' and stream[j] <= '9') or stream[j] == ';')) j += 1;+ if (j < stream.len and (stream[j] == 'h' or stream[j] == 'l')) {+ // Apply the final h/l to every ';'-separated parameter.+ const v = stream[j] == 'h';+ var k = i + 3;+ var m: u32 = 0;+ while (k <= j) : (k += 1) {+ const c = stream[k];+ if (c >= '0' and c <= '9') {+ m = m * 10 + (c - '0');+ } else {+ f.setFinal(m, v);+ m = 0;+ }+ }+ i = j;+ }+ } else if (stream[j] == '>' or stream[j] == '<') {+ const open = stream[j];+ j += 1;+ while (j < stream.len and ((stream[j] >= '0' and stream[j] <= '9') or stream[j] == ';')) j += 1;+ if (j < stream.len and stream[j] == 'u') {+ if (open == '>') f.depth += 1 else f.depth -|= 1;+ i = j;+ }+ }+ }+ return f;+}++test "spec/terminal_modes: the live constants equal the fixture's byte strings" {+ const gpa = std.testing.allocator;+ var parsed = try std.json.parseFromSlice(Value, gpa, fixtures_json, .{});+ defer parsed.deinit();+ try std.testing.expectEqualStrings(parsed.value.object.get("graff_enable").?.string, run.enable_seq);+ try std.testing.expectEqualStrings(parsed.value.object.get("graff_restore").?.string, restore.seq);+}++test "spec/terminal_modes: every fixture stream folds to its recorded outcome" {+ const gpa = std.testing.allocator;+ var parsed = try std.json.parseFromSlice(Value, gpa, fixtures_json, .{});+ defer parsed.deinit();+ const cells = parsed.value.object.get("cells").?.array.items;+ try std.testing.expectEqual(@as(usize, 14), cells.len);+ for (cells) |cell_v| {+ const cell = cell_v.object;+ const name = cell.get("name").?.string;+ var f = fold(cell.get("stream").?.string);+ var buf: [16]u32 = undefined;+ const devs = f.deviations(&buf);+ const want_devs = cell.get("deviations").?.array.items;+ const want_depth: u32 = @intCast(cell.get("depth").?.integer);+ const want_balanced = cell.get("balanced").?.bool;+ const balanced = devs.len == 0 and f.depth == 0;+ var match = devs.len == want_devs.len and f.depth == want_depth and balanced == want_balanced;+ if (match) for (devs, want_devs) |g, w| {+ if (g != @as(u32, @intCast(w.integer))) match = false;+ };+ if (!match) {+ std.debug.print("\ncounterexample {s}: depth {}/{} devs {any}\n", .{ name, want_depth, f.depth, devs });+ return error.CatalogMismatch;+ }+ }+}++test "spec/terminal_modes: graff's lifecycle balances and its restore leaves the alt-screen last" {+ var enable_then_restore = std.ArrayList(u8).empty;+ defer enable_then_restore.deinit(std.testing.allocator);+ try enable_then_restore.appendSlice(std.testing.allocator, run.enable_seq);+ try enable_then_restore.appendSlice(std.testing.allocator, restore.seq);+ var f = fold(enable_then_restore.items);+ var buf: [16]u32 = undefined;+ try std.testing.expectEqual(@as(usize, 0), f.deviations(&buf).len);+ try std.testing.expectEqual(@as(u32, 0), f.depth);+ try std.testing.expect(std.mem.endsWith(u8, restore.seq, "\x1b[?1049l"));+}diff --git a/build.zig b/build.zigindex 7a66b316..8ea7ff4b 100644--- a/build.zig+++ b/build.zig@@ -101,6 +101,7 @@ pub fn build(b: *std.Build) void {unit_tests.root_module.addAnonymousImport("spec_shape", .{ .root_source_file = b.path("spec/kernels/shape.json") });unit_tests.root_module.addAnonymousImport("spec_score", .{ .root_source_file = b.path("spec/kernels/score.json") });unit_tests.root_module.addAnonymousImport("spec_bash_policy", .{ .root_source_file = b.path("spec/kernels/bash_policy.json") });+ unit_tests.root_module.addAnonymousImport("spec_structured_output", .{ .root_source_file = b.path("spec/kernels/structured_output.json") });const run_tests = b.addRunArtifact(unit_tests);const test_step = b.step("test", "Run unit tests");test_step.dependOn(&run_tests.step);@@ -183,6 +184,7 @@ pub fn build(b: *std.Build) void {.optimize = optimize,}),});+ tui_tests.root_module.addAnonymousImport("spec_terminal_modes", .{ .root_source_file = b.path("spec/kernels/terminal_modes.json") });const tui_test_step = b.step("tui-test", "Run fullscreen TUI unit tests");tui_test_step.dependOn(&b.addRunArtifact(tui_tests).step);diff --git a/lean-proofs/Graff.lean b/lean-proofs/Graff.leanindex a57f013b..8414137c 100644--- a/lean-proofs/Graff.lean+++ b/lean-proofs/Graff.lean@@ -6,3 +6,5 @@ import Graff.PathConfineimport Graff.Shapeimport Graff.Scoreimport Graff.BashPolicy+import Graff.StructuredOutput+import Graff.TerminalModesdiff --git a/lean-proofs/Graff/StructuredOutput.lean b/lean-proofs/Graff/StructuredOutput.leannew file mode 100644index 00000000..2e7b5274--- /dev/null+++ b/lean-proofs/Graff/StructuredOutput.lean@@ -0,0 +1,79 @@+/-+ Structured-output carrier ladder (#543): which server-visible carrier a+ set --output-schema rides, per wire format, learned degrade state (sox),+ and whether real tools occupy the request.++ openai chat: json_schema until the provider rejects it (sox learned via+ the request() quirk ladder); degraded, the tools-off formatting turn+ carries the schema as a structured_output TOOL (dsh's pattern, forced by+ instruction, never tool_choice — thinking modes reject forcing), while a+ turn with real tools falls back to json_object. anthropic: no+ response_format exists at all — the tool is the only server carrier and+ the prompt always embeds the schema. responses: native text.format.++ The invariant of record is never_silent: before 9e2da0a the anthropic+ wire dropped a set schema with no error — the exact bug class this+ kernel now makes unrepresentable.++ Executable port: spec/ref/structured_output.py. Impl:+ src/agent_request_body.zig + agent_request_body_responses.zig+ (schemaAwarePrompt / writeStructuredOutputTool / writeAnthropicStructuredTool).+-/++namespace Graff.StructuredOutput++inductive Wire+ | anthropic | openai | responses+deriving DecidableEq, Repr++inductive Carrier+ | none | jsonSchema | jsonObject | toolOpenai | toolAnthropic | textFormat+deriving DecidableEq, Repr++/-- The server-visible carrier of the schema for one request.+ Args: wire, schema present, sox (json_schema was rejected), real tools present. -/+def carrier : Wire → Bool → Bool → Bool → Carrier+ | _, false, _, _ => .none+ | .responses, true, _, _ => .textFormat+ | .openai, true, false, _ => .jsonSchema+ | .openai, true, true, true => .jsonObject+ | .openai, true, true, false => .toolOpenai+ | .anthropic, true, _, true => .none+ | .anthropic, true, _, false => .toolAnthropic++/-- Whether the system prompt embeds the schema text (schemaAwarePrompt's+ embedded-schema branch). Tools presence never changes the prompt. -/+def promptSchema : Wire → Bool → Bool → Bool+ | _, false, _ => false+ | .anthropic, true, _ => true+ | .openai, true, sox => sox+ | .responses, true, _ => false++/-- #543's invariant of record: a set schema is NEVER silent — some+ server-visible carrier exists, or the prompt itself embeds the schema. -/+theorem never_silent (w : Wire) (sox tools : Bool) :+ carrier w true sox tools ≠ .none ∨ promptSchema w true sox = true := by+ cases w <;> cases sox <;> cases tools <;> decide++/-- The learned degrade is a chat-wire quirk: sox changes nothing elsewhere. -/+theorem sox_only_on_chat (w : Wire) (tools : Bool) (h : w ≠ .openai) :+ carrier w true true tools = carrier w true false tools := by+ cases w <;> cases tools <;> first | decide | exact absurd rfl h++/-- Once a provider rejected json_schema, it is never sent again. -/+theorem no_json_schema_after_rejection (w : Wire) (tools : Bool) :+ carrier w true true tools ≠ .jsonSchema := by+ cases w <;> cases tools <;> decide++/-- No schema, no artifacts: the axis is byte-silent when unused. -/+theorem absent_schema_is_silent (w : Wire) (sox tools : Bool) :+ carrier w false sox tools = .none ∧ promptSchema w false sox = false := by+ cases w <;> cases sox <;> cases tools <;> decide++/-- The anthropic wire embeds the schema in the prompt unconditionally —+ even when real tools displace the structured_output tool, nothing is lost. -/+theorem anthropic_always_teaches (sox : Bool) :+ promptSchema .anthropic true sox = true := by+ cases sox <;> decide++end Graff.StructuredOutputdiff --git a/lean-proofs/Graff/TerminalModes.lean b/lean-proofs/Graff/TerminalModes.leannew file mode 100644index 00000000..48a1c65a--- /dev/null+++ b/lean-proofs/Graff/TerminalModes.lean@@ -0,0 +1,94 @@+/-+ Terminal-mode lifecycle (the tuiguard invariant, grok-build's ModeTracker+ as a kernel): a TUI session is a stream of DEC private-mode ops and kitty+ keyboard pushes/pops; restore must return every mode to the TERMINAL+ DEFAULT and the kitty depth to zero, with the alt-screen leave (1049)+ ordered last so nothing paints on the user's real screen.++ Modes 7 (autowrap) and 25 (cursor visible) default ON — their restore+ direction is `set`, everything else restores by `reset`. Kitty pops floor+ at zero (grok-build floors the same way, so over-popping cannot go+ negative). The two concrete theorems at the bottom pin graff's ACTUAL+ enable/restore byte sequences (TUI/run.zig enable_seq, TUI/restore.zig+ seq) as op lists: their composition is balanced, and restore leaves the+ alt-screen last.++ Executable port: spec/ref/terminal_modes.py (also the semantics behind+ scripts/tui-pty-guard.py). Impl anchor: TUI/spec_terminal_modes_conformance.zig+ parses the real constants and diffs them against the fixture.+-/++namespace Graff.TerminalModes++inductive Op+ | set (n : Nat) | reset (n : Nat) | push | pop+deriving DecidableEq, Repr++def defaultOn : List Nat := [7, 25]++/-- Last-op-wins mode map plus the kitty push/pop depth (floored at 0). -/+def setFinal (m : List (Nat × Bool)) (n : Nat) (v : Bool) : List (Nat × Bool) :=+ (n, v) :: m.filter (fun p => p.1 ≠ n)++def step (s : List (Nat × Bool) × Nat) : Op → List (Nat × Bool) × Nat+ | .set n => (setFinal s.1 n true, s.2)+ | .reset n => (setFinal s.1 n false, s.2)+ | .push => (s.1, s.2 + 1)+ | .pop => (s.1, s.2 - 1)++def fold (ops : List Op) : List (Nat × Bool) × Nat := ops.foldl step ([], 0)++def isDefault (n : Nat) (v : Bool) : Bool := v == defaultOn.contains n++/-- Modes whose final state differs from the terminal default. -/+def deviations (m : List (Nat × Bool)) : List Nat :=+ (m.filter fun p => !isDefault p.1 p.2).map (·.1)++def balanced (ops : List Op) : Bool :=+ let (m, d) := fold ops+ (deviations m).isEmpty && d == 0++/-- Restore for a session: pop the kitty depth, flip every deviant mode back+ to its default, and leave the alt-screen (1049) LAST. -/+def restoreOps (ops : List Op) : List Op :=+ let (m, d) := fold ops+ let devs := deviations m+ let flips := (devs.filter (· ≠ 1049)).map fun n =>+ if defaultOn.contains n then Op.set n else Op.reset n+ let alt : List Op := if devs.contains 1049 then [.reset 1049] else []+ (List.replicate d .pop) ++ flips ++ alt++/-- graff's boot sequence (TUI/run.zig enable_seq) as ops, in byte order. -/+def graffEnable : List Op :=+ [.set 1049, .reset 25, .set 2004, .set 1000, .set 1003, .set 1006, .reset 7, .push]++/-- graff's restore sequence (TUI/restore.zig seq) as ops, in byte order.+ (The non-DEC `ESC[>4;0m` modifyOtherKeys reset carries no mode number+ and is outside this model, exactly as in the executable port.) -/+def graffRestore : List Op :=+ [.reset 2026, .pop, .set 7, .reset 1006, .reset 1003, .reset 1000, .reset 2004, .set 25, .reset 1049]++/-- Kitty pops floor at zero: over-popping can never underflow the depth. -/+theorem pop_floors : (fold [.pop, .pop, .push]).2 = 1 := by decide++/-- An untouched terminal is balanced (byte transparency's base case). -/+theorem empty_balanced : balanced [] = true := by decide++/-- THE lifecycle theorem, on the real sequences: booting graff's TUI and+ running its restore returns the terminal exactly to defaults. -/+theorem graff_lifecycle_balanced : balanced (graffEnable ++ graffRestore) = true := by decide++/-- The restore's final op leaves the alt-screen — nothing may paint after. -/+theorem graff_restore_alt_last : graffRestore.getLast? = some (.reset 1049) := by decide++/-- restore of a restored session is a no-op list (grok-build's+ byte-transparency e2e, as a theorem on the model). -/+theorem restore_idempotent :+ restoreOps (graffEnable ++ graffRestore) = [] := by decide++/-- The generated restore also balances the real boot state — the model's+ restoreOps and graff's committed sequence agree on the outcome. -/+theorem generated_restore_balances :+ balanced (graffEnable ++ restoreOps graffEnable) = true := by decide++end Graff.TerminalModesdiff --git a/spec/conformance.py b/spec/conformance.pyindex 0dffc22c..1555d24e 100644--- a/spec/conformance.py+++ b/spec/conformance.py@@ -59,6 +59,10 @@ from ref.score import check_properties as score_check_propertiesfrom ref.score import payload as score_model_payloadfrom ref.bash_policy import check_properties as bash_check_propertiesfrom ref.bash_policy import payload as bash_model_payload+from ref.structured_output import check_properties as sox_check_properties+from ref.structured_output import payload as sox_model_payload+from ref.terminal_modes import check_properties as term_check_properties+from ref.terminal_modes import payload as term_model_payloadROOT = Path(__file__).resolve().parentKERNELS = ROOT / "kernels"@@ -70,6 +74,8 @@ PATH_FIXTURE = KERNELS / "path_confine.json"SHAPE_FIXTURE = KERNELS / "shape.json"SCORE_FIXTURE = KERNELS / "score.json"BASH_FIXTURE = KERNELS / "bash_policy.json"+SOX_FIXTURE = KERNELS / "structured_output.json"+TERM_FIXTURE = KERNELS / "terminal_modes.json"LEAN_DIR = ROOT.parent / "lean-proofs"@@ -423,6 +429,24 @@ def check_bash() -> int:raise Counterexample(prop, None, detail or msg) from e+def check_sox() -> int:+ try:+ return sox_check_properties()+ except ValueError as e:+ msg = str(e)+ prop, _, detail = msg.partition(": ")+ raise Counterexample(prop, None, detail or msg) from e+++def check_term() -> int:+ try:+ return term_check_properties()+ except ValueError as e:+ msg = str(e)+ prop, _, detail = msg.partition(": ")+ raise Counterexample(prop, None, detail or msg) from e++def prefixes_first(p: str) -> list[str]:parts = [c for c in p.split("/") if c]return [parts[0]] if parts else []@@ -444,6 +468,8 @@ def export() -> list[Path]:_write(SHAPE_FIXTURE, shape_payload()),_write(SCORE_FIXTURE, score_payload()),_write(BASH_FIXTURE, bash_payload()),+ _write(SOX_FIXTURE, sox_model_payload()),+ _write(TERM_FIXTURE, term_model_payload()),]@@ -463,6 +489,8 @@ def check_fixtures() -> None:_same(SHAPE_FIXTURE, shape_payload(), "shape")_same(SCORE_FIXTURE, score_payload(), "score")_same(BASH_FIXTURE, bash_payload(), "bash_policy")+ _same(SOX_FIXTURE, sox_model_payload(), "structured_output")+ _same(TERM_FIXTURE, term_model_payload(), "terminal_modes")def break_model(kind: str) -> None:@@ -545,15 +573,18 @@ def main() -> int:n_sh = check_shape()n_sc = check_score()n_ba = check_bash()+ n_sx = check_sox()+ n_tm = check_term()if args.export:paths = export()rel = ", ".join(p.relative_to(ROOT.parent).as_posix() for p in paths)- print(f"exported catalog={n_cat} transport={n_tr} provider={n_pr} goal={n_gl} path={n_pc} shape={n_sh} score={n_sc} bash={n_ba} → {rel}")+ print(f"exported catalog={n_cat} transport={n_tr} provider={n_pr} goal={n_gl} path={n_pc} shape={n_sh} score={n_sc} bash={n_ba} sox={n_sx} term={n_tm} → {rel}")else:check_fixtures()print(f"ok tool_catalog {n_cat} transport {n_tr} (1 ws) "- f"provider {n_pr} goal_loop {n_gl} path_confine {n_pc} shape {n_sh} score {n_sc} bash {n_ba}"+ f"provider {n_pr} goal_loop {n_gl} path_confine {n_pc} shape {n_sh} score {n_sc} bash {n_ba} "+ f"structured_output {n_sx} terminal_modes {n_tm}")if args.lean:try_lean()diff --git a/spec/kernels/structured_output.json b/spec/kernels/structured_output.jsonnew file mode 100644index 00000000..36589510--- /dev/null+++ b/spec/kernels/structured_output.json@@ -0,0 +1,197 @@+{+ "kernel": "structured_output",+ "cells": [+ {+ "wire": "anthropic",+ "schema": false,+ "sox": false,+ "tools": false,+ "carrier": "none",+ "prompt_schema": false+ },+ {+ "wire": "anthropic",+ "schema": false,+ "sox": false,+ "tools": true,+ "carrier": "none",+ "prompt_schema": false+ },+ {+ "wire": "anthropic",+ "schema": false,+ "sox": true,+ "tools": false,+ "carrier": "none",+ "prompt_schema": false+ },+ {+ "wire": "anthropic",+ "schema": false,+ "sox": true,+ "tools": true,+ "carrier": "none",+ "prompt_schema": false+ },+ {+ "wire": "anthropic",+ "schema": true,+ "sox": false,+ "tools": false,+ "carrier": "toolAnthropic",+ "prompt_schema": true+ },+ {+ "wire": "anthropic",+ "schema": true,+ "sox": false,+ "tools": true,+ "carrier": "none",+ "prompt_schema": true+ },+ {+ "wire": "anthropic",+ "schema": true,+ "sox": true,+ "tools": false,+ "carrier": "toolAnthropic",+ "prompt_schema": true+ },+ {+ "wire": "anthropic",+ "schema": true,+ "sox": true,+ "tools": true,+ "carrier": "none",+ "prompt_schema": true+ },+ {+ "wire": "openai",+ "schema": false,+ "sox": false,+ "tools": false,+ "carrier": "none",+ "prompt_schema": false+ },+ {+ "wire": "openai",+ "schema": false,+ "sox": false,+ "tools": true,+ "carrier": "none",+ "prompt_schema": false+ },+ {+ "wire": "openai",+ "schema": false,+ "sox": true,+ "tools": false,+ "carrier": "none",+ "prompt_schema": false+ },+ {+ "wire": "openai",+ "schema": false,+ "sox": true,+ "tools": true,+ "carrier": "none",+ "prompt_schema": false+ },+ {+ "wire": "openai",+ "schema": true,+ "sox": false,+ "tools": false,+ "carrier": "jsonSchema",+ "prompt_schema": false+ },+ {+ "wire": "openai",+ "schema": true,+ "sox": false,+ "tools": true,+ "carrier": "jsonSchema",+ "prompt_schema": false+ },+ {+ "wire": "openai",+ "schema": true,+ "sox": true,+ "tools": false,+ "carrier": "toolOpenai",+ "prompt_schema": true+ },+ {+ "wire": "openai",+ "schema": true,+ "sox": true,+ "tools": true,+ "carrier": "jsonObject",+ "prompt_schema": true+ },+ {+ "wire": "responses",+ "schema": false,+ "sox": false,+ "tools": false,+ "carrier": "none",+ "prompt_schema": false+ },+ {+ "wire": "responses",+ "schema": false,+ "sox": false,+ "tools": true,+ "carrier": "none",+ "prompt_schema": false+ },+ {+ "wire": "responses",+ "schema": false,+ "sox": true,+ "tools": false,+ "carrier": "none",+ "prompt_schema": false+ },+ {+ "wire": "responses",+ "schema": false,+ "sox": true,+ "tools": true,+ "carrier": "none",+ "prompt_schema": false+ },+ {+ "wire": "responses",+ "schema": true,+ "sox": false,+ "tools": false,+ "carrier": "textFormat",+ "prompt_schema": false+ },+ {+ "wire": "responses",+ "schema": true,+ "sox": false,+ "tools": true,+ "carrier": "textFormat",+ "prompt_schema": false+ },+ {+ "wire": "responses",+ "schema": true,+ "sox": true,+ "tools": false,+ "carrier": "textFormat",+ "prompt_schema": false+ },+ {+ "wire": "responses",+ "schema": true,+ "sox": true,+ "tools": true,+ "carrier": "textFormat",+ "prompt_schema": false+ }+ ]+}diff --git a/spec/kernels/terminal_modes.json b/spec/kernels/terminal_modes.jsonnew file mode 100644index 00000000..1710265a--- /dev/null+++ b/spec/kernels/terminal_modes.json@@ -0,0 +1,127 @@+{+ "kernel": "terminal_modes",+ "graff_enable": "\u001b[?1049h\u001b[?25l\u001b[?2004h\u001b[?1000h\u001b[?1003h\u001b[?1006h\u001b[?7l\u001b[>11u\u001b[>4;2m",+ "graff_restore": "\u001b[?2026l\u001b[>4;0m\u001b[<u\u001b[?7h\u001b[?1006l\u001b[?1003l\u001b[?1000l\u001b[?2004l\u001b[?25h\u001b[?1049l",+ "cells": [+ {+ "name": "empty",+ "stream": "",+ "deviations": [],+ "depth": 0,+ "balanced": true+ },+ {+ "name": "graff-enable",+ "stream": "\u001b[?1049h\u001b[?25l\u001b[?2004h\u001b[?1000h\u001b[?1003h\u001b[?1006h\u001b[?7l\u001b[>11u\u001b[>4;2m",+ "deviations": [+ 7,+ 25,+ 1000,+ 1003,+ 1006,+ 1049,+ 2004+ ],+ "depth": 1,+ "balanced": false+ },+ {+ "name": "graff-lifecycle",+ "stream": "\u001b[?1049h\u001b[?25l\u001b[?2004h\u001b[?1000h\u001b[?1003h\u001b[?1006h\u001b[?7l\u001b[>11u\u001b[>4;2m\u001b[?2026l\u001b[>4;0m\u001b[<u\u001b[?7h\u001b[?1006l\u001b[?1003l\u001b[?1000l\u001b[?2004l\u001b[?25h\u001b[?1049l",+ "deviations": [],+ "depth": 0,+ "balanced": true+ },+ {+ "name": "alt-only",+ "stream": "\u001b[?1049h",+ "deviations": [+ 1049+ ],+ "depth": 0,+ "balanced": false+ },+ {+ "name": "paste-only",+ "stream": "\u001b[?2004h",+ "deviations": [+ 2004+ ],+ "depth": 0,+ "balanced": false+ },+ {+ "name": "paste-balanced",+ "stream": "\u001b[?2004h\u001b[?2004l",+ "deviations": [],+ "depth": 0,+ "balanced": true+ },+ {+ "name": "cursor-hidden",+ "stream": "\u001b[?25l",+ "deviations": [+ 25+ ],+ "depth": 0,+ "balanced": false+ },+ {+ "name": "autowrap-off",+ "stream": "\u001b[?7l",+ "deviations": [+ 7+ ],+ "depth": 0,+ "balanced": false+ },+ {+ "name": "kitty-unpopped",+ "stream": "\u001b[>1u",+ "deviations": [],+ "depth": 1,+ "balanced": false+ },+ {+ "name": "kitty-overpop",+ "stream": "\u001b[<u\u001b[<u\u001b[>1u",+ "deviations": [],+ "depth": 1,+ "balanced": false+ },+ {+ "name": "multi-num",+ "stream": "\u001b[?1000;1006h\u001b[?1000l",+ "deviations": [+ 1006+ ],+ "depth": 0,+ "balanced": false+ },+ {+ "name": "relatch",+ "stream": "\u001b[?1049h\u001b[?1049l\u001b[?1049h",+ "deviations": [+ 1049+ ],+ "depth": 0,+ "balanced": false+ },+ {+ "name": "default-noise",+ "stream": "\u001b[?2026l\u001b[?25h\u001b[?7h",+ "deviations": [],+ "depth": 0,+ "balanced": true+ },+ {+ "name": "mouse-partial",+ "stream": "\u001b[?1000h\u001b[?1003h\u001b[?1003l",+ "deviations": [+ 1000+ ],+ "depth": 0,+ "balanced": false+ }+ ]+}diff --git a/spec/ref/structured_output.py b/spec/ref/structured_output.pynew file mode 100644index 00000000..351066fd--- /dev/null+++ b/spec/ref/structured_output.py@@ -0,0 +1,70 @@+"""Executable port of lean-proofs/Graff/StructuredOutput.lean (#543)."""++from __future__ import annotations++WIRES = ("anthropic", "openai", "responses")+BOOLS = (False, True)+++def carrier(wire: str, schema: bool, sox: bool, tools: bool) -> str:+ if not schema:+ return "none"+ if wire == "responses":+ return "textFormat"+ if wire == "openai":+ if not sox:+ return "jsonSchema"+ return "jsonObject" if tools else "toolOpenai"+ # anthropic: no response_format exists on this wire at all+ return "none" if tools else "toolAnthropic"+++def prompt_schema(wire: str, schema: bool, sox: bool) -> bool:+ if not schema:+ return False+ if wire == "anthropic":+ return True+ if wire == "openai":+ return sox+ return False+++def cells() -> list[dict]:+ rows = []+ for wire in WIRES:+ for schema in BOOLS:+ for sox in BOOLS:+ for tools in BOOLS:+ rows.append({+ "wire": wire,+ "schema": schema,+ "sox": sox,+ "tools": tools,+ "carrier": carrier(wire, schema, sox, tools),+ "prompt_schema": prompt_schema(wire, schema, sox),+ })+ return rows+++def check_properties() -> int:+ n = 0+ for row in cells():+ n += 1+ w, s, x, t = row["wire"], row["schema"], row["sox"], row["tools"]+ # never_silent: a set schema always reaches the provider somewhere.+ if s and row["carrier"] == "none" and not row["prompt_schema"]:+ raise ValueError(f"never_silent violated: {row}")+ # sox_only_on_chat: the learned degrade changes nothing off the chat wire.+ if w != "openai" and carrier(w, s, True, t) != carrier(w, s, False, t):+ raise ValueError(f"sox_only_on_chat violated: {row}")+ # no_json_schema_after_rejection.+ if x and row["carrier"] == "jsonSchema":+ raise ValueError(f"no_json_schema_after_rejection violated: {row}")+ # absent_schema_is_silent.+ if not s and (row["carrier"] != "none" or row["prompt_schema"]):+ raise ValueError(f"absent_schema_is_silent violated: {row}")+ return n+++def payload() -> dict:+ return {"kernel": "structured_output", "cells": cells()}diff --git a/spec/ref/terminal_modes.py b/spec/ref/terminal_modes.pynew file mode 100644index 00000000..7218aa30--- /dev/null+++ b/spec/ref/terminal_modes.py@@ -0,0 +1,128 @@+"""Executable port of lean-proofs/Graff/TerminalModes.lean.++Also the semantics behind scripts/tui-pty-guard.py's mode-balance check:+one model gates the fixtures AND the live binary.+"""++from __future__ import annotations++import re++DEFAULT_ON = (7, 25)++MODE_RE = re.compile(r"\x1b\[\?([0-9;]+)([hl])")+KITTY_PUSH_RE = re.compile(r"\x1b\[>[0-9;]*u")+KITTY_POP_RE = re.compile(r"\x1b\[<[0-9;]*u")++# graff's actual sequences (TUI/run.zig enable_seq / TUI/restore.zig seq).+# The Zig conformance test parses the live constants and diffs them against+# the fixture copy of these, so drift in either direction trips.+GRAFF_ENABLE = "\x1b[?1049h\x1b[?25l\x1b[?2004h\x1b[?1000h\x1b[?1003h\x1b[?1006h\x1b[?7l\x1b[>11u\x1b[>4;2m"+GRAFF_RESTORE = "\x1b[?2026l\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l"+++def parse_ops(stream: str) -> list[tuple[str, int]]:+ """Byte stream -> ordered op list: (set|reset, n) | (push|pop, 0)."""+ ops: list[tuple[str, int]] = []+ events = []+ for m in MODE_RE.finditer(stream):+ for num in m.group(1).split(";"):+ events.append((m.start(), "set" if m.group(2) == "h" else "reset", int(num)))+ for m in KITTY_PUSH_RE.finditer(stream):+ events.append((m.start(), "push", 0))+ for m in KITTY_POP_RE.finditer(stream):+ events.append((m.start(), "pop", 0))+ for _, kind, n in sorted(events):+ ops.append((kind, n))+ return ops+++def fold(ops: list[tuple[str, int]]) -> tuple[dict[int, bool], int]:+ final: dict[int, bool] = {}+ depth = 0+ for kind, n in ops:+ if kind == "set":+ final[n] = True+ elif kind == "reset":+ final[n] = False+ elif kind == "push":+ depth += 1+ else:+ depth = max(depth - 1, 0) # grok-build's floor+ return final, depth+++def deviations(final: dict[int, bool]) -> list[int]:+ return sorted(n for n, v in final.items() if v != (n in DEFAULT_ON))+++def balanced(ops: list[tuple[str, int]]) -> bool:+ final, depth = fold(ops)+ return not deviations(final) and depth == 0+++def restore_ops(ops: list[tuple[str, int]]) -> list[tuple[str, int]]:+ final, depth = fold(ops)+ devs = deviations(final)+ flips = [("set" if n in DEFAULT_ON else "reset", n) for n in devs if n != 1049]+ alt = [("reset", 1049)] if 1049 in devs else []+ return [("pop", 0)] * depth + flips + alt+++SEQUENCES: tuple[tuple[str, str], ...] = (+ ("empty", ""),+ ("graff-enable", GRAFF_ENABLE),+ ("graff-lifecycle", GRAFF_ENABLE + GRAFF_RESTORE),+ ("alt-only", "\x1b[?1049h"),+ ("paste-only", "\x1b[?2004h"),+ ("paste-balanced", "\x1b[?2004h\x1b[?2004l"),+ ("cursor-hidden", "\x1b[?25l"),+ ("autowrap-off", "\x1b[?7l"),+ ("kitty-unpopped", "\x1b[>1u"),+ ("kitty-overpop", "\x1b[<u\x1b[<u\x1b[>1u"),+ ("multi-num", "\x1b[?1000;1006h\x1b[?1000l"),+ ("relatch", "\x1b[?1049h\x1b[?1049l\x1b[?1049h"),+ ("default-noise", "\x1b[?2026l\x1b[?25h\x1b[?7h"),+ ("mouse-partial", "\x1b[?1000h\x1b[?1003h\x1b[?1003l"),+)+++def check_properties() -> int:+ n = 0+ for name, stream in SEQUENCES:+ n += 1+ ops = parse_ops(stream)+ # The generated restore always balances any reachable state.+ if not balanced(ops + restore_ops(ops)):+ raise ValueError(f"restore does not balance {name!r}")+ # Restore of a restored stream is empty (byte transparency).+ if restore_ops(ops + restore_ops(ops)):+ raise ValueError(f"restore not idempotent for {name!r}")+ # graff's committed restore balances graff's committed enable...+ if not balanced(parse_ops(GRAFF_ENABLE + GRAFF_RESTORE)):+ raise ValueError("graff lifecycle unbalanced")+ # ...and its restore leaves the alt-screen LAST.+ last_mode = list(MODE_RE.finditer(GRAFF_RESTORE))[-1]+ if last_mode.group(1) != "1049" or last_mode.group(2) != "l":+ raise ValueError("graff restore does not end with the alt-screen leave")+ return n+++def payload() -> dict:+ rows = []+ for name, stream in SEQUENCES:+ ops = parse_ops(stream)+ final, depth = fold(ops)+ rows.append({+ "name": name,+ "stream": stream,+ "deviations": deviations(final),+ "depth": depth,+ "balanced": balanced(ops),+ })+ return {+ "kernel": "terminal_modes",+ "graff_enable": GRAFF_ENABLE,+ "graff_restore": GRAFF_RESTORE,+ "cells": rows,+ }diff --git a/src/agent_request_body_responses.zig b/src/agent_request_body_responses.zigindex b37ac206..266d0551 100644--- a/src/agent_request_body_responses.zig+++ b/src/agent_request_body_responses.zig@@ -93,7 +93,9 @@ pub fn schemaAwarePrompt(self: *Agent) ![]const u8 {// response_format exists) — so the schema itself must reach the model:// through the structured_output tool when offered (the tools-off// formatting turn), else as the entire final message.- if (self.sox_json_object or self.provider.kind == .anthropic) return std.mem.concat(self.scratchAlloc(), u8, &.{+ // Chat-wire only for sox: a stale learned flag must not perturb the+ // responses wire's bytes (native text.format needs no prompt embed).+ if ((self.provider.kind == .openai and self.sox_json_object) or self.provider.kind == .anthropic) return std.mem.concat(self.scratchAlloc(), u8, &.{base,"\n\nA JSON output schema is enforced on your final answer. Use tools first to gather every fact you need — never guess values. This provider cannot enforce the schema server-side, so satisfy it yourself: call the structured_output tool when it is offered, otherwise reply with a single JSON object, matching exactly this schema: ",self.output_schema.?,diff --git a/src/spec_structured_output_conformance.zig b/src/spec_structured_output_conformance.zignew file mode 100644index 00000000..2f03637f--- /dev/null+++ b/src/spec_structured_output_conformance.zig@@ -0,0 +1,96 @@+//! Impl half of StructuredOutput (#543): the fixture's 24 cells drive the REAL+//! buildBody, and the carrier is classified from the produced request bytes —+//! wire format × schema × sox × tools. The never-silent invariant is thereby+//! checked against what actually goes on the wire, not a mirrored function.++const std = @import("std");+const Value = std.json.Value;+const Agent = @import("agent.zig").Agent;++const fixtures_json = @embedFile("spec_structured_output");++const test_schema = "{\"type\":\"object\",\"properties\":{\"answer\":{\"type\":\"string\"}},\"required\":[\"answer\"]}";++fn agentFor(arena: std.mem.Allocator, wire: []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 });+ const kind: @import("provider.zig").Provider.Kind =+ if (std.mem.eql(u8, wire, "anthropic")) .anthropic else if (std.mem.eql(u8, wire, "openai")) .openai else .responses;+ const id: []const u8 = switch (kind) {+ .anthropic => "anthropic",+ .openai => "deepseek",+ .responses => "xai",+ };+ const model: []const u8 = switch (kind) {+ .anthropic => "claude-sonnet-5",+ .openai => "deepseek-v4-flash",+ .responses => "grok-4.6",+ };+ 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",+ };+}++fn toolsFor(wire: []const u8) []const u8 {+ if (std.mem.eql(u8, wire, "anthropic"))+ return "[{\"name\":\"bash\",\"description\":\"\",\"input_schema\":{\"type\":\"object\"}}]";+ if (std.mem.eql(u8, wire, "openai"))+ return "[{\"type\":\"function\",\"function\":{\"name\":\"bash\",\"description\":\"\",\"parameters\":{\"type\":\"object\"}}}]";+ return "[{\"type\":\"function\",\"name\":\"bash\",\"description\":\"\",\"parameters\":{},\"strict\":false}]";+}++fn classify(body: []const u8, wire: []const u8) []const u8 {+ if (std.mem.indexOf(u8, body, "\"text\":{\"format\":{\"type\":\"json_schema\"") != null) return "textFormat";+ if (std.mem.indexOf(u8, body, "\"response_format\":{\"type\":\"json_schema\"") != null) return "jsonSchema";+ if (std.mem.indexOf(u8, body, "\"response_format\":{\"type\":\"json_object\"}") != null) return "jsonObject";+ if (std.mem.indexOf(u8, body, "\"name\":\"structured_output\"") != null)+ return if (std.mem.eql(u8, wire, "anthropic")) "toolAnthropic" else "toolOpenai";+ return "none";+}++test "spec/structured_output: buildBody's carrier matches the model on every cell" {+ const gpa = std.testing.allocator;+ var parsed = try std.json.parseFromSlice(Value, gpa, fixtures_json, .{});+ defer parsed.deinit();+ const cells = parsed.value.object.get("cells").?.array.items;+ try std.testing.expectEqual(@as(usize, 24), cells.len);+ for (cells) |cell_v| {+ const cell = cell_v.object;+ const wire = cell.get("wire").?.string;+ const schema = cell.get("schema").?.bool;+ const sox = cell.get("sox").?.bool;+ const tools = cell.get("tools").?.bool;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ var agent = try agentFor(arena_state.allocator(), wire);+ if (schema) agent.output_schema = test_schema;+ agent.sox_json_object = sox;+ const body = try agent.buildBody(if (tools) toolsFor(wire) else null, false, true, true);+ defer gpa.free(body);+ const got = classify(body, wire);+ const want = cell.get("carrier").?.string;+ const prompt_want = cell.get("prompt_schema").?.bool;+ const prompt_got = std.mem.indexOf(u8, body, "cannot enforce the schema server-side") != null;+ if (!std.mem.eql(u8, got, want) or prompt_got != prompt_want) {+ std.debug.print(+ "\ncounterexample wire={s} schema={} sox={} tools={}: carrier {s}/{s} prompt {}/{}\n",+ .{ wire, schema, sox, tools, want, got, prompt_want, prompt_got },+ );+ return error.CatalogMismatch;+ }+ // never_silent, on the live bytes: a set schema always reaches the wire.+ if (schema and std.mem.eql(u8, got, "none") and !prompt_got) return error.SchemaSilentlyDropped;+ }+}diff --git a/src/tool_gates.zig b/src/tool_gates.zigindex a2ac7745..34f988cc 100644--- a/src/tool_gates.zig+++ b/src/tool_gates.zig@@ -101,6 +101,7 @@ test { // the served catalogs' wire-compatibility guard (an unreferenced module'_ = @import("spec_shape_conformance.zig");_ = @import("spec_score_conformance.zig");_ = @import("spec_bash_policy_conformance.zig");+ _ = @import("spec_structured_output_conformance.zig");_ = @import("grok_spec_conformance.zig");_ = @import("spec_prompt_cache_conformance.zig");}