Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

[RSI] fix(coding-agent): speed up session append and fork hot paths (#2276)

Seth Karten5c42f8549f3b
diff --git a/packages/coding-agent/.changes/session-manager-append-hot-path.md b/packages/coding-agent/.changes/session-manager-append-hot-path.md
new file mode 100644
index 0000000000..feff7450b3
--- /dev/null
+++ b/packages/coding-agent/.changes/session-manager-append-hot-path.md
@@ -0,0 +1 @@
+- Sped up session appends and forking large sessions: the per-append assistant-message scan is now a cached flag, and session forks write through a single open descriptor instead of one append syscall per source entry.
diff --git a/packages/coding-agent/src/core/session-manager.ts b/packages/coding-agent/src/core/session-manager.ts
index d918a1e068..cd10b6e1ee 100644
--- a/packages/coding-agent/src/core/session-manager.ts
+++ b/packages/coding-agent/src/core/session-manager.ts
@@ -13,6 +13,7 @@ import {
readFileSync,
readSync,
statSync,
+ writeSync,
} from "fs";
import { readdir, readFile, stat } from "fs/promises";
import { basename, dirname, join, resolve } from "path";
@@ -303,6 +304,18 @@ function createUniqueSessionFileTarget(sessionDir: string): { sessionId: string;
throw new Error("Unable to create a unique session file");
}
+// writeSync may return a short count without throwing; a torn line would
+// corrupt the forked JSONL on reopen, so loop until the whole buffer lands.
+function writeAllSync(descriptor: number, data: string, path: string): void {
+ const bytes = Buffer.from(data, "utf8");
+ let offset = 0;
+ while (offset < bytes.length) {
+ const written = writeSync(descriptor, bytes, offset, bytes.length - offset);
+ if (written <= 0) throw new Error(`Short write persisting ${path}`);
+ offset += written;
+ }
+}
+
export function getSessionArtifactsRoot(sessionDir: string): string {
return join(dirname(sessionDir), "session-artifacts");
}
@@ -1437,6 +1450,10 @@ export class SessionManager {
private cwd: string;
private persist: boolean;
private flushed: boolean = false;
+ // Flip-once cache for the no-assistant guard in _persist: true from the first
+ // assistant message on. Refreshed on every fileEntries reassignment; hot
+ // appends only ever set it to true, keeping _persist O(1).
+ private hasAssistantEntry = false;
private fileEntries: FileEntry[] = [];
private byId: Map<string, SessionEntry> = new Map();
private labelsById: Map<string, string> = new Map();
@@ -1475,6 +1492,7 @@ export class SessionManager {
if (existsSync(this.sessionFile)) {
if (this.persist && preloadedEntries === undefined) repairJsonlDamage(this.sessionFile);
this.fileEntries = preloadedEntries ?? loadEntriesFromFile(this.sessionFile);
+ this._refreshHasAssistantEntry();
// If file was empty or corrupted (no valid header), truncate and start fresh
// to avoid appending messages without a session header (which breaks the session)
@@ -1552,6 +1570,7 @@ export class SessionManager {
git,
};
this.fileEntries = [header];
+ this.hasAssistantEntry = false;
this.byId.clear();
this.labelsById.clear();
this.labelTimestampsById.clear();
@@ -1564,6 +1583,13 @@ export class SessionManager {
return this.sessionFile;
}
+ // Cold-path recompute of the flip-once has-assistant cache. Hot appends keep
+ // it O(1) in _appendEntry; every fileEntries reassignment (open, branch,
+ // rollback) refreshes it here.
+ private _refreshHasAssistantEntry(): void {
+ this.hasAssistantEntry = this.fileEntries.some((e) => e.type === "message" && e.message.role === "assistant");
+ }
+
private _buildIndex(): void {
this.byId.clear();
this.labelsById.clear();
@@ -1668,6 +1694,7 @@ export class SessionManager {
git,
};
this.fileEntries = [header, ...this.getEntries()];
+ this._refreshHasAssistantEntry();
this._rewriteFile();
this.flushed = true;
return this.sessionFile;
@@ -1694,13 +1721,16 @@ export class SessionManager {
_persist(entry: SessionEntry): void {
if (!this.persist || !this.sessionFile) return;
- const hasAssistant = this.fileEntries.some((e) => e.type === "message" && e.message.role === "assistant");
const shouldPersistWithoutAssistant = entry.type === "session_state" || entry.type === "session_info";
- if (!hasAssistant && !shouldPersistWithoutAssistant) {
+ if (!this.hasAssistantEntry && !shouldPersistWithoutAssistant) {
this.flushed = false;
return;
}
+ // The existsSync check is what lets the next append recover from the session
+ // file being deleted underneath a live session: without it appendFileSync
+ // would recreate a headerless stub (pinned by session-state.test.ts's
+ // "rewrites the full session if the session file disappears after flushing").
if (!this.flushed || !existsSync(this.sessionFile)) {
this._rewriteFile();
this.flushed = true;
@@ -1713,6 +1743,9 @@ export class SessionManager {
private _appendEntry(entry: SessionEntry): void {
this.fileEntries.push(entry);
+ if (entry.type === "message" && entry.message.role === "assistant") {
+ this.hasAssistantEntry = true;
+ }
this.byId.set(entry.id, entry);
this.leafId = entry.id;
this._persist(entry);
@@ -2017,6 +2050,7 @@ export class SessionManager {
if (this.leafId !== null && this.leafId !== previousLeafId) {
this.byId.delete(this.leafId);
this.fileEntries.pop();
+ this._refreshHasAssistantEntry();
this.leafId = previousLeafId;
// The failed append may have left a torn line on disk. Restore the file
// from the rolled-back entries now; if that also fails (e.g. the disk is
@@ -2247,6 +2281,7 @@ export class SessionManager {
}
this.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
+ this._refreshHasAssistantEntry();
this.sessionId = newSessionId;
this.sessionFile = newSessionFile;
this._buildIndex();
@@ -2256,8 +2291,7 @@ export class SessionManager {
// first assistant response, matching the newSession() contract
// and avoiding the duplicate-header bug when _persist()'s
// no-assistant guard later resets flushed to false.
- const hasAssistant = this.fileEntries.some((e) => e.type === "message" && e.message.role === "assistant");
- if (hasAssistant) {
+ if (this.hasAssistantEntry) {
this._rewriteFile();
this.flushed = true;
} else {
@@ -2282,6 +2316,7 @@ export class SessionManager {
parentId = labelEntry.id;
}
this.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
+ this._refreshHasAssistantEntry();
this.sessionId = newSessionId;
this._buildIndex();
return undefined;
@@ -2378,24 +2413,34 @@ export class SessionManager {
rlmDepth: resolveSessionRlmDepth(sourceHeader, sourcePath),
git: captureGitContext(targetCwd) ?? undefined,
};
- appendFileSync(newSessionFile, `${JSON.stringify(newHeader)}\n`);
-
- // Drop the source's git_state entries (re-linking children): they describe the source repo,
- // so the fork would otherwise report the source's git instead of its own target context.
- const droppedParent = new Map<string, string | null>();
- for (const entry of sourceEntries) {
- if (entry.type === "git_state") droppedParent.set(entry.id, entry.parentId);
- }
- const liveParent = (parentId: string | null): string | null => {
- let pid = parentId;
- while (pid !== null && droppedParent.has(pid)) pid = droppedParent.get(pid) ?? null;
- return pid;
- };
- for (const entry of sourceEntries) {
- if (entry.type === "session" || entry.type === "git_state") continue;
- const parentId = liveParent(entry.parentId);
- const out = parentId === entry.parentId ? entry : { ...entry, parentId };
- appendFileSync(newSessionFile, `${JSON.stringify(out)}\n`);
+ // The whole fork flows through one descriptor: one openSync, one
+ // writeAllSync per line, one closeSync. writeAllSync loops past short
+ // counts so every JSONL line lands whole, and "w" creates the target
+ // fresh because createUniqueSessionFileTarget guarantees it does not
+ // exist yet.
+ const descriptor = openSync(newSessionFile, "w");
+ try {
+ writeAllSync(descriptor, `${JSON.stringify(newHeader)}\n`, newSessionFile);
+
+ // Drop the source's git_state entries (re-linking children): they describe the source repo,
+ // so the fork would otherwise report the source's git instead of its own target context.
+ const droppedParent = new Map<string, string | null>();
+ for (const entry of sourceEntries) {
+ if (entry.type === "git_state") droppedParent.set(entry.id, entry.parentId);
+ }
+ const liveParent = (parentId: string | null): string | null => {
+ let pid = parentId;
+ while (pid !== null && droppedParent.has(pid)) pid = droppedParent.get(pid) ?? null;
+ return pid;
+ };
+ for (const entry of sourceEntries) {
+ if (entry.type === "session" || entry.type === "git_state") continue;
+ const parentId = liveParent(entry.parentId);
+ const out = parentId === entry.parentId ? entry : { ...entry, parentId };
+ writeAllSync(descriptor, `${JSON.stringify(out)}\n`, newSessionFile);
+ }
+ } finally {
+ closeSync(descriptor);
}
return new SessionManager(targetCwd, dir, newSessionFile, true);
diff --git a/packages/coding-agent/test/session-manager-append-bench.ts b/packages/coding-agent/test/session-manager-append-bench.ts
new file mode 100644
index 0000000000..996ac0bfcd
--- /dev/null
+++ b/packages/coding-agent/test/session-manager-append-bench.ts
@@ -0,0 +1,128 @@
+/**
+ * Benchmark: SessionManager append/fork hot paths.
+ *
+ * - _persist append cost at growing session sizes (the flip-once
+ * has-assistant cache keeps per-append cost flat as entries grow).
+ * - forkFrom wall time for source sessions of growing entry counts
+ * (the whole fork flows through one open descriptor).
+ *
+ * Run with:
+ *
+ * npx tsx test/session-manager-append-bench.ts
+ */
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { performance } from "node:perf_hooks";
+import { SessionManager } from "../src/core/session-manager.js";
+
+const SIZES = [1_000, 5_000, 20_000];
+const MEASURED_APPENDS = 100;
+const FORK_RUNS = 3;
+
+// Session files are built without any assistant entry for the pre-assistant
+// scenario (the guard then suppresses every append via the O(1) cache), and
+// with an early assistant entry for the steady-state scenario.
+
+function percentile(sorted: number[], p: number): number {
+ return sorted[Math.min(sorted.length - 1, Math.floor((p / 100) * sorted.length))];
+}
+
+function buildSourceSession(dir: string, entries: number, firstEntryRole: "user" | "assistant" = "assistant"): string {
+ const lines: string[] = [
+ JSON.stringify({
+ type: "session",
+ version: 3,
+ id: "bench-session",
+ timestamp: "2026-01-01T00:00:00.000Z",
+ cwd: dir,
+ }),
+ ];
+ let parentId: string | null = null;
+ for (let i = 0; i < entries; i++) {
+ const id = `m${i}`;
+ const role = firstEntryRole === "assistant" && (i === 0 || i % 3 === 0) ? "assistant" : "user";
+ const text = `benchmark payload ${i} `.repeat(role === "assistant" ? 12 : 5);
+ lines.push(
+ JSON.stringify({
+ type: "message",
+ id,
+ parentId,
+ timestamp: new Date(1_767_225_600_000 + i).toISOString(),
+ message: {
+ role,
+ content: [{ type: "text", text }],
+ timestamp: 1_767_225_600_000 + i,
+ ...(role === "assistant"
+ ? {
+ api: "openai-completions",
+ provider: "openai",
+ model: "test",
+ usage: {
+ input: 1,
+ output: 1,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 2,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ stopReason: "stop",
+ }
+ : {}),
+ },
+ }),
+ );
+ parentId = id;
+ }
+ const file = join(dir, `source-${entries}-${firstEntryRole}.jsonl`);
+ writeFileSync(file, `${lines.join("\n")}\n`);
+ return file;
+}
+
+function benchAppend(label: string, sourceFile: string, entries: number): void {
+ const mgr = SessionManager.open(sourceFile);
+ let leafId = mgr.getLeafId();
+ const durations: number[] = [];
+ for (let i = 0; i < MEASURED_APPENDS; i++) {
+ const start = performance.now();
+ mgr.appendMessage({ role: "user", content: `append probe ${i}`, timestamp: Date.now() });
+ durations.push(performance.now() - start);
+ leafId = mgr.getLeafId();
+ }
+ const sorted = [...durations].sort((a, b) => a - b);
+ const mean = durations.reduce((a, b) => a + b, 0) / durations.length;
+ console.log(`\n${label}: append x${MEASURED_APPENDS} into session with ${entries} entries (leaf ${leafId})`);
+ console.log(` mean: ${mean.toFixed(3)} ms`);
+ console.log(` p50: ${percentile(sorted, 50).toFixed(3)} ms`);
+ console.log(` p99: ${percentile(sorted, 99).toFixed(3)} ms`);
+}
+
+function benchFork(dir: string, sourceFile: string, entries: number): void {
+ const times: number[] = [];
+ for (let i = 0; i < FORK_RUNS; i++) {
+ const targetDir = mkdtempSync(join(tmpdir(), `pi-fork-bench-target-${entries}-`));
+ const start = performance.now();
+ SessionManager.forkFrom(sourceFile, dir, targetDir);
+ times.push(performance.now() - start);
+ rmSync(targetDir, { recursive: true, force: true });
+ }
+ console.log(
+ `\nforkFrom ${entries}-entry source, ${FORK_RUNS} runs: ${times.map((t) => `${t.toFixed(1)} ms`).join(", ")}`,
+ );
+ console.log(` best: ${Math.min(...times).toFixed(1)} ms`);
+}
+
+const root = mkdtempSync(join(tmpdir(), "pi-session-manager-bench-"));
+try {
+ for (const entries of SIZES) {
+ const sourceFile = buildSourceSession(root, entries);
+ benchAppend("post-assistant (append path)", sourceFile, entries);
+ benchFork(root, sourceFile, entries);
+ }
+ for (const entries of SIZES) {
+ const sourceFile = buildSourceSession(root, entries, "user");
+ benchAppend("pre-assistant (guard path)", sourceFile, entries);
+ }
+} finally {
+ rmSync(root, { recursive: true, force: true });
+}
diff --git a/packages/coding-agent/test/session-manager/append-hot-path.test.ts b/packages/coding-agent/test/session-manager/append-hot-path.test.ts
new file mode 100644
index 0000000000..0681c1bb39
--- /dev/null
+++ b/packages/coding-agent/test/session-manager/append-hot-path.test.ts
@@ -0,0 +1,318 @@
+import {
+ type appendFileSync,
+ existsSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ writeFileSync,
+ type writeSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+type AppendFileSync = typeof appendFileSync;
+type WriteSync = typeof writeSync;
+
+const fsMocks = vi.hoisted(() => ({
+ actualWriteSync: undefined as WriteSync | undefined,
+ appendFileSync: vi.fn<AppendFileSync>(),
+ writeSync: vi.fn<WriteSync>(),
+}));
+
+// Passthrough spies: real fs behavior everywhere, per-call interception for
+// tests that pin write behavior (append call counting, short write counts).
+vi.mock("node:fs", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("node:fs")>();
+ fsMocks.actualWriteSync = actual.writeSync;
+ fsMocks.appendFileSync.mockImplementation(actual.appendFileSync);
+ fsMocks.writeSync.mockImplementation(actual.writeSync);
+ return { ...actual, appendFileSync: fsMocks.appendFileSync, writeSync: fsMocks.writeSync };
+});
+
+import { loadEntriesFromFile, SessionManager } from "../../src/core/session-manager.js";
+
+const tempDirs: string[] = [];
+
+afterEach(() => {
+ while (tempDirs.length > 0) {
+ const dir = tempDirs.pop()!;
+ rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+function createTempDir(): string {
+ const dir = mkdtempSync(join(tmpdir(), "pi-session-manager-append-"));
+ tempDirs.push(dir);
+ return dir;
+}
+
+function userMsg(text: string) {
+ return { role: "user" as const, content: text, timestamp: Date.now() };
+}
+
+function assistantMsg(text: string) {
+ return {
+ role: "assistant" as const,
+ content: [{ type: "text" as const, text }],
+ api: "openai-completions",
+ provider: "openai",
+ model: "test",
+ usage: {
+ input: 1,
+ output: 1,
+ cacheRead: 0,
+ cacheWrite: 0,
+ totalTokens: 2,
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
+ },
+ stopReason: "stop" as const,
+ timestamp: Date.now(),
+ };
+}
+
+function readLines(file: string): string[] {
+ return readFileSync(file, "utf8").trim().split("\n");
+}
+
+describe("SessionManager append hot path", () => {
+ it("suppresses pre-assistant appends and writes the full history on the first assistant message", () => {
+ const dir = createTempDir();
+ const mgr = SessionManager.create(dir, join(dir, "sessions"));
+
+ mgr.appendMessage(userMsg("one"));
+ mgr.appendCustomEntry("thread_goal_state", { active: true });
+
+ const file = mgr.getSessionFile()!;
+ expect(existsSync(file)).toBe(false);
+
+ mgr.appendMessage(assistantMsg("hi"));
+ expect(existsSync(file)).toBe(true);
+
+ const lines = readLines(file);
+ expect(lines).toHaveLength(4); // header + user + custom + assistant
+ expect(JSON.parse(lines[0]!).type).toBe("session");
+ expect(JSON.parse(lines[1]!).message.role).toBe("user");
+ expect(JSON.parse(lines[2]!).customType).toBe("thread_goal_state");
+ expect(JSON.parse(lines[3]!).message.role).toBe("assistant");
+ });
+
+ it("persists session_state before any assistant message while suppressing message appends", () => {
+ const dir = createTempDir();
+ const mgr = SessionManager.create(dir, join(dir, "sessions"));
+
+ mgr.appendMessage(userMsg("one"));
+ mgr.appendSessionState({ status: "archived" });
+ const file = mgr.getSessionFile()!;
+ expect(existsSync(file)).toBe(true);
+ expect(readLines(file)).toHaveLength(3); // header + user + session_state
+
+ mgr.appendMessage(userMsg("two"));
+ expect(readLines(file)).toHaveLength(3); // still suppressed
+
+ mgr.appendMessage(assistantMsg("hi"));
+ const lines = readLines(file);
+ expect(lines).toHaveLength(5); // full rewrite, in memory order
+ expect(JSON.parse(lines[3]!).message.role).toBe("user");
+ expect(JSON.parse(lines[4]!).message.role).toBe("assistant");
+ });
+
+ it("recomputes the guard flag when reopening an existing session file", () => {
+ const dir = createTempDir();
+ const mgr = SessionManager.create(dir, join(dir, "sessions"));
+ mgr.appendMessage(assistantMsg("hi"));
+ const file = mgr.getSessionFile()!;
+ expect(readLines(file)).toHaveLength(2);
+
+ const reopened = SessionManager.open(file);
+ reopened.appendMessage(userMsg("after reopen"));
+
+ // The reopened session must append (guard armed from the loaded
+ // entries), not suppress: the file grows by exactly one line.
+ const lines = readLines(file);
+ expect(lines).toHaveLength(3);
+ expect(JSON.parse(lines[0]!).type).toBe("session");
+ expect(JSON.parse(lines[2]!).message.role).toBe("user");
+ });
+
+ it("re-arms the guard when branching to a path without an assistant message", () => {
+ const dir = createTempDir();
+ const mgr = SessionManager.create(dir, join(dir, "sessions"));
+ const userId = mgr.appendMessage(userMsg("one"));
+ mgr.appendMessage(assistantMsg("hi"));
+ mgr.appendMessage(userMsg("three"));
+
+ mgr.createBranchedSession(userId);
+ const branchedFile = mgr.getSessionFile()!;
+ expect(existsSync(branchedFile)).toBe(false); // no assistant on the branch path
+
+ mgr.appendMessage(userMsg("post-branch"));
+ expect(existsSync(branchedFile)).toBe(false); // guard re-armed: suppressed
+
+ mgr.appendMessage(assistantMsg("first reply"));
+ const lines = readLines(branchedFile);
+ expect(lines).toHaveLength(4); // header + user + suppressed user + assistant
+ expect(JSON.parse(lines[1]!).message.role).toBe("user");
+ expect(JSON.parse(lines[3]!).message.role).toBe("assistant");
+ });
+
+ it("keeps appending after a rolled-back custom append when an assistant message exists", () => {
+ const dir = createTempDir();
+ const mgr = SessionManager.create(dir, join(dir, "sessions"));
+ mgr.appendMessage(assistantMsg("hi"));
+ const file = mgr.getSessionFile()!;
+ expect(readLines(file)).toHaveLength(2);
+
+ const internals = mgr as unknown as { _persist(entry: unknown): void };
+ const originalPersist = internals._persist.bind(mgr);
+ internals._persist = () => {
+ throw new Error("append failed");
+ };
+ expect(() => mgr.appendCustomMessageEntryWithRollback("test.outcome", "details", false)).toThrow("append failed");
+ internals._persist = originalPersist;
+
+ // The rollback popped the failed custom entry and repaired the file;
+ // the cached guard flag must still hold, so this message persists.
+ mgr.appendMessage(userMsg("after rollback"));
+ const lines = readLines(file);
+ expect(lines).toHaveLength(3);
+ expect(JSON.parse(lines[2]!).message.role).toBe("user");
+ });
+
+ it("forks a session through a single write descriptor", () => {
+ const dir = createTempDir();
+ const sourcePath = join(dir, "source.jsonl");
+ writeFileSync(
+ sourcePath,
+ `${[
+ JSON.stringify({ type: "session", version: 3, id: "src", timestamp: "t", cwd: dir }),
+ JSON.stringify({
+ type: "message",
+ id: "m1",
+ parentId: null,
+ timestamp: "t",
+ message: { role: "user", content: "hi", timestamp: 1 },
+ }),
+ JSON.stringify({
+ type: "git_state",
+ id: "g1",
+ parentId: "m1",
+ timestamp: "t",
+ git: { commit: "sourcesha", branch: "main" },
+ }),
+ JSON.stringify({
+ type: "message",
+ id: "m2",
+ parentId: "g1",
+ timestamp: "t",
+ message: { role: "assistant", content: [{ type: "text", text: "hello" }], timestamp: 2 },
+ }),
+ ].join("\n")}\n`,
+ );
+
+ fsMocks.appendFileSync.mockClear();
+ const forked = SessionManager.forkFrom(sourcePath, dir, dir);
+ expect(fsMocks.appendFileSync).not.toHaveBeenCalled();
+
+ const entries = forked.getEntries();
+ expect(entries.filter((e) => e.type === "git_state")).toHaveLength(0);
+ expect(entries.find((e) => e.id === "m2")?.parentId).toBe("m1");
+ expect(entries).toHaveLength(2);
+ expect(loadEntriesFromFile(forked.getSessionFile()!).find((e) => e.type === "git_state")).toBeUndefined();
+ });
+
+ it("completes the fork when writeSync returns short counts", () => {
+ const dir = createTempDir();
+ const sourcePath = join(dir, "source.jsonl");
+ writeFileSync(
+ sourcePath,
+ `${[
+ JSON.stringify({ type: "session", version: 3, id: "src", timestamp: "t", cwd: dir }),
+ JSON.stringify({
+ type: "message",
+ id: "m1",
+ parentId: null,
+ timestamp: "t",
+ message: { role: "user", content: "hi", timestamp: 1 },
+ }),
+ JSON.stringify({
+ type: "message",
+ id: "m2",
+ parentId: "m1",
+ timestamp: "t",
+ message: { role: "assistant", content: [{ type: "text", text: "hello" }], timestamp: 2 },
+ }),
+ ].join("\n")}\n`,
+ );
+
+ // Inject a starving descriptor: at most 3 bytes land per buffer writeSync
+ // call (one byte for the string form). The fork must loop until every
+ // JSONL line is whole on disk instead of leaving a torn file that the
+ // next reopen would treat as corrupt.
+ let shortCounts = 0;
+ const shortWrite = ((fd: number, data: Buffer | string, offset?: number, length?: number) => {
+ if (typeof data === "string") {
+ if (data.length > 1) shortCounts++;
+ return fsMocks.actualWriteSync!(fd, data.slice(0, 1) as never);
+ }
+ const requested = length ?? data.byteLength - (offset ?? 0);
+ const landed = Math.min(requested, 3);
+ if (landed < requested) shortCounts++;
+ return fsMocks.actualWriteSync!(fd, data, offset, landed);
+ }) as unknown as WriteSync;
+ fsMocks.writeSync.mockImplementation(shortWrite);
+ try {
+ const forked = SessionManager.forkFrom(sourcePath, dir, dir);
+ const file = forked.getSessionFile()!;
+ expect(shortCounts).toBeGreaterThan(0); // the mock really forced partial writes
+
+ const lines = readLines(file);
+ expect(lines).toHaveLength(3); // header + both messages, nothing torn
+ expect(JSON.parse(lines[0]!).type).toBe("session");
+ expect(JSON.parse(lines[1]!).message.role).toBe("user");
+ expect(JSON.parse(lines[2]!).message.role).toBe("assistant");
+ // A fresh reopen must load the completed fork intact (not repair it).
+ const reopened = SessionManager.open(file);
+ expect(reopened.getEntries().find((e) => e.id === "m2")?.parentId).toBe("m1");
+ } finally {
+ fsMocks.writeSync.mockImplementation(fsMocks.actualWriteSync!);
+ }
+ });
+
+ it("keeps a forked pre-assistant session suppressed until its first assistant message", () => {
+ const dir = createTempDir();
+ const sourcePath = join(dir, "source.jsonl");
+ writeFileSync(
+ sourcePath,
+ `${[
+ JSON.stringify({ type: "session", version: 3, id: "src", timestamp: "t", cwd: dir }),
+ JSON.stringify({
+ type: "message",
+ id: "m1",
+ parentId: null,
+ timestamp: "t",
+ message: { role: "user", content: "hi", timestamp: 1 },
+ }),
+ JSON.stringify({
+ type: "message",
+ id: "m2",
+ parentId: "m1",
+ timestamp: "t",
+ message: { role: "user", content: "more", timestamp: 2 },
+ }),
+ ].join("\n")}\n`,
+ );
+
+ const forked = SessionManager.forkFrom(sourcePath, dir, dir);
+ const file = forked.getSessionFile()!;
+ expect(readLines(file)).toHaveLength(3);
+
+ forked.appendMessage(userMsg("post-fork"));
+ expect(readLines(file)).toHaveLength(3); // guard armed from the forked entries
+
+ forked.appendMessage(assistantMsg("hi"));
+ const lines = readLines(file);
+ expect(lines).toHaveLength(5);
+ expect(JSON.parse(lines[4]!).message.role).toBe("assistant");
+ });
+});