Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix: complete streaming display and peer-state safeguards

justrach85cbe172dde0
diff --git a/docs/adr/0004-peer-speech-is-a-working-set.md b/docs/adr/0004-peer-speech-is-a-working-set.md
index 1467f52b..161f0bf5 100644
--- a/docs/adr/0004-peer-speech-is-a-working-set.md
+++ b/docs/adr/0004-peer-speech-is-a-working-set.md
@@ -28,6 +28,10 @@ tiny bottleneck, not J-space.
process-local ring (`peer_inbox.zig`). The model pulls with
`peer_message action=inbox` and `action=list`. No roster essay, no
full text, no footer paragraph in history.
+- The ring retains complete bodies, not clipped previews. Its eight-message
+ limit still applies; overflow is reported in the wake and inbox result, and
+ the count survives resume. A failed inbox read does not clear the messages.
+ Wake sender counts count distinct senders, not messages from another sender.
- Peer injects (wakes and leftover `[peer message]` / `[presence]` lines
in old transcripts) are not a human user turn. `cleanUserTurn`,
`recentContextStart`, `emergencyCutIndex`, and `dropPriorTurnReasoning`
diff --git a/docs/adr/0014-session-resume-carries-the-room-cursor.md b/docs/adr/0014-session-resume-carries-the-room-cursor.md
index 52103a36..d2803b96 100644
--- a/docs/adr/0014-session-resume-carries-the-room-cursor.md
+++ b/docs/adr/0014-session-resume-carries-the-room-cursor.md
@@ -23,8 +23,9 @@ session.
## Decision
-- `.session.json` stores `chan_off`, `device_off`, and `peer_inbox`. Save
- strips `[peer]` / `[presence]` injects from `messages`. Resume restores the
+- `.session.json` stores `chan_off`, `device_off`, `peer_inbox`, and
+ `peer_inbox_dropped` (zero for older files). The mailbox holds full bodies;
+ resume also restores any unread overflow notice. Save strips `[peer]` / `[presence]` injects from `messages`. Resume restores the
cursor and mailbox, then injects at most one wake if something is still
unread.
- A legacy file with no cursor fields seeks both rooms to the tail (same as
diff --git a/docs/adr/0100-publication-claims-and-verified-completion.md b/docs/adr/0100-publication-claims-and-verified-completion.md
index 204fd8b8..45cfe40f 100644
--- a/docs/adr/0100-publication-claims-and-verified-completion.md
+++ b/docs/adr/0100-publication-claims-and-verified-completion.md
@@ -27,6 +27,13 @@ pass. Drafts and PR-only workflows (no pre-PR run) remain allowed.
Claims are structured (`peer_message` action=claim|release|handoff|status).
ACK, polling, and a missing PR do not transfer ownership. A gone owner is
stale and may be acquired. The ledger persists in `.graff/artifact-claims.json`.
+Every claim operation and publication check reads fresh state under a stable
+sibling file lock. Mutations replace the ledger while holding that lock; lock,
+parse, and persistence failures are errors, never evidence that work is free.
+Handoffs resolve the receiver through live peer addressing and store its
+canonical session, PID, and process-start identity. Unknown liveness remains
+held. Explicit targets narrow a check only within comparable key namespaces;
+compound or unrecognized commands retain conservative checks.
Verification checklist items survive a replace. `completionGate` will not
accept while they are open, including on the armed second call. Recipe
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index ec5e2a2d..379cb9ec 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -52,6 +52,8 @@
{"id": "peer-awareness-is-pull-not-push", "why": "#563: leadership is pull. A live peer must NOT dump a roster or inbound bodies into the first request — that was the token leak. Who is live is peer_message action=list; bodies wait behind a one-line wake only when something was parked.", "live_peer": true, "args": [], "prompt": "just checking in", "script": [{"text": "acknowledged"}], "assert": [{"request_lacks": {"index": 0, "text": "other live graff session"}}, {"request_lacks": {"index": 0, "text": "[peer message"}}, {"request_lacks": {"index": 0, "text": "[presence]"}}]}
{"id": "peer-message-list-names-live-peer", "why": "#563: action=list is ListAgents. With a live peer the tool result must name that they are live, not error, and not require text.", "live_peer": true, "args": [], "prompt": "who else is here", "script": [{"tool": "peer_message", "arguments": {"action": "list"}}, {"text": "saw them"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "live"}}]}
{"id": "peer-message-inbox-empty-when-quiet", "why": "#563: action=inbox is the mailbox. With nothing parked it must say so in the tool result — never invent a body, never require text.", "args": [], "prompt": "check the peer inbox", "script": [{"tool": "peer_message", "arguments": {"action": "inbox"}}, {"text": "nothing waiting"}], "assert": [{"event": {"type": "tool_call", "name": "peer_message"}}, {"request_contains": {"index": 1, "text": "inbox empty"}}]}
+{"id": "peer-inbox-full-body-on-pull", "why": "Received peer messages were clipped to previews, including the final coordination instruction. The wake must stay small while an explicit inbox read returns the complete UTF-8 body.", "args": [], "workspace_seed": {"queue-peer.py": "import json, os, pathlib\nroom = pathlib.Path.home() / '.graff/live'\nroom.mkdir(parents=True, exist_ok=True)\nmessage = {'from_pid': os.getpid(), 'from_session': 'fixture-sender', 'from_user': True, 'text': 'x' * 199 + '🟢\\nDO_NOT_PUBLISH_SENTINEL'}\nwith (room / 'chan-all.jsonl').open('a') as f: f.write(json.dumps(message) + '\\n')\n"}, "prompt": "Queue the local peer fixture, then read the inbox.", "script": [{"tool": "bash", "arguments": {"command": "python3 queue-peer.py"}}, {"tool": "peer_message", "arguments": {"action": "inbox"}}, {"text": "Received the complete coordination message."}], "assert": [{"request_lacks": {"index": 1, "text": "DO_NOT_PUBLISH_SENTINEL"}}, {"request_contains": {"index": 2, "text": "DO_NOT_PUBLISH_SENTINEL"}}, {"request_contains": {"index": 2, "text": "fixture-sender"}}]}
+{"id": "peer-claims-refresh-before-publication", "why": "#840: a warm process must observe a later persisted foreign claim before publication, including an identical retry. A local fake gh prevents any external write even if the guard regresses.", "args": [], "workspace_seed": {".graff/artifact-claims.json": "[]", "gh": "#!/bin/sh\nprintf 'PUBLICATION_RAN\\n'\n", "late-claim.py": "import json, pathlib\npathlib.Path('.graff/artifact-claims.json').write_text(json.dumps([{'kind': 'publication', 'key': 'feature', 'session': 'fixture-owner', 'pid': 1, 'start_id': 0}]))\npathlib.Path('gh').chmod(0o700)\n"}, "prompt": "Check claim status, install the late-claim fixture, then attempt the local fake publication twice.", "script": [{"tool": "peer_message", "arguments": {"action": "status", "kind": "publication", "key": "feature"}}, {"tool": "bash", "arguments": {"command": "python3 late-claim.py"}}, {"tool": "bash", "arguments": {"command": "PATH=\"$PWD:$PATH\" gh pr create --draft --head feature"}}, {"tool": "bash", "arguments": {"command": "PATH=\"$PWD:$PATH\" gh pr create --draft --head feature"}}, {"text": "Both publication attempts were refused."}], "assert": [{"request_contains": {"index": 1, "text": "no claim"}}, {"request_contains": {"index": 3, "text": "artifact claim held"}}, {"request_contains": {"index": 4, "text": "artifact claim held"}}, {"events_at_least": {"match": {"type": "tool_call_finished", "name": "bash", "is_error": true}, "count": 2}}, {"no_event": {"type": "tool_result", "name": "bash", "text": "PUBLICATION_RAN\n"}}]}
{"id": "readonly-exact-key-prefers-one-search", "why": "Named-file guidance forced a whole-file read before an exact-key search, adding avoidable context and a provider round trip. A read-only keyed lookup should call read_file once with contains set to the exact key, answer from the numbered match, and never read the entire file.", "args": [], "workspace_seed": {"catalog.py": "SKU0001 = {'price': 100, 'stock': 1}\nSKU0002 = {'price': 200, 'stock': 2}\nSKU0420 = {'price': 31415, 'stock': 27}\nSKU0900 = {'price': 900, 'stock': 9}\n"}, "prompt": "Read catalog.py without editing it. Find SKU0420. Reply with exactly one line in the format SKU0420|price=<price>|stock=<stock> and nothing else.", "script": [{"tool": "read_file", "arguments": {"path": "catalog.py", "contains": "SKU0420"}}, {"text": "SKU0420|price=31415|stock=27"}], "assert": [{"request_contains": {"index": 0, "text": "contains set to the exact key"}}, {"event": {"type": "tool_call", "name": "read_file"}}, {"events_at_most": {"match": {"type": "tool_call"}, "count": 1}}, {"final_text_contains": "SKU0420|price=31415|stock=27"}]}
{"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"}]}
diff --git a/src/agent.zig b/src/agent.zig
index 89afa76d..c8df567b 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -132,6 +132,7 @@ pub const Agent = struct {
handle_note_shown: bool = false, // #541: the handle-protocol lesson rides this agent's FIRST handle, once
seen_tool_keys: std.ArrayList([]const u8) = .empty, // root-only per-turn dedupe keys
md_buf: std.ArrayList(u8) = .empty, // current incomplete streamed line (markdown rendering)
+ md_cite: @import("cite_markup.zig").Stream = .{}, // display-only, survives split citation markers
md_fence: bool = false, // inside a ``` code fence while streaming
md_kind: MdKind = .classify, // incremental renderer: current line's classification
md_span: MdSpan = .normal, // incremental renderer: inline **bold**/`code` span state
@@ -231,6 +232,7 @@ pub const Agent = struct {
thinking_overflow: bool = false, // block scrolled past the screen -> don't erase on collapse
thinking_folded: bool = false, // user folded the live Thinking block (#92)
thinking_text: std.ArrayList(u8) = .empty, // buffered reasoning, so a fold can unfold (#92)
+ thinking_cite: @import("cite_markup.zig").Stream = .{},
ai_title_done: bool = false, // the one-time AI tab-title call has run this session
title_generation: u64 = 0, // invalidates detached results across /clear, /new, and manual /rename
session_recap: ?@import("recap.zig").Recap = null, // last turn-end recap (#419): the session_recap wire event, and /status's recap line
diff --git a/src/agent_render.zig b/src/agent_render.zig
index d293bc86..130f1bda 100644
--- a/src/agent_render.zig
+++ b/src/agent_render.zig
@@ -40,7 +40,10 @@ const isTableSeparator = Agent.isTableSeparator;
/// dropped) from renderMdLine's literal-marker fallback.
pub fn streamMarkdown(self: *Agent, text: []const u8) void {
const w = self.out orelse return;
- for (text) |b| self.mdByte(w, b);
+ var visible: [3]u8 = undefined;
+ for (text) |b| {
+ for (self.md_cite.byte(b, &visible)) |clean| self.mdByte(w, clean);
+ }
w.flush() catch {};
// Only now, with the delta actually on the terminal, may a parallel
// child's activity line through — and only if this delta ended a row
@@ -432,6 +435,7 @@ pub const codepointCount = markdown_url.codepointCount;
/// caller adds the separating newline), and reset fence state.
pub fn flushStreamTail(self: *Agent) void {
const w = self.out orelse return;
+ for (self.md_cite.finish()) |b| self.mdByte(w, b);
_ = self.mdFinishLine(w); // may swallow a final table row…
if (self.md_table.items.len > 0) self.flushTable(w); // …then render it
w.flush() catch {};
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index 5775be57..20495305 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -486,7 +486,7 @@ pub fn printDelta(self: *Agent, raw_line: []const u8) void {
},
};
if (no_ui) {
- if (oneshotShouldPaint(main_mod.unattended, main_mod.json_mode, text.len)) {
+ if (!self.stream_quiet and oneshotShouldPaint(main_mod.unattended, main_mod.json_mode, text.len)) {
if (main_mod.g_out) |w| {
w.writeAll(text) catch {};
w.flush() catch {};
diff --git a/src/agent_stream_render.zig b/src/agent_stream_render.zig
index 9c4c0b40..0cfeb7c4 100644
--- a/src/agent_stream_render.zig
+++ b/src/agent_stream_render.zig
@@ -118,6 +118,11 @@ pub fn spinnerStop(self: *Agent) void {
/// one-line summary when the answer starts (#75).
pub fn streamThinking(self: *Agent, chunk: []const u8) void {
const w = self.out orelse return;
+ const start = self.thinking_text.items.len;
+ var bytes: [3]u8 = undefined;
+ for (chunk) |b| self.thinking_text.appendSlice(self.gpa, self.thinking_cite.byte(b, &bytes)) catch return;
+ const visible = self.thinking_text.items[start..];
+ if (visible.len == 0) return;
if (!self.thinking_open) {
self.spinnerStop();
w.print("{s}▼ Thinking{s}\n{s}", .{ style.dim, style.reset, style.dim }) catch return;
@@ -131,11 +136,10 @@ pub fn streamThinking(self: *Agent, chunk: []const u8) void {
// block (or shift the erase onto real output). Hold until it closes.
tick_gate.hold();
}
- self.thinking_text.appendSlice(self.gpa, chunk) catch {};
if (self.thinking_folded) return; // folded: buffer only, don't draw the live block
- w.writeAll(chunk) catch return;
+ w.writeAll(visible) catch return;
w.flush() catch return;
- advanceThinkingRows(&self.thinking_rows, &self.thinking_col, termCols(), chunk);
+ advanceThinkingRows(&self.thinking_rows, &self.thinking_col, termCols(), visible);
if (self.thinking_rows + 1 >= termRows()) self.thinking_overflow = true;
}
@@ -145,7 +149,15 @@ pub fn streamThinking(self: *Agent, chunk: []const u8) void {
/// erase the user's earlier output. Runs on the reasoning->answer transition
/// and at stream end.
pub fn closeThinkingBlock(self: *Agent) void {
+ const tail = self.thinking_cite.finish();
if (!self.thinking_open) return;
+ if (tail.len != 0) {
+ self.thinking_text.appendSlice(self.gpa, tail) catch {};
+ if (!self.thinking_folded) if (self.out) |w| {
+ w.writeAll(tail) catch {};
+ advanceThinkingRows(&self.thinking_rows, &self.thinking_col, termCols(), tail);
+ };
+ }
self.thinking_open = false;
main_mod.g_thinking_open = false;
self.thinking_folded = false;
diff --git a/src/agent_working.zig b/src/agent_working.zig
index c3af6bb6..decc663b 100644
--- a/src/agent_working.zig
+++ b/src/agent_working.zig
@@ -44,6 +44,9 @@ pub fn write(w: *Io.Writer, title: []const u8, items: []const Item) void {
}
pub fn writeFromStanding(w: *Io.Writer, st: engine_events.StandingWork) void {
+ // Keep completed history, but do not redraw it as WORKING at every prompt.
+ // Use the full counts: an open item may be beyond the displayed slice.
+ if (st.goal.len == 0 and st.todos_total > 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| {
@@ -79,6 +82,24 @@ pub fn writeFromTodoText(w: *Io.Writer, title: []const u8, text: []const u8) voi
write(w, title, buf[0..n]);
}
+test "completed checklist stays out of idle prompt redraws" {
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ const todos = [_]engine_events.StandingTodo{.{ .content = "finished", .done = true }};
+ var st: engine_events.StandingWork = .{ .todos = &todos, .todos_done = 1, .todos_total = 1 };
+ writeFromStanding(&aw.writer, st);
+ try std.testing.expectEqualStrings("", aw.written());
+ // A live goal or an open item beyond the displayed slice is still work.
+ st.goal = "continue the goal";
+ writeFromStanding(&aw.writer, st);
+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "WORKING") != null);
+ aw.clearRetainingCapacity();
+ st.goal = "";
+ st.todos_total = 2;
+ writeFromStanding(&aw.writer, st);
+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "WORKING") != null);
+}
+
test "empty standing work draws nothing" {
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
diff --git a/src/artifact_claim.zig b/src/artifact_claim.zig
index 0df79cbb..33684b6b 100644
--- a/src/artifact_claim.zig
+++ b/src/artifact_claim.zig
@@ -52,8 +52,8 @@ pub fn kindFrom(text: []const u8) ?Kind {
}
pub fn sameOwner(a: Owner, b: Owner) bool {
- if (a.session.len > 0 and b.session.len > 0 and std.mem.eql(u8, a.session, b.session)) return true;
- return a.pid != 0 and a.pid == b.pid and a.start_id == b.start_id;
+ if (a.pid == 0 and b.pid == 0) return a.session.len > 0 and std.mem.eql(u8, a.session, b.session);
+ return a.pid != 0 and a.pid == b.pid and a.start_id == b.start_id and std.mem.eql(u8, a.session, b.session);
}
fn sameKey(a: Claim, kind: Kind, key: []const u8) bool {
@@ -174,16 +174,17 @@ pub fn isClaimedMutation(cmd: []const u8) bool {
saw_gh = true;
continue;
}
- if (saw_gh and std.mem.eql(u8, tok, "pr")) {
+ if (saw_gh and (std.mem.eql(u8, tok, "pr") or std.mem.eql(u8, tok, "issue"))) {
saw_pr = true;
continue;
}
- if (saw_pr and (std.mem.eql(u8, tok, "create") or std.mem.eql(u8, tok, "edit") or std.mem.eql(u8, tok, "ready"))) return true;
+ if (saw_pr and (std.mem.eql(u8, tok, "create") or std.mem.eql(u8, tok, "edit") or std.mem.eql(u8, tok, "ready") or std.mem.eql(u8, tok, "close") or std.mem.eql(u8, tok, "reopen") or std.mem.eql(u8, tok, "comment"))) return true;
}
return false;
}
pub fn mutationKind(cmd: []const u8) Kind {
+ if (std.mem.indexOf(u8, cmd, "gh issue ") != null) return .issue;
if (std.mem.indexOf(u8, cmd, "gh pr") != null) return .pull_request;
if (std.mem.indexOf(u8, cmd, "git push") != null) return .publication;
if (std.mem.indexOf(u8, cmd, "git commit") != null or std.mem.indexOf(u8, cmd, "git add") != null) return .commit;
@@ -200,7 +201,7 @@ var g_ledger: Ledger = .{};
var g_test_owner: Owner = .{};
var g_test_live: bool = true;
var g_persist_path: ?[]const u8 = null;
-var g_loaded: bool = false;
+var g_test_peers: ?[]const @import("worktree_lease.zig").Owner = null;
var g_store: ?std.heap.ArenaAllocator = null;
pub const persist_rel = ".graff/artifact-claims.json";
@@ -215,7 +216,7 @@ pub fn resetForTest() void {
g_test_owner = .{};
g_test_live = true;
g_persist_path = null;
- g_loaded = true; // tests start with an empty in-memory ledger
+ g_test_peers = null;
if (g_store) |*st| {
st.deinit();
g_store = null;
@@ -224,7 +225,6 @@ pub fn resetForTest() void {
pub fn setPersistPath(path: []const u8) void {
g_persist_path = path;
- g_loaded = false;
}
pub fn setTestOwner(owner: Owner) void {
@@ -239,12 +239,12 @@ pub fn testLedger() *Ledger {
return &g_ledger;
}
-pub fn selfOwner() Owner {
+pub fn selfOwner(io: Io) Owner {
if (g_test_owner.session.len > 0 or g_test_owner.pid != 0) return g_test_owner;
return .{
.session = presence.ownSession(),
.pid = proc_identity.selfPid(),
- .start_id = 0,
+ .start_id = proc_identity.selfStartId(io),
};
}
@@ -277,21 +277,15 @@ pub fn gateCommand(arena: Allocator, io: Io, cmd: []const u8, key: []const u8) ?
const ledger = if (tx != null) &local else &g_ledger;
if (tx) |transaction| loadTransaction(transaction, ledger) catch return "artifact claim ledger unreadable: action NOT performed";
const kind = mutationKind(cmd);
- var me = selfOwner();
- if (!builtin.is_test) me.start_id = proc_identity.selfStartId(io);
- if (key.len == 0) {
- for (ledger.slice()) |c| {
- if (!claimRelevant(c.kind, kind)) continue;
- const live = ownerLive(io, c.owner);
- if (verdict(ledger.slice(), c.kind, c.key, me, live) == .foreign_live)
- return refuseText(arena, c.kind, c.key, c.owner);
- }
- return null;
- }
- for (ledger.slice()) |held| {
- if (!claimRelevant(held.kind, kind)) continue;
- if (held.key.len != 0 and !std.mem.eql(u8, held.key, key)) continue;
- if (!sameOwner(held.owner, me) and ownerLive(io, held.owner)) return refuseText(arena, held.kind, held.key, held.owner);
+ const compound = std.mem.indexOfAny(u8, cmd, ";|&`$\n") != null;
+ const me = selfOwner(io);
+ const target: @import("artifact_claim_target.zig").Target = @import("artifact_claim_target.zig").explicit(cmd, kind) orelse .{ .kind = if (kind == .issue) Kind.issue else Kind.branch, .key = key };
+ for (ledger.slice()) |c| {
+ if (!compound and !claimRelevant(c.kind, kind)) continue;
+ const comparable = c.kind == target.kind or (c.kind == .publication and target.kind == .branch);
+ if (!compound and comparable and target.key.len > 0 and c.key.len > 0 and !std.mem.eql(u8, c.key, target.key)) continue;
+ if (verdict(ledger.slice(), c.kind, c.key, me, ownerLive(io, c.owner)) == .foreign_live)
+ return refuseText(arena, c.kind, c.key, c.owner);
}
return null;
}
@@ -309,8 +303,7 @@ pub fn handleTool(arena: Allocator, io: Io, action: []const u8, kind_s: []const
.text = "kind must be branch, issue, commit, pull_request, or publication",
.is_error = true,
};
- var me = selfOwner();
- if (!builtin.is_test) me.start_id = proc_identity.selfStartId(io);
+ const me = selfOwner(io);
const now: i64 = 0;
const existing = find(ledger.slice(), kind, key);
const live = if (existing) |c| ownerLive(io, c.owner) else false;
@@ -332,15 +325,21 @@ pub fn handleTool(arena: Allocator, io: Io, action: []const u8, kind_s: []const
}
if (std.mem.eql(u8, action, "handoff")) {
if (to_session.len == 0) return .{ .text = "handoff needs session (the receiver)", .is_error = true };
- var receiver = Owner{ .session = to_session };
- if (!builtin.is_test) {
- const target = @import("peer_target.zig").resolvePeer(presence.liveAllPeers(io, scratch.allocator()), to_session);
- if (target != .one) return .{ .text = "handoff needs one identifiable live peer", .is_error = true };
- const peer = target.one;
- if (!std.mem.eql(u8, peer.identity, presence.ownIdentity()) or peer.start_id == 0) return .{ .text = "handoff receiver must have verified identity in this workspace", .is_error = true };
- receiver = .{ .session = peer.session_id, .pid = peer.pid, .start_id = peer.start_id };
- }
- const msg = handoff(ledger, storage, kind, key, me, receiver, now, live) catch |err| switch (err) {
+ const receiver = switch (@import("peer_target.zig").resolvePeer(if (builtin.is_test) g_test_peers orelse presence.liveAllPeers(io, arena) else presence.liveAllPeers(io, arena), to_session)) {
+ .one => |p| p,
+ .none => return .{ .text = "handoff receiver is not a live peer", .is_error = true },
+ .ambiguous => return .{ .text = "handoff receiver is ambiguous", .is_error = true },
+ };
+ if (!builtin.is_test and (!std.mem.eql(u8, receiver.identity, presence.ownIdentity()) or receiver.start_id == 0))
+ return .{ .text = "handoff receiver must have verified identity in this workspace", .is_error = true };
+ const probe = proc_identity.probe(io, receiver.pid);
+ if (receiver.pid <= 0 or receiver.session_id.len == 0 or proc_identity.ownerState(receiver.start_id, probe) != .held)
+ return .{ .text = "handoff receiver is gone", .is_error = true };
+ const start_id = switch (probe) {
+ .id => |id| id,
+ else => receiver.start_id,
+ };
+ const msg = handoff(ledger, storage, kind, key, me, .{ .session = receiver.session_id, .pid = receiver.pid, .start_id = start_id }, now, live) catch |err| switch (err) {
error.ClaimHeld => return .{ .text = "cannot hand off a claim you do not own", .is_error = true },
error.NoClaim => return .{ .text = "no claim to hand off", .is_error = true },
else => return .{ .text = "handoff failed", .is_error = true },
@@ -388,49 +387,8 @@ fn reload(io: Io) !void {
try loadJson(storeAlloc(), &g_ledger, text);
}
-pub fn persistJson(arena: Allocator, ledger: *const Ledger) ![]const u8 {
- var aw: Io.Writer.Allocating = .init(arena);
- var s: std.json.Stringify = .{ .writer = &aw.writer };
- try s.beginArray();
- for (ledger.slice()) |c| {
- try s.beginObject();
- try s.objectField("kind");
- try s.write(@tagName(c.kind));
- try s.objectField("key");
- try s.write(c.key);
- try s.objectField("session");
- try s.write(c.owner.session);
- try s.objectField("pid");
- try s.write(c.owner.pid);
- try s.objectField("start_id");
- try s.write(c.owner.start_id);
- try s.endObject();
- }
- try s.endArray();
- return aw.writer.buffered();
-}
-
-pub fn loadJson(arena: Allocator, ledger: *Ledger, text: []const u8) !void {
- ledger.len = 0;
- const parsed = try std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{});
- if (parsed != .array) return error.InvalidLedger;
- for (parsed.array.items) |item| {
- if (item != .object) return error.InvalidLedger;
- const kind_s = if (item.object.get("kind")) |v| (if (v == .string) v.string else return error.InvalidLedger) else return error.InvalidLedger;
- const kind = kindFrom(kind_s) orelse return error.InvalidLedger;
- const key = if (item.object.get("key")) |v| (if (v == .string) v.string else "") else "";
- const session = if (item.object.get("session")) |v| (if (v == .string) v.string else "") else "";
- const pid: i32 = if (item.object.get("pid")) |v| (if (v == .integer) (std.math.cast(i32, v.integer) orelse return error.InvalidLedger) else return error.InvalidLedger) else 0;
- const start_id: u64 = if (item.object.get("start_id")) |v| (if (v == .integer and v.integer >= 0) @intCast(v.integer) else 0) else 0;
- if (ledger.len >= max_claims) return error.InvalidLedger;
- ledger.items[ledger.len] = .{
- .kind = kind,
- .key = try arena.dupe(u8, key),
- .owner = .{ .session = try arena.dupe(u8, session), .pid = pid, .start_id = start_id },
- };
- ledger.len += 1;
- }
-}
+pub const persistJson = @import("artifact_claim_store.zig").persistJson;
+pub const loadJson = @import("artifact_claim_store.zig").loadJson;
test "acquire / handoff / release are atomic and session-scoped" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
@@ -510,6 +468,9 @@ test "#840 acknowledged handoff does not let the other session create the PR" {
const ar = arena_state.allocator();
resetForTest();
defer resetForTest();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ setPersistPath(try std.fmt.allocPrint(ar, ".zig-cache/tmp/{s}/claims.json", .{tmp.sub_path}));
setTestOwner(.{ .session = "s-owner", .pid = 11, .start_id = 1 });
const got = try handleTool(ar, std.testing.io, "claim", "publication", "feat/x", "");
try std.testing.expect(!got.is_error);
@@ -521,9 +482,12 @@ test "#840 acknowledged handoff does not let the other session create the PR" {
try std.testing.expect(std.mem.indexOf(u8, blocked, "handoff") != null);
// Explicit handoff atomically enables the receiver.
setTestOwner(.{ .session = "s-owner", .pid = 11, .start_id = 1 });
- const ho = try handleTool(ar, std.testing.io, "handoff", "publication", "feat/x", "s-other");
+ const rec = proc_identity.selfRecord(std.testing.io);
+ const peers = [_]@import("worktree_lease.zig").Owner{.{ .session_id = "s-other", .title = "Receiver title", .pid = rec.pid, .start_id = rec.start_id }};
+ g_test_peers = &peers;
+ const ho = try handleTool(ar, std.testing.io, "handoff", "publication", "feat/x", "Receiver title");
try std.testing.expect(!ho.is_error);
- setTestOwner(.{ .session = "s-other", .pid = 12, .start_id = 2 });
+ setTestOwner(.{ .session = "s-other", .pid = rec.pid, .start_id = rec.start_id });
try std.testing.expect(gateCommand(ar, std.testing.io, "gh pr create --title x --body y", "feat/x") == null);
setTestOwner(.{ .session = "s-owner", .pid = 11, .start_id = 1 });
try std.testing.expect(gateCommand(ar, std.testing.io, "gh pr create --title x --body y", "feat/x") != null);
@@ -556,17 +520,41 @@ test "file persist reloads after a resume-shaped reset" {
resetForTest();
defer resetForTest();
setPersistPath(file);
- g_loaded = true;
setTestOwner(.{ .session = "s-persist", .pid = 4, .start_id = 9 });
_ = try handleTool(ar, io, "claim", "publication", "feat/x", "");
g_ledger.len = 0;
- g_loaded = false;
try reload(io);
try std.testing.expectEqual(@as(usize, 1), g_ledger.len);
try std.testing.expectEqualStrings("feat/x", g_ledger.items[0].key);
try std.testing.expectEqualStrings("s-persist", g_ledger.items[0].owner.session);
}
+test "#840 malformed ledger and recycled identity never authorize ownership" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ var ledger: Ledger = .{};
+ const invalid = [_][]const u8{
+ "{}", "[{}]", "[1]",
+ "[{\"kind\":\"branch\",\"key\":\"x\",\"session\":\"s\",\"pid\":2147483648}]", "[{\"kind\":\"branch\",\"key\":\"x\",\"session\":\"s\",\"start_id\":-1}]", "[{\"kind\":\"branch\",\"key\":\"x\",\"session\":\"s\"},{\"kind\":\"branch\",\"key\":\"x\",\"session\":\"t\"}]",
+ };
+ for (invalid) |text| try std.testing.expectError(error.InvalidClaimLedger, loadJson(ar, &ledger, text));
+ resetForTest();
+ defer resetForTest();
+ const me = selfOwner(std.testing.io);
+ var reused = me;
+ reused.start_id +%= 1;
+ try std.testing.expect(!sameOwner(me, reused));
+ if (me.start_id != 0) try std.testing.expect(!ownerLive(std.testing.io, reused));
+ reused = me;
+ reused.pid += 1;
+ try std.testing.expect(!sameOwner(me, reused));
+ setTestOwner(.{ .session = "owner" });
+ _ = try handleTool(ar, std.testing.io, "claim", "issue", "840", "");
+ try std.testing.expect((try handleTool(ar, std.testing.io, "handoff", "issue", "840", "unresolved")).is_error);
+ try std.testing.expectEqualStrings("owner", testLedger().items[0].owner.session);
+}
+
test "shared-tree ACK is not a claim release" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/artifact_claim_store.zig b/src/artifact_claim_store.zig
new file mode 100644
index 00000000..0854ff6c
--- /dev/null
+++ b/src/artifact_claim_store.zig
@@ -0,0 +1,54 @@
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const claims = @import("artifact_claim.zig");
+const Ledger = claims.Ledger;
+const kindFrom = claims.kindFrom;
+const max_claims = 32;
+
+pub fn persistJson(arena: Allocator, ledger: *const Ledger) ![]const u8 {
+ var aw: Io.Writer.Allocating = .init(arena);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.beginArray();
+ for (ledger.slice()) |c| {
+ try s.beginObject();
+ try s.objectField("kind");
+ try s.write(@tagName(c.kind));
+ try s.objectField("key");
+ try s.write(c.key);
+ try s.objectField("session");
+ try s.write(c.owner.session);
+ try s.objectField("pid");
+ try s.write(c.owner.pid);
+ try s.objectField("start_id");
+ try s.write(c.owner.start_id);
+ try s.endObject();
+ }
+ try s.endArray();
+ return aw.writer.buffered();
+}
+
+pub fn loadJson(arena: Allocator, ledger: *Ledger, text: []const u8) !void {
+ ledger.len = 0;
+ const parsed = std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{}) catch return error.InvalidClaimLedger;
+ if (parsed != .array) return error.InvalidClaimLedger;
+ for (parsed.array.items) |item| {
+ if (item != .object) return error.InvalidClaimLedger;
+ const kind_s = if (item.object.get("kind")) |v| (if (v == .string) v.string else return error.InvalidClaimLedger) else return error.InvalidClaimLedger;
+ const kind = kindFrom(kind_s) orelse return error.InvalidClaimLedger;
+ const key = if (item.object.get("key")) |v| (if (v == .string) v.string else return error.InvalidClaimLedger) else return error.InvalidClaimLedger;
+ const session = if (item.object.get("session")) |v| (if (v == .string) v.string else return error.InvalidClaimLedger) else return error.InvalidClaimLedger;
+ const pid: i32 = if (item.object.get("pid")) |v| (if (v == .integer and v.integer >= 0 and v.integer <= std.math.maxInt(i32)) @intCast(v.integer) else return error.InvalidClaimLedger) else 0;
+ const start_id: u64 = if (item.object.get("start_id")) |v| (if (v == .integer and v.integer >= 0) @intCast(v.integer) else return error.InvalidClaimLedger) else 0;
+ if (ledger.len >= max_claims) return error.InvalidClaimLedger;
+ for (ledger.slice()) |c| {
+ if (c.kind == kind and std.mem.eql(u8, c.key, key)) return error.InvalidClaimLedger;
+ }
+ ledger.items[ledger.len] = .{
+ .kind = kind,
+ .key = try arena.dupe(u8, key),
+ .owner = .{ .session = try arena.dupe(u8, session), .pid = pid, .start_id = start_id },
+ };
+ ledger.len += 1;
+ }
+}
diff --git a/src/artifact_claim_target.zig b/src/artifact_claim_target.zig
new file mode 100644
index 00000000..eb07363e
--- /dev/null
+++ b/src/artifact_claim_target.zig
@@ -0,0 +1,24 @@
+//! Bounded literal targets; unknown shell forms retain conservative checks.
+const std = @import("std");
+const claims = @import("artifact_claim.zig");
+
+pub const Target = struct { kind: claims.Kind, key: []const u8 };
+
+pub fn explicit(cmd: []const u8, kind: claims.Kind) ?Target {
+ // Do not infer one target for a compound command.
+ if (std.mem.indexOfAny(u8, cmd, ";|&`$\n\"'\\*?{}") != null) return null;
+ if (!std.mem.startsWith(u8, cmd, "gh pr ") and !std.mem.startsWith(u8, cmd, "gh issue ")) return null;
+ var words = std.mem.tokenizeAny(u8, cmd, " \t\r\"'");
+ var previous: []const u8 = "";
+ var object = false;
+ var action = false;
+ while (words.next()) |word| {
+ if (std.mem.eql(u8, previous, "--head") or std.mem.eql(u8, previous, "-H")) return .{ .kind = .branch, .key = word };
+ if (std.mem.startsWith(u8, word, "--head=")) return .{ .kind = .branch, .key = word[7..] };
+ if (action) return if (!std.mem.startsWith(u8, word, "-")) .{ .kind = kind, .key = word } else null;
+ if (object and (std.mem.eql(u8, word, "edit") or std.mem.eql(u8, word, "ready") or std.mem.eql(u8, word, "close") or std.mem.eql(u8, word, "reopen") or std.mem.eql(u8, word, "comment"))) action = true;
+ if ((kind == .issue and std.mem.eql(u8, word, "issue")) or (kind == .pull_request and std.mem.eql(u8, word, "pr"))) object = true;
+ previous = word;
+ }
+ return null;
+}
diff --git a/src/cite_markup.zig b/src/cite_markup.zig
index 326f8bd7..27ad20e3 100644
--- a/src/cite_markup.zig
+++ b/src/cite_markup.zig
@@ -75,43 +75,49 @@ pub fn dupe(alloc: Allocator, text: []const u8) ![]u8 {
return aw.toOwnedSlice();
}
-/// Incremental counterpart to dupe. Hold at most two bytes while recognizing
-/// a UTF-8 control marker; suppress its payload through the matching end.
+/// Display-only filter. Hold a possible marker prefix across deltas, and
+/// discard annotation bodies without buffering arbitrarily long references.
+/// Each channel owns its state; the provider payload is never rewritten.
pub const Stream = struct {
- prefix: u2 = 0,
- hidden: bool = false,
+ pending: usize = 0,
+ in_annotation: bool = false,
- /// buf needs three bytes. Returned bytes are ordinary user-facing text.
- pub fn byte(self: *Stream, c: u8, buf: *[3]u8) []const u8 {
- var n: usize = 0;
- if (self.prefix == 2 and c >= mark_start and c <= mark_sep) {
- if (c == mark_start) self.hidden = true;
- if (c == mark_end) self.hidden = false;
- self.prefix = 0;
- return buf[0..0];
+ pub fn byte(self: *Stream, b: u8, out: *[3]u8) []const u8 {
+ if (self.pending == 1 and b == pua_lead[1]) {
+ self.pending = 2;
+ return "";
}
- if (self.prefix == 1 and c == pua_lead[1]) {
- self.prefix = 2;
- return buf[0..0];
+ if (self.pending == 2 and b >= mark_start and b <= mark_sep) {
+ self.pending = 0;
+ if (b == mark_start) self.in_annotation = true;
+ if (b == mark_end) self.in_annotation = false;
+ return "";
}
- if (!self.hidden) {
- if (self.prefix > 0) {
- buf[n] = pua_lead[0];
- n += 1;
- }
- if (self.prefix > 1) {
- buf[n] = pua_lead[1];
- n += 1;
- }
+ var n: usize = 0;
+ if (!self.in_annotation) {
+ n = self.pending;
+ @memcpy(out[0..n], pua_lead[0..n]);
}
- self.prefix = 0;
- if (c == pua_lead[0]) {
- self.prefix = 1;
- } else if (!self.hidden) {
- buf[n] = c;
+ self.pending = 0;
+ if (b == pua_lead[0]) {
+ self.pending = 1;
+ } else if (!self.in_annotation) {
+ out[n] = b;
n += 1;
}
- return buf[0..n];
+ return out[0..n];
+ }
+
+ pub fn write(self: *Stream, w: *std.Io.Writer, text: []const u8) !void {
+ var out: [3]u8 = undefined;
+ for (text) |b| try w.writeAll(self.byte(b, &out));
+ }
+
+ /// Drop an unfinished annotation, but preserve any non-annotation tail.
+ pub fn finish(self: *Stream) []const u8 {
+ const tail = if (self.in_annotation) "" else pua_lead[0..self.pending];
+ self.* = .{};
+ return tail;
}
};
diff --git a/src/engine_sink.zig b/src/engine_sink.zig
index 458d5c09..c750acff 100644
--- a/src/engine_sink.zig
+++ b/src/engine_sink.zig
@@ -208,9 +208,19 @@ fn lifecycleEmit(ctx: *anyopaque, ev: Stamped) void {
/// text now shares the Markdown renderer so link targets exclude delimiters (#729).
fn tuiEmit(ctx: *anyopaque, ev: Stamped) void {
const a: *Agent = @ptrCast(@alignCast(ctx));
+ // Compaction uses the live transport too, but its reply is bookkeeping,
+ // not a new answer. Gate presentation, including the hosted fallback.
+ if (a.stream_quiet) switch (ev.event) {
+ .reasoning_delta, .text_delta, .tool_arg_delta, .stream_complete => return,
+ else => {},
+ };
if (hosted_frontend) return hostedEmit(a, ev.event);
switch (ev.event) {
- .stream_begin => render.spinnerStart(a),
+ .stream_begin => {
+ a.md_cite = .{};
+ a.thinking_cite = .{};
+ render.spinnerStart(a);
+ },
// Reasoning streams into the live dimmed "Thinking" block when
// /thinking is on for a live, colored root turn; otherwise the
// spinner stands in for it. TRANSITIONAL (slice-1 debt, see header):
@@ -236,7 +246,7 @@ fn tuiEmit(ctx: *anyopaque, ev: Stamped) void {
if (main_mod.use_color) {
a.streamMarkdown(d.text);
} else if (a.out) |w| {
- w.writeAll(d.text) catch return;
+ a.md_cite.write(w, d.text) catch return;
w.flush() catch return;
}
},
@@ -262,7 +272,7 @@ fn tuiEmit(ctx: *anyopaque, ev: Stamped) void {
notice(a, line);
},
.stream_aborted => |reason| {
- a.flushStreamTail(); // render any held partial markdown line
+ if (!a.stream_quiet) a.flushStreamTail(); // quiet requests must not replay a held tail
switch (reason) {
.interrupted => {}, // a deliberate Esc needs no notice
.stalled => notice(a, "\n⚠ stream stalled — ending turn\n"),
diff --git a/src/engine_sink_tests.zig b/src/engine_sink_tests.zig
index 538015ac..fbe60121 100644
--- a/src/engine_sink_tests.zig
+++ b/src/engine_sink_tests.zig
@@ -547,3 +547,44 @@ test "correlated meta tools finish without duplicating their result body" {
try std.testing.expectEqualStrings("tool_call_finished", parsed.value.object.get("type").?.string);
try std.testing.expect(parsed.value.object.get("text") == null);
}
+
+test "quiet compaction deltas and tails stay off terminal outputs" {
+ const saved_color = main_mod.use_color;
+ const saved_json = main_mod.json_mode;
+ const saved_hosted = engine_sink.hosted_frontend;
+ const saved_unattended = main_mod.unattended;
+ const saved_out = main_mod.g_out;
+ defer main_mod.use_color = saved_color;
+ defer main_mod.json_mode = saved_json;
+ defer engine_sink.hosted_frontend = saved_hosted;
+ defer main_mod.unattended = saved_unattended;
+ defer main_mod.g_out = saved_out;
+ main_mod.json_mode = false;
+ for ([_]bool{ false, true }) |color| {
+ main_mod.use_color = color;
+ for ([_]bool{ false, true }) |hosted| {
+ engine_sink.hosted_frontend = hosted;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+ defer deinitMarkdown(&a);
+ a.stream_quiet = true;
+ a.show_thinking = true;
+ const sink = tuiSink(&a);
+ sink.emit(std.testing.io, .{ .reasoning_delta = .{ .text = "internal reasoning" } });
+ sink.emit(std.testing.io, .{ .text_delta = .{ .text = "internal answer" } });
+ sink.emit(std.testing.io, .{ .tool_arg_delta = .{ .text = "internal argument" } });
+ try a.md_buf.appendSlice(a.gpa, "held tail");
+ sink.emit(std.testing.io, .{ .stream_complete = .{ .streamed_text = true } });
+ sink.emit(std.testing.io, .{ .stream_aborted = .interrupted });
+ try std.testing.expectEqualStrings("", aw.written());
+ // A frontendless oneshot has a separate stdout fast path.
+ a.out = null;
+ a.provider = .{ .id = "test", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "test", .context = 0 };
+ main_mod.g_out = &aw.writer;
+ main_mod.unattended = true;
+ a.printDelta("data: {\"type\":\"response.output_text.delta\",\"delta\":\"internal prose\"}");
+ try std.testing.expectEqualStrings("", aw.written());
+ }
+ }
+}
diff --git a/src/main_test.zig b/src/main_test.zig
index c1bde2cc..d77a773e 100644
--- a/src/main_test.zig
+++ b/src/main_test.zig
@@ -375,3 +375,200 @@ test "failure (#253): fd-quota errors carry actionable advice, system-wide says
defer gpa.free(g.text);
try std.testing.expectEqualStrings("error: AccessDenied", g.text);
}
+
+fn citationAgent(w: *Io.Writer) Agent {
+ return .{
+ .gpa = std.testing.allocator,
+ .arena = std.testing.allocator,
+ .io = std.testing.io,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "test",
+ .out = w,
+ };
+}
+
+const citation_prose = "before\u{E200}cite\u{E202}turn0view0\u{E202}turn0search1\u{E201} after \u{E203}✓";
+const citation_clean = "before after \u{E203}✓";
+
+test "citation annotations never reach streamed terminal prose" {
+ const main = @import("main.zig");
+ const sinks = @import("engine_sink.zig");
+ const saved_color = main.use_color;
+ const saved_json = main.json_mode;
+ const saved_hosted = sinks.hosted_frontend;
+ defer main.use_color = saved_color;
+ defer main.json_mode = saved_json;
+ defer sinks.hosted_frontend = saved_hosted;
+ main.json_mode = false;
+ sinks.hosted_frontend = false;
+ for ([_]bool{ false, true }) |color| {
+ main.use_color = color;
+ for ([_]bool{ false, true }) |argument| {
+ // Every chunk width, including one-byte chunks, exercises split
+ // UTF-8 glyphs as well as split annotation names and references.
+ for (1..citation_prose.len + 1) |width| {
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = citationAgent(&aw.writer);
+ defer @import("agent_render.zig").deinitMarkdown(&a);
+ const sink = sinks.tuiSink(&a);
+ var i: usize = 0;
+ while (i < citation_prose.len) : (i += width) {
+ const text = citation_prose[i..@min(i + width, citation_prose.len)];
+ sink.emit(std.testing.io, if (argument) .{ .tool_arg_delta = .{ .text = text } } else .{ .text_delta = .{ .text = text } });
+ }
+ sink.emit(std.testing.io, .{ .stream_complete = .{ .streamed_text = false } });
+ try std.testing.expectEqualStrings(citation_clean, aw.writer.buffered());
+ aw.clearRetainingCapacity();
+ // An interrupted/open annotation cannot swallow the next turn.
+ sink.emit(std.testing.io, .{ .text_delta = .{ .text = "tail\u{E200}cite\u{E202}unfinished" } });
+ sink.emit(std.testing.io, .{ .stream_aborted = .interrupted });
+ sink.emit(std.testing.io, .{ .text_delta = .{ .text = " next" } });
+ sink.emit(std.testing.io, .{ .stream_complete = .{ .streamed_text = false } });
+ try std.testing.expectEqualStrings("tail next", aw.writer.buffered());
+ }
+ }
+ }
+}
+
+test "citation annotations stay out of reasoning and fold replay" {
+ const main = @import("main.zig");
+ const sinks = @import("engine_sink.zig");
+ const saved_color = main.use_color;
+ const saved_json = main.json_mode;
+ const saved_hosted = sinks.hosted_frontend;
+ defer main.use_color = saved_color;
+ defer main.json_mode = saved_json;
+ defer sinks.hosted_frontend = saved_hosted;
+ main.use_color = true;
+ main.json_mode = false;
+ sinks.hosted_frontend = false;
+ for (1..citation_prose.len + 1) |width| {
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = citationAgent(&aw.writer);
+ a.show_thinking = true;
+ defer a.thinking_text.deinit(std.testing.allocator);
+ const sink = sinks.tuiSink(&a);
+ defer sink.emit(std.testing.io, .stream_finished);
+ var i: usize = 0;
+ while (i < citation_prose.len) : (i += width) {
+ sink.emit(std.testing.io, .{ .reasoning_delta = .{ .text = citation_prose[i..@min(i + width, citation_prose.len)] } });
+ }
+ try std.testing.expectEqualStrings(citation_clean, a.thinking_text.items);
+ sink.emit(std.testing.io, .thinking_fold_toggle);
+ sink.emit(std.testing.io, .thinking_fold_toggle);
+ const output = aw.writer.buffered();
+ try std.testing.expect(!@import("cite_markup.zig").contains(output));
+ try std.testing.expect(std.mem.indexOf(u8, output, "turn0") == null);
+ try std.testing.expect(std.mem.indexOf(u8, output, citation_clean) != null);
+ }
+}
+
+test "citation annotations remain intact on the structured wire" {
+ const main = @import("main.zig");
+ const saved_json = main.json_mode;
+ main.json_mode = false;
+ defer main.json_mode = saved_json;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = citationAgent(&aw.writer);
+ const sink = @import("engine_sink.zig").jsonSink(&a);
+ sink.emit(std.testing.io, .{ .reasoning_delta = .{ .text = citation_prose } });
+ sink.emit(std.testing.io, .{ .text_delta = .{ .text = citation_prose } });
+ var lines = std.mem.tokenizeScalar(u8, aw.writer.buffered(), '\n');
+ var count: usize = 0;
+ while (lines.next()) |line| {
+ const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, line, .{});
+ defer parsed.deinit();
+ try std.testing.expectEqualStrings(citation_prose, parsed.value.object.get("text").?.string);
+ count += 1;
+ }
+ try std.testing.expectEqual(@as(usize, 2), count);
+}
+
+const CompactDisplayServer = struct {
+ fn run(io: Io, server: *Io.net.Server) void {
+ const conn = server.accept(io) catch return;
+ defer conn.close(io);
+ var rbuf: [8192]u8 = undefined;
+ var reader = Io.net.Stream.Reader.init(conn, io, &rbuf);
+ var remaining: usize = 0;
+ while (true) {
+ const line = (reader.interface.takeDelimiter('\n') catch return) orelse return;
+ if (std.mem.trim(u8, line, "\r").len == 0) break;
+ if (std.ascii.startsWithIgnoreCase(line, "content-length:"))
+ remaining = std.fmt.parseInt(usize, std.mem.trim(u8, line[15..], " \r"), 10) catch return;
+ }
+ while (remaining > 0) : (remaining -= 1) _ = reader.interface.takeByte() catch return;
+ var wbuf: [4096]u8 = undefined;
+ var writer = Io.net.Stream.Writer.init(conn, io, &wbuf);
+ writer.interface.writeAll("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n" ++
+ "data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"compaction\",\"encrypted_content\":\"opaque\"}}\n\n" ++
+ "data: {\"type\":\"response.output_text.delta\",\"delta\":\"Previous \"}\n\n" ++
+ "data: {\"type\":\"response.output_text.delta\",\"delta\":\"answer.\"}\n\n" ++
+ "data: {\"type\":\"response.output_item.done\",\"item\":{\"type\":\"message\",\"role\":\"assistant\",\"content\":[{\"type\":\"output_text\",\"text\":\"Previous answer.\"}]}}\n\n" ++
+ "data: {\"type\":\"response.completed\",\"response\":{\"status\":\"completed\",\"output\":[]}}\n\n") catch return;
+ writer.interface.flush() catch {};
+ }
+};
+
+test "manual compaction never paints the quiet post-compaction answer" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ // The live spinner owns stdout, which is Zig's test-control stream.
+ const animation = @import("anim.zig");
+ const saved_animation = animation.g_anim_off;
+ animation.g_anim_off = true;
+ defer animation.g_anim_off = saved_animation;
+ const main = @import("main.zig");
+ const sinks = @import("engine_sink.zig");
+ const saved_color = main.use_color;
+ const saved_json = main.json_mode;
+ const saved_hosted = sinks.hosted_frontend;
+ defer main.use_color = saved_color;
+ defer main.json_mode = saved_json;
+ defer sinks.hosted_frontend = saved_hosted;
+ main.json_mode = false;
+ sinks.hosted_frontend = false;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ for ([_]bool{ false, true }) |color| {
+ main.use_color = color;
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var addr = try Io.net.IpAddress.parseLiteral("127.0.0.1:0");
+ var server = try Io.net.IpAddress.listen(&addr, io, .{});
+ defer server.deinit(io);
+ var fut = io.async(CompactDisplayServer.run, .{ io, &server });
+ defer _ = fut.cancel(io);
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+ var aw: Io.Writer.Allocating = .init(gpa);
+ defer aw.deinit();
+ var a = citationAgent(&aw.writer);
+ a.arena = arena;
+ a.client = &client;
+ a.sys_normal = "";
+ a.provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = try std.fmt.allocPrint(arena, "http://127.0.0.1:{d}/responses", .{server.socket.address.getPort()}), .api_key = "test", .model = "test", .context = 100_000 };
+ a.messages = try @import("agent_compact_test_support.zig").msg1(arena, "user", "Earlier task");
+ defer @import("agent_render.zig").deinitMarkdown(&a);
+ const sink = sinks.tuiSink(&a);
+ sink.emit(io, .{ .text_delta = .{ .text = "Previous answer." } });
+ sink.emit(io, .{ .stream_complete = .{ .streamed_text = false } });
+ aw.clearRetainingCapacity();
+ var keys: Keys = .{ .values = @splat("test") };
+ try handleCommand(&a, &keys, arena, "/compact", &aw.writer);
+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "Previous answer.") == null);
+ try std.testing.expectEqual(@as(usize, 1), a.messages.items.len);
+ try std.testing.expectEqualStrings("compaction", a.messages.items[0].object.get("type").?.string);
+ try std.testing.expect(!a.stream_quiet and !a.compaction_request and !a.server_compaction_request);
+ aw.clearRetainingCapacity();
+ sink.emit(io, .{ .text_delta = .{ .text = "Next answer." } });
+ sink.emit(io, .{ .stream_complete = .{ .streamed_text = false } });
+ try std.testing.expectEqualStrings("Next answer.", aw.written());
+ }
+}
diff --git a/src/peer_inbox.zig b/src/peer_inbox.zig
index 5ac8ae76..12d7b8bb 100644
--- a/src/peer_inbox.zig
+++ b/src/peer_inbox.zig
@@ -20,14 +20,11 @@ const Owner = worktree_lease.Owner;
/// room still has them on disk.
pub const inbox_cap: usize = 8;
-const from_cap: usize = 48;
-const text_cap: usize = 200;
+const storage = if (@import("builtin").is_test) std.testing.allocator else std.heap.page_allocator;
const Parked = struct {
- from: [from_cap]u8 = undefined,
- from_len: u8 = 0,
- text: [text_cap]u8 = undefined,
- text_len: u8 = 0,
+ bytes: []u8,
+ from_len: usize,
dm: bool = false,
device: bool = false,
};
@@ -35,10 +32,13 @@ const Parked = struct {
var g_items: [inbox_cap]Parked = undefined;
var g_head: usize = 0;
var g_len: usize = 0;
+var g_dropped: usize = 0;
pub fn clear() void {
+ for (0..g_len) |i| storage.free(itemAt(i).bytes);
g_head = 0;
g_len = 0;
+ g_dropped = 0;
}
pub fn resetForTest() void {
@@ -49,28 +49,40 @@ pub fn unread() usize {
return g_len;
}
-fn copyInto(dest: []u8, src: []const u8) u8 {
- const n = @min(dest.len, src.len);
- @memcpy(dest[0..n], src[0..n]);
- return @intCast(n);
+pub fn dropped() usize {
+ return g_dropped;
+}
+
+pub fn restoreDropped(count: u64) void {
+ g_dropped +|= std.math.cast(usize, count) orelse std.math.maxInt(usize);
}
fn parkOne(from: []const u8, text: []const u8, dm: bool, device: bool) void {
+ const size = std.math.add(usize, from.len, text.len) catch {
+ g_dropped +|= 1;
+ return;
+ };
+ const bytes = storage.alloc(u8, size) catch {
+ g_dropped +|= 1;
+ return;
+ };
+ @memcpy(bytes[0..from.len], from);
+ @memcpy(bytes[from.len..], text);
if (g_len == inbox_cap) {
+ storage.free(itemAt(0).bytes);
g_head = (g_head + 1) % inbox_cap;
g_len -= 1;
+ g_dropped +|= 1;
}
const i = (g_head + g_len) % inbox_cap;
- var item: Parked = .{ .dm = dm, .device = device };
- item.from_len = copyInto(&item.from, from);
- item.text_len = copyInto(&item.text, peer_context.clip(text, text_cap));
- g_items[i] = item;
+ g_items[i] = .{ .bytes = bytes, .from_len = from.len, .dm = dm, .device = device };
g_len += 1;
}
/// Copy heard room/device lines into the ring. Returns how many we parked
/// (overflow still counts as parked — the newest stay). Pointers are copied
-/// into static buffers because the drain's arena may reset next step.
+/// into owned storage because the drain's arena may reset next step.
+/// The ring bounds the message count, not each message's meaning.
pub fn parkHeard(local: []const Message, device: []const Message) usize {
var n: usize = 0;
for (local) |m| {
@@ -89,11 +101,11 @@ fn itemAt(i: usize) *const Parked {
}
fn fromSlice(p: *const Parked) []const u8 {
- return p.from[0..p.from_len];
+ return p.bytes[0..p.from_len];
}
fn textSlice(p: *const Parked) []const u8 {
- return p.text[0..p.text_len];
+ return p.bytes[p.from_len..];
}
/// One-line history wake. Cheap on purpose: the bodies wait in the ring.
@@ -104,40 +116,60 @@ pub fn formatWake(arena: Allocator) []const u8 {
// how to read them, but must not read as a command that displaces the
// user's actual request on a trivial turn. Prefix stays "[peer]" — every
// compact/peek path detects injects by prefix, not by this wording.
- if (g_len == 0) return "[peer] 0 unread — nothing waiting; no inbox read needed";
- const first = fromSlice(itemAt(0));
+ if (g_len == 0 and g_dropped == 0) return "[peer] 0 unread — nothing waiting; no inbox read needed";
+ const first = if (g_len > 0) fromSlice(itemAt(0)) else "";
+ var shown_len = @min(first.len, 48);
+ while (shown_len > 0 and shown_len < first.len and first[shown_len] & 0xc0 == 0x80) shown_len -= 1;
var extra: usize = 0;
- var i: usize = 1;
- while (i < g_len) : (i += 1) {
- if (!std.mem.eql(u8, fromSlice(itemAt(i)), first)) extra += 1;
+ for (1..@max(g_len, 1)) |i| {
+ var seen = false;
+ for (0..i) |j| {
+ if (std.mem.eql(u8, fromSlice(itemAt(i)), fromSlice(itemAt(j)))) {
+ seen = true;
+ break;
+ }
+ }
+ if (!seen) extra += 1;
}
- const who = if (extra == 0)
- std.fmt.allocPrint(arena, "from {s}", .{first}) catch "from a peer"
+ const who = if (g_len == 0)
+ ""
+ else if (extra == 0)
+ std.fmt.allocPrint(arena, "from {s}", .{first[0..shown_len]}) catch "from a peer"
else
- std.fmt.allocPrint(arena, "from {s} + {d} more", .{ first, extra }) catch "from peers";
- return std.fmt.allocPrint(arena, "[peer] {d} unread {s} — parked; peer_message action=inbox when relevant", .{ g_len, who }) catch "[peer] unread — peer_message action=inbox when relevant";
+ std.fmt.allocPrint(arena, "from {s} + {d} other sender(s)", .{ first[0..shown_len], extra }) catch "from peers";
+ const lost = if (g_dropped == 0) "" else std.fmt.allocPrint(arena, " · {d} not retained", .{g_dropped}) catch " · messages not retained";
+ return std.fmt.allocPrint(arena, "[peer] {d} unread {s}{s} — parked; peer_message action=inbox when relevant", .{ g_len, who, lost }) catch "[peer] unread — peer_message action=inbox when relevant";
}
-/// Read+clear. Tool result only — does not re-enter history.
+/// Read+clear only after formatting succeeds; a failed pull retains the inbox.
pub fn takeAll(arena: Allocator) []const u8 {
- if (g_len == 0) return "inbox empty";
+ if (g_len == 0 and g_dropped == 0) return "inbox empty";
+ const text = formatInbox(arena) catch return "inbox read failed — messages retained; retry action=inbox";
+ clear();
+ return text;
+}
+
+fn formatInbox(arena: Allocator) ![]const u8 {
var buf: std.ArrayList(u8) = .empty;
+ if (g_dropped > 0) {
+ const notice = try std.fmt.allocPrint(arena, "[peer inbox] {d} messages not retained (queue overflow or allocation failure); the room log still holds the originals.\n", .{g_dropped});
+ try buf.appendSlice(arena, notice);
+ }
var i: usize = 0;
while (i < g_len) : (i += 1) {
const p = itemAt(i);
const flag = if (p.device and p.dm) " · device DM" else if (p.device) " · device" else if (p.dm) " · DM" else "";
- const line = std.fmt.allocPrint(arena, "[peer message from {s}{s}]: {s}\n", .{ fromSlice(p), flag, textSlice(p) }) catch continue;
- buf.appendSlice(arena, line) catch {};
+ const line = try std.fmt.allocPrint(arena, "[peer message from {s}{s}]: {s}\n", .{ fromSlice(p), flag, textSlice(p) });
+ try buf.appendSlice(arena, line);
}
- buf.appendSlice(arena, "(inbox cleared — reply with peer_message; omit session for the room, or name one peer to DM)") catch {};
- g_head = 0;
- g_len = 0;
+ try buf.appendSlice(arena, "(inbox cleared — reply with peer_message; omit session for the room, or name one peer to DM)");
return buf.items;
}
/// Digest parked bodies so a save skips only when the mailbox is unchanged.
pub fn mixFingerprint(f: anytype) void {
f.num(g_len);
+ f.num(g_dropped);
var i: usize = 0;
while (i < g_len) : (i += 1) {
const p = itemAt(i);
@@ -242,7 +274,7 @@ test "inbox ring: park, one-line wake, overflow drops oldest, takeAll clears" {
try testing.expectEqual(@as(usize, 2), n);
try testing.expectEqual(@as(usize, 2), unread());
const wake = formatWake(a);
- try testing.expect(std.mem.startsWith(u8, wake, "[peer] 2 unread from session-aaa + 1 more"));
+ try testing.expect(std.mem.startsWith(u8, wake, "[peer] 2 unread from session-aaa + 1 other sender(s)"));
try testing.expect(std.mem.indexOf(u8, wake, "peer_message action=inbox when relevant") != null);
try testing.expect(std.mem.indexOf(u8, wake, "parked") != null);
try testing.expect(std.mem.indexOf(u8, wake, "when relevant") != null);
@@ -260,12 +292,55 @@ test "inbox ring: park, one-line wake, overflow drops oldest, takeAll clears" {
_ = parkHeard(&.{msg(from, text, "")}, &.{});
}
try testing.expectEqual(inbox_cap, unread());
+ try testing.expectEqual(@as(usize, 2), dropped());
+ try testing.expect(std.mem.indexOf(u8, formatWake(a), "2 not retained") != null);
const overflow = takeAll(a);
+ try testing.expect(std.mem.indexOf(u8, overflow, "2 messages not retained") != null);
+ try testing.expectEqual(@as(usize, 0), dropped());
try testing.expect(std.mem.indexOf(u8, overflow, "line 0") == null);
try testing.expect(std.mem.indexOf(u8, overflow, "line 1") == null);
try testing.expect(std.mem.indexOf(u8, overflow, try std.fmt.allocPrint(a, "line {d}", .{inbox_cap + 1})) != null);
}
+test "inbox full UTF-8 bodies survive the channel, parking and JSON restore" {
+ resetForTest();
+ defer resetForTest();
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var tmp = testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const prefix = try a.alloc(u8, 199);
+ @memset(prefix, 'x');
+ const text = try std.fmt.allocPrint(a, "{s}🟢\nDo not publish; wait for my handoff.\n", .{prefix});
+ try testing.expect(presence_chan.postMessage(testing.io, a, tmp.dir, "room.jsonl", .{ .from_pid = 1, .from_session = "sender", .text = text }));
+ var cursor: u64 = 0;
+ _ = parkHeard(presence_chan.readNewMessages(testing.io, a, tmp.dir, "room.jsonl", &cursor), &.{});
+ var aw: std.Io.Writer.Allocating = .init(a);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try writeJson(&s);
+ const saved = try std.json.parseFromSliceLeaky(std.json.Value, a, aw.writer.buffered(), .{});
+ restoreJson(saved);
+ try testing.expect(std.mem.indexOf(u8, takeAll(a), text) != null);
+}
+
+test "inbox wake counts distinct senders and a failed pull does not clear" {
+ resetForTest();
+ defer resetForTest();
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ _ = parkHeard(&.{ msg("first", "one", ""), msg("second", "two", ""), msg("second", "three", "") }, &.{});
+ const wake = formatWake(a);
+ try testing.expect(std.mem.indexOf(u8, wake, "+ 1 other sender(s)") != null);
+ try testing.expect(wake.len <= peer_context.inject_byte_cap);
+ var tiny: [1]u8 = undefined;
+ var fba = std.heap.FixedBufferAllocator.init(&tiny);
+ try testing.expect(std.mem.indexOf(u8, takeAll(fba.allocator()), "messages retained") != null);
+ try testing.expectEqual(@as(usize, 3), unread());
+ try testing.expect(std.mem.indexOf(u8, takeAll(a), "three") != null);
+}
+
test "formatList: one short line per peer; empty is honest" {
var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
defer arena_state.deinit();
diff --git a/src/publish_gate.zig b/src/publish_gate.zig
index 2221587a..07f0075b 100644
--- a/src/publish_gate.zig
+++ b/src/publish_gate.zig
@@ -66,6 +66,9 @@ pub fn bash(self: *Agent, cmd: []const u8) !?ExecResult {
fn mutationKey(self: *Agent, cmd: []const u8) []const u8 {
if (!artifact_claim.isClaimedMutation(cmd)) return "";
+ // Unknown shell forms do not establish a comparable branch target.
+ if (std.mem.indexOfAny(u8, cmd, ";|&`$\n\"'\\*?{}") != null or
+ std.mem.indexOf(u8, cmd, " -R") != null or std.mem.indexOf(u8, cmd, " --repo") != null) return "";
const ev = @import("pr_evidence.zig");
const c = @import("pr_command.zig").parse(self.arena, cmd) catch null;
if (c) |command| {
@@ -107,6 +110,74 @@ test "#840 conflicting gh pr create never reaches execution after an acknowledge
try std.testing.expect(std.mem.indexOf(u8, denied.text, "NOT performed") != null);
}
+test "#840 warm dispatch observes late claims, lock contention and corrupt storage" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const ar = arena_state.allocator();
+ const io = std.testing.io;
+ const path = "zig-cache/claim-dispatch-840.json";
+ const lock_path = path ++ ".lock";
+ std.Io.Dir.cwd().deleteFile(io, path) catch {};
+ defer std.Io.Dir.cwd().deleteFile(io, path) catch {};
+ defer std.Io.Dir.cwd().deleteFile(io, lock_path) catch {};
+ artifact_claim.resetForTest();
+ defer artifact_claim.resetForTest();
+ artifact_claim.setPersistPath(path);
+ artifact_claim.setTestOwner(.{ .session = "reader" });
+ _ = try artifact_claim.handleTool(ar, io, "status", "publication", "feat/a", "");
+ var agent: Agent = undefined;
+ agent.arena = ar;
+ agent.io = io;
+ // A separate writer's persisted state, without resetting the warm reader.
+ const foreign = "[{\"kind\":\"branch\",\"key\":\"feat/a\",\"session\":\"writer\",\"pid\":1,\"start_id\":0}]";
+ try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = foreign });
+ try std.testing.expect((try bash(&agent, "gh pr create --draft --head feat/a")).?.is_error);
+ try std.testing.expect(try bash(&agent, "gh pr list") == null);
+ try std.testing.expect((try bash(&agent, "gh pr create --draft --head feat/a")).?.is_error);
+ try std.testing.expect(try bash(&agent, "gh pr create --draft --head feat/b") == null);
+ for ([_][]const u8{
+ "gh issue list && gh pr create --draft --head feat/a",
+ "gh issue list; gh pr create --draft --head feat/a",
+ "gh issue list\ngh pr create --draft --head feat/a",
+ }) |cmd| try std.testing.expect((try bash(&agent, cmd)).?.is_error);
+ const held = try std.Io.Dir.cwd().createFile(io, lock_path, .{ .truncate = false, .lock = .exclusive, .lock_nonblocking = true });
+ try std.testing.expect((try bash(&agent, "gh pr create --draft --head feat/a")).?.is_error);
+ const blocked = try artifact_claim.handleTool(ar, io, "claim", "issue", "841", "");
+ try std.testing.expect(blocked.is_error);
+ held.close(io);
+ const unchanged = try std.Io.Dir.cwd().readFileAlloc(io, path, ar, .limited(4096));
+ try std.testing.expectEqualStrings(foreign, unchanged);
+ var transferred: artifact_claim.Ledger = .{};
+ try artifact_claim.loadJson(ar, &transferred, foreign);
+ _ = try artifact_claim.handoff(&transferred, ar, .branch, "feat/a", .{ .session = "writer", .pid = 1 }, .{ .session = "reader" }, 0, true);
+ try @import("credential_store.zig").replaceFile(io, std.Io.Dir.cwd(), path, try artifact_claim.persistJson(ar, &transferred), .default_file);
+ try std.testing.expect(try bash(&agent, "gh pr create --draft --head feat/a") == null);
+ artifact_claim.setTestOwner(.{ .session = "writer", .pid = 1 });
+ try std.testing.expect((try bash(&agent, "gh pr create --draft --head feat/a")).?.is_error);
+ _ = try artifact_claim.handleTool(ar, io, "claim", "issue", "840", "");
+ artifact_claim.setTestOwner(.{ .session = "reader" });
+ try std.testing.expect((try bash(&agent, "gh issue edit 840 --title x")).?.is_error);
+ try std.testing.expect(try bash(&agent, "gh issue edit 841 --title x") == null);
+ try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = "not json" });
+ try std.testing.expect((try bash(&agent, "gh pr create --draft")).?.is_error);
+ try std.testing.expect((try artifact_claim.handleTool(ar, io, "claim", "issue", "841", "")).is_error);
+}
+
+test "#840 publication branch keys are not compared with PR numbers" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ artifact_claim.resetForTest();
+ defer artifact_claim.resetForTest();
+ artifact_claim.setTestOwner(.{ .session = "owner" });
+ _ = try artifact_claim.handleTool(arena.allocator(), std.testing.io, "claim", "publication", "feat/a", "");
+ artifact_claim.setTestOwner(.{ .session = "reader" });
+ var agent: Agent = undefined;
+ agent.arena = arena.allocator();
+ agent.io = std.testing.io;
+ try std.testing.expect((try bash(&agent, "gh pr edit 123 --title x")).?.is_error);
+ try std.testing.expect(try bash(&agent, "gh pr create --draft --head feat/b") == null);
+}
+
test "#847 non-draft create with failed head is stopped before bash" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
diff --git a/src/session_peer.zig b/src/session_peer.zig
index 48abe1b4..bf9d9394 100644
--- a/src/session_peer.zig
+++ b/src/session_peer.zig
@@ -71,6 +71,8 @@ pub fn writeFields(s: *std.json.Stringify) !void {
try s.write(cur.device);
try s.objectField("peer_inbox");
try peer_inbox.writeJson(s);
+ try s.objectField("peer_inbox_dropped");
+ try s.write(peer_inbox.dropped());
}
fn u64Field(obj: std.json.ObjectMap, name: []const u8) ?u64 {
@@ -111,7 +113,8 @@ pub fn restore(root: *Agent, obj: std.json.ObjectMap) void {
presence.seekRoomsToTail(root.io, root.arena);
}
if (obj.get("peer_inbox")) |v| peer_inbox.restoreJson(v);
- if (peer_inbox.unread() > 0) injectWake(root);
+ peer_inbox.restoreDropped(u64Field(obj, "peer_inbox_dropped") orelse 0);
+ if (peer_inbox.unread() > 0 or peer_inbox.dropped() > 0) injectWake(root);
}
const testing = std.testing;
@@ -182,6 +185,49 @@ test "writeFields / restoreJson: inbox bodies survive a process restart" {
try testing.expect(std.mem.indexOf(u8, body, "your turn") != null);
}
+test "inbox resume and tool dispatch retain full bodies and overflow notice" {
+ peer_inbox.clear();
+ defer peer_inbox.clear();
+ const unattended = main_mod.unattended;
+ main_mod.unattended = false;
+ defer main_mod.unattended = unattended;
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const prefix = try a.alloc(u8, 220);
+ @memset(prefix, 'x');
+ const text = try std.fmt.allocPrint(a, "{s} — wait for my handoff", .{prefix});
+ for (0..peer_inbox.inbox_cap + 2) |_| {
+ _ = peer_inbox.parkHeard(&.{.{ .from_session = "sender", .text = text }}, &.{});
+ }
+ var aw: std.Io.Writer.Allocating = .init(a);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.beginObject();
+ try writeFields(&s);
+ try s.endObject();
+ const saved = try std.json.parseFromSliceLeaky(Value, a, aw.writer.buffered(), .{});
+ peer_inbox.clear();
+ var root: Agent = undefined;
+ root.arena = a;
+ root.io = testing.io;
+ root.messages = std.json.Array.init(a);
+ restore(&root, saved.object);
+ try testing.expectEqual(@as(usize, 2), peer_inbox.dropped());
+ try testing.expectEqual(@as(usize, 1), root.messages.items.len);
+ try testing.expect(std.mem.indexOf(u8, root.messages.items[0].object.get("content").?.string, "2 not retained") != null);
+ const call = @import("tools.zig").ToolCall{
+ .id = "inbox",
+ .name = "peer_message",
+ .input = try std.json.parseFromSliceLeaky(Value, a, "{\"action\":\"inbox\"}", .{}),
+ };
+ const result = try peer_channel.handleMessage(&root, call);
+ try testing.expect(!result.is_error);
+ try testing.expect(std.mem.indexOf(u8, result.text, text) != null);
+ try testing.expect(std.mem.indexOf(u8, result.text, "2 messages not retained") != null);
+ try testing.expectEqual(@as(usize, 0), peer_inbox.dropped());
+ try testing.expectEqual(@as(usize, 0), peer_inbox.unread());
+}
+
test "legacy session without cursor fields seeks rather than replaying (restore path)" {
// restore() with no chan_off seeks; seek is a no-op without a registry.
// What we can prove here: leftover wakes are stripped and an empty inbox