import { chmodSync, existsSync, linkSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { isAbsolute, join, resolve } from "node:path"; import { randomUUID } from "node:crypto"; import { Database } from "bun:sqlite"; import { canonicalPath, hubHome } from "./project.ts"; import { isDatabaseBusy } from "./recovery-error.ts"; import { processLiveness, processSignature } from "../pi/process-signature.ts"; const RUNNER_DB_BUSY_TIMEOUT_MS = 3000; /** A startup-path hold check never waits on the event loop: busy counts as held (#1546). */ const HOLD_CHECK_DB_BUSY_TIMEOUT_MS = 1; export const operationIdPattern = /^[a-f0-9-]{36}$/; export function operationPath(id: string, home = hubHome()): string { if (typeof id !== "string" || id.length !== 36 || !operationIdPattern.test(id)) throw new Error("invalid recovery operation ID"); return join(home, "recovery", `${id}.json`); } /** Private state only. Never put tokens or transcript/message bodies in an operation receipt. */ export function atomicPrivateJSON(file: string, value: unknown): void { const temporary = `${file}.${randomUUID()}.tmp`; try { writeFileSync(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: "wx" }); chmodSync(temporary, 0o600); renameSync(temporary, file); } finally { rmSync(temporary, { force: true }); } } export function readOperation(id: string, home = hubHome()): T { return JSON.parse(readFileSync(operationPath(id, home), "utf8")) as T; } export function writeOperation(id: string, value: unknown, home = hubHome()): void { mkdirSync(join(home, "recovery"), { recursive: true, mode: 0o700 }); atomicPrivateJSON(operationPath(id, home), value); } function legacyRecoveryLock(home: string): string | undefined { const file = join(home, "recovery.lock"); try { const data = JSON.parse(readFileSync(file, "utf8")); if (typeof data.operationId !== "string" || data.operationId.length !== 36 || !operationIdPattern.test(data.operationId)) throw new Error("invalid recovery lock"); return data.operationId; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined; throw new Error("recovery lock is unreadable; inspect it before changing runtimes", { cause: error }); } } const projectLocksPath = (home: string) => join(home, "recovery", "project-locks.db"); const projectLockError = () => new Error("project recovery coordination state is unreadable; inspect it before changing runtimes"); function recoveryProjectKey(root: string): string { if (typeof root !== "string" || !isAbsolute(root) || root.includes(String.fromCharCode(0))) throw new Error("recovery scope needs a canonical project root"); try { return canonicalPath(root); } catch (error) { // Receipts retain the already-canonical registration spelling so a removed project can still be disposed. if ((error as NodeJS.ErrnoException).code === "ENOENT") return resolve(root); throw error; } } function projectLocksExist(file: string): boolean { try { const info = lstatSync(file); if (!info.isFile() || info.isSymbolicLink()) throw projectLockError(); return true; } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; throw error; } } function projectLocks(home: string, create = false): Database | undefined { const file = projectLocksPath(home); if (!projectLocksExist(file)) { if (!create) return undefined; mkdirSync(join(home, "recovery"), { recursive: true, mode: 0o700 }); // Publish a complete DELETE-journal database, never an empty coordination file another process could misread. const temporary = `${file}.${randomUUID()}.tmp`; try { const db = new Database(temporary, { create: true }); try { db.run(`PRAGMA busy_timeout = ${RUNNER_DB_BUSY_TIMEOUT_MS}`); db.run("CREATE TABLE project_locks (project_root TEXT PRIMARY KEY, operation_id TEXT NOT NULL)"); } finally { db.close(); } chmodSync(temporary, 0o600); try { linkSync(temporary, file); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; } } finally { rmSync(temporary, { force: true }); } } if (!projectLocksExist(file)) throw projectLockError(); let db: Database | undefined; try { db = new Database(file, create ? { readwrite: true, create: false } : { readonly: true, create: false }); db.run(`PRAGMA busy_timeout = ${RUNNER_DB_BUSY_TIMEOUT_MS}`); if (!db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='project_locks'").get()) throw projectLockError(); return db; } catch (error) { db?.close(); if (isDatabaseBusy(error)) throw error; throw projectLockError(); } } /** Read-only, 1 ms busy wait: for a check on a startup path that must never wait on the event loop (#1546). Unreadable or busy throws. */ function projectLocksNonBlocking(home: string): Database | undefined { const file = projectLocksPath(home); if (!projectLocksExist(file)) return undefined; let db: Database | undefined; try { db = new Database(file, { readonly: true, create: false }); db.run(`PRAGMA busy_timeout = ${HOLD_CHECK_DB_BUSY_TIMEOUT_MS}`); if (!db.query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='project_locks'").get()) throw projectLockError(); return db; } catch (error) { db?.close(); throw error; } } function projectLockOn(db: Database, key: string): string | undefined { const rows = db.query("SELECT CASE WHEN typeof(operation_id)='text' AND length(operation_id)=36 THEN operation_id END AS id FROM project_locks WHERE project_root=? LIMIT 2").all(key) as { id: string | null }[]; if (!rows.length) return undefined; if (rows.length !== 1 || typeof rows[0]!.id !== "string" || !operationIdPattern.test(rows[0]!.id)) throw projectLockError(); return rows[0]!.id; } /** Legacy machine holds remain authoritative; new project holds affect only their canonical project. */ export function recoveryLock(home = hubHome(), projectRoot?: string): string | undefined { const legacy = legacyRecoveryLock(home); if (legacy || projectRoot === undefined) return legacy; const key = recoveryProjectKey(projectRoot), db = projectLocks(home); if (!db) return undefined; try { return projectLockOn(db, key); } finally { db.close(); } } export function acquireRecoveryLock(id: string, home = hubHome(), projectRoot?: string): void { operationPath(id, home); if (projectRoot !== undefined) { const key = recoveryProjectKey(projectRoot), legacy = legacyRecoveryLock(home); if (legacy && legacy !== id) throw new Error(`another recovery operation owns this machine: ${legacy}`); const db = projectLocks(home, true)!; try { db.transaction(() => { const existing = projectLockOn(db, key); if (existing && existing !== id) throw new Error(`another recovery operation owns this project: ${existing}`); if (!existing) db.query("INSERT INTO project_locks(project_root,operation_id) VALUES(?,?)").run(key, id); }).immediate(); } finally { db.close(); } return; } mkdirSync(home, { recursive: true, mode: 0o700 }); const existing = recoveryLock(home); if (existing === id) return; const temporary = join(home, `.recovery-lock-${randomUUID()}.tmp`); try { writeFileSync(temporary, JSON.stringify({ operationId: id }), { mode: 0o600, flag: "wx" }); try { linkSync(temporary, join(home, "recovery.lock")); } catch { throw new Error(`another recovery operation owns this machine: ${recoveryLock(home) ?? "unknown"}`); } } finally { rmSync(temporary, { force: true }); } } export function releaseRecoveryLock(id: string, home = hubHome(), projectRoot?: string): void { operationPath(id, home); if (projectRoot !== undefined) { const key = recoveryProjectKey(projectRoot), db = projectLocks(home, true)!; try { if (db.query("DELETE FROM project_locks WHERE project_root=? AND operation_id=?").run(key, id).changes !== 1) throw new Error("recovery lock ownership changed"); } finally { db.close(); } return; } // Legacy release is called under the operation's exclusive runner claim. Project releases compare/delete atomically. if (recoveryLock(home) !== id) throw new Error("recovery lock ownership changed"); rmSync(join(home, "recovery.lock")); } /** Used by CLI and manager lifecycle paths. A detached operation carries its own ID. */ export function assertLifecycleAvailable(projectRoot?: string): void { const owner = recoveryLock(undefined, projectRoot); if (owner && process.env.AGENTHUB_RECOVERY_OPERATION !== owner) throw new Error(activeOperation(owner)); } /** * #215: the command line of an operation's own coordinator, which has every recovery command. Mid-upgrade the global * `ahub` may still be the older release, so next actions and errors never name it bare. A coordinator from before #215 * lacks dispose, refuses abort and resume on a lapsed hold and shows no next actions: then the running release is * named, which does all of that in-process (its resume still runs the operation's own runner). */ export type RecoveryAction = "status" | "resume" | "abort" | "dispose" | "reattach"; export function supportsAction(sourceRoot: string, action: RecoveryAction): boolean { if (!coordinatorCurrent(sourceRoot)) return false; if (action !== "reattach") return true; try { return readFileSync(join(sourceRoot, "src/cli/upgrade.ts"), "utf8").includes("export async function reattachRecovery"); } catch { return false; } } export function recoveryCommand(op: { id: string; sourceRoot?: string }, action: RecoveryAction, flags = ""): string { const entry = !op.sourceRoot ? undefined : supportsAction(op.sourceRoot, action) ? join(op.sourceRoot, "src/cli/main.js") : join(import.meta.dir, "../cli/main.js"); const cli = !entry ? "ahub" : /^[\w./@+-]+$/.test(entry) ? `bun ${entry}` : `bun '${entry.replace(/'/g, `'\\''`)}'`; return `${cli} recovery ${action} ${op.id}${flags ? ` ${flags}` : ""}`; } /** #272: the command above as an argv for `bun`, which a screen runs instead of printing; with no coordinator of its own, this release's. */ export function recoveryArgv(op: { id: string; sourceRoot?: string }, action: RecoveryAction, flags: string[] = []): string[] { const entry = op.sourceRoot && supportsAction(op.sourceRoot, action) ? join(op.sourceRoot, "src/cli/main.js") : join(import.meta.dir, "../cli/main.js"); return [entry, "recovery", action, op.id, ...flags]; } /** * Whether a coordinator has the #215 recovery commands (dispose, re-preparation, next actions). * ponytail: a text sniff of its upgrade.ts; a rename or re-export reads as an older coordinator (the running release is * then named, which is safe). Upgrade path: a capability list in package.json, shared with targetReadsWaivers. */ export function coordinatorCurrent(sourceRoot: string): boolean { try { return readFileSync(join(sourceRoot, "src/cli/upgrade.ts"), "utf8").includes("export async function disposeRecovery"); } catch { return false; } } /** What a lifecycle command refused by the lock says: the operation's own status command, which lists what to do next. */ export function activeOperation(owner: string, home = hubHome()): string { let op: { id: string; sourceRoot?: string } = { id: owner }; try { op = { id: owner, sourceRoot: readOperation<{ sourceRoot?: string }>(owner, home).sourceRoot }; } catch { /* no readable receipt: the bare commands are all there is */ } // The choices depend on the operation's state (a partway stop-and-archive refuses resume): status lists them. return `recovery operation ${owner} is active; ${recoveryCommand(op, "status")} lists what to do next`; } /** #226: the runner row's signature column, added to a runner.db an older release created; older runners leave it NULL. */ const signed = (db: Database) => (db.query("PRAGMA table_info(runner)").all() as { name: string }[]).some((c) => c.name === "signature"); /** * The pid of the runner that holds the operation now, read without claiming it (#215 status): undefined when none does, * "unknown" when the record cannot be read (unreadable, or still locked after the busy timeout) or its owner cannot be * identified, never "none" then. A row whose signature belongs to another process now is no runner (#226). */ export function recoveryRunner(id: string, home = hubHome()): number | "unknown" | undefined { const path = `${operationPath(id, home)}.runner.db`; if (!existsSync(path)) return undefined; let db: Database | undefined; try { db = new Database(path, { readonly: true }); db.run(`PRAGMA busy_timeout = ${RUNNER_DB_BUSY_TIMEOUT_MS}`); // a claim in progress must not read as no runner // A crash between creating the file and its table leaves no runner; claimRunner creates the table and claims. if (!db.query("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'runner'").get()) return undefined; const row = db.query(`SELECT pid${signed(db) ? ", signature" : ""} FROM runner WHERE slot = 1`).get() as { pid: number; signature?: string | null } | null; if (!row) return undefined; if (!Number.isSafeInteger(row.pid) || row.pid < 1) return "unknown"; const state = processLiveness(row.pid, row.signature); return state === "gone" ? undefined : state === "live" ? row.pid : "unknown"; } catch { return "unknown"; } finally { db?.close(); } } /** * #272: the pid of the runner that holds `id`, only when its claim carries a process signature that still matches. * `recoveryRunner` answers a claim without one (a coordinator of 0.12.20 or older, or a `ps` that failed at claim * time) from its bare pid, which is enough to wait for it and never enough to signal it. */ export function signedRunner(id: string, home = hubHome()): number | undefined { const path = `${operationPath(id, home)}.runner.db`; if (!existsSync(path)) return undefined; let db: Database | undefined; try { db = new Database(path, { readonly: true }); db.run(`PRAGMA busy_timeout = ${RUNNER_DB_BUSY_TIMEOUT_MS}`); if (!signed(db)) return undefined; const row = db.query("SELECT pid, signature FROM runner WHERE slot = 1").get() as { pid: number; signature: string | null } | null; if (!row?.signature || !Number.isSafeInteger(row.pid) || row.pid < 1) return undefined; return processSignature(row.pid) === row.signature ? row.pid : undefined; } catch { return undefined; } finally { db?.close(); } } /** #272: stop that verified runner and wait until no runner holds the operation. False when one still does, or cannot be verified. */ export async function stopSignedRunner(id: string, home = hubHome(), waitMs = 5000): Promise { if (recoveryRunner(id, home) === undefined) return true; const pid = signedRunner(id, home); if (pid === undefined) return false; try { process.kill(pid, "SIGTERM"); } catch { /* gone meanwhile */ } for (const deadline = Date.now() + waitMs; Date.now() < deadline;) { if (recoveryRunner(id, home) === undefined) return true; await new Promise((resolve) => setTimeout(resolve, 100)); } return false; } /** One operation's runner claim: `release` gives the slot back and leaves the db, `retire` removes the db (#329). */ interface RunnerClaim { /** The row leaves and the handle closes, so the db survives for the next owner. */ release(): void; /** * #329/#1541: close the handle and remove the db while this process's row still names it, so no pass can claim the freed slot * in between and have the file unlinked under its own handle (SQLITE_READONLY_DBMOVED). False when the db could not be * removed: the row then keeps refusing a new owner until this process exits and a later claim replaces the stale one. */ retire(): boolean; } function openRunnerClaim(id: string, home: string): RunnerClaim { const path = `${operationPath(id, home)}.runner.db`; const nonce = randomUUID(); const db = new Database(path, { create: true }); try { db.run(`PRAGMA busy_timeout = ${RUNNER_DB_BUSY_TIMEOUT_MS}`); chmodSync(path, 0o600); db.run("CREATE TABLE IF NOT EXISTS runner (slot INTEGER PRIMARY KEY, pid INTEGER NOT NULL, nonce TEXT NOT NULL, signature TEXT)"); if (!signed(db)) { try { db.run("ALTER TABLE runner ADD COLUMN signature TEXT"); } catch (error) { if (!/duplicate column/i.test((error as Error).message)) throw error; } // a concurrent claim added it } const signature = processSignature(process.pid) ?? null; db.transaction(() => { const row = db.query("SELECT pid, signature FROM runner WHERE slot = 1").get() as { pid: number; signature: string | null } | null; if (row) { if (!Number.isSafeInteger(row.pid) || row.pid < 1) throw new Error("invalid recovery runner ownership"); const state = processLiveness(row.pid, row.signature); if (state === "live") throw new Error(`recovery runner ${row.pid} is still alive`); if (state === "unknown") throw new Error(`recovery runner ${row.pid} cannot be identified (its process exists but cannot be inspected); refusing to replace it`); } // An older runner rewrites the whole row (INSERT OR REPLACE), so its claim never inherits this signature. db.query("INSERT OR REPLACE INTO runner (slot, pid, nonce, signature) VALUES (1, ?, ?, ?)").run(process.pid, nonce, signature); }).immediate(); } catch (error) { db.close(); throw error; } return { release: () => { // A db another pass already removed cannot be written; the caller reports `kept` instead of throwing out of its pass. try { db.query("DELETE FROM runner WHERE slot = 1 AND nonce = ?").run(nonce); } finally { db.close(); } }, retire: () => { // #329: the row stays until the file is gone, so the freed slot can never be claimed between a release and an unlink. try { db.close(); } catch { return false; } try { rmSync(path, { force: true }); return true; } catch { return false; } }, }; } /** An exclusive runner claim. Never steal a live or uncertain owner on resume. */ export function claimRunner(id: string, home = hubHome()): () => void { const claim = openRunnerClaim(id, home); return () => claim.release(); } /** * True when any machine or project recovery hold exists, or the coordination state cannot be read: unknown is held. * `nonBlocking` bounds how long a locked project-locks.db may block the caller to 1 ms: a startup path passes it so a busy database is a * hold, never a wait on the event loop (#1546). Without it the normal runner timeout applies. */ export function anyRecoveryHold(home = hubHome(), nonBlocking = false): boolean { try { if (legacyRecoveryLock(home)) return true; const db = nonBlocking ? projectLocksNonBlocking(home) : projectLocks(home); if (!db) return false; try { return !!db.query("SELECT 1 FROM project_locks LIMIT 1").get(); } finally { db.close(); } } catch { return true; } } /** * #1541: remove one terminal receipt and its runner db. The exclusive runner claim is the only mutual exclusion: a live or * unidentifiable runner keeps the receipt, a dead one is replaced by `openRunnerClaim` in its own transaction, so two retirers * on the same stale claim cannot both proceed. Under the claim `confirm` sees the receipt as it is now; the receipt leaves * first, then the runner db, and this process's claim row leaves with that file, never before it (#329): a pass therefore * cannot claim the freed slot in between and have the file unlinked under its own handle (SQLITE_READONLY_DBMOVED). An * interruption leaves only a runner db without a receipt, which the next call settles through the ENOENT branch (a later * claimant re-reads the receipt, finds none and fails). A runner db whose receipt is gone is settled the same way * (`settled`, `confirm` never called); only the call that removed the receipt answers `retired`, and a db this call cannot * remove answers `kept` so the next pass settles it. */ export function retireOperation(id: string, home: string, confirm: (record: unknown) => boolean, hooks: { betweenPair?: () => void; beforeRunnerRemoval?: () => void } = {}): "retired" | "settled" | "kept" { const file = operationPath(id, home); let claim: RunnerClaim; try { claim = openRunnerClaim(id, home); } catch { return "kept"; } // Giving the claim back is best effort: a pass only reaches here with the receipt still present, so the answer is `kept`. const giveUp = (): "kept" => { try { claim.release(); } catch { /* the db another pass already moved */ } return "kept"; }; let removed = false; try { let record: unknown; try { record = readOperation(id, home); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") return giveUp(); } if (record !== undefined) { if (!confirm(record)) return giveUp(); rmSync(file); removed = true; hooks.betweenPair?.(); } } catch (error) { giveUp(); throw error; } // The seam where a second pass used to claim the slot the release had just freed, and then lose the file to this unlink. hooks.beforeRunnerRemoval?.(); return claim.retire() ? (removed ? "retired" : "settled") : "kept"; }