Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Keep saved checkpoints and transcripts in one lifecycle

justrach5400ae44f532
diff --git a/apps/native/app/api/sessions/route.ts b/apps/native/app/api/sessions/route.ts
index 1fbfeb84..5ee4098d 100644
--- a/apps/native/app/api/sessions/route.ts
+++ b/apps/native/app/api/sessions/route.ts
@@ -1,13 +1,12 @@
import { withSessionWritersStopped } from "@/lib/session-writers";
-import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync } from "node:fs";
-import path from "node:path";
+import { readFileSync, realpathSync, statSync } from "node:fs";
+import { archiveSavedSession, deleteSavedSession } from "@/lib/session-files";
import { NextRequest } from "next/server";
import { resolveRoot } from "@/lib/server-root";
import { transcriptFromMessages } from "@/lib/sessions";
import {
MAX_FULL_BYTES,
NAME_RE,
- SESSION_EXT,
clampLimit,
findSessionFile,
homeDir,
@@ -27,7 +26,6 @@ export const dynamic = "force-dynamic";
//
// Archived chats leave the list but stay on disk, in an `archived/` directory
// beside graff's own sessions, so a chat can be put away without losing it.
-const ARCHIVE_SUBDIR = "archived";
function str(v: unknown): string | null {
return typeof v === "string" && v.length > 0 ? v : null;
@@ -120,15 +118,10 @@ export async function DELETE(req: NextRequest) {
try {
return await withSessionWritersStopped(found.file, () => {
if (!archive) {
- unlinkSync(found.file);
+ deleteSavedSession(found.file);
return Response.json({ ok: true, name, archived: false });
}
- const target = path.join(path.dirname(found.file), ARCHIVE_SUBDIR);
- mkdirSync(target, { recursive: true });
- let dest = path.join(target, `${name}${SESSION_EXT}`);
- // Never overwrite an earlier archive of the same name.
- if (existsSync(dest)) dest = path.join(target, `${name}.${Date.now()}${SESSION_EXT}`);
- renameSync(found.file, dest);
+ archiveSavedSession(found.file);
return Response.json({ ok: true, name, archived: true });
});
} catch (err) {
diff --git a/apps/native/electron/attachment-lifetime-frontend.cjs b/apps/native/electron/attachment-lifetime-frontend.cjs
index ff4afd99..f0e79d58 100644
--- a/apps/native/electron/attachment-lifetime-frontend.cjs
+++ b/apps/native/electron/attachment-lifetime-frontend.cjs
@@ -56,16 +56,30 @@ async function runAttachments({win,origin,temp,output,requests,workspace,send,cl
const savedName=fs.readdirSync(savedDirectory).find(name=>name.endsWith('.session.json') && fs.readFileSync(path.join(savedDirectory,name),'utf8').includes(path.basename(aged)));
assert.ok(savedName,'Find the actual saved image conversation before deleting it');
const savedFile=path.join(savedDirectory,savedName);
+ const transcriptFile=savedFile.replace(/\.session\.json$/,'.transcript.jsonl');
+ assert.ok(fs.existsSync(transcriptFile),'The real harness must have written its companion transcript');
+ const archiveName='attachment-archive-check';
+ fs.copyFileSync(savedFile,path.join(savedDirectory,archiveName+'.session.json'));
+ fs.copyFileSync(transcriptFile,path.join(savedDirectory,archiveName+'.transcript.jsonl'));
+ const archiveResponse=await fetch(origin+'/api/sessions?'+new URLSearchParams({root:workspace,name:archiveName}),{method:'DELETE'});
+ assert.equal(archiveResponse.status,200,'Archive the copied real checkpoint through the production route');
+ assert.equal(fs.existsSync(path.join(savedDirectory,archiveName+'.transcript.jsonl')),false);
+ const archivedTranscript=path.join(savedDirectory,'archived',archiveName+'.transcript.jsonl');
+ assert.ok(fs.readFileSync(archivedTranscript,'utf8').includes(path.basename(aged)),'Archived replay must retain its image reference');
+ assert.ok(fs.existsSync(path.join(savedDirectory,'archived',archiveName+'.session.json')));
await until(()=>js(`!!document.querySelector('#sidebar-chat-list button[data-row].bg-hover-2')`),'selected saved sidebar row');
await js(`document.querySelector('#sidebar-chat-list button[data-row].bg-hover-2').parentElement.querySelector('button[aria-label^="Actions for "]').setAttribute('data-audit-delete-menu','true')`);
await click('[data-audit-delete-menu="true"]');
await until(()=>js(`!!document.querySelector('button[aria-label^="Delete "]')`),'saved conversation delete action');
await click('button[aria-label^="Delete "]');
await until(()=>!fs.existsSync(savedFile),'session removed after its writer exits');
+ assert.equal(fs.existsSync(transcriptFile),false,'Deleting a saved chat must also remove its full transcript');
await new Promise(resolve=>setTimeout(resolve,250));
assert.equal(fs.existsSync(savedFile),false,'An exiting chat worker must not recreate its deleted session');
fs.writeFileSync(path.join(output,'attachment-session-deleted.png'),(await wc.capturePage()).toPNG());
- report.passed.push('real sidebar delete retires the saved conversation writer before removing its session file');
+ assert.ok(fs.existsSync(archivedTranscript),'Deleting the original chat must preserve its independent archive');
+ assert.ok(fs.existsSync(aged),'An independent archived replay still needs the original image pixels');
+ report.passed.push('real sidebar delete retires its writer and removes checkpoint plus transcript; production archive preserves both replay files');
report.passed.push('synthetic clipboard event through real GUI paste/upload/ACP: aged draft survives, removed and closed drafts release files, sent PNG reaches model and stays available for replay');
fs.writeFileSync(path.join(output,'attachment-requests.json'),JSON.stringify(calls,null,2));
}
diff --git a/apps/native/lib/session-files.test.ts b/apps/native/lib/session-files.test.ts
new file mode 100644
index 00000000..a81a639d
--- /dev/null
+++ b/apps/native/lib/session-files.test.ts
@@ -0,0 +1,93 @@
+import { test, expect } from "bun:test";
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { archiveSavedSession, deleteSavedSession } from "./session-files";
+
+function fixture(transcript = true) {
+ const root = mkdtempSync(path.join(os.tmpdir(), "session-files-"));
+ const file = path.join(root, "saved.session.json"), companion = path.join(root, "saved.transcript.jsonl");
+ writeFileSync(file, '{"messages":[]}');
+ if (transcript) writeFileSync(companion, '{"content":"older attachment reference"}\n');
+ return { root, file, companion, dispose: () => rmSync(root, { recursive: true, force: true }) };
+}
+
+test("delete removes checkpoint and full transcript without deleting neighboring files", () => {
+ const f = fixture();
+ try {
+ const other = path.join(f.root, "saved-other.transcript.jsonl");
+ writeFileSync(other, "another conversation");
+ deleteSavedSession(f.file);
+ expect(existsSync(f.file)).toBe(false);
+ expect(existsSync(f.companion)).toBe(false);
+ expect(readFileSync(other, "utf8")).toBe("another conversation");
+ } finally { f.dispose(); }
+});
+
+test("archive keeps checkpoint and full transcript together under the same name", () => {
+ const f = fixture();
+ try {
+ const archived = archiveSavedSession(f.file);
+ expect(readFileSync(archived, "utf8")).toBe('{"messages":[]}');
+ expect(readFileSync(archived.replace(/\.session\.json$/, ".transcript.jsonl"), "utf8")).toContain("older attachment reference");
+ expect(existsSync(f.file)).toBe(false);
+ expect(existsSync(f.companion)).toBe(false);
+ } finally { f.dispose(); }
+});
+
+test("an older companion-only archive cannot be overwritten or paired with a different checkpoint", () => {
+ const f = fixture();
+ try {
+ const directory = path.join(f.root, "archived"); mkdirSync(directory);
+ const earlier = path.join(directory, "saved.transcript.jsonl"); writeFileSync(earlier, "earlier archive");
+ const archived = archiveSavedSession(f.file);
+ expect(path.basename(archived)).not.toBe("saved.session.json");
+ expect(readFileSync(earlier, "utf8")).toBe("earlier archive");
+ expect(readFileSync(archived.replace(/\.session\.json$/, ".transcript.jsonl"), "utf8")).toContain("older attachment reference");
+ expect(readdirSync(directory)).toHaveLength(3);
+ } finally { f.dispose(); }
+});
+
+test("older checkpoints without a transcript can still be archived and deleted", () => {
+ const f = fixture(false);
+ try {
+ const archived = archiveSavedSession(f.file);
+ deleteSavedSession(archived);
+ expect(existsSync(archived)).toBe(false);
+ } finally { f.dispose(); }
+});
+
+test("an invalid companion leaves both the indexed session and unrelated content untouched", () => {
+ const f = fixture(false);
+ try {
+ mkdirSync(f.companion); writeFileSync(path.join(f.companion, "keep"), "keep");
+ expect(() => deleteSavedSession(f.file)).toThrow("not a regular file");
+ expect(() => archiveSavedSession(f.file)).toThrow("not a regular file");
+ expect(existsSync(f.file)).toBe(true);
+ expect(readFileSync(path.join(f.companion, "keep"), "utf8")).toBe("keep");
+ } finally { f.dispose(); }
+});
+
+test("a symlinked companion never grants authority to remove a user original", () => {
+ const f = fixture(false);
+ try {
+ const original = path.join(f.root, "original.txt"); writeFileSync(original, "user original");
+ symlinkSync(original, f.companion);
+ expect(() => deleteSavedSession(f.file)).toThrow("not a regular file");
+ expect(() => archiveSavedSession(f.file)).toThrow("not a regular file");
+ expect(existsSync(f.file)).toBe(true);
+ expect(readFileSync(original, "utf8")).toBe("user original");
+ } finally { f.dispose(); }
+});
+
+
+test.skipIf(process.platform === "win32" || process.getuid?.() === 0)("an unwritable archive preserves the checkpoint and its transcript", () => {
+ const f = fixture(), archive = path.join(f.root, "archived");
+ mkdirSync(archive); chmodSync(archive, 0o500);
+ try {
+ expect(() => archiveSavedSession(f.file)).toThrow();
+ expect(readFileSync(f.file, "utf8")).toBe('{"messages":[]}');
+ expect(readFileSync(f.companion, "utf8")).toContain("older attachment reference");
+ expect(readdirSync(archive)).toHaveLength(0);
+ } finally { chmodSync(archive, 0o700); f.dispose(); }
+});
diff --git a/apps/native/lib/session-files.ts b/apps/native/lib/session-files.ts
new file mode 100644
index 00000000..e0f02986
--- /dev/null
+++ b/apps/native/lib/session-files.ts
@@ -0,0 +1,61 @@
+import { randomUUID } from "node:crypto";
+import { constants, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, unlinkSync } from "node:fs";
+import path from "node:path";
+
+const SESSION_EXT = ".session.json", TRANSCRIPT_EXT = ".transcript.jsonl";
+
+/** The harness appends the full transcript beside the resumable checkpoint.
+ * Both are saved conversation data, even when compaction removes older turns
+ * from the checkpoint. Call only after the session's writers have exited. */
+export function savedSessionFiles(file: string): string[] {
+ if (!file.endsWith(SESSION_EXT)) throw new Error("Invalid saved session path");
+ const files = [file];
+ const transcript = file.slice(0, -SESSION_EXT.length) + TRANSCRIPT_EXT;
+ try {
+ const stat = lstatSync(transcript);
+ if (!stat.isFile()) throw new Error("Saved transcript is not a regular file");
+ files.push(transcript);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ }
+ if (!lstatSync(file).isFile()) throw new Error("Saved session is not a regular file");
+ return files;
+}
+
+export function deleteSavedSession(file: string): void {
+ // Keep the indexed checkpoint until companion removal succeeds. A failed
+ // cleanup remains discoverable and retryable through the same DELETE route.
+ for (const source of savedSessionFiles(file).reverse()) unlinkSync(source);
+}
+
+export function archiveSavedSession(file: string): string {
+ const sources = savedSessionFiles(file);
+ const directory = path.join(path.dirname(file), "archived");
+ mkdirSync(directory, { recursive: true });
+ const stem = path.basename(file).slice(0, -SESSION_EXT.length);
+ const extensions = sources.map(source => source.endsWith(SESSION_EXT) ? SESSION_EXT : TRANSCRIPT_EXT);
+ let targetStem = stem;
+ if (extensions.some(ext => existsSync(path.join(directory, targetStem + ext)))) targetStem += `.${randomUUID()}`;
+ const targets = extensions.map(ext => path.join(directory, targetStem + ext));
+ const created: string[] = [];
+ try {
+ // Exclusive links cannot overwrite an earlier archive, even if another
+ // process creates a destination after the collision check. Link every
+ // companion before retiring either source, so a failure preserves the pair.
+ for (let i = 0; i < sources.length; i++) {
+ try { linkSync(sources[i], targets[i]); }
+ catch (error) {
+ if (!["EXDEV", "EPERM", "ENOTSUP", "EOPNOTSUPP"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
+ // Removable and network filesystems may not support hard links.
+ // Exclusive copy preserves the same no-overwrite archive contract.
+ copyFileSync(sources[i], targets[i], constants.COPYFILE_EXCL);
+ }
+ created.push(targets[i]);
+ }
+ } catch (error) {
+ for (const target of created) unlinkSync(target);
+ throw error;
+ }
+ for (const source of [...sources].reverse()) unlinkSync(source);
+ return targets[0];
+}
diff --git a/docs/adr/0117-clipboard-files-follow-consumer-ownership.md b/docs/adr/0117-clipboard-files-follow-consumer-ownership.md
index 10b8e8a1..7396acbe 100644
--- a/docs/adr/0117-clipboard-files-follow-consumer-ownership.md
+++ b/docs/adr/0117-clipboard-files-follow-consumer-ownership.md
@@ -37,6 +37,10 @@ including writers already closing after tab disposal. EOF gives the worker its
final save; a mutation gate prevents replacement writers until the file operation
finishes. Otherwise exit autosave can recreate a deleted reference and invalidate
the evidence used to decide that an attachment has no remaining consumers.
+The resumable checkpoint and its full companion transcript are one saved-chat
+lifetime: deleting removes both, while archiving moves both under a shared
+archive name without overwriting an older pair. An independent archive remains
+a consumer of its image references.
## Consequences