graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(session): the transcript never wrote a byte on windows (#441)
Rach Pradhan8e7f8112baf2
diff --git a/src/session_index.zig b/src/session_index.zigindex a6d1722d..1a42d134 100644--- a/src/session_index.zig+++ b/src/session_index.zig@@ -18,6 +18,23 @@ pub const session_ext = ".session.json";/// Title-named session files live here (resume reads this).pub const sessions_dir = ".graff/sessions";+/// INVARIANT: every `.graff/` path this harness builds is FORWARD-SLASHED on+/// every platform, including Windows. Not an accident of `allocPrint` — a+/// choice, and callers may rely on it:+///+/// - Windows accepts '/' in the paths reaching Io.Dir (sliceToPrefixedFileW+/// normalizes them), so nothing is lost by not using the platform join.+/// - These strings are SHOWN TO THE MODEL. The #410 system-prompt line names+/// the session file, #409's cap marker cites an artifact, and #441's+/// transcript path travels into #411's post-compaction note. A path whose+/// shape changes per platform makes those prompts, and the goldens that+/// pin them, harder to reason about for no gain.+///+/// The corollary is for TESTS: assert on the basename, or on a path built+/// through these helpers — never by matching a separator by hand against+/// something the OS produced. A path that came back OUT of the OS+/// (realPathFile and friends, as in #409's spill marker) is the platform's+/// shape, not ours, and ee28d8c is the commit that learned it./// #441: the append-only transcript beside each session file, and the one/// rotated generation behind it. The suffixes live here, with the session/// suffix, because BOTH the writer (session_transcript.zig) and the sweep thatdiff --git a/src/session_tests.zig b/src/session_tests.zigindex c2a837c9..c469bf9f 100644--- a/src/session_tests.zig+++ b/src/session_tests.zig@@ -323,10 +323,14 @@ test "the autosave is where the transcript sees a new message (#441)" {// The real save path wrote the transcript beside the session file, one line// per message, with no hook of its own at any of the history's mutation- // sites. #411's note gets the path from the accessor, not by rebuilding it.+ // sites. #411's note gets the path from the accessor, not by rebuilding it,+ // and the assertion goes through that accessor rather than a hand-written+ // separator: the path is forward-slashed on every platform by design+ // (session_index.zig), but what matters here is that it names a real file.f.root.session_name = "wf";- try std.testing.expectEqualStrings(".graff/sessions/wf.transcript.jsonl", session_transcript.activePath(&f.root, arena).?);- const lines = try tmp.dir.readFileAlloc(io, ".graff/sessions/wf.transcript.jsonl", gpa, .limited(64 * 1024));+ const path = session_transcript.activePath(&f.root, arena) orelse return error.TestUnexpectedResult;+ try std.testing.expectEqualStrings("wf.transcript.jsonl", std.fs.path.basename(path));+ const lines = try tmp.dir.readFileAlloc(io, path, gpa, .limited(64 * 1024));defer gpa.free(lines);try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, lines, "\n"));try std.testing.expectEqual(@as(usize, 2), session_transcript.lineCount());diff --git a/src/session_transcript.zig b/src/session_transcript.zigindex cc15461b..41a8aad9 100644--- a/src/session_transcript.zig+++ b/src/session_transcript.zig@@ -73,6 +73,9 @@ pub var cap_bytes: usize = 16 * 1024 * 1024;/// `.graff/sessions/<name>.transcript.jsonl`. Pure; #411's post-compaction note/// and anything else that needs the path calls this instead of re-deriving the/// filename.+///+/// Forward-slashed on every platform, Windows included — deliberately, and+/// downstream may rely on it. session_index.zig states the invariant and why.pub fn transcriptPath(arena: Allocator, name: []const u8) ![]const u8 {return std.fmt.allocPrint(arena, "{s}/{s}{s}", .{ session_index.sessions_dir, name, transcript_ext });}@@ -242,8 +245,13 @@ fn seed(io: Io, dir: Io.Dir, arena: Allocator, name: []const u8) void {const path = transcriptPath(arena, name) catch return;const data = dir.readFileAlloc(io, path, arena, .limited(cap_bytes)) catch return;g.bytes = data.len;+ // '\n' explicitly, both here and in `flush` — never a platform default.+ // The digest is over the line's bytes, so a stray '\r' from an editor that+ // rewrote the file with CRLF would silently stop every line matching and+ // re-append the whole history; strip it rather than trust the writer.var it = std.mem.splitScalar(u8, data, '\n');- while (it.next()) |line| {+ while (it.next()) |raw| {+ const line = std.mem.trimEnd(u8, raw, "\r");if (line.len == 0) continue; // the trailing newline, or a torn writebump(digest(line));}@@ -274,13 +282,27 @@ fn flush(io: Io, dir: Io.Dir, arena: Allocator, name: []const u8, pending: []con/// or rewritten — that is the whole append-only guarantee, and it is why a/// compaction running against the same session cannot cost the transcript a/// byte. Returns the new size.+///+/// `.read = true` is load-bearing on WINDOWS and cost-free everywhere else.+/// Io.Dir.createFile maps `read` straight onto the NT access mask+/// (`GENERIC = .{ .WRITE = true, .READ = flags.read }`), and a write-only+/// handle carries FILE_GENERIC_WRITE, which does NOT include+/// FILE_READ_ATTRIBUTES. `File.stat` is NtQueryInformationFile(.All), which+/// needs exactly that right, so on a write-only handle it fails with+/// ACCESS_DENIED — and this function then returned null having already CREATED+/// the file, so every Windows transcript was an empty file and no message was+/// ever recorded. The path-based `statFile` fallback keeps a future std change+/// from re-introducing a silent no-write instead of an append.fn appendWhole(io: Io, dir: Io.Dir, path: []const u8, data: []const u8) ?usize {dir.createDirPath(io, session_index.sessions_dir) catch {};- const f = dir.createFile(io, path, .{ .truncate = false }) catch return null;+ const f = dir.createFile(io, path, .{ .truncate = false, .read = true }) catch return null;defer f.close(io);- const st = f.stat(io) catch return null;- f.writePositionalAll(io, data, st.size) catch return null;- return @as(usize, @intCast(st.size)) + data.len;+ const end: u64 = if (f.stat(io)) |st| st.size else |_| blk: {+ const st = dir.statFile(io, path, .{}) catch return null;+ break :blk st.size;+ };+ f.writePositionalAll(io, data, end) catch return null;+ return @as(usize, @intCast(end)) + data.len;}/// At the cap the live generation is RENAMED aside, never trimmed in place.@@ -293,6 +315,13 @@ fn appendWhole(io: Io, dir: Io.Dir, path: []const u8, data: []const u8) ?usize {/// live one, every line ever written stays a line somewhere, and the bound is/// simply two generations. The previous generation is what the next rotation/// replaces, so disk use is capped rather than merely slowed.+///+/// Replacing an EXISTING previous generation is the part Windows would+/// normally refuse (its rename does not overwrite). Io.Dir.rename is the+/// replacing one on every OS — dirRenameWindows passes replace_if_exists=true,+/// and Io.Dir.renamePreserve is the variant that fails on a taken name — so+/// the second and every later rotation works there too. The test below rotates+/// twice for exactly that reason.fn rotate(io: Io, dir: Io.Dir, arena: Allocator, name: []const u8) void {const live = transcriptPath(arena, name) catch return;const prev = rotatedPath(arena, name) catch return;@@ -306,232 +335,5 @@ pub fn resetForTest() void {detach();}-// ── tests ────────────────────────────────────────────────────────────────--const testing = std.testing;--fn msg(arena: Allocator, role: []const u8, text: []const u8) !Value {- var o: std.json.ObjectMap = .empty;- try o.put(arena, "role", .{ .string = role });- try o.put(arena, "content", .{ .string = text });- return .{ .object = o };-}--/// The fields `record` reads, and nothing else.-fn agentFor(gpa: Allocator, arena: Allocator, io: Io, name: []const u8) Agent {- var root: Agent = undefined;- root.gpa = gpa;- root.io = io;- root.sub = false;- root.session_name = name;- root.messages = std.json.Array.init(arena);- return root;-}--fn readTranscript(dir: Io.Dir, gpa: Allocator, rel: []const u8) ![]u8 {- return dir.readFileAlloc(testing.io, rel, gpa, .limited(1 << 20));-}--fn countLines(data: []const u8) usize {- return std.mem.count(u8, data, "\n");-}--test "one line per message, however many times the autosave runs (#441)" {- const io = testing.io;- const gpa = testing.allocator;- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- const a = arena_state.allocator();- resetForTest();- tool_spill.resetForTest();- defer resetForTest();- var tmp = testing.tmpDir(.{ .iterate = true });- defer tmp.cleanup();-- var root = agentFor(gpa, a, io, "s");- try root.messages.append(try msg(a, "user", "why did the build fail?"));- record(&root, tmp.dir, "s");- // The autosave runs again over an unchanged history: no second line.- record(&root, tmp.dir, "s");- record(&root, tmp.dir, "s");- const one = try readTranscript(tmp.dir, gpa, ".graff/sessions/s.transcript.jsonl");- defer gpa.free(one);- try testing.expectEqual(@as(usize, 1), countLines(one));- try testing.expect(std.mem.indexOf(u8, one, "why did the build fail?") != null);-- // A new turn adds exactly its own lines.- try root.messages.append(try msg(a, "assistant", "error: undefined symbol GRAFF_441"));- record(&root, tmp.dir, "s");- record(&root, tmp.dir, "s");- const two = try readTranscript(tmp.dir, gpa, ".graff/sessions/s.transcript.jsonl");- defer gpa.free(two);- try testing.expectEqual(@as(usize, 2), countLines(two));- // Append-only at the byte level: the first line is untouched where it was.- try testing.expect(std.mem.startsWith(u8, two, one));-- // A genuine repeat is a real message, not a duplicate: forward-only- // matching must not swallow it.- try root.messages.append(try msg(a, "user", "why did the build fail?"));- record(&root, tmp.dir, "s");- const three = try readTranscript(tmp.dir, gpa, ".graff/sessions/s.transcript.jsonl");- defer gpa.free(three);- try testing.expectEqual(@as(usize, 3), countLines(three));-}--test "compaction discards the history; the transcript still has it (#441)" {- const io = testing.io;- const gpa = testing.allocator;- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- const a = arena_state.allocator();- resetForTest();- tool_spill.resetForTest();- defer resetForTest();- var tmp = testing.tmpDir(.{ .iterate = true });- defer tmp.cleanup();-- var root = agentFor(gpa, a, io, "c");- // The exact wording that a summary would paraphrase away.- const detail = "ld: symbol(s) not found for architecture arm64: _graff_441_probe";- try root.messages.append(try msg(a, "user", "build it"));- try root.messages.append(try msg(a, "tool", detail));- try root.messages.append(try msg(a, "assistant", "fixing the link order"));- try root.messages.append(try msg(a, "user", "and now?"));- record(&root, tmp.dir, "c");- const before = try readTranscript(tmp.dir, gpa, ".graff/sessions/c.transcript.jsonl");- defer gpa.free(before);- try testing.expectEqual(@as(usize, 4), countLines(before));-- // compact()'s shape: a fresh array of [handoff summary] ++ the recent- // suffix verbatim. The detail is now unreachable from `messages` — the very- // next autosave rewrites the session file without it.- const tail = root.messages.items[3];- var fresh = std.json.Array.init(a);- try fresh.append(try msg(a, "user", "[summary] we were fixing a link error"));- try fresh.append(tail);- root.messages = fresh;- record(&root, tmp.dir, "c");-- const after = try readTranscript(tmp.dir, gpa, ".graff/sessions/c.transcript.jsonl");- defer gpa.free(after);- // (a) every earlier line survived, byte for byte, in place- try testing.expect(std.mem.startsWith(u8, after, before));- // (b) the discarded detail is still greppable- try testing.expect(std.mem.indexOf(u8, after, detail) != null);- // (c) only the summary was added — the verbatim tail is not duplicated- try testing.expectEqual(@as(usize, 5), countLines(after));- try testing.expectEqual(@as(usize, 1), std.mem.count(u8, after, "and now?"));- try testing.expect(std.mem.indexOf(u8, after, "[summary] we were fixing") != null);-- // And the turn after the compaction keeps appending normally.- try root.messages.append(try msg(a, "assistant", "linked clean"));- record(&root, tmp.dir, "c");- const later = try readTranscript(tmp.dir, gpa, ".graff/sessions/c.transcript.jsonl");- defer gpa.free(later);- try testing.expectEqual(@as(usize, 6), countLines(later));- try testing.expect(std.mem.startsWith(u8, later, after));-}--test "a resumed session does not re-append its restored history (#441)" {- const io = testing.io;- const gpa = testing.allocator;- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- const a = arena_state.allocator();- resetForTest();- tool_spill.resetForTest();- defer resetForTest();- var tmp = testing.tmpDir(.{ .iterate = true });- defer tmp.cleanup();-- var root = agentFor(gpa, a, io, "r");- try root.messages.append(try msg(a, "user", "first"));- try root.messages.append(try msg(a, "assistant", "second"));- record(&root, tmp.dir, "r");-- // A new process resumes "r": same history, no in-memory state at all. The- // digests are re-seeded from the file, so nothing is written twice.- resetForTest();- record(&root, tmp.dir, "r");- const data = try readTranscript(tmp.dir, gpa, ".graff/sessions/r.transcript.jsonl");- defer gpa.free(data);- try testing.expectEqual(@as(usize, 2), countLines(data));- try testing.expectEqual(@as(usize, 2), lineCount());- // The accessor #411 uses answers for the attached session only.- try testing.expectEqualStrings(".graff/sessions/r.transcript.jsonl", activePath(&root, a).?);- root.session_name = "somewhere-else";- try testing.expect(activePath(&root, a) == null);-}--test "a subagent writes no transcript (#441)" {- const io = testing.io;- const gpa = testing.allocator;- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- const a = arena_state.allocator();- resetForTest();- tool_spill.resetForTest();- defer resetForTest();- var tmp = testing.tmpDir(.{ .iterate = true });- defer tmp.cleanup();-- var root = agentFor(gpa, a, io, "sub-session");- root.sub = true;- try root.messages.append(try msg(a, "user", "delegated mandate"));- record(&root, tmp.dir, "sub-session");- try testing.expect(tmp.dir.statFile(io, ".graff/sessions/sub-session.transcript.jsonl", .{}) == error.FileNotFound);- try testing.expect(activePath(&root, a) == null);-- // A name that could escape the sessions dir writes nothing either.- root.sub = false;- record(&root, tmp.dir, "../escape");- try testing.expectEqual(@as(usize, 0), lineCount());-}--test "the size cap rotates the generation instead of rewriting it (#441)" {- const io = testing.io;- const gpa = testing.allocator;- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- const a = arena_state.allocator();- resetForTest();- tool_spill.resetForTest();- const saved_cap = cap_bytes;- defer {- cap_bytes = saved_cap;- resetForTest();- }- cap_bytes = 400;-- var tmp = testing.tmpDir(.{ .iterate = true });- defer tmp.cleanup();- var root = agentFor(gpa, a, io, "rot");- try root.messages.append(try msg(a, "user", "the oldest thing said, worth keeping"));- record(&root, tmp.dir, "rot");- const first = try readTranscript(tmp.dir, gpa, ".graff/sessions/rot.transcript.jsonl");- defer gpa.free(first);-- // Enough turns to pass the cap.- var i: usize = 0;- while (i < 8) : (i += 1) {- try root.messages.append(try msg(a, "assistant", "0123456789012345678901234567890123456789"));- record(&root, tmp.dir, "rot");- }-- // The previous generation holds the old bytes UNCHANGED — nothing was read,- // trimmed and written back — and the oldest line is still greppable there.- const prev = try readTranscript(tmp.dir, gpa, ".graff/sessions/rot.transcript.1.jsonl");- defer gpa.free(prev);- try testing.expect(std.mem.startsWith(u8, prev, first));- try testing.expect(std.mem.indexOf(u8, prev, "the oldest thing said") != null);- // Both generations respect the cap, so the session is bounded at 2x it.- try testing.expect(prev.len <= cap_bytes);- const live = try readTranscript(tmp.dir, gpa, ".graff/sessions/rot.transcript.jsonl");- defer gpa.free(live);- try testing.expect(live.len > 0 and live.len <= cap_bytes);- // Rotation is a file operation, not an identity reset: the messages already- // written are still not re-appended to the fresh generation.- const lines_before = lineCount();- record(&root, tmp.dir, "rot");- try testing.expectEqual(lines_before, lineCount());-}+// The tests live in session_transcript_tests.zig — the 600-line cap — and are+// reached through test_hooks.zig.diff --git a/src/session_transcript_tests.zig b/src/session_transcript_tests.zignew file mode 100644index 00000000..bc2c1663--- /dev/null+++ b/src/session_transcript_tests.zig@@ -0,0 +1,304 @@+//! session_transcript.zig's tests (#441). They live here for the 600-line cap,+//! mirroring session_tests.zig and agent_overflow_tests.zig; the module they+//! cover is reached in production from session.queueSave, but nothing+//! references THIS file outside test_hooks.zig, which is what makes its tests+//! run at all (AGENTS.md).+//!+//! The cases that earn their keep: a rewrite of the history leaves every line+//! already on disk byte-identical and in place, a repeated autosave adds+//! nothing, a resume re-seeds from the file instead of re-appending, a subagent+//! writes nothing, and the cap rotates TWICE so a rename that refused an+//! existing target could not pass.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const agent_mod = @import("agent.zig");+const Agent = agent_mod.Agent;+const tool_spill = @import("tool_spill.zig");+const transcript = @import("session_transcript.zig");+const activePath = transcript.activePath;+const lineCount = transcript.lineCount;+const record = transcript.record;+const resetForTest = transcript.resetForTest;+const rotatedPath = transcript.rotatedPath;+const transcriptPath = transcript.transcriptPath;+const transcript_ext = transcript.transcript_ext;++const testing = std.testing;++fn msg(arena: Allocator, role: []const u8, text: []const u8) !Value {+ var o: std.json.ObjectMap = .empty;+ try o.put(arena, "role", .{ .string = role });+ try o.put(arena, "content", .{ .string = text });+ return .{ .object = o };+}++/// The fields `record` reads, and nothing else.+fn agentFor(gpa: Allocator, arena: Allocator, io: Io, name: []const u8) Agent {+ var root: Agent = undefined;+ root.gpa = gpa;+ root.io = io;+ root.sub = false;+ root.session_name = name;+ root.messages = std.json.Array.init(arena);+ return root;+}++/// Read a generation through the SAME builder the writer uses, so the test can+/// never disagree with the code about where the file is — and so no separator+/// is ever written by hand here (session_index.zig's invariant).+fn readGen(dir: Io.Dir, gpa: Allocator, arena: Allocator, name: []const u8, rotated: bool) ![]u8 {+ const rel = if (rotated) try rotatedPath(arena, name) else try transcriptPath(arena, name);+ return dir.readFileAlloc(testing.io, rel, gpa, .limited(1 << 20));+}++/// Lines are '\n'-terminated by construction. The '\r' check is the guard: a+/// writer that ever picked up a platform line ending would break the digests+/// silently (every line would stop matching and the history would be+/// re-appended), so make it a hard failure here instead.+fn countLines(data: []const u8) !usize {+ try testing.expect(std.mem.indexOfScalar(u8, data, '\r') == null);+ return std.mem.count(u8, data, "\n");+}++/// `activePath` asserted portably: it is the path of a file that really exists,+/// and its basename is the one we expect. Matching a '/'-joined literal would+/// pass today (the builder is forward-slashed on every platform, deliberately)+/// but it asserts the separator rather than the behaviour — ee28d8c's lesson.+fn expectActive(root: *Agent, arena: Allocator, dir: Io.Dir, name: []const u8) !void {+ const p = activePath(root, arena) orelse return error.TestUnexpectedResult;+ const want = try std.fmt.allocPrint(arena, "{s}{s}", .{ name, transcript_ext });+ try testing.expectEqualStrings(want, std.fs.path.basename(p));+ _ = try dir.statFile(testing.io, p, .{}); // the cited file is really there+}++test "one line per message, however many times the autosave runs (#441)" {+ const io = testing.io;+ const gpa = testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ resetForTest();+ tool_spill.resetForTest();+ defer resetForTest();+ var tmp = testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();++ var root = agentFor(gpa, a, io, "s");+ try root.messages.append(try msg(a, "user", "why did the build fail?"));+ record(&root, tmp.dir, "s");+ // The autosave runs again over an unchanged history: no second line.+ record(&root, tmp.dir, "s");+ record(&root, tmp.dir, "s");+ const one = try readGen(tmp.dir, gpa, a, "s", false);+ defer gpa.free(one);+ try testing.expectEqual(@as(usize, 1), try countLines(one));+ try testing.expect(std.mem.indexOf(u8, one, "why did the build fail?") != null);++ // A new turn adds exactly its own lines.+ try root.messages.append(try msg(a, "assistant", "error: undefined symbol GRAFF_441"));+ record(&root, tmp.dir, "s");+ record(&root, tmp.dir, "s");+ const two = try readGen(tmp.dir, gpa, a, "s", false);+ defer gpa.free(two);+ try testing.expectEqual(@as(usize, 2), try countLines(two));+ // Append-only at the byte level: the first line is untouched where it was.+ try testing.expect(std.mem.startsWith(u8, two, one));++ // A genuine repeat is a real message, not a duplicate: forward-only+ // matching must not swallow it.+ try root.messages.append(try msg(a, "user", "why did the build fail?"));+ record(&root, tmp.dir, "s");+ const three = try readGen(tmp.dir, gpa, a, "s", false);+ defer gpa.free(three);+ try testing.expectEqual(@as(usize, 3), try countLines(three));+}++test "compaction discards the history; the transcript still has it (#441)" {+ const io = testing.io;+ const gpa = testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ resetForTest();+ tool_spill.resetForTest();+ defer resetForTest();+ var tmp = testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();++ var root = agentFor(gpa, a, io, "c");+ // The exact wording that a summary would paraphrase away.+ const detail = "ld: symbol(s) not found for architecture arm64: _graff_441_probe";+ try root.messages.append(try msg(a, "user", "build it"));+ try root.messages.append(try msg(a, "tool", detail));+ try root.messages.append(try msg(a, "assistant", "fixing the link order"));+ try root.messages.append(try msg(a, "user", "and now?"));+ record(&root, tmp.dir, "c");+ const before = try readGen(tmp.dir, gpa, a, "c", false);+ defer gpa.free(before);+ try testing.expectEqual(@as(usize, 4), try countLines(before));++ // compact()'s shape: a fresh array of [handoff summary] ++ the recent+ // suffix verbatim. The detail is now unreachable from `messages` — the very+ // next autosave rewrites the session file without it.+ const tail = root.messages.items[3];+ var fresh = std.json.Array.init(a);+ try fresh.append(try msg(a, "user", "[summary] we were fixing a link error"));+ try fresh.append(tail);+ root.messages = fresh;+ record(&root, tmp.dir, "c");++ const after = try readGen(tmp.dir, gpa, a, "c", false);+ defer gpa.free(after);+ // (a) every earlier line survived, byte for byte, in place+ try testing.expect(std.mem.startsWith(u8, after, before));+ // (b) the discarded detail is still greppable+ try testing.expect(std.mem.indexOf(u8, after, detail) != null);+ // (c) only the summary was added — the verbatim tail is not duplicated+ try testing.expectEqual(@as(usize, 5), try countLines(after));+ try testing.expectEqual(@as(usize, 1), std.mem.count(u8, after, "and now?"));+ try testing.expect(std.mem.indexOf(u8, after, "[summary] we were fixing") != null);++ // And the turn after the compaction keeps appending normally.+ try root.messages.append(try msg(a, "assistant", "linked clean"));+ record(&root, tmp.dir, "c");+ const later = try readGen(tmp.dir, gpa, a, "c", false);+ defer gpa.free(later);+ try testing.expectEqual(@as(usize, 6), try countLines(later));+ try testing.expect(std.mem.startsWith(u8, later, after));+}++test "a resumed session does not re-append its restored history (#441)" {+ const io = testing.io;+ const gpa = testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ resetForTest();+ tool_spill.resetForTest();+ defer resetForTest();+ var tmp = testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();++ var root = agentFor(gpa, a, io, "r");+ try root.messages.append(try msg(a, "user", "first"));+ try root.messages.append(try msg(a, "assistant", "second"));+ record(&root, tmp.dir, "r");++ // A new process resumes "r": same history, no in-memory state at all. The+ // digests are re-seeded from the file, so nothing is written twice.+ resetForTest();+ record(&root, tmp.dir, "r");+ const data = try readGen(tmp.dir, gpa, a, "r", false);+ defer gpa.free(data);+ try testing.expectEqual(@as(usize, 2), try countLines(data));+ try testing.expectEqual(@as(usize, 2), lineCount());+ // The accessor #411 uses answers for the attached session only.+ try expectActive(&root, a, tmp.dir, "r");+ root.session_name = "somewhere-else";+ try testing.expect(activePath(&root, a) == null);+}++test "a subagent writes no transcript (#441)" {+ const io = testing.io;+ const gpa = testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ resetForTest();+ tool_spill.resetForTest();+ defer resetForTest();+ var tmp = testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();++ var root = agentFor(gpa, a, io, "sub-session");+ root.sub = true;+ try root.messages.append(try msg(a, "user", "delegated mandate"));+ record(&root, tmp.dir, "sub-session");+ try testing.expectError(error.FileNotFound, readGen(tmp.dir, gpa, a, "sub-session", false));+ try testing.expect(activePath(&root, a) == null);++ // A name that could escape the sessions dir writes nothing either.+ root.sub = false;+ record(&root, tmp.dir, "../escape");+ try testing.expectEqual(@as(usize, 0), lineCount());+}++test "the size cap rotates the generation instead of rewriting it (#441)" {+ const io = testing.io;+ const gpa = testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ resetForTest();+ tool_spill.resetForTest();+ const saved_cap = transcript.cap_bytes;+ defer {+ transcript.cap_bytes = saved_cap;+ resetForTest();+ }+ transcript.cap_bytes = 400;++ var tmp = testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ var root = agentFor(gpa, a, io, "rot");+ try root.messages.append(try msg(a, "user", "the oldest thing said, worth keeping"));+ record(&root, tmp.dir, "rot");+ const first = try readGen(tmp.dir, gpa, a, "rot", false);+ defer gpa.free(first);++ // Enough turns to pass the cap.+ var i: usize = 0;+ while (i < 8) : (i += 1) {+ try root.messages.append(try msg(a, "assistant", "0123456789012345678901234567890123456789"));+ record(&root, tmp.dir, "rot");+ }++ // The previous generation holds the old bytes UNCHANGED — nothing was read,+ // trimmed and written back — and the oldest line is still greppable there.+ const prev = try readGen(tmp.dir, gpa, a, "rot", true);+ defer gpa.free(prev);+ try testing.expect(std.mem.startsWith(u8, prev, first));+ try testing.expect(std.mem.indexOf(u8, prev, "the oldest thing said") != null);+ // Both generations respect the cap, so the session is bounded at 2x it.+ try testing.expect(prev.len <= transcript.cap_bytes);+ const live = try readGen(tmp.dir, gpa, a, "rot", false);+ defer gpa.free(live);+ try testing.expect(live.len > 0 and live.len <= transcript.cap_bytes);+ // Rotation is a file operation, not an identity reset: the messages already+ // written are still not re-appended to the fresh generation.+ const lines_before = lineCount();+ record(&root, tmp.dir, "rot");+ try testing.expectEqual(lines_before, lineCount());++ // A SECOND rotation, over a previous generation that already exists. This+ // is the case a rename that refuses a taken target would fail — POSIX+ // replaces, Windows natively does not, and Io.Dir.rename is the replacing+ // variant on both. Without this the suite only ever rotated onto a free+ // name and could not tell the difference.+ while (i < 40) : (i += 1) {+ try root.messages.append(try msg(a, "assistant", "0123456789012345678901234567890123456789"));+ record(&root, tmp.dir, "rot");+ }+ const prev2 = try readGen(tmp.dir, gpa, a, "rot", true);+ defer gpa.free(prev2);+ const live2 = try readGen(tmp.dir, gpa, a, "rot", false);+ defer gpa.free(live2);+ // The previous generation really was REPLACED: it used to be the one+ // holding the oldest line, and is not any more. A rename that refused a+ // taken target would have left the first generation sitting there and+ // stalled the live file past its cap instead.+ try testing.expect(std.mem.indexOf(u8, prev, "the oldest thing said") != null);+ try testing.expect(std.mem.indexOf(u8, prev2, "the oldest thing said") == null);+ // Both generations still hold whole lines, and the cap still binds.+ try testing.expect(prev2.len > 0 and prev2.len <= transcript.cap_bytes);+ try testing.expect(live2.len > 0 and live2.len <= transcript.cap_bytes);+ try testing.expect(std.mem.endsWith(u8, prev2, "\n"));+ try testing.expect(std.mem.endsWith(u8, live2, "\n"));+ // 1 + 8 + 32 messages ever entered the history, and every one was recorded+ // exactly once — no rotation re-appended anything.+ try testing.expectEqual(@as(usize, 41), lineCount());+}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 033f8746..161458f8 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -70,6 +70,11 @@ const scoring_slot_test = @import("scoring_slot_test.zig");// #273: session.zig's own tests, moved off it for the same reason.const session_tests = @import("session_tests.zig");+// #441: and session_transcript.zig's, moved off it for the same reason again.+// The module itself is reached from session.queueSave, but this FILE is not, so+// without the hook its whole suite compiles to nothing and reports green.+const session_transcript_tests = @import("session_transcript_tests.zig");+// #375: `graff acp` (Zed's Agent Client Protocol over stdio). args.zig calls// one predicate from it, which analyses the file but does not run its tests.const acp = @import("acp.zig");@@ -170,6 +175,7 @@ test {_ = serve_create;_ = scoring_slot_test;_ = session_tests;+ _ = session_transcript_tests;_ = mcp_config;_ = acp;_ = agent_eval_control_tests;