graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(rlm): MCP host functions + return-shape cache
Cursor Agent35d5e97141b5
diff --git a/graff-evals/README.md b/graff-evals/README.mdindex 93866edc..78c96f33 100644--- a/graff-evals/README.md+++ b/graff-evals/README.md@@ -13,13 +13,14 @@ harness under test spends model calls.## Suites-`--suite` selects which tasks run (`all` is the default):+`--suite` selects which tasks run (`all` is core+rlm+swe; `mcp` is opt-in):| suite | what it measures ||---|---|| `core` | sequential single-file work (instruction, debug, git, schema, …) || `rlm` | scatter-gather / multi-file reads (where default rlm can overlap) || `swe` | DeepSWE-shaped multi-file bugfixes, distilled from [deepswe.datacurve.ai/run](https://deepswe.datacurve.ai/run) (no Harbor/Docker) |+| `mcp` | Linear-shaped fixture MCP (Blacksmith code-mode + muscle memory). Use `--no-lean` harnesses. |```sh./run.py --suite swe --harness graff-dev-old,graff-dev --model grok-4.6 -j 12diff --git a/graff-evals/harnesses.json b/graff-evals/harnesses.jsonindex 49cb9897..2d7915b2 100644--- a/graff-evals/harnesses.json+++ b/graff-evals/harnesses.json@@ -34,6 +34,36 @@"default_model": "grok-4.6","note": "explicit --rlm (same as graff-dev after RLM became the default)"},+ "graff-dev-nolean": {+ "cmd": ["{repo}/zig-out/bin/graff", "-p", "{prompt}", "--model", "{model}", "--yolo", "--no-lean"],+ "answer": "stdout",+ "usage": "graff-stderr",+ "capabilities": ["output-schema"],+ "schema_args": ["--output-schema", "{schema}"],+ "env": {"GRAFF_POST_DEADLINE_SECS": "90"},+ "default_model": "grok-4.6",+ "note": "default rlm + MCP visible (need --no-lean for load_tool_schemas); MCP host functions on"+ },+ "graff-dev-rlm-struct": {+ "cmd": ["{repo}/zig-out/bin/graff", "-p", "{prompt}", "--model", "{model}", "--yolo", "--no-lean"],+ "answer": "stdout",+ "usage": "graff-stderr",+ "capabilities": ["output-schema"],+ "schema_args": ["--output-schema", "{schema}"],+ "env": {"GRAFF_POST_DEADLINE_SECS": "90", "GRAFF_RLM_MCP": "0"},+ "default_model": "grok-4.6",+ "note": "default rlm but MCP stays structured-only (today's gap / variant B)"+ },+ "graff-dev-old-nolean": {+ "cmd": ["{repo}/zig-out/bin/graff", "-p", "{prompt}", "--model", "{model}", "--yolo", "--old", "--no-lean"],+ "answer": "stdout",+ "usage": "graff-stderr",+ "capabilities": ["output-schema"],+ "schema_args": ["--output-schema", "{schema}"],+ "env": {"GRAFF_POST_DEADLINE_SECS": "90"},+ "default_model": "grok-4.6",+ "note": "--old structured MCP only + --no-lean so load_tool_schemas is visible"+ },"graff-dev-old": {"cmd": ["{repo}/zig-out/bin/graff", "-p", "{prompt}", "--model", "{model}", "--yolo", "--old"],"answer": "stdout",diff --git a/graff-evals/hidden/check_linear_report.py b/graff-evals/hidden/check_linear_report.pynew file mode 100644index 00000000..7cd7087d--- /dev/null+++ b/graff-evals/hidden/check_linear_report.py@@ -0,0 +1,31 @@+#!/usr/bin/env python3+"""Held-out check for the Linear-shaped MCP bench. The agent never sees this."""+import json+import os+import sys++EXPECTED = {+ "ISS-1": ("Login timeout on session resume", 2, "bev"),+ "ISS-2": ("Checkout tax rounding", 3, "eli"),+ "ISS-3": ("Search index lag", 1, "fay"),+ "ISS-4": ("Webhook retries drop 429s", 4, "jay"),+ "ISS-5": ("Avatar upload EXIF leak", 2, "lee"),+ "ISS-6": ("Board filter forgets assignee", 3, "oak"),+ "ISS-7": ("CSV export truncates UTF-8", 1, "pip"),+ "ISS-8": ("Nightly digest duplicates", 4, "tess"),+}++path = "report.json"+if not os.path.exists(path):+ sys.exit("report.json missing")+data = json.load(open(path))+assert data.get("issue_count") == 8, data.get("issue_count")+issues = data.get("issues") or []+assert len(issues) == 8, len(issues)+got = {i["id"]: i for i in issues}+for iid, (title, n, author) in EXPECTED.items():+ row = got[iid]+ assert row["title"] == title, (iid, row.get("title"), title)+ assert int(row["comment_count"]) == n, (iid, row.get("comment_count"), n)+ assert row["latest_author"] == author, (iid, row.get("latest_author"), author)+print("linear-report-ok")diff --git a/graff-evals/run.py b/graff-evals/run.pyindex 6aefd8f5..27dbc7a9 100755--- a/graff-evals/run.py+++ b/graff-evals/run.py@@ -10,6 +10,7 @@ outcome, and writes JSONL results plus a summary table../run.py --harness graff --model grok-4.6 # full suite (core + rlm + swe)./run.py --suite rlm --harness graff-dev-old,graff-dev # scatter-gather A/B./run.py --suite swe --harness graff-dev-old,graff-dev -j 12 # DeepSWE-shaped A/B, parallel+ ./run.py --suite mcp --harness graff-dev-old-nolean,graff-dev-rlm-struct,graff-dev-nolean./run.py --harness grok --task fix-fib --reps 3 # one task, 3 reps./run.py --interactive # pick + watch live"""@@ -350,7 +351,7 @@ def main():ap.add_argument("--harness", default="graff", help="comma-separated harness names (see harnesses.json)")ap.add_argument("--model", default=None, help="model id (default: per-harness default_model)")ap.add_argument("--task", action="append", help="task id filter (repeatable)")- ap.add_argument("--suite", default="all", help="core, rlm, swe, comma-mix, or all (default all)")+ ap.add_argument("--suite", default="all", help="core, rlm, swe, mcp, comma-mix, or all (core+rlm+swe; mcp is opt-in)")ap.add_argument("--reps", type=int, default=1)ap.add_argument("--jobs", "-j", type=int, default=1,help="parallel task×harness runs (default 1; each has its own sandbox)")@@ -367,12 +368,15 @@ def main():stamp = time.strftime("%Y%m%d-%H%M%S")out_path = os.path.join(RESULTS_DIR, f"run-{stamp}.jsonl")suites = {s.strip() for s in args.suite.split(",") if s.strip()}+ if "all" in suites:+ suites.update({"core", "rlm", "swe"})+ suites.discard("all")picked = {}for tid, t in tasks.items():if args.task and tid not in args.task:continuesuite = t.get("suite", "core")- if "all" not in suites and suite not in suites:+ if suite not in suites:continuepicked[tid] = twork = []diff --git a/graff-evals/tasks/24-linear-issues.json b/graff-evals/tasks/24-linear-issues.jsonnew file mode 100644index 00000000..56a91941--- /dev/null+++ b/graff-evals/tasks/24-linear-issues.json@@ -0,0 +1,12 @@+{+ "id": "linear-issues",+ "suite": "mcp",+ "category": "mcp-shapes",+ "prompt": "This workspace has a Linear-shaped MCP server named linear (stdio, deferred). Load its schemas, then fetch all 8 issues and every issue's comments. Write report.json as {\"issue_count\": N, \"issues\": [{\"id\", \"title\", \"comment_count\", \"latest_author\"}, ...]} in ISS-1..ISS-8 order. latest_author is the author.name of the newest comment (last in that issue's list). Do not invent ids or authors. If rlm is available, prefer one script after load_tool_schemas: issues = list_issues(); comments = each(issues, list_comments, \"id\").",+ "files": {+ ".mcp.json": "{\"mcpServers\":{\"linear\":{\"command\":\"python3\",\"args\":[\"linear_fixture_mcp.py\"]}}}\n"+ },+ "setup": ["python3 -c \"import pathlib,shutil; p=pathlib.Path('.').resolve(); root=next(x for x in p.parents if (x/'scripts'/'linear_fixture_mcp.py').exists()); shutil.copy(root/'scripts'/'linear_fixture_mcp.py','.')\""],+ "check": "python3 \"$TASK_ROOT/hidden/check_linear_report.py\"",+ "timeout_s": 240+}diff --git a/graff-evals/tasks/25-linear-warm.json b/graff-evals/tasks/25-linear-warm.jsonnew file mode 100644index 00000000..888a6ee7--- /dev/null+++ b/graff-evals/tasks/25-linear-warm.json@@ -0,0 +1,13 @@+{+ "id": "linear-warm",+ "suite": "mcp",+ "category": "mcp-shapes",+ "prompt": "This workspace has a Linear-shaped MCP server named linear (stdio, deferred). Load its schemas, then fetch all 8 issues and every issue's comments. Write report.json as {\"issue_count\": N, \"issues\": [{\"id\", \"title\", \"comment_count\", \"latest_author\"}, ...]} in ISS-1..ISS-8 order. latest_author is the author.name of the newest comment (last in that issue's list). Do not invent ids or authors. If rlm is available, prefer one script after load_tool_schemas: issues = list_issues(); comments = each(issues, list_comments, \"id\").",+ "files": {+ ".mcp.json": "{\"mcpServers\":{\"linear\":{\"command\":\"python3\",\"args\":[\"linear_fixture_mcp.py\"]}}}\n",+ ".graff/mcp-shapes.json": "{\"mcp__linear__list_issues\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"keys\":{\"id\":\"string\",\"identifier\":\"string\",\"title\":\"string\",\"description\":\"string\",\"team\":\"object\",\"labels\":\"array\",\"cycle\":\"object\",\"project\":\"object\",\"state\":\"object\",\"estimate\":\"number\",\"priority\":\"number\",\"url\":\"string\",\"createdAt\":\"string\",\"updatedAt\":\"string\",\"dueDate\":\"null\",\"parentId\":\"null\",\"subscriberIds\":\"array\",\"assignee\":\"object\",\"sla\":\"object\",\"customFields\":\"object\",\"attachments\":\"array\",\"metadata\":\"object\"}}},\"mcp__linear__list_comments\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"keys\":{\"id\":\"string\",\"issueId\":\"string\",\"body\":\"string\",\"author\":\"object\",\"createdAt\":\"string\",\"updatedAt\":\"string\",\"url\":\"string\",\"edited\":\"bool\",\"parentId\":\"null\",\"reactions\":\"array\",\"metadata\":\"object\"}}}}\n"+ },+ "setup": ["python3 -c \"import pathlib,shutil; p=pathlib.Path('.').resolve(); root=next(x for x in p.parents if (x/'scripts'/'linear_fixture_mcp.py').exists()); shutil.copy(root/'scripts'/'linear_fixture_mcp.py','.')\""],+ "check": "python3 \"$TASK_ROOT/hidden/check_linear_report.py\"",+ "timeout_s": 240+}diff --git a/graff-evals/tasks/26-linear-sidecar.json b/graff-evals/tasks/26-linear-sidecar.jsonnew file mode 100644index 00000000..100229a0--- /dev/null+++ b/graff-evals/tasks/26-linear-sidecar.json@@ -0,0 +1,12 @@+{+ "id": "linear-sidecar",+ "suite": "mcp",+ "category": "mcp-shapes",+ "prompt": "This workspace has a Linear-shaped MCP server named linear (stdio, deferred). Fetch all 8 issues and every issue's comments, then write report.json as {\"issue_count\": N, \"issues\": [{\"id\", \"title\", \"comment_count\", \"latest_author\"}, ...]} in ISS-1..ISS-8 order. latest_author is the author.name of the newest comment (last in that issue's list). Keep the MCP fetch on the root (critical path). You may spawn one sidecar subagent only to draft a one-line summary of the report after the data is on disk — do not hand list_issues/list_comments to a child.",+ "files": {+ ".mcp.json": "{\"mcpServers\":{\"linear\":{\"command\":\"python3\",\"args\":[\"linear_fixture_mcp.py\"]}}}\n"+ },+ "setup": ["python3 -c \"import pathlib,shutil; p=pathlib.Path('.').resolve(); root=next(x for x in p.parents if (x/'scripts'/'linear_fixture_mcp.py').exists()); shutil.copy(root/'scripts'/'linear_fixture_mcp.py','.')\""],+ "check": "python3 \"$TASK_ROOT/hidden/check_linear_report.py\"",+ "timeout_s": 240+}diff --git a/graff-evals/tasks/27-linear-split.json b/graff-evals/tasks/27-linear-split.jsonnew file mode 100644index 00000000..938fb687--- /dev/null+++ b/graff-evals/tasks/27-linear-split.json@@ -0,0 +1,12 @@+{+ "id": "linear-split",+ "suite": "mcp",+ "category": "mcp-shapes",+ "prompt": "This workspace has a Linear-shaped MCP server named linear (stdio, deferred). Write report.json as {\"issue_count\": N, \"issues\": [{\"id\", \"title\", \"comment_count\", \"latest_author\"}, ...]} in ISS-1..ISS-8 order. latest_author is the author.name of the newest comment (last in that issue's list). Split the 8 issues across two sibling subagents (ISS-1..4 and ISS-5..8). Each child should fetch comments for its half and return counts + latest authors. Root writes report.json.",+ "files": {+ ".mcp.json": "{\"mcpServers\":{\"linear\":{\"command\":\"python3\",\"args\":[\"linear_fixture_mcp.py\"]}}}\n"+ },+ "setup": ["python3 -c \"import pathlib,shutil; p=pathlib.Path('.').resolve(); root=next(x for x in p.parents if (x/'scripts'/'linear_fixture_mcp.py').exists()); shutil.copy(root/'scripts'/'linear_fixture_mcp.py','.')\""],+ "check": "python3 \"$TASK_ROOT/hidden/check_linear_report.py\"",+ "timeout_s": 240+}diff --git a/scripts/eval-mcp-shapes.py b/scripts/eval-mcp-shapes.pynew file mode 100755index 00000000..8653d4eb--- /dev/null+++ b/scripts/eval-mcp-shapes.py@@ -0,0 +1,172 @@+#!/usr/bin/env python3+"""Run the Blacksmith-shaped MCP A/B (variants A–E) and print the table.++ zig build -Doptimize=ReleaseSafe+ python3 scripts/eval-mcp-shapes.py+ python3 scripts/eval-mcp-shapes.py --mock # scripted model, no provider++Records pass/fail, wall, RSS, tokens, API calls, and whether the model+retried or guessed wrong MCP fields (from .graff/traces).+"""++from __future__ import annotations++import argparse+import json+import os+import re+import subprocess+import sys+from pathlib import Path++REPO = Path(__file__).resolve().parents[1]+EVALS = REPO / "graff-evals"+WRONG = re.compile(+ r"unknown|missing required|needs id|unsupported statement|not loaded|GRAFF_RLM_MCP|bad args|issue_id|issueId",+ re.I,+)+++VARIANTS = [+ {+ "id": "A",+ "harness": "graff-dev-old-nolean",+ "task": "linear-issues",+ "label": "--old structured MCP only",+ },+ {+ "id": "B",+ "harness": "graff-dev-rlm-struct",+ "task": "linear-issues",+ "label": "default rlm, MCP structured-only",+ },+ {+ "id": "C",+ "harness": "graff-dev-nolean",+ "task": "linear-issues",+ "label": "rlm + MCP host, cold",+ },+ {+ "id": "D",+ "harness": "graff-dev-nolean",+ "task": "linear-warm",+ "label": "rlm + MCP host, warm shapes",+ },+ {+ "id": "E1",+ "harness": "graff-dev-nolean",+ "task": "linear-sidecar",+ "label": "C + sidecar summarize subagent",+ },+ {+ "id": "E2",+ "harness": "graff-dev-nolean",+ "task": "linear-split",+ "label": "two sibling subagents split 8 issues",+ },+]+++def parse_traces(sandbox: Path) -> dict:+ retried = False+ wrong = False+ mcp_calls = 0+ rlm_calls = 0+ for path in sandbox.glob(".graff/traces/*.jsonl"):+ for line in path.read_text().splitlines():+ if not line.startswith("{"):+ continue+ try:+ ev = json.loads(line)+ except json.JSONDecodeError:+ continue+ name = ev.get("name") or ev.get("tool") or ""+ text = str(ev.get("text") or ev.get("output") or "")+ if name.startswith("mcp__") or name in {"list_issues", "list_comments"}:+ mcp_calls += 1+ if name == "rlm":+ rlm_calls += 1+ if ev.get("is_error") or ev.get("error"):+ if WRONG.search(text) or WRONG.search(name):+ wrong = True+ retried = True+ if "load_tool_schemas first" in text or "not loaded" in text:+ retried = True+ wrong = True+ return {"retried": retried, "wrong_fields": wrong, "mcp_calls": mcp_calls, "rlm_calls": rlm_calls}+++def main() -> int:+ ap = argparse.ArgumentParser()+ ap.add_argument("--mock", action="store_true", help="skip live provider (print harness plan only)")+ ap.add_argument("--model", default="grok-4.6")+ args = ap.parse_args()++ if args.mock:+ print("mock: not driving a provider. Unit tests cover dispatch/shapes; live A/B needs SuperGrok.")+ for v in VARIANTS:+ print(f" {v['id']} {v['harness']} {v['task']} {v['label']}")+ return 0++ oauth = Path.home() / ".xai/credentials/graff-oauth.json"+ if not oauth.exists():+ print("no SuperGrok OAuth at ~/.xai/credentials/graff-oauth.json — pass --mock or sign in", file=sys.stderr)+ return 2++ rows = []+ for v in VARIANTS:+ cmd = [+ sys.executable,+ str(EVALS / "run.py"),+ "--suite",+ "mcp",+ "--task",+ v["task"],+ "--harness",+ v["harness"],+ "--model",+ args.model,+ "--reps",+ "1",+ ]+ print(f"== {v['id']} {v['label']} ==", flush=True)+ subprocess.run(cmd, cwd=EVALS, check=False)+ # newest result line for this harness/task+ results = sorted((EVALS / "results").glob("run-*.jsonl"))+ rec = None+ if results:+ for line in reversed(results[-1].read_text().splitlines()):+ try:+ r = json.loads(line)+ except json.JSONDecodeError:+ continue+ if r.get("harness") == v["harness"] and r.get("task") == v["task"]:+ rec = r+ break+ sandbox = EVALS / ".sandboxes" / f"{v['harness']}-{v['task']}-r1"+ extra = parse_traces(sandbox) if sandbox.exists() else {}+ row = {"variant": v["id"], "label": v["label"], **(rec or {}), **extra}+ rows.append(row)+ print(json.dumps({k: row.get(k) for k in (+ "variant", "outcome_ok", "wall_s", "rss_peak_kb", "tok_in", "tok_out",+ "tok_calls", "retried", "wrong_fields")}, default=str), flush=True)++ out = EVALS / "results" / "mcp-shapes-summary.json"+ out.write_text(json.dumps(rows, indent=2) + "\n")+ print(f"\nsummary → {out}")+ print(f"{'var':<4} {'pass':<5} {'wall':>7} {'RSS':>8} {'in':>8} {'out':>6} {'calls':>5} {'retry':<6} {'wrong':<6} label")+ for row in rows:+ ok = "✓" if row.get("outcome_ok") else "✗"+ print(+ f"{row['variant']:<4} {ok:<5} {row.get('wall_s') or 0:7.1f} "+ f"{(row.get('rss_peak_kb') or 0) / 1024:7.1f}M "+ f"{row.get('tok_in') or 0:8} {row.get('tok_out') or 0:6} "+ f"{row.get('tok_calls') or 0:5} "+ f"{'yes' if row.get('retried') else 'no':<6} "+ f"{'yes' if row.get('wrong_fields') else 'no':<6} {row['label']}"+ )+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/linear_fixture_mcp.py b/scripts/linear_fixture_mcp.pynew file mode 100755index 00000000..b2e5e77b--- /dev/null+++ b/scripts/linear_fixture_mcp.py@@ -0,0 +1,157 @@+#!/usr/bin/env python3+"""Stdio MCP fixture shaped like Blacksmith's Linear task.++list_issues returns 8 fat issue objects. list_comments returns a fat comment+list per issue id. The point is payload size + return-shape guessing, not+Linear OAuth. JSON-RPC, one object per line, on stdin/stdout.+"""++from __future__ import annotations++import json+import sys++PAD = "x" * 400+++def issue(n: int) -> dict:+ return {+ "id": f"ISS-{n}",+ "identifier": f"ENG-{100 + n}",+ "title": (+ "Login timeout on session resume",+ "Checkout tax rounding",+ "Search index lag",+ "Webhook retries drop 429s",+ "Avatar upload EXIF leak",+ "Board filter forgets assignee",+ "CSV export truncates UTF-8",+ "Nightly digest duplicates",+ )[n - 1],+ "description": f"Long description for issue {n}. {PAD}",+ "team": {"id": "team-eng", "name": "Engineering", "key": "ENG", "pad": PAD},+ "labels": [{"id": f"lab-{i}", "name": f"label-{i}", "color": "#059669", "pad": PAD[:80]} for i in range(6)],+ "cycle": {"id": "cyc-9", "name": "Cycle 9", "startsAt": "2026-08-01", "endsAt": "2026-08-14", "pad": PAD},+ "project": {"id": "proj-1", "name": "Platform", "state": "started", "pad": PAD},+ "state": {"id": "st-open", "name": "In Progress", "type": "started", "pad": PAD},+ "estimate": n + 2,+ "priority": (n % 4) + 1,+ "url": f"https://linear.app/fixture/issue/ENG-{100 + n}",+ "createdAt": f"2026-08-0{n}T10:00:00Z",+ "updatedAt": f"2026-08-1{n}T12:00:00Z",+ "dueDate": None,+ "parentId": None,+ "subscriberIds": [f"user-{i}" for i in range(12)],+ "assignee": {"id": f"user-{n}", "name": f"Dev {n}", "email": f"dev{n}@example.test", "pad": PAD},+ "sla": {"breached": False, "status": "ok", "pad": PAD},+ "customFields": {f"cf_{i}": f"value-{i}-{PAD[:40]}" for i in range(8)},+ "attachments": [{"id": f"att-{n}-{i}", "url": f"https://files.example/{n}/{i}", "pad": PAD} for i in range(3)],+ "metadata": {"workspaceId": "ws-1", "pad": PAD},+ }+++AUTHORS = {+ 1: ["ada", "bev"],+ 2: ["cam", "deb", "eli"],+ 3: ["fay"],+ 4: ["gus", "hal", "ivy", "jay"],+ 5: ["kim", "lee"],+ 6: ["mo", "nia", "oak"],+ 7: ["pip"],+ 8: ["quin", "raj", "sky", "tess"],+}+++def comments(issue_id: str) -> list[dict]:+ n = int(issue_id.split("-")[1])+ out = []+ for i, author in enumerate(AUTHORS[n], start=1):+ out.append({+ "id": f"C-{n}-{i}",+ "issueId": issue_id,+ "body": f"Comment {i} on {issue_id} by {author}. {PAD}",+ "author": {"id": f"u-{author}", "name": author, "email": f"{author}@example.test", "pad": PAD},+ "createdAt": f"2026-08-{10 + i:02d}T0{i}:00:00Z",+ "updatedAt": f"2026-08-{10 + i:02d}T1{i}:00:00Z",+ "url": f"https://linear.app/fixture/comment/C-{n}-{i}",+ "edited": False,+ "parentId": None,+ "reactions": [{"emoji": "👍", "count": i, "pad": PAD[:60]} for _ in range(4)],+ "metadata": {"pad": PAD},+ })+ return out+++TOOLS = [+ {+ "name": "list_issues",+ "description": "List issues in the fixture workspace. Returns fat issue objects (many unused fields).",+ "inputSchema": {"type": "object", "properties": {}},+ },+ {+ "name": "list_comments",+ "description": "List comments for one issue. Pass id (ISS-N). Returns a fat comment list.",+ "inputSchema": {+ "type": "object",+ "properties": {"id": {"type": "string", "description": "Issue id, e.g. ISS-1"}},+ "required": ["id"],+ },+ },+]+++def send(obj: dict) -> None:+ sys.stdout.write(json.dumps(obj, separators=(",", ":")) + "\n")+ sys.stdout.flush()+++def result(mid, payload) -> None:+ send({"jsonrpc": "2.0", "id": mid, "result": payload})+++def handle(msg: dict) -> None:+ method = msg.get("method")+ mid = msg.get("id")+ if method == "initialize":+ result(mid, {+ "protocolVersion": "2025-06-18",+ "capabilities": {"tools": {}},+ "serverInfo": {"name": "linear-fixture", "version": "1"},+ })+ return+ if method == "notifications/initialized":+ return+ if method == "server/discover":+ send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "Method not found"}})+ return+ if method == "tools/list":+ result(mid, {"tools": TOOLS})+ return+ if method == "tools/call":+ params = msg.get("params") or {}+ name = params.get("name")+ args = params.get("arguments") or {}+ if name == "list_issues":+ result(mid, {"content": [{"type": "text", "text": json.dumps([issue(i) for i in range(1, 9)])}]})+ return+ if name == "list_comments":+ iid = args.get("id") or args.get("issueId") or args.get("issue_id")+ if not iid:+ send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32602, "message": "list_comments needs id"}})+ return+ result(mid, {"content": [{"type": "text", "text": json.dumps(comments(str(iid)))}]})+ return+ send({"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": f"unknown tool {name}"}})+ return+++def main() -> None:+ for line in sys.stdin:+ line = line.strip()+ if not line:+ continue+ handle(json.loads(line))+++if __name__ == "__main__":+ main()diff --git a/src/exec.zig b/src/exec.zigindex 8e597920..6c2ab3b0 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -211,6 +211,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {return failure(gpa, err);};if (r.is_error) codedbpro_report.onFailure(ctx, call.name, r.text);+ if (!r.is_error) @import("mcp_shapes.zig").remember(ctx, call.name, r.text);return .{ .text = r.text, .is_error = r.is_error };}@@ -451,5 +452,8 @@ test { // main.zig is at the 600-line cap; exec.zig is these modules' importer,_ = @import("rlm.zig");_ = @import("rlm_spec.zig");_ = @import("rlm_query.zig");+ _ = @import("rlm_mcp.zig");+ _ = @import("rlm_tests.zig");+ _ = @import("mcp_shapes.zig");_ = @import("spec_ptc.zig");}diff --git a/src/mcp_select.zig b/src/mcp_select.zigindex 67ce4a76..26eb5eb5 100644--- a/src/mcp_select.zig+++ b/src/mcp_select.zig@@ -97,10 +97,17 @@ pub fn handleSelect(agent: anytype, input: Value) tools_mod.ExecResult {return mcp_schema_gate.handleLoad(agent, selectInput(agent.arena, input));}+fn withShapes(agent: anytype, r: tools_mod.ExecResult) tools_mod.ExecResult {+ if (r.is_error) return r;+ const cwd = agent.agent_cwd;+ const text = @import("mcp_shapes.zig").annotate(agent.gpa, agent.arena, agent.io, cwd, r.text) catch r.text;+ return .{ .text = text, .is_error = r.is_error };+}+pub fn dispatch(agent: anytype, call: tools_mod.ToolCall) tools_mod.ExecResult {- if (std.mem.eql(u8, call.name, search_name)) return handleSearch(agent, call.input);- if (std.mem.eql(u8, call.name, select_name)) return handleSelect(agent, call.input);- return mcp_schema_gate.handleLoad(agent, call.input);+ if (std.mem.eql(u8, call.name, search_name)) return withShapes(agent, handleSearch(agent, call.input));+ if (std.mem.eql(u8, call.name, select_name)) return withShapes(agent, handleSelect(agent, call.input));+ return withShapes(agent, mcp_schema_gate.handleLoad(agent, call.input));}test "search lists matches and does not enable them" {diff --git a/src/mcp_shapes.zig b/src/mcp_shapes.zignew file mode 100644index 00000000..1206e59e--- /dev/null+++ b/src/mcp_shapes.zig@@ -0,0 +1,358 @@+//! Muscle memory for tool return shapes (Blacksmith): persist field names ++//! broad types, never values. Shown on the next load_tool_schemas RESULT, not+//! on the always-on catalog prefix (ADR 0011).++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const tools = @import("tools.zig");+const ToolCtx = tools.ToolCtx;++pub const file_name = "mcp-shapes.json";+pub const rel_path = ".graff/mcp-shapes.json";++const Store = struct {+ mu: Io.Mutex = .init,+ map: std.StringHashMapUnmanaged([]const u8) = .empty,+ gpa: ?Allocator = null,+};++var store: Store = .{};++pub fn reset(gpa: Allocator, io: Io) void {+ store.mu.lockUncancelable(io);+ defer store.mu.unlock(io);+ clearUnlocked(gpa);+}++fn clearUnlocked(gpa: Allocator) void {+ var it = store.map.iterator();+ while (it.next()) |e| {+ gpa.free(e.key_ptr.*);+ gpa.free(e.value_ptr.*);+ }+ store.map.deinit(gpa);+ store.map = .empty;+ store.gpa = null;+}++/// Infer a value-free schema from a tool result. Best-effort JSON; anything+/// else is just `{"type":"string"}` so we never persist payload bytes.+pub fn infer(arena: Allocator, text: []const u8) ![]const u8 {+ const trimmed = std.mem.trim(u8, text, " \t\r\n");+ if (trimmed.len == 0) return try arena.dupe(u8, "{\"type\":\"string\"}");+ const parsed = std.json.parseFromSlice(Value, arena, trimmed, .{}) catch+ return try arena.dupe(u8, "{\"type\":\"string\"}");+ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try writeShape(arena, &s, parsed.value, 0);+ return aw.toOwnedSlice();+}++fn typeName(v: Value) []const u8 {+ return switch (v) {+ .null => "null",+ .bool => "bool",+ .integer, .float, .number_string => "number",+ .string => "string",+ .array => "array",+ .object => "object",+ };+}++fn writeShape(arena: Allocator, s: *std.json.Stringify, v: Value, depth: u8) anyerror!void {+ try s.beginObject();+ try s.objectField("type");+ try s.write(typeName(v));+ if (depth >= 3) {+ try s.endObject();+ return;+ }+ switch (v) {+ .object => |obj| {+ try s.objectField("keys");+ try s.beginObject();+ var it = obj.iterator();+ while (it.next()) |e| {+ try s.objectField(e.key_ptr.*);+ try writeKeyType(arena, s, e.value_ptr.*, depth + 1);+ }+ try s.endObject();+ },+ .array => |arr| {+ try s.objectField("items");+ if (arr.items.len == 0) {+ try s.write("any");+ } else {+ try writeMergedItems(arena, s, arr.items, depth + 1);+ }+ },+ else => {},+ }+ try s.endObject();+}++fn writeKeyType(arena: Allocator, s: *std.json.Stringify, v: Value, depth: u8) anyerror!void {+ if ((v == .object or v == .array) and depth < 3) return writeShape(arena, s, v, depth);+ try s.write(typeName(v));+}++fn writeMergedItems(arena: Allocator, s: *std.json.Stringify, items: []const Value, depth: u8) anyerror!void {+ const cap = @min(items.len, 4);+ if (items[0] != .object) return writeShape(arena, s, items[0], depth);+ var keys: std.StringHashMapUnmanaged([]const u8) = .empty;+ var i: usize = 0;+ while (i < cap) : (i += 1) {+ if (items[i] != .object) continue;+ var it = items[i].object.iterator();+ while (it.next()) |e| {+ const t = typeName(e.value_ptr.*);+ if (keys.get(e.key_ptr.*)) |old| {+ if (!std.mem.eql(u8, old, t) and !std.mem.eql(u8, old, "any"))+ try keys.put(arena, e.key_ptr.*, "any");+ } else {+ try keys.put(arena, e.key_ptr.*, t);+ }+ }+ }+ try s.beginObject();+ try s.objectField("type");+ try s.write("object");+ try s.objectField("keys");+ try s.beginObject();+ var it = keys.iterator();+ while (it.next()) |e| {+ try s.objectField(e.key_ptr.*);+ try s.write(e.value_ptr.*);+ }+ try s.endObject();+ try s.endObject();+}++fn mergeShapes(arena: Allocator, old_s: []const u8, new_s: []const u8) ![]const u8 {+ const old_p = std.json.parseFromSlice(Value, arena, old_s, .{}) catch return new_s;+ const new_p = std.json.parseFromSlice(Value, arena, new_s, .{}) catch return old_s;+ const old_keys = keysOf(old_p.value);+ const new_keys = keysOf(new_p.value);+ if (old_keys == null or new_keys == null) return new_s;+ var merged: std.json.ObjectMap = .empty;+ var it = old_keys.?.iterator();+ while (it.next()) |e| try merged.put(arena, e.key_ptr.*, e.value_ptr.*);+ var it2 = new_keys.?.iterator();+ while (it2.next()) |e| {+ if (merged.get(e.key_ptr.*)) |old_t| {+ if (old_t == .string and e.value_ptr.* == .string and+ !std.mem.eql(u8, old_t.string, e.value_ptr.string))+ try merged.put(arena, e.key_ptr.*, .{ .string = "any" });+ } else try merged.put(arena, e.key_ptr.*, e.value_ptr.*);+ }+ const typ = if (old_p.value == .object) old_p.value.object.get("type") else null;+ var out: std.json.ObjectMap = .empty;+ try out.put(arena, "type", typ orelse .{ .string = "object" });+ if (old_p.value == .object) if (old_p.value.object.get("items")) |_| {+ var items: std.json.ObjectMap = .empty;+ try items.put(arena, "type", .{ .string = "object" });+ try items.put(arena, "keys", .{ .object = merged });+ try out.put(arena, "items", .{ .object = items });+ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.write(Value{ .object = out });+ return aw.toOwnedSlice();+ };+ try out.put(arena, "keys", .{ .object = merged });+ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.write(Value{ .object = out });+ return aw.toOwnedSlice();+}++fn keysOf(v: Value) ?std.json.ObjectMap {+ if (v != .object) return null;+ if (v.object.get("keys")) |k| if (k == .object) return k.object;+ if (v.object.get("items")) |items| {+ if (items == .object) if (items.object.get("keys")) |k| if (k == .object) return k.object;+ }+ return null;+}++pub fn remember(ctx: ToolCtx, name: []const u8, text: []const u8) void {+ if (name.len == 0 or text.len == 0) return;+ var arena_state = std.heap.ArenaAllocator.init(ctx.gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const shape = infer(arena, text) catch return;+ store.mu.lockUncancelable(ctx.io);+ defer store.mu.unlock(ctx.io);+ loadUnlocked(ctx.gpa, ctx.io, ctx.agent_cwd);+ putUnlocked(ctx.gpa, arena, name, shape);+ persistUnlocked(ctx.gpa, ctx.io, ctx.agent_cwd);+}++fn putUnlocked(gpa: Allocator, arena: Allocator, name: []const u8, shape: []const u8) void {+ const merged = if (store.map.get(name)) |old|+ mergeShapes(arena, old, shape) catch shape+ else+ shape;+ const owned_shape = gpa.dupe(u8, merged) catch return;+ if (store.map.getPtr(name)) |slot| {+ gpa.free(slot.*);+ slot.* = owned_shape;+ return;+ }+ const owned_name = gpa.dupe(u8, name) catch {+ gpa.free(owned_shape);+ return;+ };+ store.map.put(gpa, owned_name, owned_shape) catch {+ gpa.free(owned_name);+ gpa.free(owned_shape);+ return;+ };+ store.gpa = gpa;+}++fn loadUnlocked(gpa: Allocator, io: Io, cwd: ?[]const u8) void {+ if (store.map.count() > 0) return;+ const opened = openBase(io, cwd) orelse return;+ defer closeBase(io, opened, cwd);+ const raw = opened.dir.readFileAlloc(io, rel_path, gpa, .limited(64 * 1024)) catch return;+ defer gpa.free(raw);+ const parsed = std.json.parseFromSlice(Value, gpa, raw, .{}) catch return;+ defer parsed.deinit();+ if (parsed.value != .object) return;+ var it = parsed.value.object.iterator();+ while (it.next()) |e| {+ if (e.value_ptr.* != .object and e.value_ptr.* != .string) continue;+ var aw: Io.Writer.Allocating = .init(gpa);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ s.write(e.value_ptr.*) catch {+ aw.deinit();+ continue;+ };+ const shape = aw.toOwnedSlice() catch continue;+ const name = gpa.dupe(u8, e.key_ptr.*) catch {+ gpa.free(shape);+ continue;+ };+ store.map.put(gpa, name, shape) catch {+ gpa.free(name);+ gpa.free(shape);+ };+ }+ store.gpa = gpa;+}++fn persistUnlocked(gpa: Allocator, io: Io, cwd: ?[]const u8) void {+ const opened = openBase(io, cwd) orelse return;+ defer closeBase(io, opened, cwd);+ opened.dir.createDir(io, ".graff", .default_dir) catch {};+ var aw: Io.Writer.Allocating = .init(gpa);+ defer aw.deinit();+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ s.beginObject() catch return;+ var it = store.map.iterator();+ while (it.next()) |e| {+ s.objectField(e.key_ptr.*) catch return;+ const parsed = std.json.parseFromSlice(Value, gpa, e.value_ptr.*, .{}) catch continue;+ defer parsed.deinit();+ s.write(parsed.value) catch return;+ }+ s.endObject() catch return;+ opened.dir.writeFile(io, .{ .sub_path = rel_path, .data = aw.writer.buffered() }) catch {};+}++const Opened = struct { dir: Io.Dir, owned: bool };++fn openBase(io: Io, cwd: ?[]const u8) ?Opened {+ if (cwd) |p| {+ const d = Io.Dir.cwd().openDir(io, p, .{}) catch return null;+ return .{ .dir = d, .owned = true };+ }+ return .{ .dir = Io.Dir.cwd(), .owned = false };+}++fn closeBase(io: Io, opened: Opened, _: ?[]const u8) void {+ if (opened.owned) {+ var d = opened.dir;+ d.close(io);+ }+}++/// Splice stored shapes onto a load_tool_schemas / search RESULT. Never call+/// this from catalog render (ADR 0011 prefix must stay byte-stable).+pub fn annotate(gpa: Allocator, arena: Allocator, io: Io, cwd: ?[]const u8, text: []const u8) ![]const u8 {+ store.mu.lockUncancelable(io);+ defer store.mu.unlock(io);+ loadUnlocked(gpa, io, cwd);+ if (store.map.count() == 0) return text;+ var aw: Io.Writer.Allocating = .init(arena);+ try aw.writer.writeAll(text);+ try aw.writer.writeAll("\nreturn_shapes (field names + broad types, never values):\n");+ var it = store.map.iterator();+ while (it.next()) |e| {+ try aw.writer.print(" {s}: {s}\n", .{ e.key_ptr.*, e.value_ptr.* });+ }+ return aw.toOwnedSlice();+}++pub fn lookup(io: Io, name: []const u8) ?[]const u8 {+ store.mu.lockUncancelable(io);+ defer store.mu.unlock(io);+ return store.map.get(name);+}++test "infer strips values and keeps keys plus broad types" {+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const shape = try infer(a,+ \\[{"id":"ISS-1","title":"Login","n":3,"ok":true,"meta":{"x":1},"tags":["a"]}]+ );+ try std.testing.expect(std.mem.indexOf(u8, shape, "ISS-1") == null);+ try std.testing.expect(std.mem.indexOf(u8, shape, "Login") == null);+ try std.testing.expect(std.mem.indexOf(u8, shape, "\"id\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, shape, "string") != null);+ try std.testing.expect(std.mem.indexOf(u8, shape, "number") != null);+ try std.testing.expect(std.mem.indexOf(u8, shape, "bool") != null);+}++test "remember merges keys; annotate splices shapes; prefix text is untouched" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ 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];+ reset(gpa, io);+ defer reset(gpa, io);+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer dummy_client.deinit();+ const ctx: ToolCtx = .{+ .gpa = gpa,+ .io = io,+ .client = &dummy_client,+ .provider = undefined,+ .registry = null,+ .from_sub = false,+ .approvals = null,+ .tracer = null,+ .agent_cwd = dir,+ };+ remember(ctx, "mcp__linear__list_issues", "[{\"id\":\"A\",\"title\":\"t\"}]");+ remember(ctx, "mcp__linear__list_issues", "[{\"id\":\"B\",\"state\":\"open\"}]");+ const hit = lookup(io, "mcp__linear__list_issues") orelse return error.MissingShape;+ try std.testing.expect(std.mem.indexOf(u8, hit, "\"id\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, hit, "\"title\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, hit, "\"state\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, hit, "\"A\"") == null);+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const annotated = try annotate(gpa, arena_state.allocator(), io, dir, "1 tool schema(s) below\nmcp__linear__list_issues");+ try std.testing.expect(std.mem.indexOf(u8, annotated, "return_shapes") != null);+ try std.testing.expect(std.mem.indexOf(u8, annotated, "mcp__linear__list_issues") != null);+ try std.testing.expect(std.mem.indexOf(u8, @import("mcp_schema_gate.zig").tool_desc, "return_shapes") == null);+}diff --git a/src/rlm.zig b/src/rlm.zigindex 21b85b80..922952ab 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). Closed literal calls launch as the `code`-//! argument streams (spec-ptc) and again at exec for anything the stream missed.+//! 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.const std = @import("std");const Io = std.Io;@@ -19,14 +19,16 @@ const no_local_tools = @import("no_local_tools.zig");const exec_mod = @import("exec.zig");const rlm_query = @import("rlm_query.zig");const rlm_spec = @import("rlm_spec.zig");+const rlm_mcp = @import("rlm_mcp.zig");+const mcp_shapes = @import("mcp_shapes.zig");pub const tool_name = "rlm";-pub const tool_desc = "Programmatic tool calling (RLM + sPTC). Script whose functions ARE this session's tools. Independent literal read_file/codedb/bash/webfetch/sleep_ms/llm_query/subagent calls start as the script streams. Binds persist across rlm calls. subagent(\"task\") is sidecar-only (keep the critical-path next step local; sync in v1; run_in_background=true returns an id). print() is the answer. Example: a = read_file(\"src/main.zig\"); b = codedb(\"status\"); print(a, b). No imports, no control flow. Prefer one rlm over N tool calls.";+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; each(arr, tool, field) maps a JSON array. 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.";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\"); print(...) is the result. Assignments persist across rlm calls. 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\") / loaded mcp__server__tool(); each(arr, tool, field) maps a JSON array; print(...) is the result. Assignments persist across rlm calls."}}, "required": ["code"]};/// Process-global: on by default. `--old` / `--no-rlm` turn it off; `--rlm`@@ -144,11 +146,25 @@ fn speculate(ctx: ToolCtx, arena: Allocator, calls: []const spec_ptc.Call, claimfn runHost(ctx: ToolCtx, call: spec_ptc.Call) ToolOutput {if (std.mem.eql(u8, call.name, "sleep_ms")) return runSleep(ctx, call.args_json);if (std.mem.eql(u8, call.name, "llm_query")) return rlm_query.run(ctx, call.args_json);- var parsed = std.json.parseFromSlice(Value, ctx.gpa, call.args_json, .{}) catch {+ if (std.mem.eql(u8, call.name, "each")) {+ return .{ .text = ctx.gpa.dupe(u8, "rlm: each() needs binds, not speculation") catch &.{}, .is_error = true };+ }+ var arena_state = std.heap.ArenaAllocator.init(ctx.gpa);+ defer arena_state.deinit();+ const ready = if (rlm_mcp.looksMcp(call.name) or rlm_mcp.resolve(ctx, call.name) != null)+ switch (rlm_mcp.prepare(ctx, arena_state.allocator(), call)) {+ .refuse => |r| return r,+ .run => |c| c,+ }+ else+ call;+ var parsed = std.json.parseFromSlice(Value, ctx.gpa, ready.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 });+ const out = exec_mod.execTool(ctx, .{ .id = "rlm", .name = ready.name, .input = parsed.value });+ if (!out.is_error and rlm_mcp.looksMcp(ready.name)) mcp_shapes.remember(ctx, ready.name, out.text);+ return out;}fn runSleep(ctx: ToolCtx, args_json: []const u8) ToolOutput {@@ -171,6 +187,11 @@ fn evalStmt(printed: *std.ArrayList(u8),bind_out: *std.ArrayList(Binding),) !?[]u8 {+ switch (try rlm_mcp.evalEach(ctx, arena, stmt, binds, bind_out, runHost)) {+ .miss => {},+ .ok => return null,+ .fail => |e| return e,+ }const call = try spec_ptc.extractCall(arena, stmt);if (call) |c| {const key = try c.key(arena);@@ -229,366 +250,3 @@ fn renderPrintPart(ctx: ToolCtx, arena: Allocator, inner: []const u8, binds: []c}return try arena.dupe(u8, t);}--fn testCtx(gpa: Allocator, io: Io, client: *std.http.Client) ToolCtx {- return .{- .gpa = gpa,- .io = io,- .client = client,- .provider = undefined,- .registry = null,- .from_sub = false,- .approvals = null,- .tracer = null,- };-}--test "maybeAppend is a no-op when --old, 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;- resetLive(gpa, io);- }- available = true;- const ctx = testCtx(gpa, io, &dummy_client);- const t0: Io.Timestamp = .now(io, .awake);- const out = try runScript(ctx, "a = sleep_ms(40)\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];- 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;- var ctx = testCtx(gpa, io, &dummy_client);- ctx.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);- const nested = try runScript(ctx, "print(read_file(\"note.txt\"))");- defer gpa.free(nested.text);- try std.testing.expect(!nested.is_error);- try std.testing.expect(std.mem.indexOf(u8, nested.text, "hello-rlm") != null);-}--test "runScript splits a semicolon one-liner and prints both binds" {- const gpa = std.testing.allocator;- const io = std.testing.io;- var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };- defer dummy_client.deinit();- const saved = available;- defer {- available = saved;- resetLive(gpa, io);- }- available = true;- const ctx = testCtx(gpa, io, &dummy_client);- const t0: Io.Timestamp = .now(io, .awake);- const out = try runScript(ctx, "a = sleep_ms(40); b = sleep_ms(41); print(a, b)");- defer gpa.free(out.text);- const dt = t0.untilNow(io, .awake).toMilliseconds();- try std.testing.expect(!out.is_error);- try std.testing.expectEqualStrings("slept 40ms\nslept 41ms", out.text);- try std.testing.expect(dt < 90);-}--test "feedLive launches sleeps before runScript, so claim is a hit not a re-run" {- const gpa = std.testing.allocator;- const io = std.testing.io;- var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };- defer dummy_client.deinit();- const saved = available;- defer {- available = saved;- resetLive(gpa, io);- }- available = true;- const ctx = testCtx(gpa, io, &dummy_client);- const t0: Io.Timestamp = .now(io, .awake);- feedLive(ctx, "a = sleep_ms(40)\n");- feedLive(ctx, "b = sleep_ms(41)\n");- feedLive(ctx, "c = sleep_ms(42)\n");- 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);- try std.testing.expect(dt < 100);-}--test "feedLive splits a semicolon line before runScript claims" {- const gpa = std.testing.allocator;- const io = std.testing.io;- var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };- defer dummy_client.deinit();- const saved = available;- defer {- available = saved;- resetLive(gpa, io);- }- available = true;- const ctx = testCtx(gpa, io, &dummy_client);- const t0: Io.Timestamp = .now(io, .awake);- feedLive(ctx, "a = sleep_ms(40); b = sleep_ms(41)\n");- const out = try runScript(ctx, "a = sleep_ms(40); b = sleep_ms(41); print(a, b)");- defer gpa.free(out.text);- const dt = t0.untilNow(io, .awake).toMilliseconds();- try std.testing.expect(!out.is_error);- try std.testing.expectEqualStrings("slept 40ms\nslept 41ms", out.text);- try std.testing.expect(dt < 90);-}--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);-}--fn catalogHas(specs: anytype, name: []const u8) bool {- for (specs) |s| if (std.mem.eql(u8, s.name, name)) return true;- return false;-}--test "maybeAppend keeps subagent and workflow; rlm is never the only catalog tool" {- 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" },- .{ .name = "subagent" },- .{ .name = "workflow" },- };- const saved = available;- const saved_local = no_local_tools.enabled;- defer {- available = saved;- no_local_tools.enabled = saved_local;- sync();- }- available = true;- no_local_tools.enabled = false;- const on = try maybeAppend(Spec, arena, &base);- try std.testing.expectEqual(@as(usize, 4), on.len);- try std.testing.expect(catalogHas(on, "subagent"));- try std.testing.expect(catalogHas(on, "workflow"));- try std.testing.expect(catalogHas(on, tool_name));- try std.testing.expect(on.len > 1);-- available = false;- const off = try maybeAppend(Spec, arena, &base);- try std.testing.expectEqual(@as(usize, 3), off.len);- try std.testing.expect(catalogHas(off, "subagent"));- try std.testing.expect(!catalogHas(off, tool_name));-}--test "effectiveRootSpecs: default rlm keeps subagent; --old and --lean do not drop it" {- const schema = @import("schema.zig");- const root = @import("main.zig");- const learn_store = @import("learn_store.zig");- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const arena = arena_state.allocator();- const saved = available;- const saved_lean = no_local_tools.lean;- const saved_local = no_local_tools.enabled;- const saved_clock = root.g_clock_sleep;- const saved_learn = learn_store.active_agent_loaded;- defer {- available = saved;- no_local_tools.lean = saved_lean;- no_local_tools.enabled = saved_local;- root.g_clock_sleep = saved_clock;- learn_store.active_agent_loaded = saved_learn;- sync();- }- no_local_tools.enabled = false;- root.g_clock_sleep = false;- learn_store.active_agent_loaded = true;-- available = true;- no_local_tools.lean = false;- sync();- const def = try schema.effectiveRootSpecs(arena);- try std.testing.expect(catalogHas(def, "subagent"));- try std.testing.expect(catalogHas(def, "workflow"));- try std.testing.expect(catalogHas(def, tool_name));- try std.testing.expect(def.len > 2);-- available = false;- sync();- const old = try schema.effectiveRootSpecs(arena);- try std.testing.expect(catalogHas(old, "subagent"));- try std.testing.expect(catalogHas(old, "workflow"));- try std.testing.expect(!catalogHas(old, tool_name));-- available = true;- no_local_tools.lean = true;- sync();- const lean_on = try schema.effectiveRootSpecs(arena);- try std.testing.expect(catalogHas(lean_on, "subagent"));- try std.testing.expect(catalogHas(lean_on, tool_name));- try std.testing.expect(!catalogHas(lean_on, "workflow"));- try std.testing.expect(catalogHas(lean_on, "bash"));- try std.testing.expect(no_local_tools.leanKeeps("subagent"));- try std.testing.expect(!no_local_tools.leanKeeps(tool_name));-}--test "runScript empty subagent() reaches execSubagent; persist binds do not break that" {- 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 miss = try runScript(ctx, "h = subagent()");- defer gpa.free(miss.text);- try std.testing.expect(miss.is_error);- try std.testing.expect(std.mem.indexOf(u8, miss.text, "missing required") != null);- try std.testing.expect(std.mem.indexOf(u8, miss.text, "prompt") != null);- 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);-}--test "feedLive launches two independent subagent() calls before runScript claims" {- const gpa = std.testing.allocator;- const io = std.testing.io;- var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };- defer dummy_client.deinit();- const saved = available;- defer {- available = saved;- resetLive(gpa, io);- }- available = true;- const ctx = testCtx(gpa, io, &dummy_client);- feedLive(ctx, "a = subagent()\n");- feedLive(ctx, "b = subagent(\"\")\n");- var claimed = std.StringHashMap(ToolOutput).init(gpa);- defer {- var it = claimed.iterator();- while (it.next()) |e| gpa.free(e.value_ptr.text);- claimed.deinit();- }- var 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);- }-}--test "rlm prompt: subagent() is advertised as sidecar-only, not a critical-path handoff" {- try std.testing.expect(std.mem.indexOf(u8, tool_desc, "sidecar-only") != null);- try std.testing.expect(std.mem.indexOf(u8, tool_desc, "critical-path") != null);- try std.testing.expect(std.mem.indexOf(u8, rlm_spec.system_note, "sidecar-only") != null);- try std.testing.expect(std.mem.indexOf(u8, rlm_spec.system_note, "critical-path") != null);- try std.testing.expect(tool_desc.len < 600);-}diff --git a/src/rlm_mcp.zig b/src/rlm_mcp.zignew file mode 100644index 00000000..78467501--- /dev/null+++ b/src/rlm_mcp.zig@@ -0,0 +1,338 @@+//! MCP-inside-rlm: after `load_tool_schemas` unfolds a tool, an rlm script+//! may call that name as a host function (same exec_mod path). Unloaded+//! names are refused. Deferral can only subtract. GRAFF_RLM_MCP=0 restores+//! today's structured-only gap. Does not import schema.zig.++const std = @import("std");+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 mcp = @import("mcp.zig");+const mcp_schema_gate = @import("mcp_schema_gate.zig");+const rlm_spec = @import("rlm_spec.zig");++/// Test / env seam. `applyEnvKnobs` sets this from GRAFF_RLM_MCP.+pub var host_enabled: bool = true;++pub const Prep = union(enum) {+ run: spec_ptc.Call,+ refuse: ToolOutput,+};++pub fn looksMcp(name: []const u8) bool {+ return mcp.Registry.isMcp(name);+}++pub fn resolve(ctx: ToolCtx, name: []const u8) ?[]const u8 {+ if (mcp.Registry.isMcp(name)) return name;+ const reg = ctx.registry orelse return null;+ var hit: ?[]const u8 = null;+ for (reg.tools) |t| {+ if (!std.mem.eql(u8, shortName(t.qualified_name), name)) continue;+ if (hit != null) return null; // ambiguous+ hit = t.qualified_name;+ }+ return hit;+}++fn shortName(qualified: []const u8) []const u8 {+ if (!std.mem.startsWith(u8, qualified, "mcp__")) return qualified;+ const rest = qualified["mcp__".len..];+ const sep = std.mem.indexOf(u8, rest, "__") orelse return qualified;+ return rest[sep + 2 ..];+}++pub fn prepare(ctx: ToolCtx, arena: Allocator, call: spec_ptc.Call) Prep {+ if (!host_enabled) {+ return .{ .refuse = fail(ctx, "rlm: MCP host functions are off (GRAFF_RLM_MCP=0) — use structured MCP calls or drop the env") };+ }+ const qualified = resolve(ctx, call.name) orelse {+ if (looksMcp(call.name))+ return .{ .refuse = fail(ctx, "rlm: unknown MCP tool") };+ return .{ .run = call };+ };+ const reg = ctx.registry orelse {+ return .{ .refuse = fail(ctx, "MCP not available in this context") };+ };+ if (mcp_schema_gate.blocked(reg.tools, qualified)) {+ return .{ .refuse = fail(ctx, "rlm: MCP tool schema is not loaded — call load_tool_schemas first (deferral only; consent is unchanged)") };+ }+ const args = remapArgs(arena, reg, qualified, call.args_json) catch call.args_json;+ return .{ .run = .{ .name = qualified, .args_json = args } };+}++fn fail(ctx: ToolCtx, msg: []const u8) ToolOutput {+ return .{ .text = ctx.gpa.dupe(u8, msg) catch &.{}, .is_error = true };+}++fn remapArgs(arena: Allocator, reg: *mcp.Registry, qualified: []const u8, args_json: []const u8) ![]const u8 {+ var parsed = std.json.parseFromSlice(Value, arena, args_json, .{}) catch return args_json;+ if (parsed.value != .object) return args_json;+ if (parsed.value.object.get("arg") == null) return args_json;+ if (parsed.value.object.count() != 1) return args_json;+ const field = firstField(reg, qualified) orelse return args_json;+ const val = parsed.value.object.get("arg").?;+ var obj: std.json.ObjectMap = .empty;+ try obj.put(arena, field, val);+ var aw: std.Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.write(Value{ .object = obj });+ return aw.toOwnedSlice();+}++fn firstField(reg: *mcp.Registry, qualified: []const u8) ?[]const u8 {+ const tool = for (reg.tools) |t| {+ if (std.mem.eql(u8, t.qualified_name, qualified)) break t;+ } else return null;+ if (tool.input_schema != .object) return null;+ if (tool.input_schema.object.get("required")) |req| {+ if (req == .array and req.array.items.len > 0 and req.array.items[0] == .string)+ return req.array.items[0].string;+ }+ if (tool.input_schema.object.get("properties")) |props| {+ if (props == .object) {+ var it = props.object.iterator();+ if (it.next()) |e| return e.key_ptr.*;+ }+ }+ return null;+}++pub const StmtHit = union(enum) { miss, ok, fail: []u8 };++/// `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.+pub fn evalEach(+ ctx: ToolCtx,+ arena: Allocator,+ stmt: []const u8,+ binds: []const rlm_spec.Binding,+ bind_out: *std.ArrayList(rlm_spec.Binding),+ run: *const fn (ToolCtx, spec_ptc.Call) ToolOutput,+) !StmtHit {+ 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}) };+ };+ 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}) };+ };+ 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 },+ .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) };+ const piece = jsonOrString(arena, got.text);+ try out.appendSlice(arena, piece);+ }+ try out.append(arena, ']');+ const text = try out.toOwnedSlice(arena);+ if (parsed.assign) |nm| try bind_out.append(arena, .{ .name = try arena.dupe(u8, nm), .text = try arena.dupe(u8, text) });+ return .ok;+}++const Each = struct { assign: ?[]const u8, arr: []const u8, tool: []const u8, field: []const u8 };++fn parseEach(arena: Allocator, stmt: []const u8) ?Each {+ const trimmed = std.mem.trim(u8, stmt, " \t");+ var rest = trimmed;+ var assign: ?[]const u8 = null;+ const paren = std.mem.indexOfScalar(u8, trimmed, '(') orelse return null;+ if (std.mem.indexOfScalar(u8, trimmed[0..paren], '=')) |eq| {+ const lhs = std.mem.trim(u8, trimmed[0..eq], " \t");+ if (lhs.len == 0) return null;+ assign = lhs;+ rest = std.mem.trim(u8, trimmed[eq + 1 ..], " \t");+ }+ if (!std.mem.startsWith(u8, rest, "each(") or rest[rest.len - 1] != ')') return null;+ const inner = rest["each(".len .. rest.len - 1];+ const parts = spec_ptc.splitTopLevel(arena, inner, ',') catch return null;+ if (parts.len != 3) return null;+ return .{ .assign = assign, .arr = parts[0], .tool = parts[1], .field = parts[2] };+}++fn resolveBind(binds: []const rlm_spec.Binding, name: []const u8) ?[]const u8 {+ const t = std.mem.trim(u8, name, " \t");+ var i = binds.len;+ while (i > 0) {+ i -= 1;+ if (std.mem.eql(u8, binds[i].name, t)) return binds[i].text;+ }+ return null;+}++fn stripQuotes(s: []const u8) []const u8 {+ const t = std.mem.trim(u8, s, " \t");+ if (t.len >= 2 and (t[0] == '"' or t[0] == '\'') and t[t.len - 1] == t[0]) return t[1 .. t.len - 1];+ return t;+}++fn jsonArray(arena: Allocator, text: []const u8) ![]const Value {+ const trimmed = std.mem.trim(u8, text, " \t\r\n");+ const parsed = try std.json.parseFromSlice(Value, arena, trimmed, .{});+ if (parsed.value == .array) return parsed.value.array.items;+ if (parsed.value == .object) {+ var it = parsed.value.object.iterator();+ while (it.next()) |e| {+ if (e.value_ptr.* == .array) return e.value_ptr.array.items;+ }+ }+ return error.NotArray;+}++fn fieldValue(arena: Allocator, item: Value, field: []const u8) ![]const u8 {+ if (item != .object) return error.NotObject;+ const v = item.object.get(field) orelse return error.Missing;+ var aw: std.Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.write(v);+ return aw.toOwnedSlice();+}++fn jsonOrString(arena: Allocator, text: []const u8) []const u8 {+ const trimmed = std.mem.trim(u8, text, " \t\r\n");+ if (std.json.parseFromSlice(Value, arena, trimmed, .{})) |_| {+ return trimmed;+ } else |_| {+ var aw: std.Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ s.write(trimmed) catch return trimmed;+ return aw.toOwnedSlice() catch trimmed;+ }+}++test "unloaded MCP name is refused; loaded name is prepared for exec" {+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const io = std.testing.io;+ mcp_schema_gate.reset();+ defer mcp_schema_gate.reset();+ mcp_schema_gate.g_policy = .{ .enabled = true, .budget = 0, .eager = &.{} };+ const all = try @import("mcp_schema_gate_tests.zig").fixture(arena, "fat", 2, 200);+ var registry = mcp.Registry.empty(gpa, io);+ defer registry.deinit();+ registry.tools = all;+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer dummy_client.deinit();+ const ctx: ToolCtx = .{+ .gpa = gpa,+ .io = io,+ .client = &dummy_client,+ .provider = undefined,+ .registry = ®istry,+ .from_sub = false,+ .approvals = null,+ .tracer = null,+ };+ const saved = host_enabled;+ defer host_enabled = saved;+ host_enabled = true;+ const call: spec_ptc.Call = .{ .name = "mcp__fat__t0", .args_json = "{}" };+ switch (prepare(ctx, arena, call)) {+ .refuse => |r| {+ defer gpa.free(r.text);+ try std.testing.expect(r.is_error);+ try std.testing.expect(std.mem.indexOf(u8, r.text, "load_tool_schemas") != null);+ },+ .run => return error.ShouldRefuseUnloaded,+ }+ const req = try std.json.parseFromSliceLeaky(Value, arena, "{\"tools\":[\"mcp__fat__t0\"]}", .{ .allocate = .alloc_always });+ _ = try mcp_schema_gate.loadInto(arena, all, req);+ try std.testing.expect(mcp_schema_gate.isLoaded("mcp__fat__t0"));+ switch (prepare(ctx, arena, call)) {+ .run => |c| try std.testing.expectEqualStrings("mcp__fat__t0", c.name),+ .refuse => return error.ShouldDispatchLoaded,+ }+ host_enabled = false;+ switch (prepare(ctx, arena, call)) {+ .refuse => |r| {+ defer gpa.free(r.text);+ try std.testing.expect(std.mem.indexOf(u8, r.text, "GRAFF_RLM_MCP") != null);+ },+ .run => return error.ShouldRefuseWhenOff,+ }+}++test "short name resolves when unique and loaded; consent/deferral still block" {+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const io = std.testing.io;+ mcp_schema_gate.reset();+ defer mcp_schema_gate.reset();+ mcp_schema_gate.g_policy = .{ .enabled = true, .budget = 0, .eager = &.{} };+ const all = try @import("mcp_schema_gate_tests.zig").fixture(arena, "fat", 1, 200);+ var registry = mcp.Registry.empty(gpa, io);+ defer registry.deinit();+ registry.tools = all;+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer dummy_client.deinit();+ const ctx: ToolCtx = .{+ .gpa = gpa,+ .io = io,+ .client = &dummy_client,+ .provider = undefined,+ .registry = ®istry,+ .from_sub = false,+ .approvals = null,+ .tracer = null,+ };+ try std.testing.expectEqualStrings("mcp__fat__t0", resolve(ctx, "t0").?);+ try std.testing.expect(mcp_schema_gate.blocked(all, "mcp__fat__t0"));+ const req = try std.json.parseFromSliceLeaky(Value, arena, "{\"tools\":[\"mcp__fat__t0\"]}", .{ .allocate = .alloc_always });+ _ = try mcp_schema_gate.loadInto(arena, all, req);+ try std.testing.expect(!mcp_schema_gate.blocked(all, "mcp__fat__t0"));+}++test "each() maps a JSON array through a host function" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer dummy_client.deinit();+ const ctx: ToolCtx = .{+ .gpa = gpa,+ .io = io,+ .client = &dummy_client,+ .provider = undefined,+ .registry = null,+ .from_sub = false,+ .approvals = null,+ .tracer = null,+ };+ const binds = [_]rlm_spec.Binding{.{ .name = "issues", .text = "[{\"id\":\"A\"},{\"id\":\"B\"}]" }};+ var bind_out: std.ArrayList(rlm_spec.Binding) = .empty;+ const run = struct {+ fn go(_: ToolCtx, call: spec_ptc.Call) ToolOutput {+ const g = std.testing.allocator;+ if (std.mem.indexOf(u8, call.args_json, "A") != null)+ return .{ .text = g.dupe(u8, "{\"n\":1}") catch &.{} };+ return .{ .text = g.dupe(u8, "{\"n\":2}") catch &.{} };+ }+ }.go;+ const hit = try evalEach(ctx, arena, "out = each(issues, \"echo\", \"id\")", &binds, &bind_out, run);+ try std.testing.expect(hit == .ok);+ try std.testing.expectEqual(@as(usize, 1), bind_out.items.len);+ try std.testing.expect(std.mem.indexOf(u8, bind_out.items[0].text, "\"n\":1") != null);+ try std.testing.expect(std.mem.indexOf(u8, bind_out.items[0].text, "\"n\":2") != null);+}diff --git a/src/rlm_spec.zig b/src/rlm_spec.zigindex 03ada0e3..1c1e9cab 100644--- a/src/rlm_spec.zig+++ b/src/rlm_spec.zig@@ -22,7 +22,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): script of this session's tools. Independent literal read_file/codedb/bash/llm_query/subagent calls start as it streams. Binds persist until /new or /clear. subagent(\"task\") is sidecar-only — keep the critical-path next step local. Prefer one rlm over N tool calls. print(...) is the answer.";+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; each(arr, tool, field) maps a JSON array. 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 thediff --git a/src/rlm_tests.zig b/src/rlm_tests.zignew file mode 100644index 00000000..0cfe4401--- /dev/null+++ b/src/rlm_tests.zig@@ -0,0 +1,394 @@+//! Tests split out of rlm.zig so the REPL stays under the 600-line cap.++const std = @import("std");+const Io = std.Io;++const rlm = @import("rlm.zig");+const rlm_spec = @import("rlm_spec.zig");+const no_local_tools = @import("no_local_tools.zig");+const tools = @import("tools.zig");+const ToolCtx = tools.ToolCtx;+const ToolOutput = tools.ToolOutput;++fn testCtx(gpa: std.mem.Allocator, io: Io, client: *std.http.Client) ToolCtx {+ return .{+ .gpa = gpa,+ .io = io,+ .client = client,+ .provider = undefined,+ .registry = null,+ .from_sub = false,+ .approvals = null,+ .tracer = null,+ };+}++test "maybeAppend is a no-op when --old, 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 = rlm.available;+ const saved_local = no_local_tools.enabled;+ defer {+ rlm.available = saved;+ no_local_tools.enabled = saved_local;+ }+ rlm.available = false;+ no_local_tools.enabled = false;+ try std.testing.expectEqual(@as(usize, 1), (try rlm.maybeAppend(Spec, arena, &base)).len);+ rlm.available = true;+ const one = try rlm.maybeAppend(Spec, arena, &base);+ try std.testing.expectEqual(@as(usize, 2), one.len);+ try std.testing.expectEqualStrings(rlm.tool_name, one[1].name);+ const two = try rlm.maybeAppend(Spec, arena, one);+ try std.testing.expectEqual(@as(usize, 2), two.len);+ rlm.available = true;+ no_local_tools.enabled = true;+ try std.testing.expectEqual(@as(usize, 1), (try rlm.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 = rlm.available;+ defer {+ rlm.available = saved;+ rlm.resetLive(gpa, io);+ }+ rlm.available = true;+ const ctx = testCtx(gpa, io, &dummy_client);+ const t0: Io.Timestamp = .now(io, .awake);+ const out = try rlm.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);+ 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];+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer dummy_client.deinit();+ const saved = rlm.available;+ defer {+ rlm.available = saved;+ rlm.resetLive(gpa, io);+ }+ rlm.available = true;+ var ctx = testCtx(gpa, io, &dummy_client);+ ctx.agent_cwd = dir;+ const out = try rlm.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);+ const nested = try rlm.runScript(ctx, "print(read_file(\"note.txt\"))");+ defer gpa.free(nested.text);+ try std.testing.expect(!nested.is_error);+ try std.testing.expect(std.mem.indexOf(u8, nested.text, "hello-rlm") != null);+}++test "runScript splits a semicolon one-liner and prints both binds" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer dummy_client.deinit();+ const saved = rlm.available;+ defer {+ rlm.available = saved;+ rlm.resetLive(gpa, io);+ }+ rlm.available = true;+ const ctx = testCtx(gpa, io, &dummy_client);+ const t0: Io.Timestamp = .now(io, .awake);+ const out = try rlm.runScript(ctx, "a = sleep_ms(40); b = sleep_ms(41); print(a, b)");+ defer gpa.free(out.text);+ const dt = t0.untilNow(io, .awake).toMilliseconds();+ try std.testing.expect(!out.is_error);+ try std.testing.expectEqualStrings("slept 40ms\nslept 41ms", out.text);+ try std.testing.expect(dt < 90);+}++test "feedLive launches sleeps before runScript, so claim is a hit not a re-run" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer dummy_client.deinit();+ const saved = rlm.available;+ defer {+ rlm.available = saved;+ rlm.resetLive(gpa, io);+ }+ rlm.available = true;+ const ctx = testCtx(gpa, io, &dummy_client);+ const t0: Io.Timestamp = .now(io, .awake);+ rlm.feedLive(ctx, "a = sleep_ms(40)\n");+ rlm.feedLive(ctx, "b = sleep_ms(41)\n");+ rlm.feedLive(ctx, "c = sleep_ms(42)\n");+ const out = try rlm.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);+ try std.testing.expect(dt < 100);+}++test "feedLive splits a semicolon line before runScript claims" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer dummy_client.deinit();+ const saved = rlm.available;+ defer {+ rlm.available = saved;+ rlm.resetLive(gpa, io);+ }+ rlm.available = true;+ const ctx = testCtx(gpa, io, &dummy_client);+ const t0: Io.Timestamp = .now(io, .awake);+ rlm.feedLive(ctx, "a = sleep_ms(40); b = sleep_ms(41)\n");+ const out = try rlm.runScript(ctx, "a = sleep_ms(40); b = sleep_ms(41); print(a, b)");+ defer gpa.free(out.text);+ const dt = t0.untilNow(io, .awake).toMilliseconds();+ try std.testing.expect(!out.is_error);+ try std.testing.expectEqualStrings("slept 40ms\nslept 41ms", out.text);+ try std.testing.expect(dt < 90);+}++test "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 = rlm.available;+ defer {+ rlm.available = saved;+ rlm.resetLive(gpa, io);+ }+ rlm.available = true;+ const ctx = testCtx(gpa, io, &dummy_client);+ const first = try rlm.runScript(ctx, "prev = sleep_ms(1)");+ defer gpa.free(first.text);+ try std.testing.expect(!first.is_error);+ const reuse = try rlm.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 rlm.runScript(ctx, "prev = sleep_ms(2); print(prev)");+ defer gpa.free(overwrite.text);+ try std.testing.expectEqualStrings("slept 2ms", overwrite.text);+ const kept = try rlm.runScript(ctx, "print(prev)");+ defer gpa.free(kept.text);+ try std.testing.expectEqualStrings("slept 2ms", kept.text);+ rlm.resetLive(gpa, io);+ const gone = try rlm.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 = rlm.available;+ defer {+ rlm.available = saved;+ rlm.resetLive(gpa, io);+ }+ rlm.available = true;+ const ctx = testCtx(gpa, io, &dummy_client);+ const out = try rlm.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);+}++fn catalogHas(specs: anytype, name: []const u8) bool {+ for (specs) |s| if (std.mem.eql(u8, s.name, name)) return true;+ return false;+}++test "maybeAppend keeps subagent and workflow; rlm is never the only catalog tool" {+ 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" },+ .{ .name = "subagent" },+ .{ .name = "workflow" },+ };+ const saved = rlm.available;+ const saved_local = no_local_tools.enabled;+ defer {+ rlm.available = saved;+ no_local_tools.enabled = saved_local;+ rlm.sync();+ }+ rlm.available = true;+ no_local_tools.enabled = false;+ const on = try rlm.maybeAppend(Spec, arena, &base);+ try std.testing.expectEqual(@as(usize, 4), on.len);+ try std.testing.expect(catalogHas(on, "subagent"));+ try std.testing.expect(catalogHas(on, "workflow"));+ try std.testing.expect(catalogHas(on, rlm.tool_name));+ try std.testing.expect(on.len > 1);++ rlm.available = false;+ const off = try rlm.maybeAppend(Spec, arena, &base);+ try std.testing.expectEqual(@as(usize, 3), off.len);+ try std.testing.expect(catalogHas(off, "subagent"));+ try std.testing.expect(!catalogHas(off, rlm.tool_name));+}++test "effectiveRootSpecs: default rlm keeps subagent; --old and --lean do not drop it" {+ const schema = @import("schema.zig");+ const root = @import("main.zig");+ const learn_store = @import("learn_store.zig");+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const saved = rlm.available;+ const saved_lean = no_local_tools.lean;+ const saved_local = no_local_tools.enabled;+ const saved_clock = root.g_clock_sleep;+ const saved_learn = learn_store.active_agent_loaded;+ defer {+ rlm.available = saved;+ no_local_tools.lean = saved_lean;+ no_local_tools.enabled = saved_local;+ root.g_clock_sleep = saved_clock;+ learn_store.active_agent_loaded = saved_learn;+ rlm.sync();+ }+ no_local_tools.enabled = false;+ root.g_clock_sleep = false;+ learn_store.active_agent_loaded = true;++ rlm.available = true;+ no_local_tools.lean = false;+ rlm.sync();+ const def = try schema.effectiveRootSpecs(arena);+ try std.testing.expect(catalogHas(def, "subagent"));+ try std.testing.expect(catalogHas(def, "workflow"));+ try std.testing.expect(catalogHas(def, rlm.tool_name));+ try std.testing.expect(def.len > 2);++ rlm.available = false;+ rlm.sync();+ const old = try schema.effectiveRootSpecs(arena);+ try std.testing.expect(catalogHas(old, "subagent"));+ try std.testing.expect(catalogHas(old, "workflow"));+ try std.testing.expect(!catalogHas(old, rlm.tool_name));++ rlm.available = true;+ no_local_tools.lean = true;+ rlm.sync();+ const lean_on = try schema.effectiveRootSpecs(arena);+ try std.testing.expect(catalogHas(lean_on, "subagent"));+ try std.testing.expect(catalogHas(lean_on, rlm.tool_name));+ try std.testing.expect(!catalogHas(lean_on, "workflow"));+ try std.testing.expect(catalogHas(lean_on, "bash"));+ try std.testing.expect(no_local_tools.leanKeeps("subagent"));+ try std.testing.expect(!no_local_tools.leanKeeps(rlm.tool_name));+}++test "runScript empty subagent() reaches execSubagent; persist binds do not break that" {+ 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 = rlm.available;+ defer {+ rlm.available = saved;+ rlm.resetLive(gpa, io);+ }+ rlm.available = true;+ const ctx = testCtx(gpa, io, &dummy_client);+ const first = try rlm.runScript(ctx, "prev = sleep_ms(1)");+ defer gpa.free(first.text);+ try std.testing.expect(!first.is_error);+ const miss = try rlm.runScript(ctx, "h = subagent()");+ defer gpa.free(miss.text);+ try std.testing.expect(miss.is_error);+ try std.testing.expect(std.mem.indexOf(u8, miss.text, "missing required") != null);+ try std.testing.expect(std.mem.indexOf(u8, miss.text, "prompt") != null);+ const reuse = try rlm.runScript(ctx, "print(prev)");+ defer gpa.free(reuse.text);+ try std.testing.expect(!reuse.is_error);+ try std.testing.expectEqualStrings("slept 1ms", reuse.text);+}++test "feedLive launches two independent subagent() calls before runScript claims" {+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var dummy_client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer dummy_client.deinit();+ const saved = rlm.available;+ defer {+ rlm.available = saved;+ rlm.resetLive(gpa, io);+ }+ rlm.available = true;+ const ctx = testCtx(gpa, io, &dummy_client);+ rlm.feedLive(ctx, "a = subagent()\n");+ rlm.feedLive(ctx, "b = subagent(\"\")\n");+ var claimed = std.StringHashMap(ToolOutput).init(gpa);+ defer {+ var it = claimed.iterator();+ while (it.next()) |e| gpa.free(e.value_ptr.text);+ claimed.deinit();+ }+ var 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);+ }+}++test "rlm prompt: subagent() is advertised as sidecar-only, not a critical-path handoff" {+ try std.testing.expect(std.mem.indexOf(u8, rlm.tool_desc, "sidecar-only") != null);+ try std.testing.expect(std.mem.indexOf(u8, rlm.tool_desc, "critical-path") != null);+ try std.testing.expect(std.mem.indexOf(u8, rlm_spec.system_note, "sidecar-only") != null);+ try std.testing.expect(std.mem.indexOf(u8, rlm_spec.system_note, "critical-path") != null);+ try std.testing.expect(rlm.tool_desc.len < 600);+}++test "runScript refuses an unloaded MCP name and does not treat it as a host tool" {+ 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 = rlm.available;+ const saved_mcp = @import("rlm_mcp.zig").host_enabled;+ defer {+ rlm.available = saved;+ @import("rlm_mcp.zig").host_enabled = saved_mcp;+ rlm.resetLive(gpa, io);+ }+ rlm.available = true;+ @import("rlm_mcp.zig").host_enabled = true;+ const ctx = testCtx(gpa, io, &dummy_client);+ const out = try rlm.runScript(ctx, "x = mcp__linear__list_issues()\nprint(x)");+ defer gpa.free(out.text);+ try std.testing.expect(out.is_error);+ try std.testing.expect(std.mem.indexOf(u8, out.text, "MCP not available") != null or std.mem.indexOf(u8, out.text, "load_tool_schemas") != null);+}diff --git a/src/session_settings.zig b/src/session_settings.zigindex 9efa7fb7..bfb5a3c6 100644--- a/src/session_settings.zig+++ b/src/session_settings.zig@@ -132,6 +132,10 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {}rlm.sync();}+ if (environ_map.get("GRAFF_RLM_MCP")) |v| {+ const off = std.mem.eql(u8, v, "0") or std.ascii.eqlIgnoreCase(v, "false") or std.ascii.eqlIgnoreCase(v, "off") or std.ascii.eqlIgnoreCase(v, "no");+ @import("rlm_mcp.zig").host_enabled = !off;+ }}if (environ_map.get("GRAFF_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.leanSkipsMcpdiff --git a/src/session_settings_tests.zig b/src/session_settings_tests.zigindex 2185fe18..73087cdc 100644--- a/src/session_settings_tests.zig+++ b/src/session_settings_tests.zig@@ -43,6 +43,7 @@ const knobs = [_]Knob{.{ .name = "GRAFF_CODEX_WS", .value = "off" },.{ .name = "GRAFF_CLOCK_SLEEP", .value = "1" },.{ .name = "GRAFF_RLM", .value = "1" },+ .{ .name = "GRAFF_RLM_MCP", .value = "0" },.{ .name = "GRAFF_OLD", .value = "1" },.{ .name = "GRAFF_NO_LOCAL_TOOLS", .value = "1" },.{ .name = "GRAFF_CODEX_WS_IDLE_SECS", .value = "11" },@@ -89,6 +90,7 @@ const Saved = struct {clock_sleep: bool,rlm: bool,rlm_cli: bool,+ rlm_mcp: bool,stream_stall_ms: u64,post_deadline_ms: u64,codex_ws_idle_ms: i64,@@ -113,6 +115,7 @@ const Saved = struct {.clock_sleep = main_mod.g_clock_sleep,.rlm = @import("rlm.zig").available,.rlm_cli = @import("rlm.zig").cli_set,+ .rlm_mcp = @import("rlm_mcp.zig").host_enabled,.stream_stall_ms = http.stream_stall_ms,.post_deadline_ms = http.post_deadline_ms,.codex_ws_idle_ms = agent_ws.codex_ws_idle_ms,@@ -139,6 +142,7 @@ const Saved = struct {@import("rlm.zig").available = s.rlm;@import("rlm.zig").cli_set = s.rlm_cli;@import("rlm.zig").sync();+ @import("rlm_mcp.zig").host_enabled = s.rlm_mcp;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;@@ -253,6 +257,17 @@ test "GRAFF_OLD / GRAFF_RLM=0 turn default rlm off; --old is not clobbered by entry std.testing.expect(rlm.cli_set);}+test "GRAFF_RLM_MCP=0 turns MCP-inside-rlm host functions off" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const saved = Saved.capture();+ defer saved.restore();+ const rlm_mcp = @import("rlm_mcp.zig");+ rlm_mcp.host_enabled = true;+ try session_settings.applyEnvKnobs(arena_state.allocator(), PairEnv{ .pairs = &.{.{ .name = "GRAFF_RLM_MCP", .value = "0" }} });+ try std.testing.expect(!rlm_mcp.host_enabled);+}+test "GRAFF_STABLE_CATALOG=0 / GRAFF_NO_STABLE_CATALOG turn default-on catalog off" {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena_state.deinit();