graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(rlm): showcase on context ≥50% of compactAt
Cursor Agent0ddf002e9e1d
diff --git a/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md b/docs/adr/0022-rlm-is-opt-in-speculative-ptc.mdindex 04b65803..3e12b8ba 100644--- a/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md+++ b/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md@@ -85,8 +85,8 @@ regression* without a catalog tax. Per-task swings are one-rep variance.- Semicolons (outside strings) are statements, so a one-line script stillspeculates. Host positional fields include `bash` / `webfetch`. `print(a, b)`joins binds. Do not splice `system_note` onto the always-on prefix- (ADR 0011 / 0030): small turns hide `rlm` until `--rlm` or a wide- native batch. sPTC stays wired for after unfold.+ (ADR 0011 / 0030): small turns hide `rlm` until `--rlm`, a wide+ native batch, or context ≥50% of compactAt. sPTC stays wired for after unfold.- Scatter-gather tasks live in the `rlm` eval suite (`graff-evals/run.py--suite rlm`). Default `--suite all` runs core + rlm + swe. Measured2026-08-25 on grok-4.6 (one rep): both **4/4**, native **86.8s / 53564diff --git a/docs/adr/0030-rlm-late-showcase.md b/docs/adr/0030-rlm-late-showcase.mdindex 2af5dd1a..13f955dd 100644--- a/docs/adr/0030-rlm-late-showcase.md+++ b/docs/adr/0030-rlm-late-showcase.md@@ -18,23 +18,41 @@ only runs when an `rlm` script streams. Listing `rlm` is what invitesspeculation — and on grok-4.6, an `each()` hint is a footgun (ADR 0029).Showcasing because MCP slims would push Linear back into that dialect.+Zhang / Li / Khattab (MGH, 2026) argue the other half: RLM's job is+length generalization — expanding the decomposition space so the root+can chunk near-infinite context — not replacing structured tools on+short in-distribution turns. Their 32k/1-needle RL curriculum is how a+small model *learns* that decomposition; it is not a production+token-floor. A naive "fat first payload" trigger is the MCP-slim case+already rejected. The signal that matches the paper is the existing+session meter (`effectiveContextTokens` / `compactAt`): the root is+actually seeing OOD-length context.+## DecisionFold `rlm` whenever it is available, including `--lean`. Omit it fromthe Folded-native listing and from `composeBase` / lean notes until a-showcase. Do not splice `system_note` onto the prefix (ADR 0011).+showcase. Do not splice `system_note` onto the prefix (ADR 0011). Do+not put `rlm` in the `load_tool_schemas` listing: that rewrites the+tools **head**. Discovery is `markLoaded` so the next catalog carries+the schema on the **tail**.-Showcase (listing + `markLoaded`, so the next catalog can carry the-schema and sPTC is live) when:+Showcase when:- `--rlm` / `setFromCli(true)` — immediate;- a structured batch of **≥4 native** host tools (`read_file`, `codedb`,`bash`, `webfetch`) — the scatter-gather that sPTC overlaps;+- `effectiveContextTokens() ≥ 50%` of `provider.compactAt()` — the+ existing overflow meter, not a second counter;- explicit `load_tool_schemas tools=["rlm"]` (already `markLoaded`).+`GRAFF_RLM_CONTEXT` overrides the size gate: unset = 50% of compactAt;+`0`/`off` disables; `1`–`100` or `50%` is a percent; `32k` / `32768`+is an absolute floor (Zhang's curriculum, opt-in).+Do **not** showcase on MCP-only fan-out, first slim, or fat-payloadsize. `/new` and `/clear` hide a session-discovered showcase; `--rlm`-sticks for the process.+sticks for the process. `--old` resets discovery.## Consequences@@ -42,6 +60,10 @@ sticks for the process.sPTC invitation. Token win is prefix + listing, not another hint.- Scatter-gather one-shots pay one wide native batch, then see `rlm`and can stream-speculate. `--rlm` skips the wait.+- A long session (or a huge user paste) that crosses half of compactAt+ gets the RLM decomposition space without a prefix essay. Tools-head+ bytes stay identical; only the tail grows.- Auto-load on a confident `rlm` call still works (`gateExec`).- Revisit if a measured coding one-shot regresses to N serial reads- because the model never emits a 4-wide batch and never sees `rlm`.+ because the model never emits a 4-wide batch, never crosses 50% of+ compactAt, and never sees `rlm`.diff --git a/src/agent.zig b/src/agent.zigindex ab228c8c..f2d88f2e 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -362,6 +362,15 @@ pub const Agent = struct {self.autocompact(recovery_meter);self.closeCodexWs();}+ // ADR 0030: showcase rlm once the existing compact meter is+ // actually large. Schema rides the tail; head bytes stay put.+ if (!self.sub) {+ const fold = @import("native_fold.zig");+ if (fold.noticeContext(self.effectiveContextTokens(), self.provider.compactAt())) {+ self.invalidateRootTools();+ try self.ensureRootTools(self.provider.kind);+ }+ }const hist_len = self.messages.items.len;const root = try self.request(if (self.text_only) null else self.toolsJson());const done = switch (self.provider.kind) {diff --git a/src/mcp_schema_gate.zig b/src/mcp_schema_gate.zigindex 6aa352f8..5d9a5f46 100644--- a/src/mcp_schema_gate.zig+++ b/src/mcp_schema_gate.zig@@ -508,7 +508,9 @@ pub fn descWithListing(arena: Allocator, all: []const mcp.Tool) ![]const u8 {if (native_fold.anyFolded() and !@import("no_local_tools.zig").lean) {for (native_fold.folded) |name| {if (!native_fold.isFolded(name)) continue;- if (std.mem.eql(u8, name, "rlm") and !native_fold.listed()) continue;+ // rlm never rides the meta desc: listing it on showcase would+ // rewrite the tools head (ADR 0011 / 0030). Discovery is the tail.+ if (std.mem.eql(u8, name, "rlm")) continue;if (!g_stable_catalog and native_fold.isLoaded(name)) continue;if (tool_surface.hideBuiltin(name)) continue;try natives.append(arena, name);diff --git a/src/native_fold.zig b/src/native_fold.zigindex d71f1652..dc385bf5 100644--- a/src/native_fold.zig+++ b/src/native_fold.zig@@ -72,11 +72,80 @@ pub fn isFolded(name: []const u8) bool {return false;}-/// Session-discovered rlm (a wide native batch). `--rlm` sets `g_cli_forced`-/// so /new does not hide it again. Never set this because MCP slims.+/// Session-discovered rlm (wide native batch or context threshold). `--rlm`+/// sets `g_cli_forced` so /new does not hide it again. Never set this+/// because MCP slims or a fat first payload.var g_showcased: bool = false;var g_cli_forced: bool = false;+/// GRAFF_RLM_CONTEXT. Unset = 50% of `compactAt`. `0`/`off` disables.+/// `1`–`100` or `50%` is a percent of compactAt; `32k` / `32768` is an+/// absolute token floor. Zhang's 32k is an RL curriculum, not the default.+pub var g_context_off: bool = false;+pub var g_context_pct: ?u8 = null;+pub var g_context_tokens: ?u64 = null;++pub fn resetContextKnob() void {+ g_context_off = false;+ g_context_pct = null;+ g_context_tokens = null;+}++pub fn applyContextEnv(v: []const u8) void {+ const t = std.mem.trim(u8, v, " \t");+ if (t.len == 0) return;+ if (std.mem.eql(u8, t, "0") or std.ascii.eqlIgnoreCase(t, "off") or+ std.ascii.eqlIgnoreCase(t, "false") or std.ascii.eqlIgnoreCase(t, "no"))+ {+ g_context_off = true;+ g_context_pct = null;+ g_context_tokens = null;+ return;+ }+ g_context_off = false;+ if (std.mem.endsWith(u8, t, "%")) {+ if (std.fmt.parseInt(u8, std.mem.trim(u8, t[0 .. t.len - 1], " \t"), 10)) |n| {+ if (n > 0) g_context_pct = @min(n, 100);+ g_context_tokens = null;+ } else |_| {}+ return;+ }+ var num = t;+ var mul: u64 = 1;+ if (t.len > 1 and (t[t.len - 1] == 'k' or t[t.len - 1] == 'K')) {+ num = t[0 .. t.len - 1];+ mul = 1000;+ }+ const n = std.fmt.parseInt(u64, std.mem.trim(u8, num, " \t"), 10) catch return;+ if (n == 0) return;+ if (mul == 1 and n <= 100) {+ g_context_pct = @intCast(n);+ g_context_tokens = null;+ } else {+ g_context_tokens = n * mul;+ g_context_pct = null;+ }+}++/// Named threshold on the existing compact meter. `null` = disabled.+pub fn contextThreshold(compact_at: u64) ?u64 {+ if (g_context_off) return null;+ if (g_context_tokens) |abs| return abs;+ if (compact_at == 0) return null;+ const pct: u64 = g_context_pct orelse 50;+ return compact_at * pct / 100;+}++/// True when this sample newly showcased rlm (caller rebuilds the catalog).+pub fn noticeContext(tokens: u64, compact_at: u64) bool {+ if (listed() or !@import("rlm_spec.zig").available) return false;+ const threshold = contextThreshold(compact_at) orelse return false;+ if (tokens < threshold) return false;+ showcaseRlm();+ markLoaded("rlm");+ return true;+}+/// Folded-native listing and catalog discovery: hidden on small turns.pub fn listed() bool {return g_showcased or isLoaded("rlm");diff --git a/src/native_fold_rlm.zig b/src/native_fold_rlm.zigindex 43429683..caea1592 100644--- a/src/native_fold_rlm.zig+++ b/src/native_fold_rlm.zig@@ -12,6 +12,7 @@ const no_local = @import("no_local_tools.zig");fn isolate() void {fold.enabled = true;fold.resetRlmDiscovery();+ fold.resetContextKnob();}test "rlm joins the fold only while available (off under --old)" {@@ -76,10 +77,16 @@ test "folded rlm stays off the listing until showcase; off stays off" {fold.showcaseRlm();try std.testing.expect(fold.listed());+ // Name stays off the meta listing (that would rewrite the tools head).+ const still = try schema_mod.renderRootTools(arena, .openai, &with_rlm, &.{});+ try std.testing.expect(std.mem.indexOf(u8, still, "rlm") == null);+ try std.testing.expect(std.mem.indexOf(u8, still, "llm_query") == null);++ fold.markLoaded("rlm");const shown = try schema_mod.renderRootTools(arena, .openai, &with_rlm, &.{});try std.testing.expect(std.mem.indexOf(u8, shown, "rlm") != null);- try std.testing.expect(std.mem.indexOf(u8, shown, "llm_query") == null);- try std.testing.expect(std.mem.indexOf(u8, shown, rlm.tool_schema) == null);+ try std.testing.expect(std.mem.indexOf(u8, shown, "llm_query") != null);+ try std.testing.expect(std.mem.indexOf(u8, shown, rlm.tool_schema) != null);}test "lean keeps rlm folded until showcase; --rlm puts the schema on" {@@ -153,3 +160,105 @@ test "wide native batch showcases rlm; MCP fan-out does not" {fold.resetSession();try std.testing.expect(fold.listed());}++test "context below 50% of compactAt does not showcase; crossing it does" {+ const saved_spec = rlm_spec.available;+ defer {+ rlm_spec.available = saved_spec;+ fold.resetRlmDiscovery();+ fold.resetContextKnob();+ }+ isolate();+ rlm_spec.available = true;++ // Default: 50% of compactAt. compactAt=8000 → threshold 4000.+ try std.testing.expectEqual(@as(?u64, 4000), fold.contextThreshold(8000));+ try std.testing.expect(!fold.noticeContext(0, 8000));+ try std.testing.expect(!fold.noticeContext(3999, 8000));+ try std.testing.expect(!fold.listed());++ try std.testing.expect(fold.noticeContext(4000, 8000));+ try std.testing.expect(fold.listed());+ try std.testing.expect(fold.isLoaded("rlm"));+ try std.testing.expect(!fold.noticeContext(8000, 8000)); // already showcased++ fold.resetSession();+ try std.testing.expect(!fold.listed());+ try std.testing.expect(!fold.isLoaded("rlm"));++ fold.g_context_off = true;+ try std.testing.expect(!fold.noticeContext(8000, 8000));+ try std.testing.expect(!fold.listed());+}++test "lean first turn and MCP fan-out stay below the context trigger" {+ const saved_spec = rlm_spec.available;+ const saved_lean = no_local.lean;+ defer {+ rlm_spec.available = saved_spec;+ no_local.lean = saved_lean;+ fold.resetRlmDiscovery();+ fold.resetContextKnob();+ }+ isolate();+ rlm_spec.available = true;+ no_local.lean = true;++ // A small -p prompt is nowhere near 50% of a real compactAt.+ try std.testing.expect(!fold.noticeContext(800, 160_000));+ try std.testing.expect(!fold.listed());+ try std.testing.expect(!fold.noticeWideNative(&.{+ "mcp__linear__list_comments",+ "mcp__linear__list_comments",+ "mcp__linear__list_comments",+ "mcp__linear__list_comments",+ }));+ try std.testing.expect(!fold.listed());+}++test "showcasing rlm keeps the tools head bytes; schema rides the tail" {+ const saved_avail = rlm.available;+ const saved_spec = rlm_spec.available;+ const saved_stable = mcp_schema_gate.g_stable_catalog;+ defer {+ rlm.available = saved_avail;+ rlm_spec.available = saved_spec;+ rlm.sync();+ mcp_schema_gate.g_stable_catalog = saved_stable;+ fold.resetRlmDiscovery();+ fold.resetContextKnob();+ }+ isolate();+ mcp_schema_gate.g_stable_catalog = true;+ rlm.available = true;+ rlm.sync();++ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const specs = [_]schema_mod.ToolSpec{+ .{+ .name = mcp_schema_gate.tool_name,+ .desc = mcp_schema_gate.tool_desc,+ .schema = mcp_schema_gate.tool_schema,+ },+ .{ .name = "bash", .desc = "run a command", .schema = "{\"type\":\"object\"}" },+ .{ .name = rlm.tool_name, .desc = rlm.tool_desc, .schema = rlm.tool_schema },+ };++ const before = try schema_mod.renderRootTools(arena, .openai, &specs, &.{});+ try std.testing.expect(std.mem.indexOf(u8, before, "rlm") == null);+ try std.testing.expect(std.mem.indexOf(u8, before, rlm.tool_schema) == null);++ try std.testing.expect(fold.noticeContext(50_000, 80_000));+ const after = try schema_mod.renderRootTools(arena, .openai, &specs, &.{});+ try std.testing.expect(before.len >= 1 and before[before.len - 1] == ']');+ try std.testing.expect(std.mem.startsWith(u8, after, before[0 .. before.len - 1]));+ try std.testing.expect(after.len > before.len);+ try std.testing.expect(after[before.len - 1] == ',');+ try std.testing.expect(std.mem.indexOf(u8, after[before.len - 1 ..], rlm.tool_schema) != null);+ try std.testing.expect(std.mem.indexOf(u8, after[before.len - 1 ..], "llm_query") != null);++ fold.resetSession();+ try std.testing.expect(!fold.listed());+}diff --git a/src/rlm.zig b/src/rlm.zigindex 9cfdd3b1..f64a497e 100644--- a/src/rlm.zig+++ b/src/rlm.zig@@ -65,9 +65,9 @@ pub fn feedLive(ctx: ToolCtx, delta: []const u8) void {}/// Append `rlm` after the lean/no-local filters so a later showcase can-/// put the spec on the catalog. Folded and unlisted until `--rlm`, a-/// wide native batch, or an explicit load (ADR 0030). No-op when `--old`-/// or embedder mode stripped host tools.+/// put the spec on the catalog tail. Folded and unlisted until `--rlm`,+/// a wide native batch, context ≥50% of compactAt, or an explicit load+/// (ADR 0030). No-op when `--old` or embedder mode stripped host tools.pub fn maybeAppend(comptime Spec: type, arena: Allocator, specs: []const Spec) ![]const Spec {sync();if (!available or no_local_tools.enabled) return specs;diff --git a/src/session_settings.zig b/src/session_settings.zigindex 5c996042..bccb4adb 100644--- a/src/session_settings.zig+++ b/src/session_settings.zig@@ -137,6 +137,7 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {const off = std.mem.eql(u8, v, "0") or std.ascii.eqlIgnoreCase(v, "false") or std.ascii.eqlIgnoreCase(v, "off") or std.ascii.eqlIgnoreCase(v, "no");@import("rlm_mcp.zig").host_enabled = !off;}+ if (environ_map.get("GRAFF_RLM_CONTEXT")) |v| native_fold.applyContextEnv(v);}if (environ_map.get("GRAFF_NO_LOCAL_TOOLS")) |v| no_local_tools.enabled = no_local_tools.enabled or no_local_tools.envEnables(v);// GRAFF_LEAN: presence-based, matching session_start.leanModediff --git a/src/session_settings_tests.zig b/src/session_settings_tests.zigindex b550504a..4b65c4ff 100644--- a/src/session_settings_tests.zig+++ b/src/session_settings_tests.zig@@ -44,6 +44,7 @@ const knobs = [_]Knob{.{ .name = "GRAFF_CLOCK_SLEEP", .value = "1" },.{ .name = "GRAFF_RLM", .value = "1" },.{ .name = "GRAFF_RLM_MCP", .value = "0" },+ .{ .name = "GRAFF_RLM_CONTEXT", .value = "32k" },.{ .name = "GRAFF_OLD", .value = "1" },.{ .name = "GRAFF_NO_LOCAL_TOOLS", .value = "1" },.{ .name = "GRAFF_CODEX_WS_IDLE_SECS", .value = "11" },@@ -92,6 +93,9 @@ const Saved = struct {rlm: bool,rlm_cli: bool,rlm_mcp: bool,+ rlm_context_off: bool,+ rlm_context_pct: ?u8,+ rlm_context_tokens: ?u64,stream_stall_ms: u64,post_deadline_ms: u64,codex_ws_idle_ms: i64,@@ -118,6 +122,9 @@ const Saved = struct {.rlm = @import("rlm.zig").available,.rlm_cli = @import("rlm.zig").cli_set,.rlm_mcp = @import("rlm_mcp.zig").host_enabled,+ .rlm_context_off = @import("native_fold.zig").g_context_off,+ .rlm_context_pct = @import("native_fold.zig").g_context_pct,+ .rlm_context_tokens = @import("native_fold.zig").g_context_tokens,.stream_stall_ms = http.stream_stall_ms,.post_deadline_ms = http.post_deadline_ms,.codex_ws_idle_ms = agent_ws.codex_ws_idle_ms,@@ -146,6 +153,9 @@ const Saved = struct {@import("rlm.zig").cli_set = s.rlm_cli;@import("rlm.zig").sync();@import("rlm_mcp.zig").host_enabled = s.rlm_mcp;+ @import("native_fold.zig").g_context_off = s.rlm_context_off;+ @import("native_fold.zig").g_context_pct = s.rlm_context_pct;+ @import("native_fold.zig").g_context_tokens = s.rlm_context_tokens;http.stream_stall_ms = s.stream_stall_ms;http.post_deadline_ms = s.post_deadline_ms;agent_ws.codex_ws_idle_ms = s.codex_ws_idle_ms;@@ -204,6 +214,7 @@ test "applyEnvKnobs actually applies the values it reads" {plugins.disabled = false;mcp_schema_gate.g_stable_catalog = false;@import("xai_hosted.zig").enabled = true;+ @import("native_fold.zig").resetContextKnob();var asked: [knobs.len]bool = @splat(false);try session_settings.applyEnvKnobs(arena_state.allocator(), RecordingEnv{ .asked = &asked });@@ -226,6 +237,7 @@ test "applyEnvKnobs actually applies the values it reads" {try std.testing.expect(plugins.disabled);try std.testing.expect(mcp_schema_gate.g_stable_catalog); // GRAFF_STABLE_CATALOG=1 wins over GRAFF_NO_STABLE_CATALOG=1try std.testing.expect(!@import("xai_hosted.zig").enabled); // GRAFF_XAI_X_SEARCH=0+ try std.testing.expectEqual(@as(?u64, 32_000), @import("native_fold.zig").g_context_tokens);}const PairEnv = struct {@@ -289,6 +301,26 @@ test "GRAFF_STABLE_CATALOG=0 / GRAFF_NO_STABLE_CATALOG turn default-on catalog otry std.testing.expect(!mcp_schema_gate.g_stable_catalog);}+test "GRAFF_RLM_CONTEXT parses percent, absolute tokens, and off" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const saved = Saved.capture();+ defer saved.restore();+ const fold = @import("native_fold.zig");+ fold.resetContextKnob();+ try session_settings.applyEnvKnobs(arena_state.allocator(), PairEnv{ .pairs = &.{.{ .name = "GRAFF_RLM_CONTEXT", .value = "32k" }} });+ try std.testing.expectEqual(@as(?u64, 32_000), fold.g_context_tokens);+ try std.testing.expectEqual(@as(?u64, 32_000), fold.contextThreshold(200_000));+ fold.resetContextKnob();+ try session_settings.applyEnvKnobs(arena_state.allocator(), PairEnv{ .pairs = &.{.{ .name = "GRAFF_RLM_CONTEXT", .value = "50%" }} });+ try std.testing.expectEqual(@as(?u8, 50), fold.g_context_pct);+ try std.testing.expectEqual(@as(?u64, 40_000), fold.contextThreshold(80_000));+ fold.resetContextKnob();+ try session_settings.applyEnvKnobs(arena_state.allocator(), PairEnv{ .pairs = &.{.{ .name = "GRAFF_RLM_CONTEXT", .value = "off" }} });+ try std.testing.expect(fold.g_context_off);+ try std.testing.expectEqual(@as(?u64, null), fold.contextThreshold(80_000));+}+test "GRAFF_XAI_X_SEARCH=0 turns hosted x_search off" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();diff --git a/src/startup.zig b/src/startup.zigindex ebdde456..1e425e06 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -127,8 +127,9 @@ pub fn buildSystemPrompt(}if (unattended) sys_normal = try std.fmt.allocPrint(arena, "{s}{s}", .{ sys_normal, prompts.unattended_note });// ADR 0030 / 0011: do not splice rlm_spec.system_note onto the always-on- // prefix. Small turns must not advertise rlm/sPTC; discovery is listing- // or autoLoad after showcase (--rlm or a wide native batch).+ // prefix. Small turns must not advertise rlm/sPTC; discovery is the+ // catalog tail after showcase (--rlm, a wide native batch, or context+ // ≥50% of compactAt).// Codex-style skills: one capability line per installed optional// companion (skills_registry) — metadata in context, --help on demand.// Lean one-shots do not need companion essays (ADR 0024 prefix tax).