graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(rlm): speculate semicolon scripts and add a scatter eval suite
Cursor Agent7cf11594dbb5
diff --git a/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md b/docs/adr/0022-rlm-is-opt-in-speculative-ptc.mdindex 8b0b31aa..5822ad41 100644--- a/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md+++ b/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md@@ -70,3 +70,9 @@ regression* without a catalog tax. Per-task swings are one-rep variance.(`src/rlm_query.zig`). Nested spend is real; the host function exists sosPTC can overlap an expensive sub-LM with the rest of the script.- SDK / `--schema` do not list `rlm` until it graduates off the flag.+- Semicolons (outside strings) are statements, so a one-line script still+ speculates. Host positional fields include `bash` / `webfetch`. `print(a, b)`+ joins binds. A short system note is spliced only while the flag is on so+ the folded spec is discoverable without paying its schema.+- Scatter-gather tasks live in the `rlm` eval suite (`graff-evals/run.py+ --suite rlm`). Default `--suite all` runs core + rlm.diff --git a/graff-evals/run.py b/graff-evals/run.pyindex cc302837..2e9df85e 100755--- a/graff-evals/run.py+++ b/graff-evals/run.py@@ -7,7 +7,8 @@ drives any configured harness (harnesses.json) with any model, captures walltime / first-output latency / token usage, verifies the outcome, and writesJSONL results plus a summary table.- ./run.py --harness graff --model grok-4.6 # full suite+ ./run.py --harness graff --model grok-4.6 # full suite (core + rlm)+ ./run.py --suite rlm --harness graff-dev,graff-dev-rlm # scatter-gather A/B./run.py --harness grok --task fix-fib --reps 3 # one task, 3 reps./run.py --harness graff,grok --model grok-4.6 # side by side./run.py --interactive # pick + watch live@@ -206,6 +207,7 @@ def main():ap.add_argument("--harness", default="graff", help="comma-separated harness names (see harnesses.json)")ap.add_argument("--model", default=None, help="model id (default: per-harness default_model)")ap.add_argument("--task", action="append", help="task id filter (repeatable)")+ ap.add_argument("--suite", default="all", help="core, rlm, or all (default all)")ap.add_argument("--reps", type=int, default=1)ap.add_argument("--interactive", action="store_true", help="pick a task+harness, watch it live")args = ap.parse_args()@@ -219,7 +221,15 @@ def main():os.makedirs(RESULTS_DIR, exist_ok=True)stamp = time.strftime("%Y%m%d-%H%M%S")out_path = os.path.join(RESULTS_DIR, f"run-{stamp}.jsonl")- picked = {tid: t for tid, t in tasks.items() if not args.task or tid in args.task}+ suites = {s.strip() for s in args.suite.split(",") if s.strip()}+ picked = {}+ for tid, t in tasks.items():+ if args.task and tid not in args.task:+ continue+ suite = t.get("suite", "core")+ if "all" not in suites and suite not in suites:+ continue+ picked[tid] = trecords = []with open(out_path, "w") as f:for hname in args.harness.split(","):diff --git a/graff-evals/tasks/13-multi-read.json b/graff-evals/tasks/13-multi-read.jsonnew file mode 100644index 00000000..99633d61--- /dev/null+++ b/graff-evals/tasks/13-multi-read.json@@ -0,0 +1,14 @@+{+ "id": "multi-read",+ "suite": "rlm",+ "category": "scatter",+ "prompt": "Each of a.txt, b.txt, c.txt, and d.txt has one token on its first line. Write tokens.txt with those four tokens, one per line, in that file order. Do not invent tokens.",+ "files": {+ "a.txt": "ALPHA-9\nnoise a\n",+ "b.txt": "BRAVO-2\nnoise b\n",+ "c.txt": "CHARLIE-7\nnoise c\n",+ "d.txt": "DELTA-4\nnoise d\n"+ },+ "check": "python3 -c \"t=open('tokens.txt').read().split(); assert t[:4]==['ALPHA-9','BRAVO-2','CHARLIE-7','DELTA-4'], t\"",+ "timeout_s": 180+}diff --git a/graff-evals/tasks/14-scatter-sum.json b/graff-evals/tasks/14-scatter-sum.jsonnew file mode 100644index 00000000..c88c9790--- /dev/null+++ b/graff-evals/tasks/14-scatter-sum.json@@ -0,0 +1,14 @@+{+ "id": "scatter-sum",+ "suite": "rlm",+ "category": "scatter",+ "prompt": "n1.txt, n2.txt, n3.txt, and n4.txt each contain one integer. Write their sum as a bare integer (no spaces) to total.txt.",+ "files": {+ "n1.txt": "17\n",+ "n2.txt": "8\n",+ "n3.txt": "25\n",+ "n4.txt": "10\n"+ },+ "check": "test \"$(cat total.txt | tr -d ' \\n')\" = 60",+ "timeout_s": 180+}diff --git a/graff-evals/tasks/15-fanout-merge.json b/graff-evals/tasks/15-fanout-merge.jsonnew file mode 100644index 00000000..867b0e28--- /dev/null+++ b/graff-evals/tasks/15-fanout-merge.json@@ -0,0 +1,13 @@+{+ "id": "fanout-merge",+ "suite": "rlm",+ "category": "scatter",+ "prompt": "host.cfg, port.cfg, and name.cfg each hold one key=value line. Write merged.cfg containing all three keys (host, port, name) with those values, one key=value per line.",+ "files": {+ "host.cfg": "host=edge-7\n",+ "port.cfg": "port=8443\n",+ "name.cfg": "name=relay\n"+ },+ "check": "python3 -c \"t=open('merged.cfg').read(); assert 'host=edge-7' in t and 'port=8443' in t and 'name=relay' in t, t\"",+ "timeout_s": 180+}diff --git a/graff-evals/tasks/16-needle-files.json b/graff-evals/tasks/16-needle-files.jsonnew file mode 100644index 00000000..59c7fab0--- /dev/null+++ b/graff-evals/tasks/16-needle-files.json@@ -0,0 +1,15 @@+{+ "id": "needle-files",+ "suite": "rlm",+ "category": "scatter",+ "prompt": "Five notes (p1.txt through p5.txt). Exactly one contains a line NEEDLE=<word>. Write that word (the value only) to found.txt.",+ "files": {+ "p1.txt": "status=idle\nqueue=3\n",+ "p2.txt": "status=warm\nqueue=0\n",+ "p3.txt": "status=live\nNEEDLE=FOXTROT\nqueue=1\n",+ "p4.txt": "status=idle\nqueue=9\n",+ "p5.txt": "status=drain\nqueue=2\n"+ },+ "check": "test \"$(cat found.txt | tr -d ' \\n')\" = FOXTROT",+ "timeout_s": 180+}diff --git a/src/args.zig b/src/args.zigindex f3809cd1..f3d99f39 100644--- a/src/args.zig+++ b/src/args.zig@@ -177,6 +177,7 @@ pub fn parse(init: std.process.Init) !Flags {} else if (std.mem.eql(u8, arg, "--rlm")) {@import("rlm.zig").available = true; // ADR 0022: opt-in programmatic tool calling (also GRAFF_RLM=1)@import("rlm.zig").sync();+ @import("rlm.zig").sync();} else if (std.mem.eql(u8, arg, "--no-autocommit")) {main_mod.g_worktree_autocommit = false;} else if (std.mem.eql(u8, arg, "--schema")) {diff --git a/src/rlm.zig b/src/rlm.zigindex ff039146..5b9f6d88 100644--- a/src/rlm.zig+++ b/src/rlm.zig@@ -21,9 +21,9 @@ const rlm_query = @import("rlm_query.zig");const rlm_spec = @import("rlm_spec.zig");pub const tool_name = "rlm";-pub const tool_desc = "Programmatic tool calling (RLM + sPTC). Run a short Python-like script whose functions ARE this session's tools. Independent read_file/codedb/sleep_ms/llm_query calls with literal arguments start in parallel as the script streams (speculated), then print() is the answer. llm_query(prompt) is a tools-off sub-LM call. Example: a = read_file(\"src/main.zig\"); b = codedb(\"status\"); print(a); print(b). No imports, no control flow — assignments and calls only. Prefer this over N separate tool calls when the reads do not depend on each other.";+pub const tool_desc = "Programmatic tool calling (RLM + sPTC). Run a short Python-like script whose functions ARE this session's tools. Independent read_file/codedb/bash/webfetch/sleep_ms/llm_query calls with literal arguments start in parallel as the script streams (speculated), then print() is the answer. Semicolons or newlines separate statements. llm_query(prompt) is a tools-off sub-LM call. Example: a = read_file(\"src/main.zig\"); b = codedb(\"status\"); print(a, b). No imports, no control flow — assignments and calls only. Prefer this over N separate tool calls when the work does not depend on itself.";pub const tool_schema =- \\{"type": "object", "properties": {"code": {"type": "string", "description": "Python-like script: name = read_file(\"path\") / codedb(\"command\") / sleep_ms(ms) / llm_query(\"prompt\"); print(...) is the result"}}, "required": ["code"]}+ \\{"type": "object", "properties": {"code": {"type": "string", "description": "Python-like script: name = read_file(\"path\") / codedb(\"command\") / bash(\"cmd\") / sleep_ms(ms) / llm_query(\"prompt\"); print(...) is the result. Semicolons or newlines separate statements."}}, "required": ["code"]};/// Process-global: `--rlm` / GRAFF_RLM=1. Never flipped mid-session.@@ -84,21 +84,16 @@ pub fn runScript(ctx: ToolCtx, code: []const u8) !ToolOutput {}rlm_spec.takeLive(ctx, &claimed, arena);- var stmts: std.ArrayList([]const u8) = .empty;- var it = std.mem.splitScalar(u8, code, '\n');- while (it.next()) |raw| {- const line = std.mem.trim(u8, raw, " \t\r");- if (line.len > 0) try stmts.append(arena, line);- }+ const stmts = try spec_ptc.splitStatements(arena, code);- const calls = try spec_ptc.extractCalls(arena, stmts.items);+ const calls = try spec_ptc.extractCalls(arena, stmts);try speculate(ctx, arena, calls, &claimed);var binds: std.ArrayList(Binding) = .empty;var printed: std.ArrayList(u8) = .empty;defer printed.deinit(ctx.gpa);- for (stmts.items) |stmt| {+ for (stmts) |stmt| {if (try evalStmt(ctx, arena, stmt, binds.items, &claimed, &printed, &binds)) |err| {return .{ .text = err, .is_error = true };}@@ -191,6 +186,17 @@ fn printArgs(stmt: []const u8) ?[]const u8 {}fn renderPrint(arena: Allocator, inner: []const u8, binds: []const Binding) ![]const u8 {+ const parts = try spec_ptc.splitTopLevel(arena, inner, ',');+ if (parts.len == 0) return "";+ var out: std.ArrayList(u8) = .empty;+ for (parts, 0..) |part, i| {+ if (i > 0) try out.append(arena, '\n');+ try out.appendSlice(arena, try renderPrintPart(arena, part, binds));+ }+ return out.toOwnedSlice(arena);+}++fn renderPrintPart(arena: Allocator, inner: []const u8, binds: []const Binding) ![]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];for (binds) |b| if (std.mem.eql(u8, b.name, t)) return b.text;@@ -278,6 +284,24 @@ test "runScript reads a fixture via speculated read_file and prints it" {try std.testing.expect(std.mem.indexOf(u8, out.text, "hello-rlm") != null);}+test "runScript splits a semicolon one-liner and prints both binds" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer dummy_client.deinit();+ const saved = available;+ defer available = saved;+ available = true;+ const ctx = testCtx(gpa, io, &dummy_client);+ const t0: Io.Timestamp = .now(io, .awake);+ const out = try runScript(ctx, "a = sleep_ms(40); b = sleep_ms(41); print(a, b)");+ defer gpa.free(out.text);+ const dt = t0.untilNow(io, .awake).toMilliseconds();+ try std.testing.expect(!out.is_error);+ try std.testing.expectEqualStrings("slept 40ms\nslept 41ms", out.text);+ try std.testing.expect(dt < 90);+}+test "feedLive launches sleeps before runScript, so claim is a hit not a re-run" {const gpa = std.testing.allocator;const io = std.testing.io;@@ -301,3 +325,25 @@ test "feedLive launches sleeps before runScript, so claim is a hit not a re-run"try std.testing.expectEqualStrings("slept 40ms", out.text);try std.testing.expect(dt < 100);}++test "feedLive splits a semicolon line before runScript claims" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer dummy_client.deinit();+ const saved = available;+ defer {+ available = saved;+ resetLive(gpa, io);+ }+ available = true;+ const ctx = testCtx(gpa, io, &dummy_client);+ const t0: Io.Timestamp = .now(io, .awake);+ feedLive(ctx, "a = sleep_ms(40); b = sleep_ms(41)\n");+ const out = try runScript(ctx, "a = sleep_ms(40); b = sleep_ms(41); print(a, b)");+ defer gpa.free(out.text);+ const dt = t0.untilNow(io, .awake).toMilliseconds();+ try std.testing.expect(!out.is_error);+ try std.testing.expectEqualStrings("slept 40ms\nslept 41ms", out.text);+ try std.testing.expect(dt < 90);+}diff --git a/src/rlm_spec.zig b/src/rlm_spec.zigindex e5fe41fe..64eea3fc 100644--- a/src/rlm_spec.zig+++ b/src/rlm_spec.zig@@ -14,6 +14,10 @@ const ToolOutput = tools.ToolOutput;pub var available: bool = false;pub var run_host: ?*const fn (ToolCtx, spec_ptc.Call) ToolOutput = null;+/// Cheap discovery while the full spec stays folded (ADR 0022). Startup+/// splices this only when `--rlm` is on.+pub const system_note = "\n\nrlm(code) is available: a short script whose functions are this session's tools. Independent read_file/codedb/bash/llm_query calls with literal args start in parallel as the script streams. Prefer one rlm script over N separate tool calls when the work does not depend on itself. Semicolons or newlines separate statements; print(...) is the answer.";+const Inflight = struct {fut: Io.Future(ToolOutput),key: []u8,@@ -118,31 +122,39 @@ fn launchStmts(ctx: ToolCtx, stmts: []const []const u8) void {defer arena_state.deinit();const arena = arena_state.allocator();for (stmts) |stmt| {- const call = (spec_ptc.extractCall(arena, stmt) catch continue) orelse continue;- const key = call.key(arena) catch continue;- if (live.launched.contains(key) or live.done.contains(key)) continue;- const owned_key = ctx.gpa.dupe(u8, key) catch continue;- const owned_name = ctx.gpa.dupe(u8, call.name) catch {- ctx.gpa.free(owned_key);- continue;- };- const owned_args = ctx.gpa.dupe(u8, call.args_json) catch {- ctx.gpa.free(owned_key);- ctx.gpa.free(owned_name);- continue;- };- live.launched.put(owned_key, {}) catch {- ctx.gpa.free(owned_key);- ctx.gpa.free(owned_name);- ctx.gpa.free(owned_args);- continue;- };- const owned: spec_ptc.Call = .{ .name = owned_name, .args_json = owned_args };- const fut = ctx.io.async(runHostThunk, .{ ctx, owned });- live.inflight.append(ctx.gpa, .{ .fut = fut, .key = owned_key, .name = owned_name, .args = owned_args }) catch {};+ const pieces = spec_ptc.splitStatements(arena, stmt) catch continue;+ for (pieces) |piece| {+ launchOne(ctx, arena, piece);+ }}}+fn launchOne(ctx: ToolCtx, arena: Allocator, stmt: []const u8) void {+ if (run_host == null) return;+ const call = (spec_ptc.extractCall(arena, stmt) catch return) orelse return;+ const key = call.key(arena) catch return;+ if (live.launched.contains(key) or live.done.contains(key)) return;+ const owned_key = ctx.gpa.dupe(u8, key) catch return;+ const owned_name = ctx.gpa.dupe(u8, call.name) catch {+ ctx.gpa.free(owned_key);+ return;+ };+ const owned_args = ctx.gpa.dupe(u8, call.args_json) catch {+ ctx.gpa.free(owned_key);+ ctx.gpa.free(owned_name);+ return;+ };+ live.launched.put(owned_key, {}) catch {+ ctx.gpa.free(owned_key);+ ctx.gpa.free(owned_name);+ ctx.gpa.free(owned_args);+ return;+ };+ const owned: spec_ptc.Call = .{ .name = owned_name, .args_json = owned_args };+ const fut = ctx.io.async(runHostThunk, .{ ctx, owned });+ live.inflight.append(ctx.gpa, .{ .fut = fut, .key = owned_key, .name = owned_name, .args = owned_args }) catch {};+}+fn absorbUnlocked(gpa: Allocator, io: Io) void {for (live.inflight.items) |*item| {const out = item.fut.await(io);diff --git a/src/spec_ptc.zig b/src/spec_ptc.zigindex df9ee562..6beddca4 100644--- a/src/spec_ptc.zig+++ b/src/spec_ptc.zig@@ -292,9 +292,103 @@ fn hostField(tool: []const u8) []const u8 {if (std.mem.eql(u8, tool, "codedb")) return "command";if (std.mem.eql(u8, tool, "sleep_ms")) return "ms";if (std.mem.eql(u8, tool, "llm_query")) return "prompt";+ if (std.mem.eql(u8, tool, "bash")) return "command";+ if (std.mem.eql(u8, tool, "webfetch")) return "url";return "arg";}+/// Split a script on newlines and semicolons that are outside strings and+/// parentheses. Models often emit `a = read_file("x"); b = read_file("y")`+/// on one line; each call must be its own statement or sPTC never launches.+pub fn splitStatements(arena: Allocator, src: []const u8) ![][]const u8 {+ var out: std.ArrayList([]const u8) = .empty;+ var i: usize = 0;+ var start: usize = 0;+ var in_str: ?u8 = null;+ var esc = false;+ var depth: usize = 0;+ while (i < src.len) : (i += 1) {+ const c = src[i];+ if (in_str) |q| {+ if (esc) {+ esc = false;+ continue;+ }+ if (c == '\\') {+ esc = true;+ continue;+ }+ if (c == q) in_str = null;+ continue;+ }+ if (c == '"' or c == '\'') {+ in_str = c;+ continue;+ }+ if (c == '(') {+ depth += 1;+ continue;+ }+ if (c == ')' and depth > 0) {+ depth -= 1;+ continue;+ }+ if (depth == 0 and (c == ';' or c == '\n')) {+ const piece = std.mem.trim(u8, src[start..i], " \t\r");+ if (piece.len > 0) try out.append(arena, piece);+ start = i + 1;+ }+ }+ const tail = std.mem.trim(u8, src[start..], " \t\r\n");+ if (tail.len > 0) try out.append(arena, tail);+ return out.toOwnedSlice(arena);+}++/// Comma-split at depth 0 outside strings — `print(a, b)` and keyword lists.+pub fn splitTopLevel(arena: Allocator, src: []const u8, sep: u8) ![][]const u8 {+ var out: std.ArrayList([]const u8) = .empty;+ var i: usize = 0;+ var start: usize = 0;+ var in_str: ?u8 = null;+ var esc = false;+ var depth: usize = 0;+ while (i < src.len) : (i += 1) {+ const c = src[i];+ if (in_str) |q| {+ if (esc) {+ esc = false;+ continue;+ }+ if (c == '\\') {+ esc = true;+ continue;+ }+ if (c == q) in_str = null;+ continue;+ }+ if (c == '"' or c == '\'') {+ in_str = c;+ continue;+ }+ if (c == '(') {+ depth += 1;+ continue;+ }+ if (c == ')' and depth > 0) {+ depth -= 1;+ continue;+ }+ if (depth == 0 and c == sep) {+ const piece = std.mem.trim(u8, src[start..i], " \t");+ if (piece.len > 0) try out.append(arena, piece);+ start = i + 1;+ }+ }+ const tail = std.mem.trim(u8, src[start..], " \t");+ if (tail.len > 0) try out.append(arena, tail);+ return out.toOwnedSlice(arena);+}+fn putValue(arena: Allocator, obj: *std.json.ObjectMap, key: []const u8, v: Value) !void {const jv: std.json.Value = switch (v) {.string => |s| .{ .string = s },@@ -354,3 +448,17 @@ test "extractCalls finds independent sleeps in a three-call script" {try std.testing.expectEqual(@as(usize, 3), calls.len);try std.testing.expectEqualStrings("sleep_ms", calls[0].name);}++test "splitStatements breaks semicolon one-liners; strings keep their commas" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const parts = try splitStatements(a, "a = read_file(\"x;y.txt\"); b = bash(\"ls\"); print(a, b)");+ try std.testing.expectEqual(@as(usize, 3), parts.len);+ try std.testing.expectEqualStrings("a = read_file(\"x;y.txt\")", parts[0]);+ try std.testing.expectEqualStrings("b = bash(\"ls\")", parts[1]);+ try std.testing.expectEqualStrings("print(a, b)", parts[2]);+ const bash = (try extractCall(a, "b = bash(\"ls -la\")")).?;+ try std.testing.expectEqualStrings("bash", bash.name);+ try std.testing.expectEqualStrings("{\"command\":\"ls -la\"}", bash.args_json);+}diff --git a/src/startup.zig b/src/startup.zigindex 9bece751..bc355672 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -124,6 +124,8 @@ pub fn buildSystemPrompt(if (@import("repo_map.zig").segment(io, arena)) |map| sys_normal = try std.fmt.allocPrint(arena, "{s}{s}", .{ sys_normal, map });}if (unattended) sys_normal = try std.fmt.allocPrint(arena, "{s}{s}", .{ sys_normal, prompts.unattended_note });+ if (@import("rlm_spec.zig").available)+ sys_normal = try std.fmt.allocPrint(arena, "{s}{s}", .{ sys_normal, @import("rlm_spec.zig").system_note });// Codex-style skills: one capability line per installed optional// companion (skills_registry) — metadata in context, --help on demand.for (skills.skills_registry) |sk| {