graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: resume linked-worktree saves in that tree
justrach52c6dfa294f7
diff --git a/apps/native/lib/session-store.test.ts b/apps/native/lib/session-store.test.tsindex 29637004..a1304668 100644--- a/apps/native/lib/session-store.test.ts+++ b/apps/native/lib/session-store.test.ts@@ -53,6 +53,23 @@ describe("listSessionRows", () => {assert.equal(notes?.local, false);assert.equal(notes?.origin, "~");});++ it("lists an isolated worktree save and cwd still wins on the same name", () => {+ const cwd = mkdtempSync(path.join(tmpdir(), "graff-cwd-"));+ const home = mkdtempSync(path.join(tmpdir(), "graff-home-"));+ const wt = path.join(cwd, ".graff", "worktrees", "session-a");+ writeSession(cwd, "shared", { title: "Main copy", updated_ms: 20 });+ writeSession(wt, "shared", { title: "Tree copy", updated_ms: 90 });+ writeSession(wt, "isolated", { title: "Only tree", updated_ms: 40, workspace: wt });+ const rows = listSessionRows(cwd, home);+ assert.equal(rows.find((r) => r.name === "shared")?.title, "Main copy");+ assert.equal(rows.find((r) => r.name === "shared")?.local, true);+ const isolated = rows.find((r) => r.name === "isolated");+ assert.equal(isolated?.title, "Only tree");+ assert.equal(isolated?.local, false);+ assert.equal(isolated?.workspace, wt);+ assert.equal(findSessionFile(cwd, "isolated", home)?.workspace, wt);+ });});describe("legacy placeholder titles", () => {diff --git a/apps/native/lib/session-store.ts b/apps/native/lib/session-store.tsindex 81865260..916f6742 100644--- a/apps/native/lib/session-store.ts+++ b/apps/native/lib/session-store.ts@@ -207,12 +207,35 @@ function newerFirst(a: StoredSessionRow, b: StoredSessionRow): number {return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;}-/** Cwd saves first (they win on the same base name), then `~/.graff/sessions`- * when that tree is a different workspace. ADR 0059 / #712. */+/** Auto-isolate trees live here (ADR 0146). Other git worktrees are listed+ * by the engine via `git worktree list`. */+export function extraWorktreeRoots(cwd: string): string[] {+ const root = path.join(cwd, ".graff", "worktrees");+ if (!existsSync(root)) return [];+ try {+ return readdirSync(root, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .map((entry) => path.join(root, entry.name));+ } catch {+ return [];+ }+}++/** Cwd saves first (they win on the same base name), then linked worktrees+ * under `.graff/worktrees` (#1151), then `~/.graff/sessions` when that tree+ * is a different workspace. ADR 0059 / #712. */export function listSessionRows(cwd: string, home = homeDir()): StoredSessionRow[] {const cwdDir = path.join(cwd, SESSIONS_DIR);const rows = readDir(cwdDir, cwd, true, home, cwd);const seen = new Set(rows.map((r) => r.name));+ for (const wt of extraWorktreeRoots(cwd)) {+ if (sameWorkspace(wt, cwd)) continue;+ for (const row of readDir(path.join(wt, SESSIONS_DIR), wt, false, home, cwd)) {+ if (seen.has(row.name)) continue;+ rows.push(row);+ seen.add(row.name);+ }+ }if (home && !sameWorkspace(home, cwd)) {for (const row of readDir(path.join(home, SESSIONS_DIR), home, false, home, cwd)) {if (seen.has(row.name)) continue;@@ -272,6 +295,10 @@ export function findSessionFile(cwd: string, name: string, home = homeDir()): {if (!NAME_RE.test(name)) return null;const localFile = path.join(cwd, SESSIONS_DIR, `${name}${SESSION_EXT}`);if (existsSync(localFile)) return { file: localFile, local: true, workspace: cwd };+ for (const wt of extraWorktreeRoots(cwd)) {+ const file = path.join(wt, SESSIONS_DIR, `${name}${SESSION_EXT}`);+ if (existsSync(file)) return { file, local: false, workspace: wt };+ }if (home && !sameWorkspace(home, cwd)) {const homeFile = path.join(home, SESSIONS_DIR, `${name}${SESSION_EXT}`);if (existsSync(homeFile)) return { file: homeFile, local: false, workspace: home };diff --git a/docs/adr/0059-saved-session-discovery-is-device-scoped.md b/docs/adr/0059-saved-session-discovery-is-device-scoped.mdindex 60c6d3ca..f23bd76c 100644--- a/docs/adr/0059-saved-session-discovery-is-device-scoped.md+++ b/docs/adr/0059-saved-session-discovery-is-device-scoped.md@@ -2,6 +2,9 @@Status: accepted 2026-09-01+The no-chdir rule below still applies to **`$HOME` origin** saves. Linked+git worktrees re-enter on resume ([0155](0155-resume-reenters-saved-worktree.md)).+## ContextBare `/resume` and `/sessions` only opened `.graff/sessions` under thediff --git a/docs/adr/0155-resume-reenters-saved-worktree.md b/docs/adr/0155-resume-reenters-saved-worktree.mdnew file mode 100644index 00000000..fd346217--- /dev/null+++ b/docs/adr/0155-resume-reenters-saved-worktree.md@@ -0,0 +1,30 @@+# 0155. Resume re-enters a linked-worktree save++Status: accepted 2026-09-22++## Context++ADR 0059 listed cwd then `~/.graff/sessions` and restored history into the+**current** cwd — file tools stayed put. That avoided a silent jump into+`$HOME`. ADR 0146 then auto-isolated a second concurrent session into+`.graff/worktrees/<slug>`. Those conversations save under the linked tree.+`/resume` from the main checkout either missed them or replayed the+transcript onto the wrong branch.++## Decision++- `/sessions` and the resume picker also list `.graff/sessions` in this+ repository's git worktrees. Cwd still wins on the same base name; home+ saves come last.+- On `/resume`, `--resume`, and the TUI/desktop picker, if the save's+ workspace still exists and is not `$HOME`, enter it (same `chdir` as+ `workspace use`) so `read_file` / `edit_file` / `bash` follow the+ conversation.+- If the tree is gone, restore history here and say so.+- Home-origin saves stay history-only (ADR 0059).++## Consequences++A conversation that ran in an isolated tree resumes in that tree. `$HOME`+chats opened from a repo still do not steal the process cwd. Stale+worktrees need `/workspace use` only when git no longer lists them.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex cd360d9c..fef80de6 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -69,7 +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. |+| [0059](0059-saved-session-discovery-is-device-scoped.md) | `/resume` and `/sessions` list cwd then `~/.graff/sessions`; home-origin resume keeps tools in the current cwd. Linked worktrees: [0155](0155-resume-reenters-saved-worktree.md). || [0060](0060-named-source-gate-is-per-unanswered-mention.md) | The named-source nudge is per unanswered mention; identical user turns do not replay (#714). || [0061](0061-tool-only-turns-narrate-and-ask-in-band.md) | Heads-up text rides in the same response as the tool calls; a choice for the user is an `ask_user` call; a job exit the model already read never wakes it. || [0062](0062-background-servers-idle-lifecycle-and-ownership-record.md) | A background job silent and unread for 2h is stopped with its command kept; `/jobs keep` pins one (retained at exit); every job has an ownership record `graff servers` can list and stop, verified by start identity (#199). |@@ -176,6 +176,7 @@ record only when you need the evidence or the edge cases.| [0152](0152-persistent-shells-snapshot-once.md) | Persistent shells snapshot immediately (`wait_ms` ignored) and stay on `/jobs`; do not poll. Finite jobs still wait until exit (ADR 0010). || [0153](0153-task-workspaces-copy-and-scripts.md) | Task workspaces copy gitignored include files from the main checkout and run setup/run/archive scripts from `.graff/workspace.toml`. Finish is still not archive. || [0154](0154-parked-shells-yield-the-parent.md) | Interactive parked shells yield the parent like subagents: 15s foreground wait, then the prompt is yours until the job-exit wake. |+| [0155](0155-resume-reenters-saved-worktree.md) | Resume of a linked-worktree save re-enters that tree; `$HOME` origin stays history-only. |## When to write onediff --git a/src/commands_resume.zig b/src/commands_resume.zigindex 6bf6c459..82cd5440 100644--- a/src/commands_resume.zig+++ b/src/commands_resume.zig@@ -70,7 +70,11 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,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| {+ if (resumed.entered) {+ try out.print("now at {s} — read_file/edit_file/bash use this tree\n", .{session.displayWorkspace(arena, resumed.workspace, root.home)});+ } else if (resumed.enter_failed) {+ try out.print("could not enter {s} — history restored here; read_file/edit_file/bash stay in {s}\n", .{ session.displayWorkspace(arena, resumed.workspace, root.home), main_mod.g_cwd_display });+ } else 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) {diff --git a/src/main.zig b/src/main.zigindex 27ad956f..a9c05dfa 100644--- a/src/main.zig+++ b/src/main.zig@@ -563,13 +563,9 @@ const exec = @import("exec.zig");test { // ── Unit tests (`zig build test`): pull in tests from imported modules (mcp.zig)_ = .{ @import("mcp_apps.zig"), @import("html_view.zig"), @import("providers_confirmation_tests.zig"), @import("repl_model_confirmation_tests.zig"), @import("repl_model_pick_tests.zig"), @import("engine_sink_citation_tests.zig"), @import("cite_markup_stream_tests.zig"), @import("oneshot_citation_tests.zig"), @import("tui_acp.zig") };_ = .{ @import("mcp_server_tests.zig"), @import("main_test.zig"), @import("artifact_claim_command.zig"), @import("cli_path_hint.zig"), @import("run_budget.zig"), @import("pr_review_input.zig"), @import("pr_claim_review.zig"), @import("tui_paste_transfer.zig") };- _ = @import("session_catalog.zig");- _ = @import("session_prompt.zig");+ _ = .{ @import("session_catalog.zig"), @import("session_prompt.zig"), @import("session_discovery.zig") };_ = .{ @import("prompt_astra.zig"), @import("prompt_guidance.zig") }; // per-model guidance (Astra, GPT-5.6)- _ = @import("agent_empty_completion.zig"); // #745: plain-final reconciliation- _ = @import("agent_model_loop.zig");- _ = @import("publication_policy_tests.zig");- _ = @import("jobs_completion_tests.zig");+ _ = .{ @import("agent_empty_completion.zig"), @import("agent_model_loop.zig"), @import("publication_policy_tests.zig"), @import("jobs_completion_tests.zig") };_ = .{ @import("readline_paste_number_tests.zig"), @import("test_hooks.zig"), @import("peer_wake_loop.zig") };_ = @import("list_dir_nearmiss.zig");_ = @import("repo_map.zig");diff --git a/src/session.zig b/src/session.zigindex 6ed112e3..a42c9ead 100644--- a/src/session.zig+++ b/src/session.zig@@ -51,7 +51,7 @@ 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 listSavedSessionsAll = @import("session_discovery.zig").listAll;pub const homeSessionPath = session_index.homeSessionPath;pub const displayWorkspace = session_index.displayWorkspace;@@ -461,17 +461,8 @@ pub fn restoreContextMeter(root: *Agent, saved_context_tokens: u64, saved_local_/// the restored provider's kind — same provider id guarantees it.pub fn loadSession(root: *Agent, keys: *Keys, arena: Allocator, name: []const u8) !void {flushSaves(); // #273: a session switch never leaves the outgoing one queued- const path = try sessionPath(arena, name);- const 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 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 found = @import("session_discovery.zig").locate(root, arena, name) orelse return error.FileNotFound;+ const data = Io.Dir.cwd().readFileAlloc(root.io, found.path, arena, .limited(8 * 1024 * 1024)) catch return error.FileNotFound;const parsed = try std.json.parseFromSliceLeaky(Value, arena, data, .{ .allocate = .alloc_always });if (parsed != .object) return error.BadSession;const obj = parsed.object;diff --git a/src/session_branch.zig b/src/session_branch.zigindex 23b2a1c1..9457bddd 100644--- a/src/session_branch.zig+++ b/src/session_branch.zig@@ -8,6 +8,7 @@ const agent_mod = @import("agent.zig");const provider_mod = @import("provider.zig");const providers = @import("providers.zig");const session = @import("session.zig");+const session_discovery = @import("session_discovery.zig");const http_headers = @import("http_headers.zig");const prompts = @import("prompts.zig");const goal_flow = @import("goal_flow.zig");@@ -23,6 +24,9 @@ pub const Result = struct {source: []const u8,target: []const u8,branched: bool,+ workspace: []const u8 = "",+ entered: bool = false,+ enter_failed: bool = false,};pub const Spec = struct { source: []const u8, branch: ?[]const u8 };@@ -45,6 +49,7 @@ pub fn restore(root: *agent_mod.Agent, keys: *provider_mod.Keys, arena: Allocatoconst source = try arena.dupe(u8, source_raw);if (!session.validSessionName(source)) return Error.InvalidSessionName;const branch = if (branch_raw) |raw| try arena.dupe(u8, raw) else null;+ const origin = session_discovery.enterOrigin(root, arena, source);var reserved_path: ?[]const u8 = null;if (branch) |dest| {if (!session.validSessionName(dest)) return Error.InvalidSessionName;@@ -87,7 +92,14 @@ pub fn restore(root: *agent_mod.Agent, keys: *provider_mod.Keys, arena: Allocatoroot.pending_goal_note = goal_flow.reapplyFlagGoal(arena, root, g, util.unixMs(root.io)) catch null;prompts.pinStandingGoal(root, arena);}- return .{ .source = source, .target = root.session_name, .branched = branch != null };+ return .{+ .source = source,+ .target = root.session_name,+ .branched = branch != null,+ .workspace = origin.workspace,+ .entered = origin.kind == .entered,+ .enter_failed = origin.kind == .failed,+ };}test "--model outranks the model a resumed session saved" {diff --git a/src/session_discovery.zig b/src/session_discovery.zignew file mode 100644index 00000000..60c1d1cd--- /dev/null+++ b/src/session_discovery.zig@@ -0,0 +1,213 @@+//! Saved-session discovery across linked git worktrees, plus re-entering+//! that tree on resume (#1151). `$HOME` origin stays history-only (ADR 0059).++const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const agent_mod = @import("agent.zig");+const main_mod = @import("main.zig");+const session_index = @import("session_index.zig");+const workspace_switch = @import("workspace_switch.zig");++const Agent = agent_mod.Agent;++pub const Located = struct {+ path: []const u8,+ workspace: []const u8,+ local: bool,+};++pub const EnterKind = enum { none, skipped, entered, failed };++pub const Entered = struct {+ workspace: []const u8 = "",+ kind: EnterKind = .none,+};++fn exists(io: Io, path: []const u8) bool {+ return (Io.Dir.cwd().statFile(io, path, .{}) catch null) != null;+}++fn cwdDisplay() []const u8 {+ return if (main_mod.g_cwd_display.len > 0) main_mod.g_cwd_display else ".";+}++fn absSession(arena: Allocator, workspace: []const u8, name: []const u8) ![]const u8 {+ return std.fmt.allocPrint(arena, "{s}/{s}/{s}{s}", .{ workspace, session_index.sessions_dir, name, session_index.session_ext });+}++/// Home-origin saves do not move file-tool cwd. Linked worktrees do (#1151).+pub fn shouldEnter(origin: []const u8, cwd: []const u8, home: []const u8) bool {+ if (origin.len == 0 or !std.fs.path.isAbsolute(origin)) return false;+ if (session_index.sameWorkspace(origin, cwd)) return false;+ if (home.len > 0 and session_index.sameWorkspace(origin, home)) return false;+ return true;+}++/// `extra` is additional workspace roots (tests pass fake trees; production+/// passes `git worktree list` paths). Cwd, then extras (newest wins on a+/// duplicate name), then `$HOME`.+pub fn locateIn(+ io: Io,+ arena: Allocator,+ name: []const u8,+ cwd: []const u8,+ home: []const u8,+ extra: []const []const u8,+) ?Located {+ if (!session_index.validSessionName(name)) return null;+ const local_rel = session_index.sessionPath(arena, name) catch return null;+ if (exists(io, local_rel)) return .{ .path = local_rel, .workspace = cwd, .local = true };+ const legacy = std.fmt.allocPrint(arena, "{s}{s}", .{ name, session_index.session_ext }) catch return null;+ if (exists(io, legacy)) return .{ .path = legacy, .workspace = cwd, .local = true };++ var best: ?Located = null;+ var best_ms: i64 = -1;+ for (extra) |workspace| {+ if (session_index.sameWorkspace(workspace, cwd)) continue;+ const path = absSession(arena, workspace, name) catch continue;+ if (!exists(io, path)) continue;+ const data = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(8 * 1024 * 1024)) catch continue;+ const meta = session_index.sessionMetaFromBytes(arena, data);+ const ms = meta.updated_ms;+ if (best == null or ms > best_ms) {+ best = .{ .path = path, .workspace = meta.workspace orelse workspace, .local = false };+ best_ms = ms;+ }+ }+ if (best) |hit| return hit;++ if (home.len > 0 and !session_index.sameWorkspace(home, cwd)) {+ const home_path = session_index.homeSessionPath(arena, home, name) catch return null;+ if (exists(io, home_path)) return .{ .path = home_path, .workspace = home, .local = false };+ }+ return null;+}++fn extraWorktrees(root: *Agent, arena: Allocator) []const []const u8 {+ const trees = workspace_switch.listWorktrees(root.gpa, root.io, arena);+ var paths: std.ArrayList([]const u8) = .empty;+ for (trees) |t| {+ if (t.path.len == 0) continue;+ paths.append(arena, t.path) catch {};+ }+ return paths.items;+}++pub fn locate(root: *Agent, arena: Allocator, name: []const u8) ?Located {+ return locateIn(root.io, arena, name, cwdDisplay(), root.home, extraWorktrees(root, arena));+}++pub fn listAll(root: *Agent, arena: Allocator) std.ArrayList(session_index.SessionEntry) {+ var entries = session_index.listSavedSessions(root, arena);+ const cwd = cwdDisplay();+ for (extraWorktrees(root, arena)) |workspace| {+ if (session_index.sameWorkspace(workspace, cwd)) continue;+ session_index.appendWorkspaceSessions(root.io, arena, &entries, workspace, false);+ }+ const home = root.home;+ if (home.len > 0 and !session_index.sameWorkspace(home, cwd))+ session_index.appendWorkspaceSessions(root.io, arena, &entries, home, false);+ std.mem.sort(session_index.SessionEntry, entries.items, {}, struct {+ fn newer(_: void, a: session_index.SessionEntry, b: session_index.SessionEntry) bool {+ if (a.local != b.local) return a.local;+ return a.updated_ms > b.updated_ms;+ }+ }.newer);+ return entries;+}++pub fn enterOrigin(root: *Agent, arena: Allocator, name: []const u8) Entered {+ const found = locate(root, arena, name) orelse return .{};+ if (!shouldEnter(found.workspace, cwdDisplay(), root.home))+ return .{ .workspace = found.workspace, .kind = .skipped };+ if (builtin.os.tag == .windows)+ return .{ .workspace = found.workspace, .kind = .failed };+ const abs = workspace_switch.enterPath(root.gpa, root.io, arena, found.workspace) catch+ return .{ .workspace = found.workspace, .kind = .failed };+ return .{ .workspace = abs, .kind = .entered };+}++test "shouldEnter skips home and the current tree (#1151)" {+ try std.testing.expect(shouldEnter("/tmp/repo/.graff/worktrees/a", "/tmp/repo", "/Users/me"));+ try std.testing.expect(!shouldEnter("/Users/me", "/tmp/repo", "/Users/me"));+ try std.testing.expect(!shouldEnter("/tmp/repo", "/tmp/repo", "/Users/me"));+ try std.testing.expect(!shouldEnter("/tmp/repo/", "/tmp/repo", "/Users/me"));+ try std.testing.expect(!shouldEnter("relative", "/tmp/repo", "/Users/me"));+ try std.testing.expect(!shouldEnter("", "/tmp/repo", "/Users/me"));+}++test "locateIn prefers cwd then a linked worktree then home (#1151)" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ try tmp.dir.createDirPath(io, "cwd/.graff/sessions");+ try tmp.dir.createDirPath(io, "wt/.graff/sessions");+ try tmp.dir.createDirPath(io, "home/.graff/sessions");+ const cwd = try tmp.dir.realPathFileAlloc(io, "cwd", arena);+ const wt = try tmp.dir.realPathFileAlloc(io, "wt", arena);+ const home = try tmp.dir.realPathFileAlloc(io, "home", arena);++ try tmp.dir.writeFile(io, .{+ .sub_path = "cwd/.graff/sessions/here.session.json",+ .data = "{\"title\":\"Cwd\",\"updated_ms\":1,\"messages\":[]}",+ });+ try tmp.dir.writeFile(io, .{+ .sub_path = "wt/.graff/sessions/here.session.json",+ .data = "{\"title\":\"Tree\",\"updated_ms\":9,\"workspace\":\"unused\",\"messages\":[]}",+ });+ try tmp.dir.writeFile(io, .{+ .sub_path = "wt/.graff/sessions/isolated.session.json",+ .data = "{\"title\":\"Only tree\",\"updated_ms\":5,\"messages\":[]}",+ });+ try tmp.dir.writeFile(io, .{+ .sub_path = "home/.graff/sessions/notes.session.json",+ .data = "{\"title\":\"Home\",\"updated_ms\":3,\"messages\":[]}",+ });++ // locateIn cwd-relative paths are process-cwd, not tmp. Use absolute extras+ // and an empty relative cwd so local lookup misses, then extras/home hit.+ const isolated = locateIn(io, arena, "isolated", cwd, home, &.{wt}).?;+ try std.testing.expectEqualStrings(try absSession(arena, wt, "isolated"), isolated.path);+ try std.testing.expectEqualStrings(wt, isolated.workspace);+ try std.testing.expect(!isolated.local);++ const notes = locateIn(io, arena, "notes", cwd, home, &.{wt}).?;+ try std.testing.expect(session_index.sameWorkspace(notes.workspace, home));+ try std.testing.expect(!notes.local);+}++test "appendWorkspaceSessions skips names already listed (#1151)" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();++ try tmp.dir.createDirPath(io, "wt/.graff/sessions");+ try tmp.dir.writeFile(io, .{+ .sub_path = "wt/.graff/sessions/shared.session.json",+ .data = "{\"title\":\"Tree\",\"updated_ms\":9,\"messages\":[]}",+ });+ try tmp.dir.writeFile(io, .{+ .sub_path = "wt/.graff/sessions/only.session.json",+ .data = "{\"title\":\"Only\",\"updated_ms\":2,\"messages\":[]}",+ });+ const wt = try tmp.dir.realPathFileAlloc(io, "wt", arena);++ var entries: std.ArrayList(session_index.SessionEntry) = .empty;+ try entries.append(arena, .{ .base = "shared", .title = "Cwd", .updated_ms = 1, .workspace = "/cwd", .local = true });+ session_index.appendWorkspaceSessions(io, arena, &entries, wt, false);+ try std.testing.expectEqual(@as(usize, 2), entries.items.len);+ try std.testing.expectEqualStrings("shared", entries.items[0].base);+ try std.testing.expect(entries.items[0].local);+ try std.testing.expectEqualStrings("only", entries.items[1].base);+ try std.testing.expect(!entries.items[1].local);+}diff --git a/src/session_index.zig b/src/session_index.zigindex ce45c96b..4ead554d 100644--- a/src/session_index.zig+++ b/src/session_index.zig@@ -111,7 +111,7 @@ pub const SessionEntry = struct {local: bool = true,};-fn sameWorkspace(a: []const u8, b: []const u8) bool {+pub fn sameWorkspace(a: []const u8, b: []const u8) bool {return std.mem.eql(u8, std.mem.trimEnd(u8, a, "/"), std.mem.trimEnd(u8, b, "/"));}@@ -136,6 +136,32 @@ fn listFromDir(io: Io, arena: Allocator, dir: Io.Dir, workspace: []const u8, locreturn entries;}+/// Merge `.graff/sessions` under `workspace` into `entries`. Existing base+/// names win (cwd / earlier extras stay). #1151+pub fn appendWorkspaceSessions(+ io: Io,+ arena: Allocator,+ entries: *std.ArrayList(SessionEntry),+ workspace: []const u8,+ local: bool,+) void {+ var root = Io.Dir.cwd().openDir(io, workspace, .{}) catch return;+ defer root.close(io);+ var sess = root.openDir(io, sessions_dir, .{ .iterate = true }) catch return;+ defer sess.close(io);+ const extra = listFromDir(io, arena, sess, workspace, local);+ for (extra.items) |e| {+ var seen = false;+ for (entries.items) |c| {+ if (std.mem.eql(u8, c.base, e.base)) {+ seen = true;+ break;+ }+ }+ if (!seen) entries.append(arena, e) catch {};+ }+}+fn newerFirst(_: void, a: SessionEntry, b: SessionEntry) bool {if (a.local != b.local) return a.local;return a.updated_ms > b.updated_ms;diff --git a/src/session_list.zig b/src/session_list.zigindex bf481093..b9b90ff1 100644--- a/src/session_list.zig+++ b/src/session_list.zig@@ -1,4 +1,5 @@-//! `/sessions` listing: cwd saves, then device-wide home saves (#712).+//! `/sessions` listing: cwd saves, then linked worktrees (#1151), then+//! device-wide home saves (#712).const std = @import("std");const Io = std.Io;diff --git a/src/session_run.zig b/src/session_run.zigindex af8fd422..0b8665c5 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -433,8 +433,10 @@ pub fn restoreResumedSession(arena: Allocator, out: *Io.Writer, root: *agent_mod// Prefer the saved AI summary; fall back to the first user// message only for older sessions that have no saved title.const restored_title = root.session_title orelse title_mod.firstUserTitle(arena, root.messages);- title_mod.setTerminalTitle(out, restored_title, cwd_display);- try title_mod.printSessionHeader(out, restored_title, cwd_display);+ const cwd_now = @import("main.zig").g_cwd_display;+ const cwd_shown = if (cwd_now.len > 0) cwd_now else cwd_display;+ title_mod.setTerminalTitle(out, restored_title, cwd_shown);+ try title_mod.printSessionHeader(out, restored_title, cwd_shown);root.tui_header_shown = true;if (flags.branch_flag) |dest|try out.print("↩ branched {s}{s} → {s}{s} — {d} message(s) on {s}\n", .{ source, session.session_ext, dest, session.session_ext, root.messages.items.len, root.provider.model })diff --git a/src/tui_session.zig b/src/tui_session.zigindex cc53885e..23213b7e 100644--- a/src/tui_session.zig+++ b/src/tui_session.zig@@ -91,6 +91,8 @@ pub fn resumeCb(ctx_ptr: ?*anyopaque, gpa: Allocator, raw: []const u8, out: *tuiout.ultracode = root.ultracode_mode;out.note = if (resumed.branched)std.fmt.allocPrint(gpa, "branched {s} → {s}", .{ resumed.source, resumed.target }) catch &.{}+ else if (resumed.entered)+ std.fmt.allocPrint(gpa, "resumed {s} at {s}", .{ resumed.source, resumed.workspace }) catch &.{}elsestd.fmt.allocPrint(gpa, "resumed {s}", .{resumed.source}) catch &.{};return true;@@ -102,7 +104,7 @@ pub fn sessionsCb(ctx_ptr: ?*anyopaque, gpa: Allocator) ?[]const u8 {var arena_inst = std.heap.ArenaAllocator.init(gpa);defer arena_inst.deinit();const arena = arena_inst.allocator();- const entries = session.listSavedSessions(root, arena);+ const entries = session.listSavedSessionsAll(root, arena);if (entries.items.len == 0) return gpa.dupe(u8, "") catch null;var out: std.ArrayList(u8) = .empty;for (entries.items, 0..) |e, i| {@@ -112,12 +114,16 @@ pub fn sessionsCb(ctx_ptr: ?*anyopaque, gpa: Allocator) ?[]const u8 {};const age = session.sessionAge(arena, root.io, e.updated_ms);const title = e.title orelse e.base;- 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;+ };const line = std.fmt.allocPrint(arena, "{s}\t{s}\t{s}", .{ e.base, title, desc }) catch continue;out.appendSlice(gpa, line) catch {out.deinit(gpa);diff --git a/src/workspace_switch.zig b/src/workspace_switch.zigindex 3737adb9..2d82c6b7 100644--- a/src/workspace_switch.zig+++ b/src/workspace_switch.zig@@ -82,7 +82,7 @@ fn own(arena: Allocator, s: []const u8) []const u8 {/// Parse `git worktree list --porcelain`. Ignores bare/detached/locked extras.///-/// Every row OWNS its bytes. `listEntries` frees git's stdout as soon as it+/// Every row OWNS its bytes. `listWorktrees` frees git's stdout as soon as it/// returns, so borrowing out of `text` left each path and branch pointing at/// released memory (#715): reused pages read back as NUL, which printed blank/// rows for `action=list` and made `action=use` match neither the name nor the@@ -193,7 +193,7 @@ fn currentAbs(io: Io, arena: Allocator) []const u8 {return arena.dupe(u8, buf[0..n]) catch main_mod.g_cwd_display;}-fn listEntries(gpa: Allocator, io: Io, arena: Allocator) []Entry {+pub fn listWorktrees(gpa: Allocator, io: Io, arena: Allocator) []Entry {const listed = jobs.runCapped(gpa, io, &.{ "git", "worktree", "list", "--porcelain" }, 64 * 1024, 4096, 15_000) catch return &.{};defer {gpa.free(listed.stdout);@@ -203,7 +203,7 @@ fn listEntries(gpa: Allocator, io: Io, arena: Allocator) []Entry {return parsePorcelain(arena, listed.stdout);}-fn enterPath(gpa: Allocator, io: Io, arena: Allocator, path: []const u8) ![]const u8 {+pub fn enterPath(gpa: Allocator, io: Io, arena: Allocator, path: []const u8) ![]const u8 {if (builtin.os.tag == .windows) return error.Unsupported;const z = try arena.dupeSentinel(u8, path, 0);if (std.posix.system.chdir(z.ptr) != 0) return error.ChdirFailed;@@ -243,7 +243,7 @@ fn run(gpa: Allocator, io: Io, arena: Allocator, from_sub: bool, action: []const};const current = currentAbs(io, arena);if (std.mem.eql(u8, action, "list") or action.len == 0) {- return .{ .text = formatList(arena, listEntries(gpa, io, arena), current, io), .is_error = false };+ return .{ .text = formatList(arena, listWorktrees(gpa, io, arena), current, io), .is_error = false };}if (std.mem.eql(u8, action, "create")) {return createAndEnter(gpa, io, arena, path, base);@@ -264,7 +264,7 @@ fn run(gpa: Allocator, io: Io, arena: Allocator, from_sub: bool, action: []const.text = "workspace use needs path — a worktree folder or unique fragment. action=list to see them.",.is_error = true,};- const entries = listEntries(gpa, io, arena);+ const entries = listWorktrees(gpa, io, arena);return switch (resolve(arena, entries, path, current, io)) {.none => .{.text = tryText(arena, "no worktree matches \"{s}\" — action=list to see them", .{path}),@@ -387,7 +387,7 @@ test "parsePorcelain: path, short branch, ignores extras" {}test "#715: rows outlive the git output they were parsed from" {- // `listEntries` frees git's stdout the moment it returns. While rows+ // `listWorktrees` frees git's stdout the moment it returns. While rows// borrowed their bytes out of that buffer, every path and branch pointed at// released memory: reused pages read back as NUL, so `action=list` printed// blank rows and `action=use` matched neither the name nor the exact path@@ -419,7 +419,7 @@ test "#715: rows outlive the git output they were parsed from" {}}-test "#715: real git rows survive listEntries freeing git's stdout" {+test "#715: real git rows survive listWorktrees freeing git's stdout" {// Every other test here parses a comptime literal, which lives in .rodata// and can never be freed — which is exactly why the dangling rows in #715// went unnoticed. This one walks the production path: spawn git, parse,@@ -430,7 +430,7 @@ test "#715: real git rows survive listEntries freeing git's stdout" {defer arena_state.deinit();const a = arena_state.allocator();- const rows = listEntries(gpa, std.testing.io, a);+ const rows = listWorktrees(gpa, std.testing.io, a);if (rows.len == 0) return error.SkipZigTest; // not a git worktree herefor (rows) |e| {