Skip to content

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

Python

feat(compact): A/B the server-side compaction for real users (#compact-ab)

Rach Pradhan08151b07c73b
diff --git a/evals/compact_ab/README.md b/evals/compact_ab/README.md
new file mode 100644
index 00000000..80457b8d
--- /dev/null
+++ b/evals/compact_ab/README.md
@@ -0,0 +1,59 @@
+# Compaction A/B: server-side vs client-side vs none
+
+Pre-ship benchmark behind the `#compact-ab` telemetry experiment
+(`src/agent_server_compact.zig`). Question: at a forced-low compaction
+threshold (~16.3k tokens, `GRAFF_COMPACT_PCT=6` on the 272k window), which
+compaction strategy preserves coding-task recall best, and at what cost?
+
+## Task
+
+`gen_compact_bench.py` writes a frozen synthetic Zig codebase
+(`alpha…foxtrot.zig`, ~500 lines each, 12 planted `audit anchor` constants)
+plus a one-line audit prompt: read all six files in full, then write
+`answer.md` with 10 of the constants. Facts sit mid-file, and questions span
+all six files, so a wrong answer means compaction destroyed early-file recall.
+`GRAFF_TOOL_HANDLE_BYTES=262144` keeps full file contents in history (defeats
+the #440 spill) so context actually crosses the threshold; `--yolo` because
+scripted stdin sessions cannot approve writes (#unattended-gate).
+
+## Arms
+
+| arm | env |
+|---|---|
+| server | `GRAFF_SERVER_COMPACT=1 GRAFF_COMPACT_PCT=6` |
+| client | `GRAFF_SERVER_COMPACT=0 GRAFF_COMPACT_PCT=6` |
+| none | `GRAFF_SERVER_COMPACT=0 GRAFF_COMPACT_PCT=100` |
+
+`run_compact_bench.sh wave N` runs one trial per arm in parallel; `score_compact_bench.py`
+grades `answer.md` against `questions.json` and counts compaction notices.
+
+## Results (gpt-5.6-sol, 2 trials/arm, 2026-08-10)
+
+| run | score | compactions | wall | API calls | ctx tokens processed |
+|---|---|---|---|---|---|
+| none1 | 10/10 | 0 | 60s | 16 | 638k |
+| none2 | 10/10 | 0 | 63s | 16 | 635k |
+| server1 | 10/10 | 8 | 254s | 16 | 264k |
+| server2 | 10/10 | 9 | 207s | 16 | 266k |
+| client1 | 10/10 | 18 | 360s | 34 | 500k |
+| client2 | 10/10 | 18 | 341s | 34 | 483k |
+
+Read: recall tied at 10/10 everywhere at this scale. Forced to compact,
+server-side dominated client-side on every cost axis (2.4× fewer tokens, no
+extra round-trips — client burned 18 summary calls plus amnesia re-reads —
+and ~40% less wall time). Not compacting beat both, as expected when the
+workload fits the window: compaction is insurance, not a free lunch.
+
+Known risk shape (observed in a pre-`--yolo` harness run): when forward
+progress is blocked for an unrelated reason, aggressive server-side pruning
+can erase "I already tried that" state and amplify a retry loop (25
+compactions, no progress). Watch the `compact_ab` telemetry for arm=server
+sessions with high prune_items counts and no turn completions.
+
+## Telemetry (the real A/B)
+
+In production each install is bucketed 50/50 by anonymous install id
+(`armForId`). OTLP records: body=`experiment`, kind=`compact_ab`, detail ∈
+`arm=server|arm=client` (once per process), `prune_items=N` (per server
+prune), `summary_chars=N` (per client summary on the Responses wire).
+`GRAFF_SERVER_COMPACT=0|1` forces an arm (and skips assignment).
diff --git a/evals/compact_ab/gen_compact_bench.py b/evals/compact_ab/gen_compact_bench.py
new file mode 100644
index 00000000..bc4e023e
--- /dev/null
+++ b/evals/compact_ab/gen_compact_bench.py
@@ -0,0 +1,114 @@
+#!/usr/bin/env python3
+"""Generate the frozen compaction-benchmark codebase into /tmp/compact_bench/src.
+
+Six deterministic Zig-ish files (~400 lines each), each carrying planted
+constants. facts.json holds ground truth; prompt.txt asks for 10 of them.
+The facts are planted mid-file so the agent must read each file fully, and
+the questions span all six files so post-compaction recall of EARLY files
+is what separates the arms.
+"""
+import json, os, random, shutil
+
+BASE = "/tmp/compact_bench"
+SRC = os.path.join(BASE, "src")
+rng = random.Random(20260210)
+
+FILES = ["alpha", "beta", "gamma", "delta", "epsilon", "foxtrot"]
+WORDS = ("meridian harlow pistil cinder vortex lattice ember quorum "
+ "solace thresh welkin bramble copse falcon garnet hollow "
+ "indigo jasper kindle lantern marrow numen obsidian palisade").split()
+
+def filler_fn(name, i):
+ acc = rng.randint(2, 9)
+ lines = [f"fn {name}_{i:03d}(ledger: *Ledger, entry: Entry) !u64 {{"]
+ lines.append(f" var acc: u64 = entry.checksum ^ {rng.randint(100, 999)};")
+ for j in range(rng.randint(3, 6)):
+ op = rng.choice(["+", "-", "^", "*"])
+ lines.append(f" acc = acc {op} (@as(u64, {rng.randint(3, 977)}) +% ledger.salt[{j} % 8]);")
+ lines.append(f" if (acc % {rng.randint(3, 17)} == 0) acc +%= {rng.randint(11, 555)};")
+ lines.append(f" return acc *% {acc};")
+ lines.append("}")
+ return "\n".join(lines)
+
+facts = {} # const name -> value (string form)
+used = set()
+
+def plant(lines, fname, fidx):
+ """Insert a planted constant at a random position; record the fact."""
+ word = rng.choice([w for w in WORDS if w not in used])
+ used.add(word)
+ cname = f"{word.upper()}_{fname.upper()[:6]}"
+ if rng.random() < 0.5:
+ val = str(rng.randint(10_000, 99_999))
+ decl = f'pub const {cname}: u64 = {val}; // audit anchor'
+ else:
+ val = f"{word}-{rng.randint(100, 999)}"
+ decl = f'pub const {cname} = "{val}"; // audit anchor'
+ pos = rng.randint(len(lines) // 4, 3 * len(lines) // 4)
+ lines.insert(pos, decl)
+ facts[cname] = val
+
+os.makedirs(SRC, exist_ok=True)
+for fidx, fname in enumerate(FILES):
+ lines = [
+ f"//! {fname}.zig — archival ledger segment {fidx} of the benchmark codebase.",
+ "",
+ "const std = @import(\"std\");",
+ "const Ledger = @import(\"ledger.zig\").Ledger;",
+ "const Entry = @import(\"ledger.zig\").Entry;",
+ "",
+ ]
+ for i in range(38): # ~400+ lines of filler per file
+ lines.append(filler_fn(fname, i))
+ lines.append("")
+ plant(lines, fname, fidx)
+ plant(lines, fname, fidx) # two facts per file, 12 total
+ with open(os.path.join(SRC, f"{fname}.zig"), "w") as f:
+ f.write("\n".join(lines) + "\n")
+
+# a tiny ledger.zig so the imports look real
+with open(os.path.join(SRC, "ledger.zig"), "w") as f:
+ f.write("//! shared types\n\npub const Ledger = struct { salt: [8]u64 };\n"
+ "pub const Entry = struct { checksum: u64, route: u32 };\n")
+
+with open(os.path.join(BASE, "facts.json"), "w") as f:
+ json.dump(facts, f, indent=2)
+
+# 10 questions spanning all six files (order matches reading order stress:
+# half the questions are about the first two files read).
+items = list(facts.items())
+qidxs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
+questions = []
+for qi, fi in enumerate(qidxs, 1):
+ cname, _ = items[fi]
+ ffile = cname.split("_")[-1].lower()
+ # map suffix back to file name
+ for fname in FILES:
+ if fname.upper()[:6] == cname.split("_")[-1]:
+ ffile = fname
+ break
+ questions.append((qi, cname, ffile))
+
+with open(os.path.join(BASE, "questions.json"), "w") as f:
+ json.dump([{"q": q, "const": c, "file": fn, "expect": facts[c]} for q, c, fn in questions], f, indent=2)
+
+qlines = "\n".join(f"Q{q}: What is the exact value of the constant {c} in src/{fn}.zig?" for q, c, fn in questions)
+prompt = f"""You are auditing a small Zig codebase in ./src (files: {', '.join(f + '.zig' for f in FILES)}, plus ledger.zig).
+
+Rules, in order:
+1. Read EACH of the six files completely, one at a time, in this order: {', '.join(FILES)}. Use full-file reads (read_file without a range, or ranges that cover the whole file). Do NOT use search/grep tools to shortcut — the audit requires complete reads.
+2. After all six reads, write a file answer.md in the current directory containing EXACTLY 10 lines in this format (no prose, no code fences):
+Q1: <value>
+...
+Q10: <value>
+
+The questions:
+{qlines}
+
+Values must be exact: integers without quotes, strings WITH their quotes. After writing answer.md, reply with DONE.
+"""
+with open(os.path.join(BASE, "prompt.txt"), "w") as f:
+ f.write(prompt)
+
+total = sum(os.path.getsize(os.path.join(SRC, fn)) for fn in os.listdir(SRC))
+print(f"generated {len(os.listdir(SRC))} files, {total/1024:.0f} KB total, {len(facts)} facts, 10 questions")
diff --git a/evals/compact_ab/run_compact_bench.sh b/evals/compact_ab/run_compact_bench.sh
new file mode 100644
index 00000000..d1ca7e04
--- /dev/null
+++ b/evals/compact_ab/run_compact_bench.sh
@@ -0,0 +1,39 @@
+#!/bin/bash
+# Compaction-arms benchmark driver v2: --yolo (unattended writes), wall-time
+# tracking, full contents in history (spill defeated), one turn per run.
+# Arms: server (context_management), client (classic summary), none (baseline).
+set -u
+B=/tmp/compact_bench
+GRAFF=$HOME/.local/bin/graff
+mkdir -p $B/runs
+
+run_one() {
+ local arm=$1 trial=$2
+ local d=$B/runs/${arm}${trial}
+ rm -rf "$d"; mkdir -p "$d"; cp -r $B/src "$d"/
+ local envs
+ case $arm in
+ server) envs="GRAFF_SERVER_COMPACT=1 GRAFF_COMPACT_PCT=6";;
+ client) envs="GRAFF_SERVER_COMPACT=0 GRAFF_COMPACT_PCT=6";;
+ none) envs="GRAFF_SERVER_COMPACT=0 GRAFF_COMPACT_PCT=100";;
+ esac
+ envs="$envs GRAFF_TOOL_HANDLE_BYTES=262144"
+ echo "== ${arm}${trial} start $(date +%H:%M:%S)"
+ local t0=$(date +%s)
+ (cd "$d" && env $envs "$GRAFF" --yolo --new --model gpt-5.6-sol < $B/prompt.txt > out.log 2>&1)
+ local rc=$?
+ echo "$(( $(date +%s) - t0 ))" > "$d/wall_seconds"
+ echo "== ${arm}${trial} exit=$rc wall=$(cat $d/wall_seconds)s"
+}
+
+if [ "${1:-}" = "wave" ]; then
+ # one trial per arm in parallel (wave $2)
+ run_one server "$2" & run_one client "$2" & run_one none "$2" & wait
+else
+ for trial in 1 2; do
+ for arm in server client none; do
+ run_one $arm $trial
+ done
+ done
+fi
+echo "ALL DONE"
diff --git a/evals/compact_ab/score_compact_bench.py b/evals/compact_ab/score_compact_bench.py
new file mode 100644
index 00000000..7470df59
--- /dev/null
+++ b/evals/compact_ab/score_compact_bench.py
@@ -0,0 +1,60 @@
+#!/usr/bin/env python3
+"""Score compaction-benchmark runs: correctness + compaction counts + cost/time."""
+import json, os, re, sys, glob
+
+B = "/tmp/compact_bench"
+qs = json.load(open(f"{B}/questions.json"))
+
+def score_run(d):
+ out = {"run": os.path.basename(d.rstrip("/"))}
+ log = open(os.path.join(d, "out.log"), errors="replace").read()
+ out["server_compacts"] = log.count("[server compacted context")
+ out["client_compacts"] = log.count("[history compacted to") + log.count("[compacting ~")
+ out["done"] = "DONE" in log
+ wall = os.path.join(d, "wall_seconds")
+ out["wall"] = open(wall).read().strip() + "s" if os.path.exists(wall) else "?"
+ # answers
+ path = os.path.join(d, "answer.md")
+ answers = {}
+ if os.path.exists(path):
+ for line in open(path, errors="replace"):
+ m = re.match(r"Q(\d+):\s*(.+?)\s*$", line)
+ if m:
+ answers[int(m.group(1))] = m.group(2)
+ correct, wrong = 0, []
+ for q in qs:
+ got = answers.get(q["q"])
+ exp = q["expect"]
+ ok = got is not None and (got == exp or got.strip('"') == exp.strip('"'))
+ if ok:
+ correct += 1
+ else:
+ wrong.append(f'Q{q["q"]}({q["file"]}): got {got!r} want {exp!r}')
+ out["score"] = f"{correct}/10"
+ out["wrong"] = wrong
+ # token/time metrics from the session jsonl trace if present
+ traces = glob.glob(os.path.join(d, ".graff/traces/*.jsonl"))
+ if traces:
+ reqs = toks = 0
+ for line in open(traces[0], errors="replace"):
+ try:
+ ev = json.loads(line)
+ except json.JSONDecodeError:
+ continue
+ if ev.get("ev") == "api":
+ reqs += 1
+ toks += ev.get("context_tokens", 0) or 0
+ out["api_calls"] = reqs
+ out["sum_context_tokens"] = toks
+ return out
+
+runs = sorted(glob.glob(f"{B}/runs/*/"), key=os.path.getmtime)
+if len(sys.argv) > 1:
+ runs = [d for d in runs if any(a in d for a in sys.argv[1:])]
+print(f"{'run':<10} {'score':<6} {'srvCmp':<6} {'cliCmp':<6} {'done':<5} {'wall':<6} {'api':<4} {'sumCtxTok':<10}")
+for d in runs:
+ r = score_run(d)
+ print(f"{r['run']:<10} {r['score']:<6} {r['server_compacts']:<6} {r['client_compacts']:<6} "
+ f"{str(r['done']):<5} {r['wall']:<6} {r.get('api_calls','?'):<4} {r.get('sum_context_tokens','?'):<10}")
+ for w in r["wrong"]:
+ print(" ", w)
diff --git a/src/agent_compact.zig b/src/agent_compact.zig
index e2feec57..1c93b863 100644
--- a/src/agent_compact.zig
+++ b/src/agent_compact.zig
@@ -18,6 +18,7 @@ const goal_flow = @import("goal_flow.zig");
const prompts = @import("prompts.zig");
const handoff_note = @import("compact_handoff_note.zig"); // #411: both halves of "what survives a compaction"
const compact_note_glue = @import("compact_note_glue.zig"); // #391
+const server_compact = @import("agent_server_compact.zig"); // #compact-ab telemetry
const messages_mod = @import("messages.zig");
const textMessage = messages_mod.textMessage;
@@ -222,6 +223,10 @@ pub fn compact(self: *Agent) anyerror!usize {
// prefix, so mutating the system prompt here costs nothing extra. Root-only
// and once per session — prompts.noteSessionCompacted owns both rules.
prompts.noteSessionCompacted(self, self.arena);
+ // A/B control arm doing work (#compact-ab): a client-side summary on the
+ // Responses wire. Manual /compact on codex lands here too — correctly
+ // labeled, since it IS a client compaction.
+ if (self.provider.kind == .responses) server_compact.noteClientSummary(summary.len);
if (!main_mod.json_mode) try self.say("[history compacted to a {d}-char summary]\n", .{summary.len});
return summary.len;
}
diff --git a/src/agent_request_body.zig b/src/agent_request_body.zig
index 94527f4d..f0ff8793 100644
--- a/src/agent_request_body.zig
+++ b/src/agent_request_body.zig
@@ -247,8 +247,7 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo
server_compact.noteExposure(self);
try server_compact.writeContextManagement(self, &s);
// No top-level max_output_tokens: the codex backend rejects it
- // ("Unsupported parameter") on gpt-5.6-* models, hard-failing every
- // turn; codex itself only sets it as a tool argument.
+ // ("Unsupported parameter") on gpt-5.6-* — codex sets it only as a tool argument.
try s.objectField("stream");
try s.write(true);
},
diff --git a/src/agent_server_compact.zig b/src/agent_server_compact.zig
index cfd87d81..1bea6e2c 100644
--- a/src/agent_server_compact.zig
+++ b/src/agent_server_compact.zig
@@ -22,18 +22,80 @@
//! ladder (agent_overflow.zig) is the safety net.
const std = @import("std");
+const Io = std.Io;
const main_mod = @import("main.zig");
const Agent = @import("agent.zig").Agent;
const Provider = @import("provider.zig").Provider;
+const telemetry = @import("telemetry.zig");
+const keys_cli = @import("keys_cli.zig");
-/// GRAFF_SERVER_COMPACT=0/false/off opts back out to client-side summaries
-/// (session_settings.applyEnvKnobs). Default: on for .responses providers.
+/// GRAFF_SERVER_COMPACT=0/false/off forces the client arm, =1 forces the
+/// server arm (session_settings.applyEnvKnobs). Default: A/B assignment.
pub var g_server_compact_override: ?bool = null;
+/// A/B assignment (#compact-ab): 50/50, bucketed by the anonymous install id
+/// so a person's arm is stable across sessions and machines stay whole-user
+/// consistent. Set once per process by assignArm (startup); null means
+/// unassigned, which behaves as the client arm (the pre-feature default).
+var g_ab_arm: ?bool = null;
+
+/// Pure bucketing: true = server arm. Deterministic on the install id.
+pub fn armForId(id: *const [32]u8) bool {
+ return (std.hash.Wyhash.hash(0, id) & 1) == 0;
+}
+
+/// Startup hook (session_settings.setupSkillsAndTheme): bucket this install.
+/// The env override wins outright, so no assignment is made when it is set.
+pub fn assignArm(io: Io, arena: std.mem.Allocator, home: []const u8) void {
+ if (g_server_compact_override != null or g_ab_arm != null) return;
+ const id = keys_cli.loadOrCreateId(io, arena, home, ".simple-harness-install-id");
+ g_ab_arm = armForId(&id);
+}
+
+/// Is the server-compaction path active for this provider?
pub fn enabled(p: Provider) bool {
if (p.kind != .responses) return false;
if (g_server_compact_override) |o| return o;
- return true;
+ return g_ab_arm orelse false;
+}
+
+/// One OTLP log record: body="experiment", kind="compact_ab", detail carries
+/// the fact ("arm=server", "prune_items=5", "summary_chars=8481"). Static or
+/// numeric content only — never user text. No-op without a telemetry sink.
+fn pushExp(detail: []const u8) void {
+ const t = telemetry.g_telem orelse return;
+ if (!t.on()) return;
+ const dup = t.gpa.dupe(u8, detail) catch "";
+ t.mutex.lockUncancelable(t.io);
+ t.push(.{ .t_ms = t.elapsedMsLocked(), .body = "experiment", .kind = "compact_ab", .detail = dup });
+ t.mutex.unlock(t.io);
+ t.maybeFlushEvents();
+}
+
+var g_ab_noted = false; // one exposure record per process; a race double-counts harmlessly
+
+/// Record which arm this session is in (both arms, so the control group is
+/// visible). Called from the Responses request-body builder on every build;
+/// the flag makes it once per process.
+pub fn noteExposure(self: *Agent) void {
+ if (g_ab_noted or self.provider.kind != .responses) return;
+ g_ab_noted = true;
+ pushExp(if (enabled(self.provider)) "arm=server" else "arm=client");
+}
+
+/// Record a successful server-side prune (the treatment arm doing work).
+fn notePrune(dropped: usize) void {
+ var buf: [24]u8 = undefined;
+ const d = std.fmt.bufPrint(&buf, "prune_items={d}", .{dropped}) catch return;
+ pushExp(d);
+}
+
+/// Record a successful client-side summary on a .responses provider — the
+/// control arm doing work (auto at >=95%, or manual /compact on codex).
+pub fn noteClientSummary(chars: usize) void {
+ var buf: [28]u8 = undefined;
+ const d = std.fmt.bufPrint(&buf, "summary_chars={d}", .{chars}) catch return;
+ pushExp(d);
}
/// Emit the compaction directive on a Responses request body. The threshold
@@ -42,6 +104,10 @@ pub fn enabled(p: Provider) bool {
/// have.
pub fn writeContextManagement(self: *const Agent, s: anytype) !void {
if (!enabled(self.provider)) return;
+ try writeContextManagementBody(self, s);
+}
+
+fn writeContextManagementBody(self: *const Agent, s: anytype) !void {
try s.objectField("context_management");
try s.beginArray();
try s.beginObject();
@@ -62,7 +128,11 @@ pub fn writeContextManagement(self: *const Agent, s: anytype) !void {
/// such histories are left to the client-side path. In practice the trailing
/// blob lands at a response boundary where pairs are complete.
pub fn pruneToLatestBlob(self: *Agent) bool {
- if (!enabled(self.provider)) return false;
+ return pruneIf(self, enabled(self.provider));
+}
+
+fn pruneIf(self: *Agent, server_arm: bool) bool {
+ if (!server_arm or self.provider.kind != .responses) return false;
const items = self.messages.items;
var blob_idx: ?usize = null;
for (items, 0..) |m, i| {
@@ -104,6 +174,7 @@ pub fn pruneToLatestBlob(self: *Agent) bool {
self.context_local_tokens = 0;
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 {};
return true;
}
@@ -113,11 +184,15 @@ pub fn pruneToLatestBlob(self: *Agent) bool {
/// between-turns checks). Non-responses providers get the legacy policy
/// unchanged.
pub fn autocompact(self: *Agent, recovery_meter: u64) void {
- if (!enabled(self.provider)) {
+ autocompactIf(self, recovery_meter, enabled(self.provider));
+}
+
+fn autocompactIf(self: *Agent, recovery_meter: u64, server_arm: bool) void {
+ if (!server_arm or self.provider.kind != .responses) {
self.compactOrRecover(self.provider.nearContextLimit(recovery_meter));
return;
}
- if (pruneToLatestBlob(self)) return;
+ if (pruneIf(self, true)) return;
// No blob yet: the server compacts in-stream at the same threshold, so
// trust it at the ordinary compactAt line; the client-side summary (and
// its destructive fallback) is reserved for genuinely near the wall, where
@@ -147,17 +222,26 @@ fn item(a: std.mem.Allocator, typ: []const u8, call_id: ?[]const u8) !std.json.V
return .{ .object = obj };
}
-test "enabled: responses-only, override wins both ways" {
+test "enabled: responses-only; unassigned defaults to client; override wins" {
var p: Provider = .{ .id = "codex", .kind = .responses, .auth = .bearer, .url = "", .api_key = "k", .model = "m", .context = 272_000 };
- try std.testing.expect(enabled(p));
+ try std.testing.expect(!enabled(p)); // no assignment in tests → client arm
p.kind = .anthropic;
try std.testing.expect(!enabled(p));
p.kind = .openai;
try std.testing.expect(!enabled(p));
p.kind = .responses;
+ g_server_compact_override = true;
+ try std.testing.expect(enabled(p));
g_server_compact_override = false;
- defer g_server_compact_override = null;
try std.testing.expect(!enabled(p));
+ g_server_compact_override = null;
+}
+
+test "armForId: deterministic bucketing of the install id" {
+ const id: [32]u8 = "0123456789abcdef0123456789abcdef".*;
+ try std.testing.expectEqual(armForId(&id), armForId(&id));
+ const other: [32]u8 = "ffffffffffffffffffffffffffffffff".*;
+ _ = armForId(&other); // both buckets are reachable outcomes; no crash, pure
}
test "writeContextManagement: threshold mirrors compactAt; silent for other kinds" {
@@ -168,7 +252,7 @@ test "writeContextManagement: threshold mirrors compactAt; silent for other kind
var aw: @import("std").Io.Writer.Allocating = .init(a);
var s: std.json.Stringify = .{ .writer = &aw.writer };
try s.beginObject();
- try writeContextManagement(&agent, &s);
+ try writeContextManagementBody(&agent, &s);
try s.endObject();
try std.testing.expect(std.mem.indexOf(u8, aw.written(), "\"context_management\":[{\"type\":\"compaction\",\"compact_threshold\":80000}]") != null); // 80% of 100k
agent.provider.kind = .anthropic;
@@ -186,13 +270,13 @@ test "pruneToLatestBlob: no blob or blob-first leaves history untouched" {
const a = arena_state.allocator();
var agent = testAgent(a, .responses);
try agent.messages.append(try item(a, "message", null));
- try std.testing.expect(!pruneToLatestBlob(&agent));
+ try std.testing.expect(!pruneIf(&agent, true));
try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
// blob already at the head: nothing to prune
var agent2 = testAgent(a, .responses);
try agent2.messages.append(try item(a, "compaction", null));
try agent2.messages.append(try item(a, "message", null));
- try std.testing.expect(!pruneToLatestBlob(&agent2));
+ try std.testing.expect(!pruneIf(&agent2, true));
try std.testing.expectEqual(@as(usize, 2), agent2.messages.items.len);
try std.testing.expectEqual(@as(u32, 0), agent2.history_rewrites);
}
@@ -210,7 +294,7 @@ test "pruneToLatestBlob: prunes to the newest blob and resets the meters" {
try agent.messages.append(try item(a, "function_call_output", "c1"));
agent.last_context_tokens = 200_000;
agent.context_local_tokens = 190_000;
- try std.testing.expect(pruneToLatestBlob(&agent));
+ try std.testing.expect(pruneIf(&agent, true));
try std.testing.expectEqual(@as(usize, 3), agent.messages.items.len);
try std.testing.expectEqualStrings("compaction", agent.messages.items[0].object.get("type").?.string);
try std.testing.expectEqual(@as(u32, 1), agent.history_rewrites);
@@ -226,18 +310,18 @@ test "pruneToLatestBlob: an orphaned tool output refuses the prune" {
try agent.messages.append(try item(a, "function_call", "c1")); // pruned by the cut
try agent.messages.append(try item(a, "compaction", null));
try agent.messages.append(try item(a, "function_call_output", "c1")); // orphan if pruned
- try std.testing.expect(!pruneToLatestBlob(&agent));
+ try std.testing.expect(!pruneIf(&agent, true));
try std.testing.expectEqual(@as(usize, 3), agent.messages.items.len);
}
-test "pruneToLatestBlob: never fires for non-responses providers" {
+test "pruneIf: never fires off the server arm or off responses" {
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
const a = arena_state.allocator();
var agent = testAgent(a, .anthropic);
try agent.messages.append(try item(a, "message", null));
try agent.messages.append(try item(a, "compaction", null));
- try std.testing.expect(!pruneToLatestBlob(&agent));
+ try std.testing.expect(!pruneIf(&agent, true));
try std.testing.expectEqual(@as(usize, 2), agent.messages.items.len);
}
@@ -250,7 +334,7 @@ test "autocompact: responses providers hold at the ordinary threshold without a
// Over the 80% compactAt line but under the 95% wall, no blob: the server
// owns compaction now, so history must survive untouched (legacy policy
// would have run a summary here).
- autocompact(&agent, 85_000);
+ autocompactIf(&agent, 85_000, true);
try std.testing.expectEqual(@as(usize, 1), agent.messages.items.len);
try std.testing.expectEqual(@as(u32, 0), agent.history_rewrites);
}