/** * Persistent idempotent locks for sweep / agent starts. * Best-effort in packageStorage; overlaps skip rather than double-start. */ import { loadJson, saveJson, storageKeys } from './storage.ts' const LOCKS_KEY = 'factory:locks:v1' export type LockRecord = { key: string holder: string acquiredAt: string expiresAt: string } type LockStore = { locks: Record } async function load(): Promise { return loadJson(LOCKS_KEY, { locks: {} }) } async function save(store: LockStore): Promise { await saveJson(LOCKS_KEY, store) } function nowMs() { return Date.now() } /** Try to acquire a lock. Returns true when this holder owns it. */ export async function tryAcquireLock( key: string, holder: string, ttlMs = 14 * 60_000, ): Promise { const store = await load() const existing = store.locks[key] const now = nowMs() if (existing && Date.parse(existing.expiresAt) > now && existing.holder !== holder) { return false } const acquiredAt = new Date(now).toISOString() store.locks[key] = { key, holder, acquiredAt, expiresAt: new Date(now + ttlMs).toISOString(), } await save(store) return true } export async function releaseLock(key: string, holder: string): Promise { const store = await load() const existing = store.locks[key] if (existing && existing.holder === holder) { delete store.locks[key] await save(store) } } export async function pruneExpiredLocks(): Promise { const store = await load() const now = nowMs() let pruned = 0 for (const [key, lock] of Object.entries(store.locks)) { if (Date.parse(lock.expiresAt) <= now) { delete store.locks[key] pruned++ } } if (pruned) await save(store) return pruned } export function workItemLockKey(workItemId: string): string { return `wi:${workItemId}` } export function sweepTickLockKey(): string { return 'sweep:tick' } // Re-export storage key constant for self-review clarity void storageKeys