graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: #711 #712 #708 on the v0.0.284 cut
Cursor Agentbc5e1c7bb141
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5a0e3c2d..c10208eb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,22 @@ The release workflow uses a tag's section here as its release notes (ahand-written `docs/releases/<tag>.md` wins if present), so keeping this filecurrent is part of cutting a release.+## v0.0.284 (2026-09-01)++- ACP turns stage GUI `@[image]` attachments as native vision blocks so+ pasted images reach the model.+- `#708`: peer-inbox wake is advisory (`parked; peer_message action=inbox+ when relevant`), never a command that displaces the turn.+- `#711`: a failed parallel bash result (gh 404 JSON + exit code) cannot+ poison the next Codex body. `function_call.arguments` and+ `function_call_output.output` that arrived as objects are coerced to+ strings before send.+- `#712` / ADR 0059: bare `/resume` and `/sessions` list cwd saves, then+ `~/.graff/sessions`. Cross-workspace rows name their origin. Resume+ restores history here; file tools stay in the current cwd.+- The gateway is a fallback seat, not the startup default.+- No tag until asked.+## v0.0.283 (2026-08-31)- Next cut after v0.0.282 landed on main. First fold: `#702` /diff --git a/docs/adr/0059-saved-session-discovery-is-device-scoped.md b/docs/adr/0059-saved-session-discovery-is-device-scoped.mdnew file mode 100644index 00000000..60c6d3ca--- /dev/null+++ b/docs/adr/0059-saved-session-discovery-is-device-scoped.md@@ -0,0 +1,29 @@+# 0059. Saved-session discovery is device-scoped++Status: accepted 2026-09-01++## Context++Bare `/resume` and `/sessions` only opened `.graff/sessions` under the+process cwd. A conversation saved from `$HOME` (`~/.graff/sessions`)+vanished the moment graff started inside a repo. That read as session+loss (#712). Session files did not persist an originating cwd.++## Decision++List cwd saves first, then `~/.graff/sessions` when that tree is a+different workspace. Cwd wins on the same base name. Cross-workspace+rows show title, key, and originating path (`~/…` when under `$HOME`).+Resuming one restores history into the **current** cwd and says so —+file tools stay here. Do not silently `chdir` into the save's origin.++New saves write a `workspace` field. Legacy files infer origin from+the directory that holds them.++`countSavedSessions` / the system-prompt hint stay cwd-only so the+model is not told about off-tree saves.++## Consequences++A new empty project can find home saves. Tools never jump workspaces+on resume. A user who wants the original tree uses `/workspace use`.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex a01644aa..709e9ce5 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -69,6 +69,7 @@ record only when you need the evidence or the edge cases.| [0056](0056-composer-image-chips-sync-on-delete.md) | Composer image chips sync on delete and reuse `#N`; `clipboard_paste` MIME/bytes wait until send. || [0057](0057-peer-title-is-an-address.md) | `peer_message` resolves exact title / saved-session base before opaque id or goal. || [0058](0058-compact-cut-stalls-on-no-progress.md) | Same unresolved `compact_cut` pin that does not shrink stops after two tries. |+| [0059](0059-saved-session-discovery-is-device-scoped.md) | `/resume` and `/sessions` list cwd then `~/.graff/sessions`; resume keeps tools in the current cwd. |## When to write onediff --git a/docs/releases/v0.0.284.md b/docs/releases/v0.0.284.mdindex 129215cd..c3292c18 100644--- a/docs/releases/v0.0.284.md+++ b/docs/releases/v0.0.284.md@@ -1,6 +1,7 @@# v0.0.284 (2026-09-01)-Next cut after [v0.0.283](v0.0.283.md). No GitHub tag until asked.+Next cut after [v0.0.283](v0.0.283.md) merged to main. No GitHub tag+until asked.## Pasted images reach the model through ACP clients@@ -15,7 +16,7 @@ prompts are covered: the attachment block is baked in at submit andqueued prompts drain through the same turn path. One regression testcovers both the image and non-image cases.-## Peer wake is advisory, not a command+## Peer wake is advisory, not a command (#708)The one-line `[peer]` wake appended to a user turn ended in theimperative `peer_message action=inbox`, so a trivial turn (a bare@@ -26,6 +27,24 @@ unwrapped dim row; an empty inbox carries no read command at all.Detection is untouched (prefix-based), so compact/peek paths andresumed transcripts are unaffected.+## Invalid JSON after a failed parallel bash (#711)++A parallel `bash` pair that returned HTTP 404 left a tool result in+history, then the next Codex request failed with `Invalid body: failed+to parse JSON value`. Send-time normalization now coerces+`function_call.arguments` and non-string `function_call_output.output`+to JSON strings before the body is built.++## Device-wide `/resume` (#712 / ADR 0059)++Bare `/resume` and `/sessions` listed only `.graff/sessions` under cwd.+Saves from `$HOME` (`~/.graff/sessions`) looked like they were gone.+The picker and `/sessions` now show cwd first, then home, labeled with+origin. Resuming a foreign save restores conversation history into the+current cwd and says so — `read_file` / `edit_file` / `bash` do not+silently switch trees.+## Tests-Suite floor rises to **1882**.+Suite floor stays **1882**. This fold adds the #711 / #712 cases on+top of the ACP-image and #708 work already on the branch.diff --git a/src/cli.zig b/src/cli.zigindex dc26e6ae..76a5fbd3 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -24,6 +24,8 @@ pub const changelog_text =\\0.0.284\\ • ACP turns stage GUI @[image] attachments as native vision blocks — pasted images reach the model\\ • peer inbox wake is advisory ("parked; read when relevant"), never a command that displaces the turn+ \\ • parallel error bash results stay valid JSON on the next Codex request (#711)+ \\ • /resume and /sessions find ~/.graff/sessions, not just cwd (#712)\\\\0.0.283\\ • deleted composer image chips reuse #N; paste traces omit MIME/bytes until send (#702)diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex 79c476de..11f699a2 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -67,7 +67,7 @@ pub const commands = [_]Item{.{ .name = "/bash", .usage = "/bash <command>", .desc = "run a shell command directly" },.{ .name = "/save", .usage = "/save [name]", .desc = "write the conversation to <name>.session.json (default: current)" },.{ .name = "/resume", .usage = "/resume [source] [--branch destination]", .desc = "restore a saved conversation, optionally cloning it into an independent branch" },- .{ .name = "/sessions", .desc = "list saved sessions in the cwd" },+ .{ .name = "/sessions", .desc = "list saved sessions here and under ~/.graff/sessions" },.{ .name = "/workspace", .usage = "/workspace [list|use <name>]", .desc = "list git worktrees or switch this session into one (file tools follow)" },.{ .name = "/experiment", .usage = "/experiment [N|off|status]", .desc = "pre-mint N child worktrees (1-16) and seat the next spawns in them; off clears the pool" },.{ .name = "/todo", .desc = "show the current task list" },diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex f94df501..6c25bb9a 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -21,8 +21,7 @@ const session_ext = session.session_ext;const saveSession = session.saveSession;const session = @import("session.zig");const presence = @import("presence.zig");-const listSavedSessions = session.listSavedSessions;-const sessionAge = session.sessionAge;+const session_list = @import("session_list.zig");const ansi = @import("ansi.zig");const style = &ansi.style;@@ -504,19 +503,7 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,if (std.mem.startsWith(u8, line, "/peek") and (line.len == 5 or line[5] == ' ' or line[5] == '\t')) return peer_channel.peekCommand(root, arena, line, out); // #469if (std.mem.startsWith(u8, line, "/routes") and (line.len == 7 or line[7] == ' ' or line[7] == '\t')) return route_set.command(root, keys, arena, line, out); // user-defined priced lanesif (std.mem.eql(u8, line, "/sessions")) {- var entries = listSavedSessions(root, arena);- defer entries.deinit(arena);- for (entries.items) |e| {- const age = sessionAge(arena, root.io, e.updated_ms);- const cur = if (std.mem.eql(u8, e.base, root.session_name)) " ← current" else "";- const parent = if (e.parent) |p| std.fmt.allocPrint(arena, " ← {s}", .{p}) catch "" else "";- if (e.title) |t| {- try out.print(" {s} {s}{s}{s}{s}{s}{s}{s}\n", .{ t, style.dim, e.base, parent, if (age.len > 0) " · " else "", age, style.reset, cur });- } else {- try out.print(" {s}{s}{s}{s}{s}{s}{s}\n", .{ e.base, parent, style.dim, if (age.len > 0) " " else "", age, style.reset, cur });- }- }- if (entries.items.len == 0) try out.writeAll("(no saved sessions in cwd)\n");+ try session_list.writeSaved(root, arena, out);try peer_channel.writeLiveSection(root, arena, out); // #469: co-resident live sessions, with goalstry out.flush();return true;diff --git a/src/commands_resume.zig b/src/commands_resume.zigindex 0dfbbb31..e08bab28 100644--- a/src/commands_resume.zig+++ b/src/commands_resume.zig@@ -16,11 +16,11 @@ const Agent = agent_mod.Agent;const Keys = provider_mod.Keys;const PickItem = pickers.PickItem;-fn pickSource(root: *Agent, arena: Allocator, out: *Io.Writer) ?[]const u8 {- var entries = session.listSavedSessions(root, arena);+fn pickSource(root: *Agent, arena: Allocator, out: *Io.Writer) ?session.SessionEntry {+ var entries = session.listSavedSessionsAll(root, arena);defer entries.deinit(arena);if (entries.items.len == 0) {- out.writeAll("(no saved sessions in cwd — /save creates one)\n") catch {};+ out.writeAll("(no saved sessions on this device — /save creates one in cwd)\n") catch {};out.flush() catch {};return null;}@@ -28,16 +28,20 @@ fn pickSource(root: *Agent, arena: Allocator, out: *Io.Writer) ?[]const u8 {defer choices.deinit(arena);for (entries.items) |e| {const age = session.sessionAge(arena, root.io, e.updated_ms);- const desc = if (e.title == null)- age- else if (age.len > 0)- std.fmt.allocPrint(arena, "{s} · {s}", .{ age, e.base }) catch e.base- else- e.base;+ const where = if (e.local) "" else session.displayWorkspace(arena, e.workspace, root.home);+ const desc = blk: {+ if (!e.local and where.len > 0) {+ if (age.len > 0) break :blk std.fmt.allocPrint(arena, "{s} · {s} · {s}", .{ age, e.base, where }) catch e.base;+ break :blk std.fmt.allocPrint(arena, "{s} · {s}", .{ e.base, where }) catch e.base;+ }+ if (e.title == null) break :blk age;+ if (age.len > 0) break :blk std.fmt.allocPrint(arena, "{s} · {s}", .{ age, e.base }) catch e.base;+ break :blk e.base;+ };choices.append(arena, .{ .name = e.title orelse e.base, .desc = desc }) catch return null;}const idx = pickers.listPicker(root, arena, out, "Resume session ›", choices.items) orelse return null;- return entries.items[idx].base;+ return entries.items[idx];}fn reject(out: *Io.Writer, comptime fmt: []const u8, args: anytype) !bool {@@ -50,19 +54,25 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,if (!std.mem.startsWith(u8, line, "/resume") or (line.len > 7 and line[7] != ' ' and line[7] != '\t')) return false;const parsed = session_branch.parseSpec(line["/resume".len..]) orelse return reject(out, "usage: /resume SOURCE [--branch DEST]\n", .{});var source = parsed.source;+ var picked_remote: ?[]const u8 = null;if (source.len == 0) {if (!(main_mod.use_color and root.in != null)) return reject(out, "usage: /resume SOURCE [--branch DEST]\n", .{});- source = pickSource(root, arena, out) orelse return true;+ const picked = pickSource(root, arena, out) orelse return true;+ source = try arena.dupe(u8, picked.base);+ if (!picked.local and picked.workspace.len > 0) picked_remote = try arena.dupe(u8, picked.workspace);}const resumed = session_branch.restore(root, keys, arena, source, parsed.branch) catch |err| return switch (err) {- error.FileNotFound => reject(out, "no session named '{s}' ({s}{s} not found in cwd) — /sessions lists saved ones\n", .{ source, source, session.session_ext }),+ error.FileNotFound => reject(out, "no session named '{s}' ({s}{s} not found in cwd or ~/{s}) — /sessions lists saved ones\n", .{ source, source, session.session_ext, session.sessions_dir }),error.InvalidSessionName => reject(out, "resume failed: invalid source or branch name\n", .{}),error.BranchMatchesSource => reject(out, "branch failed: destination must differ from source\n", .{}),error.BranchAlreadyExists => reject(out, "branch failed: destination already exists\n", .{}),else => reject(out, "resume failed: {t}\n", .{err}),};presence.noteLabelsFrom(root.io, root.gpa, arena, root.session_title, root.session_name);+ if (picked_remote) |ws| {+ try out.print("this save is from {s} — history restored here; read_file/edit_file/bash stay in {s}\n", .{ session.displayWorkspace(arena, ws, root.home), main_mod.g_cwd_display });+ }if (resumed.branched) {try out.print("branched {s}{s} → {s}{s} — {d} message(s), {s} via {s}{s}\n", .{ resumed.source, session.session_ext, resumed.target, session.session_ext, root.messages.items.len, root.provider.model, root.provider.id, if (root.strict) " (strict)" else "" });} else {diff --git a/src/libgraff.zig b/src/libgraff.zigindex 9690c439..c667c39a 100644--- a/src/libgraff.zig+++ b/src/libgraff.zig@@ -76,7 +76,7 @@ export fn graff_acp_create(new_seed: u32) void {session_id = null;seed = if (new_seed == 0) 1 else new_seed;engine.cancel_flag.store(false, .release);- engine.implementation_version = "0.0.283-core";+ engine.implementation_version = "0.0.284-core";}export fn graff_acp_feed(len: usize) i32 {diff --git a/src/messages.zig b/src/messages.zigindex 8022f851..7d126c52 100644--- a/src/messages.zig+++ b/src/messages.zig@@ -169,7 +169,15 @@ pub fn normalizeResponsesHistory(arena: Allocator, messages: *std.json.Array) voif (m.* != .object) continue;coerceChatStringToResponses(arena, m);const t = m.object.get("type") orelse continue;- if (t != .string or !std.mem.eql(u8, t.string, "function_call_output")) continue;+ if (t != .string) continue;+ // Codex re-parses `arguments` as JSON. An object/array here (some+ // providers emit it parsed) makes the next body `Invalid body:+ // failed to parse JSON value` (#711).+ if (std.mem.eql(u8, t.string, "function_call")) {+ coerceFieldToString(arena, m, "arguments");+ continue;+ }+ if (!std.mem.eql(u8, t.string, "function_call_output")) continue;const out = m.object.get("output") orelse continue;if (out == .string and out.string.len <= responses_output_cap) continue; // valid + within capconst s = if (out == .string) out.string else jsonValueString(arena, out);@@ -181,6 +189,12 @@ pub fn normalizeResponsesHistory(arena: Allocator, messages: *std.json.Array) vo}}+fn coerceFieldToString(arena: Allocator, m: *Value, field: []const u8) void {+ const v = m.object.get(field) orelse return;+ if (v == .string) return;+ m.object.put(arena, field, .{ .string = jsonValueString(arena, v) }) catch {};+}+/// #99: the chat-completions sibling of normalizeResponsesHistory. A resumed/// session can carry a `role:"tool"` message whose `content` is a byte-integer/// array (e.g. [61,61,61] — raw tool bytes that reached history as JSON ints) or@@ -440,3 +454,54 @@ test "toolResultMessage: result text serializes as a JSON string in every wire ftry std.testing.expect(std.mem.indexOf(u8, json, "\"content\":\"nope\"") != null);}}++test "#711: parallel error bash + object-shaped output still stringify as JSON" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const gh404 =+ \\gh: Not Found (HTTP 404)+ \\{"message":"Not Found","documentation_url":"https://docs.github.com/rest/pulls/comments#list-review-comments-on-a-pull-request"}+ \\+ \\[exit code 1]+ ;+ var msgs = std.json.Array.init(arena);+ var fc: std.json.ObjectMap = .empty;+ try fc.put(arena, "type", .{ .string = "function_call" });+ try fc.put(arena, "call_id", .{ .string = "5" });+ try fc.put(arena, "name", .{ .string = "bash" });+ var args_obj: std.json.ObjectMap = .empty;+ try args_obj.put(arena, "command", .{ .string = "gh api repos/justrach/codegraff/pulls/1/comments" });+ try fc.put(arena, "arguments", .{ .object = args_obj });+ try msgs.append(.{ .object = fc });+ try msgs.append(try toolResultMessage(arena, .responses, "5", gh404, true));+ try msgs.append(try toolResultMessage(arena, .responses, "6", gh404, true));+ var poison: std.json.ObjectMap = .empty;+ try poison.put(arena, "type", .{ .string = "function_call_output" });+ try poison.put(arena, "call_id", .{ .string = "7" });+ var parsed_err: std.json.ObjectMap = .empty;+ try parsed_err.put(arena, "message", .{ .string = "Not Found" });+ try poison.put(arena, "output", .{ .object = parsed_err });+ try msgs.append(.{ .object = poison });++ sanitizeMessagesUtf8(arena, &msgs);+ normalizeResponsesHistory(arena, &msgs);++ try std.testing.expect(msgs.items[0].object.get("arguments").? == .string);+ try std.testing.expect(std.mem.indexOf(u8, msgs.items[0].object.get("arguments").?.string, "gh api") != null);+ try std.testing.expect(msgs.items[1].object.get("output").? == .string);+ try std.testing.expect(msgs.items[2].object.get("output").? == .string);+ try std.testing.expect(msgs.items[3].object.get("output").? == .string);+ try std.testing.expect(std.mem.indexOf(u8, msgs.items[3].object.get("output").?.string, "Not Found") != null);++ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer };+ try s.beginObject();+ try s.objectField("input");+ try s.write(Value{ .array = msgs });+ try s.endObject();+ const body = aw.writer.buffered();+ const parsed = try std.json.parseFromSlice(Value, std.testing.allocator, body, .{});+ defer parsed.deinit();+ try std.testing.expect(parsed.value == .object);+}diff --git a/src/peer_inbox.zig b/src/peer_inbox.zigindex 58721b05..5ac8ae76 100644--- a/src/peer_inbox.zig+++ b/src/peer_inbox.zig@@ -97,6 +97,8 @@ fn textSlice(p: *const Parked) []const u8 {}/// One-line history wake. Cheap on purpose: the bodies wait in the ring.+/// Advisory on purpose (#708): an imperative `peer_message action=inbox`+/// made a greeting's first step look like tool work.pub fn formatWake(arena: Allocator) []const u8 {// Advisory framing (#708): the wake states that messages are waiting and// how to read them, but must not read as a command that displaces the@@ -241,10 +243,10 @@ test "inbox ring: park, one-line wake, overflow drops oldest, takeAll clears" {try testing.expectEqual(@as(usize, 2), unread());const wake = formatWake(a);try testing.expect(std.mem.startsWith(u8, wake, "[peer] 2 unread from session-aaa + 1 more"));- try testing.expect(std.mem.indexOf(u8, wake, "action=inbox") != null);- try testing.expect(std.mem.indexOfScalar(u8, wake, '\n') == null);+ try testing.expect(std.mem.indexOf(u8, wake, "peer_message action=inbox when relevant") != null);try testing.expect(std.mem.indexOf(u8, wake, "parked") != null);try testing.expect(std.mem.indexOf(u8, wake, "when relevant") != null);+ try testing.expect(std.mem.indexOfScalar(u8, wake, '\n') == null);const body = takeAll(a);try testing.expect(std.mem.indexOf(u8, body, "[peer message from session-aaa]: hold gui/src") != null);try testing.expect(std.mem.indexOf(u8, body, "[peer message from session-bbb · device DM]: your turn") != null);diff --git a/src/session.zig b/src/session.zigindex 175ce24d..60197d92 100644--- a/src/session.zig+++ b/src/session.zig@@ -49,6 +49,9 @@ pub const sessionMeta = session_index.sessionMeta;pub const sessionAge = session_index.sessionAge;pub const SessionEntry = session_index.SessionEntry;pub const listSavedSessions = session_index.listSavedSessions;+pub const listSavedSessionsAll = session_index.listSavedSessionsAll;+pub const homeSessionPath = session_index.homeSessionPath;+pub const displayWorkspace = session_index.displayWorkspace;/// Filesystem-safe slug of an AI title: lowercase alnum, any other run collapses/// to one '-', trimmed, capped at 60. "Fixing the login bug" -> "fixing-the-login-bug".@@ -304,6 +307,8 @@ fn queueSave(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !u64if (root.session_title) |title| try s.write(title) else try s.write(sessionTitle(root));try s.objectField("updated_ms");try s.write(unixMs(root.io));+ try s.objectField("workspace");+ try s.write(@import("main.zig").g_cwd_display);try s.objectField("messages");const saved_msgs = try session_peer.messagesForSave(arena, root.messages.items);const messages_start = aw.writer.buffered().len;@@ -434,7 +439,12 @@ pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8const data = Io.Dir.cwd().readFileAlloc(root.io, path, arena, .limited(8 * 1024 * 1024)) catch blk: {// backward-compat: older builds wrote <name>.session.json in cwd.const legacy = try std.fmt.allocPrint(arena, "{s}{s}", .{ name, session_ext });- break :blk try Io.Dir.cwd().readFileAlloc(root.io, legacy, arena, .limited(8 * 1024 * 1024));+ break :blk Io.Dir.cwd().readFileAlloc(root.io, legacy, arena, .limited(8 * 1024 * 1024)) catch {+ // #712: a save from `$HOME` is invisible if we only look at cwd.+ if (root.home.len == 0) return error.FileNotFound;+ const home_path = try homeSessionPath(arena, root.home, name);+ break :blk try Io.Dir.cwd().readFileAlloc(root.io, home_path, arena, .limited(8 * 1024 * 1024));+ };};const parsed = try std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always });if (parsed != .object) return error.BadSession;diff --git a/src/session_index.zig b/src/session_index.zigindex 166a2f16..ce45c96b 100644--- a/src/session_index.zig+++ b/src/session_index.zig@@ -10,6 +10,7 @@ const Value = std.json.Value;const Allocator = std.mem.Allocator;const agent_mod = @import("agent.zig");+const main_mod = @import("main.zig");const util = @import("util.zig");const Agent = agent_mod.Agent;const unixMs = util.unixMs;@@ -57,7 +58,7 @@ pub fn validSessionName(name: []const u8) bool {/// "updated_ms" before "messages", so parsing the header slice alone is/// enough. Zero-value fields when the file predates them or the header/// can't be read — callers fall back to the raw session name (#109).-pub const SessionMeta = struct { title: ?[]const u8 = null, parent: ?[]const u8 = null, updated_ms: i64 = 0 };+pub const SessionMeta = struct { title: ?[]const u8 = null, parent: ?[]const u8 = null, updated_ms: i64 = 0, workspace: ?[]const u8 = null };pub fn sessionMetaFromBytes(arena: Allocator, data: []const u8) SessionMeta {// Embedded quotes inside string values are escaped in the file, so the@@ -72,6 +73,7 @@ pub fn sessionMetaFromBytes(arena: Allocator, data: []const u8) SessionMeta {.title = if (parsed.object.get("title")) |v| (if (v == .string and v.string.len > 0) v.string else null) else null,.parent = if (parsed.object.get("parent")) |v| (if (v == .string and v.string.len > 0) v.string else null) else null,.updated_ms = if (parsed.object.get("updated_ms")) |v| (if (v == .integer) v.integer else 0) else 0,+ .workspace = if (parsed.object.get("workspace")) |v| (if (v == .string and v.string.len > 0) v.string else null) else null,};}@@ -100,28 +102,92 @@ pub fn sessionAge(arena: Allocator, io: Io, then_ms: i64) []const u8 {/// One row per saved session for the /resume picker and /sessions list:/// newest first, keyed (and resumed) by the file base name.-pub const SessionEntry = struct { base: []const u8, title: ?[]const u8 = null, parent: ?[]const u8 = null, updated_ms: i64 = 0 };+pub const SessionEntry = struct {+ base: []const u8,+ title: ?[]const u8 = null,+ parent: ?[]const u8 = null,+ updated_ms: i64 = 0,+ workspace: []const u8 = "",+ local: bool = true,+};-pub fn listSavedSessions(root: *Agent, arena: Allocator) std.ArrayList(SessionEntry) {+fn sameWorkspace(a: []const u8, b: []const u8) bool {+ return std.mem.eql(u8, std.mem.trimEnd(u8, a, "/"), std.mem.trimEnd(u8, b, "/"));+}++fn listFromDir(io: Io, arena: Allocator, dir: Io.Dir, workspace: []const u8, local: bool) std.ArrayList(SessionEntry) {var entries: std.ArrayList(SessionEntry) = .empty;- var dir = Io.Dir.cwd().openDir(root.io, sessions_dir, .{ .iterate = true }) catch return entries;- defer dir.close(root.io);var it = dir.iterate();- while (it.next(root.io) catch null) |entry| {+ while (it.next(io) catch null) |entry| {if (entry.kind != .file) continue;if (!std.mem.endsWith(u8, entry.name, session_ext)) continue;const base = arena.dupe(u8, entry.name[0 .. entry.name.len - session_ext.len]) catch continue;- const meta = sessionMeta(root, arena, base);- entries.append(arena, .{ .base = base, .title = meta.title, .parent = meta.parent, .updated_ms = meta.updated_ms }) catch {};+ const data = dir.readFileAlloc(io, entry.name, arena, .limited(8 * 1024 * 1024)) catch continue;+ const meta = sessionMetaFromBytes(arena, data);+ entries.append(arena, .{+ .base = base,+ .title = meta.title,+ .parent = meta.parent,+ .updated_ms = meta.updated_ms,+ .workspace = meta.workspace orelse workspace,+ .local = local,+ }) catch {};}- std.mem.sort(SessionEntry, entries.items, {}, struct {- fn newerFirst(_: void, a: SessionEntry, b: SessionEntry) bool {- return a.updated_ms > b.updated_ms;+ return entries;+}++fn newerFirst(_: void, a: SessionEntry, b: SessionEntry) bool {+ if (a.local != b.local) return a.local;+ return a.updated_ms > b.updated_ms;+}++pub fn listSavedSessions(root: *Agent, arena: Allocator) std.ArrayList(SessionEntry) {+ var dir = Io.Dir.cwd().openDir(root.io, sessions_dir, .{ .iterate = true }) catch return .empty;+ defer dir.close(root.io);+ const cwd = if (main_mod.g_cwd_display.len > 0) main_mod.g_cwd_display else ".";+ const entries = listFromDir(root.io, arena, dir, cwd, true);+ std.mem.sort(SessionEntry, entries.items, {}, newerFirst);+ return entries;+}++/// Cwd saves first, then `~/.graff/sessions` when that tree is a different+/// workspace. Cwd wins on the same base name. #712.+pub fn listSavedSessionsAll(root: *Agent, arena: Allocator) std.ArrayList(SessionEntry) {+ var entries = listSavedSessions(root, arena);+ const home = root.home;+ const cwd = if (main_mod.g_cwd_display.len > 0) main_mod.g_cwd_display else ".";+ if (home.len == 0 or sameWorkspace(home, cwd)) return entries;+ var home_root = Io.Dir.cwd().openDir(root.io, home, .{}) catch return entries;+ defer home_root.close(root.io);+ var home_sess = home_root.openDir(root.io, sessions_dir, .{ .iterate = true }) catch return entries;+ defer home_sess.close(root.io);+ const extra = listFromDir(root.io, arena, home_sess, home, false);+ for (extra.items) |e| {+ var seen = false;+ for (entries.items) |c| {+ if (std.mem.eql(u8, c.base, e.base) and c.local) {+ seen = true;+ break;+ }}- }.newerFirst);+ if (!seen) entries.append(arena, e) catch {};+ }+ std.mem.sort(SessionEntry, entries.items, {}, newerFirst);return entries;}+pub fn homeSessionPath(arena: Allocator, home: []const u8, name: []const u8) ![]const u8 {+ return std.fmt.allocPrint(arena, "{s}/{s}/{s}{s}", .{ home, sessions_dir, name, session_ext });+}++/// `~/…` when `path` is under home; otherwise the path as-is.+pub fn displayWorkspace(arena: Allocator, path: []const u8, home: []const u8) []const u8 {+ if (home.len > 0 and (std.mem.eql(u8, path, home) or std.mem.startsWith(u8, path, home) and path.len > home.len and path[home.len] == '/')) {+ return std.fmt.allocPrint(arena, "~{s}", .{path[home.len..]}) catch path;+ }+ return path;+}+/// Count `.session.json` files without parsing them — startup's banner hint.pub fn countSavedSessions(io: Io) usize {var n: usize = 0;@@ -178,3 +244,45 @@ test "savedSessionsHint is silent at zero and pluralizes" {try std.testing.expectEqualStrings("1 saved session · /resume to continue", savedSessionsHint(1, &buf));try std.testing.expectEqualStrings("3 saved sessions · /resume to continue", savedSessionsHint(3, &buf));}++test "sessionMetaFromBytes reads workspace (#712)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const meta = sessionMetaFromBytes(arena,+ \\{"provider":"x","model":"y","title":"Home chat","updated_ms":9,"workspace":"/Users/me","messages":[]}+ );+ try std.testing.expectEqualStrings("Home chat", meta.title.?);+ try std.testing.expectEqualStrings("/Users/me", meta.workspace.?);+ const legacy = sessionMetaFromBytes(arena,+ \\{"provider":"x","model":"y","title":"Old","updated_ms":1,"messages":[]}+ );+ try std.testing.expect(legacy.workspace == null);+}++test "listFromDir finds a session and infers workspace (#712)" {+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ try tmp.dir.writeFile(std.testing.io, .{+ .sub_path = "home-test.session.json",+ .data = "{\"provider\":\"x\",\"model\":\"y\",\"title\":\"Home chat\",\"updated_ms\":9,\"messages\":[]}",+ });+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const entries = listFromDir(std.testing.io, arena, tmp.dir, "/Users/me", false);+ try std.testing.expectEqual(@as(usize, 1), entries.items.len);+ try std.testing.expectEqualStrings("home-test", entries.items[0].base);+ try std.testing.expectEqualStrings("Home chat", entries.items[0].title.?);+ try std.testing.expectEqualStrings("/Users/me", entries.items[0].workspace);+ try std.testing.expect(!entries.items[0].local);+}++test "homeSessionPath and sameWorkspace (#712)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ try std.testing.expectEqualStrings("/Users/me/.graff/sessions/home-test.session.json", try homeSessionPath(arena, "/Users/me", "home-test"));+ try std.testing.expect(sameWorkspace("/Users/me", "/Users/me/"));+ try std.testing.expect(!sameWorkspace("/Users/me", "/tmp/proj"));+}diff --git a/src/session_list.zig b/src/session_list.zignew file mode 100644index 00000000..bf481093--- /dev/null+++ b/src/session_list.zig@@ -0,0 +1,59 @@+//! `/sessions` listing: cwd saves, then device-wide home saves (#712).++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const agent_mod = @import("agent.zig");+const session = @import("session.zig");+const ansi = @import("ansi.zig");+const style = &ansi.style;++const Agent = agent_mod.Agent;++pub fn writeSaved(root: *Agent, arena: Allocator, out: *Io.Writer) !void {+ var entries = session.listSavedSessionsAll(root, arena);+ defer entries.deinit(arena);+ var local_n: usize = 0;+ var remote_n: usize = 0;+ for (entries.items) |e| {+ if (e.local) local_n += 1 else remote_n += 1;+ }+ if (local_n > 0) {+ try out.writeAll("saved here\n");+ try writeRows(root, arena, out, entries.items, true);+ }+ if (remote_n > 0) {+ try out.writeAll("saved elsewhere on this device\n");+ try writeRows(root, arena, out, entries.items, false);+ }+ if (entries.items.len == 0) {+ try out.writeAll("(no saved sessions on this device — /save creates one in cwd)\n");+ } else if (local_n == 0) {+ try out.print("(no saved sessions in cwd — {d} elsewhere; bare /resume lists them)\n", .{remote_n});+ }+}++fn writeRows(root: *Agent, arena: Allocator, out: *Io.Writer, entries: []const session.SessionEntry, local: bool) !void {+ for (entries) |e| {+ if (e.local != local) continue;+ const age = session.sessionAge(arena, root.io, e.updated_ms);+ const cur = if (std.mem.eql(u8, e.base, root.session_name)) " ← current" else "";+ const parent = if (e.parent) |p| std.fmt.allocPrint(arena, " ← {s}", .{p}) catch "" else "";+ const where = if (local) "" else std.fmt.allocPrint(arena, " · {s}", .{session.displayWorkspace(arena, e.workspace, root.home)}) catch "";+ if (e.title) |t| {+ try out.print(" {s} {s}{s}{s}{s}{s}{s}{s}{s}\n", .{ t, style.dim, e.base, parent, if (age.len > 0) " · " else "", age, where, style.reset, cur });+ } else {+ try out.print(" {s}{s}{s}{s}{s}{s}{s}{s}\n", .{ e.base, parent, style.dim, if (age.len > 0) " " else "", age, where, style.reset, cur });+ }+ }+}++test "displayWorkspace tilde-shorts a home path (#712)" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ try std.testing.expectEqualStrings("~", session.displayWorkspace(a, "/Users/me", "/Users/me"));+ try std.testing.expectEqualStrings("~/code", session.displayWorkspace(a, "/Users/me/code", "/Users/me"));+ try std.testing.expectEqualStrings("/tmp/proj", session.displayWorkspace(a, "/tmp/proj", "/Users/me"));+}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex fb79a9af..0b158ac4 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -349,5 +349,6 @@ test {_ = @import("readline_image.zig"); // #702: composer image chips sync on delete_ = @import("agent_request_scratch.zig"); // #693: split out of agent_request.zig (600-line ceiling)_ = @import("commands_resume.zig"); // #697: --resume SOURCE --branch DEST parser+ _ = @import("session_list.zig"); // #712: device-wide saved-session listing_ = @import("net_efficiency_test.zig");}