Skip to content

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

Python

feat(mcp): learnt slim of fat MCP results + muscle playbook

Cursor Agentca9cd217498b
diff --git a/docs/adr/0029-mcp-inside-rlm-and-return-shapes.md b/docs/adr/0029-mcp-inside-rlm-and-return-shapes.md
index e1c40dd4..2d5e0a5e 100644
--- a/docs/adr/0029-mcp-inside-rlm-and-return-shapes.md
+++ b/docs/adr/0029-mcp-inside-rlm-and-return-shapes.md
@@ -133,3 +133,13 @@ print(len, project)`). It is the **token vertex**. H is the **wall
vertex**. There is still no point that wins both. Warm shapes (K) did
not help J. Do not ship rlm-as-default for this MCP task; keep
len/project so the token vertex is reachable.
+
+## Learnt slim (the muscle, not another hint)
+
+Shapes on the load result did not change grok-4.6's path (I still never
+called `rlm`). The learnt part is therefore applied in Zig: after
+`remember()` of the fat payload, `takeSlim` / `print()` drop
+`description`/`body` and fold comment arrays to `{n, latest_author}`.
+When two MCP shapes are stored, `annotate` adds a one-line `# muscle:`
+playbook on the load **result** (never the catalog prefix). No new
+`GRAFF_` knob. Live L–Q sweep: `eval-mcp-shapes.py --only L,M,N,O,P,Q`.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 24a45f9c..8d77e61a 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -39,7 +39,7 @@ record only when you need the evidence or the edge cases.
| [0026](0026-foreground-bash-auto-backgrounds.md) | Root foreground `bash` auto-backgrounds after 120s (or `timeout` ms); it is not killed. Subagents still kill at 120s (#93). |
| [0027](0027-kimi-identity-is-graff.md) | Kimi Coding User-Agent is `graff/<version>`, not a spoofed `kimi-code-cli` token. X-Msh device fields follow kimi-code's shapes. |
| [0028](0028-codex-session-id-is-the-cache-key.md) | Codex HTTP/WS `session_id` is the `prompt_cache_key` (openai/codex ModelClient default), not a per-process random UUID. |
-| [0029](0029-mcp-inside-rlm-and-return-shapes.md) | Loaded MCP tools are rlm host functions; persist return shapes on the load result, never the prefix. Measured vs `--old`. |
+| [0029](0029-mcp-inside-rlm-and-return-shapes.md) | Loaded MCP tools are rlm host functions; persist return shapes on the load result, never the prefix; fat MCP results auto-slim from learnt keys. |
## When to write one
diff --git a/graff-evals/README.md b/graff-evals/README.md
index ddf3cf44..c5fcc19c 100644
--- a/graff-evals/README.md
+++ b/graff-evals/README.md
@@ -20,7 +20,7 @@ harness under test spends model calls.
| `core` | sequential single-file work (instruction, debug, git, schema, …) |
| `rlm` | scatter-gather / multi-file reads (where default rlm can overlap) |
| `swe` | DeepSWE-shaped multi-file bugfixes, distilled from [deepswe.datacurve.ai/run](https://deepswe.datacurve.ai/run) (no Harbor/Docker) |
-| `mcp` | Linear-shaped fixture MCP (Blacksmith code-mode + muscle memory). Use `--no-lean` harnesses. Variants include warm shapes, quiet `print()`, and no-`each()` prompts. |
+| `mcp` | Linear-shaped fixture MCP (Blacksmith code-mode + muscle memory). Use `--no-lean` harnesses. Variants include warm shapes, quiet `print()`, no-`each()` prompts, and learnt slim (L–Q). |
```sh
./run.py --suite swe --harness graff-dev-old,graff-dev --model grok-4.6 -j 12
diff --git a/scripts/eval-mcp-pareto.py b/scripts/eval-mcp-pareto.py
index d6c2253c..e964fcb5 100644
--- a/scripts/eval-mcp-pareto.py
+++ b/scripts/eval-mcp-pareto.py
@@ -91,7 +91,7 @@ def live_row(variant: str) -> dict | None:
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--history", action="store_true", help="do not drive a provider")
- ap.add_argument("--only", default="A,H,J,K", help="live variant ids")
+ ap.add_argument("--only", default="L,M,N,O,P,Q", help="live variant ids")
args = ap.parse_args()
points = [dict(p) for p in HISTORY]
diff --git a/scripts/eval-mcp-shapes.py b/scripts/eval-mcp-shapes.py
index c169c18e..6ff57737 100755
--- a/scripts/eval-mcp-shapes.py
+++ b/scripts/eval-mcp-shapes.py
@@ -100,6 +100,42 @@ VARIANTS = [
"task": "linear-reduce-warm",
"label": "rlm+MCP host, warm, len/project recipe",
},
+ {
+ "id": "L",
+ "harness": "graff-dev-nolean",
+ "task": "linear-nohint-warm",
+ "label": "learnt slim + playbook, no each() hint, warm",
+ },
+ {
+ "id": "M",
+ "harness": "graff-dev-nolean",
+ "task": "linear-warm",
+ "label": "learnt slim + each() hint, warm",
+ },
+ {
+ "id": "N",
+ "harness": "graff-dev-nolean",
+ "task": "linear-nohint",
+ "label": "learnt slim mid-run, no each() hint, cold",
+ },
+ {
+ "id": "O",
+ "harness": "graff-dev-nolean",
+ "task": "linear-quiet",
+ "label": "learnt slim, quiet print, cold",
+ },
+ {
+ "id": "P",
+ "harness": "graff-dev-nolean",
+ "task": "linear-reduce",
+ "label": "learnt slim + len/project recipe, cold",
+ },
+ {
+ "id": "Q",
+ "harness": "graff-dev-nolean",
+ "task": "linear-reduce-warm",
+ "label": "learnt slim + len/project recipe, warm",
+ },
]
diff --git a/src/exec.zig b/src/exec.zig
index a7d89714..4480cd83 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -211,7 +211,11 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
return failure(gpa, err);
};
if (r.is_error) codedbpro_report.onFailure(ctx, call.name, r.text);
- if (!r.is_error) @import("mcp_shapes.zig").remember(ctx, call.name, r.text);
+ if (!r.is_error) {
+ const shapes = @import("mcp_shapes.zig");
+ shapes.remember(ctx, call.name, r.text);
+ return .{ .text = shapes.takeSlim(gpa, r.text), .is_error = false };
+ }
return .{ .text = r.text, .is_error = r.is_error };
}
diff --git a/src/mcp_shapes.zig b/src/mcp_shapes.zig
index 1206e59e..de927f5e 100644
--- a/src/mcp_shapes.zig
+++ b/src/mcp_shapes.zig
@@ -280,6 +280,141 @@ fn closeBase(io: Io, opened: Opened, _: ?[]const u8) void {
}
}
+/// Fat enough that dumping the bind is the token problem C/D/F hit.
+pub const slim_min_bytes: usize = 800;
+
+const identity_keys = [_][]const u8{ "id", "identifier", "title", "name" };
+
+/// Learnt projection: identity keys on issue-like rows; comments fold to
+/// `{n, latest_author}`. Values of `description`/`body` never survive.
+/// Returns null when the payload is small, not a JSON array of objects, or
+/// has nothing to cut. Caller owns a non-null result.
+pub fn slim(alloc: Allocator, payload: []const u8) ?[]u8 {
+ if (payload.len < slim_min_bytes) return null;
+ const trimmed = std.mem.trim(u8, payload, " \t\r\n");
+ const parsed = std.json.parseFromSlice(Value, alloc, trimmed, .{}) catch return null;
+ defer parsed.deinit();
+ const items = arrayItems(parsed.value) orelse return null;
+ if (items.len == 0 or items[0] != .object) return null;
+ if (looksLikeComments(items[0].object)) return slimComments(alloc, items);
+ return slimIdentity(alloc, items);
+}
+
+/// Remember the fat payload, then replace it with the learnt cut when one
+/// exists. `text` is owned by `gpa`.
+pub fn takeSlim(gpa: Allocator, text: []u8) []u8 {
+ const cut = slim(gpa, text) orelse return text;
+ gpa.free(text);
+ return cut;
+}
+
+fn arrayItems(v: Value) ?[]const Value {
+ if (v == .array) return v.array.items;
+ if (v != .object) return null;
+ var it = v.object.iterator();
+ while (it.next()) |e| {
+ if (e.value_ptr.* == .array) return e.value_ptr.array.items;
+ }
+ return null;
+}
+
+fn looksLikeComments(obj: std.json.ObjectMap) bool {
+ return obj.get("body") != null and obj.get("author") != null;
+}
+
+fn slimComments(alloc: Allocator, items: []const Value) ?[]u8 {
+ var latest_i: usize = items.len - 1;
+ var latest_at: []const u8 = "";
+ for (items, 0..) |item, i| {
+ if (item != .object) continue;
+ const at = if (item.object.get("createdAt")) |c| (if (c == .string) c.string else "") else "";
+ if (at.len == 0) continue;
+ if (latest_at.len == 0 or std.mem.order(u8, at, latest_at) == .gt) {
+ latest_at = at;
+ latest_i = i;
+ }
+ }
+ const name = authorName(items[latest_i]);
+ var aw: Io.Writer.Allocating = .init(alloc);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ s.beginObject() catch {
+ aw.deinit();
+ return null;
+ };
+ s.objectField("n") catch {
+ aw.deinit();
+ return null;
+ };
+ s.write(items.len) catch {
+ aw.deinit();
+ return null;
+ };
+ s.objectField("latest_author") catch {
+ aw.deinit();
+ return null;
+ };
+ s.write(name orelse "") catch {
+ aw.deinit();
+ return null;
+ };
+ s.endObject() catch {
+ aw.deinit();
+ return null;
+ };
+ return aw.toOwnedSlice() catch null;
+}
+
+fn authorName(item: Value) ?[]const u8 {
+ if (item != .object) return null;
+ const author = item.object.get("author") orelse return null;
+ if (author == .string) return author.string;
+ if (author != .object) return null;
+ const n = author.object.get("name") orelse return null;
+ return if (n == .string) n.string else null;
+}
+
+fn slimIdentity(alloc: Allocator, items: []const Value) ?[]u8 {
+ if (!hasIdentity(items[0].object)) return null;
+ var aw: Io.Writer.Allocating = .init(alloc);
+ var s: std.json.Stringify = .{ .writer = &aw.writer };
+ s.beginArray() catch {
+ aw.deinit();
+ return null;
+ };
+ for (items) |item| {
+ if (item != .object) continue;
+ s.beginObject() catch {
+ aw.deinit();
+ return null;
+ };
+ for (identity_keys) |k| {
+ const v = item.object.get(k) orelse continue;
+ s.objectField(k) catch {
+ aw.deinit();
+ return null;
+ };
+ s.write(v) catch {
+ aw.deinit();
+ return null;
+ };
+ }
+ s.endObject() catch {
+ aw.deinit();
+ return null;
+ };
+ }
+ s.endArray() catch {
+ aw.deinit();
+ return null;
+ };
+ return aw.toOwnedSlice() catch null;
+}
+
+fn hasIdentity(obj: std.json.ObjectMap) bool {
+ for (identity_keys) |k| if (obj.get(k) != null) return true;
+ return false;
+}
+
/// Splice stored shapes onto a load_tool_schemas / search RESULT. Never call
/// this from catalog render (ADR 0011 prefix must stay byte-stable).
pub fn annotate(gpa: Allocator, arena: Allocator, io: Io, cwd: ?[]const u8, text: []const u8) ![]const u8 {
@@ -294,6 +429,11 @@ pub fn annotate(gpa: Allocator, arena: Allocator, io: Io, cwd: ?[]const u8, text
while (it.next()) |e| {
try aw.writer.print(" {s}: {s}\n", .{ e.key_ptr.*, e.value_ptr.* });
}
+ if (store.map.count() >= 2) {
+ try aw.writer.writeAll(
+ "# muscle: fat MCP print() auto-slims (id/title; comments → n+latest_author). issues=list_issues(); comments=each(issues,\"list_comments\",\"id\"); print(len(issues), project(issues,\"id\"), project(comments,\"latest_author\"))\n",
+ );
+ }
return aw.toOwnedSlice();
}
@@ -354,5 +494,67 @@ test "remember merges keys; annotate splices shapes; prefix text is untouched" {
const annotated = try annotate(gpa, arena_state.allocator(), io, dir, "1 tool schema(s) below\nmcp__linear__list_issues");
try std.testing.expect(std.mem.indexOf(u8, annotated, "return_shapes") != null);
try std.testing.expect(std.mem.indexOf(u8, annotated, "mcp__linear__list_issues") != null);
+ try std.testing.expect(std.mem.indexOf(u8, annotated, "muscle:") == null);
try std.testing.expect(std.mem.indexOf(u8, @import("mcp_schema_gate.zig").tool_desc, "return_shapes") == null);
+ try std.testing.expect(std.mem.indexOf(u8, @import("rlm.zig").tool_desc, "muscle:") == null);
+}
+
+test "slim drops description/body; comments fold to n and latest_author" {
+ const gpa = std.testing.allocator;
+ try std.testing.expect(slim(gpa, "[{\"id\":1}]") == null);
+ const pad: [400]u8 = @splat('x');
+ const pad_s: []const u8 = &pad;
+ const issues = try std.fmt.allocPrint(gpa, "[{{\"id\":\"ISS-1\",\"identifier\":\"ENG-101\",\"title\":\"Login\",\"description\":\"{s}\",\"body\":\"KEEP-OUT\"}},{{\"id\":\"ISS-2\",\"identifier\":\"ENG-102\",\"title\":\"Tax\",\"description\":\"{s}\"}}]", .{ pad_s, pad_s });
+ defer gpa.free(issues);
+ const cut = slim(gpa, issues) orelse return error.ExpectedSlim;
+ defer gpa.free(cut);
+ try std.testing.expect(std.mem.indexOf(u8, cut, "ISS-1") != null);
+ try std.testing.expect(std.mem.indexOf(u8, cut, "ENG-101") != null);
+ try std.testing.expect(std.mem.indexOf(u8, cut, "Login") != null);
+ try std.testing.expect(std.mem.indexOf(u8, cut, "description") == null);
+ try std.testing.expect(std.mem.indexOf(u8, cut, "KEEP-OUT") == null);
+ try std.testing.expect(std.mem.indexOf(u8, cut, pad_s) == null);
+
+ const comments = try std.fmt.allocPrint(gpa, "[{{\"body\":\"old {s}\",\"author\":{{\"name\":\"ada\"}},\"createdAt\":\"2026-08-11T01:00:00Z\"}},{{\"body\":\"new {s}\",\"author\":{{\"name\":\"bev\"}},\"createdAt\":\"2026-08-12T02:00:00Z\"}}]", .{ pad_s, pad_s });
+ defer gpa.free(comments);
+ const folded = slim(gpa, comments) orelse return error.ExpectedCommentSlim;
+ defer gpa.free(folded);
+ try std.testing.expect(std.mem.indexOf(u8, folded, "\"n\":2") != null);
+ try std.testing.expect(std.mem.indexOf(u8, folded, "bev") != null);
+ try std.testing.expect(std.mem.indexOf(u8, folded, "ada") == null);
+ try std.testing.expect(std.mem.indexOf(u8, folded, "old ") == null);
+ try std.testing.expect(std.mem.indexOf(u8, folded, pad_s) == null);
+}
+
+test "annotate writes a muscle playbook once two MCP shapes are stored" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;
+ const n = try tmp.dir.realPath(io, &path_buf);
+ const dir = path_buf[0..n];
+ reset(gpa, io);
+ defer reset(gpa, io);
+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer dummy_client.deinit();
+ const ctx: ToolCtx = .{
+ .gpa = gpa,
+ .io = io,
+ .client = &dummy_client,
+ .provider = undefined,
+ .registry = null,
+ .from_sub = false,
+ .approvals = null,
+ .tracer = null,
+ .agent_cwd = dir,
+ };
+ remember(ctx, "mcp__linear__list_issues", "[{\"id\":\"A\"}]");
+ remember(ctx, "mcp__linear__list_comments", "[{\"body\":\"b\",\"author\":\"ada\"}]");
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const annotated = try annotate(gpa, arena_state.allocator(), io, dir, "2 tool schema(s)");
+ try std.testing.expect(std.mem.indexOf(u8, annotated, "muscle:") != null);
+ try std.testing.expect(std.mem.indexOf(u8, annotated, "each(") != null);
+ try std.testing.expect(std.mem.indexOf(u8, @import("mcp_schema_gate.zig").tool_desc, "muscle:") == null);
}
diff --git a/src/rlm.zig b/src/rlm.zig
index 0690bc56..f4e7c03d 100644
--- a/src/rlm.zig
+++ b/src/rlm.zig
@@ -163,9 +163,7 @@ fn runHost(ctx: ToolCtx, call: spec_ptc.Call) ToolOutput {
return .{ .text = ctx.gpa.dupe(u8, "rlm: bad args") catch &.{}, .is_error = true };
};
defer parsed.deinit();
- const out = exec_mod.execTool(ctx, .{ .id = "rlm", .name = ready.name, .input = parsed.value });
- if (!out.is_error and rlm_mcp.looksMcp(ready.name)) mcp_shapes.remember(ctx, ready.name, out.text);
- return out;
+ return exec_mod.execTool(ctx, .{ .id = "rlm", .name = ready.name, .input = parsed.value });
}
fn runSleep(ctx: ToolCtx, args_json: []const u8) ToolOutput {
@@ -242,18 +240,23 @@ fn renderPrint(ctx: ToolCtx, arena: Allocator, inner: []const u8, binds: []const
fn renderPrintPart(ctx: ToolCtx, arena: Allocator, inner: []const u8, binds: []const Binding, claimed: *std.StringHashMap(ToolOutput)) ![]const u8 {
const t = std.mem.trim(u8, inner, " \t");
if (t.len >= 2 and (t[0] == '"' or t[0] == '\'') and t[t.len - 1] == t[0]) return t[1 .. t.len - 1];
- if (rlm_reduce.evalExpr(arena, t, binds)) |text| return text else |_| {}
+ if (rlm_reduce.evalExpr(arena, t, binds)) |text| return maybeSlim(arena, text) else |_| {}
var i = binds.len;
while (i > 0) {
i -= 1;
- if (std.mem.eql(u8, binds[i].name, t)) return binds[i].text;
+ if (std.mem.eql(u8, binds[i].name, t)) return maybeSlim(arena, binds[i].text);
}
if (try spec_ptc.extractCall(arena, t)) |c| {
const key = try c.key(arena);
- if (claimed.get(key)) |hit| return try arena.dupe(u8, hit.text);
+ if (claimed.get(key)) |hit| return maybeSlim(arena, hit.text);
const out = runHost(ctx, c);
defer ctx.gpa.free(out.text);
+ if (mcp_shapes.slim(arena, out.text)) |s| return s;
return try arena.dupe(u8, out.text);
}
return try arena.dupe(u8, t);
}
+
+fn maybeSlim(arena: Allocator, payload: []const u8) []const u8 {
+ return mcp_shapes.slim(arena, payload) orelse payload;
+}