graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
todos: cancelled items carry a required reason; ask_user answers count as scope changes
Rach Pradhan5bf0598bbab9
diff --git a/docs/adr/0305-cancelled-checklist-items-carry-a-reason.md b/docs/adr/0305-cancelled-checklist-items-carry-a-reason.mdnew file mode 100644index 00000000..7a4da47f--- /dev/null+++ b/docs/adr/0305-cancelled-checklist-items-carry-a-reason.md@@ -0,0 +1,46 @@+# 0305. Cancelled checklist items carry a reason++Status: accepted 2026-10-28++## Context++Verification items stay on the checklist until the user changes scope (#844),+so a session whose user withdrew publication steps, or handed them to another+session, could not finish: leaving the items out of `todo_write` restored them,+and `attempt_completion` refused with "completion deferred: N unresolved+verification item(s) remain" (#1520). #1545 added a `cancelled` status, honored+for a verification item only after a newer user message. An answer given+through `ask_user` did not count, and a cancelled item said nothing about why.++## Decision++`cancelled` is the one status for work the user withdrew or delegated. Every+cancelled item needs a short `reason` (one line, capped at 160 bytes). A+`todo_write` that cancels an item without one is rejected whole and leaves the+list unchanged, so a client never shows a cancel that did not happen. An item+that was already cancelled keeps its recorded reason when re-listed without+one.++A verification item can be cancelled only after the user's latest word on the+task changed since the item was first written: a newer user message, as+before, or an answered `ask_user`. The request fingerprint folds in the count+of recorded answers.++A cancelled item stays in the list and in the saved session with its reason.+It no longer blocks completion or counts as open work, and it never counts as+verified (`goal_verify.taskVerified`). The checklist renders it as+`[-] content (cancelled: reason)`; the line REPL's WORKING block draws it as+`⊘ content (reason)`, outside the done/total count.++## Consequences++The model cannot drop a verification item silently: the item stays visible,+its reason is on the record, and verified-success telemetry still reads the+task as unverified. Any answered `ask_user` unlocks cancellation, the same+trust a newer user message already had.++ACP has no plan update. ACP clients see the `todo_write` call's raw input,+which now carries `reason`. A rejected write closes its row as failed. A+cancel refused for lack of a scope change is still applied per item (the item+keeps its previous status, and the reply says so), so that row's raw input can+overstate what happened.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 17036b38..7e7cc17a 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -329,6 +329,7 @@ record only when you need the evidence or the edge cases.| [0303](0303-terminal-markdown-and-worker-inspection.md) | The line REPL renders inline emphasis and offers a temporary mouse/keyboard `/workers` inspector over the existing bounded ACP child feed, without replacing the editor or changing engine behavior. || [0304](0304-file-tools-allow-in-root-symlinks.md) | File tools allow canonical in-root symlinks, reject escaping or unresolved links, and retain lexical confinement and missing write targets; the check is not an atomic sandbox. |+| [0305](0305-cancelled-checklist-items-carry-a-reason.md) | A `cancelled` todo needs a short reason or the write is rejected whole; it stays listed with that reason, stops blocking completion and never counts as verified. A verification item can be cancelled after a newer user message or an answered `ask_user`. |## When to write onediff --git a/src/agent.zig b/src/agent.zigindex 4413b91f..95cc3eb4 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -34,9 +34,8 @@ pub const TodoItem = struct {epoch: u64 = 0, // the goal epoch that authored this item (#318); 0 = no goalretired: bool = false, // a LATER user ask retired this finished item (#394): kept as the session's archive, invisible to every epoch-scoped queryask_fp: u64 = 0, // #1545: fingerprint of the user request this item was first written under; "cancelled" needs a newer one (0 = legacy/restored)-- /// Completed or cancelled: no longer open work. A cancelled item is parked,- /// never verified (goal_verify.taskVerified still refuses it).+ reason: []const u8 = "", // #1520: why a "cancelled" item was withdrawn or delegated; required, shown with it (todo_cancel.zig)+ /// Completed or cancelled: no longer open work. A cancelled item is parked, never verified (goal_verify.taskVerified refuses it).pub fn closed(t: TodoItem) bool {return std.mem.eql(u8, t.status, "completed") or std.mem.eql(u8, t.status, "cancelled");}diff --git a/src/agent_prompt.zig b/src/agent_prompt.zigindex 446ff643..dc3cc9c9 100644--- a/src/agent_prompt.zig+++ b/src/agent_prompt.zig@@ -85,7 +85,8 @@ fn standing(self: *const Agent) engine_events.StandingWork {var items: std.ArrayList(engine_events.StandingTodo) = .empty;for (self.todos.items) |t| {if (t.epoch != epoch or t.retired) continue;- out.todos_total += 1;+ const cancelled = std.mem.eql(u8, t.status, "cancelled"); // #1520: shown with its reason, not counted+ if (!cancelled) out.todos_total += 1;const done = std.mem.eql(u8, t.status, "completed");const active = std.mem.eql(u8, t.status, "in_progress");if (done) out.todos_done += 1;@@ -94,6 +95,8 @@ fn standing(self: *const Agent) engine_events.StandingWork {.content = util.utf8Prefix(t.content, 48),.done = done,.active = active,+ .cancelled = cancelled,+ .reason = t.reason,}) catch {};}}@@ -270,6 +273,11 @@ test "standing work snapshots goal, checklist, session, and a staged image" {try std.testing.expectEqualStrings("open item", sw.todos[1].content);try std.testing.expect(!sw.todos[1].done);try std.testing.expect(sw.image);+ // #1520: a cancelled item is listed with its reason but kept out of the counts.+ try agent.todos.append(agent.gpa, .{ .content = "publish", .status = "cancelled", .epoch = 1, .reason = "delegated" });+ sw = standing(&agent);+ try std.testing.expectEqual(@as(u32, 2), sw.todos_total);+ try std.testing.expect(sw.todos[2].cancelled and std.mem.eql(u8, sw.todos[2].reason, "delegated"));// A completed goal is not standing work; the default session name stays hidden.agent.goal.?.status = .complete;diff --git a/src/agent_working.zig b/src/agent_working.zigindex e51d02b9..093dbca4 100644--- a/src/agent_working.zig+++ b/src/agent_working.zig@@ -14,10 +14,14 @@ pub const Item = struct {content: []const u8,done: bool = false,active: bool = false,+ /// #1520: withdrawn or delegated. Drawn ⊘ with its reason, outside the done/total count.+ cancelled: bool = false,+ reason: []const u8 = "",};const title_clip: usize = 40;const item_clip: usize = 48;+const reason_clip: usize = 40;const max_items: usize = 8;fn clip(s: []const u8, n: usize) []const u8 {@@ -30,15 +34,24 @@ pub fn write(w: *Io.Writer, title: []const u8, items: []const Item) void {if (items.len == 0 and title.len == 0) return;const shown = if (title.len > 0) clip(title, title_clip) else "work";var done: usize = 0;+ var counted: usize = 0;for (items) |it| {+ if (it.cancelled) continue;+ counted += 1;if (it.done) done += 1;}w.print("{s}WORKING{s} {s}{s}{s}{s}", .{ style.muted, style.reset, style.bold, style.text, shown, style.reset }) catch return;- if (items.len > 0) w.print(" {s}{d}/{d}{s}", .{ style.muted, done, items.len, style.reset }) catch return;+ if (counted > 0) w.print(" {s}{d}/{d}{s}", .{ style.muted, done, counted, style.reset }) catch return;w.writeByte('\n') catch return;const n = @min(items.len, max_items);for (items[0..n], 0..) |it, i| {const branch: []const u8 = if (i + 1 == n) "└ " else "├ ";+ if (it.cancelled) {+ w.print("{s}{s}⊘ {s}", .{ style.faint, branch, clip(it.content, item_clip) }) catch return;+ if (it.reason.len > 0) w.print(" ({s})", .{clip(it.reason, reason_clip)}) catch return;+ w.print("{s}\n", .{style.reset}) catch return;+ continue;+ }const mark: []const u8 = if (it.done) "✓" else if (it.active)(if (style.accent.len > 0) "●" else "◌")else@@ -56,11 +69,12 @@ pub fn writeFromStanding(w: *Io.Writer, st: engine_events.StandingWork) void {defer writeWaiting(w, st.waiting);// Keep completed history, but do not redraw a finished checklist as WORKING.// Use the full counts: an open item may be beyond the displayed slice.- if (st.todos_total > 0 and st.todos_done == st.todos_total) return;+ // Cancelled items sit outside the counts (#1520), so all-cancelled is finished too.+ if ((st.todos_total > 0 or st.todos.len > 0) and st.todos_done == st.todos_total) return;var buf: [max_items]Item = undefined;const n = @min(st.todos.len, buf.len);for (st.todos[0..n], 0..) |t, i| {- buf[i] = .{ .content = t.content, .done = t.done, .active = t.active };+ buf[i] = .{ .content = t.content, .done = t.done, .active = t.active, .cancelled = t.cancelled, .reason = t.reason };}write(w, st.goal, buf[0..n]);}@@ -95,6 +109,15 @@ pub fn writeFromTodoText(w: *Io.Writer, title: []const u8, text: []const u8) voi} else if (std.mem.eql(u8, mark, "[ ]")) {buf[n] = .{ .content = rest };n += 1;+ } else if (std.mem.eql(u8, mark, "[-]")) {+ // goal_state.renderTodos writes "[-] content (cancelled: reason)".+ const cut = std.mem.lastIndexOf(u8, rest, " (cancelled: ");+ const has_reason = cut != null and std.mem.endsWith(u8, rest, ")");+ buf[n] = if (has_reason)+ .{ .content = rest[0..cut.?], .reason = rest[cut.? + " (cancelled: ".len .. rest.len - 1], .cancelled = true }+ else+ .{ .content = rest, .cancelled = true };+ n += 1;}}if (n == 0) return;@@ -160,6 +183,27 @@ test "a checklist is WORKING plus a tree, not [~] dump lines" {);}+test "#1520 a cancelled item is drawn with its reason, outside the done count" {+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();+ writeFromTodoText(&aw.writer, "ship", "[x] land the fix\n[ ] run the tests\n[-] verify the release (cancelled: delegated to the release session)\n");+ try std.testing.expectEqualStrings(+ "WORKING ship 1/2\n" +++ "├ ✓ land the fix\n" +++ "├ ○ run the tests\n" +++ "└ ⊘ verify the release (delegated to the release session)\n",+ aw.writer.buffered(),+ );+ aw.clearRetainingCapacity();+ // Everything else done: the idle prompt treats the list as finished.+ const items = [_]engine_events.StandingTodo{+ .{ .content = "land the fix", .done = true },+ .{ .content = "verify the release", .cancelled = true, .reason = "delegated" },+ };+ writeFromStanding(&aw.writer, .{ .todos = &items, .todos_done = 1, .todos_total = 1 });+ try std.testing.expectEqualStrings("", aw.written());+}+test "writeFromStanding uses the goal title and active/done marks" {var aw: Io.Writer.Allocating = .init(std.testing.allocator);defer aw.deinit();diff --git a/src/ask_user_answers.zig b/src/ask_user_answers.zigindex 1bc19d14..c35f5a47 100644--- a/src/ask_user_answers.zig+++ b/src/ask_user_answers.zig@@ -13,6 +13,13 @@ const Entry = struct { turn: u64 = 0, len: usize = 0, buf: [max_bytes]u8 = undefvar ring: [slots]Entry = @splat(.{});var next: usize = 0;var lock: std.atomic.Value(bool) = .init(false);+/// Every answer ever recorded, never reset (#1520): an answer is a user scope+/// change that todo_write's cancel guard must see, like a newer user message.+var answered: std.atomic.Value(u64) = .init(0);++pub fn answeredCount() u64 {+ return answered.load(.acquire);+}fn acquire() void {while (lock.swap(true, .acquire)) std.atomic.spinLoopHint();@@ -35,6 +42,7 @@ pub fn record(turn: u64, answer: []const u8) void {ring[next] = .{ .turn = turn, .len = n };@memcpy(ring[next].buf[0..n], answer[0..n]);next = (next + 1) % slots;+ _ = answered.fetchAdd(1, .acq_rel);}pub fn reset() void {diff --git a/src/engine_events.zig b/src/engine_events.zigindex 852fd968..0eab39be 100644--- a/src/engine_events.zig+++ b/src/engine_events.zig@@ -228,6 +228,10 @@ pub const StandingTodo = struct {done: bool = false,/// `todo_write` in_progress — the ◌ mark in the WORKING tree.active: bool = false,+ /// #1520: cancelled (withdrawn or delegated) with its required reason.+ /// Not counted in `todos_done`/`todos_total`.+ cancelled: bool = false,+ reason: []const u8 = "",};/// Standing work the line REPL may draw above the model prompt. Emptydiff --git a/src/goal_state.zig b/src/goal_state.zigindex b2d487e5..2344a581 100644--- a/src/goal_state.zig+++ b/src/goal_state.zig@@ -315,7 +315,9 @@ pub fn renderTodos(self: *Agent, epoch: u64) []const u8 {"[-]"else"[ ]";- w.print("{s} {s}\n", .{ mark, t.content }) catch break;+ w.print("{s} {s}", .{ mark, t.content }) catch break;+ if (t.reason.len > 0) w.print(" (cancelled: {s})", .{t.reason}) catch break; // #1520: a cancel shows why+ w.writeByte('\n') catch break;}return std.mem.trimEnd(u8, aw.writer.buffered(), "\n");}diff --git a/src/goal_todo.zig b/src/goal_todo.zigindex fc16b577..9522a9ab 100644--- a/src/goal_todo.zig+++ b/src/goal_todo.zig@@ -30,6 +30,8 @@ const Agent = agent_mod.Agent;const TodoItem = agent_mod.TodoItem;const goal_state = @import("goal_state.zig");const goal_verify_kind = @import("goal_verify_kind.zig");+const todo_cancel = @import("todo_cancel.zig"); // #1520: the cancelled status's reason and authorization rules+const contentOf = todo_cancel.contentOf;pub const ReplaceClear = struct { dropped_open: usize = 0, kept_verify: usize = 0 };@@ -133,7 +135,9 @@ pub fn applyTodoWrite(root: *Agent, list: ?Value) !WriteResult {const priors = try root.gpa.alloc(?TodoItem, incoming.items.len);defer root.gpa.free(priors);for (incoming.items, priors) |c, *p| p.* = priorItem(root.todos.items, epoch, c);- const ask_now = askFingerprint(root);+ // #1520: every cancel says why. Rejected whole, before anything changes.+ if (try todo_cancel.missingReason(root.arena, asArray(list).?, priors)) |msg| return .{ .text = msg, .rejected = true };+ const ask_now = todo_cancel.askFingerprint(root);const cleared = clearEpochForReplaceEx(&root.todos, epoch, incoming.items);goal_state.noteTodoWrite(root); // list changed; open verification still fails allDone (#844)var refused_cancel: usize = 0;@@ -143,8 +147,8 @@ pub fn applyTodoWrite(root: *Agent, list: ?Value) !WriteResult {const content = contentOf(item) orelse continue;const prior = priors[k];k += 1;- var status = if (item.object.get("status")) |st| (if (st == .string) st.string else "pending") else "pending";- if (!cancelAllowed(status, content, prior, ask_now)) {+ var status = todo_cancel.statusOf(item);+ if (!todo_cancel.allowed(status, content, prior, ask_now)) {status = if (prior) |p| p.status else "pending";refused_cancel += 1;}@@ -153,37 +157,19 @@ pub fn applyTodoWrite(root: *Agent, list: ?Value) !WriteResult {.status = try root.arena.dupe(u8, status),.epoch = epoch,.ask_fp = if (prior) |p| p.ask_fp else ask_now, // the request it was FIRST written under+ .reason = if (todo_cancel.isCancel(status)) try root.arena.dupe(u8, todo_cancel.reasonOf(item, prior)) else "",});}}var res = try writeResult(root, epoch, incoming.items, cleared);if (refused_cancel > 0) {- const note = try std.fmt.allocPrint(root.arena, "\n({d} verification item(s) were not cancelled: a verification item can be cancelled only after a newer user message changes scope; they keep their previous status)", .{refused_cancel});+ const note = try std.fmt.allocPrint(root.arena, "\n({d} verification item(s) were not cancelled: a verification item can be cancelled only after a newer user message or an ask_user answer changes scope; they keep their previous status)", .{refused_cancel});res.text = try std.mem.concat(root.arena, u8, &.{ res.text, note });res.model_text = try std.mem.concat(root.arena, u8, &.{ res.reply(), note });}return res;}-/// #1545: cancelling ordinary work is always allowed (omitting it drops it-/// anyway). A verification item is the #844 obligation, so only the USER can-/// lift it: the latest user request must differ from the one it was written-/// under. A brand-new item has nothing to cancel.-fn cancelAllowed(status: []const u8, content: []const u8, prior: ?TodoItem, ask_now: u64) bool {- if (!std.mem.eql(u8, status, "cancelled")) return true;- if (!goal_verify_kind.isVerification(content)) return true;- const p = prior orelse return false;- return p.ask_fp != ask_now;-}--/// Fingerprint of the latest real user request (notices excluded). Compaction-/// keeps the current turn's opening message verbatim, so it is stable within-/// a request and changes when the user sends a new one or steers mid-run.-fn askFingerprint(root: *const Agent) u64 {- const t = @import("messages.zig").latestUserText(root.messages.items);- return std.hash.Wyhash.hash(0x1545, t) | 1; // never 0: 0 marks a legacy item-}-fn priorItem(todos: []const TodoItem, epoch: u64, content: []const u8) ?TodoItem {for (todos) |t| if (t.epoch == epoch and !t.retired and std.mem.eql(u8, t.content, content)) return t;return null;@@ -213,13 +199,6 @@ fn asArray(list: ?Value) ?[]const Value {return l.array.items;}-fn contentOf(item: Value) ?[]const u8 {- if (item != .object) return null;- const c = item.object.get("content") orelse return null;- if (c != .string) return null;- return c.string;-}-/// A root agent in the shape the todo helpers read; no live turn behind it.fn todoRoot(arena: std.mem.Allocator) Agent {var root: Agent = undefined;@@ -505,7 +484,7 @@ test "#1545 cancelled and dropped records coexist without reopening or adoptingvar root = todoRoot(ar);_ = try applyTodoWrite(&root, try todosArg(ar,\\{"todos":[{"content":"finished work","status":"completed"},- \\ {"content":"cancelled work","status":"cancelled"},+ \\ {"content":"cancelled work","status":"cancelled","reason":"user moved on"},\\ {"content":"abandoned work","status":"dropped"}]}));try std.testing.expectEqual(@as(usize, 0), goal_state.openCount(root.todos.items, 0));@@ -516,7 +495,7 @@ test "#1545 cancelled and dropped records coexist without reopening or adopting));try std.testing.expectEqual(@as(usize, 4), root.todos.items.len);try std.testing.expectEqual(@as(usize, 0), res.dropped_open);- try std.testing.expect(std.mem.indexOf(u8, res.text, "[-] cancelled work") != null);+ try std.testing.expect(std.mem.indexOf(u8, res.text, "[-] cancelled work (cancelled: user moved on)") != null);try std.testing.expect(std.mem.indexOf(u8, res.text, "[-] abandoned work") != null);goal_state.adoptTodos(root.todos.items, 0, 1);for (root.todos.items[0..3]) |t| try std.testing.expectEqual(@as(u64, 0), t.epoch);diff --git a/src/goal_verify.zig b/src/goal_verify.zigindex a76d627a..7273f546 100644--- a/src/goal_verify.zig+++ b/src/goal_verify.zig@@ -44,7 +44,7 @@ pub fn completionGate(arena: Allocator, agent: *Agent) !?[]const u8 {if (agent.review_mode or agent.sub) return goal_state.completionGate(arena, agent);if (hasUnresolved(agent)) {const rendered = goal_state.renderTodos(agent, goal_state.currentEpoch(agent.goal));- return try std.fmt.allocPrint(arena, "completion deferred: {d} unresolved verification item(s) remain:\n{s}\nDropping or summarizing them does not satisfy completion. Finish the verification, or have the user change scope. If a newer user message already moved away from this work, set those items to status \"cancelled\" with todo_write (allowed only after a newer user message).", .{ unresolvedCount(agent), rendered });+ return try std.fmt.allocPrint(arena, "completion deferred: {d} unresolved verification item(s) remain:\n{s}\nDropping or summarizing them does not satisfy completion. Finish the verification, or have the user change scope. If the user already withdrew this work or handed it elsewhere (a newer message or an ask_user answer), set those items to status \"cancelled\" with todo_write, each with a short \"reason\" naming who withdrew it or where it went. A cancelled item stays on the list and is never counted as verified.", .{ unresolvedCount(agent), rendered });}return goal_state.completionGate(arena, agent);}@@ -176,7 +176,7 @@ test "#1545 a verification item cannot be cancelled within the request that wrot));// Same request, no user message since: the #844 obligation stands.const refused = try goal_todo.applyTodoWrite(&root, try todosArg(ar,- \\{"todos":[{"content":"run the tests","status":"cancelled"}]}+ \\{"todos":[{"content":"run the tests","status":"cancelled","reason":"taking too long"}]}));try std.testing.expect(std.mem.indexOf(u8, refused.reply(), "were not cancelled") != null);try std.testing.expectEqual(@as(usize, 1), unresolvedCount(&root));@@ -198,7 +198,7 @@ test "#1545 after a newer user message, a cancelled verification item is parked,// The user changes scope; the old verification is no longer the task.try root.messages.append(try textMessage(ar, "user", "stop that, file an issue about it instead"));const res = try goal_todo.applyTodoWrite(&root, try todosArg(ar,- \\{"todos":[{"content":"run the tests","status":"cancelled"},+ \\{"todos":[{"content":"run the tests","status":"cancelled","reason":"user switched to filing an issue"},\\ {"content":"file the issue","status":"completed"}]}));try std.testing.expect(std.mem.indexOf(u8, res.reply(), "were not cancelled") == null);@@ -221,10 +221,80 @@ test "#1545 ordinary work can be cancelled any time; a brand-new verification itconst textMessage = @import("messages.zig").textMessage;try root.messages.append(try textMessage(ar, "user", "ship it"));const res = try goal_todo.applyTodoWrite(&root, try todosArg(ar,- \\{"todos":[{"content":"sketch an alternative","status":"cancelled"},- \\ {"content":"verify the fix","status":"cancelled"}]}+ \\{"todos":[{"content":"sketch an alternative","status":"cancelled","reason":"not needed"},+ \\ {"content":"verify the fix","status":"cancelled","reason":"not needed"}]}));try std.testing.expect(std.mem.indexOf(u8, res.text, "[-] sketch an alternative") != null);try std.testing.expect(std.mem.indexOf(u8, res.text, "[ ] verify the fix") != null);try std.testing.expectEqual(@as(usize, 1), unresolvedCount(&root));}++test "#1520 withdrawn verification: omission is restored, a reasonless cancel is rejected, a reasoned cancel lets completion through unverified" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var root = todoRoot(ar);+ root.goal = .{ .objective = "ship the fix", .epoch = 1 };+ const textMessage = @import("messages.zig").textMessage;+ try root.messages.append(try textMessage(ar, "user", "fix it, run the tests, then publish and verify the release"));+ _ = try goal_todo.applyTodoWrite(&root, try todosArg(ar,+ \\{"todos":[{"content":"land the fix","status":"completed"},+ \\ {"content":"run the tests","status":"in_progress"},+ \\ {"content":"verify the published release","status":"pending"}]}+ ));+ // The user withdraws publication and hands it to another session.+ try root.messages.append(try textMessage(ar, "user", "do not publish; the release session owns that now"));+ // Leaving the item out still keeps it as an unresolved obligation.+ _ = try goal_todo.applyTodoWrite(&root, try todosArg(ar,+ \\{"todos":[{"content":"run the tests","status":"completed"}]}+ ));+ try std.testing.expectEqual(@as(usize, 1), unresolvedCount(&root));+ try std.testing.expect((try completionGate(ar, &root)) != null);+ // Cancelling without a reason is rejected whole: nothing changes.+ const bare = try goal_todo.applyTodoWrite(&root, try todosArg(ar,+ \\{"todos":[{"content":"run the tests","status":"completed"},+ \\ {"content":"verify the published release","status":"cancelled"}]}+ ));+ try std.testing.expect(bare.rejected);+ try std.testing.expect(std.mem.indexOf(u8, bare.text, "\"reason\"") != null);+ try std.testing.expectEqual(@as(usize, 1), unresolvedCount(&root));+ // With a reason, the item is closed, stays on the list, and shows why.+ const ok = try goal_todo.applyTodoWrite(&root, try todosArg(ar,+ \\{"todos":[{"content":"run the tests","status":"completed"},+ \\ {"content":"verify the published release","status":"cancelled","reason":"delegated to the release session"}]}+ ));+ try std.testing.expect(!ok.rejected);+ try std.testing.expect(std.mem.indexOf(u8, ok.text, "[-] verify the published release (cancelled: delegated to the release session)") != null);+ try std.testing.expectEqual(@as(usize, 0), unresolvedCount(&root));+ try std.testing.expect((try completionGate(ar, &root)) == null);+ try std.testing.expect(!taskVerified(&root)); // closed, never verified+ // A later write that omits it keeps the record and its reason.+ _ = try goal_todo.applyTodoWrite(&root, try todosArg(ar,+ \\{"todos":[{"content":"run the tests","status":"completed"}]}+ ));+ try std.testing.expect(std.mem.indexOf(u8, goal_state.renderTodos(&root, 1), "(cancelled: delegated to the release session)") != null);+ try std.testing.expectEqual(@as(usize, 0), unresolvedCount(&root));+}++test "#1520 an ask_user answer counts as the user's scope change for cancelling verification" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ var root = todoRoot(ar);+ const answers = @import("ask_user_answers.zig");+ defer answers.reset();+ try root.messages.append(try @import("messages.zig").textMessage(ar, "user", "publish to the old target and verify it"));+ _ = try goal_todo.applyTodoWrite(&root, try todosArg(ar,+ \\{"todos":[{"content":"verify the old target","status":"pending"}]}+ ));+ const cancel =+ \\{"todos":[{"content":"verify the old target","status":"cancelled","reason":"user replaced the target in a clarification"}]}+ ;+ const before = try goal_todo.applyTodoWrite(&root, try todosArg(ar, cancel));+ try std.testing.expect(std.mem.indexOf(u8, before.reply(), "were not cancelled") != null);+ try std.testing.expectEqual(@as(usize, 1), unresolvedCount(&root));+ answers.record(answers.turnKey("publish to the old target and verify it"), "yes, use the new target instead");+ const after = try goal_todo.applyTodoWrite(&root, try todosArg(ar, cancel));+ try std.testing.expect(std.mem.indexOf(u8, after.reply(), "were not cancelled") == null);+ try std.testing.expectEqual(@as(usize, 0), unresolvedCount(&root));+}diff --git a/src/main.zig b/src/main.zigindex 4fdf3ea3..b1322d82 100644--- a/src/main.zig+++ b/src/main.zig@@ -588,7 +588,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("goal_persist_tests.zig");_ = @import("agent_render_cleanup.zig");_ = .{ @import("goal_flow.zig"), @import("shell_identity.zig") };- _ = @import("goal_todo.zig");+ _ = .{ @import("goal_todo.zig"), @import("todo_cancel.zig") };_ = @import("goal_pacing.zig");_ = .{ @import("presence_accord.zig"), @import("peer_idle.zig"), @import("acp_idle.zig"), @import("presence_chan.zig"), @import("presence_record.zig"), @import("daddy.zig"), @import("peer_inbox_content_test.zig"), @import("peer_inbox_failure_test.zig"), @import("peer_inbox_storage_test.zig"), @import("peer_inbox_sequence_test.zig"), @import("peer_inbox_snapshot_test.zig") };_ = .{ @import("acp_agents.zig"), @import("repo_context_tests.zig") };diff --git a/src/schema.zig b/src/schema.zigindex ea77d2bc..94d34027 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -103,9 +103,9 @@ pub const base_specs = [_]ToolSpec{const meta_specs = [_]ToolSpec{.{.name = "todo_write",- .desc = "Replace the task list for the current standing goal (items from a replaced, cleared or completed goal are parked - kept in the session, but not part of this list and not replaced by this call). An item you already marked completed is kept as history when you leave it out, for as long as the current request is being worked; list it again (with any status) to change or remove it that way. Once every item is completed, the next thing the user asks starts a clean list - finished work is not carried into it. Omitted pending/in_progress items are dropped. Every call needs at least one item: a call with none leaves the list untouched. Use to plan and track multi-step work; skip it for trivial single-step tasks. Each item has content and status (pending|in_progress|completed|cancelled). Use cancelled only for work the user has moved away from: it parks the item without counting it as done, and a verification item can be cancelled only after a newer user message changes scope. Write steps small enough to verify individually; keep exactly ONE item in_progress at a time — mark it in_progress when you start and completed as it lands, never a batch flipped at the end.",+ .desc = "Replace the task list for the current standing goal (items from a replaced, cleared or completed goal are parked - kept in the session, but not part of this list and not replaced by this call). An item you already marked completed is kept as history when you leave it out, for as long as the current request is being worked; list it again (with any status) to change or remove it that way. Once every item is completed, the next thing the user asks starts a clean list - finished work is not carried into it. Omitted pending/in_progress items are dropped. Every call needs at least one item: a call with none leaves the list untouched. Use to plan and track multi-step work; skip it for trivial single-step tasks. Each item has content and status (pending|in_progress|completed|cancelled). Use cancelled only for work the user withdrew or handed to someone else, with a short reason (required: who withdrew it or where it went): the item stays on the list with its reason and stops blocking completion, but never counts as done or verified. A verification item can be cancelled only after a newer user message or an ask_user answer changes scope. Write steps small enough to verify individually; keep exactly ONE item in_progress at a time — mark it in_progress when you start and completed as it lands, never a batch flipped at the end.",.schema =- \\{"type": "object", "properties": {"todos": {"type": "array", "items": {"type": "object", "properties": {"content": {"type": "string"}, "status": {"type": "string", "enum": ["pending", "in_progress", "completed", "cancelled"]}}, "required": ["content", "status"]}}}, "required": ["todos"]}+ \\{"type": "object", "properties": {"todos": {"type": "array", "items": {"type": "object", "properties": {"content": {"type": "string"}, "status": {"type": "string", "enum": ["pending", "in_progress", "completed", "cancelled"]}, "reason": {"type": "string", "description": "Required when status is cancelled: who withdrew the item or where it was delegated, in a few words."}}, "required": ["content", "status"]}}}, "required": ["todos"]},},.{diff --git a/src/session.zig b/src/session.zigindex f89523f6..699cb1a2 100644--- a/src/session.zig+++ b/src/session.zig@@ -177,6 +177,7 @@ fn fingerprint(root: *Agent, name: []const u8) u64 {f.text(t.status);f.num(t.epoch);f.flag(t.retired); // #394: retiring a finished checklist is a real state change, so it must reach disk+ f.text(t.reason); // #1520}if (root.session_parent) |parent| f.text(parent) else f.flag(false);f.text(root.session_title orelse sessionTitle(root));@@ -319,6 +320,10 @@ fn queueSave(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !u64try s.objectField("retired");try s.write(true);}+ if (t.reason.len > 0) { // #1520: why a cancelled item was withdrawn; absent otherwise+ try s.objectField("reason");+ try s.write(t.reason);+ }try s.endObject();}try s.endArray();@@ -410,7 +415,8 @@ pub fn appendTodosFromValue(arena: Allocator, todos: *std.ArrayList(agent_mod.To// Absent in sessions written before #394: those items are live, and the// first new ask retires them if they turn out to be a finished list.const retired = if (item.object.get("retired")) |r| (r == .bool and r.bool) else false;- try todos.append(arena, .{ .content = content, .status = status, .epoch = epoch, .retired = retired });+ const reason = if (item.object.get("reason")) |r| (if (r == .string) r.string else "") else "";+ try todos.append(arena, .{ .content = content, .status = status, .epoch = epoch, .retired = retired, .reason = reason });}}diff --git a/src/session_tests.zig b/src/session_tests.zigindex b01aee4d..52698b23 100644--- a/src/session_tests.zig+++ b/src/session_tests.zig@@ -47,6 +47,10 @@ test "todos round-trip: appendTodosFromValue parses content/status/epoch, skipstry session.appendTodosFromValue(a, &todos, retired);try std.testing.expectEqual(@as(usize, 3), todos.items.len);try std.testing.expect(todos.items[2].retired);+ // #1520: a cancelled item's reason survives resume; its absence reads as none.+ try session.appendTodosFromValue(a, &todos, try std.json.parseFromSliceLeaky(Value, a, "[{\"content\":\"publish\",\"status\":\"cancelled\",\"reason\":\"delegated to the release session\"}]", .{}));+ try std.testing.expectEqualStrings("delegated to the release session", todos.items[3].reason);+ try std.testing.expectEqualStrings("", todos.items[0].reason);}test "goalFromValue: legacy string -> active; object round-trips; paused stays paused (#223)" {diff --git a/src/todo_cancel.zig b/src/todo_cancel.zignew file mode 100644index 00000000..70a4b166--- /dev/null+++ b/src/todo_cancel.zig@@ -0,0 +1,138 @@+//! todo_write's "cancelled" status (#1545, #1520): work the user withdrew or+//! handed to someone else. A cancelled item stays on the list as a record and+//! no longer blocks completion, but it never counts as verified+//! (goal_verify.taskVerified), so cancelling is not a quiet way to finish.+//!+//! Two rules keep it honest:+//! - Every cancelled item carries a short reason (who withdrew the work, or+//! where it went). A write that cancels without one is rejected whole, so+//! the reason is always on the record and the UI never shows a cancel that+//! did not happen.+//! - A verification item is the #844 obligation, so only the user can lift+//! it: a newer user message, or an ask_user answer, must have arrived since+//! the item was first written.++const std = @import("std");+const Value = std.json.Value;+const Agent = @import("agent.zig").Agent;+const TodoItem = @import("agent.zig").TodoItem;+const goal_verify_kind = @import("goal_verify_kind.zig");+const util = @import("util.zig");++pub const status = "cancelled";+/// Longest reason kept, in bytes. A reason is a label, not a report.+pub const max_reason: usize = 160;++pub fn isCancel(s: []const u8) bool {+ return std.mem.eql(u8, s, status);+}++pub fn contentOf(item: Value) ?[]const u8 {+ if (item != .object) return null;+ const c = item.object.get("content") orelse return null;+ if (c != .string) return null;+ return c.string;+}++pub fn statusOf(item: Value) []const u8 {+ const st = item.object.get("status") orelse return "pending";+ return if (st == .string) st.string else "pending";+}++/// The item's reason: its first line, trimmed and capped. A re-listed item+/// that was already cancelled keeps its recorded reason when it sends none.+pub fn reasonOf(item: Value, prior: ?TodoItem) []const u8 {+ const raw = if (item.object.get("reason")) |r| (if (r == .string) r.string else "") else "";+ const line = raw[0 .. std.mem.indexOfAny(u8, raw, "\r\n") orelse raw.len];+ const got = util.utf8Prefix(std.mem.trim(u8, line, " \t"), max_reason);+ if (got.len > 0) return got;+ const p = prior orelse return "";+ return if (isCancel(p.status)) p.reason else "";+}++/// The rejection for a write that cancels an item without a reason, or null+/// when every cancelled item has one. `priors` is aligned with the usable+/// items (those with a content string), as applyTodoWrite builds it.+pub fn missingReason(arena: std.mem.Allocator, items: []const Value, priors: []const ?TodoItem) !?[]const u8 {+ var k: usize = 0;+ for (items) |item| {+ const content = contentOf(item) orelse continue;+ const prior = priors[k];+ k += 1;+ if (!isCancel(statusOf(item)) or reasonOf(item, prior).len > 0) continue;+ return try std.fmt.allocPrint(arena, "todo_write rejected; the list is unchanged. The cancelled item \"{s}\" needs a short \"reason\" saying who withdrew the work or where it went (for example \"user withdrew publication\" or \"delegated to the release session\"). Resend the full list with a reason on every cancelled item.", .{content});+ }+ return null;+}++/// Cancelling ordinary work is always allowed (omitting it drops it anyway).+/// A verification item needs a user scope change since it was first written:+/// its request fingerprint must differ from the current one. A brand-new item+/// has nothing to cancel.+pub fn allowed(s: []const u8, content: []const u8, prior: ?TodoItem, ask_now: u64) bool {+ if (!isCancel(s)) return true;+ if (!goal_verify_kind.isVerification(content)) return true;+ const p = prior orelse return false;+ return p.ask_fp != ask_now;+}++/// Fingerprint of the user's latest word on the task: the latest real user+/// request (notices excluded) plus how many ask_user answers have arrived.+/// Compaction keeps the current turn's opening message verbatim, so it is+/// stable within a request and changes when the user sends a new message,+/// steers mid-run, or answers a question (#1520).+pub fn askFingerprint(root: *const Agent) u64 {+ const t = @import("messages.zig").latestUserText(root.messages.items);+ const answers = @import("ask_user_answers.zig").answeredCount();+ return std.hash.Wyhash.hash(0x1545 ^ answers, t) | 1; // never 0: 0 marks a legacy item+}++fn parse(arena: std.mem.Allocator, json: []const u8) !Value {+ return std.json.parseFromSliceLeaky(Value, arena, json, .{ .allocate = .alloc_always });+}++test "#1520 a cancel reason is one trimmed, capped line; a re-list keeps the recorded one" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ const given = try parse(ar, "{\"content\":\"publish\",\"status\":\"cancelled\",\"reason\":\" delegated to the release session \\nmore\"}");+ try std.testing.expectEqualStrings("delegated to the release session", reasonOf(given, null));+ const long_reason: [400]u8 = @splat('a');+ const long = try parse(ar, try std.fmt.allocPrint(ar, "{{\"content\":\"x\",\"status\":\"cancelled\",\"reason\":\"{s}\"}}", .{&long_reason}));+ try std.testing.expectEqual(max_reason, reasonOf(long, null).len);+ const bare = try parse(ar, "{\"content\":\"publish\",\"status\":\"cancelled\"}");+ try std.testing.expectEqualStrings("", reasonOf(bare, null));+ const kept: TodoItem = .{ .content = "publish", .status = "cancelled", .reason = "user withdrew it" };+ try std.testing.expectEqualStrings("user withdrew it", reasonOf(bare, kept));+ const reopened: TodoItem = .{ .content = "publish", .status = "pending", .reason = "stale" };+ try std.testing.expectEqualStrings("", reasonOf(bare, reopened));+}++test "#1520 missingReason names the first cancelled item without a reason" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const ar = arena_state.allocator();+ const list = try parse(ar,+ \\[{"content":"done","status":"completed"},{"status":"pending"},+ \\ {"content":"publish","status":"cancelled","reason":"delegated"},+ \\ {"content":"tag the release","status":"cancelled","reason":" "}]+ );+ const priors = [_]?TodoItem{ null, null, null };+ const msg = (try missingReason(ar, list.array.items, &priors)).?;+ try std.testing.expect(std.mem.indexOf(u8, msg, "\"tag the release\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, msg, "unchanged") != null);+ try std.testing.expect((try missingReason(ar, list.array.items[0..3], priors[0..2])) == null);+}++test "#1520 an ask_user answer changes the request fingerprint" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ var root: Agent = undefined;+ root.messages = std.json.Array.init(arena_state.allocator());+ const answers = @import("ask_user_answers.zig");+ defer answers.reset();+ const before = askFingerprint(&root);+ try std.testing.expectEqual(before, askFingerprint(&root)); // stable while nothing new arrives+ answers.record(0, "yes, the other session publishes");+ try std.testing.expect(before != askFingerprint(&root));+}diff --git a/src/todo_reply.zig b/src/todo_reply.zigindex 811ed830..5b5c153a 100644--- a/src/todo_reply.zig+++ b/src/todo_reply.zig@@ -42,6 +42,7 @@ pub fn text(arena: Allocator, todos: []const TodoItem, epoch: u64, incoming: []cif (!kept_header) try w.writeAll("\nKept from before (not in your list):");kept_header = true;try w.print("\n{s} {s}", .{ mark(t.status), t.content });+ if (t.reason.len > 0) try w.print(" (cancelled: {s})", .{t.reason}); // #1520}if (kept_verify > 0) try w.print("\n({d} verification item(s) you left out were kept as unresolved acceptance requirements)", .{kept_verify});if (dropped_open > 0) try w.print("\n({d} open item(s) you left out were dropped; re-list one to keep it)", .{dropped_open});@@ -100,7 +101,7 @@ test "#1545 todo reply distinguishes cancelled and dropped records from pendingdefer arena_state.deinit();const todos = [_]TodoItem{.{ .content = "finished", .status = "completed", .epoch = 1 },- .{ .content = "scope changed", .status = "cancelled", .epoch = 1 },+ .{ .content = "scope changed", .status = "cancelled", .epoch = 1, .reason = "delegated to another session" },.{ .content = "abandoned", .status = "dropped", .epoch = 1 },.{ .content = "remaining", .status = "pending", .epoch = 1 },};@@ -108,7 +109,7 @@ test "#1545 todo reply distinguishes cancelled and dropped records from pendingtry std.testing.expectEqualStrings(\\Todo list saved: 1 done, 0 in progress, 1 pending, 1 cancelled. 1 dropped (abandoned by user order; no longer blocks completion).\\Kept from before (not in your list):- \\[-] scope changed+ \\[-] scope changed (cancelled: delegated to another session)\\[-] abandoned, got);}