Skip to content

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

Python

feat(rlm): persist binds across calls and add subagent()

Cursor Agent15c066624a67
diff --git a/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md b/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md
index 4de88595..15bed296 100644
--- a/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md
+++ b/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md
@@ -80,3 +80,13 @@ regression* without a catalog tax. Per-task swings are one-rep variance.
**23.7s / 54496 in**. `needle-files` (62.8s → 5.6s) dominates the wall
delta; `multi-read` was 1s slower on `--rlm` (one-rep noise). Extra input
is the system note (~900 tokens across four tasks), not a catalog schema.
+
+Graff's `--rlm` is a Zig subset of [Prime Agent's RLM programming
+model](https://github.com/PrimeIntellect-ai/prime-agent/blob/main/packages/coding-agent/docs/rlm.md),
+not an IPython/ZeroMQ kernel. Prime's invariants we keep in graff shape:
+assignments persist across `rlm` tool calls in a session (context as
+variables; `/new` and `/clear` drop them), and `subagent("task")` is
+Prime-style recursion via graff's existing `subagent` tool (positional
+`prompt`; v1 is synchronous so `print(h)` is the child's report;
+`run_in_background=true` returns an id). We do not make `rlm` the only
+catalog tool, and we do not add control flow. The speculator is still Zig.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 3ebfa3a6..8f851c3b 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -32,7 +32,7 @@ record only when you need the evidence or the edge cases.
| [0019](0019-codedb-one-shot-over-hop-chains.md) | Advertise only `context` / `around` / `callpath` / `list_dir` / `status`; hop verbs stay callable, not on the menu. |
| [0020](0020-transcript-shows-decisions.md) | Transcript shows decisions: one interpreted tool line, collapsed infra failures, compact WORKING; raw output is `/debug` / TUI-fold. |
| [0021](0021-transcript-is-the-task-not-the-bus.md) | Transcript is the task, not the event bus: bookkeeping is silent, todos are WORKING, subagents are scouts. |
-| [0022](0022-rlm-is-opt-in-speculative-ptc.md) | `rlm` is opt-in RLM + mid-stream spec-ptc (`--rlm` / `GRAFF_RLM=1`). Default catalog unchanged. |
+| [0022](0022-rlm-is-opt-in-speculative-ptc.md) | `rlm` is opt-in RLM + mid-stream spec-ptc (`--rlm` / `GRAFF_RLM=1`). Default catalog unchanged. Zig subset of Prime's model: persistent binds + `subagent("task")`. |
## When to write one
diff --git a/graff-evals/tasks/17-bind-reuse.json b/graff-evals/tasks/17-bind-reuse.json
new file mode 100644
index 00000000..7d44f55b
--- /dev/null
+++ b/graff-evals/tasks/17-bind-reuse.json
@@ -0,0 +1,11 @@
+{
+ "id": "bind-reuse",
+ "suite": "rlm",
+ "category": "scatter",
+ "prompt": "secret.txt has one token on its first line. Use the rlm tool twice: first script binds it (s = read_file(\"secret.txt\")), second script only print(s) and write that exact token to found.txt. Do not call read_file in the second script — the bind survives across rlm calls.",
+ "files": {
+ "secret.txt": "QUORUM-11\n"
+ },
+ "check": "test \"$(cat found.txt | tr -d ' \\n')\" = QUORUM-11",
+ "timeout_s": 180
+}
diff --git a/src/cli.zig b/src/cli.zig
index 0a529330..91d00056 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -245,7 +245,7 @@ pub const usage_text =
\\ --context-limit name=N cap a named prefix: skill_catalog_bytes|mcp_schema_bytes|agents_md_bytes
\\ --no-autocommit with -w, don't auto-commit each turn (default on; land work with `graff worktree merge`)
\\ --yolo skip all permission prompts for the session
- \\ --rlm advertise the rlm REPL (RLM llm_query + mid-stream spec-ptc; GRAFF_RLM=1)
+ \\ --rlm advertise the rlm REPL (persistent binds, subagent(), llm_query, mid-stream spec-ptc; GRAFF_RLM=1)
\\ --lean slim tool surface (9 core tools) + MCP deferred behind load_tool_schemas — the DEFAULT for -p one-shots (GRAFF_LEAN=1)
\\ --no-lean opt a one-shot out of the implied --lean: full tool surface + eager MCP, the pre-default -p behavior
\\ --no-local-tools embedder mode: hard-disable the built-in bash/bash_output/bash_kill/read_file/edit_file/write_file/codedb tools for the whole process (subagents included), so graff can run outside the sandbox and get its coding tools from an MCP server instead; webfetch, orchestration and MCP tools still work (GRAFF_NO_LOCAL_TOOLS=1)
diff --git a/src/commands_session.zig b/src/commands_session.zig
index d3ac96b2..b92f5dbb 100644
--- a/src/commands_session.zig
+++ b/src/commands_session.zig
@@ -78,6 +78,7 @@ pub fn resetConversationSteering(root: *Agent) void {
// the user set a fresh /goal, got a RETIRABLE one, and the next
// attempt_completion ended their steering - #318 through the /clear door.
if (root.goal_flag) |g| root.goal = goal_flow.standingGoalFromFlag(g, null, root.todos.items, 0);
+ @import("rlm_spec.zig").resetBindsSession(root.io);
}
/// Try to handle a session/environment slash command. Returns false (line
diff --git a/src/commands_session_test.zig b/src/commands_session_test.zig
index 4021c246..4fc8b1a0 100644
--- a/src/commands_session_test.zig
+++ b/src/commands_session_test.zig
@@ -10,6 +10,7 @@ const resetConversationSteering = @import("commands_session.zig").resetConversat
test "/clear + /new reset conversation steering — goal and ultracode_mode don't survive (#178)" {
var root: Agent = undefined;
+ root.io = std.testing.io;
root.goal = .{ .objective = "ultracode: index the statutes" };
root.ultracode_mode = true;
root.goal_flag = null; // no --goal: the conversation's goal dies with it
@@ -21,6 +22,7 @@ test "/clear + /new reset conversation steering — goal and ultracode_mode don'
test "/clear keeps a --goal standing objective standing (#318 through the /clear door)" {
var root: Agent = undefined;
+ root.io = std.testing.io;
root.ultracode_mode = false;
root.todos = .empty;
root.goal_flag = "keep the tree green"; // the user passed --goal
@@ -32,3 +34,23 @@ test "/clear keeps a --goal standing objective standing (#318 through the /clear
try std.testing.expect(g.standing);
try std.testing.expectEqualStrings("keep the tree green", g.objective);
}
+
+test "/clear drops persisted rlm binds" {
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ const rlm_spec = @import("rlm_spec.zig");
+ try rlm_spec.commitBinds(gpa, io, &.{.{ .name = "prev", .text = "keep" }});
+ defer rlm_spec.resetBinds(gpa, io);
+ var root: Agent = undefined;
+ root.io = io;
+ root.goal = null;
+ root.ultracode_mode = false;
+ root.goal_flag = null;
+ root.todos = .empty;
+ resetConversationSteering(&root);
+ var seeded: std.ArrayList(rlm_spec.Binding) = .empty;
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ try rlm_spec.seedBinds(gpa, io, arena_state.allocator(), &seeded);
+ try std.testing.expectEqual(@as(usize, 0), seeded.items.len);
+}
diff --git a/src/rlm.zig b/src/rlm.zig
index 5b9f6d88..5ac3d0fb 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/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_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/subagent calls with literal arguments start in parallel as the script streams (speculated), then print() is the answer. Assignments persist across rlm calls in this session. subagent(\"task\") is Prime-style recursion (graff's subagent tool; sync in v1; run_in_background=true returns an id). 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\") / bash(\"cmd\") / sleep_ms(ms) / llm_query(\"prompt\"); print(...) is the result. Semicolons or newlines separate statements."}}, "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\") / subagent(\"task\"); print(...) is the result. Assignments persist across rlm calls. Semicolons or newlines separate statements."}}, "required": ["code"]}
;
/// Process-global: `--rlm` / GRAFF_RLM=1. Never flipped mid-session.
@@ -39,6 +39,7 @@ pub fn sync() void {
pub fn resetLive(gpa: Allocator, io: Io) void {
sync();
rlm_spec.resetLive(gpa, io);
+ rlm_spec.resetBinds(gpa, io);
}
pub fn feedLive(ctx: ToolCtx, delta: []const u8) void {
@@ -68,7 +69,7 @@ pub fn exec(ctx: ToolCtx, input: Value) !ToolOutput {
return runScript(ctx, code);
}
-const Binding = struct { name: []const u8, text: []const u8 };
+const Binding = rlm_spec.Binding;
pub fn runScript(ctx: ToolCtx, code: []const u8) !ToolOutput {
sync();
@@ -90,6 +91,8 @@ pub fn runScript(ctx: ToolCtx, code: []const u8) !ToolOutput {
try speculate(ctx, arena, calls, &claimed);
var binds: std.ArrayList(Binding) = .empty;
+ try rlm_spec.seedBinds(ctx.gpa, ctx.io, arena, &binds);
+ defer rlm_spec.commitBinds(ctx.gpa, ctx.io, binds.items) catch {};
var printed: std.ArrayList(u8) = .empty;
defer printed.deinit(ctx.gpa);
@@ -199,7 +202,11 @@ fn renderPrint(arena: Allocator, inner: []const u8, binds: []const Binding) ![]c
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;
+ var i = binds.len;
+ while (i > 0) {
+ i -= 1;
+ if (std.mem.eql(u8, binds[i].name, t)) return binds[i].text;
+ }
return try arena.dupe(u8, t);
}
@@ -249,7 +256,10 @@ test "runScript speculates three sleeps so wall time is ~one sleep, not three" {
var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };
defer dummy_client.deinit();
const saved = available;
- defer available = saved;
+ defer {
+ available = saved;
+ resetLive(gpa, io);
+ }
available = true;
const ctx = testCtx(gpa, io, &dummy_client);
const t0: Io.Timestamp = .now(io, .awake);
@@ -274,7 +284,10 @@ test "runScript reads a fixture via speculated read_file and prints it" {
var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };
defer dummy_client.deinit();
const saved = available;
- defer available = saved;
+ defer {
+ available = saved;
+ resetLive(gpa, io);
+ }
available = true;
var ctx = testCtx(gpa, io, &dummy_client);
ctx.agent_cwd = dir;
@@ -290,7 +303,10 @@ test "runScript splits a semicolon one-liner and prints both binds" {
var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };
defer dummy_client.deinit();
const saved = available;
- defer available = saved;
+ defer {
+ available = saved;
+ resetLive(gpa, io);
+ }
available = true;
const ctx = testCtx(gpa, io, &dummy_client);
const t0: Io.Timestamp = .now(io, .awake);
@@ -347,3 +363,52 @@ test "feedLive splits a semicolon line before runScript claims" {
try std.testing.expectEqualStrings("slept 40ms\nslept 41ms", out.text);
try std.testing.expect(dt < 90);
}
+
+test "runScript reuses last-script binds; resetLive drops them" {
+ 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 first = try runScript(ctx, "prev = sleep_ms(1)");
+ defer gpa.free(first.text);
+ try std.testing.expect(!first.is_error);
+ const reuse = try runScript(ctx, "print(prev)");
+ defer gpa.free(reuse.text);
+ try std.testing.expect(!reuse.is_error);
+ try std.testing.expectEqualStrings("slept 1ms", reuse.text);
+ const overwrite = try runScript(ctx, "prev = sleep_ms(2); print(prev)");
+ defer gpa.free(overwrite.text);
+ try std.testing.expectEqualStrings("slept 2ms", overwrite.text);
+ const kept = try runScript(ctx, "print(prev)");
+ defer gpa.free(kept.text);
+ try std.testing.expectEqualStrings("slept 2ms", kept.text);
+ resetLive(gpa, io);
+ const gone = try runScript(ctx, "print(prev)");
+ defer gpa.free(gone.text);
+ try std.testing.expectEqualStrings("prev", gone.text);
+}
+
+test "runScript last assignment wins when a name is rebound in one script" {
+ 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 out = try runScript(ctx, "a = sleep_ms(1); a = sleep_ms(2); print(a)");
+ defer gpa.free(out.text);
+ try std.testing.expect(!out.is_error);
+ try std.testing.expectEqualStrings("slept 2ms", out.text);
+}
diff --git a/src/rlm_spec.zig b/src/rlm_spec.zig
index 64eea3fc..d59720f6 100644
--- a/src/rlm_spec.zig
+++ b/src/rlm_spec.zig
@@ -16,7 +16,89 @@ 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.";
+///
+/// Graff's rlm is a Zig subset of Prime Agent's programming model: assignments
+/// persist across rlm calls (context as variables, not an IPython kernel), and
+/// `subagent("task")` is Prime-style recursion via graff's existing subagent
+/// tool. v1 is synchronous; speculate() still overlaps independent calls.
+/// Keyword `run_in_background=true` returns an agent id (a handle).
+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/subagent calls with literal args start in parallel as the script streams. Bindings persist across rlm calls until /new or /clear. subagent(\"task\") is Prime-style recursion (graff's subagent tool; sync in v1). 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.";
+
+/// One REPL assignment. `runScript` seeds these from the process-local store
+/// so a later `rlm` call can `print(prev)` without re-reading. Owned by the
+/// caller's arena when seeded; the store holds gpa copies.
+pub const Binding = struct { name: []const u8, text: []const u8 };
+
+const BindStore = struct {
+ mu: Io.Mutex = .init,
+ items: std.ArrayList(Binding) = .empty,
+ gpa: ?Allocator = null,
+};
+
+var binds: BindStore = .{};
+
+/// Copy last-script binds into `out` (arena-owned). No-op until a script has
+/// committed at least one assignment.
+pub fn seedBinds(gpa: Allocator, io: Io, arena: Allocator, out: *std.ArrayList(Binding)) !void {
+ _ = gpa;
+ binds.mu.lockUncancelable(io);
+ defer binds.mu.unlock(io);
+ for (binds.items.items) |b| {
+ try out.append(arena, .{
+ .name = try arena.dupe(u8, b.name),
+ .text = try arena.dupe(u8, b.text),
+ });
+ }
+}
+
+/// Replace the process-local store with last-wins unique copies of `items`.
+pub fn commitBinds(gpa: Allocator, io: Io, items: []const Binding) !void {
+ binds.mu.lockUncancelable(io);
+ defer binds.mu.unlock(io);
+ clearBindsUnlocked(binds.gpa orelse gpa);
+ binds.gpa = gpa;
+ var i: usize = 0;
+ while (i < items.len) : (i += 1) {
+ if (laterSameName(items, i)) continue;
+ try binds.items.append(gpa, .{
+ .name = try gpa.dupe(u8, items[i].name),
+ .text = try gpa.dupe(u8, items[i].text),
+ });
+ }
+}
+
+fn laterSameName(items: []const Binding, i: usize) bool {
+ const name = items[i].name;
+ for (items[i + 1 ..]) |b| if (std.mem.eql(u8, b.name, name)) return true;
+ return false;
+}
+
+fn clearBindsUnlocked(gpa: Allocator) void {
+ for (binds.items.items) |b| {
+ gpa.free(b.name);
+ gpa.free(b.text);
+ }
+ binds.items.clearRetainingCapacity();
+}
+
+/// Drop persisted binds. `rlm.resetLive` calls this (session / test cleanup).
+/// `rlm_spec.resetLive` does not — that is the per-call speculation cache.
+pub fn resetBinds(gpa: Allocator, io: Io) void {
+ binds.mu.lockUncancelable(io);
+ defer binds.mu.unlock(io);
+ const a = binds.gpa orelse gpa;
+ clearBindsUnlocked(a);
+ binds.items.deinit(a);
+ binds.items = .empty;
+ binds.gpa = null;
+}
+
+/// Session doors (`/new`, `/clear`, TUI history reset) that may not have
+/// allocated binds yet: no-op until a script has committed.
+pub fn resetBindsSession(io: Io) void {
+ const gpa = binds.gpa orelse return;
+ resetBinds(gpa, io);
+}
const Inflight = struct {
fut: Io.Future(ToolOutput),
diff --git a/src/spec_ptc.zig b/src/spec_ptc.zig
index 6beddca4..82045c01 100644
--- a/src/spec_ptc.zig
+++ b/src/spec_ptc.zig
@@ -294,6 +294,7 @@ fn hostField(tool: []const u8) []const u8 {
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";
+ if (std.mem.eql(u8, tool, "subagent")) return "prompt";
return "arg";
}
@@ -462,3 +463,20 @@ test "splitStatements breaks semicolon one-liners; strings keep their commas" {
try std.testing.expectEqualStrings("bash", bash.name);
try std.testing.expectEqualStrings("{\"command\":\"ls -la\"}", bash.args_json);
}
+
+test "extractCall maps subagent(\"task\") onto prompt; two calls stay independent" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const one = (try extractCall(a, "h = subagent(\"review auth\")")).?;
+ try std.testing.expectEqualStrings("subagent", one.name);
+ try std.testing.expectEqualStrings("{\"prompt\":\"review auth\"}", one.args_json);
+ const bg = (try extractCall(a, "subagent(prompt=\"audit tests\", run_in_background=true)")).?;
+ try std.testing.expectEqualStrings("subagent", bg.name);
+ try std.testing.expectEqualStrings("{\"prompt\":\"audit tests\",\"run_in_background\":true}", bg.args_json);
+ const stmts = try splitStatements(a, "a = subagent(\"read a.txt\"); b = subagent(\"read b.txt\")");
+ const calls = try extractCalls(a, stmts);
+ try std.testing.expectEqual(@as(usize, 2), calls.len);
+ try std.testing.expectEqualStrings("{\"prompt\":\"read a.txt\"}", calls[0].args_json);
+ try std.testing.expectEqualStrings("{\"prompt\":\"read b.txt\"}", calls[1].args_json);
+}
diff --git a/src/tui_launch.zig b/src/tui_launch.zig
index cd8734fd..321d38e8 100644
--- a/src/tui_launch.zig
+++ b/src/tui_launch.zig
@@ -129,7 +129,10 @@ fn historyCb(ctx: ?*anyopaque, op: tui.HistoryOp) void {
const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return));
const convo = c.convo orelse return;
switch (op) {
- .reset => convo.reset(),
+ .reset => {
+ convo.reset();
+ @import("rlm_spec.zig").resetBindsSession(c.io);
+ },
.rewind => convo.rewind(),
}
}