graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
compaction: compact on the Codegraff gateway when logged in
justrach1b51c7eb6614
diff --git a/docs/adr/0252-hosted-compaction-with-a-codegraff-login.md b/docs/adr/0252-hosted-compaction-with-a-codegraff-login.mdnew file mode 100644index 00000000..b75cfdf1--- /dev/null+++ b/docs/adr/0252-hosted-compaction-with-a-codegraff-login.md@@ -0,0 +1,74 @@+# 0252. Hosted compaction with a Codegraff login++Status: accepted 2026-10-04.++## Context++graff's own compaction asks the session's model for a summary and restarts+history from it (agent_compact.zig). A summary is lossy in the worst place:+exact error text, file paths and the constraints a task depends on are what a+paraphrase drops, and nothing records what was dropped.++The Codegraff gateway now offers `POST /v1/compact`. It takes a neutral+transcript (`role`, `text`, `toolUses`, `toolResults`) and answers with a+decision per tool call — keep it, drop only its result's bulk, or drop the+call and its result — made by a decision model. Text is never rewritten, the+first message and the newest few are pinned, and every decision comes back+with the reply. Pruning alone cannot shrink a session forever, so in `hybrid`+mode, when pruning frees too little, the gateway also summarizes the middle+of the transcript and splices that summary in. The call is billed to the+account like any other request and returns a settled charge receipt.++## Decision++- With a persisted Codegraff login, `compact()` tries the gateway first, with+ `model: "clef"` and `mode: "hybrid"`. The only credential is the persisted+ login (the same one the effort picker uses), never the chat provider's key.+ Without a login nothing changes.+- The reply is applied to graff's own wire-format history by call id+ (gateway_compact_wire.zig). Nothing is rebuilt from the neutral copy, so+ reasoning items, images and provider metadata stay as they were.+ - A trimmed result keeps its head and tail plus the #409 pointer to the full+ output when the session is durable.+ - A dropped call goes with its result only in earlier turns. In the live+ turn the call stays and only its result shrinks, so that turn's reasoning,+ thinking blocks and signatures stay paired with every call they reference.+ Earlier turns' reasoning items go, as in the local path (#174).+ - A spliced summary becomes graff's usual handoff note between the pinned+ first message and the kept tail. The cut moves back over any call a kept+ result answers, and an unresolved turn's opening prompt stays verbatim+ (#581).+- The reply is checked before it is installed: the transcript it returns has+ to be exactly what its decisions imply, the new history may not pair calls+ and results worse than the old one, and it has to free at least a tenth of+ the estimated context. Anything else is a failure.+- Refusals and failures:+ - A refused key (401/403) turns hosted compaction off for the session and+ compaction stays local.+ - Exhausted credits (`insufficient_credits`, `key_budget_exceeded`) turn it+ off for the session as well. Compaction continues with the local summary,+ and graff says once that it is local and lossy until the account is topped+ up. `gateway_compact.on_credits_exhausted = .off` stops compaction instead.+ - Any other failure — a 5xx, a timeout, a reply that does not check out —+ falls back to the local summary for that compaction only and is noted in+ the trace.+- The settled charge is added to the session's cost tally; an unsettled reply+ counts its tokens as unpriced.+- Opaque provider state (Responses `compaction` items) still needs the+ provider's own compaction: `compact()` refuses before the gateway is asked.+ Routes that compact in-stream keep doing so; the gateway replaces the local+ summary wherever graff would have written one, including their near-the-wall+ fallback.+- `GRAFF_HOSTED_COMPACT=0` keeps compaction local. `GRAFF_COMPACT_URL` and+ `GRAFF_COMPACT_MODEL` point it at another gateway or decision model.++## Consequences++Signed-in sessions send their transcript, tool output included, to the+Codegraff gateway each time they compact. Each compaction costs a small+billed request and a round trip, which buys decisions that can be audited and+results that are trimmed rather than paraphrased. A gateway outage or an empty+balance never stops a session; it costs that compaction its quality.+Revisit when the endpoint accepts graff's own pin (the hybrid summary keeps a+fixed number of newest messages today), or when live-turn calls can be+dropped safely on a given wire.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex a0a0ea29..74bae277 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -278,6 +278,7 @@ record only when you need the evidence or the edge cases.| [0249](0249-a-spec-task-ends-at-its-own-tests.md) | The work note no longer says a green public test is not the whole spec: it made the model write an extra verification script on every spec task without changing the pass rate. Spec tasks end at their own tests; the lean note is unchanged. Refines 0024. || [0250](0250-pr-publication-is-not-gated.md) | PR publication is not gated: no local-check, head-CI or claim-review preflight and no completion obligation; drafts complete like any task. Artifact claims and disclosure policy are unchanged. Supersedes 0120, 0123, 0126, 0133 and parts of 0100/0104. || [0251](0251-tool-results-inline-up-to-64-kib.md) | Tool results inline up to 64 KiB (was 16 KiB); `effectiveThreshold` still clamps to half the context window, so small windows are unchanged. The codedb small-read exemption follows the same number. |+| [0252](0252-hosted-compaction-with-a-codegraff-login.md) | With a Codegraff login, `compact()` asks the gateway first: per-call keep/trim/drop decisions applied to graff's own history by call id, plus a spliced summary when pruning frees too little. Live-turn calls stay; a reply must check out and free a tenth of the context. Refused key or exhausted credits: local for the session; other failures: local for that compaction. |## When to write onediff --git a/src/agent_compact.zig b/src/agent_compact.zigindex b14c2de3..85a1e243 100644--- a/src/agent_compact.zig+++ b/src/agent_compact.zig@@ -117,6 +117,7 @@ pub fn compactPrelude(self: *Agent) ?usize {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;+ if (try @import("gateway_compact.zig").run(self)) |freed| return freed; // ADR 0252: a Codegraff login compacts on the gateway firstconst fork = @import("cache_fork.zig").begin(self); // ADR 0220: read the cached history, not rewrite itdefer @import("cache_fork.zig").end();const pending_tokens = compactPrelude(self) orelse {@@ -283,7 +284,7 @@ pub fn handoffMessage(self: *Agent, summary: []const u8, discarded: []const Valureturn handoff_note.handoff(self.arena, self, base, standing, discarded);}-fn rootHandoff(self: *Agent, summary: []const u8) ![]const u8 {+pub fn rootHandoff(self: *Agent, summary: []const u8) ![]const u8 {return std.fmt.allocPrint(self.arena,\\Context: the earlier conversation was compacted to save space.\\Summary of the earlier work:@@ -559,7 +560,7 @@ pub fn compactOrRecover(self: *Agent, trim_on_fail: bool) void {self.compact_transport_failures = 0;return; // user hit Esc mid-compaction},- error.EmptySummary, error.IncompleteSummary, error.ActivePromptPinned => {}, // compact() already explained it+ error.EmptySummary, error.IncompleteSummary, error.ActivePromptPinned, error.CompactionOff => {}, // compact() already explained itelse => {if (main_mod.json_mode)self.emit(.{ .type = "error", .message = std.fmt.allocPrint(self.arena, "auto-compaction failed: {s}", .{@errorName(err)}) catch "auto-compaction failed" })diff --git a/src/gateway_compact.zig b/src/gateway_compact.zignew file mode 100644index 00000000..7d6d0355--- /dev/null+++ b/src/gateway_compact.zig@@ -0,0 +1,312 @@+//! Hosted compaction (ADR 0252). With a persisted Codegraff login, compaction+//! runs through the gateway's POST /v1/compact before graff's own summary: a+//! decision model drops stale tool calls and results — text is never+//! rewritten — and when that frees too little the gateway splices a summary of+//! the middle in ("hybrid"). gateway_compact_wire.zig maps the history out and+//! applies the reply back onto graff's own items by call id.+//!+//! Without a login nothing changes. A refused key or exhausted credits switch+//! the hosted path off for the session (`on_credits_exhausted` decides what+//! credits do next); any other failure — a 5xx, a timeout, a reply that does+//! not check out — falls back to the local summary for that compaction only.+//! A gateway problem can cost one compaction its quality, never the session+//! its progress.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const Value = std.json.Value;++const Agent = @import("agent.zig").Agent;+const Provider = @import("provider.zig").Provider;+const main_mod = @import("main.zig");+const wire = @import("gateway_compact_wire.zig");+const compact_cut = @import("compact_cut.zig");+const tool_spill = @import("tool_spill.zig");+const pricing = @import("pricing.zig");+const acp_compaction = @import("acp_compaction.zig");++pub const endpoint = "https://gateway.codegraff.com/v1/compact";+const default_model = "clef";++/// Bytes a trimmed tool result keeps: head and tail around a gap, plus the+/// #409 pointer to the full output when the session is durable.+const stub_cap: usize = 800;+const stub_fallback = "[older tool output trimmed by compaction]";++/// A reply must free at least this share of the estimated context, or the+/// local summary runs instead: installing less would trigger compaction again+/// on the next request and pay for it again.+const min_freed_pct: u64 = 10;++pub const CreditPolicy = enum {+ /// Keep compacting with the local summary; say so once.+ local,+ /// Stop compacting for the rest of the session.+ off,+};+/// What a refusal for credits (insufficient_credits, key_budget_exceeded) does.+pub var on_credits_exhausted: CreditPolicy = .local;++const Trip = enum(u8) { none, credits, auth };++var g_mu: Io.Mutex = .init;+var g_key: []const u8 = "";+var g_url: []const u8 = endpoint;+var g_model: []const u8 = default_model;+var g_disabled = false;+var g_trip = std.atomic.Value(Trip).init(.none);+/// Bumped by every hosted compaction that installs, so `/compact` can tell+/// whether the last line is about the compaction it just asked for.+var g_seq = std.atomic.Value(u32).init(0);+var g_line_buf: [160]u8 = undefined;+var g_line_len: usize = 0;++fn isOff(v: []const u8) bool {+ const t = std.mem.trim(u8, v, " \t");+ return std.mem.eql(u8, t, "0") or std.ascii.eqlIgnoreCase(t, "off") or+ std.ascii.eqlIgnoreCase(t, "false") or std.ascii.eqlIgnoreCase(t, "no");+}++/// GRAFF_HOSTED_COMPACT=0 keeps compaction local. GRAFF_COMPACT_URL and+/// GRAFF_COMPACT_MODEL point it at another gateway or decision model.+pub fn configure(arena: Allocator, env: anytype) !void {+ g_disabled = if (env.get("GRAFF_HOSTED_COMPACT")) |v| isOff(v) else false;+ g_url = if (env.get("GRAFF_COMPACT_URL")) |v| try arena.dupe(u8, v) else endpoint;+ g_model = if (env.get("GRAFF_COMPACT_MODEL")) |v| try arena.dupe(u8, v) else default_model;+ g_trip.store(.none, .release);+}++/// The persisted Codegraff login, the only credential this endpoint takes+/// (the chat provider's key may belong to another vendor entirely). Null+/// clears it. The slice must outlive the session.+pub fn setLoginKey(io: Io, key: ?[]const u8) void {+ g_mu.lockUncancelable(io);+ defer g_mu.unlock(io);+ g_key = key orelse "";+ g_trip.store(.none, .release); // a new login gets a fresh chance+}++fn loginKey(io: Io) ?[]const u8 {+ g_mu.lockUncancelable(io);+ defer g_mu.unlock(io);+ return if (g_key.len > 0) g_key else null;+}++pub fn seq() u32 {+ return g_seq.load(.acquire);+}++/// What the latest installed hosted compaction did, copied into `out`.+pub fn lastLine(io: Io, out: []u8) []const u8 {+ g_mu.lockUncancelable(io);+ defer g_mu.unlock(io);+ const n = @min(g_line_len, out.len);+ @memcpy(out[0..n], g_line_buf[0..n]);+ return out[0..n];+}++fn setLine(io: Io, line: []const u8) void {+ g_mu.lockUncancelable(io);+ defer g_mu.unlock(io);+ g_line_len = @min(line.len, g_line_buf.len);+ @memcpy(g_line_buf[0..g_line_len], line[0..g_line_len]);+ _ = g_seq.fetchAdd(1, .acq_rel);+}++const Stubber = struct {+ note: tool_spill.Note,++ pub fn stub(self: *const Stubber, a: Allocator, full: []const u8) []const u8 {+ if (full.len <= stub_cap) return full;+ const marker = self.note.text(a, full, stub_cap);+ const body = @import("output_elide.zig").headTail(a, full, stub_cap -| (marker.len + 1)) catch return marker;+ return std.fmt.allocPrint(a, "{s}\n{s}", .{ body, marker }) catch marker;+ }+};++fn goalText(self: *const Agent) ?[]const u8 {+ const g = self.goal orelse return null;+ return if (g.status == .complete) null else g.objective;+}++/// Called first by agent_compact.compact(). Null means "not handled here" —+/// no login, the opt-out, a refusal earlier in the session, too little+/// history to decide on, or a failure — and compact() then runs the local+/// summary exactly as before.+pub fn run(self: *Agent) anyerror!?usize {+ if (g_disabled) return null;+ const key = loginKey(self.io) orelse return null;+ switch (g_trip.load(.acquire)) {+ .none => {},+ .auth => return null,+ .credits => return if (on_credits_exhausted == .off) error.CompactionOff else null,+ }+ var scratch = std.heap.ArenaAllocator.init(self.gpa);+ defer scratch.deinit();+ const a = scratch.allocator();+ const msgs = try wire.transcript(a, self.messages.items);+ // The first message and the newest few are pinned: below this the+ // endpoint has nothing to decide, and above its cap it refuses.+ if (msgs.len <= wire.recent_kept + 1 or msgs.len > wire.max_messages) return null;+ const body = try wire.request(a, msgs, g_model, goalText(self));++ self.closeCodexWs(); // the history is about to be rewritten+ @import("agent_compact.zig").pinChildTask(self);+ if (!main_mod.json_mode and @import("repl.zig").g_debug) try self.say("[compacting {d} messages on the gateway…]\n", .{msgs.len});+ var progress = @import("compact_status.zig").begin(self);+ defer progress.end(self);+ var acp_run = acp_compaction.start(!self.sub and self.call_kind != .title);+ defer acp_run.finish(.failed, null, "hosted compaction did not complete"); // no-op once finished++ const provider: Provider = .{ .id = "codegraff", .kind = .openai, .auth = .bearer, .url = g_url, .api_key = key, .model = g_model, .context = 0 };+ const posted = @import("http.zig").postWatched(self.gpa, self.io, self.client, provider, body, null);+ progress.end(self); // the spinner stops before anything below prints+ const raw = posted catch |err| switch (err) {+ error.Interrupted, error.Canceled => {+ acp_run.finish(.cancelled, null, "interrupted");+ return error.Interrupted;+ },+ error.OutOfMemory => return err,+ else => {+ pricing.g_cost.failedWithoutUsage(self.io, 1);+ return fallback(self, &acp_run, @errorName(err));+ },+ };+ defer self.gpa.free(raw);+ const root = std.json.parseFromSliceLeaky(Value, a, raw, .{ .allocate = .alloc_always }) catch {+ pricing.g_cost.failedWithoutUsage(self.io, 1);+ return fallback(self, &acp_run, "unreadable reply");+ };+ if (refusal(root)) |code| return refused(self, &acp_run, code);+ noteUsage(self.io, root);+ const reply = wire.parseReply(a, root) catch |err| switch (err) {+ error.OutOfMemory => return err,+ else => return fallback(self, &acp_run, "unexpected reply"),+ };+ const outcome = install(self, a, msgs, &reply) catch |err| switch (err) {+ error.OutOfMemory => return err,+ else => return fallback(self, &acp_run, @errorName(err)),+ };+ acp_run.finish(.completed, if (reply.summarized) reply.summary else outcome.line, null);+ if (!main_mod.json_mode and @import("repl.zig").g_debug) try self.say("[{s}]\n", .{outcome.line});+ return outcome.freed;+}++fn fallback(self: *Agent, acp_run: *acp_compaction.Run, reason: []const u8) ?usize {+ if (self.tracer) |tr| tr.note("hosted_compact_fallback", reason);+ var buf: [128]u8 = undefined;+ const why = std.fmt.bufPrint(&buf, "hosted compaction unavailable ({s}); compacting locally", .{reason}) catch "hosted compaction unavailable; compacting locally";+ acp_run.finish(.failed, null, why);+ if (!main_mod.json_mode) self.say("[{s}]\n", .{why}) catch {};+ return null;+}++/// The gateway's error envelope code, if the reply is a refusal.+pub fn refusal(root: Value) ?[]const u8 {+ if (root != .object) return null;+ const e = root.object.get("error") orelse return null;+ if (e != .object) return "error";+ const code = e.object.get("code") orelse e.object.get("type") orelse return "error";+ return if (code == .string) code.string else "error";+}++fn refused(self: *Agent, acp_run: *acp_compaction.Run, code: []const u8) anyerror!?usize {+ const eql = std.mem.eql;+ const credits = eql(u8, code, "insufficient_credits") or eql(u8, code, "key_budget_exceeded");+ const auth = eql(u8, code, "invalid_api_key") or eql(u8, code, "missing_api_key") or eql(u8, code, "insufficient_scope");+ if (!credits and !auth) return fallback(self, acp_run, code);+ g_trip.store(if (credits) .credits else .auth, .release);+ if (self.tracer) |tr| tr.note("hosted_compact_off", code);+ const off = credits and on_credits_exhausted == .off;+ const why = if (off)+ "compaction is off: Codegraff credits are used up — top up to turn it back on"+ else if (credits)+ "Codegraff credits are used up: compacting locally (a lossy summary) until you top up"+ else+ "hosted compaction unavailable (Codegraff key refused); compacting locally";+ acp_run.finish(.failed, null, why);+ if (!main_mod.json_mode) self.say("[{s}]\n", .{why}) catch {};+ return if (off) error.CompactionOff else null;+}++fn noteUsage(io: Io, root: Value) void {+ const usage = if (root == .object) root.object.get("usage") orelse Value.null else Value.null;+ if (usage == .object) {+ const input = count(usage.object.get("input_tokens"));+ const output = count(usage.object.get("output_tokens"));+ if (input != null and output != null) {+ if (@import("pricing_gateway.zig").settledCharge(root)) |charge|+ pricing.g_cost.addSettled(io, input.?, output.?, charge)+ else+ pricing.g_cost.addForProvider(io, .unpriced, "codegraff", g_model, input.?, 0, 0, output.?);+ return;+ }+ }+ pricing.g_cost.missingUsage(io);+}++fn count(v: ?Value) ?i64 {+ const n = v orelse return null;+ return if (n == .integer and n.integer >= 0) n.integer else null;+}++fn estimate(items: []const Value) u64 {+ var total: u64 = 0;+ for (items) |m| total +|= @import("context_tokens.zig").estimatedTokens(m);+ return total;+}++const Outcome = struct { freed: usize, line: []const u8 };++fn install(self: *Agent, a: Allocator, msgs: []const wire.Msg, reply: *const wire.Reply) !Outcome {+ const items = self.messages.items;+ const p = try wire.plan(a, msgs, reply, compact_cut.pinOpening(items));+ var note: ?Value = null;+ if (reply.summarized) {+ const base = try @import("agent_compact.zig").rootHandoff(self, reply.summary);+ const standing = try @import("goal_flow.zig").compactionSnapshot(self.arena, self);+ const discarded = try wire.replaced(a, items, msgs, p);+ const text = try @import("compact_handoff_note.zig").handoff(self.arena, self, base, standing, discarded);+ note = try @import("messages.zig").userNote(self.arena, self.provider.kind, text);+ }+ const stubber: Stubber = .{ .note = .{ .fallback = stub_fallback, .session = tool_spill.sessionFor(self.sub, self.session_name) } };+ // Earlier turns lose dropped calls outright; the live turn keeps them.+ const removable = compact_cut.turnOpeningUserIndex(items) orelse 0;+ const fresh = try wire.apply(self.arena, items, msgs, p, &reply.decisions, removable, note, &stubber);+ try wire.checkPairs(a, items, fresh.items);+ const before = estimate(items);+ const after = estimate(fresh.items);+ if (after * 100 > before * (100 - min_freed_pct)) return error.TooLittleFreed;+ const line = try outcomeLine(self.arena, reply, p);++ self.messages = fresh;+ self.compact_summary_failures = 0;+ self.last_context_tokens = 0;+ self.context_local_tokens = 0;+ if (reply.summarized) self.goal_note_fp = 0; // the injected goal note may be in the summarized middle (#318)+ self.history_rewrites +%= 1; // trimmed results may hold pasted state, e.g. a todo_write render (#318)+ @import("prompts.zig").noteSessionCompacted(self, self.arena);+ @import("hot_context.zig").afterCompact(self);+ const counters = @import("agent_server_compact.zig");+ if (reply.summarized) counters.session_summaries +|= 1 else counters.session_prunes +|= 1;+ setLine(self.io, line);+ if (self.tracer) |tr| tr.note("hosted_compact", line);+ return .{ .freed = @intCast(before - after), .line = line };+}++fn outcomeLine(a: Allocator, reply: *const wire.Reply, p: wire.Plan) ![]const u8 {+ var trimmed: usize = 0;+ var dropped: usize = 0;+ var it = reply.decisions.valueIterator();+ while (it.next()) |action| switch (action.*) {+ .drop_result => trimmed += 1,+ .drop_call => dropped += 1,+ .keep => {},+ };+ if (!reply.summarized)+ return std.fmt.allocPrint(a, "compacted on the gateway: trimmed {d} tool results, dropped {d} calls", .{ trimmed, dropped });+ var summarized: usize = 0;+ for (p.keep) |k| summarized += @intFromBool(!k);+ return std.fmt.allocPrint(a, "compacted on the gateway: summarized {d} earlier messages, trimmed {d} tool results, dropped {d} calls", .{ summarized, trimmed, dropped });+}diff --git a/src/gateway_compact_tests.zig b/src/gateway_compact_tests.zignew file mode 100644index 00000000..002f6709--- /dev/null+++ b/src/gateway_compact_tests.zig@@ -0,0 +1,318 @@+//! Hosted compaction (ADR 0252) on fixtures: every wire format maps to the+//! gateway's neutral transcript, and a reply applies back onto the native+//! items — trimmed results, dropped calls, a spliced summary — without ever+//! leaving a result without its call.++const std = @import("std");+const Allocator = std.mem.Allocator;+const Value = std.json.Value;+const wire = @import("gateway_compact_wire.zig");+const hosted = @import("gateway_compact.zig");++const TestStub = struct {+ pub fn stub(_: *const TestStub, a: Allocator, full: []const u8) []const u8 {+ if (full.len <= 8) return full;+ return std.fmt.allocPrint(a, "{s}…[trimmed]", .{full[0..8]}) catch full;+ }+};++fn parse(a: Allocator, raw: []const u8) ![]const Value {+ const v = try std.json.parseFromSliceLeaky(Value, a, raw, .{ .allocate = .alloc_always });+ return v.array.items;+}++fn field(v: Value, key: []const u8) Value {+ return v.object.get(key) orelse .null;+}++test "ADR 0252: Anthropic history folds into neutral messages with calls, results and errors" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ const items = try parse(a,+ \\[{"role":"user","content":"Fix the failing test"},+ \\ {"role":"assistant","content":[{"type":"thinking","thinking":"plan","signature":"s"},{"type":"text","text":"Reading it"},{"type":"tool_use","id":"t1","name":"read_file","input":{"path":"a.zig"}}]},+ \\ {"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"file body"}]},+ \\ {"role":"assistant","content":[{"type":"tool_use","id":"t2","name":"bash","input":{"cmd":"zig build test"}}]},+ \\ {"role":"user","content":[{"type":"tool_result","tool_use_id":"t2","content":[{"type":"text","text":"1 failed"}],"is_error":true},{"type":"text","text":"also check b"}]},+ \\ {"role":"assistant","content":"Done"}]+ );+ const msgs = try wire.transcript(a, items);+ try std.testing.expectEqual(@as(usize, 6), msgs.len);+ try std.testing.expectEqual(wire.Role.assistant, msgs[1].role);+ try std.testing.expectEqualStrings("Reading it", msgs[1].text);+ try std.testing.expectEqualStrings("t1", msgs[1].uses[0].id);+ try std.testing.expectEqualStrings("a.zig", field(msgs[1].uses[0].input, "path").string);+ try std.testing.expectEqualStrings("file body", msgs[2].results[0].text);+ try std.testing.expectEqualStrings("also check b", msgs[4].text);+ try std.testing.expectEqualStrings("1 failed", msgs[4].results[0].text);+ try std.testing.expect(msgs[4].results[0].is_error);+ for (msgs, 0..) |m, i| try std.testing.expectEqual(i, m.lo);+}++test "ADR 0252: Chat tool messages fold into one user message; unparsable arguments are wrapped" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ const items = try parse(a,+ \\[{"role":"user","content":"go"},+ \\ {"role":"assistant","content":null,"tool_calls":[{"id":"c1","type":"function","function":{"name":"bash","arguments":"{\"cmd\":\"ls\"}"}},{"id":"c2","type":"function","function":{"name":"grep","arguments":"not json"}}]},+ \\ {"role":"tool","tool_call_id":"c1","content":"a\nb"},+ \\ {"role":"tool","tool_call_id":"c2","content":"[error] bad pattern"},+ \\ {"role":"assistant","content":"ok"}]+ );+ const msgs = try wire.transcript(a, items);+ try std.testing.expectEqual(@as(usize, 4), msgs.len);+ try std.testing.expectEqualStrings("ls", field(msgs[1].uses[0].input, "cmd").string);+ try std.testing.expectEqualStrings("not json", field(msgs[1].uses[1].input, "arguments").string);+ try std.testing.expectEqual(@as(usize, 2), msgs[2].lo);+ try std.testing.expectEqual(@as(usize, 4), msgs[2].hi);+ try std.testing.expectEqual(@as(usize, 2), msgs[2].results.len);+ try std.testing.expect(!msgs[2].results[0].is_error);+ try std.testing.expect(msgs[2].results[1].is_error);+}++test "ADR 0252: Responses and Interactions items fold the same way; reasoning joins the model's side" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ const responses = try wire.transcript(a, try parse(a,+ \\[{"role":"user","content":"go"},+ \\ {"type":"reasoning","encrypted_content":"x","summary":[]},+ \\ {"type":"function_call","call_id":"f1","name":"bash","arguments":"{\"cmd\":\"ls\"}"},+ \\ {"type":"function_call_output","call_id":"f1","output":"listing"},+ \\ {"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}]+ ));+ try std.testing.expectEqual(@as(usize, 4), responses.len);+ try std.testing.expectEqual(@as(usize, 1), responses[1].lo);+ try std.testing.expectEqual(@as(usize, 3), responses[1].hi);+ try std.testing.expectEqualStrings("f1", responses[2].results[0].id);+ try std.testing.expectEqualStrings("done", responses[3].text);+ const interactions = try wire.transcript(a, try parse(a,+ \\[{"type":"user_input","content":"go"},+ \\ {"type":"thought","signature":"s"},+ \\ {"type":"function_call","id":"g1","name":"bash","arguments":{"cmd":"ls"}},+ \\ {"type":"function_result","call_id":"g1","name":"bash","result":[{"type":"text","text":"listing"}]},+ \\ {"type":"model_output","content":[{"type":"text","text":"done"}]}]+ ));+ try std.testing.expectEqual(@as(usize, 4), interactions.len);+ try std.testing.expectEqualStrings("go", interactions[0].text);+ try std.testing.expectEqualStrings("ls", field(interactions[1].uses[0].input, "cmd").string);+ try std.testing.expectEqualStrings("listing", interactions[2].results[0].text);+}++test "ADR 0252: the request names the model, hybrid mode, the goal and every call by id" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ const msgs = try wire.transcript(a, try parse(a,+ \\[{"role":"user","content":"go"},+ \\ {"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"read_file","input":{"path":"a.zig"}}]},+ \\ {"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"body","is_error":true}]}]+ ));+ const body = try wire.request(a, msgs, "clef", "ship the fix");+ const v = try std.json.parseFromSliceLeaky(Value, a, body, .{});+ try std.testing.expectEqualStrings("clef", field(v, "model").string);+ try std.testing.expectEqualStrings("hybrid", field(v, "mode").string);+ try std.testing.expectEqualStrings("ship the fix", field(v, "goal").string);+ const sent = field(v, "messages").array.items;+ try std.testing.expectEqualStrings("assistant", field(sent[1], "role").string);+ const use = field(sent[1], "toolUses").array.items[0];+ try std.testing.expectEqualStrings("t1", field(use, "tool_use_id").string);+ try std.testing.expectEqualStrings("a.zig", field(field(use, "input"), "path").string);+ const result = field(sent[2], "toolResults").array.items[0];+ try std.testing.expect(field(result, "isError").bool);+}++/// Two finished turns' worth of Anthropic history: t1/t2 in the earlier turn,+/// t3/t4 in the live one (it opens at item 6).+const two_turns =+ \\[{"role":"user","content":"first prompt"},+ \\ {"role":"assistant","content":[{"type":"text","text":"look"},{"type":"tool_use","id":"t1","name":"read_file","input":{"path":"a"}}]},+ \\ {"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"aaaaaaaaaaaaaaaaaaaaaaaa"}]},+ \\ {"role":"assistant","content":[{"type":"tool_use","id":"t2","name":"grep","input":{"q":"x"}}]},+ \\ {"role":"user","content":[{"type":"tool_result","tool_use_id":"t2","content":"bbbbbbbbbbbbbbbbbbbbbbbb"}]},+ \\ {"role":"assistant","content":"answer one"},+ \\ {"role":"user","content":"second prompt"},+ \\ {"role":"assistant","content":[{"type":"tool_use","id":"t3","name":"bash","input":{"cmd":"ls"}}]},+ \\ {"role":"user","content":[{"type":"tool_result","tool_use_id":"t3","content":"cccccccccccccccccccccccc"}]},+ \\ {"role":"assistant","content":[{"type":"tool_use","id":"t4","name":"bash","input":{"cmd":"pwd"}}]},+ \\ {"role":"user","content":[{"type":"tool_result","tool_use_id":"t4","content":"short"}]},+ \\ {"role":"assistant","content":"answer two"}]+;++/// The endpoint's transcript for two_turns after t1 drop_result, t2 and t3+/// drop_call, t4 keep: messages holding only dropped calls are gone.+const pruned_reply =+ \\{"messages":[+ \\ {"role":"user","text":"first prompt","toolUses":[],"toolResults":[]},+ \\ {"role":"assistant","text":"look","toolUses":[{"tool_use_id":"t1","tool":"read_file","input":{"path":"a"}}],"toolResults":[]},+ \\ {"role":"user","text":"","toolUses":[],"toolResults":[{"tool_use_id":"t1","text":"aaa…[truncated]"}]},+ \\ {"role":"assistant","text":"answer one","toolUses":[],"toolResults":[]},+ \\ {"role":"user","text":"second prompt","toolUses":[],"toolResults":[]},+ \\ {"role":"assistant","text":"","toolUses":[{"tool_use_id":"t4","tool":"bash","input":{"cmd":"pwd"}}],"toolResults":[]},+ \\ {"role":"user","text":"","toolUses":[],"toolResults":[{"tool_use_id":"t4","text":"short"}]},+ \\ {"role":"assistant","text":"answer two","toolUses":[],"toolResults":[]}],+ \\ "decisions":[{"id":"t1","tool":"read_file","tool_use_id":"t1","action":"drop_result"},+ \\ {"id":"t2","tool":"grep","tool_use_id":"t2","action":"drop_call"},+ \\ {"id":"t3","tool":"bash","tool_use_id":"t3","action":"drop_call"},+ \\ {"id":"t4","tool":"bash","tool_use_id":"t4","action":"keep"}],+ \\ "stats":{"summarized":false}}+;++test "ADR 0252: earlier turns lose dropped calls; the live turn keeps its calls and trims their results" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ const items = try parse(a, two_turns);+ const msgs = try wire.transcript(a, items);+ const reply = try wire.parseReply(a, try std.json.parseFromSliceLeaky(Value, a, pruned_reply, .{ .allocate = .alloc_always }));+ try std.testing.expect(!reply.summarized);+ const p = try wire.plan(a, msgs, &reply, null);+ const stubber: TestStub = .{};+ const fresh = try wire.apply(a, items, msgs, p, &reply.decisions, 6, null, &stubber);+ // t2's pair (items 3, 4) is gone; t3 (live turn) keeps its call.+ try std.testing.expectEqual(@as(usize, 10), fresh.items.len);+ const t1 = field(fresh.items[2], "content").array.items[0];+ try std.testing.expectEqualStrings("aaaaaaaa…[trimmed]", field(t1, "content").string);+ try std.testing.expectEqualStrings("answer one", field(fresh.items[3], "content").string);+ try std.testing.expectEqualStrings("t3", field(field(fresh.items[5], "content").array.items[0], "id").string);+ const t3 = field(fresh.items[6], "content").array.items[0];+ try std.testing.expectEqualStrings("cccccccc…[trimmed]", field(t3, "content").string);+ try std.testing.expectEqualStrings("short", field(field(fresh.items[8], "content").array.items[0], "content").string);+ // The live history was not touched: the fresh one shares untouched items.+ try std.testing.expectEqualStrings("aaaaaaaaaaaaaaaaaaaaaaaa", field(field(items[2], "content").array.items[0], "content").string);+ try wire.checkPairs(a, items, fresh.items);+}++test "ADR 0252: a reply that does not match what its decisions imply is refused" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ const items = try parse(a, two_turns);+ const msgs = try wire.transcript(a, items);+ // The endpoint must never rewrite text: an edited message fails the check.+ const edited = try std.mem.replaceOwned(u8, a, pruned_reply, "answer one", "answer 1");+ const reply = try wire.parseReply(a, try std.json.parseFromSliceLeaky(Value, a, edited, .{ .allocate = .alloc_always }));+ try std.testing.expectError(error.UnexpectedReply, wire.plan(a, msgs, &reply, null));+ // So does a decision list that disagrees with the transcript it came with.+ const kept = try std.mem.replaceOwned(u8, a, pruned_reply, "\"action\":\"drop_call\"}", "\"action\":\"keep\"}");+ const mismatch = try wire.parseReply(a, try std.json.parseFromSliceLeaky(Value, a, kept, .{ .allocate = .alloc_always }));+ try std.testing.expectError(error.UnexpectedReply, wire.plan(a, msgs, &mismatch, null));+}++/// Responses history: a task, two earlier calls and a reply, then a new prompt+/// at item 6 and three calls in the live turn.+const long_turn =+ \\[{"role":"user","content":"task"},+ \\ {"type":"function_call","call_id":"a1","name":"bash","arguments":"{}"},+ \\ {"type":"function_call_output","call_id":"a1","output":"one"},+ \\ {"type":"function_call","call_id":"a2","name":"bash","arguments":"{}"},+ \\ {"type":"function_call_output","call_id":"a2","output":"two"},+ \\ {"type":"message","role":"assistant","content":[{"type":"output_text","text":"progress"}]},+ \\ {"role":"user","content":"now do X"},+ \\ {"type":"function_call","call_id":"a3","name":"bash","arguments":"{}"},+ \\ {"type":"function_call_output","call_id":"a3","output":"three"},+ \\ {"type":"function_call","call_id":"a4","name":"bash","arguments":"{}"},+ \\ {"type":"function_call_output","call_id":"a4","output":"four"},+ \\ {"type":"function_call","call_id":"a5","name":"bash","arguments":"{}"},+ \\ {"type":"function_call_output","call_id":"a5","output":"five"}+;++fn summarizedReply(a: Allocator, msgs: []const wire.Msg) !wire.Reply {+ var out: std.Io.Writer.Allocating = .init(a);+ const w = &out.writer;+ try w.writeAll("{\"stats\":{\"summarized\":true},\"decisions\":[],\"messages\":[");+ const neutral = try std.json.parseFromSliceLeaky(Value, a, try wire.request(a, msgs, "clef", null), .{ .allocate = .alloc_always });+ const sent = field(neutral, "messages").array.items;+ try std.json.Stringify.value(sent[0], .{}, w);+ try w.writeAll(",{\"role\":\"user\",\"text\":\"[compacted summary of 6 earlier messages]\\nRan two checks.\",\"toolUses\":[]}");+ for (sent[sent.len - wire.recent_kept ..]) |m| {+ try w.writeByte(',');+ try std.json.Stringify.value(m, .{}, w);+ }+ try w.writeAll("]}");+ return wire.parseReply(a, try std.json.parseFromSliceLeaky(Value, a, out.writer.buffered(), .{ .allocate = .alloc_always }));+}++test "ADR 0252: a summary keeps the unresolved turn's opening prompt and never orphans a result" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ // Unresolved (it ends on a tool result): the prompt at item 6 must survive.+ const unresolved = try parse(a, long_turn ++ "]");+ const msgs = try wire.transcript(a, unresolved);+ try std.testing.expectEqual(@as(usize, 13), msgs.len);+ const reply = try summarizedReply(a, msgs);+ try std.testing.expectEqualStrings("Ran two checks.", reply.summary);+ const p = try wire.plan(a, msgs, &reply, 6);+ const stubber: TestStub = .{};+ const note = try @import("messages.zig").userNote(a, .responses, "SUMMARY");+ const fresh = try wire.apply(a, unresolved, msgs, p, &reply.decisions, 6, note, &stubber);+ try std.testing.expectEqualStrings("task", field(fresh.items[0], "content").string);+ try std.testing.expectEqualStrings("now do X", field(fresh.items[2], "content").string);+ try std.testing.expectEqual(@as(usize, 2 + 7), fresh.items.len); // task, summary, prompt, a3..a5 pairs+ try wire.checkPairs(a, unresolved, fresh.items);+ try std.testing.expectEqual(@as(usize, 5), (try wire.replaced(a, unresolved, msgs, p)).len); // items 1-5++ // Resolved by a reply: the newest six now open on a3's RESULT, so the cut+ // moves back over a3's call instead of shipping an orphan.+ const resolved = try parse(a, long_turn +++ \\,{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}]+ );+ const msgs2 = try wire.transcript(a, resolved);+ const reply2 = try summarizedReply(a, msgs2);+ const p2 = try wire.plan(a, msgs2, &reply2, null);+ const fresh2 = try wire.apply(a, resolved, msgs2, p2, &reply2.decisions, 6, note, &stubber);+ try std.testing.expectEqualStrings("a3", field(fresh2.items[2], "call_id").string);+ try std.testing.expectEqualStrings("function_call", field(fresh2.items[2], "type").string);+ try wire.checkPairs(a, resolved, fresh2.items);+}++test "ADR 0252: a history that pairs worse than the one it replaces is refused" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ const before = try parse(a,+ \\[{"role":"user","content":"go"},+ \\ {"type":"function_call","call_id":"f1","name":"bash","arguments":"{}"},+ \\ {"type":"function_call_output","call_id":"f1","output":"ok"}]+ );+ try std.testing.expectError(error.UnpairedToolCall, wire.checkPairs(a, before, &.{ before[0], before[2] }));+ try std.testing.expectError(error.UnpairedToolCall, wire.checkPairs(a, before, before[0..2]));+ // An unanswered call the session already had is not this compaction's doing.+ try wire.checkPairs(a, before[0..2], before[0..2]);+}++test "ADR 0252: refusals are read from the gateway's error envelope" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ const credits = try std.json.parseFromSliceLeaky(Value, a, "{\"error\":{\"message\":\"m\",\"type\":\"insufficient_credits\",\"code\":\"insufficient_credits\"}}", .{});+ try std.testing.expectEqualStrings("insufficient_credits", hosted.refusal(credits).?);+ const ok = try std.json.parseFromSliceLeaky(Value, a, "{\"messages\":[],\"decisions\":[]}", .{});+ try std.testing.expect(hosted.refusal(ok) == null);+}++test "ADR 0252: the opt-out and a missing login leave compaction local" {+ const Env = struct {+ off: bool,+ pub fn get(self: @This(), key: []const u8) ?[]const u8 {+ return if (self.off and std.mem.eql(u8, key, "GRAFF_HOSTED_COMPACT")) "0" else null;+ }+ };+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const a = state.allocator();+ defer hosted.setLoginKey(std.testing.io, null);+ defer hosted.configure(a, Env{ .off = false }) catch {};+ var agent = @import("agent_compact_test_support.zig").subAgent(a, false);+ agent.io = std.testing.io;+ agent.messages = std.json.Array.init(a);+ try hosted.configure(a, Env{ .off = false });+ hosted.setLoginKey(std.testing.io, null);+ try std.testing.expect(try hosted.run(&agent) == null); // no login: nothing sent+ try hosted.configure(a, Env{ .off = true });+ hosted.setLoginKey(std.testing.io, "cg_sk_synthetic");+ try std.testing.expect(try hosted.run(&agent) == null); // opted out+}diff --git a/src/gateway_compact_wire.zig b/src/gateway_compact_wire.zignew file mode 100644index 00000000..039c8605--- /dev/null+++ b/src/gateway_compact_wire.zig@@ -0,0 +1,568 @@+//! The wire half of hosted compaction (ADR 0252): graff's provider-shaped+//! history to the gateway's neutral transcript, and the reply back onto it.+//! Pure — no Agent, no network — so every wire format's mapping is pinned by+//! fixtures (gateway_compact_tests.zig).+//!+//! Out: consecutive items of one side fold into one neutral message — user+//! prompts, harness notes and tool results on one side; assistant text, calls+//! and reasoning on the other — and each message remembers the native range+//! it came from. In: the endpoint's per-call decisions are applied to the+//! NATIVE items by call id. Nothing is rebuilt from the neutral copy, so+//! reasoning, images and provider metadata stay as they were; a hybrid summary+//! replaces only the native range it summarized.++const std = @import("std");+const Allocator = std.mem.Allocator;+const Value = std.json.Value;+const ObjectMap = std.json.ObjectMap;++const sanitizeUtf8 = @import("messages.zig").sanitizeUtf8;++/// The endpoint's own cap on one transcript.+pub const max_messages = 2000;+/// Newest messages the hybrid summary keeps verbatim: the endpoint's default,+/// which its summary step applies whatever the request says.+pub const recent_kept = 6;++pub const Role = enum { user, assistant };+pub const Use = struct { id: []const u8, name: []const u8, input: Value = .null };+pub const Result = struct { id: []const u8, text: []const u8 = "", is_error: bool = false };++pub const Msg = struct {+ role: Role,+ /// The native items [lo, hi) this message folds.+ lo: usize,+ hi: usize,+ text: []const u8 = "",+ uses: []const Use = &.{},+ results: []const Result = &.{},+};++const Builder = struct {+ a: Allocator,+ /// Call/result ids only: no text, no argument parsing (pair checks).+ ids_only: bool = false,+ out: std.ArrayList(Msg) = .empty,+ open: ?Msg = null,+ text: std.ArrayList(u8) = .empty,+ uses: std.ArrayList(Use) = .empty,+ results: std.ArrayList(Result) = .empty,++ fn close(b: *Builder) !void {+ var m = b.open orelse return;+ m.text = try b.text.toOwnedSlice(b.a);+ m.uses = try b.uses.toOwnedSlice(b.a);+ m.results = try b.results.toOwnedSlice(b.a);+ try b.out.append(b.a, m);+ b.open = null;+ }++ fn addText(b: *Builder, s: []const u8) !void {+ if (b.ids_only or s.len == 0) return;+ if (b.text.items.len > 0) try b.text.append(b.a, '\n');+ try b.text.appendSlice(b.a, sanitizeUtf8(b.a, s));+ }++ fn use(b: *Builder, id: ?[]const u8, name: ?[]const u8, input: ?Value, wrap_as: []const u8) !void {+ const call_id = id orelse return;+ const args: Value = if (b.ids_only) .null else try argsObject(b.a, input, wrap_as);+ try b.uses.append(b.a, .{ .id = call_id, .name = name orelse "tool", .input = args });+ }++ fn result(b: *Builder, id: ?[]const u8, payload: ?Value, is_error: bool) !void {+ const call_id = id orelse return;+ const text = if (b.ids_only) "" else sanitizeUtf8(b.a, try textOf(b.a, payload orelse .null));+ try b.results.append(b.a, .{ .id = call_id, .text = text, .is_error = is_error });+ }+};++fn str(o: ObjectMap, key: []const u8) ?[]const u8 {+ const v = o.get(key) orelse return null;+ return if (v == .string) v.string else null;+}++fn eql(a: []const u8, b: []const u8) bool {+ return std.mem.eql(u8, a, b);+}++fn errorFlag(o: ObjectMap) bool {+ const v = o.get("is_error") orelse o.get("isError") orelse return false;+ return v == .bool and v.bool;+}++/// Which side an item speaks for. Typed items (Responses, Interactions) are+/// the model's unless they carry a result or a prompt; role messages follow+/// their role, with tool results and harness notes on the user side.+fn itemRole(item: Value) ?Role {+ if (item != .object) return null;+ const o = item.object;+ if (str(o, "type")) |t| {+ if (eql(t, "function_call_output") or eql(t, "custom_tool_call_output") or+ eql(t, "function_result") or eql(t, "user_input")) return .user;+ if (!eql(t, "message")) return .assistant; // calls, reasoning, thought, model_output, opaque state+ }+ const role = str(o, "role") orelse return null;+ return if (eql(role, "assistant")) .assistant else .user;+}++/// Joined text of a string, a text-bearing object, or an array of parts.+/// Images and other non-text parts contribute nothing.+pub fn textOf(a: Allocator, v: Value) ![]const u8 {+ switch (v) {+ .string => |s| return s,+ .object => |o| return str(o, "text") orelse "",+ .array => |arr| {+ var out: std.ArrayList(u8) = .empty;+ for (arr.items) |part| {+ const t = switch (part) {+ .string => |s| s,+ .object => |o| str(o, "text") orelse "",+ else => "",+ };+ if (t.len == 0) continue;+ if (out.items.len > 0) try out.append(a, '\n');+ try out.appendSlice(a, t);+ }+ return out.items;+ },+ else => return "",+ }+}++/// The endpoint takes a call's input as a JSON object: Chat/Responses carry a+/// string of JSON, a freeform tool a raw string, and either may not parse.+fn argsObject(a: Allocator, v: ?Value, wrap_as: []const u8) !Value {+ const raw = v orelse return .{ .object = .empty };+ switch (raw) {+ .object => return raw,+ .null => return .{ .object = .empty },+ .string => |s| {+ if (std.json.parseFromSliceLeaky(Value, a, s, .{ .allocate = .alloc_always })) |parsed| {+ if (parsed == .object) return parsed;+ } else |_| {}+ },+ else => {},+ }+ var o: ObjectMap = .empty;+ try o.put(a, wrap_as, raw);+ return .{ .object = o };+}++fn absorbBlock(b: *Builder, block: Value) !void {+ if (block == .string) return b.addText(block.string);+ if (block != .object) return;+ const o = block.object;+ const t = str(o, "type") orelse return;+ if (eql(t, "text") or eql(t, "input_text") or eql(t, "output_text")) return b.addText(str(o, "text") orelse "");+ if (eql(t, "tool_use")) return b.use(str(o, "id"), str(o, "name"), o.get("input"), "input");+ if (eql(t, "tool_result")) return b.result(str(o, "tool_use_id"), o.get("content"), errorFlag(o));+}++fn absorb(b: *Builder, item: Value) !void {+ if (item != .object) return;+ const o = item.object;+ if (str(o, "type")) |t| {+ if (eql(t, "function_call")) return b.use(str(o, "call_id") orelse str(o, "id"), str(o, "name"), o.get("arguments"), "arguments");+ if (eql(t, "custom_tool_call")) return b.use(str(o, "call_id"), str(o, "name"), o.get("input"), "input");+ if (eql(t, "function_call_output") or eql(t, "custom_tool_call_output")) return b.result(str(o, "call_id"), o.get("output"), false);+ if (eql(t, "function_result")) return b.result(str(o, "call_id"), o.get("result"), errorFlag(o));+ if (eql(t, "user_input") or eql(t, "model_output") or eql(t, "message")) {+ if (b.ids_only) return;+ return b.addText(try textOf(b.a, o.get("content") orelse .null));+ }+ return; // reasoning, thought, opaque provider state: nothing readable+ }+ const role = str(o, "role") orelse return;+ if (eql(role, "tool")) {+ // OpenAI Chat has no error bit; graff writes failures with this prefix.+ const content = o.get("content") orelse Value.null;+ const failed = content == .string and std.mem.startsWith(u8, content.string, "[error] ");+ return b.result(str(o, "tool_call_id"), content, failed);+ }+ if (o.get("content")) |content| switch (content) {+ .string => |s| try b.addText(s),+ .array => |arr| for (arr.items) |block| try absorbBlock(b, block),+ else => {},+ };+ if (o.get("tool_calls")) |calls| if (calls == .array) for (calls.array.items) |call| {+ if (call != .object) continue;+ const f = call.object.get("function") orelse continue;+ if (f != .object) continue;+ try b.use(str(call.object, "id"), str(f.object, "name"), f.object.get("arguments"), "arguments");+ };+}++fn fold(a: Allocator, items: []const Value, ids_only: bool) ![]const Msg {+ var b: Builder = .{ .a = a, .ids_only = ids_only };+ for (items, 0..) |item, i| {+ const role = itemRole(item) orelse if (b.open) |m| m.role else Role.user;+ if (b.open == null or b.open.?.role != role) {+ try b.close();+ b.open = .{ .role = role, .lo = i, .hi = i };+ }+ b.open.?.hi = i + 1;+ try absorb(&b, item);+ }+ try b.close();+ return b.out.items;+}++/// Native history → neutral messages. The ranges are contiguous and cover+/// every item, so each native item belongs to exactly one message.+pub fn transcript(a: Allocator, items: []const Value) ![]const Msg {+ return fold(a, items, false);+}++/// The POST /v1/compact body.+pub fn request(a: Allocator, msgs: []const Msg, model: []const u8, goal: ?[]const u8) ![]const u8 {+ const WireUse = struct { tool_use_id: []const u8, tool: []const u8, input: Value };+ const WireResult = struct { tool_use_id: []const u8, text: []const u8, isError: ?bool };+ const WireMsg = struct { role: []const u8, text: []const u8, toolUses: []const WireUse, toolResults: []const WireResult };+ const out = try a.alloc(WireMsg, msgs.len);+ for (msgs, out) |m, *w| {+ const uses = try a.alloc(WireUse, m.uses.len);+ for (m.uses, uses) |u, *x| x.* = .{ .tool_use_id = u.id, .tool = u.name, .input = u.input };+ const results = try a.alloc(WireResult, m.results.len);+ for (m.results, results) |r, *x| x.* = .{ .tool_use_id = r.id, .text = r.text, .isError = if (r.is_error) true else null };+ w.* = .{ .role = @tagName(m.role), .text = m.text, .toolUses = uses, .toolResults = results };+ }+ var aw: std.Io.Writer.Allocating = .init(a);+ const body = .{ .model = model, .mode = "hybrid", .goal = goal, .messages = out };+ try std.json.Stringify.value(body, .{ .emit_null_optional_fields = false }, &aw.writer);+ return aw.writer.buffered();+}++pub const Action = enum { keep, drop_result, drop_call };+pub const Decisions = std.StringHashMapUnmanaged(Action);++pub const Reply = struct {+ decisions: Decisions = .empty,+ /// The endpoint's transcript after compaction, for validation only.+ messages: []const Value = &.{},+ summarized: bool = false,+ /// The spliced summary without the endpoint's header line.+ summary: []const u8 = "",+};++pub fn parseReply(a: Allocator, root: Value) !Reply {+ if (root != .object) return error.UnexpectedReply;+ const msgs = root.object.get("messages") orelse return error.UnexpectedReply;+ const decisions = root.object.get("decisions") orelse return error.UnexpectedReply;+ if (msgs != .array or decisions != .array) return error.UnexpectedReply;+ var reply: Reply = .{ .messages = msgs.array.items };+ for (decisions.array.items) |d| {+ if (d != .object) return error.UnexpectedReply;+ const id = str(d.object, "tool_use_id") orelse return error.UnexpectedReply;+ const action = std.meta.stringToEnum(Action, str(d.object, "action") orelse "") orelse return error.UnexpectedReply;+ try reply.decisions.put(a, id, action);+ }+ if (root.object.get("stats")) |stats| {+ if (stats == .object) if (stats.object.get("summarized")) |v| {+ reply.summarized = v == .bool and v.bool;+ };+ }+ if (reply.summarized) {+ if (reply.messages.len < 2 or reply.messages[1] != .object) return error.UnexpectedReply;+ const text = str(reply.messages[1].object, "text") orelse return error.UnexpectedReply;+ const body = if (std.mem.indexOfScalar(u8, text, '\n')) |nl| text[nl + 1 ..] else text;+ reply.summary = std.mem.trim(u8, body, " \t\r\n");+ if (reply.summary.len == 0) return error.UnexpectedReply;+ }+ return reply;+}++fn act(d: *const Decisions, id: ?[]const u8) Action {+ return d.get(id orelse return .keep) orelse .keep;+}++/// The endpoint's rule: a message survives unless compaction touched it and+/// left no text, call, or result behind.+fn survives(m: Msg, d: *const Decisions) bool {+ var touched = false;+ var left = m.text.len > 0;+ for (m.uses) |u| {+ if (act(d, u.id) == .drop_call) touched = true else left = true;+ }+ for (m.results) |r| switch (act(d, r.id)) {+ .drop_call => touched = true,+ .drop_result => {+ touched = true;+ left = true;+ },+ .keep => left = true,+ };+ return !touched or left;+}++fn sameIds(listed: ?Value, comptime T: type, mine: []const T, d: *const Decisions) bool {+ const arr = if (listed) |v| (if (v == .array) v.array.items else return false) else &[_]Value{};+ var k: usize = 0;+ for (mine) |x| {+ if (act(d, x.id) == .drop_call) continue;+ if (k >= arr.len or arr[k] != .object) return false;+ const id = str(arr[k].object, "tool_use_id") orelse return false;+ if (!eql(id, x.id)) return false;+ k += 1;+ }+ return k == arr.len;+}++/// Is `r` (from the reply) message `m` after the decisions? Text is compared+/// byte for byte: the endpoint never rewrites it.+fn matches(r: Value, m: Msg, d: *const Decisions) bool {+ if (r != .object) return false;+ const role = str(r.object, "role") orelse return false;+ if (!eql(role, @tagName(m.role))) return false;+ if (!eql(str(r.object, "text") orelse "", m.text)) return false;+ return sameIds(r.object.get("toolUses"), Use, m.uses, d) and+ sameIds(r.object.get("toolResults"), Result, m.results, d);+}++fn useAt(msgs: []const Msg, id: []const u8) ?usize {+ for (msgs, 0..) |m, j| for (m.uses) |u| if (eql(u.id, id)) return j;+ return null;+}++pub fn msgAt(msgs: []const Msg, native: usize) ?usize {+ for (msgs, 0..) |m, j| if (native >= m.lo and native < m.hi) return j;+ return null;+}++pub const Plan = struct {+ /// Per neutral message: kept (with its per-call decisions applied).+ keep: []bool,+ /// The neutral message the summary note goes before; null = no summary.+ note_before: ?usize = null,+};++/// Check the reply against what the decisions imply, then decide which+/// neutral messages stay. A summarized reply is [first, summary, newest+/// recent_kept]; the cut moves back over any call a kept result answers (a+/// result without its call is rejected by every wire), and `opening` — an+/// unresolved turn's opening prompt (#581) — is kept verbatim too.+pub fn plan(a: Allocator, msgs: []const Msg, reply: *const Reply, opening: ?usize) !Plan {+ const d = &reply.decisions;+ var left: std.ArrayList(usize) = .empty;+ for (msgs, 0..) |m, j| if (survives(m, d)) try left.append(a, j);+ const keep = try a.alloc(bool, msgs.len);+ @memset(keep, true);+ if (!reply.summarized) {+ if (reply.messages.len != left.items.len) return error.UnexpectedReply;+ for (left.items, reply.messages) |j, r| if (!matches(r, msgs[j], d)) return error.UnexpectedReply;+ return .{ .keep = keep };+ }+ if (left.items.len < recent_kept + 3 or reply.messages.len != recent_kept + 2) return error.UnexpectedReply;+ const head = left.items[0];+ const tail = left.items[left.items.len - recent_kept ..];+ if (!matches(reply.messages[0], msgs[head], d)) return error.UnexpectedReply;+ for (tail, reply.messages[2..]) |j, r| if (!matches(r, msgs[j], d)) return error.UnexpectedReply;+ var cut = tail[0];+ var moved = true;+ while (moved) {+ moved = false;+ for (msgs[cut..]) |m| for (m.results) |r| {+ const j = useAt(msgs, r.id) orelse continue;+ if (j > head and j < cut) {+ cut = j;+ moved = true;+ }+ };+ }+ @memset(keep, false);+ keep[head] = true;+ @memset(keep[cut..], true);+ if (opening) |t| {+ if (msgAt(msgs, t)) |j| keep[j] = keep[j] or j > head;+ }+ var note_before: ?usize = null;+ for (keep[head + 1 ..], head + 1..) |k, j| if (k) {+ note_before = j;+ break;+ };+ return .{ .keep = keep, .note_before = note_before orelse return error.UnexpectedReply };+}++fn cloneObject(a: Allocator, o: ObjectMap) !ObjectMap {+ var c: ObjectMap = .empty;+ try c.ensureTotalCapacity(a, o.count());+ var it = o.iterator();+ while (it.next()) |e| c.putAssumeCapacity(e.key_ptr.*, e.value_ptr.*);+ return c;+}++fn withField(a: Allocator, o: ObjectMap, key: []const u8, v: Value) !Value {+ var c = try cloneObject(a, o);+ try c.put(a, key, v);+ return .{ .object = c };+}++const Shape = enum { string, parts };++/// A result payload per its decision: gone with its call, shrunk to a stub,+/// or untouched. Null removes the item.+fn shrink(a: Allocator, o: ObjectMap, field: []const u8, action: Action, removable: bool, shape: Shape, stubber: anytype) !?Value {+ if (action == .keep) return .{ .object = o };+ if (action == .drop_call and removable) return null;+ const full = try textOf(a, o.get(field) orelse .null);+ const stub = stubber.stub(a, full);+ if (stub.len >= full.len) return .{ .object = o };+ const payload: Value = switch (shape) {+ .string => .{ .string = stub },+ .parts => blk: {+ var part: ObjectMap = .empty;+ try part.put(a, "type", .{ .string = "text" });+ try part.put(a, "text", .{ .string = stub });+ var parts = std.json.Array.init(a);+ try parts.append(.{ .object = part });+ break :blk .{ .array = parts };+ },+ };+ return try withField(a, o, field, payload);+}++fn shrinkBlocks(a: Allocator, o: ObjectMap, d: *const Decisions, removable: bool, stubber: anytype) !?Value {+ const content = o.get("content") orelse return .{ .object = o };+ if (content != .array) return .{ .object = o };+ var blocks = std.json.Array.init(a);+ var changed = false;+ for (content.array.items) |block| {+ const is_result = block == .object and eql(str(block.object, "type") orelse "", "tool_result");+ const action = if (is_result) act(d, str(block.object, "tool_use_id")) else .keep;+ if (action == .keep) {+ try blocks.append(block);+ continue;+ }+ changed = true;+ if (try shrink(a, block.object, "content", action, removable, .string, stubber)) |v| try blocks.append(v);+ }+ if (!changed) return .{ .object = o };+ if (blocks.items.len == 0) return null;+ return try withField(a, o, "content", .{ .array = blocks });+}++/// Something a later request can use: text or a call. Reasoning, thinking or+/// an empty shell left behind by dropped calls is not.+fn substantive(content: ?Value, calls: ?Value) bool {+ if (calls) |c| if (c == .array and c.array.items.len > 0) return true;+ const v = content orelse return false;+ if (v == .string) return v.string.len > 0;+ if (v != .array) return false;+ for (v.array.items) |block| {+ if (block != .object) continue;+ const t = str(block.object, "type") orelse continue;+ if (eql(t, "tool_use")) return true;+ if (!eql(t, "text")) continue;+ const text: []const u8 = str(block.object, "text") orelse "";+ if (text.len > 0) return true;+ }+ return false;+}++fn dropCalls(a: Allocator, o: ObjectMap, d: *const Decisions) !?Value {+ var calls = o.get("tool_calls");+ var calls_changed = false;+ if (calls) |c| if (c == .array) {+ var kept = std.json.Array.init(a);+ for (c.array.items) |call| {+ const id = if (call == .object) str(call.object, "id") else null;+ if (act(d, id) == .drop_call) calls_changed = true else try kept.append(call);+ }+ if (calls_changed) calls = .{ .array = kept };+ };+ var content = o.get("content");+ var content_changed = false;+ if (content) |c| if (c == .array) {+ var kept = std.json.Array.init(a);+ for (c.array.items) |block| {+ const dropped = block == .object and eql(str(block.object, "type") orelse "", "tool_use") and+ act(d, str(block.object, "id")) == .drop_call;+ if (dropped) content_changed = true else try kept.append(block);+ }+ if (content_changed) content = .{ .array = kept };+ };+ if (!calls_changed and !content_changed) return .{ .object = o };+ if (!substantive(content, calls)) return null;+ var c = try cloneObject(a, o);+ if (calls_changed) {+ // An empty tool_calls array is rejected outright; the key goes.+ if (calls.?.array.items.len == 0) _ = c.orderedRemove("tool_calls") else try c.put(a, "tool_calls", calls.?);+ }+ if (content_changed) try c.put(a, "content", content.?);+ return .{ .object = c };+}++/// One native item after the decisions. `removable`: the item is from an+/// earlier turn, so a dropped call goes with its result and stale reasoning+/// goes too (#174). In the live turn a dropped call only loses its result's+/// bulk: that turn's reasoning, thinking and signatures stay paired with every+/// call they reference.+pub fn applyItem(a: Allocator, item: Value, d: *const Decisions, removable: bool, stubber: anytype) !?Value {+ if (item != .object) return item;+ const o = item.object;+ if (str(o, "type")) |t| {+ if (eql(t, "function_call") or eql(t, "custom_tool_call"))+ return if (removable and act(d, str(o, "call_id") orelse str(o, "id")) == .drop_call) null else item;+ if (eql(t, "function_call_output") or eql(t, "custom_tool_call_output"))+ return shrink(a, o, "output", act(d, str(o, "call_id")), removable, .string, stubber);+ if (eql(t, "function_result"))+ return shrink(a, o, "result", act(d, str(o, "call_id")), removable, .parts, stubber);+ if (eql(t, "reasoning") and removable) return null;+ return item;+ }+ const role = str(o, "role") orelse return item;+ if (eql(role, "tool")) return shrink(a, o, "content", act(d, str(o, "tool_call_id")), removable, .string, stubber);+ if (eql(role, "assistant")) return if (removable) dropCalls(a, o, d) else item;+ if (eql(role, "user")) return shrinkBlocks(a, o, d, removable, stubber);+ return item;+}++/// The history to install. `removable_before`: items before this index belong+/// to earlier turns (see applyItem).+pub fn apply(a: Allocator, items: []const Value, msgs: []const Msg, p: Plan, d: *const Decisions, removable_before: usize, note: ?Value, stubber: anytype) !std.json.Array {+ var fresh = std.json.Array.init(a);+ try fresh.ensureTotalCapacity(items.len + 1);+ for (msgs, 0..) |m, j| {+ if (p.note_before == j) if (note) |n| try fresh.append(n);+ if (!p.keep[j]) continue;+ for (items[m.lo..m.hi], m.lo..) |item, i| {+ if (try applyItem(a, item, d, i < removable_before, stubber)) |v| try fresh.append(v);+ }+ }+ return fresh;+}++/// The items a summary replaced (#409 reads their artifact paths).+pub fn replaced(a: Allocator, items: []const Value, msgs: []const Msg, p: Plan) ![]const Value {+ var out: std.ArrayList(Value) = .empty;+ for (msgs, p.keep) |m, k| if (!k) try out.appendSlice(a, items[m.lo..m.hi]);+ return out.items;+}++const IdSet = std.StringHashMapUnmanaged(void);++/// Results without an earlier call, and calls without a later result.+fn unpaired(a: Allocator, items: []const Value) !IdSet {+ const msgs = try fold(a, items, true);+ var calls: IdSet = .empty;+ var answered: IdSet = .empty;+ var bad: IdSet = .empty;+ for (msgs) |m| {+ for (m.uses) |u| try calls.put(a, u.id, {});+ for (m.results) |r| {+ if (!calls.contains(r.id)) try bad.put(a, r.id, {});+ try answered.put(a, r.id, {});+ }+ }+ var it = calls.keyIterator();+ while (it.next()) |id| if (!answered.contains(id.*)) try bad.put(a, id.*, {});+ return bad;+}++/// Refuse a history that pairs worse than the one it replaces: a provider+/// rejects an orphaned result or an unanswered call on every request.+pub fn checkPairs(a: Allocator, before: []const Value, after: []const Value) !void {+ const was = try unpaired(a, before);+ const now = try unpaired(a, after);+ var it = now.keyIterator();+ while (it.next()) |id| if (!was.contains(id.*)) return error.UnpairedToolCall;+}diff --git a/src/jev_tool.zig b/src/jev_tool.zigindex 713551f1..80442ddd 100644--- a/src/jev_tool.zig+++ b/src/jev_tool.zig@@ -173,18 +173,7 @@ fn usageCount(v: Value) ?i64 {return if (v == .integer and v.integer >= 0) v.integer else null;}-fn settledCharge(body: Value) ?u64 {- if (body != .object) return null;- const receipt = body.object.get("codegraff_billing") orelse return null;- if (receipt != .object) return null;- const settled = receipt.object.get("settled") orelse return null;- const currency = receipt.object.get("currency") orelse return null;- const charge = receipt.object.get("charge_micro_usd") orelse return null;- if (settled != .bool or !settled.bool or currency != .string or- !std.mem.eql(u8, currency.string, "USD") or charge != .integer or- charge.integer < 0 or charge.integer > 9_007_199_254_740_991) return null;- return @intCast(charge.integer);-}+const settledCharge = @import("pricing_gateway.zig").settledCharge;fn noteGatewayUsage(io: Io, tally: *pricing.CostTally, arena: Allocator, raw: []const u8) void {const parsed = std.json.parseFromSliceLeaky(Value, arena, raw, .{}) catch {diff --git a/src/main.zig b/src/main.zigindex f27d22f0..1620f551 100644--- a/src/main.zig+++ b/src/main.zig@@ -593,7 +593,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = .{ @import("acp_agents.zig"), @import("repo_context_tests.zig") };_ = .{ @import("subagent_activity.zig"), @import("subagent_interactive.zig"), @import("subagent_recovery.zig"), @import("subagent_retained.zig"), @import("subagent_run_tests.zig") };_ = .{ @import("acp_agent_activity.zig"), @import("acp_subagent_live.zig"), @import("acp_line_writer.zig") };- _ = .{ @import("acp_replay.zig"), @import("python_version.zig"), @import("jev_auto.zig"), @import("background_wait.zig") };+ _ = .{ @import("acp_replay.zig"), @import("python_version.zig"), @import("jev_auto.zig"), @import("background_wait.zig"), @import("gateway_compact_tests.zig") };_ = @import("read_image.zig");_ = .{ @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig"), @import("review_deadline.zig"), @import("issue_cmd.zig"), @import("shell_tool.zig"), @import("acp_ask.zig"), @import("side_steer.zig"), @import("task_workspace_tests.zig"), @import("workspace_prepare_tests.zig"), @import("worktree_reap.zig") };}diff --git a/src/picker_auth.zig b/src/picker_auth.zigindex 19f8c3ad..61da6bef 100644--- a/src/picker_auth.zig+++ b/src/picker_auth.zig@@ -109,6 +109,7 @@ pub fn reloadLoginKey(root: *Agent, keys: *Keys, arena: Allocator, provider_id:}if (std.mem.eql(u8, provider_id, "codegraff") and jev_tool.setCodegraffLoginKey(root.io, codegraff_key))root.invalidateRootTools();+ if (std.mem.eql(u8, provider_id, "codegraff")) @import("gateway_compact.zig").setLoginKey(root.io, codegraff_key);if (std.mem.eql(u8, provider_id, "codex") and keys.get("codex") != null)root.reloadModelCatalog(keys.*);}diff --git a/src/pricing_gateway.zig b/src/pricing_gateway.zigindex c797d775..4c78d50b 100644--- a/src/pricing_gateway.zig+++ b/src/pricing_gateway.zig@@ -45,3 +45,18 @@ pub fn find(model: []const u8) ?ModelPrice {for (rows) |p| if (std.mem.eql(u8, p.name, model)) return p;return null;}++/// A gateway endpoint's settled charge receipt, or null when it is missing,+/// unsettled, or malformed: a published list rate never stands in for one.+pub fn settledCharge(body: std.json.Value) ?u64 {+ if (body != .object) return null;+ const receipt = body.object.get("codegraff_billing") orelse return null;+ if (receipt != .object) return null;+ const settled = receipt.object.get("settled") orelse return null;+ const currency = receipt.object.get("currency") orelse return null;+ const charge = receipt.object.get("charge_micro_usd") orelse return null;+ if (settled != .bool or !settled.bool or currency != .string or+ !std.mem.eql(u8, currency.string, "USD") or charge != .integer or+ charge.integer < 0 or charge.integer > 9_007_199_254_740_991) return null;+ return @intCast(charge.integer);+}diff --git a/src/repl_compact.zig b/src/repl_compact.zigindex 4112e4b8..54c35d94 100644--- a/src/repl_compact.zig+++ b/src/repl_compact.zig@@ -92,11 +92,13 @@ pub fn replCompactCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const replcv.list().* = agent.messages;cv.compaction_window = agent.compaction_window;};+ const hosted_seq = @import("gateway_compact.zig").seq();const n = agent.manualCompact() catch |err| {out.note = (switch (err) {error.EmptySummary => gpa.dupe(u8, "compaction failed: empty summary, history unchanged"),error.IncompleteSummary => gpa.dupe(u8, "compaction failed: incomplete summary, history unchanged"),error.ApiError => gpa.dupe(u8, "compaction failed: provider error, history unchanged"),+ error.CompactionOff => gpa.dupe(u8, "compaction is off: Codegraff credits are used up"),else => gpa.dupe(u8, "compaction failed, history unchanged"),}) catch "";return false;@@ -126,6 +128,10 @@ pub fn replCompactCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const replturns.append(.{ .role = role, .text = text }) catch gpa.free(text);}out.turns = turns.toOwnedSlice() catch &.{};- out.note = std.fmt.allocPrint(gpa, "history compacted to a {d}-char summary", .{n}) catch "";+ var line_buf: [160]u8 = undefined;+ out.note = if (@import("gateway_compact.zig").seq() != hosted_seq)+ gpa.dupe(u8, @import("gateway_compact.zig").lastLine(c.io, &line_buf)) catch ""+ else+ std.fmt.allocPrint(gpa, "history compacted to a {d}-char summary", .{n}) catch "";return true;}diff --git a/src/session_settings.zig b/src/session_settings.zigindex 38175aa0..85db6389 100644--- a/src/session_settings.zig+++ b/src/session_settings.zig@@ -70,6 +70,7 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {main_mod.g_path_env = try arena.dupe(u8, environ_map.get("PATH") orelse "");plugins.applyEnv(environ_map);jev_tool.configure(environ_map);+ try @import("gateway_compact.zig").configure(arena, environ_map); // ADR 0252: GRAFF_HOSTED_COMPACT, GRAFF_COMPACT_URL/_MODELmain_mod.g_codedb_guard = environ_map.get("GRAFF_NO_CODEDB_GUARD") == null; // issue #626 guard, opt-out via envjob_idle.applyEnv(environ_map); // #199: background-job idle warn/stop, minutes (0 = off)@import("run_idle.zig").applyEnv(environ_map); // GRAFF_HEARTBEAT_SECS: a waiting run's heartbeat (0 = off)@@ -276,7 +277,9 @@ fn codegraffLoginKey(io: Io, arena: Allocator, environ_map: anytype) ?[]const u8pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out: *Io.Writer, flags: args.Flags, use_color: bool, json_mode: bool, cwd_display: []const u8) !ThemeSetup {try applyEnvKnobs(arena, environ_map);@import("python_version.zig").detect(io, environ_map.get("PATH")); // ADR 0242: before any catalog renders- _ = jev_tool.setCodegraffLoginKey(io, codegraffLoginKey(io, arena, environ_map));+ const codegraff_key = codegraffLoginKey(io, arena, environ_map);+ _ = jev_tool.setCodegraffLoginKey(io, codegraff_key);+ @import("gateway_compact.zig").setLoginKey(io, codegraff_key); // ADR 0252: the login also compactsskills.loadSkillSettings(io, arena); // per-skill opt-outs, also gates the auto-connectanim.loadAnimationSetting(io, arena); // {"animation": "..."} → thinking spinner choiceanim.loadThemeSetting(io, arena); // {"theme": "<name>"} → opt-in terminal color theme