import { AsyncLocalStorage } from 'node:async_hooks'; import { createHash } from 'node:crypto'; import { join } from 'node:path'; import { withStoreLock } from './lock.js'; const held = new AsyncLocalStorage>(); /** Event listeners start independent operations, not children of the writer. */ export function outsideTaskTransaction(work: () => T): T { return held.run(new Map(), work); } /** Cross-process, reentrant task transaction. Never hold this during model execution. */ export async function taskTransaction( root: string, id: string, work: () => Promise, ): Promise { const key = join( root, 'transactions', createHash('sha256').update(id).digest('hex'), ); if (held.getStore()?.get(key)?.active) return work(); return withStoreLock(key, async () => { const token = { active: true }; try { return await held.run( new Map([...(held.getStore() ?? []), [key, token]]), work, ); } finally { token.active = false; } }); }