graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: #714 named-source gate is per mention; skip identical user turns
Cursor Agent1a9cb5923ea3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c10208eb..ee46014b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,9 @@ current is part of cutting a release.- `#712` / ADR 0059: bare `/resume` and `/sessions` list cwd saves, then`~/.graff/sessions`. Cross-workspace rows name their origin. Resumerestores history here; file tools stay in the current cwd.+- `#714` / ADR 0060: the “named a source file” nudge is per unanswered+ mention, not the whole history. Identical user turns are not+ re-injected; three copies fail closed as stuck replay.- The gateway is a fallback seat, not the startup default.- No tag until asked.diff --git a/docs/adr/0060-named-source-gate-is-per-unanswered-mention.md b/docs/adr/0060-named-source-gate-is-per-unanswered-mention.mdnew file mode 100644index 00000000..afa00713--- /dev/null+++ b/docs/adr/0060-named-source-gate-is-per-unanswered-mention.md@@ -0,0 +1,33 @@+# 0060. Named-source gate is per unanswered mention++Status: accepted 2026-09-01++## Context++`named_work` appends a user-role nudge when the prompt names a source+file and the model answers without tools. `handle` also walked every+string in history (`conversationNamesSource`). After a successful+read, `SPEC.md` was still in an earlier message; the next turn reset+`named_work_nudges` and fired again.++Separately, `repl_convo.adopt` always appended the frontend's trailing+user row. A host that re-submitted the same prompt injected another+user turn. Combined with the gate, the session replayed the same Q&A+until the human interrupted (#714).++## Decision++The gate keys on **this turn's** user text only (`latestUserText` /+`remembered_task`), including Responses `input_text`. Once that+mention is nudged or tools run, it is settled; a later turn must name+a different path.++`adopt` and the mainloop/ACP inject path skip a user payload that+already is the latest user text. After three identical injects, fail+closed and print `stuck replay`.++## Consequences++A greeting after a file question does not re-open the file. A+literal identical re-ask after an answer is treated as replay (rephrase+to run it again). The history-wide walk stays as a test helper only.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 709e9ce5..0fe73988 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -70,6 +70,7 @@ record only when you need the evidence or the edge cases.| [0057](0057-peer-title-is-an-address.md) | `peer_message` resolves exact title / saved-session base before opaque id or goal. || [0058](0058-compact-cut-stalls-on-no-progress.md) | Same unresolved `compact_cut` pin that does not shrink stops after two tries. || [0059](0059-saved-session-discovery-is-device-scoped.md) | `/resume` and `/sessions` list cwd then `~/.graff/sessions`; resume keeps tools in the current cwd. |+| [0060](0060-named-source-gate-is-per-unanswered-mention.md) | The named-source nudge is per unanswered mention; identical user turns do not replay (#714). |## When to write onediff --git a/docs/releases/v0.0.284.md b/docs/releases/v0.0.284.mdindex c3292c18..fb54da09 100644--- a/docs/releases/v0.0.284.md+++ b/docs/releases/v0.0.284.md@@ -44,7 +44,16 @@ origin. Resuming a foreign save restores conversation history into thecurrent cwd and says so — `read_file` / `edit_file` / `bash` do notsilently switch trees.+## Named-source gate and turn replay (#714 / ADR 0060)++A user question that named a source file could replay for dozens of+turns. The nudge walked all history, so `SPEC.md` in an earlier+message re-armed the gate on every later completion, and+`repl_convo.adopt` appended the frontend's trailing user row even+when it was already the latest ask. The gate is now per unanswered+mention. Identical user injects are skipped; three copies fail closed.+## Tests-Suite floor stays **1882**. This fold adds the #711 / #712 cases on-top of the ACP-image and #708 work already on the branch.+Suite floor stays **1882**. This fold adds the #711 / #712 / #714+cases on top of the ACP-image and #708 work already on the branch.diff --git a/src/acp.zig b/src/acp.zigindex 2930b926..45423af6 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -153,7 +153,11 @@ const LiveTurn = struct {fn run(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {const self: *LiveTurn = @ptrCast(@alignCast(ctx));- try self.root.messages.append(try userMessage(arena, self.root, text));+ switch (try @import("turn_dedup.zig").enqueue(self.root, arena, self.out, text)) {+ .started => {},+ .skipped => return "",+ .stuck => return @import("turn_dedup.zig").stuck_text,+ }if (telemetry.g_telem) |t| t.beginTurn(@intCast(@min(text.len, std.math.maxInt(u32))), self.root.provider.model);self.saw_text = false;var sink: stream.EventSink = undefined;diff --git a/src/cli.zig b/src/cli.zigindex 76a5fbd3..450f701d 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -26,6 +26,7 @@ pub const changelog_text =\\ • peer inbox wake is advisory ("parked; read when relevant"), never a command that displaces the turn\\ • parallel error bash results stay valid JSON on the next Codex request (#711)\\ • /resume and /sessions find ~/.graff/sessions, not just cwd (#712)+ \\ • named-source gate is per mention; identical user turns do not replay (#714)\\\\0.0.283\\ • deleted composer image chips reuse #N; paste traces omit MIME/bytes until send (#702)diff --git a/src/mainloop.zig b/src/mainloop.zigindex 7e820384..01d54d80 100644--- a/src/mainloop.zig+++ b/src/mainloop.zig@@ -389,7 +389,7 @@ pub fn run(ctx: *Ctx) !void {var review_context = review.Context.begin(ctx.arena, ctx.root, ctx.root.review_mode);if (ctx.root.review_mode) ctx.root.rebaseContextMeter();defer if (review_context.restore(ctx.root)) ctx.root.rebaseContextMeter();- try ctx.root.messages.append(try @import("vision_queue.zig").consumePromptImages(ctx.arena, ctx.root, ultracode_msg.text));+ if (try @import("turn_dedup.zig").enqueueOrSkip(ctx.root, ctx.arena, ctx.out, ultracode_msg.text)) continue;ctx.root.snapshots.?.turn += 1; // tag file edits in this turn (matches /rewind numbering)ctx.root.recap_generation +%= 1; // #419: a starting turn supersedes any recap job still in flightif (telemetry.g_telem) |t| t.beginTurn(@intCast(@min(base_msg.len, std.math.maxInt(u32))), ctx.root.provider.model);diff --git a/src/messages.zig b/src/messages.zigindex 7d126c52..029d9cf1 100644--- a/src/messages.zig+++ b/src/messages.zig@@ -23,6 +23,36 @@ pub fn textMessage(arena: Allocator, role: []const u8, text: []const u8) !Valuereturn .{ .object = msg };}+/// Newest user-role payload: a Chat `content` string or a Responses+/// `input_text` / `text` block. Tool-result wrappers are skipped (#714).+pub fn latestUserText(messages: []const Value) []const u8 {+ var i = messages.len;+ while (i > 0) {+ i -= 1;+ if (userPromptText(messages[i])) |t| return t;+ }+ return "";+}++fn userPromptText(msg: Value) ?[]const u8 {+ if (msg != .object) return null;+ const role = msg.object.get("role") orelse return null;+ if (role != .string or !std.mem.eql(u8, role.string, "user")) return null;+ const content = msg.object.get("content") orelse return null;+ if (content == .string) return if (content.string.len > 0) content.string else null;+ if (content != .array) return null;+ for (content.array.items) |block| {+ if (block != .object) continue;+ const typ = block.object.get("type") orelse continue;+ if (typ != .string) continue;+ if (std.mem.eql(u8, typ.string, "tool_result")) return null;+ if (!std.mem.eql(u8, typ.string, "input_text") and !std.mem.eql(u8, typ.string, "text")) continue;+ const tx = block.object.get("text") orelse continue;+ if (tx == .string and tx.string.len > 0) return tx.string;+ }+ return null;+}+/// Build the message appended to the conversation after a tool runs, shaped/// for each provider's request body. The tool's result text is ALWAYS written/// as a JSON string (`.{ .string = ... }`) — never a raw `[]u8` handed to the@@ -505,3 +535,29 @@ test "#711: parallel error bash + object-shaped output still stringify as JSON"defer parsed.deinit();try std.testing.expect(parsed.value == .object);}++test "#714: latestUserText sees Responses input_text and skips tool_result" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var msgs = std.json.Array.init(a);+ try msgs.append(try textMessage(a, "user", "Read SPEC.md"));+ var block: std.json.ObjectMap = .empty;+ try block.put(a, "type", .{ .string = "input_text" });+ try block.put(a, "text", .{ .string = "thanks" });+ var content: std.json.Array = .init(a);+ try content.append(.{ .object = block });+ var msg: std.json.ObjectMap = .empty;+ try msg.put(a, "type", .{ .string = "message" });+ try msg.put(a, "role", .{ .string = "user" });+ try msg.put(a, "content", .{ .array = content });+ try msgs.append(.{ .object = msg });+ try std.testing.expectEqualStrings("thanks", latestUserText(msgs.items));+ var blocks = std.json.Array.init(a);+ try blocks.append(try toolResultMessage(a, .anthropic, "id-1", "ok", false));+ var wrapper: std.json.ObjectMap = .empty;+ try wrapper.put(a, "role", .{ .string = "user" });+ try wrapper.put(a, "content", .{ .array = blocks });+ try msgs.append(.{ .object = wrapper });+ try std.testing.expectEqualStrings("thanks", latestUserText(msgs.items));+}diff --git a/src/named_work.zig b/src/named_work.zigindex e67ad546..71023be8 100644--- a/src/named_work.zig+++ b/src/named_work.zig@@ -27,18 +27,17 @@ pub fn remember(text: []const u8) void {remembered_task = text;}+pub fn resetForTest() void {+ remembered_task = "";+ settled_task = "";+}++/// Last mention this process already nudged or saw tools for. A later+/// turn must name a *different* source path before the gate fires again.+var settled_task: []const u8 = "";+fn lastUserText(self: *Agent) []const u8 {- var i = self.messages.items.len;- while (i > 0) {- i -= 1;- const msg = self.messages.items[i];- if (msg != .object) continue;- const role = msg.object.get("role") orelse continue;- if (role != .string or !std.mem.eql(u8, role.string, "user")) continue;- const content = msg.object.get("content") orelse continue;- if (content == .string) return content.string;- }- return "";+ return messages_mod.latestUserText(self.messages.items);}/// Snapshot the user prompt at turn start, while `role=user` still exists.@@ -49,8 +48,8 @@ pub fn rememberFrom(self: *Agent) void {}pub fn beginTurn(self: *Agent) void {- self.named_work_nudges = 0;rememberFrom(self);+ if (!std.mem.eql(u8, remembered_task, settled_task)) self.named_work_nudges = 0;}/// True when `text` names a source path (not a greeting.txt-style data file).@@ -131,10 +130,18 @@ const isResponsesInputText = messages_mod.isResponsesInputText;/// Re-anchor the Responses chain so the new item is not a dropped delta.pub fn handle(self: *Agent, _: []const u8) !bool {if (self.named_work_nudges >= max_nudges) return false;- if (self.tools_used.count() != 0) return false;- const named = hasNamedSource(remembered_task) or conversationNamesSource(self.messages.items);- if (!named) return false;+ if (self.tools_used.count() != 0) {+ if (hasNamedSource(remembered_task)) settled_task = remembered_task;+ return false;+ }+ // Per unanswered mention (#714): this turn's user text only. Walking+ // all history re-fired after a successful read because SPEC.md stayed+ // in an earlier message.+ if (!hasNamedSource(remembered_task)) return false;+ if (std.mem.eql(u8, remembered_task, settled_task)) return false;+ if (std.mem.eql(u8, lastUserText(self), nudge_text)) return false;self.named_work_nudges += 1;+ settled_task = remembered_task;self.closeCodexWs();try self.messages.append(try userNudge(self.arena, self.provider.kind, nudge_text));return true;@@ -159,7 +166,7 @@ test "shouldNudge is once, and only when no tools have run" {test "remembered task is enough to shouldNudge even without history walk" {remember("Fix stall_notice.py");- defer remember("");+ defer resetForTest();try std.testing.expect(hasNamedSource(remembered_task));remember("Reply with exactly: pong");try std.testing.expect(!hasNamedSource(remembered_task));@@ -220,7 +227,7 @@ test "handle appends Responses input_text once and re-anchors the chain" {};defer if (agent.codex_prev_id) |p| std.testing.allocator.free(p);remember("Fix atomic_write.py");- defer remember("");+ defer resetForTest();try std.testing.expect(try handle(&agent, "I'll read SPEC.md"));try std.testing.expect(agent.codex_prev_id == null);try std.testing.expectEqual(@as(usize, 0), agent.codex_sent_upto);@@ -230,3 +237,59 @@ test "handle appends Responses input_text once and re-anchors the chain" {try std.testing.expect(isResponsesInputText(agent.messages.items[agent.messages.items.len - 1], nudge_text));try std.testing.expect(!try handle(&agent, "I'll read SPEC.md"));}++fn testAgent(arena: std.mem.Allocator, msgs: std.json.Array) Agent {+ return .{+ .gpa = std.testing.allocator,+ .arena = arena,+ .io = std.testing.io,+ .client = undefined,+ .provider = .{+ .id = "xai",+ .kind = .openai,+ .auth = .bearer,+ .url = "",+ .api_key = "k",+ .model = "grok-4.6",+ .context = 100_000,+ },+ .messages = msgs,+ .sub = false,+ .label = "test",+ .out = null,+ };+}++test "#714: a later greeting does not re-fire because history still names SPEC.md" {+ resetForTest();+ defer resetForTest();+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var msgs = std.json.Array.init(a);+ try msgs.append(try messages_mod.textMessage(a, "user", "Read SPEC.md and explain affinity"));+ try msgs.append(try messages_mod.textMessage(a, "assistant", "affinity is keyed on the git root"));+ try msgs.append(try messages_mod.textMessage(a, "user", "thanks"));+ var agent = testAgent(a, msgs);+ rememberFrom(&agent);+ try std.testing.expectEqualStrings("thanks", remembered_task);+ try std.testing.expect(conversationNamesSource(agent.messages.items));+ try std.testing.expect(!try handle(&agent, "you're welcome"));+}++test "#714: tools on a named path settle the gate for that mention" {+ resetForTest();+ defer resetForTest();+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var msgs = std.json.Array.init(a);+ try msgs.append(try messages_mod.textMessage(a, "user", "Fix fib.py"));+ var agent = testAgent(a, msgs);+ remember("Fix fib.py");+ agent.tools_used.add(agent.io, a, "read_file", false);+ try std.testing.expect(!try handle(&agent, "I read fib.py"));+ agent.tools_used.clear(agent.io);+ agent.named_work_nudges = 0;+ try std.testing.expect(!try handle(&agent, "still fib.py"));+}diff --git a/src/repl_convo.zig b/src/repl_convo.zigindex b7600521..3907644d 100644--- a/src/repl_convo.zig+++ b/src/repl_convo.zig@@ -105,6 +105,10 @@ pub const Conversation = struct {if (history.len == 0) return;const last = history[history.len - 1];if (last.role != .user) return;+ // #714: a host that re-submits the same trailing user row must not+ // inject another turn. The named-source gate then re-read the file+ // and the session looped the same Q&A.+ if (std.mem.eql(u8, messages_mod.latestUserText(msgs.items), last.text)) return;try msgs.append(try textOf(self.alloc(), last));}@@ -192,6 +196,21 @@ test "adopt takes the whole transcript once, then only the new prompt" {try testing.expectEqualStrings("two", msgs.items[2].object.get("content").?.string);}+test "#714: adopt does not replay an identical trailing user prompt" {+ var convo = Conversation.init(testing.allocator);+ defer convo.deinit();+ try convo.adopt(&.{.{ .role = .user, .text = "Read SPEC.md" }});+ const msgs = convo.list();+ try msgs.append(try messages_mod.textMessage(convo.alloc(), "assistant", "affinity is the git root"));+ try convo.adopt(&.{+ .{ .role = .user, .text = "Read SPEC.md" },+ .{ .role = .assistant, .text = "affinity is the git root" },+ .{ .role = .user, .text = "Read SPEC.md" },+ });+ try testing.expectEqual(@as(usize, 2), convo.len());+ try testing.expectEqualStrings("assistant", roleOf(msgs.items[1]));+}+test "reset clears the conversation; rewind drops back to before the last prompt" {var convo = Conversation.init(testing.allocator);defer convo.deinit();diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 0b158ac4..5ac03076 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -350,5 +350,6 @@ test {_ = @import("agent_request_scratch.zig"); // #693: split out of agent_request.zig (600-line ceiling)_ = @import("commands_resume.zig"); // #697: --resume SOURCE --branch DEST parser_ = @import("session_list.zig"); // #712: device-wide saved-session listing+ _ = @import("turn_dedup.zig"); // #714: identical user turns do not replay_ = @import("net_efficiency_test.zig");}diff --git a/src/turn_dedup.zig b/src/turn_dedup.zignew file mode 100644index 00000000..88da0ec0--- /dev/null+++ b/src/turn_dedup.zig@@ -0,0 +1,101 @@+//! Consecutive identical user turns are not a new ask (#714).+//!+//! The TUI/ACP host can re-submit the same trailing user row; combined with+//! the named-source gate that looked like a fresh question every time. Skip+//! the duplicate. After `max_replays` identical injects, fail closed.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const Agent = @import("agent.zig").Agent;+const messages = @import("messages.zig");+const vision = @import("vision.zig");+const vision_queue = @import("vision_queue.zig");+const ansi = @import("ansi.zig");+const style = &ansi.style;++pub const max_replays: u8 = 3;++pub const stuck_text = "stuck replay: the same user turn was injected again; stopping so this session does not loop";++var hits: u8 = 0;++pub fn resetForTest() void {+ hits = 0;+}++fn sameAsLast(text: []const u8, history_tail: []const u8) bool {+ return text.len > 0 and std.mem.eql(u8, history_tail, text);+}++pub const Outcome = enum { started, skipped, stuck };++/// Append `text` as this turn's user message, or skip a duplicate.+pub fn enqueue(root: *Agent, arena: Allocator, out: ?*Io.Writer, text: []const u8) !Outcome {+ const tail = messages.latestUserText(root.messages.items);+ if (sameAsLast(text, tail)) {+ hits +|= 1;+ if (hits >= max_replays) {+ if (out) |w| {+ w.print("{s}{s}{s}\n", .{ style.yellow, stuck_text, style.reset }) catch {};+ w.flush() catch {};+ } else {+ root.say("{s}\n", .{stuck_text}) catch {};+ }+ return .stuck;+ }+ return .skipped;+ }+ hits = 0;+ vision.stageGuiImageAttachment(root, text);+ try root.messages.append(try vision_queue.consumePromptImages(arena, root, text));+ return .started;+}++/// True when the caller should not start a model turn.+pub fn enqueueOrSkip(root: *Agent, arena: Allocator, out: ?*Io.Writer, text: []const u8) !bool {+ return try enqueue(root, arena, out, text) != .started;+}++test "#714: the first copy of a prompt proceeds" {+ resetForTest();+ defer resetForTest();+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var agent: Agent = .{+ .gpa = std.testing.allocator,+ .arena = a,+ .io = std.testing.io,+ .client = undefined,+ .provider = .{+ .id = "xai",+ .kind = .openai,+ .auth = .bearer,+ .url = "",+ .api_key = "k",+ .model = "grok-4.6",+ .context = 100_000,+ },+ .messages = .init(a),+ .sub = false,+ .label = "test",+ .out = null,+ };+ try std.testing.expect(!try enqueueOrSkip(&agent, a, null, "Read SPEC.md"));+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);+ try std.testing.expect(try enqueueOrSkip(&agent, a, null, "Read SPEC.md"));+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);+ try std.testing.expect(try enqueueOrSkip(&agent, a, null, "Read SPEC.md"));+ try std.testing.expect(try enqueueOrSkip(&agent, a, null, "Read SPEC.md"));+ try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);+}++test "#714: a different prompt resets the replay counter" {+ resetForTest();+ defer resetForTest();+ try std.testing.expect(sameAsLast("Read SPEC.md", "Read SPEC.md"));+ try std.testing.expect(!sameAsLast("thanks", "Read SPEC.md"));+ try std.testing.expect(!sameAsLast("", "Read SPEC.md"));+}