{"draft":null,"from":2,"to":318,"files":[{"path":"src/engine/projection-scratch.ts","added":60,"removed":0,"diff":"--- /dev/null\n+++ b/src/engine/projection-scratch.ts\n@@ -0,0 +1,60 @@\n+import type { GraphStateStorage } from \"./state-source.ts\";\n+\n+let nextScope = 0;\n+\n+/** Synchronous derived-state work only. All scratch writes roll back, even on\n+ * success. The outer canonical transaction is left intact. Returned values\n+ * must be detached data, never iterators, promises or storage handles. */\n+export function withProjectionScratch<T>(\n+\tstorage: GraphStateStorage,\n+\tvalidateIdentity: () => void,\n+\toperation: (scratch: GraphStateStorage) => T,\n+): T {\n+\tif (nextScope >= Number.MAX_SAFE_INTEGER) throw new Error(\"projection scope identity exhausted\");\n+\tconst prefix = `projection-scratch:${++nextScope}:`;\n+\tconst finished = {};\n+\tlet active = true;\n+\tlet result: T;\n+\tconst collection = (name: string): string => {\n+\t\tif (!active) throw new Error(\"projection scratch scope has ended\");\n+\t\treturn prefix + name;\n+\t};\n+\tconst scratch: GraphStateStorage = {\n+\t\tread: (name, key) => storage.read(collection(name), key),\n+\t\twrite: (name, key, value) => storage.write(collection(name), key, value),\n+\t\tremove: (name, key) => storage.remove(collection(name), key),\n+\t\t*entries(name) {\n+\t\t\tfor (const entry of storage.entries(collection(name))) {\n+\t\t\t\tcollection(name);\n+\t\t\t\tyield entry;\n+\t\t\t}\n+\t\t},\n+\t\ttransaction: (body) => {\n+\t\t\tcollection(\"\");\n+\t\t\treturn storage.transaction(body);\n+\t\t},\n+\t};\n+\ttry {\n+\t\tstorage.transaction(() => {\n+\t\t\tvalidateIdentity();\n+\t\t\tconst value = operation(scratch);\n+\t\t\tif (\n+\t\t\t\tvalue &&\n+\t\t\t\t(typeof (value as { then?: unknown }).then === \"function\" ||\n+\t\t\t\t\ttypeof (value as { next?: unknown }).next === \"function\")\n+\t\t\t)\n+\t\t\t\tthrow new Error(\"projection must complete synchronously\");\n+\t\t\t// Detach successful output before rollback; rejects embedded functions,\n+\t\t\t// storage capabilities and generators instead of leaking their scope.\n+\t\t\tresult = structuredClone(value);\n+\t\t\tvalidateIdentity();\n+\t\t\tthrow finished;\n+\t\t});\n+\t} catch (error) {\n+\t\tif (error !== finished) throw error;\n+\t\treturn result!;\n+\t} finally {\n+\t\tactive = false;\n+\t}\n+\tthrow new Error(\"storage did not propagate projection rollback\");\n+}"}],"unmatched":[]}