graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: reconcile unfinished work before plain final replies (#745)
Rach Pradhan41d3e541335c
diff --git a/docs/adr/0064-plain-finals-reconcile-open-work.md b/docs/adr/0064-plain-finals-reconcile-open-work.mdnew file mode 100644index 00000000..8e7adb08--- /dev/null+++ b/docs/adr/0064-plain-finals-reconcile-open-work.md@@ -0,0 +1,35 @@+# 0064. Plain finals reconcile open work once++Status: accepted 2026-09-05++## Context++A root turn can emit a plain final reply after starting tools while its current+checklist remains unfinished (#745). The `attempt_completion` gate does not run+on that path; empty-completion and named-source nudges do not cover it. A promise+to continue can therefore return control to the user without continuing work.++## Decision++Before accepting a plain final with live, current-epoch checklist items, offer+one reconciliation request per root turn. Include the actual open checklist and+instruct the model to continue independent work, collect required background+results with a blocking wait, or explain the real blocker. Status-only requests+and user instructions to pause must not be converted into permission to act.++Do not gate explicit accepted completion, review, text-only or child agents, or+paused/blocked goals. Preserve cancellation and model/tool budgets. Do not reset+the retry allowance after tools: a model repeatedly narrating progress must not+create an unbounded loop. If the turn still ends with open work, append a factual+notice that root execution has stopped; existing background jobs may still run.++## Consequences++- One extra model call is possible for a legitimate status answer with an open+ checklist. This is preferable to language-specific promise detection.+- The guard cannot force a model to finish. It provides a bounded recovery and+ makes the remaining stop explicit rather than silently implying continuation.+- No global worker wait: unrelated jobs and long-lived servers must not hold a+ turn open. The checklist, not process-wide job presence, owns the scope.+- Scripted tier-2 cases cover continuation and the retry limit; unit tests cover+ epoch scope, exemptions, wire shapes and cancellation/budget boundaries.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 93c74aa5..2dca0e8c 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -74,6 +74,7 @@ record only when you need the evidence or the edge cases.| [0061](0061-tool-only-turns-narrate-and-ask-in-band.md) | Heads-up text rides in the same response as the tool calls; a choice for the user is an `ask_user` call; a job exit the model already read never wakes it. || [0062](0062-background-servers-idle-lifecycle-and-ownership-record.md) | A background job silent and unread for 2h is stopped with its command kept; `/jobs keep` pins one (retained at exit); every job has an ownership record `graff servers` can list and stop, verified by start identity (#199). || [0063](0063-unsourced-cancel-is-the-harness.md) | Every cancel records its source; a turn cancelled with no recorded source is labelled a harness cancel, never a user interrupt, and the source lands in the trace (#728). |+| [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. |## When to write onediff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex dda3b83d..2e40909f 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -54,4 +54,9 @@{"id": "plugin-skill-on-demand", "why": "ADR 0007: a Cursor cache plugin skill named in installed_plugins.json must appear in the catalog as (plugin) without its body, and skill name= loads the body. The regression is copying/adopting (body always in the prompt) or walking plugins/cache/ instead of the index.", "args": [], "workspace_seed": {".cursor/plugins/installed_plugins.json": "{\"plugins\":{\"eval-gmail@cursor-public\":[{\"installPath\":\"cache/cursor-public/evalfix/2a8044425c7bddf429c3bdedf3ab61e791d34d65\"}]}}\n", ".cursor/plugins/cache/cursor-public/evalfix/2a8044425c7bddf429c3bdedf3ab61e791d34d65/.cursor-plugin/plugin.json": "{\"name\":\"eval-gmail\"}\n", ".cursor/plugins/cache/cursor-public/evalfix/2a8044425c7bddf429c3bdedf3ab61e791d34d65/skills/plugin-secret/SKILL.md": "---\nname: plugin-secret\ndescription: load before using the plugin secret handshake\n---\n\n# Plugin Secret\n\nPLUGIN_SKILL_BODY_TOKEN_9f3a\n", ".cursor/skills-cursor/env-setup/SKILL.md": "---\nname: env-setup\ndescription: personal skills-cursor playbook that survives GRAFF_NO_PLUGINS\n---\n\n# Env Setup\n\nPERSONAL_SKILL_BODY_TOKEN_c2e1\n"}, "prompt": "list available skills, then load plugin-secret", "script": [{"tool": "load_tool_schemas", "arguments": {"tools": ["skill"]}}, {"tool": "skill", "arguments": {}}, {"tool": "skill", "arguments": {"name": "plugin-secret"}}, {"text": "loaded the plugin secret playbook"}], "assert": [{"request_contains": {"index": 0, "text": "plugin-secret (plugin)"}}, {"request_contains": {"index": 0, "text": "env-setup (personal)"}}, {"request_lacks": {"index": 0, "text": "PLUGIN_SKILL_BODY_TOKEN_9f3a"}}, {"request_lacks": {"index": 0, "text": "PERSONAL_SKILL_BODY_TOKEN_c2e1"}}, {"event": {"type": "tool_call", "name": "skill"}}, {"request_contains": {"index": -1, "text": "PLUGIN_SKILL_BODY_TOKEN_9f3a"}}, {"final_text_contains": "loaded the plugin secret playbook"}]}{"id": "plugin-off-keeps-personal-skills", "why": "GRAFF_NO_PLUGINS must drop plugin-tree skills while ~/.cursor/skills-cursor stays personal. The regression is treating skills-cursor as a plugin (it vanishes) or ignoring the opt-out (plugin-secret still loads).", "args": [], "env": {"GRAFF_NO_PLUGINS": "1"}, "workspace_seed": {".cursor/plugins/cache/cursor-public/evalfix/2a8044425c7bddf429c3bdedf3ab61e791d34d65/.cursor-plugin/plugin.json": "{\"name\":\"eval-gmail\"}\n", ".cursor/plugins/cache/cursor-public/evalfix/2a8044425c7bddf429c3bdedf3ab61e791d34d65/skills/plugin-secret/SKILL.md": "---\nname: plugin-secret\ndescription: load before using the plugin secret handshake\n---\n\n# Plugin Secret\n\nPLUGIN_SKILL_BODY_TOKEN_9f3a\n", ".cursor/skills-cursor/env-setup/SKILL.md": "---\nname: env-setup\ndescription: personal skills-cursor playbook that survives GRAFF_NO_PLUGINS\n---\n\n# Env Setup\n\nPERSONAL_SKILL_BODY_TOKEN_c2e1\n"}, "prompt": "load the handshake playbook if it exists", "script": [{"tool": "skill", "arguments": {"name": "plugin-secret"}}, {"text": "plugin skill is gone; personal env-setup remains"}], "assert": [{"request_contains": {"index": 0, "text": "env-setup (personal)"}}, {"request_lacks": {"index": 0, "text": "plugin-secret"}}, {"request_lacks": {"index": 0, "text": "plugin-secret (plugin)"}}, {"request_lacks": {"index": 0, "text": "PLUGIN_SKILL_BODY_TOKEN_9f3a"}}, {"event": {"type": "tool_call", "name": "skill"}}, {"request_contains": {"index": -1, "text": "no skill named 'plugin-secret'"}}, {"final_text_contains": "plugin skill is gone"}]}{"id": "workspace-list-use", "why": "ADR 0006: workspace is a folded tool that must list real git worktrees and chdir the session. A skill cannot move file-tool cwd; bash-cd is not enough. Guards load_tool_schemas unfold + use by folder name.", "args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "create a feature worktree, list workspaces, switch into it", "script": [{"tool": "bash", "arguments": {"command": "git init && git config user.email eval@invalid && git config user.name Eval && echo x > README && git add README && git commit -m init && git worktree add wt-feature -b feature && echo seeded-worktree"}}, {"tool": "load_tool_schemas", "arguments": {"tools": ["workspace"]}}, {"tool": "workspace", "arguments": {"action": "list"}}, {"tool": "workspace", "arguments": {"action": "use", "path": "wt-feature"}}, {"tool": "bash", "arguments": {"command": "basename \"$(pwd)\""}}, {"text": "switched into wt-feature"}], "assert": [{"event": {"type": "tool_call", "name": "load_tool_schemas"}}, {"event": {"type": "tool_call", "name": "workspace"}}, {"request_contains": {"index": -1, "text": "wt-feature"}}, {"request_contains": {"index": -1, "text": "now at"}}, {"final_text_contains": "switched into wt-feature"}]}+{"id":"final-open-work-continues","why":"#745: plain final prose must not stop an unfinished checklist after tools have run.","args":[],"prompt":"finish the work","script":[{"tool":"todo_write","arguments":{"todos":[{"content":"do the work","status":"in_progress"}]}},{"text":"I will continue working."},{"tool":"todo_write","arguments":{"todos":[{"content":"do the work","status":"completed"}]}},{"text":"Work completed."}],"assert":[{"request_contains":{"index":2,"text":"Open-work reconciliation"}},{"events_at_least":{"match":{"type":"tool_call","name":"todo_write"},"count":2}},{"final_text_contains":"Work completed."}]}+{"id":"final-open-work-background","why":"#745: starting a background job must not turn a progress reply into a terminal response while independent root work remains.","args":[],"env":{"GRAFF_NO_CODEDB_GUARD":"1"},"prompt":"start a background check, do the independent root step, then collect the check and finish","script":[{"tool":"todo_write","arguments":{"todos":[{"content":"root step and background check","status":"in_progress"}]}},{"tool":"bash","arguments":{"command":"sleep 0.1; echo worker-ready","run_in_background":true}},{"text":"The worker is running; I will continue the local work."},{"tool":"bash","arguments":{"command":"echo root-step-done"}},{"tool":"bash_output","arguments":{"id":1,"wait_ms":1000}},{"tool":"todo_write","arguments":{"todos":[{"content":"root step and background check","status":"completed"}]}},{"text":"Root step and background check completed."}],"assert":[{"request_contains":{"index":3,"text":"Open-work reconciliation"}},{"event":{"type":"tool_result","name":"bash","text":"root-step-done\n"}},{"event":{"type":"tool_call","name":"bash_output"}},{"events_at_most":{"match":{"type":"turn"},"count":1}},{"final_text_contains":"Root step and background check completed."}]}+{"id":"final-open-work-bounded","why":"#745: repeated status prose must not create an infinite retry loop or imply root execution continues after returning.","args":[],"prompt":"finish the two steps","script":[{"tool":"todo_write","arguments":{"todos":[{"content":"first step","status":"in_progress"},{"content":"second step","status":"pending"}]}},{"text":"I will keep working."},{"text":"I will keep working."},{"tool":"bash","arguments":{"command":"echo must-not-run"}}],"assert":[{"request_contains":{"index":2,"text":"Open-work reconciliation"}},{"no_event":{"type":"tool_call","name":"bash"}},{"final_text_contains":"Root execution has stopped with 2 open checklist items"}]}+{"id":"final-open-work-status","why":"#745: an open checklist is not permission to resume work after a status-only user request; reconciliation is bounded and explicitly preserves that request.","args":[],"prompt":"create a pending checklist, then wait for my decision","second_prompt":"Only tell me the status; do not run tools or resume the task.","script":[{"tool":"todo_write","arguments":{"todos":[{"content":"await decision","status":"pending"}]}},{"tool":"attempt_completion","arguments":{"result":"Waiting for your decision."}},{"text":"Waiting for your decision; no work has resumed."},{"text":"Waiting for your decision; root execution is stopping."},{"tool":"bash","arguments":{"command":"echo must-not-run"}}],"assert":[{"request_contains":{"index":3,"text":"status-only question"}},{"no_event":{"type":"tool_call","name":"bash"}},{"final_text_contains":"Waiting for your decision; root execution is stopping."}]}+{"id":"final-open-work-budget","why":"#745: reconciliation must not consume an unavailable model call when a plain final reaches the invocation budget.","args":["--max-model-calls","2"],"prompt":"start a checklist and report the limit","script":[{"tool":"todo_write","arguments":{"todos":[{"content":"unfinished","status":"pending"}]}},{"text":"The call budget is spent."},{"tool":"bash","arguments":{"command":"echo must-not-run"}}],"assert":[{"no_event":{"type":"tool_call","name":"bash"}},{"final_text_contains":"Root execution has stopped with 1 open checklist items"}]}{"id": "plugin-command-as-skill", "why": "Claude plugins ship playbooks as commands/*.md, not only skills/. A Claude tree must appear in the skill catalog as (plugin) without the body, and skill name= loads it — the same first-class load Claude uses.", "args": [], "workspace_seed": {".claude/plugins/greet/.claude-plugin/plugin.json": "{\"name\":\"greet\"}\n", ".claude/plugins/greet/commands/hello.md": "---\nname: hello\ndescription: Claude command playbook for the handshake\n---\n\n# Hello\n\nCLAUDE_COMMAND_BODY_TOKEN_7c1e\n"}, "prompt": "list skills, then load the hello playbook", "script": [{"tool": "skill", "arguments": {}}, {"tool": "skill", "arguments": {"name": "hello"}}, {"text": "loaded the Claude command playbook"}], "assert": [{"request_contains": {"index": 0, "text": "hello (plugin)"}}, {"request_lacks": {"index": 0, "text": "CLAUDE_COMMAND_BODY_TOKEN_7c1e"}}, {"event": {"type": "tool_call", "name": "skill"}}, {"request_contains": {"index": -1, "text": "CLAUDE_COMMAND_BODY_TOKEN_7c1e"}}, {"final_text_contains": "loaded the Claude command playbook"}]}diff --git a/src/agent.zig b/src/agent.zigindex 0bc891b5..60e2de86 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -331,7 +331,7 @@ pub const Agent = struct {// Defensive for restored/embedded agents whose provider was assigned// directly instead of going through providers.applyProvider.try self.ensureRootTools(self.provider.kind);- // No per-turn teardown: the socket and the chain span user turns, guarded by codex_chain.usable instead.+ var pending_work: empty_completion.PendingWork = .{};self.completed = null;@import("named_work.zig").beginTurn(self);if (!self.sub and !root_turn_prepared.swap(false, .acq_rel)) @import("cancel_source.zig").clear();@@ -394,11 +394,11 @@ pub const Agent = struct {.responses => try self.stepResponses(root),};if (done) |final_text| {- // A completion with no text and no tool calls used to end the turn- // silently — mid-task that just looks like a dead session.+ // Retry empty replies; reconcile plain finals with live work (#745).if (try empty_completion.handle(self, final_text, hist_len)) continue;if (try @import("named_work.zig").handle(self, final_text)) continue;- return final_text;+ if (try pending_work.finish(self, final_text)) |text| return text;+ continue;}self.empty_completion_retries = 0;}diff --git a/src/agent_empty_completion.zig b/src/agent_empty_completion.zigindex 8e5743f4..94a65d32 100644--- a/src/agent_empty_completion.zig+++ b/src/agent_empty_completion.zig@@ -52,6 +52,148 @@ pub fn handle(self: *Agent, final_text: []const u8, hist_len: usize) !bool {return true;}+/// Plain finals bypass attempt_completion's gate (#745). Keep the allowance+/// on the runTurn stack: tool progress and compaction must not reset it.+pub const PendingWork = struct {+ nudged: bool = false,++ pub const note = "Open-work reconciliation: your plain final reply would end root execution, but the current checklist is unfinished. " +++ "If the user still wants this task done, continue actionable independent work now; collect required background results with agent_output/bash_output and wait_ms>0 when needed, rather than polling or promising future work. " +++ "One blocked branch does not block unrelated work. Respect a user pause/cancel, status-only question, or change of task; do not treat this reminder as permission to resume unwanted work. " +++ "If stopping is appropriate, explain the actual blocker or status and say root execution is stopping. Never imply the root keeps working after a final reply. " +++ "Update the checklist only to reflect real progress; do not mark unfinished work completed to bypass this check.";++ fn open(self: *const Agent) usize {+ if (self.sub or self.review_mode or self.text_only or self.completed != null or main_mod.plan_mode) return 0;+ if (self.goal) |g| if (g.status == .paused or g.status == .blocked) return 0;+ const goals = @import("goal_state.zig");+ return goals.openCount(self.todos.items, goals.currentEpoch(self.goal));+ }++ fn canRequest(self: *const Agent) bool {+ if (self.run_budget) |b| if (!b.canAfford(1)) return false;+ if (main_mod.max_tool_calls) |max| if (self.tool_calls_this_turn >= max) return false;+ const cap = @import("turn_chrome.zig").max_turn_model_calls;+ return cap == 0 or self.model_calls_this_turn < cap;+ }++ /// Null continues the same turn. A final stop is explicit even when the+ /// provider ignores the reminder or the remaining budget cannot buy it.+ pub fn finish(state: *PendingWork, self: *Agent, text: []const u8) !?[]const u8 {+ if (!self.sub and Agent.esc_cancel.load(.acquire)) return error.Interrupted;+ const count = open(self);+ if (count == 0) return text;+ if (!state.nudged and canRequest(self)) {+ state.nudged = true;+ const goals = @import("goal_state.zig");+ const body = try std.fmt.allocPrint(self.arena, "{s}\n\n{s}", .{ note, goals.renderTodos(self, goals.currentEpoch(self.goal)) });+ try self.messages.append(try @import("named_work.zig").userNudge(self.arena, self.provider.kind, body));+ if (self.tracer) |tr| tr.note("pending_work", "plain final reconciled; one retry granted");+ return null;+ }+ const footer = try std.fmt.allocPrint(self.arena, "\n\n[Root execution has stopped with {d} open checklist items; background jobs may still run.]", .{count});+ if (self.tracer) |tr| tr.note("pending_work", "plain final stopped with open work; retry or budget exhausted");+ // The answer may already have streamed, so surface the new suffix too.+ if (self.streamed_text) {+ if (main_mod.json_mode) self.emit(.{ .type = "text", .text = footer }) else try self.say("{s}\n", .{footer});+ }+ return try std.fmt.allocPrint(self.arena, "{s}{s}", .{ text, footer });+ }+};++fn pendingFixture(arena: std.mem.Allocator) Agent {+ var self: Agent = undefined;+ self.arena = arena;+ self.sub = false;+ self.review_mode = false;+ self.text_only = false;+ self.completed = null;+ self.goal = null;+ self.todos = .empty;+ self.messages = .init(arena);+ self.provider.kind = .openai;+ self.run_budget = null;+ self.tool_calls_this_turn = 3; // unlike the zero-tool guards, tools ran+ self.model_calls_this_turn = 4;+ self.tracer = null;+ self.streamed_text = false;+ return self;+}++test "#745 plain final retries once after tools, then explicitly stops without completing work" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ var self = pendingFixture(arena.allocator());+ try self.todos.append(self.arena, .{ .content = "finish", .status = "in_progress" });+ var state: PendingWork = .{};+ try std.testing.expect((try state.finish(&self, "I will keep working")) == null);+ try std.testing.expectEqual(@as(usize, 1), self.messages.items.len);+ try std.testing.expect(std.mem.indexOf(u8, messages.latestUserText(self.messages.items), "finish") != null);+ self.tool_calls_this_turn += 1; // tool progress must not refill the allowance+ const final = (try state.finish(&self, "I will keep working")).?;+ try std.testing.expect(std.mem.indexOf(u8, final, "Root execution has stopped with 1 open checklist items") != null);+ try std.testing.expectEqualStrings("in_progress", self.todos.items[0].status);+ try std.testing.expect(self.completed == null);+ self.todos.items[0].status = "completed";+ try std.testing.expectEqualStrings("done", (try state.finish(&self, "done")).?);+}++test "#745 only live current work gates root finals, never explicit completion or paused goals" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ var self = pendingFixture(arena.allocator());+ self.goal = .{ .objective = "current", .epoch = 2 };+ try self.todos.append(self.arena, .{ .content = "parked", .status = "pending", .epoch = 1 });+ try self.todos.append(self.arena, .{ .content = "retired", .status = "pending", .epoch = 2, .retired = true });+ try std.testing.expectEqual(@as(usize, 0), PendingWork.open(&self));+ try self.todos.append(self.arena, .{ .content = "current", .status = "pending", .epoch = 2 });+ try std.testing.expectEqual(@as(usize, 1), PendingWork.open(&self));+ for ([_]@import("agent.zig").GoalStatus{ .paused, .blocked }) |status| {+ self.goal.?.status = status;+ try std.testing.expectEqual(@as(usize, 0), PendingWork.open(&self));+ }+ self.goal.?.status = .active;+ for ([_]*bool{ &self.sub, &self.review_mode, &self.text_only }) |flag| {+ flag.* = true;+ try std.testing.expectEqual(@as(usize, 0), PendingWork.open(&self));+ flag.* = false;+ }+ self.completed = "explicitly accepted";+ try std.testing.expectEqual(@as(usize, 0), PendingWork.open(&self));+}++test "#745 cancellation and exhausted budgets do not buy a reconciliation request" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ var self = pendingFixture(arena.allocator());+ try self.todos.append(self.arena, .{ .content = "finish", .status = "pending" });+ var budget: @import("run_budget.zig").RunBudget = .{ .max_model_calls = 1 };+ budget.model_calls.store(1, .release);+ self.run_budget = &budget;+ var state: PendingWork = .{};+ try std.testing.expect((try state.finish(&self, "budget spent")) != null);+ try std.testing.expectEqual(@as(usize, 0), self.messages.items.len);+ Agent.esc_cancel.store(true, .release);+ defer Agent.esc_cancel.store(false, .release);+ try std.testing.expectError(error.Interrupted, state.finish(&self, "cancelled"));+}++test "#745 reconciliation supports every wire without coercing status requests into action" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ for ([_]@import("provider.zig").Provider.Kind{ .openai, .anthropic, .responses }) |kind| {+ var self = pendingFixture(arena.allocator());+ self.provider.kind = kind;+ try self.todos.append(self.arena, .{ .content = "finish", .status = "pending" });+ var state: PendingWork = .{};+ try std.testing.expect((try state.finish(&self, "status")) == null);+ const body = messages.latestUserText(self.messages.items);+ try std.testing.expect(std.mem.indexOf(u8, body, "status-only question") != null);+ try std.testing.expect(std.mem.indexOf(u8, body, "wait_ms>0") != null);+ if (kind == .responses) try std.testing.expectEqualStrings("message", self.messages.items[0].object.get("type").?.string);+ }+}+test "retry empty completions up to the cap" {try std.testing.expect(shouldRetry("", 0));try std.testing.expect(shouldRetry("", 1));diff --git a/src/main.zig b/src/main.zigindex d5628479..53d8dc2e 100644--- a/src/main.zig+++ b/src/main.zig@@ -1,6 +1,5 @@-//! simple-harness — a minimal, dependency-free agentic loop supporting-//! Anthropic and OpenAI-compatible providers, built-in/meta/MCP tools, parallel-//! agents, strict tool-call mode, compaction, and JSONL traces in `.graff/traces`.+//! Agentic loop for Anthropic and OpenAI-compatible providers: native/MCP tools,+//! parallel agents, strict tool-call mode, compaction, and local JSONL traces.const std = @import("std");pub const panic = @import("tui").restore.Panic; // leave the alt screen BEFORE std prints a panic, or the restore sequence erases the trace (#535)const Io = std.Io;@@ -581,6 +580,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("http_client_integration_tests.zig");_ = @import("http_client_trajectory_tests.zig");_ = @import("prompt_astra.zig");+ _ = @import("agent_empty_completion.zig"); // #745: plain-final reconciliation_ = @import("test_hooks.zig"); // unreached modules; their tests were silently skipped_ = @import("agent_overflow_tests.zig"); // #414: and, through it, agent_overflow.zig's table tests_ = @import("agent_server_compact.zig"); // server-side autocompact (codex Responses)