Skip to content

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

Python

Preserve canonical compaction windows and make recovery explicit

Rach Pradhan9fd6efb46394
diff --git a/docs/adr/0089-canonical-compaction-windows-survive-recovery.md b/docs/adr/0089-canonical-compaction-windows-survive-recovery.md
new file mode 100644
index 00000000..bc065ce2
--- /dev/null
+++ b/docs/adr/0089-canonical-compaction-windows-survive-recovery.md
@@ -0,0 +1,38 @@
+# 0089. Canonical compaction windows survive recovery
+
+Status: accepted 2026-09-08
+
+## Context
+
+Automatic Responses compaction permits dropping items before the latest
+in-stream compaction item. Standalone `/responses/compact` instead returns a
+canonical window: all its output items must be retained. Treating these two
+origins alike allowed later automatic pruning to discard retained items (#804).
+Local summarization also returned successful zero work when history began with
+an opaque item, preventing meaningful recovery while reporting no failure.
+
+## Decision
+
+Persist a fingerprint of the latest standalone compaction item alongside
+session history. Protect that canonical window until a distinct automatic
+compaction item supersedes it. Saves without provenance conservatively protect
+the existing window; new saves explicitly distinguish automatic state.
+
+A local summary cannot replace opaque state, wherever it appears in history.
+Near-limit recovery uses the eligible server compaction route instead. A failed
+server attempt reports failure and preserves history; it does not fall through
+to a local summary or emergency trim of opaque context. Non-OpenAI routes do
+not acquire server compaction support through this recovery path.
+
+Show `Compacting…` only around an actual compaction operation, not merely
+because a normal request enables automatic compaction. Keep detailed successful
+compaction diagnostics behind debug mode.
+
+## Consequences
+
+Canonical context survives pruning, save/resume, and REPL history handoffs.
+Legacy saves may retain more input until the next automatic compaction. A
+server outage can block further context reduction, but cannot silently discard
+opaque state or claim a successful local fallback. Regressions in
+`agent_server_compact_tests.zig` cover retained windows and loopback server
+recovery, including malformed server output.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 6eaa120a..3b7dd76b 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -99,6 +99,7 @@ record only when you need the evidence or the edge cases.
| [0086](0086-desktop-drafts-belong-to-open-chats.md) | Unsent desktop drafts and uploads belong to open chats and survive hidden panes; closing a chat disposes them. |
| [0087](0087-bounded-desktop-presentation-work.md) | Bound syntax caches and live code rendering; project saved transcripts before sending them to the renderer and measure identical desktop workloads. |
| [0088](0088-failed-children-return-partial-evidence.md) | Failed children return bounded partial evidence with error status intact, including an excerpt for workflow synthesis. |
+| [0089](0089-canonical-compaction-windows-survive-recovery.md) | Preserve standalone compaction windows across pruning and resume; opaque recovery uses the server or reports failure without discarding history. |
## When to write one
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index f33ac7d2..a2009ee2 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -71,3 +71,4 @@
{"id": "native-read-image-same-turn", "why": "Native image reads must deliver pixels on the next model request without waiting for a second user prompt.", "prompt": "Read image.png with read_file and confirm that the image arrived.", "script": [{"tool": "bash", "arguments": {"command": "python3 -c \"import base64; open('image.png','wb').write(base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII='))\""}}, {"tool": "read_file", "arguments": {"path": "image.png"}}, {"text": "Image received."}], "assert": [{"event": {"type": "tool_result", "name": "read_file", "is_error": false}}, {"request_contains": {"index": -1, "text": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII="}}, {"final_text_contains": "Image received."}], "controls_before_prompt": [{"type": "set_model", "provider": "lmstudio", "model": "mock-vision"}]}
{"id": "meta-tool-completion-status", "why": "A metadata tool must finish its announced GUI row even when its result body uses a separate presentation path.", "prompt": "Create one pending todo, then finish your response.", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "Review fixture", "status": "pending"}]}}, {"text": "The pending item is ready."}], "assert": [{"event": {"type": "tool_call", "name": "todo_write", "id": "call_1"}}, {"event": {"type": "tool_call_finished", "name": "todo_write", "id": "call_1", "is_error": false}}]}
{"id": "subagent-activity-isolated-sink", "why": "Frontendless workers must publish their streamed progress, tool identity and final report to a separate bounded activity feed without emitting child prose as parent text.", "workspace_seed": {"example.txt": "fixture content\n", "check_activity.py": "import json, pathlib\nsnapshots = [json.loads(p.read_text()) for p in pathlib.Path('.graff/live').glob('activity-*/*.json')]\nassert len(snapshots) == 1, len(snapshots)\ns = snapshots[0]\nassert s['agent']['status'] == 'completed', s['agent']\nassert s['response'] == 'Child review complete.', s['response']\nassert any(e['type'] == 'text' and 'Child is inspecting.' in e['text'] for e in s['events']), s['events']\nassert any(e['type'] == 'tool_call' and e['name'] == 'read_file' and e['text'] == 'example.txt' and e['input_key'] == 'path' for e in s['events']), s['events']\nassert any(e['type'] == 'tool_result' and 'fixture content' in e['text'] for e in s['events']), s['events']\nassert not any('Parent has finished.' in e['text'] for e in s['events'])\nprint('child-activity-verified')\n"}, "prompt": "Use one subagent to inspect example.txt, then verify its activity feed with check_activity.py.", "script": [{"tool": "subagent", "arguments": {"description": "Inspect example", "prompt": "Read example.txt and report your findings."}}, {"text": "Child is inspecting.", "tool": "read_file", "arguments": {"path": "example.txt"}}, {"text": "Child review complete."}, {"tool": "bash", "arguments": {"command": "python3 check_activity.py"}}, {"text": "Parent has finished."}], "assert": [{"event": {"type": "tool_result", "name": "bash", "text": "child-activity-verified\n"}}, {"events_at_most": {"match": {"type": "text", "text": "Child is inspecting."}, "count": 0}}, {"final_text_contains": "Parent has finished."}]}
+{"id":"opaque-compaction-is-not-success-804","why":"An unsupported local fallback must report that opaque history needs server compaction, not emit successful zero-work compaction or discard the preserved context.","args":["--resume","compact-fixture"],"workspace_seed":{".graff/sessions/compact-fixture.session.json":"{\"provider\":\"lmstudio\",\"model\":\"mock\",\"messages\":[{\"type\":\"compaction\",\"encrypted_content\":\"opaque-fixture-804\"},{\"role\":\"user\",\"content\":\"retained-context-804\"}]}"},"controls_before_prompt":[{"type":"compact"}],"prompt":"Continue using the retained context.","script":[{"text":"Retained context is available."}],"assert":[{"event":{"type":"error","message":"compaction failed: ServerCompactionRequired"}},{"events_at_most":{"match":{"type":"compact","ok":true},"count":0}},{"request_contains":{"index":0,"text":"retained-context-804"}},{"request_contains":{"index":0,"text":"opaque-fixture-804"}},{"final_text_contains":"Retained context is available."}]}
diff --git a/src/agent.zig b/src/agent.zig
index d8c91f2a..1aa0e2fe 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -201,6 +201,7 @@ pub const Agent = struct {
stream_quiet: bool = false, // mute live paint (one-shot / compact); transport still streams
compaction_request: bool = false, // the current model call is the synthetic compaction-summary request
server_compaction_request: bool = false, // force one explicit Codex in-stream compaction pass
+ compaction_window: @import("compaction_window.zig").State = .{}, // durable standalone-window provenance
responses_output_limit: ?u32 = null, // auxiliary override (title=64); compaction always uses 4096
last_request_context_overflow: bool = false, // explicit provider rejection, not an inferred meter threshold
last_request_write_failed: bool = false, // transport gave up specifically with WriteFailed this request
diff --git a/src/agent_compact.zig b/src/agent_compact.zig
index b461f834..8b4bc3c2 100644
--- a/src/agent_compact.zig
+++ b/src/agent_compact.zig
@@ -109,19 +109,14 @@ pub fn compactPrelude(self: *Agent) ?usize {
// AFTER compaction; this covers the request compaction itself makes.
self.closeCodexWs();
if (self.messages.items.len == 0) return null;
- // Opaque server blobs (xAI leftover, OpenAI compact item) are not
- // summarizable — the client model cannot see inside them.
- if (self.messages.items[0] == .object) {
- if (self.messages.items[0].object.get("type")) |t| {
- if (t == .string and std.mem.eql(u8, t.string, "compaction")) return null;
- }
- }
pinChildTask(self);
self.last_request_context_overflow = false;
return self.effectiveContextTokens();
}
pub fn compact(self: *Agent) anyerror!usize {
+ // An opaque item anywhere in history needs the server, never a local summary.
+ if (@import("compaction_window.zig").latestBlob(self.messages.items) != null) return error.ServerCompactionRequired;
const pending_tokens = compactPrelude(self) orelse {
if (!main_mod.json_mode) try self.say("nothing to compact\n", .{});
return 0;
@@ -202,6 +197,8 @@ pub fn compact(self: *Agent) anyerror!usize {
_ = dropPriorTurnReasoning(self);
_ = trimOldestToolOutputsAlloc(self, compact_arena);
+ var progress = @import("compact_status.zig").begin(self);
+ defer progress.end(self);
// The handoff summary is internal — don't stream it to the terminal.
const was_quiet = self.stream_quiet;
const was_compaction_request = self.compaction_request;
@@ -213,6 +210,7 @@ pub fn compact(self: *Agent) anyerror!usize {
defer self.compaction_request = was_compaction_request;
defer self.message_mutation_arena = was_message_mutation_arena;
const root = try self.request(null);
+ progress.end(self);
// Any complete transport response proves the previous opaque failure was
// transient/non-wedging, even when its summary text is empty or truncated.
self.compact_transport_failures = 0;
@@ -543,7 +541,9 @@ pub fn compactOrRecover(self: *Agent, trim_on_fail: bool) void {
compact_cut.resetStall(&self.compact_stall);
}
if (self.compact_pin_degraded and !trim_on_fail) return;
- if (self.compact()) |_| {
+ const has_opaque = @import("compaction_window.zig").latestBlob(self.messages.items) != null;
+ const result = if (has_opaque) server_compact.manualCompact(self) else self.compact();
+ if (result) |_| {
self.compact_transport_failures = 0;
return;
} else |err| {
@@ -560,6 +560,7 @@ pub fn compactOrRecover(self: *Agent, trim_on_fail: bool) void {
self.say("[auto-compaction failed: {t}]\n", .{err}) catch {};
},
}
+ if (has_opaque) return; // server failed: preserve its canonical window, never emergency-trim it
const repeated_opaque_overflow = repeatedOpaqueCompactionFailure(self, err);
const repeated_empty_summary = repeatedEmptySummaryFailure(self, err);
// The caller's policy is computed before compact() makes its summary
diff --git a/src/agent_server_compact.zig b/src/agent_server_compact.zig
index 859a87e6..c1ace552 100644
--- a/src/agent_server_compact.zig
+++ b/src/agent_server_compact.zig
@@ -174,7 +174,9 @@ pub fn installCompactedOutput(self: *Agent, response: std.json.Value) !usize {
if (response != .object) return error.InvalidCompactionResponse;
const output = response.object.get("output") orelse return error.InvalidCompactionResponse;
if (output != .array or output.array.items.len == 0) return error.InvalidCompactionResponse;
+ const window = try @import("compaction_window.zig").State.canonical(self.gpa, output.array.items);
try installItems(self, output.array.items);
+ self.compaction_window = window;
return output.array.items.len;
}
@@ -199,6 +201,7 @@ pub fn installInStreamCompaction(self: *Agent, response: std.json.ObjectMap) !us
}
const k = compact_idx orelse return error.MissingCompactionItem;
try installItems(self, output.array.items[k .. k + 1]); // discard any quiet post-blob reply
+ self.compaction_window = .{};
return payload_len;
}
@@ -219,7 +222,7 @@ fn compactStandalone(self: *Agent) !usize {
if (self.tracer) |tr| tr.note("server_compact_error", response_body[0..@min(response_body.len, 400)]);
return err;
};
- if (!main_mod.json_mode) try self.say("[OpenAI compacted context into {d} canonical item(s)]\n", .{items});
+ if (!main_mod.json_mode and @import("repl.zig").g_debug) try self.say("[OpenAI compacted context into {d} canonical item(s)]\n", .{items});
return response_body.len;
}
@@ -255,12 +258,16 @@ fn compactInStream(self: *Agent) !usize {
const response = try self.request(null);
const payload_len = try installInStreamCompaction(self, response);
self.closeCodexWs();
- if (!main_mod.json_mode) try self.say("[OpenAI compacted context into server state]\n", .{});
+ if (!main_mod.json_mode and @import("repl.zig").g_debug) try self.say("[OpenAI compacted context into server state]\n", .{});
return payload_len;
}
fn fallbackLocal(self: *Agent, err: anyerror) anyerror!usize {
if (err == error.Interrupted or err == error.OutOfMemory) return err;
+ if (@import("compaction_window.zig").latestBlob(self.messages.items) != null) {
+ if (self.tracer) |tr| tr.note("server_compact_failed", @errorName(err));
+ return err; // local summaries cannot replace opaque state; caller reports the failure
+ }
if (self.tracer) |tr| tr.note("server_compact_fallback", @errorName(err));
if (!main_mod.json_mode) try self.say("[OpenAI server compaction unavailable; falling back to local summary]\n", .{});
return self.compact();
@@ -287,8 +294,7 @@ pub fn manualCompact(self: *Agent) anyerror!usize {
if (items[0] == .object) {
if (items[0].object.get("type")) |t| {
if (t == .string and std.mem.eql(u8, t.string, "compaction")) {
- if (!main_mod.json_mode) try self.say("[history already anchored on a server compaction blob]\n", .{});
- return 0;
+ return error.ServerCompactionRequired;
}
}
}
@@ -303,11 +309,18 @@ pub fn manualCompact(self: *Agent) anyerror!usize {
}
const pending_tokens = self.effectiveContextTokens();
if (!main_mod.json_mode and @import("repl.zig").g_debug) try self.say("[compacting ~{d} tokens with OpenAI…]\n", .{pending_tokens});
+ var progress = @import("compact_status.zig").begin(self);
+ defer progress.end(self);
const result = switch (route) {
.standalone => compactStandalone(self),
.in_stream => compactInStream(self),
.local => unreachable,
- } catch |err| return fallbackLocal(self, err);
+ } catch |err| {
+ progress.end(self);
+ return fallbackLocal(self, err);
+ };
+ progress.end(self);
+ if (!main_mod.json_mode) try self.say("Compacted context.\n", .{});
return result;
}
@@ -335,6 +348,7 @@ pub fn pruneIf(self: *Agent, server_arm: bool) bool {
}
const k = blob_idx orelse return false;
if (k == 0) return false; // already anchored on the blob
+ if (self.compaction_window.protects(self.gpa, items[k])) return false;
// #581: a blob after the live unresolved prompt would drop its images.
if (compact_cut.pinOpening(items)) |t| {
if (k > t) return false;
@@ -364,6 +378,7 @@ pub fn pruneIf(self: *Agent, server_arm: bool) bool {
var fresh = std.json.Array.init(self.arena);
fresh.appendSlice(items[k..]) catch return false;
self.messages = fresh;
+ self.compaction_window = .{}; // a newer in-stream blob supersedes the canonical window
// Mirror compact()'s post-install meter reset: both anchors recompute
// lazily, and the goal note died with the pruned prefix (#318).
self.last_context_tokens = 0;
@@ -371,7 +386,12 @@ pub fn pruneIf(self: *Agent, server_arm: bool) bool {
self.goal_note_fp = 0;
self.history_rewrites +%= 1; // breaks the codex chain → next request re-anchors
notePrune(dropped);
- if (!main_mod.json_mode) self.say("[server compacted context: {d} earlier item(s) now carried by the model's compaction state]\n", .{dropped}) catch {};
+ if (!main_mod.json_mode) {
+ if (@import("repl.zig").g_debug)
+ self.say("[server compacted context: {d} earlier item(s) now carried by the model's compaction state]\n", .{dropped}) catch {}
+ else
+ self.say("Compacted context.\n", .{}) catch {};
+ }
return true;
}
diff --git a/src/agent_server_compact_tests.zig b/src/agent_server_compact_tests.zig
index 015169b1..e258f3ce 100644
--- a/src/agent_server_compact_tests.zig
+++ b/src/agent_server_compact_tests.zig
@@ -39,6 +39,9 @@ fn testAgent(a: std.mem.Allocator, kind: Provider.Kind) Agent {
agent.goal_note_fp = 0;
agent.history_rewrites = 0;
agent.messages = std.json.Array.init(a);
+ agent.compaction_window = .{};
+ agent.call_kind = .root;
+ agent.stream_quiet = true;
return agent;
}
@@ -385,7 +388,7 @@ test "explicitCompact anti-thrash: a fresh blob head with little growth refuses
try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);
}
-test "manualCompact (#503): a blob-anchored history on an explicit-compact provider no-ops instead of client-summarizing the blob" {
+test "manualCompact (#804): unsupported opaque history reports failure instead of a successful no-op" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const a = arena_state.allocator();
@@ -402,7 +405,166 @@ test "manualCompact (#503): a blob-anchored history on an explicit-compact provi
try blob.put(a, "encrypted_content", .{ .string = "opaque" });
try agent.messages.append(.{ .object = blob });
try agent.messages.append(try item(a, "message", null));
- const n = try manualCompact(&agent);
- try std.testing.expectEqual(@as(usize, 0), n);
+ try std.testing.expectError(error.ServerCompactionRequired, manualCompact(&agent));
try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len); // untouched
}
+
+test "standalone compaction window survives pruning and save restore until a new blob (#804)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .responses);
+ const response = try std.json.parseFromSliceLeaky(Value, a,
+ \\{"output":[{"type":"message","role":"user","content":"retained"},{"type":"compaction","encrypted_content":"old"},{"type":"message","role":"assistant","content":"retained too"}]}
+ , .{});
+ _ = try installCompactedOutput(&agent, response);
+ const before = try std.json.Stringify.valueAlloc(a, Value{ .array = agent.messages }, .{});
+ try std.testing.expect(!pruneIf(&agent, true));
+ // Simulate the exact provenance field the session serializer/loader carries.
+ var aw: Io.Writer.Allocating = .init(a);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ try s.beginObject();
+ try agent.compaction_window.write(&s);
+ try s.endObject();
+ const saved = try std.json.parseFromSliceLeaky(Value, a, aw.written(), .{});
+ agent.compaction_window = try @import("compaction_window.zig").State.restore(a, saved.object, agent.messages.items);
+ autocompactIf(&agent, 85_000, true);
+ const after = try std.json.Stringify.valueAlloc(a, Value{ .array = agent.messages }, .{});
+ try std.testing.expectEqualStrings(before, after);
+ const body = try compactBody(&agent);
+ const request = try std.json.parseFromSliceLeaky(Value, a, body, .{});
+ const input = try std.json.Stringify.valueAlloc(a, request.object.get("input").?, .{});
+ try std.testing.expectEqualStrings(before, input);
+ // Only a distinct, newly returned in-stream blob may retire the window.
+ const next = try std.json.parseFromSliceLeaky(Value, a, "{\"type\":\"compaction\",\"encrypted_content\":\"new\"}", .{});
+ try agent.messages.append(next);
+ try agent.messages.append(try item(a, "function_call", "c1"));
+ try agent.messages.append(try item(a, "function_call_output", "c1"));
+ try std.testing.expect(pruneIf(&agent, true));
+ try std.testing.expectEqual(@as(usize, 3), agent.messages.items.len);
+ try std.testing.expect(agent.compaction_window.canonical_blob == null);
+}
+
+test "legacy saved compaction windows retain their prefix (#804)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .responses);
+ try agent.messages.append(try item(a, "message", null));
+ try agent.messages.append(try item(a, "compaction", null));
+ agent.compaction_window = try @import("compaction_window.zig").State.restore(a, .empty, agent.messages.items);
+ try std.testing.expect(!pruneIf(&agent, true));
+ try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len);
+ // An explicit null belongs to a newer save whose blob was automatic.
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(a, "canonical_compaction", .null);
+ agent.compaction_window = try @import("compaction_window.zig").State.restore(a, obj, agent.messages.items);
+ try std.testing.expect(pruneIf(&agent, true));
+}
+
+test "local compaction rejects opaque items anywhere without changing history (#804)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ for ([_][]const u8{ "compaction", "compaction_summary" }) |kind| {
+ var agent = testAgent(a, .responses);
+ try agent.messages.append(try item(a, "message", null));
+ try agent.messages.append(try item(a, kind, null));
+ try std.testing.expectError(error.ServerCompactionRequired, agent.compact());
+ try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len);
+ try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);
+ }
+}
+
+test "opaque recovery failure is visible and never emergency trims (#804)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var agent = testAgent(a, .responses); // unsupported server route, no network
+ agent.compact_pin_degraded = false;
+ agent.compact_stall = .{};
+ agent.compact_transport_failures = 1;
+ var aw: Io.Writer.Allocating = .init(a);
+ agent.out = &aw.writer;
+ const was_json = main_mod.json_mode;
+ main_mod.json_mode = false;
+ defer main_mod.json_mode = was_json;
+ try agent.messages.append(try item(a, "compaction", null));
+ for (0..20) |_| try agent.messages.append(try item(a, "message", null));
+ agent.compactOrRecover(true);
+ try std.testing.expectEqual(@as(usize, 21), agent.messages.items.len);
+ try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);
+ try std.testing.expectEqual(@as(u8, 1), agent.compact_transport_failures);
+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "auto-compaction failed: ServerCompactionRequired") != null);
+}
+
+test "near-limit opaque recovery uses the standalone server and preserves failed output (#804)" {
+ const io = std.testing.io;
+ const Server = struct {
+ fn run(io_: Io, server: *Io.net.Server, payload: []const u8, saw: *std.atomic.Value(bool)) 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);
+ const line = (reader.interface.takeDelimiter('\n') catch return) orelse return;
+ const route_ok = std.mem.startsWith(u8, line, "POST /responses/compact ");
+ var length: usize = 0;
+ while (true) {
+ const header = (reader.interface.takeDelimiter('\n') catch return) orelse return;
+ if (std.mem.eql(u8, header, "\r")) break;
+ if (std.ascii.startsWithIgnoreCase(header, "content-length:"))
+ length = std.fmt.parseInt(usize, std.mem.trim(u8, header[15..], " \r"), 10) catch return;
+ }
+ const body = reader.interface.take(length) catch return;
+ saw.store(route_ok and std.mem.indexOf(u8, body, "old-state") != null, .release);
+ var wbuf: [1024]u8 = undefined;
+ var writer = Io.net.Stream.Writer.init(conn, io_, &wbuf);
+ writer.interface.print("HTTP/1.1 200 OK\r\ncontent-length: {d}\r\nconnection: close\r\n\r\n{s}", .{ payload.len, payload }) catch return;
+ writer.interface.flush() catch {};
+ }
+ };
+ for ([_]bool{ true, false }) |success| {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = 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 saw: std.atomic.Value(bool) = .init(false);
+ var group: Io.Group = .init;
+ defer group.cancel(io);
+ const payload = if (success)
+ "{\"output\":[{\"type\":\"message\",\"role\":\"user\",\"content\":\"keep\"},{\"type\":\"compaction\",\"encrypted_content\":\"new-state\"}]}"
+ else
+ "{\"output\":[]}";
+ try group.concurrent(io, Server.run, .{ io, &server, payload, &saw });
+ var client: std.http.Client = .{ .allocator = a, .io = io };
+ defer client.deinit();
+ var agent = testAgent(a, .responses);
+ agent.io = io;
+ agent.client = &client;
+ agent.tracer = null;
+ agent.provider.id = "openai";
+ agent.provider.url = try std.fmt.allocPrint(a, "http://127.0.0.1:{d}/responses", .{server.socket.address.getPort()});
+ agent.compact_pin_degraded = false;
+ agent.compact_stall = .{};
+ agent.compact_transport_failures = 1;
+ var aw: Io.Writer.Allocating = .init(a);
+ agent.out = &aw.writer;
+ const blob = try std.json.parseFromSliceLeaky(Value, a, "{\"type\":\"compaction\",\"encrypted_content\":\"old-state\"}", .{});
+ try agent.messages.append(blob);
+ try agent.messages.append(try item(a, "message", null));
+ autocompactIf(&agent, 96_000, true);
+ try std.testing.expect(saw.load(.acquire));
+ try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len);
+ try std.testing.expectEqual(@as(u32, if (success) 1 else 0), agent.history_rewrites);
+ if (success) {
+ try std.testing.expect(!pruneIf(&agent, true));
+ try std.testing.expectEqualStrings("new-state", agent.messages.items[1].object.get("encrypted_content").?.string);
+ } else {
+ try std.testing.expectEqualStrings("old-state", agent.messages.items[0].object.get("encrypted_content").?.string);
+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "auto-compaction failed") != null);
+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "falling back to local") == null);
+ }
+ }
+}
diff --git a/src/agent_stream_render.zig b/src/agent_stream_render.zig
index fc5356f9..ef1b4899 100644
--- a/src/agent_stream_render.zig
+++ b/src/agent_stream_render.zig
@@ -28,6 +28,10 @@ const termCols = terminal.termCols;
const termRows = terminal.termRows;
const advanceThinkingRows = terminal.advanceThinkingRows;
+test {
+ _ = @import("compact_status.zig");
+}
+
pub fn spinnerTask(io: Io) void {
var i: usize = 0;
var buf: [512]u8 = undefined;
@@ -39,7 +43,11 @@ pub fn spinnerTask(io: Io) void {
}
// Clear-then-draw each frame: animations may vary in width.
w.interface.writeAll("\r\x1b[2K\x1b[?7l") catch return; // ?7l: autowrap off so a wide spinner truncates instead of wrapping in a narrow window (the "goes on and on" bug)
- anim.anims[anim.g_anim_current].frame(&w.interface, i) catch return;
+ if (@import("compact_status.zig").isActive()) {
+ w.interface.writeAll(@import("compact_status.zig").label) catch return;
+ } else {
+ anim.anims[anim.g_anim_current].frame(&w.interface, i) catch return;
+ }
w.interface.writeAll("\x1b[?7h") catch return; // restore autowrap
w.interface.flush() catch return;
i += 1;
diff --git a/src/compact_status.zig b/src/compact_status.zig
new file mode 100644
index 00000000..75a50e53
--- /dev/null
+++ b/src/compact_status.zig
@@ -0,0 +1,85 @@
+//! REPL-only compaction presentation. Call begin only after committing to real
+//! compaction (or an explicit provider compaction-start event), never merely
+//! because a request supports automatic compaction. Always defer end, including
+//! errors/cancellation. The caller retains responsibility for visible failures.
+const std = @import("std");
+const Agent = @import("agent.zig").Agent;
+const main = @import("main.zig");
+const render = @import("agent_stream_render.zig");
+const anim = @import("anim.zig");
+
+pub const label = "Compacting…";
+var active = std.atomic.Value(bool).init(false);
+
+pub fn isActive() bool {
+ return active.load(.acquire);
+}
+
+pub const Scope = struct {
+ engaged: bool = false,
+ resume_spinner: bool = false,
+
+ pub fn end(self: *Scope, agent: *Agent) void {
+ if (!self.engaged) return;
+ render.spinnerStop(agent);
+ active.store(false, .release);
+ self.engaged = false;
+ if (self.resume_spinner) render.spinnerStart(agent);
+ }
+};
+
+/// Root human output only: no GUI/JSON, child, title, or quiet-stream output.
+/// A nested begin is inert; the outer scope owns cleanup.
+pub fn begin(agent: *Agent) Scope {
+ if (!eligible(agent.sub, main.json_mode, agent.stream_quiet, agent.call_kind == .title, agent.out != null)) return .{};
+ if (active.swap(true, .acq_rel)) return .{};
+ const had_spinner = Agent.g_spin_future != null;
+ render.spinnerStop(agent);
+ // Print immediately: progress must survive disabled animation, no color,
+ // and failure to schedule the animation task. No diagnostic payload.
+ agent.say("{s}\n", .{label}) catch {};
+ if (main.use_color and !anim.g_anim_off) render.spinnerStart(agent);
+ return .{ .engaged = true, .resume_spinner = had_spinner };
+}
+
+fn eligible(sub: bool, json: bool, quiet: bool, title: bool, has_writer: bool) bool {
+ return !sub and !json and !quiet and !title and has_writer;
+}
+
+test "compact status is explicit and restricted to root REPL output" {
+ try std.testing.expect(!isActive());
+ try std.testing.expect(eligible(false, false, false, false, true));
+ try std.testing.expect(!eligible(true, false, false, false, true));
+ try std.testing.expect(!eligible(false, true, false, false, true));
+ try std.testing.expect(!eligible(false, false, true, false, true));
+ try std.testing.expect(!eligible(false, false, false, true, true));
+ try std.testing.expect(!eligible(false, false, false, false, false));
+ try std.testing.expectEqualStrings("Compacting…", label);
+}
+
+test "compact status displays progress without animation and cleans up a failed scope" {
+ const old_color = main.use_color;
+ const old_json = main.json_mode;
+ main.use_color = false;
+ main.json_mode = false;
+ defer main.use_color = old_color;
+ defer main.json_mode = old_json;
+ var output: std.Io.Writer.Allocating = .init(std.testing.allocator);
+ defer output.deinit();
+ var agent: Agent = undefined;
+ agent.sub = false;
+ agent.call_kind = .root;
+ agent.stream_quiet = false;
+ agent.out = &output.writer;
+ agent.io = std.testing.io;
+ var scope = begin(&agent);
+ defer scope.end(&agent);
+ try std.testing.expect(isActive());
+ try std.testing.expectEqualStrings("Compacting…\n", output.written());
+ var nested = begin(&agent);
+ nested.end(&agent);
+ try std.testing.expect(isActive());
+ // This is the same deferred cleanup used on cancellation/request failure.
+ scope.end(&agent);
+ try std.testing.expect(!isActive());
+}
diff --git a/src/compaction_window.zig b/src/compaction_window.zig
new file mode 100644
index 00000000..2f1307f5
--- /dev/null
+++ b/src/compaction_window.zig
@@ -0,0 +1,65 @@
+//! Provenance for canonical /responses/compact windows (#804).
+//! Keep every returned item until a NEW in-stream blob supersedes the window.
+//! Persist only a fingerprint, never another copy of the opaque payload.
+const std = @import("std");
+const Value = std.json.Value;
+const Allocator = std.mem.Allocator;
+
+pub fn latestBlob(items: []const Value) ?usize {
+ var latest: ?usize = null;
+ for (items, 0..) |item, i| {
+ if (item != .object) continue;
+ const kind = item.object.get("type") orelse continue;
+ if (kind != .string) continue;
+ if (std.mem.eql(u8, kind.string, "compaction") or std.mem.eql(u8, kind.string, "compaction_summary")) latest = i;
+ }
+ return latest;
+}
+
+fn fingerprint(a: Allocator, item: Value) ![32]u8 {
+ const bytes = try std.json.Stringify.valueAlloc(a, item, .{});
+ defer a.free(bytes);
+ var digest: [32]u8 = undefined;
+ std.crypto.hash.sha2.Sha256.hash(bytes, &digest, .{});
+ return digest;
+}
+
+pub const State = struct {
+ canonical_blob: ?[32]u8 = null,
+
+ pub fn canonical(a: Allocator, items: []const Value) !State {
+ const k = latestBlob(items) orelse return error.MissingCompactionItem;
+ return .{ .canonical_blob = try fingerprint(a, items[k]) };
+ }
+
+ pub fn protects(self: State, a: Allocator, blob: Value) bool {
+ const saved = self.canonical_blob orelse return false;
+ // Allocation failure must never turn a protected window into a cut.
+ const current = fingerprint(a, blob) catch return true;
+ return std.mem.eql(u8, &saved, &current);
+ }
+
+ pub fn write(self: State, s: *std.json.Stringify) !void {
+ try s.objectField("canonical_compaction");
+ if (self.canonical_blob) |digest| {
+ const hex = std.fmt.bytesToHex(digest, .lower);
+ try s.write(@as([]const u8, &hex));
+ } else try s.write(null);
+ }
+
+ pub fn restore(a: Allocator, obj: std.json.ObjectMap, items: []const Value) !State {
+ if (obj.get("canonical_compaction")) |value| {
+ if (value == .null) return .{};
+ if (value == .string and value.string.len == 64) {
+ var digest: [32]u8 = undefined;
+ if (std.fmt.hexToBytes(&digest, value.string)) |_| {
+ return .{ .canonical_blob = digest };
+ } else |_| {}
+ }
+ }
+ // Older saves lack provenance. Keep their existing window conservatively;
+ // a newly returned automatic blob can still supersede it normally.
+ if (latestBlob(items) == null) return .{};
+ return canonical(a, items);
+ }
+};
diff --git a/src/main.zig b/src/main.zig
index 52fa4a72..1364eb9a 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -546,7 +546,6 @@ const agent_mod = @import("agent.zig");
pub const Agent = agent_mod.Agent;
// Wire-format message construction lives in messages.zig, imported as messages_mod to avoid shadowing the `messages` params/fields.
const messages_mod = @import("messages.zig");
-/// A base64-encoded image staged by `/image`, sent with the next user turn.
const vision = @import("vision.zig"); // staged-image type, /image·/paste stagers, macOS clipboard grab
/// User-Agent for outbound Kimi Coding calls is `graff/<version>` (Moonshot forbids spoofing).
/// Device headers follow kimi-code's X-Msh-* shapes. Other providers keep the default UA.
@@ -578,6 +577,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("test_hooks.zig"); // unreached modules; their tests were silently skipped
_ = @import("agent_overflow_tests.zig"); // #414: and, through it, agent_overflow.zig's table tests
_ = @import("agent_server_compact.zig"); // server-side autocompact (codex Responses)
+ _ = @import("compact_status.zig");
_ = @import("agent_request_search_tests.zig");
_ = @import("agent_ws_steer.zig"); // gpt-6-astra response.steer
_ = @import("tui_acp_updates.zig");
diff --git a/src/repl_compact.zig b/src/repl_compact.zig
index 734b19ac..5f9ecc2e 100644
--- a/src/repl_compact.zig
+++ b/src/repl_compact.zig
@@ -72,6 +72,7 @@ pub fn replCompactCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl
if (c.convo) |cv| {
agent.scratch_arena = &scratch_state;
agent.messages = cv.list().*;
+ agent.compaction_window = cv.compaction_window;
} else for (history) |t| {
const role = switch (t.role) {
.user => "user",
@@ -89,6 +90,7 @@ pub fn replCompactCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl
// on a failure that leaves history untouched — is the session's state now.
defer if (c.convo) |cv| {
cv.list().* = agent.messages;
+ cv.compaction_window = agent.compaction_window;
};
const n = agent.manualCompact() catch |err| {
out.note = (switch (err) {
diff --git a/src/repl_convo.zig b/src/repl_convo.zig
index d9596cc7..184c6456 100644
--- a/src/repl_convo.zig
+++ b/src/repl_convo.zig
@@ -32,6 +32,7 @@ pub const Conversation = struct {
/// has settled at its final address.
messages: std.json.Array = undefined,
live: bool = false,
+ compaction_window: @import("compaction_window.zig").State = .{},
pub fn init(gpa: Allocator) Conversation {
return .{ .arena = std.heap.ArenaAllocator.init(gpa) };
@@ -72,6 +73,7 @@ pub const Conversation = struct {
pub fn reset(self: *Conversation) void {
_ = self.arena.reset(.free_all);
self.live = false;
+ self.compaction_window = .{};
}
/// `/rewind`: drop back to just before the last human prompt, so the
@@ -125,6 +127,7 @@ pub const Conversation = struct {
pub fn replace(self: *Conversation, rewritten: []const Value) !void {
const msgs = self.list();
msgs.clearRetainingCapacity();
+ self.compaction_window = .{};
try msgs.appendSlice(rewritten);
}
};
@@ -223,11 +226,14 @@ test "reset clears the conversation; rewind drops back to before the last prompt
try convo.adopt(&.{ .{ .role = .user, .text = "first" }, .{ .role = .assistant, .text = "reply" }, .{ .role = .user, .text = "second" } });
try testing.expectEqual(@as(usize, 3), convo.len());
+ convo.compaction_window = .{ .canonical_blob = @as([32]u8, @splat(7)) };
convo.rewind();
+ try testing.expectEqual(@as(?[32]u8, @as([32]u8, @splat(7))), convo.compaction_window.canonical_blob);
try testing.expectEqual(@as(usize, 2), convo.len());
try testing.expectEqualStrings("assistant", roleOf(convo.list().items[1]));
convo.reset();
+ try testing.expectEqual(@as(?[32]u8, null), convo.compaction_window.canonical_blob);
try testing.expectEqual(@as(usize, 0), convo.len());
// Usable again after a reset — the arena was freed, not poisoned.
try convo.adopt(&.{.{ .role = .user, .text = "fresh" }});
diff --git a/src/repl_turn.zig b/src/repl_turn.zig
index cef699bb..89210aa3 100644
--- a/src/repl_turn.zig
+++ b/src/repl_turn.zig
@@ -157,6 +157,7 @@ fn borrowHistory(c: *ReplCtx, agent: *Agent, history: []const repl.Turn, arena:
try cv.adopt(history);
try promoteTailImages(agent, cv, history);
agent.messages = cv.list().*;
+ agent.compaction_window = cv.compaction_window;
// Transient parse garbage goes here instead of the session arena (#124).
agent.scratch_arena = scratch;
}
@@ -183,7 +184,10 @@ fn promoteTailImages(agent: *Agent, cv: anytype, history: []const repl.Turn) !vo
/// and every tool_use/tool_result pair to the borrowed list, and a managed
/// ArrayList is a VALUE — not copying it back would drop the whole turn.
fn returnHistory(c: *ReplCtx, agent: *Agent) void {
- if (c.convo) |cv| cv.list().* = agent.messages;
+ if (c.convo) |cv| {
+ cv.list().* = agent.messages;
+ cv.compaction_window = agent.compaction_window;
+ }
const root = c.root orelse return;
root.strict = agent.strict;
root.ultracode_mode = agent.ultracode_mode;
@@ -414,6 +418,7 @@ test "turn 2 carries turn 1's tool_use and tool_result; /clear drops both (#551)
var agent = try turnAgent(&c, gpa, convo.alloc(), .{}, &discarding.writer, &approvals);
defer agent.tools_used.deinit(gpa);
try borrowHistory(&c, &agent, &.{.{ .role = .user, .text = "count the files" }}, convo.alloc(), &scratch);
+ agent.compaction_window = .{ .canonical_blob = @as([32]u8, @splat(7)) };
try fakeToolTurn(&agent, "call-1", "ls | wc -l", "42");
try agent.messages.append(try textMessage(agent.arena, "assistant", "there are 42"));
returnHistory(&c, &agent);
@@ -430,6 +435,7 @@ test "turn 2 carries turn 1's tool_use and tool_result; /clear drops both (#551)
.{ .role = .assistant, .text = "there are 42" },
.{ .role = .user, .text = "and how many are zig?" },
}, convo.alloc(), &scratch);
+ try testing.expectEqual(@as(?[32]u8, @as([32]u8, @splat(7))), agent.compaction_window.canonical_blob);
const body = try agent.buildBody(tools, false, true, true);
defer gpa.free(body);
try testing.expect(std.mem.indexOf(u8, body, "tool_use") != null);
diff --git a/src/session.zig b/src/session.zig
index 90bcbb76..f9935929 100644
--- a/src/session.zig
+++ b/src/session.zig
@@ -332,6 +332,7 @@ fn queueSave(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !u64
// this component with today's prompt/tool-schema estimate.
try s.objectField("context_local_tokens");
try s.write(@min(context_estimate.local, @as(u64, std.math.maxInt(i64))));
+ try root.compaction_window.write(&s);
// #330: the --json protocol sequence high-water mark. A REPLACEMENT graff
// resuming this session continues the numbering from here instead of
// reissuing ids the supervisor has already read off the event log.
@@ -479,7 +480,9 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8
// default. Materialize that catalog before rebasing its saved context
// meter, and keep every still-unused format lazy.
try root.ensureRootTools(root.provider.kind);
+ const compaction_window = try @import("compaction_window.zig").State.restore(arena, obj, msgs.items);
root.messages = msgs;
+ root.compaction_window = compaction_window;
// Repair histories written by older builds where a Responses
// `function_call_output.output` was persisted as a byte array instead of a
// string. The Responses API rejects that ("input[N].output[0]: expected an
diff --git a/src/session_run.zig b/src/session_run.zig
index 9024c3b6..35a5296a 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -89,6 +89,7 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent
var convo = repl_glue.Conversation.init(gpa);
defer convo.deinit();
try convo.seed(root.messages);
+ convo.compaction_window = root.compaction_window;
var repl_ctx = repl_glue.ReplCtx{
.io = io,
.client = client,
@@ -121,6 +122,7 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent
// same way. TTY `graff repl` is the TUI and keeps the restore tail clean.
pricing.printUsageFooter(io);
root.messages = try convo.cloneInto(root.arena);
+ root.compaction_window = convo.compaction_window;
return true;
}
diff --git a/src/tui_session.zig b/src/tui_session.zig
index aa9bc1e2..6f34543f 100644
--- a/src/tui_session.zig
+++ b/src/tui_session.zig
@@ -12,10 +12,12 @@ const tui = @import("tui");
pub fn seed(convo: *repl_glue.Conversation, root: *agent_mod.Agent) !void {
try convo.seed(root.messages);
+ convo.compaction_window = root.compaction_window;
}
pub fn syncRoot(convo: *repl_glue.Conversation, root: *agent_mod.Agent) !void {
root.messages = try convo.cloneInto(root.arena);
+ root.compaction_window = convo.compaction_window;
}
pub fn visibleTurns(arena: Allocator, messages: std.json.Array) ![]tui.Turn {