const WRITE_LOCKS = new Map>(); export async function withInboxLock(inboxPath: string, fn: () => Promise): Promise { const prev = WRITE_LOCKS.get(inboxPath) ?? Promise.resolve(); let release!: () => void; const mine = new Promise((resolve) => { release = resolve; }); WRITE_LOCKS.set(inboxPath, mine); await prev; try { return await fn(); } finally { release(); if (WRITE_LOCKS.get(inboxPath) === mine) { WRITE_LOCKS.delete(inboxPath); } } }