import { stopLockHolder, type LockInfo } from './instance-lock.js'; import type { ServiceAdapter } from './types.js'; /** * Probe cadence for the generated systemd timer / launchd StartInterval * agent. Single source of truth so systemd.ts and launchd.ts stay in * lock-step, and so the recovery bound (interval + probe timeout + a * restart cycle) stays comfortably under the Windows PT5M (5 min) keepalive * this mirrors. */ export declare const WATCHDOG_PROBE_INTERVAL_SEC = 180; /** Default /health request timeout — generous enough that a merely-busy * (not hung) daemon under load always answers well inside it; see the * reinstall.ts DEFAULT_HEALTH_TIMEOUT_MS comment for the kind of boot-time * contention that can legitimately delay a response. Note this has to cover * the SAME endpoint under load a real incident hit: /dashboard cold-renders * in ~7.9s on a box with 15k+ memories because better-sqlite3 is * synchronous and blocks the whole event loop — a concurrent /health * request queues up behind it, not just /dashboard callers. 10s stays * comfortably above that. */ export declare const DEFAULT_PROBE_TIMEOUT_MS = 10000; /** * Consecutive /health failures required before the probe actually kills and * restarts anything (AC-4, issue #206). Each probe invocation is a fresh, * short-lived process (scheduler timer tick / schtasks run) with no * in-memory memory of the previous tick, so the count is persisted on disk * per data dir (see watchdogStatePath below) and reset to 0 the moment * `/health` answers again. * * Why 2, not 1: a genuinely wedged daemon (the failure mode this file exists * to catch) cannot recover on its own — every subsequent probe fails too, so * the second consecutive failure always arrives, just one interval later. A * merely slow-but-healthy daemon under load (the observed 7.9s dashboard * cold-render, or a burst of concurrent requests queued behind one * synchronous query) is already comfortably inside DEFAULT_PROBE_TIMEOUT_MS * and essentially never fails even a single probe, let alone two in a row — * so requiring 2 costs nothing in the common case and only adds one extra * interval of detection latency in the rare genuine-hang case, while * filtering out a single anomalous probe (a GC pause, a transient network * hiccup, a request that straddles the timeout boundary by chance) that * would otherwise trigger a needless kill-and-restart of a healthy process — * exactly the false-positive outcome AC-3 warns is worse than no watchdog. */ export declare const DEFAULT_FAILURE_THRESHOLD = 2; /** * Restart-storm circuit breaker (2026-07-15 incident, stabilization plan * P1.1): on that day the watchdog killed a busy-but-alive daemon 5 times in * ~2 hours — each kill re-enqueued the orphaned jobs at boot, re-saturated * the embed path, re-stalled the event loop, and earned the next kill. The * kill mechanism itself became the outage. If the watchdog has already * killed the daemon RESTART_STORM_THRESHOLD times inside a rolling * RESTART_STORM_WINDOW_MS, it stops killing and reports * `action: 'breaker-tripped'` instead; the restart-storm doctor check (RED, * src/doctor/checks/restart-storm.ts) is the operator signal. * * Fail-open direction is deliberate: every observed instance of this class * was busy-misclassified-as-dead, where another kill only makes things * worse. The accepted tradeoff is that a GENUINELY wedged daemon that trips * the breaker stays wedged until a human responds to the doctor RED — that * costs response latency, not correctness, while the old behavior actively * destroyed work in the common case. * * Hardcoded consts (not config.yaml) on the CRASH_LOOP_THRESHOLD precedent: * one more governance-fallback config value is one more place for defaults * to drift (see the DEFAULT_* const trap in CLAUDE.md). * * No explicit reset/trip flag is persisted: the window is recomputed from * the kill log on every tick, so the breaker self-clears once kills age * past the window. */ export declare const RESTART_STORM_THRESHOLD = 3; export declare const RESTART_STORM_WINDOW_MS: number; /** * Safety-valve absolute cap (2026-07-20 boot-grace fix): a daemon instance * that has NEVER answered `/health` since it started is normally never * killed, no matter how many consecutive probes fail (see the boot-grace * doc comment at the top of this file) — but that must not mean "wait * forever" for an instance that is genuinely stuck before ever reaching * `app.listen()` (a real deadlock during openDb/migrate/provider wiring, not * merely a slow one). Once a never-healthy instance has been alive (per its * own `daemon.lock` `startedAt`) longer than this cap, it is killed exactly * once and the reason is logged loudly — distinct from the ordinary * was-healthy-then-hung kill path below. * * Deliberately generous: a 573MB SQLCipher DB under disk contention was * observed taking ~6-8 minutes to bind on the affected box. 20 minutes * leaves ample headroom above that worst-observed case while still bounding * a truly-wedged boot instead of leaving it stuck forever. */ export declare const BOOT_HARD_CAP_SEC = 1200; /** One line per actual watchdog kill (only the `stopResult.ok === true` * path — refused/failed stops don't count; nothing died). */ export interface WatchdogKillEvent { ts: string; } /** Append-only kill log — same per-dataDir convention as * watchdog-probe-state.json below. NOT under logs/: the logs dir belongs to * the daemon's own rotation sweep, and this file must never be rotated away * from under the breaker's 6h window. */ export declare function watchdogKillsPath(dataDir: string): string; /** * Pure parse of kill-log content: timestamps (epoch ms) inside the rolling * window, oldest first. Malformed LINES are skipped (per-line, never fatal); * this function itself never touches the filesystem. Exported separately * from {@link readKillsInWindow} so callers who need to distinguish "file * unreadable" from "no kills" (the doctor check's inconclusive path) can do * their own read and still share this parsing. */ export declare function parseKillLog(content: string, nowMs: number, windowMs: number): number[]; /** * Kill timestamps (epoch ms) inside the rolling window, oldest first. * Never throws: an unreadable/missing/malformed log degrades to [] — a read * glitch must not trip the breaker (that would silently disable the * watchdog), and equally must not crash the probe. Callers who must NOT * conflate unreadable-with-empty (doctor's restart-storm check) should read * the file themselves and call {@link parseKillLog}. */ export declare function readKillsInWindow(dataDir: string, nowMs?: number, windowMs?: number): number[]; export interface WatchdogTimerAdapter { /** Register the periodic hang-probe timer/agent. Idempotent — same * overwrite-in-full discipline as installBackupTimer. */ installWatchdogTimer(execPath: string, intervalSec: number): Promise; /** Remove the hang-probe timer/agent. No-op if never installed. */ uninstallWatchdogTimer(): Promise; } /** * Duck-typed capability check — deliberately NOT part of the shared * `ServiceAdapter` interface, so plain-object test mocks that satisfy * `ServiceAdapter` without these two methods (e.g. * tests/service/install-flow.test.ts's older fixtures) simply don't match, * and callers skip the feature safely instead of throwing. All three * platform adapters (systemd.ts, launchd.ts, schtasks.ts) implement it as of * issue #206. */ export declare function hasWatchdogTimer(adapter: ServiceAdapter): adapter is ServiceAdapter & WatchdogTimerAdapter; export interface WatchdogProbeOptions { port: number; dataDir: string; adapter: ServiceAdapter; timeoutMs?: number; /** Consecutive /health failures required before acting (AC-4). Defaults to * DEFAULT_FAILURE_THRESHOLD. */ failureThreshold?: number; /** Injectable fetch — tests substitute a stub instead of a live daemon. */ fetchImpl?: typeof fetch; /** Injectable stopLockHolder — tests substitute a stub instead of really * signaling a PID. Defaults to the real instance-lock.ts implementation. */ stopLockHolderImpl?: typeof stopLockHolder; /** Injectable watchdog-state persistence — tests substitute in-memory * stubs instead of touching disk. Defaults to a JSON file under dataDir * (see `WatchdogState` / `watchdogStatePath`). */ readStateImpl?: (dataDir: string) => WatchdogState; writeStateImpl?: (dataDir: string, state: WatchdogState) => void; /** Injectable `daemon.lock` reader — identifies the CURRENT daemon * instance (`pid:startedAt`) so the boot-grace gate can tell "never * healthy, still booting" apart from "was healthy, now hung", and can * compute how long a never-healthy instance has been alive for the * `BOOT_HARD_CAP_SEC` safety valve. Defaults to the real * instance-lock.ts `readLockInfo`. */ readLockInfoImpl?: (dataDir: string) => LockInfo | null; /** Boot-grace hard-cap override (ms) — tests substitute a tiny value * instead of the real `BOOT_HARD_CAP_SEC` default. */ bootHardCapMs?: number; /** Restart-storm breaker knobs/seams (P1.1) — tests substitute in-memory * kill logs and a fixed clock; production always uses the defaults. */ restartStormThreshold?: number; restartStormWindowMs?: number; readKillsInWindowImpl?: typeof readKillsInWindow; appendKillEventImpl?: (dataDir: string) => void; nowMs?: number; } export interface WatchdogProbeResult { healthy: boolean; action: 'none' | 'below-threshold' | 'still-booting' | 'breaker-tripped' | 'restarted' | 'restart-failed'; detail: string; } /** * Persisted watchdog state (per dataDir, `watchdogStatePath` below) — same * file `{consecutiveFailures}` used to live in alone, now extended (2026-07-20 * boot-grace fix) with per-instance identity so a hang recorded against one * daemon process can never be misattributed to its successor. * * - `consecutiveFailures` — unchanged: consecutive `/health` failures * against the CURRENT instance, reset to 0 the moment it answers. * - `instanceKey` — `${pid}:${startedAt}` of the `daemon.lock` holder this * state was last observed against, or `null` when no lock could be read. * A probe that reads a DIFFERENT key than the one persisted here means a * new daemon process has taken over since the last tick — see the reset * logic in `runWatchdogProbe`. * - `everHealthyThisInstance` — has THIS instance (by `instanceKey`) ever * answered `/health` at all. Gates the kill path: only a daemon that was * healthy at least once and has since gone silent is treated as hung. */ export interface WatchdogState { consecutiveFailures: number; instanceKey: string | null; everHealthyThisInstance: boolean; } /** * Runs one probe cycle. Never throws — this is invoked unattended from a * scheduler timer with no one watching stderr in real time; every failure * mode is reported back in the result instead. */ export declare function runWatchdogProbe(opts: WatchdogProbeOptions): Promise;