graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Record image session scopes and inspect durable references
justrachd295d0a872ca
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsindex a3d7f925..613873a8 100644--- a/apps/native/app/api/acp/route.ts+++ b/apps/native/app/api/acp/route.ts@@ -324,7 +324,7 @@ export async function POST(req: NextRequest) {if (slot.streaming) return Response.json({ error: "A turn is already active" }, { status: 409 });const promptParams = await prepareGuiPrompt(body.params);if (slot.streaming) return Response.json({ error: "A turn is already active" }, { status: 409 });- attachmentStore().retainPrompt(promptParams);+ attachmentStore().retainPrompt(promptParams, path.dirname(sessionFile(slot.cwd, slot.resume ?? slot.sessionId!)));slot.streaming = true;const { stream, pending } = createPromptStream(slot.transport,{ ...promptParams, sessionId: slot.sessionId }, () => {diff --git a/apps/native/electron/attachment-lifetime-frontend.cjs b/apps/native/electron/attachment-lifetime-frontend.cjsindex 848fa987..239c6cf2 100644--- a/apps/native/electron/attachment-lifetime-frontend.cjs+++ b/apps/native/electron/attachment-lifetime-frontend.cjs@@ -45,6 +45,9 @@ async function runAttachments({win,origin,temp,output,requests,workspace,send,classert.ok(JSON.stringify(calls).includes(png),'Actual model requests must contain the pasted PNG bytes');const record=JSON.parse(fs.readFileSync(path.join(directory,'.ownership',path.basename(aged)+'.json'),'utf8'));assert.equal(record.retained,true,'ACP acceptance must retain replay pixels');+ const referenceDir=path.join(directory,'.ownership','references',path.basename(aged));+ const scopes=fs.readdirSync(referenceDir).map(name=>JSON.parse(fs.readFileSync(path.join(referenceDir,name),'utf8')).directory);+ assert.deepEqual(scopes,[path.join(fs.realpathSync(workspace),'.graff','sessions')],'ACP must enroll the actual saved-session scope');await fetch(origin+'/api/attach',{method:'DELETE',headers:{'content-type':'application/json'},body:JSON.stringify({paths:[aged]})});assert.ok(fs.existsSync(aged),'Discard cannot delete pixels retained by an accepted message');assert.equal((await fetch(origin+'/api/attach?name='+encodeURIComponent(path.basename(aged)))).status,200);diff --git a/apps/native/lib/attachment-references.test.ts b/apps/native/lib/attachment-references.test.tsnew file mode 100644index 00000000..4d106fa9--- /dev/null+++ b/apps/native/lib/attachment-references.test.ts@@ -0,0 +1,68 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync, mkdirSync, writeFileSync, unlinkSync, rmSync, symlinkSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { attachmentReferences } from "./attachment-references";++function fixture(run: (root: string, image: string) => void) {+ const root = mkdtempSync(path.join(os.tmpdir(), "graff-image-references-"));+ try { run(root, path.join(os.tmpdir(), "owned-é.png")); }+ finally { rmSync(root, {recursive:true, force:true}); }+}++test("an independent archive retains its reference after original session removal", () => fixture((root,image) => {+ const current = path.join(root,"chat.session.json"), archive = path.join(root,"archived");+ mkdirSync(archive);+ writeFileSync(current, JSON.stringify({messages:[{text:`@[${image}]`}]}));+ const rotated = path.join(archive,"copy.transcript.1.jsonl");+ writeFileSync(rotated, JSON.stringify({type:"message",content:[{text:`@[${image}]`}]}).replace('é','\\u00e9')+'\n');+ assert.equal(attachmentReferences([root],image),"referenced");+ unlinkSync(current);+ assert.equal(attachmentReferences([root],image),"referenced");+ unlinkSync(rotated);+ assert.equal(attachmentReferences([root],image),"absent");+}));++test("all supplied workspaces participate in the reference decision", () => fixture((root,image) => {+ const other = path.join(root,"other");mkdirSync(other);+ writeFileSync(path.join(other,"chat.session.json"),JSON.stringify({messages:[image]}));+ const empty = path.join(root,"empty");mkdirSync(empty);+ assert.equal(attachmentReferences([empty,other],image),"referenced");+ assert.equal(attachmentReferences([empty],image),"absent");+ assert.equal(attachmentReferences([],image),"unknown");+}));++test("malformed, unrecognized and missing session data cannot prove absence", () => fixture((root,image) => {+ const file = path.join(root,"chat.session.json");writeFileSync(file,'{');+ assert.equal(attachmentReferences([root],image),"unknown");unlinkSync(file);+ writeFileSync(path.join(root,"unrecognized.txt"),'unknown replay format');+ assert.equal(attachmentReferences([root],image),"unknown");+ assert.equal(attachmentReferences([path.join(root,"missing")],image),"unknown");+}));++test("entry and byte limits report uncertainty rather than partial absence", () => fixture((root,image) => {+ writeFileSync(path.join(root,"chat.session.json"),'{}');+ assert.equal(attachmentReferences([root],image,{entries:0,bytes:100}),"unknown");+ assert.equal(attachmentReferences([root],image,{entries:10,bytes:1}),"unknown");+}));++test("symlinked replay directories are not followed or treated as empty", () => fixture((root,image) => {+ symlinkSync(root,path.join(root,"archived"),'dir');+ assert.equal(attachmentReferences([root],image),"unknown");+}));++test("escaped references in object keys remain consumers", () => fixture((root,image) => {+ writeFileSync(path.join(root,"chat.session.json"),JSON.stringify({messages:[],images:{[image]:{kind:'image'}}}).replace('é','\\u00e9'));+ assert.equal(attachmentReferences([root],image),"referenced");+}));++test("invalid scan limits cannot silently disable the bounds", () => fixture((root,image) => {+ assert.equal(attachmentReferences([root],image,{entries:Infinity,bytes:100}),"unknown");+ assert.equal(attachmentReferences([root],image,{entries:10,bytes:NaN}),"unknown");+}));++test("syntactically valid but invalid checkpoint data is unknown", () => fixture((root,image) => {+ writeFileSync(path.join(root,"chat.session.json"),'{}');+ assert.equal(attachmentReferences([root],image),"unknown");+}));diff --git a/apps/native/lib/attachment-references.ts b/apps/native/lib/attachment-references.tsnew file mode 100644index 00000000..40d8e48e--- /dev/null+++ b/apps/native/lib/attachment-references.ts@@ -0,0 +1,71 @@+import { closeSync, fstatSync, lstatSync, openSync, opendirSync, readSync } from "node:fs";+import path from "node:path";++export type ReferenceState = "referenced" | "absent" | "unknown";+export type ReferenceLimits = { entries: number; bytes: number };+const defaults: ReferenceLimits = { entries: 256, bytes: 32 * 1024 * 1024 };+const checkpoint = /\.session\.json$/;+const transcript = /\.transcript(?:\.1)?\.jsonl$/;++function mentions(value: unknown, name: string): boolean {+ if (typeof value === "string") return value.includes(name);+ if (Array.isArray(value)) return value.some(item => mentions(item, name));+ if (value && typeof value === "object") return Object.entries(value).some(([key,item]) => key.includes(name) || mentions(item, name));+ return false;+}++/** Inspect every supplied managed session directory, including archives.+ * This proves absence only within those scopes. Callers must separately prove+ * scope completeness and exclude live writers before using it for cleanup. */+export function attachmentReferences(directories: readonly string[], target: string, limits: ReferenceLimits = defaults): ReferenceState {+ if (!directories.length || !path.isAbsolute(target) ||+ !Number.isSafeInteger(limits.entries) || limits.entries < 0 ||+ !Number.isSafeInteger(limits.bytes) || limits.bytes < 0) return "unknown";+ const name = path.basename(target);+ if (!name || name === "." || name === "..") return "unknown";+ let remainingEntries = limits.entries, remainingBytes = limits.bytes, uncertain = false;+ const pending = [...new Set(directories.map(directory => path.resolve(directory)))];+ while (pending.length) {+ const directory = pending.pop()!;+ try {+ if (!lstatSync(directory).isDirectory()) { uncertain = true; continue; }+ const entries = opendirSync(directory);+ try {+ for (;;) {+ const entry = entries.readSync();+ if (!entry) break;+ if (--remainingEntries < 0) return "unknown";+ const file = path.join(directory, entry.name), stat = lstatSync(file);+ if (stat.isDirectory()) { pending.push(file); continue; }+ if (!stat.isFile()) { uncertain = true; continue; }+ const isCheckpoint = checkpoint.test(entry.name), isTranscript = transcript.test(entry.name);+ if (!isCheckpoint && !isTranscript) { uncertain = true; continue; }+ if (stat.size > remainingBytes) return "unknown";+ remainingBytes -= stat.size;+ const descriptor = openSync(file, "r");+ let bytes: Buffer;+ try {+ const opened = fstatSync(descriptor);+ if (!opened.isFile() || opened.dev !== stat.dev || opened.ino !== stat.ino || opened.size !== stat.size) { uncertain = true; continue; }+ bytes = Buffer.alloc(stat.size);+ let offset = 0;+ while (offset < bytes.length) {+ const count = readSync(descriptor, bytes, offset, bytes.length - offset, offset);+ if (!count) break;+ offset += count;+ }+ const after = fstatSync(descriptor);+ if (offset !== bytes.length || after.size !== stat.size || after.mtimeMs !== stat.mtimeMs) { uncertain = true; continue; }+ } finally { closeSync(descriptor); }+ const text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);+ const records = isCheckpoint ? [JSON.parse(text)] : text.split("\n").filter(line => line.trim()).map(line => JSON.parse(line));+ const shaped = records.every(record => record && typeof record === "object" && !Array.isArray(record) &&+ (isCheckpoint ? Array.isArray(record.messages) : typeof record.type === "string" || typeof record.role === "string"));+ if (!shaped) { uncertain = true; continue; }+ if (records.some(record => mentions(record, name))) return "referenced";+ }+ } finally { entries.closeSync(); }+ } catch { uncertain = true; }+ }+ return uncertain ? "unknown" : "absent";+}diff --git a/apps/native/lib/attachment-store.test.ts b/apps/native/lib/attachment-store.test.tsindex 86466224..d28c8a47 100644--- a/apps/native/lib/attachment-store.test.ts+++ b/apps/native/lib/attachment-store.test.ts@@ -1,5 +1,5 @@import { afterEach, expect, test } from "bun:test";-import { mkdtempSync, rmSync, existsSync, utimesSync, writeFileSync, renameSync, chmodSync, readdirSync } from "node:fs";+import { mkdtempSync, rmSync, existsSync, utimesSync, writeFileSync, renameSync, chmodSync, readdirSync, mkdirSync } from "node:fs";import os from "node:os";import path from "node:path";import { AttachmentStore } from "./attachment-store";@@ -69,3 +69,32 @@ test("an in-place edit is preserved even when the inode and byte count match", (expect(store.sweep()).toBe(0);expect(existsSync(edited)).toBe(true);});++test("enrolled workspace references survive restart and independent archive deletion", () => {+ const {store,root} = fixture();+ const first = path.join(root,"first"), second = path.join(root,"second");+ mkdirSync(first);mkdirSync(second);+ const sent = store.create("shared.png",new Uint8Array([1]));+ const prompt = {prompt:[{type:"text",text:`Inspect @[${sent}]`}]};+ store.retainPrompt(prompt,first);store.retainPrompt(prompt,second);+ const a=path.join(first,"chat.session.json"), b=path.join(second,"chat.session.json");+ writeFileSync(a,JSON.stringify({messages:[sent]}));writeFileSync(b,JSON.stringify({messages:[sent]}));+ const restarted=new AttachmentStore(root,67890,()=>false);+ try {+ expect(restarted.references(sent)).toBe("referenced");rmSync(a);+ const archive=path.join(second,"archived");mkdirSync(archive);+ renameSync(b,path.join(archive,"chat.session.json"));+ expect(restarted.references(sent)).toBe("referenced");+ rmSync(path.join(archive,"chat.session.json"));+ expect(restarted.references(sent)).toBe("absent");+ expect(existsSync(sent)).toBe(true); // Absence evidence alone is not deletion authority.+ } finally { restarted.close(); }+});++test("an unscoped submission cannot be retroactively treated as complete scope knowledge", () => {+ const {store,root}=fixture();const scope=path.join(root,"sessions");mkdirSync(scope);+ const sent=store.create("unknown.png",new Uint8Array([1]));+ const prompt={prompt:[{type:"text",text:`@[${sent}]`}]};+ store.retainPrompt(prompt);store.retainPrompt(prompt,scope);+ expect(store.references(sent)).toBe("unknown");+});diff --git a/apps/native/lib/attachment-store.ts b/apps/native/lib/attachment-store.tsindex e52f8a84..ab48b8fb 100644--- a/apps/native/lib/attachment-store.ts+++ b/apps/native/lib/attachment-store.ts@@ -1,9 +1,10 @@import { createHash, randomUUID } from "node:crypto";-import { mkdirSync, openSync, closeSync, fstatSync, writeFileSync, readFileSync, renameSync, unlinkSync, lstatSync, opendirSync, type Dir } from "node:fs";+import { mkdirSync, openSync, closeSync, fstatSync, writeFileSync, readFileSync, renameSync, unlinkSync, lstatSync, opendirSync, readdirSync, type Dir } from "node:fs";import os from "node:os";+import { attachmentReferences, type ReferenceState } from "./attachment-references";import path from "node:path";-type Record = { version: 1; name: string; owner: number; retained: boolean; dev: number; ino: number; size?: number; sha256?: string };+type Record = { version: 1; name: string; owner: number; retained: boolean; dev: number; ino: number; size?: number; sha256?: string; referenceVersion?: 1 };export const attachmentDirectory = path.join(os.tmpdir(), "graff-native-attachments");function ownerAlive(pid: number): boolean {try { process.kill(pid, 0); return true; }@@ -47,7 +48,7 @@ export class AttachmentStore {const file = fstatSync(descriptor);try {writeFileSync(descriptor, bytes);- this.save({ version: 1, name, owner: this.owner, retained: false, dev: file.dev, ino: file.ino, size: bytes.byteLength, sha256: createHash("sha256").update(bytes).digest("hex") });+ this.save({ version: 1, name, owner: this.owner, retained: false, dev: file.dev, ino: file.ino, size: bytes.byteLength, sha256: createHash("sha256").update(bytes).digest("hex"), referenceVersion: 1 });} catch (error) {try {const current = lstatSync(target);@@ -58,7 +59,37 @@ export class AttachmentStore {} finally { closeSync(descriptor); }return target;}- retainPrompt(params: unknown) {+ private enroll(name: string, directory?: string) {+ const root = path.join(this.records, "references", name);+ mkdirSync(root, { recursive: true, mode: 0o700 });+ const scope = directory && path.isAbsolute(directory) ? path.resolve(directory) : null;+ const key = scope ? createHash("sha256").update(scope).digest("hex") : "unknown";+ try { writeFileSync(path.join(root, key + ".json"), JSON.stringify({ directory: scope }), { flag: "wx", mode: 0o600 }); }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }+ }+ /** Read-only evidence within enrolled scopes; not authorization to delete.+ * A future collector must also exclude every active consumer. */+ references(target: string): ReferenceState {+ if (path.dirname(target) !== this.directory) return "unknown";+ const record = this.read(path.basename(target));+ if (!record?.retained || record.referenceVersion !== 1) return "unknown";+ try {+ const root = path.join(this.records, "references", record.name);+ const names = readdirSync(root);+ if (!names.length || names.length > 64 || names.includes("unknown.json")) return "unknown";+ const scopes: string[] = [];+ for (const name of names) {+ const file = path.join(root, name), stat = lstatSync(file);+ if (!stat.isFile() || stat.size > 16 * 1024) return "unknown";+ const { directory } = JSON.parse(readFileSync(file, "utf8"));+ if (typeof directory !== "string" || !path.isAbsolute(directory) ||+ name !== createHash("sha256").update(directory).digest("hex") + ".json") return "unknown";+ scopes.push(directory);+ }+ return attachmentReferences(scopes, target);+ } catch { return "unknown"; }+ }+ retainPrompt(params: unknown, sessionDirectory?: string) {const prompt = (params as { prompt?: unknown } | undefined)?.prompt;if (!Array.isArray(prompt)) return;for (const part of prompt) {@@ -66,7 +97,10 @@ export class AttachmentStore {for (const match of part.text.matchAll(/@\[([^\]\n]+)\]/g)) {if (path.dirname(match[1]) !== this.directory) continue;const record = this.read(path.basename(match[1]));- if (record && !record.retained) this.save({ ...record, retained: true });+ if (record) {+ this.enroll(record.name, sessionDirectory);+ if (!record.retained) this.save({ ...record, retained: true });+ }}}}diff --git a/docs/adr/0117-clipboard-files-follow-consumer-ownership.md b/docs/adr/0117-clipboard-files-follow-consumer-ownership.mdindex a04d2bc0..ab114f80 100644--- a/docs/adr/0117-clipboard-files-follow-consumer-ownership.md+++ b/docs/adr/0117-clipboard-files-follow-consumer-ownership.md@@ -39,6 +39,15 @@ pending files only when their known desktop owner has exited. The desktop ownsdrafts independently of route-server restarts. Unknown owners and unrecorded orreplaced files do not grant deletion authority. Age alone never grants it.+New native submissions also enroll their canonical session directory in+immutable per-image reference records. Multiple workspaces accumulate records+without overwriting one another. An unscoped submission permanently records+uncertainty; older exports cannot acquire complete scope knowledge retroactively.+A bounded read-only scan covers checkpoints, both transcript generations and+archives, decoding JSON before checking names. Missing, malformed, symlinked,+changed or over-budget data is unknown. This evidence is scoped: it does not+by itself authorize deletion or exclude active consumers.+The legacy desktop keeps clipboard exports in a private owner directory withan operating-system file lease. Recovery takes a nonblocking exclusive leasebefore removing recorded unsent exports from a stopped owner. Its prompt