graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(rlm): opt-in speculative programmatic tool calling in Zig
Cursor Agentba43a249dc48
diff --git a/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md b/docs/adr/0022-rlm-is-opt-in-speculative-ptc.mdnew file mode 100644index 00000000..0ceacf3b--- /dev/null+++ b/docs/adr/0022-rlm-is-opt-in-speculative-ptc.md@@ -0,0 +1,34 @@+# 0022. `rlm` is opt-in speculative programmatic tool calling++Status: accepted 2026-08-25++## Context++[spec-ptc](https://github.com/alexzhang13/spec-ptc) overlaps tool work with+generation for harnesses whose tools are functions inside one code REPL (RLM,+CodeAct). Graff's native loop is the opposite shape: the model emits structured+`read_file` / `bash` / `subagent` calls, and `runTools` fans a *finished* batch+across the pool. That is parallelism after the arguments close, not speculation+from partial source.++Dropping spec-ptc's Python shadow REPL into the default catalog would change+every prefix and the 64-cell tool-catalog kernel. A first cut has to be+measurable against the native loop without that cost.++## Decision++`rlm` is an opt-in native tool (`--rlm` / `GRAFF_RLM=1`). Off, the catalog is+unchanged. On, the model gets one REPL whose functions *are* graff tools+(`read_file`, `codedb`) plus `sleep_ms` / `print`. The speculator is Zig+(`src/spec_ptc.zig`): closed statements with literal args launch in parallel+before the script walks them. Default structured tools stay the main harness.++A live comparison is `scripts/compare-ptc.py`: same prompt, native vs `--rlm`.++## Consequences++- True mid-stream speculation (feed `code` while the `rlm` argument is still+ arriving) is the next increment; v1 speculates at exec start from the+ complete script, which already overlaps independent calls with each other.+- `llm_query` as a host function (a real RLM sub-call) is not in this cut.+- SDK / `--schema` do not list `rlm` until it graduates off the flag.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex dfadd37e..8f10f6b2 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -32,6 +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 speculative PTC (`--rlm` / `GRAFF_RLM=1`). Zig speculator; default structured-tool catalog unchanged. |## When to write onediff --git a/scripts/compare-ptc.py b/scripts/compare-ptc.pynew file mode 100755index 00000000..6b019e3c--- /dev/null+++ b/scripts/compare-ptc.py@@ -0,0 +1,106 @@+#!/usr/bin/env python3+"""Compare native structured tool calls vs --rlm (spec-ptc) on the same prompt.++Runs graff twice against a three-file fixture and prints tool_call shape ++timing. Default binary: zig-out/bin/graff, then $PATH graff.+"""++from __future__ import annotations++import argparse+import json+import os+import subprocess+import sys+import tempfile+import time+from pathlib import Path+++PROMPT = """Read the FIRST line of each of these three files and report them as+a three-line list (file: line). Do not use bash. Files:+ a.txt+ b.txt+ c.txt+"""++RLM_HINT = """+You MUST use the rlm tool once. Write a short script:+ a = read_file("a.txt")+ b = read_file("b.txt")+ c = read_file("c.txt")+ print(a)+ print(b)+ print(c)+Do not call read_file as a top-level tool.+"""+++def graff_bin() -> str:+ here = Path(__file__).resolve().parents[1] / "zig-out" / "bin" / "graff"+ if here.exists():+ return str(here)+ return "graff"+++def run(bin: str, extra: list[str], prompt: str, cwd: str) -> dict:+ cmd = [bin, "-p", "--json", "--yolo", "--model", "grok-4.6", *extra, prompt]+ t0 = time.perf_counter()+ proc = subprocess.run(cmd, cwd=cwd, text=True, capture_output=True)+ ms = int((time.perf_counter() - t0) * 1000)+ events = []+ for line in (proc.stdout or "").splitlines():+ line = line.strip()+ if not line.startswith("{"):+ continue+ try:+ events.append(json.loads(line))+ except json.JSONDecodeError:+ continue+ tools = [e for e in events if e.get("type") == "tool_call"]+ finished = [e for e in events if e.get("type") == "tool_call_finished"]+ text_bits = [e.get("text", "") for e in events if e.get("type") in ("text", "assistant", "turn") and e.get("text")]+ return {+ "ok": proc.returncode == 0,+ "ms": ms,+ "stderr": (proc.stderr or "")[-800:],+ "tools": [{"name": t.get("name"), "input": t.get("input")} for t in tools],+ "finished_ms": [e.get("ms") for e in finished],+ "names": [t.get("name") for t in tools],+ "answer": "\n".join(text_bits)[-500:],+ }+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--graff", default=graff_bin())+ ap.add_argument("--skip-live", action="store_true", help="print the plan only")+ args = ap.parse_args()+ if args.skip_live:+ print("native: structured read_file x3 (or however the model fans out)")+ print("rlm: one rlm script; Zig speculator launches the three reads together")+ return 0++ with tempfile.TemporaryDirectory() as td:+ Path(td, "a.txt").write_text("alpha-first\nrest-a\n")+ Path(td, "b.txt").write_text("bravo-first\nrest-b\n")+ Path(td, "c.txt").write_text("charlie-first\nrest-c\n")+ print(f"graff={args.graff}", flush=True)+ print("=== native (structured tools) ===", flush=True)+ native = run(args.graff, ["--no-lean"], PROMPT, td)+ print(json.dumps({k: native[k] for k in ("ok", "ms", "names", "finished_ms")}, indent=2))+ print("=== rlm (--rlm, speculated reads) ===", flush=True)+ rlm = run(args.graff, ["--no-lean", "--rlm"], PROMPT + RLM_HINT, td)+ print(json.dumps({k: rlm[k] for k in ("ok", "ms", "names", "finished_ms")}, indent=2))+ print("=== answers ===")+ print("native:\n", native.get("answer") or native.get("stderr"))+ print("rlm:\n", rlm.get("answer") or rlm.get("stderr"))+ if native.get("stderr") and not native["ok"]:+ print("native stderr:\n", native["stderr"], file=sys.stderr)+ if rlm.get("stderr") and not rlm["ok"]:+ print("rlm stderr:\n", rlm["stderr"], file=sys.stderr)+ return 0 if native["ok"] and rlm["ok"] else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/args.zig b/src/args.zigindex 15c38a87..d4097462 100644--- a/src/args.zig+++ b/src/args.zig@@ -174,6 +174,8 @@ pub fn parse(init: std.process.Init) !Flags {no_local_tools.enabled = true; // #330: hard-disable the host-touching built-ins for the whole process (also GRAFF_NO_LOCAL_TOOLS=1)} else if (std.mem.eql(u8, arg, "--clock-sleep")) {main_mod.g_clock_sleep = true; // #225: opt in to the root-only clock_sleep meta tool (also GRAFF_CLOCK_SLEEP=1)+ } else if (std.mem.eql(u8, arg, "--rlm")) {+ @import("rlm.zig").available = true; // ADR 0022: opt-in programmatic tool calling (also GRAFF_RLM=1)} 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/cli.zig b/src/cli.zigindex ce288d3b..3e98dde5 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -245,6 +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 programmatic-tool-calling REPL (spec-ptc in Zig; 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/exec.zig b/src/exec.zigindex e4ba58ea..283ad7b7 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -491,6 +491,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {if (std.mem.eql(u8, call.name, imagegen.tool_name)) return imagegen.execImagegen(ctx, input);if (std.mem.eql(u8, call.name, "subagent")) return execSubagent(ctx, input);if (std.mem.eql(u8, call.name, "workflow")) return execWorkflow(ctx, input);+ if (std.mem.eql(u8, call.name, @import("rlm.zig").tool_name)) return @import("rlm.zig").exec(ctx, input);if (std.mem.eql(u8, call.name, "agent_output")) {const id = intField(input, "id") orelse return missingArg(gpa, "id");const wait_ms = intField(input, "wait_ms") orelse 0;@@ -537,4 +538,6 @@ test { // main.zig is at the 600-line cap; exec.zig is these modules' importer,_ = @import("codedb_around.zig");_ = @import("codedb_health.zig");_ = @import("list_dir.zig");+ _ = @import("rlm.zig");+ _ = @import("spec_ptc.zig");}diff --git a/src/rlm.zig b/src/rlm.zignew file mode 100644index 00000000..99ec176b--- /dev/null+++ b/src/rlm.zig@@ -0,0 +1,256 @@+//! Opt-in `rlm` tool: one programmatic-tool-calling REPL per call.+//!+//! Off unless `--rlm` / `GRAFF_RLM=1`. The default catalog stays byte-stable+//! (ADR 0022). Host functions: `read_file`, `codedb` (real graff tools),+//! `sleep_ms` (overlap proof), `print` (answer). Independent literal calls+//! launch in parallel via spec_ptc before the script walks them — the Zig+//! half of speculative PTC.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const spec_ptc = @import("spec_ptc.zig");+const tools = @import("tools.zig");+const ToolCtx = tools.ToolCtx;+const ToolOutput = tools.ToolOutput;+const no_local_tools = @import("no_local_tools.zig");+const exec_mod = @import("exec.zig");++pub const tool_name = "rlm";+pub const tool_desc = "Programmatic tool calling (sPTC). Run a short Python-like script whose functions ARE this session's tools. Independent read_file/codedb/sleep_ms calls with literal arguments start in parallel as the script is parsed (speculated), then print() is the answer. 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_schema =+ \\{"type": "object", "properties": {"code": {"type": "string", "description": "Python-like script: name = read_file(\"path\") / codedb(\"command\") / sleep_ms(ms); print(...) is the result"}}, "required": ["code"]}+;++/// Process-global: `--rlm` / GRAFF_RLM=1. Never flipped mid-session.+pub var available: bool = false;++/// Append `rlm` after the lean/no-local filters so `--rlm -p` still sees it.+/// No-op when the flag is off or embedder mode stripped host tools.+pub fn maybeAppend(comptime Spec: type, arena: Allocator, specs: []const Spec) ![]const Spec {+ if (!available or no_local_tools.enabled) return specs;+ for (specs) |s| if (std.mem.eql(u8, s.name, tool_name)) return specs;+ const buf = try arena.alloc(Spec, specs.len + 1);+ @memcpy(buf[0..specs.len], specs);+ buf[specs.len] = .{ .name = tool_name, .desc = tool_desc, .schema = tool_schema };+ return buf;+}++pub fn exec(ctx: ToolCtx, input: Value) !ToolOutput {+ if (!available) return .{ .text = try ctx.gpa.dupe(u8, "rlm is off — pass --rlm (or GRAFF_RLM=1)"), .is_error = true };+ if (no_local_tools.enabled) return .{ .text = try ctx.gpa.dupe(u8, "rlm is a host tool and is disabled under --no-local-tools"), .is_error = true };+ const code = tools.strField(input, "code") orelse return tools.missingArg(ctx.gpa, "code");+ return runScript(ctx, code);+}++const Binding = struct { name: []const u8, text: []const u8 };++pub fn runScript(ctx: ToolCtx, code: []const u8) !ToolOutput {+ var arena_state = std.heap.ArenaAllocator.init(ctx.gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ 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 calls = try spec_ptc.extractCalls(arena, stmts.items);+ var claimed = std.StringHashMap(ToolOutput).init(ctx.gpa);+ defer {+ var cit = claimed.iterator();+ while (cit.next()) |e| ctx.gpa.free(e.value_ptr.text);+ claimed.deinit();+ }+ 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| {+ if (try evalStmt(ctx, arena, stmt, binds.items, &claimed, &printed, &binds)) |err| {+ return .{ .text = err, .is_error = true };+ }+ }+ if (printed.items.len == 0) return .{ .text = try ctx.gpa.dupe(u8, "(rlm: script produced no print())") };+ return .{ .text = try printed.toOwnedSlice(ctx.gpa) };+}++fn speculate(ctx: ToolCtx, arena: Allocator, calls: []const spec_ptc.Call, claimed: *std.StringHashMap(ToolOutput)) !void {+ if (calls.len == 0) return;+ var uniq: std.ArrayList(spec_ptc.Call) = .empty;+ var seen = std.StringHashMap(void).init(arena);+ for (calls) |c| {+ const key = try c.key(arena);+ if (try seen.fetchPut(key, {})) |_| continue;+ try uniq.append(arena, c);+ }+ const futs = try arena.alloc(Io.Future(ToolOutput), uniq.items.len);+ const keys = try arena.alloc([]const u8, uniq.items.len);+ for (uniq.items, futs, keys) |c, *fut, *key| {+ key.* = try c.key(arena);+ fut.* = ctx.io.async(runHost, .{ ctx, c });+ }+ for (futs, keys) |*fut, key| {+ const out = fut.await(ctx.io);+ try claimed.put(key, out);+ }+}++fn runHost(ctx: ToolCtx, call: spec_ptc.Call) ToolOutput {+ if (std.mem.eql(u8, call.name, "sleep_ms")) return runSleep(ctx, call.args_json);+ var parsed = std.json.parseFromSlice(Value, ctx.gpa, call.args_json, .{}) catch {+ return .{ .text = ctx.gpa.dupe(u8, "rlm: bad args") catch &.{}, .is_error = true };+ };+ defer parsed.deinit();+ return exec_mod.execTool(ctx, .{ .id = "rlm", .name = call.name, .input = parsed.value });+}++fn runSleep(ctx: ToolCtx, args_json: []const u8) ToolOutput {+ var parsed = std.json.parseFromSlice(Value, ctx.gpa, args_json, .{}) catch {+ return .{ .text = ctx.gpa.dupe(u8, "rlm: sleep_ms needs ms") catch &.{}, .is_error = true };+ };+ defer parsed.deinit();+ const ms = tools.intField(parsed.value, "ms") orelse 0;+ const capped: i64 = @min(@max(ms, 0), 5_000);+ ctx.io.sleep(.fromMilliseconds(capped), .awake) catch {};+ return .{ .text = std.fmt.allocPrint(ctx.gpa, "slept {d}ms", .{capped}) catch ctx.gpa.dupe(u8, "slept") catch &.{} };+}++fn evalStmt(+ ctx: ToolCtx,+ arena: Allocator,+ stmt: []const u8,+ binds: []const Binding,+ claimed: *std.StringHashMap(ToolOutput),+ printed: *std.ArrayList(u8),+ bind_out: *std.ArrayList(Binding),+) !?[]u8 {+ const call = try spec_ptc.extractCall(arena, stmt);+ if (call) |c| {+ const key = try c.key(arena);+ const out = claimed.get(key) orelse runHost(ctx, c);+ if (out.is_error) return try ctx.gpa.dupe(u8, out.text);+ if (assignName(stmt)) |nm| try bind_out.append(arena, .{ .name = try arena.dupe(u8, nm), .text = try arena.dupe(u8, out.text) });+ return null;+ }+ if (printArgs(stmt)) |inner| {+ const text = try renderPrint(arena, inner, binds);+ if (printed.items.len > 0) try printed.append(ctx.gpa, '\n');+ try printed.appendSlice(ctx.gpa, text);+ return null;+ }+ return try std.fmt.allocPrint(ctx.gpa, "rlm: unsupported statement: {s}", .{stmt});+}++fn assignName(stmt: []const u8) ?[]const u8 {+ const eq = std.mem.indexOfScalar(u8, stmt, '=') orelse return null;+ const lhs = std.mem.trim(u8, stmt[0..eq], " \t");+ if (lhs.len == 0) return null;+ return lhs;+}++fn printArgs(stmt: []const u8) ?[]const u8 {+ const t = std.mem.trim(u8, stmt, " \t");+ if (!std.mem.startsWith(u8, t, "print(") or t[t.len - 1] != ')') return null;+ return t["print(".len .. t.len - 1];+}++fn renderPrint(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;+ return try arena.dupe(u8, t);+}++test "maybeAppend is a no-op until --rlm, and refuses to double-append" {+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const Spec = struct { name: []const u8, desc: []const u8 = "", schema: []const u8 = "{}" };+ const base = [_]Spec{.{ .name = "read_file" }};+ const saved = available;+ const saved_local = no_local_tools.enabled;+ defer {+ available = saved;+ no_local_tools.enabled = saved_local;+ }+ available = false;+ no_local_tools.enabled = false;+ try std.testing.expectEqual(@as(usize, 1), (try maybeAppend(Spec, arena, &base)).len);+ available = true;+ const one = try maybeAppend(Spec, arena, &base);+ try std.testing.expectEqual(@as(usize, 2), one.len);+ try std.testing.expectEqualStrings(tool_name, one[1].name);+ const two = try maybeAppend(Spec, arena, one);+ try std.testing.expectEqual(@as(usize, 2), two.len);+ available = true;+ no_local_tools.enabled = true;+ try std.testing.expectEqual(@as(usize, 1), (try maybeAppend(Spec, arena, &base)).len);+}++test "runScript speculates three sleeps so wall time is ~one sleep, not three" {+ 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: ToolCtx = .{+ .gpa = gpa,+ .io = io,+ .client = &dummy_client,+ .provider = undefined,+ .registry = null,+ .from_sub = false,+ .approvals = null,+ .tracer = null,+ };+ const t0: Io.Timestamp = .now(io, .awake);+ const out = try runScript(ctx, "a = sleep_ms(40)\nb = sleep_ms(41)\nc = sleep_ms(42)\nprint(a)");+ 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", out.text);+ // Sequential would be ~120ms. Parallel speculation should land well under 100.+ try std.testing.expect(dt < 100);+}++test "runScript reads a fixture via speculated read_file and prints it" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ try tmp.dir.writeFile(io, .{ .sub_path = "note.txt", .data = "hello-rlm\n" });+ 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];+ // confinedPath requires a relative path; run from tmp via agent_cwd.+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer dummy_client.deinit();+ const saved = available;+ defer available = saved;+ available = true;+ const ctx: ToolCtx = .{+ .gpa = gpa,+ .io = io,+ .client = &dummy_client,+ .provider = undefined,+ .registry = null,+ .from_sub = false,+ .approvals = null,+ .tracer = null,+ .agent_cwd = dir,+ };+ const out = try runScript(ctx, "x = read_file(\"note.txt\")\nprint(x)");+ defer gpa.free(out.text);+ try std.testing.expect(!out.is_error);+ try std.testing.expect(std.mem.indexOf(u8, out.text, "hello-rlm") != null);+}diff --git a/src/schema.zig b/src/schema.zigindex bf7c290f..e6fd9171 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -13,7 +13,8 @@ const peer_channel = @import("peer_channel.zig");const workspace_switch = @import("workspace_switch.zig");const no_local_tools = @import("no_local_tools.zig"); // #330: the hard --no-local-tools gate (layer 1 lives here, layer 2 in exec.zig)const tool_gates = @import("tool_gates.zig"); // #352: the additive twin — optional tools that only exist when startup found their backing capability-const imagegen = @import("imagegen.zig"); // #352: name/desc/schema as plain strings, like skill_docs, so this catalog needs one entry and no import cycle+const imagegen = @import("imagegen.zig");+const rlm = @import("rlm.zig");const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: load_tool_schemas stringsconst mcp_select = @import("mcp_select.zig"); // fx search-then-selectconst result_read = @import("result_read.zig"); // overflow handle pager@@ -326,7 +327,7 @@ pub fn effectiveRootSpecs(arena: Allocator) ![]const ToolSpec {else(if (learn_store.active_agent_loaded) &root_specs_without_clock else &root_specs_without_optional);// Optionals are appended BEFORE the #330 filter, never after (optional ≠ exempt); the --lean token filter chains last.- return no_local_tools.compactLeanSpecs(ToolSpec, arena, try no_local_tools.filterLeanSpecs(ToolSpec, arena, try no_local_tools.filterRootSpecs(ToolSpec, arena, try tool_gates.withAvailable(ToolSpec, arena, chosen, &optional_specs))));+ return rlm.maybeAppend(ToolSpec, arena, try no_local_tools.compactLeanSpecs(ToolSpec, arena, try no_local_tools.filterLeanSpecs(ToolSpec, arena, try no_local_tools.filterRootSpecs(ToolSpec, arena, try tool_gates.withAvailable(ToolSpec, arena, chosen, &optional_specs)))));}const Schema = union(enum) { raw: []const u8, value: Value };diff --git a/src/session_settings.zig b/src/session_settings.zigindex a36d7225..c8c24ec2 100644--- a/src/session_settings.zig+++ b/src/session_settings.zig@@ -113,6 +113,10 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {if (environ_map.get("GRAFF_CLOCK_SLEEP")) |v| {main_mod.g_clock_sleep = main_mod.g_clock_sleep or std.mem.eql(u8, v, "1") or std.ascii.eqlIgnoreCase(v, "true") or std.ascii.eqlIgnoreCase(v, "on") or std.ascii.eqlIgnoreCase(v, "yes");}+ if (environ_map.get("GRAFF_RLM")) |v| {+ const rlm = @import("rlm.zig");+ rlm.available = rlm.available or std.mem.eql(u8, v, "1") or std.ascii.eqlIgnoreCase(v, "true") or std.ascii.eqlIgnoreCase(v, "on") or std.ascii.eqlIgnoreCase(v, "yes");+ }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, exactly matching session_start.leanSkipsMcp// (the MCP half of the same switch) — a "0" still means lean, by design.diff --git a/src/session_settings_tests.zig b/src/session_settings_tests.zigindex afd01296..a7055f85 100644--- a/src/session_settings_tests.zig+++ b/src/session_settings_tests.zig@@ -41,6 +41,7 @@ const knobs = [_]Knob{.{ .name = "GRAFF_POST_DEADLINE_SECS", .value = "90" },.{ .name = "GRAFF_CODEX_WS", .value = "off" },.{ .name = "GRAFF_CLOCK_SLEEP", .value = "1" },+ .{ .name = "GRAFF_RLM", .value = "1" },.{ .name = "GRAFF_NO_LOCAL_TOOLS", .value = "1" },.{ .name = "GRAFF_CODEX_WS_IDLE_SECS", .value = "11" },.{ .name = "GRAFF_CONTEXT", .value = "123456" },@@ -82,6 +83,7 @@ const Saved = struct {drop_always: bool,codex_ws: bool,clock_sleep: bool,+ rlm: bool,stream_stall_ms: u64,post_deadline_ms: u64,codex_ws_idle_ms: i64,@@ -103,6 +105,7 @@ const Saved = struct {.drop_always = main_mod.g_force_drop_always,.codex_ws = main_mod.g_codex_ws,.clock_sleep = main_mod.g_clock_sleep,+ .rlm = @import("rlm.zig").available,.stream_stall_ms = http.stream_stall_ms,.post_deadline_ms = http.post_deadline_ms,.codex_ws_idle_ms = agent_ws.codex_ws_idle_ms,@@ -125,6 +128,7 @@ const Saved = struct {main_mod.g_force_drop_always = s.drop_always;main_mod.g_codex_ws = s.codex_ws;main_mod.g_clock_sleep = s.clock_sleep;+ @import("rlm.zig").available = s.rlm;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;@@ -170,6 +174,7 @@ test "applyEnvKnobs actually applies the values it reads" {main_mod.g_force_stall_once = false;main_mod.g_codex_ws = true;main_mod.g_clock_sleep = false;+ @import("rlm.zig").available = false;no_local_tools.enabled = false;ws.g_debug = false;provider_mod.g_context_override = null;@@ -184,6 +189,7 @@ test "applyEnvKnobs actually applies the values it reads" {try std.testing.expect(main_mod.g_force_stall_once);try std.testing.expect(!main_mod.g_codex_ws); // "off" disables the WS transporttry std.testing.expect(main_mod.g_clock_sleep);+ try std.testing.expect(@import("rlm.zig").available);try std.testing.expect(no_local_tools.enabled);try std.testing.expect(ws.g_debug);try std.testing.expectEqual(@as(u64, 7_000), http.stream_stall_ms); // seconds → msdiff --git a/src/spec_ptc.zig b/src/spec_ptc.zignew file mode 100644index 00000000..30ed5443--- /dev/null+++ b/src/spec_ptc.zig@@ -0,0 +1,353 @@+//! Zig speculator for programmatic tool calling (sPTC).+//!+//! [spec-ptc](https://github.com/alexzhang13/spec-ptc) overlaps tool work+//! with generation: as a code REPL streams, closed statements whose arguments+//! are literals launch as futures; the real exec claims them. Graff's native+//! loop already fans a finished batch across the pool — this is earlier: the+//! call is visible in partial source before the `rlm` tool argument closes.+//!+//! This module is the language-agnostic half. It does not run tools. A host+//! (rlm.zig) feeds source, launches `Call`s, and claims by canonical key.++const std = @import("std");+const Allocator = std.mem.Allocator;++/// A closed call with literal args, ready to speculate or claim.+pub const Call = struct {+ name: []const u8,+ /// Canonical JSON object, e.g. `{"path":"a.txt"}`. Arena/gpa-owned.+ args_json: []const u8,++ pub fn key(self: Call, arena: Allocator) ![]const u8 {+ return std.fmt.allocPrint(arena, "{s}\n{s}", .{ self.name, self.args_json });+ }+};++/// Incremental source → complete top-level statements (newline-terminated).+pub const Segmenter = struct {+ pending: std.ArrayList(u8) = .empty,++ pub fn deinit(self: *Segmenter, gpa: Allocator) void {+ self.pending.deinit(gpa);+ }++ /// Append `delta`. Returns newly closed statements (each without the+ /// trailing newline). Caller frees the slice; strings alias `pending`+ /// until the next feed, so copy what you keep.+ pub fn feed(self: *Segmenter, gpa: Allocator, delta: []const u8) ![][]const u8 {+ try self.pending.appendSlice(gpa, delta);+ return self.takeClosed(gpa);+ }++ pub fn finish(self: *Segmenter, gpa: Allocator) ![][]const u8 {+ if (self.pending.items.len == 0) return &.{};+ const tail = std.mem.trim(u8, self.pending.items, " \t\r\n");+ if (tail.len == 0) {+ self.pending.clearRetainingCapacity();+ return &.{};+ }+ const one = try gpa.alloc([]const u8, 1);+ one[0] = try gpa.dupe(u8, tail);+ self.pending.clearRetainingCapacity();+ return one;+ }++ fn takeClosed(self: *Segmenter, gpa: Allocator) ![][]const u8 {+ var out: std.ArrayList([]const u8) = .empty;+ errdefer out.deinit(gpa);+ var rest = self.pending.items;+ while (std.mem.indexOfScalar(u8, rest, '\n')) |nl| {+ const line = std.mem.trim(u8, rest[0..nl], " \t\r");+ if (line.len > 0) try out.append(gpa, try gpa.dupe(u8, line));+ rest = rest[nl + 1 ..];+ }+ if (rest.ptr != self.pending.items.ptr) {+ const n = rest.len;+ std.mem.copyForwards(u8, self.pending.items[0..n], rest);+ self.pending.shrinkRetainingCapacity(n);+ }+ return out.toOwnedSlice(gpa);+ }+};++/// Pull a speculatable `name(...)` / `var = name(...)` from one statement.+/// Only literal args (string / int / bool). Returns null for print, comments,+/// or anything that still depends on a runtime value.+pub fn extractCall(arena: Allocator, stmt: []const u8) !?Call {+ const line = stripComment(stmt);+ const trimmed = std.mem.trim(u8, line, " \t");+ if (trimmed.len == 0) return null;+ const call_src = afterOptionalAssign(trimmed) orelse return null;+ const open = std.mem.indexOfScalar(u8, call_src, '(') orelse return null;+ const name = std.mem.trim(u8, call_src[0..open], " \t");+ if (!isIdent(name)) return null;+ if (std.mem.eql(u8, name, "print")) return null;+ const close = lastParen(call_src) orelse return null;+ const inner = call_src[open + 1 .. close];+ const args_json = parseArgs(arena, name, inner) catch |err| switch (err) {+ error.NeedKeywords => return null,+ else => return err,+ } orelse return null;+ return .{ .name = try arena.dupe(u8, name), .args_json = args_json };+}++pub fn extractCalls(arena: Allocator, statements: []const []const u8) ![]Call {+ var out: std.ArrayList(Call) = .empty;+ for (statements) |stmt| {+ if (try extractCall(arena, stmt)) |c| try out.append(arena, c);+ }+ return out.toOwnedSlice(arena);+}++fn stripComment(stmt: []const u8) []const u8 {+ var i: usize = 0;+ var in_str: ?u8 = null;+ var esc = false;+ while (i < stmt.len) : (i += 1) {+ const c = stmt[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 == '#') return stmt[0..i];+ }+ return stmt;+}++fn afterOptionalAssign(stmt: []const u8) ?[]const u8 {+ const paren = std.mem.indexOfScalar(u8, stmt, '(') orelse stmt.len;+ if (std.mem.indexOfScalar(u8, stmt[0..paren], '=')) |eq| {+ // `==` or a comparison is not an assignment we care about.+ if (eq + 1 < stmt.len and stmt[eq + 1] == '=') return stmt;+ const lhs = std.mem.trim(u8, stmt[0..eq], " \t");+ if (!isIdent(lhs)) return null;+ return trimStart(stmt[eq + 1 ..], " \t");+ }+ return stmt;+}++fn isIdent(s: []const u8) bool {+ if (s.len == 0) return false;+ if (!identStart(s[0])) return false;+ for (s[1..]) |c| if (!identCont(c)) return false;+ return true;+}++fn identStart(c: u8) bool {+ return (c >= 'A' and c <= 'Z') or (c >= 'a' and c <= 'z') or c == '_';+}++fn identCont(c: u8) bool {+ return identStart(c) or (c >= '0' and c <= '9');+}++fn lastParen(s: []const u8) ?usize {+ if (s.len == 0 or s[s.len - 1] != ')') return null;+ return s.len - 1;+}++const Arg = struct { key: ?[]const u8, value: Value };++const Value = union(enum) {+ string: []const u8,+ int: i64,+ bool: bool,+};++fn parseArgs(arena: Allocator, tool: []const u8, inner: []const u8) !?[]const u8 {+ var args: std.ArrayList(Arg) = .empty;+ var i: usize = 0;+ const src = inner;+ skipWs(src, &i);+ if (i >= src.len) return try canonicalize(arena, tool, &.{});+ while (i < src.len) {+ skipWs(src, &i);+ if (i >= src.len) break;+ var key: ?[]const u8 = null;+ const start = i;+ if (identStart(src[i])) {+ i += 1;+ while (i < src.len and identCont(src[i])) i += 1;+ const ident = src[start..i];+ skipWs(src, &i);+ if (i < src.len and src[i] == '=') {+ i += 1;+ key = ident;+ skipWs(src, &i);+ } else {+ i = start;+ }+ }+ const val = (try parseValue(arena, src, &i)) orelse return null;+ try args.append(arena, .{ .key = key, .value = val });+ skipWs(src, &i);+ if (i >= src.len) break;+ if (src[i] != ',') return null;+ i += 1;+ }+ return try canonicalize(arena, tool, args.items);+}++fn parseValue(arena: Allocator, src: []const u8, i: *usize) !?Value {+ if (i.* >= src.len) return null;+ const c = src[i.*];+ if (c == '"' or c == '\'') return .{ .string = (try parseString(arena, src, i)) orelse return null };+ if (c == '-' or (c >= '0' and c <= '9')) return parseInt(src, i);+ if (takeWord(src, i, "true")) return .{ .bool = true };+ if (takeWord(src, i, "false")) return .{ .bool = false };+ return null;+}++fn parseString(arena: Allocator, src: []const u8, i: *usize) !?[]const u8 {+ const q = src[i.*];+ i.* += 1;+ var out: std.ArrayList(u8) = .empty;+ var esc = false;+ while (i.* < src.len) : (i.* += 1) {+ const c = src[i.*];+ if (esc) {+ try out.append(arena, switch (c) {+ 'n' => '\n',+ 't' => '\t',+ else => c,+ });+ esc = false;+ continue;+ }+ if (c == '\\') {+ esc = true;+ continue;+ }+ if (c == q) {+ i.* += 1;+ return @as(?[]const u8, try out.toOwnedSlice(arena));+ }+ try out.append(arena, c);+ }+ return null;+}++fn parseInt(src: []const u8, i: *usize) ?Value {+ const start = i.*;+ if (src[i.*] == '-') i.* += 1;+ if (i.* >= src.len or src[i.*] < '0' or src[i.*] > '9') {+ i.* = start;+ return null;+ }+ while (i.* < src.len and src[i.*] >= '0' and src[i.*] <= '9') i.* += 1;+ const n = std.fmt.parseInt(i64, src[start..i.*], 10) catch return null;+ return .{ .int = n };+}++fn takeWord(src: []const u8, i: *usize, word: []const u8) bool {+ if (i.* + word.len > src.len) return false;+ if (!std.mem.eql(u8, src[i.*..][0..word.len], word)) return false;+ const after = i.* + word.len;+ if (after < src.len and identCont(src[after])) return false;+ i.* = after;+ return true;+}++fn trimStart(s: []const u8, cutset: []const u8) []const u8 {+ var i: usize = 0;+ while (i < s.len and std.mem.indexOfScalar(u8, cutset, s[i]) != null) i += 1;+ return s[i..];+}++fn skipWs(src: []const u8, i: *usize) void {+ while (i.* < src.len and (src[i.*] == ' ' or src[i.*] == '\t')) i.* += 1;+}++fn canonicalize(arena: Allocator, tool: []const u8, args: []const Arg) ![]const u8 {+ var obj: std.json.ObjectMap = .empty;+ const field = hostField(tool);+ if (args.len == 1 and args[0].key == null) {+ try putValue(arena, &obj, field, args[0].value);+ } else {+ for (args) |a| {+ const k = a.key orelse return error.NeedKeywords;+ try putValue(arena, &obj, k, a.value);+ }+ }+ var aw: std.Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.write(std.json.Value{ .object = obj });+ return aw.toOwnedSlice();+}++fn hostField(tool: []const u8) []const u8 {+ if (std.mem.eql(u8, tool, "read_file")) return "path";+ 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";+ return "arg";+}++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 },+ .int => |n| .{ .integer = n },+ .bool => |b| .{ .bool = b },+ };+ try obj.put(arena, key, jv);+}++test "Segmenter yields a line only after the newline, then flushes the tail" {+ const gpa = std.testing.allocator;+ var seg: Segmenter = .{};+ defer seg.deinit(gpa);+ const none = try seg.feed(gpa, "a = read_file(\"x\")");+ defer gpa.free(none);+ try std.testing.expectEqual(@as(usize, 0), none.len);+ const one = try seg.feed(gpa, "\nb = read_file(\"y\")\n");+ defer {+ for (one) |s| gpa.free(s);+ gpa.free(one);+ }+ try std.testing.expectEqual(@as(usize, 2), one.len);+ try std.testing.expectEqualStrings("a = read_file(\"x\")", one[0]);+ try std.testing.expectEqualStrings("b = read_file(\"y\")", one[1]);+}++test "extractCall reads positional and keyword literals; print and names are skipped" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const r = (try extractCall(a, "x = read_file(\"docs/a.txt\")")).?;+ try std.testing.expectEqualStrings("read_file", r.name);+ try std.testing.expectEqualStrings("{\"path\":\"docs/a.txt\"}", r.args_json);+ const k = (try extractCall(a, "codedb(command=\"status\")")).?;+ try std.testing.expectEqualStrings("{\"command\":\"status\"}", k.args_json);+ const s = (try extractCall(a, "sleep_ms(40)")).?;+ try std.testing.expectEqualStrings("{\"ms\":40}", s.args_json);+ try std.testing.expect(try extractCall(a, "print(x)") == null);+ try std.testing.expect(try extractCall(a, "read_file(path)") == null);+ try std.testing.expect(try extractCall(a, "# just a comment") == null);+}++test "extractCalls finds independent sleeps in a three-call script" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const src = [_][]const u8{+ "a = sleep_ms(40)",+ "b = sleep_ms(40)",+ "c = sleep_ms(40)",+ "print(a)",+ };+ const calls = try extractCalls(a, &src);+ try std.testing.expectEqual(@as(usize, 3), calls.len);+ try std.testing.expectEqualStrings("sleep_ms", calls[0].name);+}