graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: structural constraint ledger and paste-end latch
Rach Pradhanc33f1ebc1053
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3871f77e..ae936243 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,12 @@ current is part of cutting a release.## Unreleased+- Recorded user constraints ride the root prefix as live ledger JSON, including+ the empty set, so a compaction recap cannot invent a recording. A write+ refreshes instructions in the same turn and drops a cached Responses+ continuation.+- A second bracketed paste in the same input batch no longer turns its first+ newline into Enter after the previous paste ends.- Gemini is a first-class provider, on Google's own Interactions API.`GEMINI_API_KEY` serves `gemini-*` directly instead of falling throughto the gateway as an uncatalogued model, and `graff --modeldiff --git a/TUI/input_batch.zig b/TUI/input_batch.zignew file mode 100644index 00000000..f8014b58--- /dev/null+++ b/TUI/input_batch.zig@@ -0,0 +1,28 @@+//! Shared terminal-read decoder/batcher for the live loop and headless composer.+const key = @import("key.zig");+const pacing = @import("pacing.zig");++pub const Decoder = struct {+ batch: pacing.Batch = .{},+ carried: ?key.Key = null,+ done: bool = false,++ pub fn next(self: *Decoder, bytes: []const u8, i: *usize) ?[]const pacing.Item {+ if (self.done) return null;+ self.batch.reset();+ if (self.carried) |k| {+ _ = self.batch.push(k);+ self.carried = null;+ }+ while (key.next(bytes, i)) |k| {+ pacing.events += 1;+ if (pacing.wheelNotch(k) != null) pacing.wheel_events += 1;+ if (self.batch.push(k) == .full) {+ self.carried = k;+ return self.batch.items();+ }+ }+ self.done = true;+ return if (self.batch.len > 0) self.batch.items() else null;+ }+};diff --git a/TUI/issue_737_tests.zig b/TUI/issue_737_tests.zigindex fc1f6de6..c80e1180 100644--- a/TUI/issue_737_tests.zig+++ b/TUI/issue_737_tests.zig@@ -91,3 +91,26 @@ test "#737 Enter coalesced with bracketed terminator submits once, not a paste ntry std.testing.expectEqualStrings("", term.model.input.getValue());try std.testing.expect(!term.model.cancel_requested);}++test "#737 delayed paste_end dispatch cannot reset a subsequent decoded paste" {+ const a = std.testing.allocator;+ var term: sim.Term = undefined;+ term.init(a, 80, 24);+ defer term.deinit();+ const job = try a.create(engine.Job);+ job.* = .{ .gpa = a, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };+ term.model.pending = job;+ defer {+ term.model.pending = null;+ a.destroy(job);+ }+ try term.model.push(.pending, "active turn");+ _ = term.feed("\x1b[200~first\x1b[201~\x1b[200~second");+ _ = term.feed("\r");+ _ = term.feed("\nthird\x1b[201~");+ const got = term.model.input.getValue();+ try std.testing.expect(std.mem.startsWith(u8, got, "firstsecond"));+ try std.testing.expect(std.mem.endsWith(u8, got, "third"));+ try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);+ try std.testing.expect(!term.model.cancel_requested);+}diff --git a/TUI/keys.zig b/TUI/keys.zigindex 8c5a98a8..5b9d1e2f 100644--- a/TUI/keys.zig+++ b/TUI/keys.zig@@ -27,7 +27,8 @@ pub fn handle(self: *Model, k: Key) Effect {}if (k == .paste_end) {self.pasting = false;- key_mod.endPaste(); // the two latches must never drift apart+ // Decoder owns its latch: batching may already have decoded the next+ // paste_start. Rewinding it here turns that paste's LF into Enter (#737).const v = std.mem.trim(u8, self.input.getValue(), " \t\r\n");if (@import("image.zig").attachDropped(self, v)) {self.input.setValue("") catch {};diff --git a/TUI/run.zig b/TUI/run.zigindex 4437dbdb..c8a1ff3c 100644--- a/TUI/run.zig+++ b/TUI/run.zig@@ -376,25 +376,17 @@ pub fn run(// its exact position, so typing is never starved behind a flood — and// because only one frame follows the whole batch, no intermediate// scroll position is ever painted.- var batch: pacing.Batch = .{};var i: usize = 0;- var drained = false;- while (!drained) {- const arrived: ?key_mod.Key = key_mod.next(inbuf[0..n], &i);- if (arrived) |k| {- pacing.events += 1;- if (pacing.wheelNotch(k) != null) pacing.wheel_events += 1;- if (batch.push(k) == .ok) continue;- } else drained = true;- for (batch.items()) |item| {+ var batch: @import("input_batch.zig").Decoder = .{};+ batches: while (batch.next(inbuf[0..n], &i)) |items| {+ for (items) |item| {if (item == .wheel) pacing.wheel_batches += 1;const effect = keys.handleBatchItem(&m, item);switch (effect) {.stay => {},.quit => {m.running = false;- drained = true;- break;+ break :batches;},.background => {parkToShell(io, w, &raw);@@ -405,12 +397,6 @@ pub fn run(},}}- batch.reset();- // The batch filled mid-stream: the event that did not fit opens the- // next one, so nothing is dropped and nothing is reordered.- if (!drained) {- if (arrived) |k| _ = batch.push(k);- }}if (i < n) {const rest = n - i;diff --git a/TUI/run_tests.zig b/TUI/run_tests.zigindex 03452acb..3a847457 100644--- a/TUI/run_tests.zig+++ b/TUI/run_tests.zig@@ -56,14 +56,14 @@ test "one tick drains the whole tty, coalesces the wheel, and paints once" {// (a) Every byte the tty already holds joins THIS tick before dispatch —// one read per frame is what made momentum scrolling lag and then jump.const read_at = std.mem.indexOf(u8, src, "const got = tty.readStdin(").?;- const dispatch_at = std.mem.indexOfPos(u8, src, read_at, "key_mod.next(inbuf[0..n]").?;+ const dispatch_at = std.mem.indexOfPos(u8, src, read_at, "batch.next(inbuf[0..n]").?;const drain = src[read_at..dispatch_at];try std.testing.expect(std.mem.indexOf(u8, drain, "while (filled < inbuf.len and tty.poll(0))") != null);// ...bounded, or an endless flood would be drained and never painted.try std.testing.expect(std.mem.indexOf(u8, drain, "pacing.drainExpired(") != null);// (b) The batch is applied as one unit and the wheel run goes through the// same door a single report does.- try std.testing.expect(std.mem.indexOf(u8, src, "var batch: pacing.Batch") != null);+ try std.testing.expect(std.mem.indexOf(u8, src, "@import(\"input_batch.zig\").Decoder") != null);try std.testing.expect(std.mem.indexOf(u8, src, "keys.handleBatchItem(&m, item)") != null);// (c) The frame is gated on the budget, and the gate sits BEFORE the render// — gating only the paint would still pay for composing every frame.diff --git a/TUI/sim_batch.zig b/TUI/sim_batch.zigindex 8bb47f37..fdd9e59b 100644--- a/TUI/sim_batch.zig+++ b/TUI/sim_batch.zig@@ -1,26 +1,18 @@//! Simulator input uses the production parser, read-burst latch, bounded//! pacing batch and handleBatchItem seam (run.zig), not direct key dispatch.const app = @import("app.zig");-const key = @import("key.zig");const keys = @import("keys.zig");-const pacing = @import("pacing.zig");const paste = @import("key_paste.zig");pub fn apply(m: *app.Model, bytes: []const u8, i: *usize, now_ms: u64) app.Effect {paste.setBurstRead(paste.burstRead(bytes, now_ms));- var batch: pacing.Batch = .{};- while (true) {- const arrived = key.next(bytes, i);- if (arrived) |k| {- if (batch.push(k) == .ok) continue;+ var last: app.Effect = .stay;+ var batch: @import("input_batch.zig").Decoder = .{};+ while (batch.next(bytes, i)) |items| {+ for (items) |item| {+ last = keys.handleBatchItem(m, item);+ if (last != .stay) return last;}- for (batch.items()) |item| {- const effect = keys.handleBatchItem(m, item);- if (effect != .stay) return effect;- }- batch.reset();- if (arrived) |k| {- _ = batch.push(k);- } else return .stay;}+ return last;}diff --git a/docs/adr/0067-recorded-constraints-are-ledger-state.md b/docs/adr/0067-recorded-constraints-are-ledger-state.mdnew file mode 100644index 00000000..dcc4978a--- /dev/null+++ b/docs/adr/0067-recorded-constraints-are-ledger-state.md@@ -0,0 +1,40 @@+# 0067. Recorded constraints are ledger state, not recap prose++Status: accepted 2026-09-05++## Context++Issue #738 exposed two distinct failures: a compaction recap invented a+recorded prohibition, and a recorded user override did not reconcile the+active instructions until another human turn. A model-written summary is+not evidence that an append-only ledger operation succeeded (ADR 0033).+ADR 0066 already makes publication and constraint-authority instructions+unconditional; this record is the structural half: the prefix carries the+live ledger as data, not as generated prose.++## Decision++The root prefix carries a deterministic `recorded_user_constraints` JSON+array derived from the live ledger, including ids, exact text and provenance.+The empty array is explicit. Learned advice and retired records are excluded.+Generated handoffs are labelled fallible context, not recorded-constraint+authority; the summarizer must not regenerate a recorded-constraints section.+This distinction does not erase explicit user instructions that were never+recorded, and does not grant permission to override safety requirements.++Successful `note_constraint` writes and duplicate calls rebuild all active+prompt variants before the next model request in the same turn. Changed+instructions invalidate the Responses continuation. If rebuilding fails, the+tool reports durable success separately from unavailable prompt refresh,+rather than falsely promising immediate reconciliation. Duplicates retry the+refresh without appending another record. Bookkeeping stays out of normal UX.++## Consequences++The root prefix pays for the structural ledger even when it is empty, and+constraint changes intentionally invalidate the cached continuation. Summary+prose can still be factually wrong, but is never the source of recorded rules.+Built-in style guidance must separately yield to explicit user overrides;+actual safety requirements remain non-overridable. Tests exercise ledger+serialization/retirement, duplicate recovery, same-turn refresh, and handoff+authority boundaries in the existing playbook and compaction suites.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 1c831dfa..10d2d5f2 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -77,6 +77,7 @@ record only when you need the evidence or the edge cases.| [0064](0064-plain-finals-reconcile-open-work.md) | Plain root finals with open current work get one reconciliation request; a remaining stop is explicit, not a promise of continued execution. || [0065](0065-stop-bounded-prose-repetition.md) | Stop bounded lexical prose loops before delivery without user cancellation, transport retries, or completion nudges. || [0066](0066-publication-policy-and-ledger-authority.md) | Publication safeguards survive custom prompts; recaps cannot change ledger authority, and constraint writes refresh active prompts atomically. |+| [0067](0067-recorded-constraints-are-ledger-state.md) | Recorded constraints are live ledger JSON in the root prefix; recap prose is not authority, and a write refreshes instructions in the same turn. |## When to write onediff --git a/src/compact_handoff_note.zig b/src/compact_handoff_note.zigindex 7312e03f..dcb0ae09 100644--- a/src/compact_handoff_note.zig+++ b/src/compact_handoff_note.zig@@ -66,8 +66,10 @@ const persists_note =\\summary. Record NAMES, not contents: file paths, directories, artifact paths,\\the command lines that worked, identifiers. Spend the words instead on what\\disk cannot give back - the decisions and why they were made, what was tried- \\and failed, the constraints the user set, and the exact state of the- \\unfinished work. Peer-channel notes are a working set, not the conversation:+ \\and failed, explicit user requests (not invented standing rules), and the exact state of the+ \\unfinished work. Recorded user constraints are durable harness state, supplied structurally+ \\in the active instructions. Do not regenerate a recorded-constraints section+ \\or claim note_constraint succeeded from memory. Peer-channel notes are a working set, not the conversation:\\do not transcribe [peer message] or [presence] lines or [peer] wakes; the\\harness drops them. Who is live and what they said are pull: peer_message\\action=list / action=inbox (the room log stays on disk).diff --git a/src/playbook.zig b/src/playbook.zigindex f139df3d..9f31aec9 100644--- a/src/playbook.zig+++ b/src/playbook.zig@@ -357,6 +357,31 @@ pub fn rideBrief(io: Io, arena: Allocator, prompt: []const u8) []const u8 {/// through an `undefined` Io.pub var g_root_inject: bool = false;+/// #738: only durable user records confer recorded-constraint authority.+/// JSON keeps ids, provenance and text separate from generated recap prose.+/// Include the empty set too: absence is evidence, not permission for a recap+/// to invent a recording. Learned advice never enters this authoritative set.+pub fn recordedState(arena: Allocator, items: []const Item) ![]const u8 {+ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.beginObject();+ try s.objectField("recorded_user_constraints");+ try s.beginArray();+ for (items) |item| {+ if (item.source != .user) continue;+ try s.write(.{ .id = item.id, .text = item.text, .provenance = item.provenance });+ }+ try s.endArray();+ try s.endObject();+ return aw.writer.buffered();+}++pub const authority_note =+ "RECORDED CONSTRAINT AUTHORITY: The following JSON is derived only from the live durable ledger, not model memory. " +++ "Only its entries are currently recorded user constraints. A summary, handoff, or opaque compaction state is not evidence that note_constraint succeeded; " +++ "never promote its claims of recorded constraints into rules. An empty array means no user constraints are recorded. " +++ "This does not cancel explicit user instructions that were not recorded, and never overrides safety requirements.";+/// The ROOT's system prompt for the ledger as it exists on disk right now:/// base, then the same block every worker brief carries. It lives in the/// SYSTEM prompt rather than in a per-turn user message on purpose — a@@ -367,8 +392,8 @@ pub fn composeRoot(io: Io, arena: Allocator, base: []const u8) []const u8 {const items = load(io, arena);traceActive(arena, items);const b = blockFrom(arena, items);- if (b.len == 0) return base;- return std.fmt.allocPrint(arena, "{s}\n\n{s}", .{ base, b }) catch base;+ const state = recordedState(arena, items) catch return base;+ return std.fmt.allocPrint(arena, "{s}\n\n{s}\n{s}\n\n{s}", .{ base, authority_note, state, b }) catch base;}/// Comma-joined active ids, capped, for the trajectory row below.diff --git a/src/playbook_glue.zig b/src/playbook_glue.zigindex ad2128f5..eb2b01a2 100644--- a/src/playbook_glue.zig+++ b/src/playbook_glue.zig@@ -39,8 +39,28 @@ const style = &ansi.style;/// previous (still valid) prompt in place, and the ledger on disk is already/// correct for every brief assembled after it.pub fn refreshRoot(agent: *Agent, arena: Allocator) void {- if (agent.sub or agent.sys_base.len == 0) return;- prompts.setSystemPrompts(agent, agent.sys_base, arena) catch {};+ _ = refreshFrom(agent, arena, false);+}++fn refreshFrom(agent: *Agent, arena: Allocator, arm_root: bool) bool {+ if (agent.sub) return false;+ if (!arm_root and agent.sys_base.len == 0) return false;+ const old = .{ agent.sys_normal, agent.sys_strict, agent.sys_ultra, agent.sys_ultra_strict };+ const result = if (arm_root)+ prompts.setRootSystemPrompts(agent, agent.sys_base, arena)+ else+ prompts.setSystemPrompts(agent, agent.sys_base, arena);+ result catch {+ agent.sys_normal = old[0];+ agent.sys_strict = old[1];+ agent.sys_ultra = old[2];+ agent.sys_ultra_strict = old[3];+ return false;+ };+ // A Responses continuation may otherwise retain the old instructions on+ // the server. Re-send the refreshed prefix on this turn's next request.+ if (!std.mem.eql(u8, old[0], agent.sys_normal)) agent.closeCodexWs();+ return true;}/// The `note_constraint` meta-tool handler (root-only; the spec lives in@@ -71,22 +91,15 @@ pub fn noteConstraint(agent: *Agent, input: std.json.Value) ExecResult {@import("prompt_cache_hud.zig").noteBust(.playbook);// A duplicate must reconcile a stale prefix too. Never promise same-turn// activation after a failed refresh (the durable write already succeeded).- prompts.setRootSystemPrompts(agent, agent.sys_base, agent.arena) catch- return .{ .text = "Constraint is durable, but active prompt refresh failed. Do not claim activation; retry note_constraint to reconcile it.", .is_error = true };- const block = playbook.blockNow(agent.io, agent.arena);- for ([_][]const u8{ agent.sys_normal, agent.sys_strict, agent.sys_ultra, agent.sys_ultra_strict }) |variant| {- if (block.len == 0 or std.mem.indexOf(u8, variant, block) == null)- return .{ .text = "Constraint is durable, but active ledger injection failed. Retry note_constraint to reconcile it.", .is_error = true };- }+ const refreshed = refreshFrom(agent, agent.arena, true) and+ std.mem.indexOf(u8, agent.sys_normal, r.id) != null;+ const effect = if (refreshed)+ "It takes effect immediately, in this same turn: user instructions override built-in authoring/style defaults (including optional attribution), not secret-safety or disclosure-approval requirements. Act on the constraint now rather than waiting for the next turn."+ else+ "Durable state is saved, but the active prompt could not be refreshed. Do not claim activation; retry note_constraint to reconcile it.";// ADR 0021: the user just said this. Echoing "constraint recorded" is// machine state, not progress. The tool result still tells the model.- // The recorded constraint is in force NOW, not from the next user turn:- // the ledger was rewritten before this result was written and the root- // prompt refreshed above, so the very next request carries it. Saying so- // matters — the model was still treating built-in guidance as controlling- // for the rest of the turn and refusing the correction the user had just- // asked for (#738).- return .{ .text = std.fmt.allocPrint(agent.arena, "constraint recorded as {s}. It is now in {s} and rides every subagent, workflow and pipeline brief from here on, in this session and in later ones — you do not need to restate it. It takes effect immediately, in this turn: user instructions override built-in authoring/style defaults (including optional attribution), not secret-safety or disclosure-approval requirements. Act on the constraint now rather than waiting for the next turn.", .{ r.id, playbook.path }) catch "constraint recorded", .is_error = false };+ return .{ .text = std.fmt.allocPrint(agent.arena, "constraint recorded as {s}. It is now in {s} and rides every subagent, workflow and pipeline brief from here on, in this session and in later ones — you do not need to restate it. {s}", .{ r.id, playbook.path, effect }) catch "constraint recorded; active prompt refresh status unavailable", .is_error = false };}/// Privacy-safe operational trace: id + success, never constraint text (#644).diff --git a/src/playbook_tests.zig b/src/playbook_tests.zigindex 4f78151e..27ac098d 100644--- a/src/playbook_tests.zig+++ b/src/playbook_tests.zig@@ -510,9 +510,12 @@ test "refreshRoot (#381): a constraint recorded mid-session reaches the ROOT's otry prompts.setRootSystemPrompts(&root, "ROOT-BASE", arena);try std.testing.expectEqualStrings("ROOT-BASE", root.sys_base);- try std.testing.expectEqualStrings("ROOT-BASE", root.sys_normal); // empty ledger costs nothing+ try std.testing.expect(std.mem.indexOf(u8, root.sys_normal, "\"recorded_user_constraints\":[]") != null); // empty ledger explicitly denies invented recordings- _ = glue.noteConstraint(&root, try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"text\":\"no scroll hints\"}", .{}));+ root.codex_prev_id = try std.testing.allocator.dupe(u8, "stale-server-instructions");+ const result = glue.noteConstraint(&root, try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"text\":\"no scroll hints\"}", .{}));+ try std.testing.expect(std.mem.indexOf(u8, result.text, "same turn") != null);+ try std.testing.expect(root.codex_prev_id == null);// noteConstraint refreshed it: no restart, no re-login, next request.for ([_][]const u8{ root.sys_normal, root.sys_strict, root.sys_ultra, root.sys_ultra_strict }) |v| {try std.testing.expect(std.mem.indexOf(u8, v, "ROOT-BASE") != null);@@ -534,6 +537,27 @@ test "refreshRoot (#381): a constraint recorded mid-session reaches the ROOT's o}.body);}+test "recorded constraint authority is structural, escaped, and excludes learned and retired items (#738)" {+ try inScratch(struct {+ fn body(io: Io, arena: std.mem.Allocator) !void {+ const empty = playbook.composeRoot(io, arena, "BASE");+ try std.testing.expect(std.mem.indexOf(u8, empty, "\"recorded_user_constraints\":[]") != null);+ try std.testing.expect(playbook.add(io, arena, "advisory only", .learned, "run:1").ok);+ const added = playbook.add(io, arena, "no \"trailers\"\nplease", .user, "user:1");+ try std.testing.expect(added.ok);+ const encoded = try playbook.recordedState(arena, playbook.load(io, arena));+ const state = try std.json.parseFromSliceLeaky(std.json.Value, arena, encoded, .{});+ const records = state.object.get("recorded_user_constraints").?.array.items;+ try std.testing.expectEqual(@as(usize, 1), records.len);+ try std.testing.expectEqualStrings(added.id, records[0].object.get("id").?.string);+ try std.testing.expectEqualStrings("no \"trailers\"\nplease", records[0].object.get("text").?.string);+ try std.testing.expectEqualStrings("user:1", records[0].object.get("provenance").?.string);+ try std.testing.expectEqual(playbook.Retire.ok, playbook.retire(io, arena, added.id));+ try std.testing.expectEqualStrings("{\"recorded_user_constraints\":[]}", try playbook.recordedState(arena, playbook.load(io, arena)));+ }+ }.body);+}+test "idList: the kind:\"playbook\" row's id column is the join key for later attribution" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();