graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Track attachment worker consumers before prompt dispatch
justrach0072b5f0e1b9
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsindex 613873a8..405d5d45 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, path.dirname(sessionFile(slot.cwd, slot.resume ?? slot.sessionId!)));+ attachmentStore().retainPrompt(promptParams, path.dirname(sessionFile(slot.cwd, slot.resume ?? slot.sessionId!)), slot.child.pid);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 239c6cf2..2fb4ec94 100644--- a/apps/native/electron/attachment-lifetime-frontend.cjs+++ b/apps/native/electron/attachment-lifetime-frontend.cjs@@ -48,6 +48,12 @@ async function runAttachments({win,origin,temp,output,requests,workspace,send,clconst 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');+ const consumerDir=path.join(directory,'.ownership','consumers',path.basename(aged));+ const consumers=fs.readdirSync(consumerDir).map(name=>JSON.parse(fs.readFileSync(path.join(consumerDir,name),'utf8')).pid);+ assert.equal(consumers.length,1,'The image handoff must enroll its actual ACP worker');+ assert.ok(Number.isSafeInteger(consumers[0]) && consumers[0]>1);+ process.kill(consumers[0],0); // Completed output does not mean the worker released its history.+ fs.writeFileSync(path.join(output,'attachment-consumers.json'),JSON.stringify({worker:consumers[0],aliveAfterTurn:true},null,2));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);@@ -92,6 +98,8 @@ async function runAttachments({win,origin,temp,output,requests,workspace,send,clawait 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');+ await until(()=>{try{process.kill(consumers[0],0);return false;}catch(error){return error.code==='ESRCH';}},'image consumer process exited');+ fs.writeFileSync(path.join(output,'attachment-consumers.json'),JSON.stringify({worker:consumers[0],aliveAfterTurn:true,exitedAfterDelete:true},null,2));assert.equal(fs.existsSync(transcriptFile),false,'Deleting a saved chat must also remove its full transcript');assert.equal(fs.existsSync(rotatedFile),false,'Deleting a saved chat must remove its rotated transcript');await new Promise(resolve=>setTimeout(resolve,250));diff --git a/apps/native/lib/attachment-consumers.test.ts b/apps/native/lib/attachment-consumers.test.tsnew file mode 100644index 00000000..1f7998c5--- /dev/null+++ b/apps/native/lib/attachment-consumers.test.ts@@ -0,0 +1,59 @@+import { expect, test } from "bun:test";+import { spawn } from "node:child_process";+import { once } from "node:events";+import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";+import os from "node:os";+import path from "node:path";+import { AttachmentStore } from "./attachment-store";+import { attachmentConsumers, enrollAttachmentConsumer } from "./attachment-consumers";++test("worker consumers survive store restart and release only after both processes exit", async () => {+ const root = mkdtempSync(path.join(os.tmpdir(), "graff-live-image-consumers-"));+ const workers = [spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"]),+ spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"])];+ const exits = workers.map(child => once(child, "exit"));+ const alive = (pid: number) => {+ if (pid === 2147483647) return false; // The producer has already exited.+ try { process.kill(pid, 0); return true; }+ catch (error) { return (error as NodeJS.ErrnoException).code !== "ESRCH"; }+ };+ const original = new AttachmentStore(root, 2147483647, alive);+ const restarted = new AttachmentStore(root, 2147483647, alive);+ try {+ await Promise.all(workers.map(child => once(child, "spawn")));+ const sessions = path.join(root, "sessions"); mkdirSync(sessions);+ const image = original.create("shared.png", new Uint8Array([1]));+ const prompt = { prompt: [{ type: "text", text: `@[${image}]` }] };+ for (const child of workers) original.retainPrompt(prompt, sessions, child.pid);+ original.close();+ // No checkpoint exists yet: absence must not conceal the in-memory worker.+ expect(restarted.references(image)).toBe("absent");+ expect(restarted.consumers(image)).toBe("active");+ workers[0].kill(); await exits[0];+ expect(restarted.consumers(image)).toBe("active");+ workers[1].kill(); await exits[1];+ expect(restarted.consumers(image)).toBe("inactive");+ expect(restarted.discard(image)).toBe(false); // Cross-surface collection is not enabled yet.+ } finally {+ for (const child of workers) if (child.exitCode === null && child.signalCode === null) child.kill();+ await Promise.all(exits);+ original.close(); restarted.close(); rmSync(root, { recursive: true, force: true });+ }+});++test("unknown, malformed and unenrolled consumers never prove inactivity", () => {+ const root = mkdtempSync(path.join(os.tmpdir(), "graff-unknown-image-consumers-"));+ try {+ expect(attachmentConsumers(root, 12345, () => false)).toBe("unknown");+ enrollAttachmentConsumer(root, 54321);+ expect(attachmentConsumers(root, 12345, () => false)).toBe("inactive");+ expect(attachmentConsumers(root, 12345, pid => pid === 12345)).toBe("active");+ expect(attachmentConsumers(root, 0, () => false)).toBe("unknown");+ writeFileSync(path.join(root, "broken.json"), "{");+ expect(attachmentConsumers(root, 12345, () => false)).toBe("unknown");+ rmSync(path.join(root, "broken.json"));+ enrollAttachmentConsumer(root);+ enrollAttachmentConsumer(root, 54321);+ expect(attachmentConsumers(root, 12345, () => false)).toBe("unknown");+ } finally { rmSync(root, { recursive: true, force: true }); }+});diff --git a/apps/native/lib/attachment-consumers.ts b/apps/native/lib/attachment-consumers.tsnew file mode 100644index 00000000..a4d88051--- /dev/null+++ b/apps/native/lib/attachment-consumers.ts@@ -0,0 +1,37 @@+import { createHash } from "node:crypto";+import { lstatSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";+import path from "node:path";++export type ConsumerState = "active" | "inactive" | "unknown";+const validPid = (pid: number | undefined): pid is number => Number.isSafeInteger(pid) && pid! > 1;++/** Append before handing a path to a worker. Never erase another consumer. */+export function enrollAttachmentConsumer(root: string, pid?: number): void {+ mkdirSync(root, { recursive: true, mode: 0o700 });+ const value = validPid(pid) ? pid : null;+ const name = value === null ? "unknown" : createHash("sha256").update(String(value)).digest("hex");+ try { writeFileSync(path.join(root, name + ".json"), JSON.stringify({ pid: value }), { flag: "wx", mode: 0o600 }); }+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }+}++/** Inactivity covers enrolled processes only. It is not a collection lock or+ * proof that no other surface has acquired the path. PID reuse preserves data. */+export function attachmentConsumers(root: string, owner: number, alive: (pid: number) => boolean): ConsumerState {+ try {+ if (!validPid(owner)) return "unknown";+ if (alive(owner)) return "active";+ const names = readdirSync(root);+ if (!names.length || names.length > 256 || names.includes("unknown.json")) return "unknown";+ let unknown = false;+ for (const name of names) {+ const file = path.join(root, name), stat = lstatSync(file);+ if (!stat.isFile() || stat.size > 1024) { unknown = true; continue; }+ const { pid } = JSON.parse(readFileSync(file, "utf8"));+ if (!validPid(pid) || name !== createHash("sha256").update(String(pid)).digest("hex") + ".json") {+ unknown = true; continue;+ }+ if (alive(pid)) return "active";+ }+ return unknown ? "unknown" : "inactive";+ } catch { return "unknown"; }+}diff --git a/apps/native/lib/attachment-store.ts b/apps/native/lib/attachment-store.tsindex ab48b8fb..80f371b6 100644--- a/apps/native/lib/attachment-store.ts+++ b/apps/native/lib/attachment-store.ts@@ -2,9 +2,10 @@ import { createHash, randomUUID } from "node:crypto";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 { attachmentConsumers, enrollAttachmentConsumer, type ConsumerState } from "./attachment-consumers";import path from "node:path";-type Record = { version: 1; name: string; owner: number; retained: boolean; dev: number; ino: number; size?: number; sha256?: string; referenceVersion?: 1 };+type Record = { version: 1; name: string; owner: number; retained: boolean; dev: number; ino: number; size?: number; sha256?: string; referenceVersion?: 1; consumerVersion?: 1 };export const attachmentDirectory = path.join(os.tmpdir(), "graff-native-attachments");function ownerAlive(pid: number): boolean {try { process.kill(pid, 0); return true; }@@ -48,7 +49,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"), referenceVersion: 1 });+ 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, consumerVersion: 1 });} catch (error) {try {const current = lstatSync(target);@@ -89,7 +90,13 @@ export class AttachmentStore {return attachmentReferences(scopes, target);} catch { return "unknown"; }}- retainPrompt(params: unknown, sessionDirectory?: string) {+ consumers(target: string): ConsumerState {+ if (path.dirname(target) !== this.directory) return "unknown";+ const record = this.read(path.basename(target));+ if (!record?.retained || record.consumerVersion !== 1) return "unknown";+ return attachmentConsumers(path.join(this.records, "consumers", record.name), record.owner, this.alive);+ }+ retainPrompt(params: unknown, sessionDirectory?: string, workerPid?: number) {const prompt = (params as { prompt?: unknown } | undefined)?.prompt;if (!Array.isArray(prompt)) return;for (const part of prompt) {@@ -98,6 +105,7 @@ export class AttachmentStore {if (path.dirname(match[1]) !== this.directory) continue;const record = this.read(path.basename(match[1]));if (record) {+ enrollAttachmentConsumer(path.join(this.records, "consumers", record.name), workerPid);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 ab114f80..af5ae057 100644--- a/docs/adr/0117-clipboard-files-follow-consumer-ownership.md+++ b/docs/adr/0117-clipboard-files-follow-consumer-ownership.md@@ -48,6 +48,14 @@ archives, decoding JSON before checking names. Missing, malformed, symlinked,changed or over-budget data is unknown. This evidence is scoped: it does notby itself authorize deletion or exclude active consumers.+Native prompt handoff also appends a worker process record before dispatch.+The originating desktop and every enrolled worker protect in-memory consumers+across route-server restarts. Process termination, rather than completed output+or tab disposal, releases that evidence; unknown records and reused live process+identifiers preserve files. Older exports cannot gain complete consumer knowledge+retroactively. This process inventory still requires cross-surface enrollment+and collection serialization before it can authorize submitted-file cleanup.+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