export interface LockInfo { pid: number; startedAt: string; port: number; version: string; } export interface InstanceLock { path: string; release(): void; } export declare class AlreadyRunningError extends Error { readonly holder: LockInfo; constructor(holder: LockInfo); } /** * Minimum time a lock holder must have been recorded as started (per its own * `startedAt` in daemon.lock) before three failed `/health` probes are * treated as zombie evidence at all (issue #396). The 3-probe loop below has * NO sleep between attempts — once the holder hasn't bound its port yet, * `fetch` fails with ECONNREFUSED almost instantly (not after the 2s probe * timeout), so a holder can fail all 3 probes within milliseconds of its own * launch. Boot can legitimately take several seconds (`migrate` + * `recoverOrphans` + `getProviders`, including ONNX worker spin-up, all run * BEFORE `app.listen()` in `serve.ts`), so "3 fast failures" alone proves * nothing about dead vs. still-booting. This grace period gives a * genuinely-alive, still-booting holder room to reach `app.listen()` before a * second launcher — the schtasks keepalive (PT5M) / watchdog (PT3M) racing * the SAME boot window — can ever consider it a zombie. 30s sits comfortably * above the worst plausible boot-to-listen time (single-digit seconds). */ export declare const ZOMBIE_BOOT_GRACE_MS = 30000; /** * Thrown when a lock holder fails 3 health probes but was recorded as * started too recently (within `ZOMBIE_BOOT_GRACE_MS`, or an injected * override) to treat as a zombie (issue #396) — it is far more likely still * booting than dead. The caller must defer, not steal: exiting cleanly here * is the SAME "cheap no-op" posture `AlreadyRunningError` already gives a * confirmed-healthy holder — a genuinely-booting daemon gets to finish * without a second launcher racing it into a kill. */ export declare class StillBootingError extends Error { readonly holder: LockInfo; readonly elapsedMs: number; constructor(holder: LockInfo, elapsedMs: number); } export declare function lockPath(dataDir: string): string; /** * The acquire-mutex sentinel path (Item 2). Separate FILE from `daemon.lock` * itself — the mutex's job is to serialize DECISION-MAKING across * near-simultaneous callers, not to record who holds the daemon; keeping it * a distinct file means daemon.lock's own format/readers never have to know * this mutex exists. */ export declare function acquiringLockPath(dataDir: string): string; /** Thrown when the acquire mutex itself cannot be obtained within the * timeout — i.e. another process has been mid-decide for longer than any * real boot (probe + zombie-kill + bind) should ever take. Almost always * means a sibling astramem-local process is genuinely wedged, not merely * slow; surfaced as a loud, distinct error rather than silently retried * forever, so it reaches the crash-exit path instead of hanging the caller. */ export declare class MutexTimeoutError extends Error { readonly path: string; readonly timeoutMs: number; constructor(path: string, timeoutMs: number); } /** * Resolve the OS-reported creation time of `pid`, or null when it cannot be * determined (process gone, permission denied, unparseable output, or an * unsupported platform). Callers MUST treat null as "cannot prove identity" * — never as a pass. */ export declare function getProcessStartTime(pid: number): Promise; /** * Check whether something is actively listening on 127.0.0.1:. * * Used by the zombie-takeover path (issue #389) to tell apart a recycled-PID * holder (identity mismatch, but nothing is actually bound to the port — * takeover is safe, there is nothing to race) from a holder that is * genuinely still bound (takeover would race the new listener's own * `app.listen()` into an EADDRINUSE crash loop, issue #387's original bug). * * ECONNREFUSED is the only outcome that proves "free". A successful connect * proves "in use". A timeout or any other connection error cannot prove * either way, so both fail CLOSED as "in use" — the same fail-closed posture * `stopLockHolder`'s identity check already uses: we would rather over-refuse * a takeover than under-refuse one and race a live listener. */ export declare function isPortInUse(port: number, timeoutMs?: number): Promise; /** Read the current lock holder for a data dir (null when absent/corrupt). */ export declare function readLockInfo(dataDir: string): LockInfo | null; /** * Machine-readable sub-case for a `StopLockHolderResult` with `ok: false`. * `detail` is the human-readable message; `reason` is for callers (like * `restore --force`) that need to tell "identity could not be checked" apart * from "identity was checked and is confirmed wrong" without pattern-matching * the prose. * * - `identity-unverifiable` — the check could not run at all (malformed * lock, or the OS query itself failed). Identity is UNKNOWN, not wrong. * - `identity-mismatch` — the check ran successfully and the OS-reported * start time does NOT match the lock's recorded one. Identity is * CONFIRMED wrong (almost certainly a recycled PID). * - `signal-failed` — identity was confirmed fine; sending the * signal itself failed (OS-level, e.g. permissions). * - `stop-timeout` — identity was confirmed fine and the signal was * sent, but the holder kept answering /health past the wait budget. */ export type StopLockHolderFailureReason = 'identity-unverifiable' | 'identity-mismatch' | 'signal-failed' | 'stop-timeout'; export interface StopLockHolderResult { ok: boolean; detail: string; /** Present only when `ok: false` — see `StopLockHolderFailureReason`. */ reason?: StopLockHolderFailureReason; } export interface StopLockHolderOptions { /** Injectable signal sender — tests substitute a spy instead of really killing a PID. */ signal?: (pid: number, signal: NodeJS.Signals | number) => void; /** Injectable liveness probe — tests substitute a stub instead of real fetch. */ healthProbe?: (port: number) => Promise; /** Total time to wait for /health to stop answering after signaling. Default 5000ms. */ waitMs?: number; /** Injectable process-start-time resolver — tests substitute a stub instead of shelling out to the OS. */ processStartTime?: (pid: number) => Promise; /** * When true, bypass the `identity-mismatch` drift refusal below (issue * #307: a crash-looped daemon whose lock's recorded `startedAt` has * drifted — e.g. a clock jump, or a lock format change across an upgrade * — could never be stopped via the CLI, with no documented recovery). * Does NOT touch the other three failure reasons (`identity-unverifiable`, * `signal-failed`, `stop-timeout`) — those still fail closed exactly as * before. Default false: the drift guard stays ON unless a caller opts in * explicitly. The drift is still computed and logged when bypassed, so * the operator can see exactly what was overridden. */ force?: boolean; } /** * Terminate whichever process actually holds `dataDir`'s daemon.lock, by PID * — not by asking the OS service manager to stop. * * Needed because the scheduler-level stop (schtasks `/end`, `systemctl * stop`, `launchctl unload`) only ends the launcher process it directly * started; `launch.cjs` (shim.ts) spawns the real daemon as a child via * `spawnSync`, and that child can keep running — still holding the port and * this lock — after the launcher/task is reported "stopped". `service stop` * used to report success while `/health` kept answering because of exactly * this gap. * * Idempotent: no lock, or a lock whose PID is already dead, both return * `ok: true` with no error. Cross-platform: `process.kill(pid, 'SIGTERM')` * force-terminates on Windows (no handler runs — same as the existing * `reinstall` stop path) and delivers a real, gracefully-handled SIGTERM on * POSIX (`serve.ts` has a `process.on('SIGTERM', shutdown)` handler). * * Every `ok: true` outcome ALSO deletes `daemon.lock` (issue: reinstall * stale-lock false-fail) — once a holder is CONFIRMED gone (dead PID, or * signaled and no longer answering `/health`), leaving its lock file behind * serves no purpose and actively misleads the next reader: `reinstall`'s * verify-health gate (`waitForHealthWithBootGrace`, cli/reinstall.ts) reads * `daemon.lock` while polling a freshly-started daemon and, finding the OLD * dead PID still recorded there, correctly concludes "daemon-dead" and * rolls back — even when the real problem was upstream (the new daemon * never got a chance to write ITS OWN lock at all). Deletion only fires when * the file, re-read at cleanup time, still names the EXACT holder this call * just confirmed gone (`pid` + `startedAt` both match) — never while a * holder might still be alive, and never a lock some OTHER process (a * sibling watchdog restart, a brand-new boot) has since claimed. Mirrors the * same "only touch it if it's still ours" guard `InstanceLock.release()` * already uses against its own pid, checked here against the STOPPED * holder's identity instead of the caller's own. */ export declare function stopLockHolder(dataDir: string, port: number, opts?: StopLockHolderOptions): Promise; /** * Thrown when a lock holder fails 3 health probes (looks like a zombie), * `stopLockHolder` could not confirm it is actually gone, AND (issue #389) * the holder's port is still genuinely bound — so taking over the lock and * calling `app.listen()` would risk racing a live listener. Issue #387: the * old code logged a warning and stole the lock unconditionally on 3 failed * probes — when the "zombie" was actually alive-but-wedged (a daemon stuck * before `app.listen()`, e.g. mid an unbounded consolidate setup), the new * process's own `listen()` threw `EADDRINUSE`, the crash handler exited 1, * and the scheduler's keepalive respawned another instance that repeated the * identical misdiagnosis — dozens of exit-1s in a tight loop with no * self-heal. Issue #389: `stopLockHolder`'s refusal alone is not proof of * danger — a recycled-PID holder (identity-mismatch) also refuses to be * signaled, but if it isn't our daemon it isn't bound to our port either, so * `acquireInstanceLock` only reaches this error when the port is confirmed * still in use. Surfacing this as a distinct, loud error (rather than * silently retrying `writeLock`/`listen`) means the caller fails fast with a * diagnosable message instead of racing the port. */ export declare class ZombieLockTakeoverError extends Error { readonly holder: LockInfo; readonly stopResult: StopLockHolderResult; constructor(holder: LockInfo, stopResult: StopLockHolderResult); } /** * Acquire the single-instance lock for `dataDir`. * * Throws AlreadyRunningError when a healthy daemon already holds it — this * now includes the case where a near-simultaneous sibling caller won the * acquire mutex first and successfully bound; the loser waits out the mutex * (see `acquireMutex`) and then resolves through this exact same path once * it can see the winner's now-written, now-bound daemon.lock. * Throws StillBootingError (issue #396) when the holder fails 3 health * probes but was recorded as started too recently to plausibly have reached * `app.listen()` yet — see `ZOMBIE_BOOT_GRACE_MS`'s doc comment. * Throws ZombieLockTakeoverError (issue #387) when the holder fails 3 * health probes but cannot be confirmed stopped — we must never return a * lock handle (and let the caller proceed to `app.listen()`) while the old * holder might still own the port. * Throws MutexTimeoutError (Item 2) when the acquire mutex itself cannot be * obtained within `opts.mutexTimeoutMs` — a sibling has been mid-decide far * longer than any real boot should take. * Returns a handle whose release() is idempotent and safe from crash handlers. */ export declare function acquireInstanceLock(dataDir: string, port: number, version: string, opts?: { healthProbe?: (port: number) => Promise; /** Injectable signal sender for the zombie-stop path — tests substitute a spy instead of really killing a PID. Threaded through to `stopLockHolder`. */ signal?: (pid: number, signal: NodeJS.Signals | number) => void; /** * Injectable process-start-time resolver for identity checks. Threaded * through to `stopLockHolder`'s zombie-stop identity check AND to * `acquireMutex`'s own `.acquiring` sentinel staleness check (issue #415 * LOW) — one injectable resolver covers both identity checks in the * boot path. */ processStartTime?: (pid: number) => Promise; /** Total time to wait for the zombie holder's /health to stop answering after signaling it. Threaded through to `stopLockHolder`'s `waitMs`. */ zombieStopWaitMs?: number; /** Injectable port-liveness probe for the zombie-stop path's port-free check (issue #389) — tests substitute a stub instead of a real socket connect. */ portInUse?: (port: number) => Promise; /** * Item 2/3 coupling: called AFTER daemon.lock is written, WHILE the * `.acquiring` mutex is still held — typically `() => app.listen(...)`. * The mutex is released only once this settles (resolve or reject), so * a second racer can never observe "lock written, port not yet bound" * and mistakenly steal. Defaults to a no-op, so callers that only care * about the lock-decision logic itself (most of this file's own test * suite) are unaffected — the mutex is still acquired and released * around the decide+write sequence either way, just with nothing to * wait for afterward. On failure, the lock we just wrote is released * (best-effort, only if we still own it) before the mutex releases and * the error propagates, so a bind failure never leaves a phantom * healthy-looking lock behind for the next boot attempt to trip over. */ bind?: () => Promise; /** Injectable acquire-mutex timeout — tests substitute a tiny value instead of the real 30s default. */ mutexTimeoutMs?: number; /** Override for `ZOMBIE_BOOT_GRACE_MS` (issue #396) — tests substitute a tiny/zero value instead of waiting out the real 30s default. */ bootGraceMs?: number; }): Promise;