graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Preserve dependent tool order and stopped results in scripts
Rach Pradhancf4e87f303d3
diff --git a/docs/adr/0175-rlm-preserves-dependent-tool-order.md b/docs/adr/0175-rlm-preserves-dependent-tool-order.mdnew file mode 100644index 00000000..3cc843dc--- /dev/null+++ b/docs/adr/0175-rlm-preserves-dependent-tool-order.md@@ -0,0 +1,32 @@+# 0175. RLM preserves dependent tool order++Status: accepted 2026-09-23++## Context++Speculating every literal host call lets verification race ahead of an edit.+A failed edit can then leave later side effects behind. Nested host calls also+need to retain errors, cancellation, and pending status in the outer result.++## Decision++Only a leading sequence of explicitly read-only host calls may overlap or start+while source streams. The first other statement closes that speculation window+for the rest of the script, including subsequent streamed chunks. Shell calls,+mutations, and unknown external tools execute in statement order.++Discard speculative result reuse at that boundary. Repeated mutations execute+each time, and reads after mutations obtain fresh results. Previously assigned+bindings retain their original values.++Stop evaluation on a failed, cancelled, or pending host result and preserve its+status in the outer result, including calls inside `print` and `each`. Record+each executed host result once at execution, rather than replaying observations+from a cache.++## Consequences++Independent leading reads still overlap. Shell and external calls lose implicit+speculative parallelism; expanding the allowlist requires a verified read-only+contract. `src/rlm_order_tests.zig` covers ordered edits, stopped evaluation,+fresh reads, repeated writes, and the streaming boundary.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 863a9c3b..d5e7b217 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -198,6 +198,7 @@ record only when you need the evidence or the edge cases.| [0173](0173-loaded-tool-order-survives-resume.md) | Native and external schemas share admission order, which survives session save and restore. || [0174](0174-completion-requires-terminal-tool-results.md) | Deferred completion rejects pending work and preserves background verification exit status. |+| [0175](0175-rlm-preserves-dependent-tool-order.md) | RLM speculates only leading read-only calls, then preserves statement order and stopped tool results. |## When to write onediff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex 2df1908a..4ddf4f47 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -127,3 +127,7 @@{"id": "exact-reply-one-call", "why": "An explicit literal reply needs no edit-oriented fake-done retry.", "args": ["--lean", "-p", "Reply with exactly: pong"], "prompt": "Reply with exactly: pong", "script": [{"text": "pong"}], "assert": [{"request_count": 1}, {"stdout_equals": "pong\n"}]}{"id": "exact-reply-quoted-action-words", "why": "An explicit literal reply needs no edit-oriented fake-done retry.", "args": ["--lean", "-p", "Reply with exactly: \"run tests and deploy\""], "prompt": "Reply with exactly: \"run tests and deploy\"", "script": [{"text": "run tests and deploy"}], "assert": [{"request_count": 1}, {"stdout_equals": "run tests and deploy\n"}]}{"id": "exact-reply-mixed-coding-bounces", "why": "A trailing coding request must retain the first-response backstop and perform the actual write.", "args": ["--lean", "-p", "Reply with exactly: \"pong\"; then create target.txt containing changed."], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Reply with exactly: \"pong\"; then create target.txt containing changed.", "script": [{"text": "pong"}, {"tool": "write_file", "arguments": {"path": "target.txt", "content": "changed\n"}}, {"tool": "bash", "arguments": {"command": "test \"$(cat target.txt)\" = changed"}}, {"text": "Created and verified target.txt."}], "assert": [{"request_count": 4}, {"request_contains": {"index": 1, "text": "a description alone is not completion"}}, {"file_equals": {"path": "target.txt", "content": "changed\n"}}, {"stdout_equals": "Created and verified target.txt.\n"}]}+{"args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Run the scripted RLM ordering fixture and report only observed results.", "workspace_seed": {"target.txt": "old"}, "id": "rlm-ordered-edit-then-verification", "why": "A dependent verification sees the preceding edit within one RLM script.", "script": [{"tool": "rlm", "arguments": {"code": "e = edit_file(path=\"target.txt\", old_string=\"old\", new_string=\"new\")\nv = bash(\"test $(cat target.txt) = new && printf ORDER_VERIFIED\")\nprint(v)"}}, {"text": "Ordered verification passed."}], "assert": [{"event": {"type": "tool_call_finished", "name": "rlm", "is_error": false}}, {"request_contains": {"index": 1, "text": "ORDER_VERIFIED"}}, {"file_equals": {"path": "target.txt", "content": "new"}}]}+{"args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Run the scripted RLM ordering fixture and report only observed results.", "workspace_seed": {"target.txt": "old"}, "id": "rlm-failed-edit-blocks-tail", "why": "A failed native edit aborts dependent RLM commands without marker side effects.", "script": [{"tool": "rlm", "arguments": {"code": "e = edit_file(path=\"target.txt\", old_string=\"absent\", new_string=\"new\")\nv = bash(\"printf ran > marker\")\nprint(v)"}}, {"text": "The edit failed; the later command did not run."}], "verify_command": ["python3", "-c", "from pathlib import Path; assert not Path('marker').exists()"], "assert": [{"event": {"type": "tool_call_finished", "name": "rlm", "is_error": true}}, {"file_equals": {"path": "target.txt", "content": "old"}}]}+{"args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Run the scripted RLM ordering fixture and report only observed results.", "workspace_seed": {"target.txt": "old"}, "id": "rlm-nested-shell-failure-status", "why": "A nested shell failure propagates error status and prevents later nested mutation.", "script": [{"tool": "rlm", "arguments": {"code": "print(bash(\"printf NESTED_FAILURE; exit 7\"), write_file(path=\"marker\", content=\"ran\"))"}}, {"text": "The nested command failed."}], "verify_command": ["python3", "-c", "from pathlib import Path; assert not Path('marker').exists()"], "assert": [{"event": {"type": "tool_call_finished", "name": "rlm", "is_error": true}}, {"request_contains": {"index": 1, "text": "NESTED_FAILURE"}}]}+{"args": [], "env": {"GRAFF_NO_CODEDB_GUARD": "1"}, "prompt": "Run the scripted RLM ordering fixture and report only observed results.", "workspace_seed": {"target.txt": "old"}, "id": "rlm-pending-host-blocks-tail-completion", "why": "Pending nested background work preserves pending status, stops later mutation and cannot satisfy same-batch completion.", "script": [{"tools": [{"tool": "rlm", "arguments": {"code": "print(bash(command=\"sleep 0.2; exit 0\", run_in_background=true), write_file(path=\"marker\", content=\"ran\"))"}}, {"tool": "attempt_completion", "arguments": {"result": "PREMATURE_COMPLETION"}}]}, {"text": "Verification is still pending."}], "verify_command": ["python3", "-c", "from pathlib import Path; assert not Path('marker').exists()"], "assert": [{"event": {"type": "tool_call_finished", "name": "rlm", "is_error": false}}, {"event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": true}}, {"no_event": {"type": "tool_call_finished", "name": "attempt_completion", "is_error": false}}, {"final_text_contains": "Verification is still pending."}]}diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 2492a0ad..6c9a6238 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -15,7 +15,7 @@"src/repl.zig","TUI/root.zig"],- "test_count_baseline": 2674,+ "test_count_baseline": 2684,"test_count_slack": 25,"required_invariants": [{diff --git a/src/job_notify.zig b/src/job_notify.zigindex 790c76de..424d1f9f 100644--- a/src/job_notify.zig+++ b/src/job_notify.zig@@ -40,6 +40,15 @@ var count: usize = 0;var dismissed: [cap]u32 = undefined;var dismissed_len: usize = 0;+/// Unit fixtures must join their job pumps before clearing notification state.+pub fn resetForTest(io: Io) void {+ if (!@import("builtin").is_test) @compileError("test-only notification reset");+ mu.lockUncancelable(io);+ defer mu.unlock(io);+ count = 0;+ dismissed_len = 0;+}+fn clipCmd(cmd: []const u8) struct { buf: [48]u8, len: u8 } {const t = std.mem.trim(u8, cmd, " \t\r\n");const keep: u8 = @intCast(@min(t.len, 48));diff --git a/src/main.zig b/src/main.zigindex 1a797337..ce24ce65 100644--- a/src/main.zig+++ b/src/main.zig@@ -584,7 +584,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = .{ @import("acp_protocol.zig"), @import("subagent_mimo_tests.zig"), @import("gateway_picker_catalog.zig") };_ = @import("task_outcome.zig"); // goal-outcome telemetry events_ = @import("learn_delete.zig"); // #303: its tests were dead until listed here- _ = .{ @import("additional_tests.zig"), @import("req_stats.zig"), @import("exact_reply.zig") };+ _ = .{ @import("additional_tests.zig"), @import("req_stats.zig"), @import("exact_reply.zig"), @import("rlm_order_tests.zig") };_ = @import("goal_pacing_autonomous_test.zig");_ = @import("goal_state.zig");_ = @import("goal_persist_tests.zig");diff --git a/src/rlm.zig b/src/rlm.zigindex 455e706c..2f762477 100644--- a/src/rlm.zig+++ b/src/rlm.zig@@ -3,8 +3,8 @@//! On unless `--old` / `--no-rlm` / `GRAFF_OLD=1` / `GRAFF_RLM=0`. `--rlm`//! and `GRAFF_RLM=1` force it back on. Host functions: `read_file`, `codedb`//! (real graff tools), `sleep_ms` (overlap proof), `llm_query` (RLM tools-off-//! sub-LM), `print` (answer), plus loaded MCP names (ADR 0029). Closed literal-//! calls launch as the `code` argument streams (spec-ptc) and again at exec.+//! sub-LM), `print` (answer), plus loaded MCP names (ADR 0029). Leading safe+//! literal reads overlap while streaming; subsequent calls execute lexically.const std = @import("std");const Io = std.Io;@@ -25,10 +25,10 @@ const mcp_shapes = @import("mcp_shapes.zig");const read_miss = @import("read_miss.zig");pub const tool_name = "rlm";-pub const tool_desc = "Programmatic tool calling (RLM + sPTC). Functions ARE this session's tools. Literal read_file/codedb/bash/webfetch/sleep_ms/llm_query/subagent start as the script streams. Binds persist. subagent(\"task\") is sidecar-only (keep the critical-path next step local). Loaded MCP names are host functions after load_tool_schemas; tools.server.tool(...) is that name; each(arr, tool, field) maps a JSON array; len(x)/project(x, field) slim it. print() is the answer. Prefer one rlm over N tool calls.";+pub const tool_desc = "Programmatic tool calling (RLM + sPTC). Functions ARE this session's tools. Leading read_file/codedb/sleep_ms/llm_query calls overlap as it streams; other calls run in order, stopping on error/cancel/pending. Binds persist. subagent(\"task\") is sidecar-only (keep the critical-path next step local). Loaded MCP names are host functions after load_tool_schemas; tools.server.tool(...) is that name; each(arr, tool, field) maps a JSON array; len(x)/project(x, field) slim it. print() is the answer. Prefer one rlm over N tool calls.";/// --lean catalog desc: same contract, no REPL essay. maybeAppend is after/// compactLeanSpecs, so this is the one-shot wire text.-pub const lean_tool_desc = "Batch independent read_file/codedb/bash here. print(read_file(\"p\")) returns the file — do not catalog-read it again. Then edit_file/write_file/bash as catalog tools. Literal calls start as it streams. Binds persist. Loaded MCP names are host functions after load_tool_schemas.";+pub const lean_tool_desc = "Batch independent read_file/codedb here. print(read_file(\"p\")) returns the file — do not catalog-read it again. Then edit_file/write_file/bash as catalog tools. Leading reads overlap; other calls run in order, stopping on error/cancel/pending. Binds persist. Loaded MCP names are host functions after load_tool_schemas.";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\") / subagent(\"task\") / loaded mcp__server__tool() or tools.server.tool(); each(arr, tool, field) maps a JSON array; len(x) and project(x, field) slim it; print(...) is the result. Assignments persist across rlm calls."}}, "required": ["code"]};@@ -86,6 +86,7 @@ pub fn exec(ctx: ToolCtx, input: Value) !ToolOutput {}const Binding = rlm_spec.Binding;+const order = @import("rlm_order.zig");pub fn runScript(ctx: ToolCtx, code: []const u8) !ToolOutput {sync();@@ -103,30 +104,29 @@ pub fn runScript(ctx: ToolCtx, code: []const u8) !ToolOutput {const stmts = try spec_ptc.splitStatements(arena, code);- const calls = try spec_ptc.extractCalls(arena, stmts);- try speculate(ctx, arena, calls, &claimed);- // Observe only joined host results, including calls that began while the- // script streamed. The recorder serializes updates from concurrent scripts.- if (ctx.publication_observer) |observer| {- var observed = std.StringHashMap(void).init(arena);- for (calls) |call| {- const key = try call.key(arena);- if (try observed.fetchPut(key, {})) |_| continue;- const output = claimed.get(key) orelse continue;- const input_value = pathValue(arena, call.args_json);- try observer.record(observer.context, .{ .id = "rlm", .name = call.name, .input = input_value }, .{ .text = output.text, .is_error = output.is_error, .cancelled = output.cancelled, .pending = output.pending });- }+ var leading: std.ArrayList(spec_ptc.Call) = .empty;+ for (stmts) |stmt| {+ const safe_calls = try order.leading(arena, stmt) orelse break;+ try leading.appendSlice(arena, safe_calls);}-+ const calls = leading.items;+ 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);+ var barrier = false;for (stmts) |stmt| {+ if (!barrier and try order.leading(arena, stmt) == null) {+ barrier = true;+ var old = claimed.valueIterator();+ while (old.next()) |out| ctx.gpa.free(out.text);+ claimed.clearRetainingCapacity();+ }if (try evalStmt(ctx, arena, stmt, binds.items, &claimed, &printed, &binds)) |err| {- return .{ .text = err, .is_error = true };+ return err;}}if (printed.items.len == 0) return .{ .text = try ctx.gpa.dupe(u8, "(rlm: script produced no print())") };@@ -218,6 +218,15 @@ fn pathValue(arena: Allocator, args_json: []const u8) Value {}fn runHost(ctx: ToolCtx, call: spec_ptc.Call) ToolOutput {+ const out = runHostRaw(ctx, call);+ observe(ctx, call, out) catch {+ ctx.gpa.free(out.text);+ return .{ .text = ctx.gpa.dupe(u8, "rlm: could not record host result") catch &.{}, .is_error = true };+ };+ return out;+}++fn runHostRaw(ctx: ToolCtx, call: spec_ptc.Call) ToolOutput {if (std.mem.eql(u8, call.name, "sleep_ms") or std.mem.eql(u8, call.name, "llm_query")) {if (ctx.run_budget) |budget| if (budget.toolRefusal(ctx.gpa, ctx.tracer)) |denied| return denied;}@@ -261,7 +270,7 @@ fn evalStmt(claimed: *std.StringHashMap(ToolOutput),printed: *std.ArrayList(u8),bind_out: *std.ArrayList(Binding),-) !?[]u8 {+) !?ToolOutput {switch (try rlm_mcp.evalEach(ctx, arena, stmt, binds, bind_out, runHost)) {.miss => {},.ok => return null,@@ -270,23 +279,27 @@ fn evalStmt(switch (try rlm_reduce.evalStmt(arena, ctx.gpa, stmt, binds, bind_out)) {.miss => {},.ok => return null,- .fail => |e| return e,+ .fail => |e| return .{ .text = e, .is_error = true },}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);+ const cached = claimed.get(key);+ const out = cached orelse runHost(ctx, c);+ defer if (cached == null) ctx.gpa.free(out.text);+ if (order.stopped(out)) return try order.copy(ctx.gpa, out);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(ctx, arena, inner, binds, claimed);+ var status: ?ToolOutput = null;+ const text = try renderPrint(ctx, arena, inner, binds, claimed, &status);+ if (status) |out| return out;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});+ return .{ .text = try std.fmt.allocPrint(ctx.gpa, "rlm: unsupported statement: {s}", .{stmt}), .is_error = true };}fn assignName(stmt: []const u8) ?[]const u8 {@@ -302,18 +315,19 @@ fn printArgs(stmt: []const u8) ?[]const u8 {return t["print(".len .. t.len - 1];}-fn renderPrint(ctx: ToolCtx, arena: Allocator, inner: []const u8, binds: []const Binding, claimed: *std.StringHashMap(ToolOutput)) ![]const u8 {+fn renderPrint(ctx: ToolCtx, arena: Allocator, inner: []const u8, binds: []const Binding, claimed: *std.StringHashMap(ToolOutput), status: *?ToolOutput) ![]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(ctx, arena, part, binds, claimed));+ try out.appendSlice(arena, try renderPrintPart(ctx, arena, part, binds, claimed, status));+ if (status.* != null) break;}return out.toOwnedSlice(arena);}-fn renderPrintPart(ctx: ToolCtx, arena: Allocator, inner: []const u8, binds: []const Binding, claimed: *std.StringHashMap(ToolOutput)) ![]const u8 {+fn renderPrintPart(ctx: ToolCtx, arena: Allocator, inner: []const u8, binds: []const Binding, claimed: *std.StringHashMap(ToolOutput), status: *?ToolOutput) ![]const u8 {const t = std.mem.trim(u8, inner, " \t");if (t.len >= 2 and (t[0] == '"' or t[0] == '\'') and t[t.len - 1] == t[0]) return t[1 .. t.len - 1];if (rlm_reduce.evalExpr(arena, t, binds)) |text| return maybeSlim(arena, text) else |_| {}@@ -324,9 +338,13 @@ fn renderPrintPart(ctx: ToolCtx, arena: Allocator, inner: []const u8, binds: []c}if (try spec_ptc.extractCall(arena, t)) |c| {const key = try c.key(arena);- if (claimed.get(key)) |hit| return maybeSlim(arena, hit.text);- const out = runHost(ctx, c);- defer ctx.gpa.free(out.text);+ const cached = claimed.get(key);+ const out = cached orelse runHost(ctx, c);+ defer if (cached == null) ctx.gpa.free(out.text);+ if (order.stopped(out)) {+ status.* = try order.copy(ctx.gpa, out);+ return "";+ }if (mcp_shapes.slim(arena, out.text)) |s| return s;return try arena.dupe(u8, out.text);}@@ -336,3 +354,11 @@ fn renderPrintPart(ctx: ToolCtx, arena: Allocator, inner: []const u8, binds: []cfn maybeSlim(arena: Allocator, payload: []const u8) []const u8 {return mcp_shapes.slim(arena, payload) orelse payload;}++fn observe(ctx: ToolCtx, call: spec_ptc.Call, out: ToolOutput) !void {+ if (ctx.publication_observer) |observer| {+ var arena = std.heap.ArenaAllocator.init(ctx.gpa);+ defer arena.deinit();+ try observer.record(observer.context, .{ .id = "rlm", .name = call.name, .input = pathValue(arena.allocator(), call.args_json) }, .{ .text = out.text, .is_error = out.is_error, .cancelled = out.cancelled, .pending = out.pending });+ }+}diff --git a/src/rlm_mcp.zig b/src/rlm_mcp.zigindex 3ab16da0..fffb3058 100644--- a/src/rlm_mcp.zig+++ b/src/rlm_mcp.zig@@ -152,6 +152,7 @@ fn firstField(reg: *mcp.Registry, qualified: []const u8) ?[]const u8 {}pub const StmtHit = union(enum) { miss, ok, fail: []u8 };+pub const HostHit = union(enum) { miss, ok, fail: ToolOutput };/// `each(arr, tool, field)` — map a JSON array through one host tool./// Smallest control flow that makes `for issue in list_issues(): list_comments(id)` honest.@@ -162,30 +163,30 @@ pub fn evalEach(binds: []const rlm_spec.Binding,bind_out: *std.ArrayList(rlm_spec.Binding),run: *const fn (ToolCtx, spec_ptc.Call) ToolOutput,-) !StmtHit {+) !HostHit {const parsed = parseEach(arena, stmt) orelse return .miss;const arr_text = resolveBind(binds, parsed.arr) orelse parsed.arr;const tool = stripQuotes(parsed.tool);const field = stripQuotes(parsed.field);const items = jsonArray(arena, arr_text) catch {- return .{ .fail = try std.fmt.allocPrint(ctx.gpa, "rlm: each() needs a JSON array (got {s})", .{arr_text}) };+ return .{ .fail = .{ .text = try std.fmt.allocPrint(ctx.gpa, "rlm: each() needs a JSON array (got {s})", .{arr_text}), .is_error = true } };};var out: std.ArrayList(u8) = .empty;try out.append(arena, '[');for (items, 0..) |item, i| {if (i > 0) try out.append(arena, ',');const val = fieldValue(arena, item, field) catch {- return .{ .fail = try std.fmt.allocPrint(ctx.gpa, "rlm: each() item missing field {s}", .{field}) };+ return .{ .fail = .{ .text = try std.fmt.allocPrint(ctx.gpa, "rlm: each() item missing field {s}", .{field}), .is_error = true } };};const args = try std.fmt.allocPrint(arena, "{{\"arg\":{s}}}", .{val});const call: spec_ptc.Call = .{ .name = tool, .args_json = args };const ready = switch (prepare(ctx, arena, call)) {- .refuse => |r| return .{ .fail = r.text },+ .refuse => |r| return .{ .fail = r },.run => |c| c,};const got = run(ctx, ready);defer ctx.gpa.free(got.text);- if (got.is_error) return .{ .fail = try ctx.gpa.dupe(u8, got.text) };+ if (@import("rlm_order.zig").stopped(got)) return .{ .fail = try @import("rlm_order.zig").copy(ctx.gpa, got) };const piece = jsonOrString(arena, got.text);try out.appendSlice(arena, piece);}diff --git a/src/rlm_order.zig b/src/rlm_order.zignew file mode 100644index 00000000..7743dd19--- /dev/null+++ b/src/rlm_order.zig@@ -0,0 +1,37 @@+//! Only a leading, explicitly safe read wave may execute speculatively.+const std = @import("std");+const ptc = @import("spec_ptc.zig");+const tools = @import("tools.zig");++pub fn safe(call: ptc.Call) bool {+ return std.mem.eql(u8, call.name, "read_file") or std.mem.eql(u8, call.name, "codedb") or std.mem.eql(u8, call.name, "llm_query") or std.mem.eql(u8, call.name, "sleep_ms");+}++pub fn leading(arena: std.mem.Allocator, stmt: []const u8) !?[]const ptc.Call {+ if (try ptc.extractCall(arena, stmt)) |call| {+ if (!safe(call)) return null;+ const calls = try arena.alloc(ptc.Call, 1);+ calls[0] = call;+ return calls;+ }+ const text = std.mem.trim(u8, stmt, " \t");+ if (!std.mem.startsWith(u8, text, "print(") or text[text.len - 1] != ')') return null;+ const parts = try ptc.splitTopLevel(arena, text[6 .. text.len - 1], ',');+ var calls: std.ArrayList(ptc.Call) = .empty;+ for (parts) |part| {+ const call = try ptc.extractCall(arena, part) orelse return null;+ if (!safe(call)) return null;+ try calls.append(arena, call);+ }+ return if (calls.items.len > 0) calls.items else null;+}++pub fn stopped(out: tools.ToolOutput) bool {+ return out.is_error or out.cancelled or out.pending;+}++pub fn copy(gpa: std.mem.Allocator, out: tools.ToolOutput) !tools.ToolOutput {+ var result = out;+ result.text = try gpa.dupe(u8, out.text);+ return result;+}diff --git a/src/rlm_order_tests.zig b/src/rlm_order_tests.zignew file mode 100644index 00000000..e46676a0--- /dev/null+++ b/src/rlm_order_tests.zig@@ -0,0 +1,200 @@+const std = @import("std");+const rlm = @import("rlm.zig");+const spec = @import("rlm_spec.zig");+const tools = @import("tools.zig");+const gpa = std.testing.allocator;+const io = std.testing.io;++const Fixture = struct {+ tmp: std.testing.TmpDir,+ client: std.http.Client,+ cwd: []u8,+ fn init() !Fixture {+ var tmp = std.testing.tmpDir(.{});+ errdefer tmp.cleanup();+ try tmp.dir.writeFile(io, .{ .sub_path = "target.txt", .data = "old" });+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const n = try tmp.dir.realPath(io, &buf);+ return .{ .tmp = tmp, .client = .{ .allocator = gpa, .io = io }, .cwd = try gpa.dupe(u8, buf[0..n]) };+ }+ fn ctx(self: *Fixture) tools.ToolCtx {+ return .{ .gpa = gpa, .io = io, .client = &self.client, .provider = undefined, .registry = null, .from_sub = false, .approvals = null, .tracer = null, .agent_cwd = self.cwd };+ }+ fn deinit(self: *Fixture) void {+ @import("jobs.zig").jobsReap(gpa, io);+ @import("job_notify.zig").resetForTest(io);+ rlm.resetLive(gpa, io);+ self.client.deinit();+ gpa.free(self.cwd);+ self.tmp.cleanup();+ }+ fn run(self: *Fixture, code: []const u8) !tools.ToolOutput {+ return rlm.runScript(self.ctx(), code);+ }+};++test "rlm order applies native edit before dependent verification" {+ var f = try Fixture.init();+ defer f.deinit();+ const out = try f.run("e = edit_file(path=\"target.txt\", old_string=\"old\", new_string=\"new\")\nv = bash(\"test $(cat target.txt) = new && printf VERIFIED\")\nprint(v)");+ defer gpa.free(out.text);+ try std.testing.expect(!out.is_error and !out.pending);+ try std.testing.expectEqualStrings("VERIFIED", out.text);+}++test "rlm order failed edit prevents following verification side effects" {+ var f = try Fixture.init();+ defer f.deinit();+ const out = try f.run("e = edit_file(path=\"target.txt\", old_string=\"absent\", new_string=\"new\")\nv = bash(\"printf ran > marker\")\nprint(v)");+ defer gpa.free(out.text);+ try std.testing.expect(out.is_error);+ try std.testing.expectError(error.FileNotFound, f.tmp.dir.openFile(io, "marker", .{}));+}++test "rlm order repeated mutations execute twice and post mutation read is fresh" {+ var f = try Fixture.init();+ defer f.deinit();+ const out = try f.run("before = read_file(\"target.txt\")\na = bash(\"printf x >> target.txt\")\nb = bash(\"printf x >> target.txt\")\nafter = read_file(\"target.txt\")\nprint(before, after)");+ defer gpa.free(out.text);+ try std.testing.expect(!out.is_error);+ try std.testing.expectEqualStrings("old\noldxx", out.text);+}++test "rlm order nested failed host prevents later mutation" {+ var f = try Fixture.init();+ defer f.deinit();+ const out = try f.run("print(bash(\"printf FAILED; exit 7\"), write_file(path=\"marker\", content=\"ran\"))");+ defer gpa.free(out.text);+ try std.testing.expect(out.is_error);+ try std.testing.expect(std.mem.indexOf(u8, out.text, "FAILED") != null);+ try std.testing.expectError(error.FileNotFound, f.tmp.dir.openFile(io, "marker", .{}));+}++test "rlm order pending direct and nested hosts stop and preserve status" {+ var f = try Fixture.init();+ defer f.deinit();+ for ([_][]const u8{+ "v = bash(command=\"sleep 0.1\", run_in_background=true)\nx = write_file(path=\"marker\", content=\"ran\")\nprint(v)",+ "print(bash(command=\"sleep 0.1\", run_in_background=true), write_file(path=\"marker\", content=\"ran\"))",+ }) |code| {+ const out = try f.run(code);+ defer gpa.free(out.text);+ try std.testing.expect(out.pending and !out.is_error);+ try std.testing.expectError(error.FileNotFound, f.tmp.dir.openFile(io, "marker", .{}));+ }+}++const ReadHost = struct {+ var started: std.atomic.Value(usize) = .init(0);+ var overlap: std.atomic.Value(bool) = .init(false);+ fn run(ctx: tools.ToolCtx, _: @import("spec_ptc.zig").Call) tools.ToolOutput {+ _ = started.fetchAdd(1, .seq_cst);+ for (0..100) |_| {+ if (started.load(.seq_cst) >= 2) {+ overlap.store(true, .seq_cst);+ break;+ }+ ctx.io.sleep(.fromMilliseconds(1), .awake) catch {};+ }+ return .{ .text = ctx.gpa.dupe(u8, "read") catch unreachable };+ }+};++test "rlm order streamed prefix reads overlap and barrier survives partial chunks" {+ var f = try Fixture.init();+ defer f.deinit();+ const saved = spec.run_host;+ defer spec.run_host = saved;+ spec.run_host = ReadHost.run;+ ReadHost.started.store(0, .seq_cst);+ ReadHost.overlap.store(false, .seq_cst);+ spec.feedLive(f.ctx(), "a = read_file(\"a\")\nb = read_file(\"b\")\ne = edit_file(path=\"target.txt\", ");+ spec.feedLive(f.ctx(), "old_string=\"old\", new_string=\"new\")\nc = read_file(\"target.txt\")\n");+ var arena = std.heap.ArenaAllocator.init(gpa);+ defer arena.deinit();+ var claimed = std.StringHashMap(tools.ToolOutput).init(gpa);+ defer {+ var it = claimed.valueIterator();+ while (it.next()) |out| gpa.free(out.text);+ claimed.deinit();+ }+ spec.takeLive(f.ctx(), &claimed, arena.allocator());+ try std.testing.expectEqual(@as(usize, 2), ReadHost.started.load(.seq_cst));+ try std.testing.expect(ReadHost.overlap.load(.seq_cst));+}++test "rlm order cancelled shell preserves cancellation and prevents tail mutation" {+ var f = try Fixture.init();+ defer f.deinit();+ const cancel = @import("cancel_source.zig");+ defer cancel.clear();+ cancel.cancel(.json_cancel);+ const out = try f.run("print(bash(\"sleep 0.1\"), write_file(path=\"marker\", content=\"ran\"))");+ defer gpa.free(out.text);+ try std.testing.expect(out.cancelled and out.is_error);+ try std.testing.expectError(error.FileNotFound, f.tmp.dir.openFile(io, "marker", .{}));+}++const StoppedHost = struct {+ var count: usize = 0;+ var pending: bool = false;+ fn run(ctx: tools.ToolCtx, _: @import("spec_ptc.zig").Call) tools.ToolOutput {+ count += 1;+ return .{ .text = ctx.gpa.dupe(u8, "stopped") catch unreachable, .pending = pending, .cancelled = !pending };+ }+};++test "rlm order each preserves pending and cancellation without binding partial results" {+ var f = try Fixture.init();+ defer f.deinit();+ var arena = std.heap.ArenaAllocator.init(gpa);+ defer arena.deinit();+ for ([_]bool{ true, false }) |pending| {+ StoppedHost.count = 0;+ StoppedHost.pending = pending;+ const binds = [_]spec.Binding{.{ .name = "items", .text = "[{\"id\":1},{\"id\":2}]" }};+ var outputs: std.ArrayList(spec.Binding) = .empty;+ const hit = try @import("rlm_mcp.zig").evalEach(f.ctx(), arena.allocator(), "out = each(items, \"read_file\", \"id\")", &binds, &outputs, StoppedHost.run);+ try std.testing.expect(hit == .fail);+ defer gpa.free(hit.fail.text);+ try std.testing.expectEqual(pending, hit.fail.pending);+ try std.testing.expectEqual(!pending, hit.fail.cancelled);+ try std.testing.expectEqual(@as(usize, 1), StoppedHost.count);+ try std.testing.expectEqual(@as(usize, 0), outputs.items.len);+ }+}++const Observed = struct {+ names: [8][]const u8 = undefined,+ count: usize = 0,+ fn record(context: *anyopaque, call: tools.ToolCall, _: tools.ExecResult) !void {+ const self: *Observed = @ptrCast(@alignCast(context));+ self.names[self.count] = try gpa.dupe(u8, call.name);+ self.count += 1;+ }+};++test "rlm order observes each lexical host output exactly once in execution order" {+ var f = try Fixture.init();+ defer f.deinit();+ try f.tmp.dir.writeFile(io, .{ .sub_path = "items.json", .data = "[{\"id\":1},{\"id\":2}]" });+ var observed: Observed = .{};+ defer for (observed.names[0..observed.count]) |name| gpa.free(name);+ var state: @import("pr_local_checks.zig").State = .{};+ var ctx = f.ctx();+ ctx.publication_observer = .{ .context = &observed, .state = &state, .record = Observed.record };+ const out = try rlm.runScript(ctx, "items = read_file(\"items.json\")\nmapped = each(items, \"sleep_ms\", \"id\")\ne = write_file(path=\"target.txt\", content=\"new\")\nr = read_file(\"target.txt\")\nprint(r)");+ defer gpa.free(out.text);+ try std.testing.expect(!out.is_error);+ try std.testing.expectEqualStrings("new", out.text);+ try std.testing.expectEqual(@as(usize, 5), observed.count);+ for ([_][]const u8{ "read_file", "sleep_ms", "sleep_ms", "write_file", "read_file" }, observed.names[0..observed.count]) |want, got| try std.testing.expectEqualStrings(want, got);+}++test "rlm order unresolved print argument prevents speculative tail reads" {+ var arena = std.heap.ArenaAllocator.init(gpa);+ defer arena.deinit();+ const order = @import("rlm_order.zig");+ try std.testing.expect(try order.leading(arena.allocator(), "print(bash(command=cmd), read_file(\"x\"))") == null);+ try std.testing.expect(try order.leading(arena.allocator(), "print(read_file(\"a\"), read_file(\"b\"))") != null);+}diff --git a/src/rlm_spec.zig b/src/rlm_spec.zigindex 85a2a638..41af19d4 100644--- a/src/rlm_spec.zig+++ b/src/rlm_spec.zig@@ -8,6 +8,7 @@ const Allocator = std.mem.Allocator;const spec_ptc = @import("spec_ptc.zig");const tools = @import("tools.zig");+const order = @import("rlm_order.zig");const ToolCtx = tools.ToolCtx;const ToolOutput = tools.ToolOutput;@@ -22,7 +23,7 @@ pub var run_host: ?*const fn (ToolCtx, spec_ptc.Call) ToolOutput = null;/// `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): session tools as a script. Literal read_file/codedb/bash/llm_query/subagent start as it streams. Binds persist until /new or /clear. subagent(\"task\") is sidecar-only; keep the critical-path next step local. Loaded MCP names are host functions (tools.server.tool(...) too); each() maps a JSON array; len/project slim it. print(...) is the answer.";+pub const system_note = "\n\nrlm(code): tools as script. Leading reads overlap; other calls run in order, stopping on error/cancel/pending. Binds persist until /new or /clear. subagent() is sidecar-only; keep critical-path local. Loaded MCP names are functions (tools.server.tool too). each maps arrays; len/project slim them. print() returns 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@@ -110,6 +111,7 @@ const Inflight = struct {const Live = struct {mu: Io.Mutex = .init,ready: bool = false,+ barrier: bool = false,seg: spec_ptc.Segmenter = .{},launched: std.StringHashMap(void) = undefined,inflight: std.ArrayList(Inflight) = .empty,@@ -166,6 +168,7 @@ pub fn takeLive(ctx: ToolCtx, claimed: *std.StringHashMap(ToolOutput), arena: Allive.launched.clearRetainingCapacity();live.seg.deinit(ctx.gpa);live.seg = .{};+ live.barrier = false;}fn liveInit(gpa: Allocator) void {@@ -191,6 +194,7 @@ fn resetUnlocked(gpa: Allocator, io: Io) void {}live.seg.deinit(gpa);live.seg = .{};+ live.barrier = false;}fn runHostThunk(ctx: ToolCtx, call: spec_ptc.Call) ToolOutput {@@ -206,14 +210,18 @@ fn launchStmts(ctx: ToolCtx, stmts: []const []const u8) void {for (stmts) |stmt| {const pieces = spec_ptc.splitStatements(arena, stmt) catch continue;for (pieces) |piece| {- launchOne(ctx, arena, piece);+ if (live.barrier) continue;+ const calls = (order.leading(arena, piece) catch null) orelse {+ live.barrier = true;+ continue;+ };+ for (calls) |call| launchOne(ctx, arena, call);}}}-fn launchOne(ctx: ToolCtx, arena: Allocator, stmt: []const u8) void {+fn launchOne(ctx: ToolCtx, arena: Allocator, call: spec_ptc.Call) 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;diff --git a/src/rlm_tests.zig b/src/rlm_tests.zigindex 195d86a2..b9a931fc 100644--- a/src/rlm_tests.zig+++ b/src/rlm_tests.zig@@ -333,7 +333,7 @@ test "runScript empty subagent() reaches execSubagent; persist binds do not breatry std.testing.expectEqualStrings("slept 1ms", reuse.text);}-test "feedLive launches two independent subagent() calls before runScript claims" {+test "feedLive leaves side-effecting subagents for lexical execution" {const gpa = std.testing.allocator;const io = std.testing.io;var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };@@ -356,12 +356,7 @@ test "feedLive launches two independent subagent() calls before runScript claimsvar arena_state = std.heap.ArenaAllocator.init(gpa);defer arena_state.deinit();rlm_spec.takeLive(ctx, &claimed, arena_state.allocator());- try std.testing.expectEqual(@as(usize, 2), claimed.count());- var it = claimed.iterator();- while (it.next()) |e| {- try std.testing.expect(e.value_ptr.is_error);- try std.testing.expect(std.mem.indexOf(u8, e.value_ptr.text, "prompt") != null);- }+ try std.testing.expectEqual(@as(usize, 0), claimed.count());}test "rlm prompt: subagent() is advertised as sidecar-only, not a critical-path handoff" {