graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: retain catalog and layout state across resume
justrached54c699a4b3
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 97834222..3c7d2f4d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -92,6 +92,9 @@ jobs:python3 scripts/test-json-controls.py zig-out/bin/graffpython3 scripts/test-json-cancel.py zig-out/bin/graff+ - name: Fresh-process session catalog and layout restoration+ run: python3 scripts/test-resume-cache.py --graff zig-out/bin/graff --mode offline --out "$RUNNER_TEMP/resume-cache"+- name: ACP cancellation and same-session follow-uprun: python3 scripts/test-acp-steer.py zig-out/bin/graffdiff --git a/docs/adr/0104-resume-retains-catalog-and-layout-snapshots.md b/docs/adr/0104-resume-retains-catalog-and-layout-snapshots.mdnew file mode 100644index 00000000..033b2ff3--- /dev/null+++ b/docs/adr/0104-resume-retains-catalog-and-layout-snapshots.md@@ -0,0 +1,38 @@+# 0104. Resume retains catalog selections and the layout snapshot++Status: accepted 2026-09-12++## Context++Restoring message history alone does not restore the request prefix. Deferred+native/MCP tool selections lived only in process memory, and rebuilding the+project map after file changes changed the system prompt. A fresh-process+resume could therefore send different tools and instructions for the same+conversation (#867).++## Decision++- Save loaded native names, MCP names in their rendered order, and RLM+ visibility. Include them in the save fingerprint. Restore selections and+ invalidate cached catalogs before materializing the resumed provider format.+- Resolve names against today's available catalog. Never persist or trust+ saved schemas, credentials, or permission grants. Legacy/malformed selection+ fields start without another session's loaded selections.+- Save only the project-layout snapshot, not the assembled system prompt.+ Restore that segment when resuming in the same workspace. Keep today's+ instructions around it, and respect prompts that opt out of the map.+ Legacy and cross-workspace resumes use the startup map.+- Preserve the existing native-first/MCP-by-load-order rendering contract;+ changing catalog ordering across tool families is a separate decision.++## Consequences++With unchanged instructions, capabilities, and schemas, process restart no+longer discards these cache-relevant parts of the prefix. Provider cache+availability remains separate from successful state restoration; neither a+cache hit nor a miss alone proves whether history was restored.++The production save/load regressions cover catalog equality, stale and malformed+selections, layout changes, and updated instructions. The synthetic process+verifier is `scripts/test-resume-cache.py`; its live mode is opt-in and reports+restoration independently from provider-reported cached input.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 8e6721b5..39d6f66e 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -114,6 +114,7 @@ record only when you need the evidence or the edge cases.| [0101](0101-gui-tests-preserve-desktop-focus.md) | GUI tests stay hidden by default; visible opt-in can overlap other apps, and native foreground checks require separate opt-in. || [0102](0102-workspace-agents-and-cancel-recovery.md) | Agents uses the workspace area, Tasks visibility is explicit and persisted, and timed-out cancellation retires the worker before session recovery. || [0103](0103-mcp-apps-are-isolated-result-views.md) | MCP Apps are private saved result views in isolated GUI/browser sandboxes; app tool calls require a future approval path. |+| [0104](0104-resume-retains-catalog-and-layout-snapshots.md) | Resume restores loaded tool selections and the same-workspace layout snapshot, without freezing current instructions or granting permissions. |## When to write onediff --git a/scripts/test-resume-cache.py b/scripts/test-resume-cache.pynew file mode 100644index 00000000..ded10742--- /dev/null+++ b/scripts/test-resume-cache.py@@ -0,0 +1,265 @@+#!/usr/bin/env python3+"""Synthetic save/exit/resume checks. Offline by default; live login calls opt in.++No credentials, headers, private prompts, or raw responses are written to reports.+Live mode uses a fixed synthetic system prompt; offline mode also changes the+workspace tree to exercise the persisted layout snapshot.+"""+from __future__ import annotations++import argparse+import hashlib+import json+import os+from pathlib import Path+import queue+import subprocess+import sys+import threading+import time++ROOT = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(ROOT / "scripts" / "eval"))+from mock_model import ScriptedModel++MARKER = "SYNTHETIC-CEDAR-48271"+SYSTEM = (+ "This is a synthetic session-restoration test. Follow the user's test steps. "+ "Only load_tool_schemas may be called; never execute the loaded tool. Never read files, "+ "run commands, communicate with peers, or use other tools. "+ "When asked to recall, answer only the retained marker, without tools."+)+ARCHIVE = "\n".join(+ f"Synthetic record {i:04d}: cedar amber quartz violet; archive value {(i * 73) % 997:03d}."+ for i in range(200)+)+INITIAL = "Load the webfetch schema using load_tool_schemas. Do not fetch anything. Then reply only with the retained marker."+RECALL = "Recall the retained marker. Reply only with it; do not call or load tools."+++def digest(value):+ return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()+++class Process:+ def __init__(self, binary, workspace, env, model, provider, fixed_prompt):+ argv = [str(binary), "--json", "--yolo", "--old", "--no-lean",+ "--no-telemetry", "--learning-privacy", "local", "--resume", "probe",+ "--model", model, "--system-prompt", SYSTEM, "--max-model-calls", "8"]+ self.stderr = (workspace / "process-stderr.log").open("a")+ self.proc = subprocess.Popen(argv, cwd=workspace, env=env, stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=self.stderr, text=True,+ bufsize=1)+ self.q = queue.Queue()+ self.events = []+ self.last_totals = {}+ threading.Thread(target=self._read, daemon=True).start()+ if fixed_prompt:+ self.send({"type": "set_system_prompt", "text": SYSTEM})+ self.until("system_prompt")++ def _read(self):+ for line in self.proc.stdout:+ try:+ self.q.put(json.loads(line))+ except ValueError:+ pass+ self.q.put(None)++ def send(self, value):+ self.proc.stdin.write(json.dumps(value) + "\n")+ self.proc.stdin.flush()++ def until(self, wanted, timeout=240):+ end = time.monotonic() + timeout+ events = []+ while time.monotonic() < end:+ try:+ event = self.q.get(timeout=max(0.1, end - time.monotonic()))+ except queue.Empty:+ raise RuntimeError("model/control response timed out") from None+ if event is None:+ raise RuntimeError("harness exited before terminal event")+ self.events.append(event)+ events.append(event)+ if event.get("type") == "error":+ # Do not echo potentially identifying upstream diagnostics.+ raise RuntimeError("harness emitted an error; inspect local stderr")+ if event.get("type") == wanted:+ return event, events+ raise RuntimeError("model/control response timed out")++ def turn(self, text):+ start = time.monotonic()+ self.send({"type": "user", "text": text})+ event, events = self.until("turn")+ fields = {"input_tokens": "input_tokens", "uncached_input_tokens": "uncached_input_tokens",+ "cached_tokens": "cache_read_tokens", "api_calls": "api_calls"}+ totals = {key: event.get(field, 0) for key, field in fields.items()}+ delta = {key: total - self.last_totals.get(key, 0) for key, total in totals.items()}+ self.last_totals = totals+ return {+ **delta,+ "tool_calls": sum(e.get("type") == "tool_call" for e in events),+ "marker_recalled": event.get("text", "").strip() == MARKER,+ "ms": round((time.monotonic() - start) * 1000),+ }++ def close(self):+ try:+ if self.proc.poll() is None:+ self.proc.stdin.close()+ self.proc.wait(timeout=45)+ finally:+ if self.proc.poll() is None:+ self.proc.kill()+ self.proc.wait()+ self.stderr.close()+ if self.proc.returncode:+ raise RuntimeError("harness exited unsuccessfully")+++def posture(workspace):+ turns = []+ for path in (workspace / ".graff" / "trajectories").glob("*.jsonl"):+ for line in path.read_text().splitlines():+ item = json.loads(line)+ if item.get("kind") == "turn" and "task" in item:+ turns.append((path.stat().st_mtime_ns, item))+ if not turns:+ raise RuntimeError("no request posture recorded")+ return max(enumerate(turns), key=lambda v: (v[1][0], v[0]))[1][1]+++def check(binary, out, mode, model):+ workspace = out / model+ workspace.mkdir(parents=True, exist_ok=False)+ subprocess.run(["git", "init", "-q"], cwd=workspace, check=True)+ (workspace / "fixture.txt").write_text("Synthetic fixture only.\n")+ empty_mcp = workspace / "empty-mcp.json"+ empty_mcp.write_text('{"mcpServers":{}}\n')+ env = {k: v for k, v in os.environ.items()+ if not k.endswith("_API_KEY") and not k.startswith(("GRAFF_", "HARNESS_", "OTEL_"))}+ # Keep login HOME, but do not auto-connect companion binaries from the user's PATH.+ env.update(PATH="/usr/bin:/bin:/usr/sbin:/sbin", GRAFF_NO_TELEMETRY="1",+ GRAFF_LEARNING_PRIVACY="local", GRAFF_FLEET="off",+ GRAFF_LEARNED_PROMPT="0", GRAFF_RLM_CONTEXT="off",+ GRAFF_MCP_CONFIG=str(empty_mcp), GRAFF_CONTEXT="128000", NO_COLOR="1")+ offline = mode != "live"+ fixed_prompt = mode != "offline"+ if mode == "offline":+ home = workspace / ".home"+ home.mkdir()+ env.update(HOME=str(home), CODEX_HOME=str(home / ".codex"))+ if offline:+ env["LMSTUDIO_API_KEY"] = "local"+ provider = "lmstudio" if offline else ("xai" if model.startswith("grok") else "codex")+ wire_model = "lmstudio" if offline else model+ sessions = workspace / ".graff" / "sessions"+ sessions.mkdir(parents=True)+ session_path = sessions / "probe.session.json"+ session_path.write_text(json.dumps({+ "provider": provider, "model": wire_model, "strict": False, "ultracode_mode": False,+ "title": "Synthetic resume check", "messages": [{"role": "user", "content":+ f"Retain this marker: {MARKER}.\nThe following records are synthetic padding.\n{ARCHIVE}"}],+ }))+ scripted = None+ process = None+ result = {"model": model, "mode": mode}+ try:+ if offline:+ scripted = ScriptedModel([+ {"tool": "load_tool_schemas", "arguments": {"tools": ["webfetch"]}},+ {"text": MARKER}, {"text": MARKER}, {"text": MARKER},+ ])+ scripted.start(1234)+ process = Process(binary, workspace, env, wire_model, provider, fixed_prompt)+ result["initial"] = process.turn(INITIAL)+ result["warm"] = process.turn(RECALL)+ process.close()+ process = None+ before = json.loads(session_path.read_text())+ warm_posture = posture(workspace)+ result["native_loaded_before"] = "webfetch" in before.get("loaded_tools", {}).get("native", [])+ request_count = len(scripted.requests) if scripted else 0+ (workspace / "added-after-exit.txt").write_text("Synthetic tree change.\n")+ process = Process(binary, workspace, env, wire_model, provider, fixed_prompt)+ result["resumed"] = process.turn(RECALL)+ process.close()+ process = None+ after = json.loads(session_path.read_text())+ resumed_posture = posture(workspace)+ result["history_restored"] = after["messages"][:len(before["messages"])] == before["messages"]+ result["catalog_equal"] = warm_posture.get("recipe_toolset_sha") == resumed_posture.get("recipe_toolset_sha")+ result["system_equal"] = warm_posture.get("prompt_sha") == resumed_posture.get("prompt_sha")+ result["native_restored"] = "webfetch" in after.get("loaded_tools", {}).get("native", [])+ result["saved_history_digest"] = digest(before["messages"])+ if scripted:+ pre = scripted.requests[request_count - 1]+ post = scripted.requests[request_count]+ result["wire_catalog_equal"] = pre.get("tools") == post.get("tools")+ result["wire_system_equal"] = pre["messages"][0] == post["messages"][0]+ result["wire_history_restored"] = post["messages"][1:len(pre["messages"])] == pre["messages"][1:]+ result["wire_tool_loaded_before"] = any(t.get("function", t).get("name") == "webfetch" for t in pre.get("tools", []))+ if fixed_prompt:+ # This preflight uses the real login HOME, but ONLY a local server.+ # Reject any inherited private prompt/catalog before authorizing live mode.+ for request in scripted.requests:+ content = request["messages"][0].get("content", "")+ # Only the inspected stock footer with an EMPTY constraint ledger is allowed.+ footer_sha = hashlib.sha256(content[len(SYSTEM):].encode()).hexdigest()+ if content != SYSTEM and (not content.startswith(SYSTEM) or footer_sha !=+ "31152a719eec6db47c2254fdbcfdb622eed8e5c0a56de63e60ae8d78e323432c"):+ raise RuntimeError("privacy preflight: unexpected system instructions")+ for tool in request.get("tools", []):+ name = tool.get("function", tool).get("name", "")+ if name.startswith(("mcp__", "local__")):+ raise RuntimeError("privacy preflight: unexpected external/local tool")+ if os.path.expanduser("~") in json.dumps(request):+ raise RuntimeError("privacy preflight: home path appeared in request")+ result["privacy_preflight"] = True+ checks = ["history_restored", "catalog_equal", "system_equal", "native_loaded_before", "native_restored"]+ if scripted:+ checks += ["wire_catalog_equal", "wire_system_equal", "wire_history_restored", "wire_tool_loaded_before"]+ result["restoration_pass"] = all(result.get(k) for k in checks) and result["resumed"]["marker_recalled"] and result["resumed"]["tool_calls"] == 0+ result["cache_hit_after_resume"] = result["resumed"]["cached_tokens"] > 0 if not offline else None+ except Exception as error:+ result["error"] = str(error) if isinstance(error, RuntimeError) else type(error).__name__+ result["restoration_pass"] = False+ finally:+ if process:+ try:+ process.close()+ except Exception:+ pass+ if scripted:+ scripted.stop()+ (workspace / "result.json").write_text(json.dumps(result, indent=2) + "\n")+ return result+++def main():+ p = argparse.ArgumentParser(description=__doc__)+ p.add_argument("--graff", type=Path, default=ROOT / "zig-out/bin/graff")+ p.add_argument("--out", type=Path, required=True)+ p.add_argument("--mode", choices=("offline", "preflight", "live"), default="offline")+ p.add_argument("--models", nargs="+", help="Explicit model names for opt-in live testing")+ args = p.parse_args()+ if args.mode == "live" and not args.models:+ p.error("--models is required for live testing")+ out = args.out.resolve()+ out.mkdir(parents=True, exist_ok=True)+ if args.mode == "live":+ preflight = check(args.graff.resolve(), out, "preflight", "privacy-preflight")+ if not preflight.get("restoration_pass") or not preflight.get("privacy_preflight"):+ print(json.dumps(preflight, indent=2))+ return 1+ models = args.models if args.mode == "live" else [args.mode]+ results = [check(args.graff.resolve(), out, args.mode, model) for model in models]+ (out / "results.json").write_text(json.dumps(results, indent=2) + "\n")+ print(json.dumps(results, indent=2))+ return 0 if all(r["restoration_pass"] for r in results) else 1+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/agent.zig b/src/agent.zigindex d57aeee6..f86d031c 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -120,6 +120,7 @@ pub const Agent = struct {depth: u8 = 0, // root/auxiliary = 0; delegated child = 1call_kind: run_budget_mod.CallKind = .root,last_cache_read: u64 = 0, // KV-cache read tokens from the latest response+ repo_map_snapshot: ?[]const u8 = null, // the resumed layout only; current instructions stay livesys_normal: []const u8 = prompts.main_system_prompt, // root system prompt (+ project instructions)sys_override: ?[]const u8 = null, // per-child custom prompt or transient isolated-review basetask_prompt: ?[]const u8 = null, // a subagent's mandate, pinned once before the first history rewrite so compaction can restate it verbatim (recentContextStart can keep no verbatim suffix for a child - its only clean user turn is index 0)@@ -288,16 +289,7 @@ pub const Agent = struct {return @import("agent_catalog.zig").ensureRootTools(self, kind);}- /// A live MCP registry change invalidates provider-specific catalogs. The- /// active format is immediately rebuilt; inactive formats remain lazy.- pub fn invalidateRootTools(self: *Agent) void {- if (self.sub) return;- @import("prompt_cache_hud.zig").noteBust(.tools);- self.tools_anthropic = "";- self.tools_openai = "";- self.tools_responses = "";- self.tools_interactions = "";- }+ pub const invalidateRootTools = @import("agent_catalog.zig").invalidateRootTools;pub noinline fn ensureModelCatalog(self: *Agent, keys: provider_mod.Keys) void {if (self.model_catalog) |*catalog|diff --git a/src/agent_catalog.zig b/src/agent_catalog.zigindex 907f3778..1edb241c 100644--- a/src/agent_catalog.zig+++ b/src/agent_catalog.zig@@ -40,6 +40,17 @@ fn slot(self: *const Agent) []const u8 {};}+/// A registry or restored selection change invalidates every provider format.+/// The active format is rebuilt immediately; inactive formats remain lazy.+pub fn invalidateRootTools(self: *Agent) void {+ if (self.sub) return;+ @import("prompt_cache_hud.zig").noteBust(.tools);+ self.tools_anthropic = "";+ self.tools_openai = "";+ self.tools_responses = "";+ self.tools_interactions = "";+}+pub fn ensureRootTools(self: *Agent, kind: Provider.Kind) !void {if (self.sub and !main_mod.g_codedbpro_licensed) return;const dest = switch (kind) {diff --git a/src/main.zig b/src/main.zigindex 3fe54731..264abd40 100644--- a/src/main.zig+++ b/src/main.zig@@ -565,8 +565,8 @@ const exec = @import("exec.zig");test { // ── Unit tests (`zig build test`): pull in tests from imported modules (mcp.zig)_ = @import("mcp_apps.zig");_ = @import("main_test.zig");- _ = @import("http_client.zig");- _ = @import("http_client_tests.zig");+ _ = @import("session_catalog.zig");+ _ = @import("session_prompt.zig");_ = @import("prompt_astra.zig");_ = @import("agent_empty_completion.zig"); // #745: plain-final reconciliation_ = @import("agent_model_loop.zig");diff --git a/src/native_fold.zig b/src/native_fold.zigindex dc385bf5..1139fda1 100644--- a/src/native_fold.zig+++ b/src/native_fold.zig@@ -248,6 +248,13 @@ pub fn blocked(name: []const u8) bool {return enabled and isFolded(name) and !isLoaded(name);}+/// Replace session selections while retaining an explicit CLI RLM request.+pub fn clearLoadedSession() void {+ g_loaded_len = 0;+ g_showcased = g_cli_forced;+ if (g_cli_forced) markLoaded("rlm");+}+/// The session's loaded folded natives, in load order (schema.zig's stable/// tail appends them after the stable head — load order keeps it append-only).pub fn loadedNames() []const []const u8 {diff --git a/src/repo_map.zig b/src/repo_map.zigindex e08486bf..c4aba75e 100644--- a/src/repo_map.zig+++ b/src/repo_map.zig@@ -48,6 +48,12 @@ const Budget = struct {var cached: ?[]const u8 = null; // built once per process (see module doc)+/// The startup snapshot, without scanning or replacing a restored session map.+pub fn cachedSegment() ?[]const u8 {+ const value = cached orelse return null;+ return if (value.len == 0) null else value;+}+fn skipped(name: []const u8) bool {if (name.len == 0 or name[0] == '.') return true;for (skip_dirs) |d| if (std.mem.eql(u8, name, d)) return true;diff --git a/src/session.zig b/src/session.zigindex be68b36d..b2c70487 100644--- a/src/session.zig+++ b/src/session.zig@@ -183,6 +183,8 @@ fn fingerprint(root: *Agent, name: []const u8) u64 {f.num(root.context_local_tokens);f.num(protocol_seq.current());f.json(Value{ .array = root.messages });+ @import("session_catalog.zig").mixFingerprint(root, &f);+ f.text(@import("session_prompt.zig").snapshot(root) orelse "");session_peer.mixFingerprint(&f);subagent_ledger.mixFingerprint(&f);return f.final();@@ -264,6 +266,8 @@ fn queueSave(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !u64defer aw.deinit();var s: std.json.Stringify = .{ .writer = &aw.writer };try s.beginObject();+ try @import("session_catalog.zig").write(root, &s);+ try @import("session_prompt.zig").write(root, &s);try s.objectField("provider");try s.write(root.provider.id);try s.objectField("model");@@ -486,6 +490,8 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8// A resumed session may use a different wire format than the startup// default. Materialize that catalog before rebasing its saved context// meter, and keep every still-unused format lazy.+ try @import("session_prompt.zig").restore(root, obj);+ try @import("session_catalog.zig").restore(root, obj);try root.ensureRootTools(root.provider.kind);const compaction_window = try @import("compaction_window.zig").State.restore(arena, obj, msgs.items);root.messages = msgs;diff --git a/src/session_catalog.zig b/src/session_catalog.zignew file mode 100644index 00000000..183b18bb--- /dev/null+++ b/src/session_catalog.zig@@ -0,0 +1,225 @@+//! Persist schema selections, never schemas, credentials, or permission grants.++const std = @import("std");+const Agent = @import("agent.zig").Agent;+const native = @import("native_fold.zig");+const gate = @import("mcp_schema_gate.zig");+const Tool = @import("mcp.zig").Tool;++test "#867 session save load preserves the loaded catalog and clears legacy selections" {+ const session = @import("session.zig");+ const writer = @import("session_writer.zig");+ const transcript = @import("session_transcript.zig");+ 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();+ writer.resetForTest();+ defer writer.resetForTest();+ transcript.resetForTest();+ defer transcript.resetForTest();+ native.resetRlmDiscovery();+ native.clearLoadedSession();+ defer native.clearLoadedSession();+ gate.reset();+ defer gate.reset();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();+ var keys: @import("provider.zig").Keys = .{ .values = @splat("test-key") };+ var root: Agent = .{+ .gpa = gpa,+ .arena = arena,+ .io = io,+ .client = &client,+ .provider = try keys.providerById("anthropic", "sonnet"),+ .messages = (try std.json.parseFromSliceLeaky(std.json.Value, arena, "[{\"role\":\"user\",\"content\":\"catalog regression\"}]", .{})).array,+ .sub = false,+ .label = "root",+ .out = null,+ .home = try std.fmt.allocPrint(arena, ".zig-cache/tmp/{s}", .{tmp.sub_path}),+ };+ var registry: @import("mcp.zig").Registry = undefined;+ const spec = try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"type\":\"object\",\"properties\":{}}", .{});+ var tools = [_]Tool{+ .{ .server_index = 0, .original_name = "a", .qualified_name = "mcp__fixture__a", .description = "A", .input_schema = spec },+ .{ .server_index = 0, .original_name = "b", .qualified_name = "mcp__fixture__b", .description = "B", .input_schema = spec },+ };+ registry.tools = &tools;+ root.registry = ®istry;+ // Save before loading schemas: unchanged messages must not suppress the next save.+ try session.saveSessionTo(&root, arena, tmp.dir, "catalog-867");+ session.flushSaves();+ native.markLoaded("webfetch");+ gate.autoLoad(arena, &tools, tools[1].qualified_name);+ native.markLoaded("skill");+ gate.autoLoad(arena, &tools, tools[0].qualified_name);+ native.showcaseRlm();+ root.invalidateRootTools();+ try root.ensureRootTools(root.provider.kind);+ const before = try arena.dupe(u8, root.toolsJson());+ try session.saveSessionTo(&root, arena, tmp.dir, "catalog-867");+ session.flushSaves();+ native.clearLoadedSession();+ gate.reset();+ root.invalidateRootTools();+ // Simulate a fresh process, then an already-materialized other session.+ try root.ensureRootTools(root.provider.kind);+ try session.loadSession(&root, &keys, arena, "catalog-867");+ try std.testing.expectEqualStrings(before, root.toolsJson());+ native.markLoaded("workflow");+ root.invalidateRootTools();+ try root.ensureRootTools(root.provider.kind);+ try session.loadSession(&root, &keys, arena, "catalog-867");+ try std.testing.expectEqualStrings(before, root.toolsJson());+ try tmp.dir.writeFile(io, .{ .sub_path = ".graff/sessions/catalog-legacy-867.session.json", .data = "{\"provider\":\"anthropic\",\"model\":\"sonnet\",\"messages\":[]}" });+ try session.loadSession(&root, &keys, arena, "catalog-legacy-867");+ try std.testing.expectEqual(@as(usize, 0), native.loadedNames().len);+ try std.testing.expect(!native.listed());+ try std.testing.expect(!gate.isLoaded(tools[0].qualified_name));+ try std.testing.expect(!gate.isLoaded(tools[1].qualified_name));+}++test "#867 malformed catalog state resets selections and validates saved names" {+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ native.resetRlmDiscovery();+ native.clearLoadedSession();+ defer native.clearLoadedSession();+ gate.reset();+ defer gate.reset();+ var client: std.http.Client = .{ .allocator = gpa, .io = std.testing.io };+ defer client.deinit();+ const keys: @import("provider.zig").Keys = .{ .values = @splat("test-key") };+ var root: Agent = .{+ .gpa = gpa,+ .arena = arena,+ .io = std.testing.io,+ .client = &client,+ .provider = try keys.providerById("anthropic", "sonnet"),+ .messages = .init(arena),+ .sub = false,+ .label = "root",+ .out = null,+ };+ var registry: @import("mcp.zig").Registry = undefined;+ const spec = try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"type\":\"object\",\"properties\":{}}", .{});+ var tools = [_]Tool{+ .{ .server_index = 0, .original_name = "current", .qualified_name = "mcp__fixture__current", .description = "Current registry schema", .input_schema = spec },+ };+ registry.tools = &tools;+ root.registry = ®istry;+ for ([_][]const u8{+ "{}",+ "{\"loaded_tools\":null}",+ "{\"loaded_tools\":[]}",+ "{\"loaded_tools\":{\"native\":false,\"mcp\":{},\"rlm_showcased\":\"true\"}}",+ "{\"loaded_tools\":{\"native\":[null,7,\"unknown-tool\"],\"mcp\":[false,\"mcp__missing__tool\"],\"schemas\":{\"injected\":{}}}}",+ }) |json| {+ native.markLoaded("webfetch");+ gate.autoLoad(arena, &tools, tools[0].qualified_name);+ native.showcaseRlm();+ root.tools_anthropic = "stale";+ const saved = try std.json.parseFromSliceLeaky(std.json.Value, arena, json, .{});+ try restore(&root, saved.object);+ try std.testing.expectEqual(@as(usize, 0), native.loadedNames().len);+ try std.testing.expect(!native.listed());+ try std.testing.expectEqualStrings("", root.tools_anthropic);+ try std.testing.expect(!gate.isLoaded("mcp__missing__tool"));+ try std.testing.expect(!gate.isLoaded(tools[0].qualified_name));+ }+ const saved = try std.json.parseFromSliceLeaky(std.json.Value, arena, "{\"loaded_tools\":{\"native\":[\"webfetch\",7,\"webfetch\",\"unknown-tool\"]}}", .{});+ try restore(&root, saved.object);+ try std.testing.expectEqual(@as(usize, 1), native.loadedNames().len);+ try std.testing.expectEqualStrings("webfetch", native.loadedNames()[0]);+ const mcp_saved = try std.json.parseFromSliceLeaky(std.json.Value, arena,+ \\{"loaded_tools":{"mcp":["mcp__missing__tool",null,"mcp__fixture__current","mcp__fixture__current"],"schemas":{"mcp__fixture__current":{"saved_schema_867_must_not_render":true}}}}+ , .{});+ try restore(&root, mcp_saved.object);+ try std.testing.expect(gate.isLoaded(tools[0].qualified_name));+ try std.testing.expect(!gate.isLoaded("mcp__missing__tool"));+ try std.testing.expectEqual(@as(usize, 1), gate.rendersForTest());+ try root.ensureRootTools(root.provider.kind);+ try std.testing.expect(std.mem.indexOf(u8, root.toolsJson(), "Current registry schema") != null);+ try std.testing.expect(std.mem.indexOf(u8, root.toolsJson(), "saved_schema_867_must_not_render") == null);+}++fn connected(root: *const Agent) []const Tool {+ return if (root.registry) |r| r.tools else &.{};+}++pub fn mixFingerprint(root: *const Agent, f: anytype) void {+ f.flag(native.listed());+ for (native.loadedNames()) |name| f.text(name);+ for (connected(root)) |tool| {+ if (gate.loadSeq(tool.qualified_name)) |seq| {+ f.text(tool.qualified_name);+ f.num(seq);+ }+ }+}++pub fn write(root: *const Agent, s: *std.json.Stringify) !void {+ try s.objectField("loaded_tools");+ try s.beginObject();+ try s.objectField("native");+ try s.write(native.loadedNames());+ try s.objectField("rlm_showcased");+ try s.write(native.listed());+ try s.objectField("mcp");+ try s.beginArray();+ // Match the existing native-first, MCP-by-sequence catalog tail.+ var previous: usize = 0;+ while (true) {+ var next: ?Tool = null;+ var best: usize = std.math.maxInt(usize);+ for (connected(root)) |tool| {+ const seq = gate.loadSeq(tool.qualified_name) orelse continue;+ if (seq > previous and seq < best) {+ next = tool;+ best = seq;+ }+ }+ const tool = next orelse break;+ try s.write(tool.qualified_name);+ previous = best;+ }+ try s.endArray();+ try s.endObject();+}++pub fn restore(root: *Agent, obj: std.json.ObjectMap) !void {+ native.clearLoadedSession();+ gate.reset();+ root.invalidateRootTools();+ const saved = obj.get("loaded_tools") orelse return;+ if (saved != .object) return;+ if (saved.object.get("rlm_showcased")) |v| {+ if (v == .bool and v.bool) native.showcaseRlm();+ }+ if (saved.object.get("native")) |names| {+ if (names == .array) for (names.array.items) |name| {+ if (name != .string or !native.isFolded(name.string)) continue;+ if (try native.findRootSpec(root.arena, name.string) != null)+ native.markLoaded(name.string);+ };+ }+ if (saved.object.get("mcp")) |names| {+ if (names == .array) for (names.array.items) |name| {+ if (name != .string) continue;+ for (connected(root)) |tool| {+ if (!std.mem.eql(u8, tool.qualified_name, name.string)) continue;+ var input: std.json.ObjectMap = .empty;+ var list: std.json.Array = .init(root.arena);+ try list.append(name);+ try input.put(root.arena, "tools", .{ .array = list });+ _ = try gate.loadInto(root.arena, connected(root), .{ .object = input });+ break;+ }+ };+ }+}diff --git a/src/session_prompt.zig b/src/session_prompt.zignew file mode 100644index 00000000..b2ff4ad9--- /dev/null+++ b/src/session_prompt.zig@@ -0,0 +1,113 @@+//! Resume the layout snapshot, not stale instructions or permission policy.++const std = @import("std");+const Agent = @import("agent.zig").Agent;+const map = @import("repo_map.zig");+const prompts = @import("prompts.zig");++pub fn snapshot(root: *const Agent) ?[]const u8 {+ if (root.repo_map_snapshot) |saved| {+ if (std.mem.indexOf(u8, root.sys_base, saved) != null) return saved;+ }+ if (map.cachedSegment()) |fresh| {+ if (std.mem.indexOf(u8, root.sys_base, fresh) != null) return fresh;+ }+ return null;+}++pub fn write(root: *const Agent, s: *std.json.Stringify) !void {+ try s.objectField("repo_map");+ try s.write(snapshot(root));+}++fn savedMap(obj: std.json.ObjectMap) ?[]const u8 {+ const value = obj.get("repo_map") orelse return null;+ if (value != .string or value.string.len > 6 * 1024 + 512) return null;+ if (!std.mem.startsWith(u8, value.string, "\n\n# Project layout (working tree at session start,") or+ !std.mem.endsWith(u8, value.string, "\n")) return null;+ return value.string;+}++pub fn restore(root: *Agent, obj: std.json.ObjectMap) !void {+ const current = snapshot(root) orelse {+ root.repo_map_snapshot = null; // The current prompt opted out of a map.+ return;+ };+ const workspace = obj.get("workspace");+ const same_workspace = if (workspace) |v|+ v == .string and std.mem.eql(u8, v.string, @import("main.zig").g_cwd_display)+ else+ false;+ // Legacy saves and cross-workspace resumes use this process's fresh map.+ const desired = (if (same_workspace) savedMap(obj) else null) orelse map.cachedSegment() orelse current;+ if (!std.mem.eql(u8, current, desired)) {+ const at = std.mem.indexOf(u8, root.sys_base, current) orelse return;+ const base = try std.fmt.allocPrint(root.arena, "{s}{s}{s}", .{+ root.sys_base[0..at], desired, root.sys_base[at + current.len ..],+ });+ // Recompose all variants while keeping today's instructions on both sides.+ try prompts.setSystemPrompts(root, base, root.arena);+ }+ root.repo_map_snapshot = desired;+}++test "#867 production save load preserves layout after tree changes without restoring old rules" {+ const session = @import("session.zig");+ const writer = @import("session_writer.zig");+ const transcript = @import("session_transcript.zig");+ const gpa = std.testing.allocator;+ const io = std.testing.io;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ writer.resetForTest();+ defer writer.resetForTest();+ transcript.resetForTest();+ defer transcript.resetForTest();+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ var path_buf: [std.fs.max_path_bytes]u8 = undefined;+ const abs = path_buf[0..try tmp.dir.realPath(io, &path_buf)];+ try tmp.dir.writeFile(io, .{ .sub_path = "first.txt", .data = "synthetic" });+ const original = map.build(io, a, abs) orelse return error.TestUnexpectedResult;+ var client: std.http.Client = .{ .allocator = gpa, .io = io };+ defer client.deinit();+ var keys: @import("provider.zig").Keys = .{ .values = @splat("test-key") };+ var root: Agent = .{+ .gpa = gpa,+ .arena = a,+ .io = io,+ .client = &client,+ .provider = try keys.providerById("anthropic", "sonnet"),+ .messages = (try std.json.parseFromSliceLeaky(std.json.Value, a, "[{\"role\":\"user\",\"content\":\"synthetic\"}]", .{})).array,+ .sub = false,+ .label = "root",+ .out = null,+ .home = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}),+ .repo_map_snapshot = original,+ };+ const before = try std.fmt.allocPrint(a, "RULE{s}\n\nAFTER", .{original});+ try prompts.setSystemPrompts(&root, before, a);+ try session.saveSessionTo(&root, a, tmp.dir, "layout-867");+ session.flushSaves();+ try tmp.dir.writeFile(io, .{ .sub_path = "later.txt", .data = "synthetic" });+ const fresh = map.build(io, a, abs) orelse return error.TestUnexpectedResult;+ try std.testing.expect(!std.mem.eql(u8, original, fresh));+ const rebooted = try std.fmt.allocPrint(a, "RULE{s}\n\nAFTER", .{fresh});+ try prompts.setSystemPrompts(&root, rebooted, a);+ root.repo_map_snapshot = fresh;+ try session.loadSession(&root, &keys, a, "layout-867");+ try std.testing.expectEqualStrings(before, root.sys_base);+ try std.testing.expectEqualStrings(original, snapshot(&root).?);+ // The old map must never freeze new instructions around it.+ const changed_rules = try std.fmt.allocPrint(a, "CURRENT RULE{s}\n\nCURRENT AFTER", .{fresh});+ try prompts.setSystemPrompts(&root, changed_rules, a);+ root.repo_map_snapshot = fresh;+ try session.loadSession(&root, &keys, a, "layout-867");+ const expected = try std.fmt.allocPrint(a, "CURRENT RULE{s}\n\nCURRENT AFTER", .{original});+ try std.testing.expectEqualStrings(expected, root.sys_base);+ try prompts.setSystemPrompts(&root, "NO MAP", a);+ root.repo_map_snapshot = null;+ try session.loadSession(&root, &keys, a, "layout-867");+ try std.testing.expectEqualStrings("NO MAP", root.sys_base);+}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex d7184979..fefa7d79 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -268,6 +268,8 @@ test {_ = serve_create;_ = scoring_slot_test;_ = session_tests;+ _ = @import("http_client.zig");+ _ = @import("http_client_tests.zig");_ = help;_ = session_transcript_tests;_ = session_settings_tests;