import { Effect } from 'effect';
import { monitorEventLoopDelay } from 'node:perf_hooks';

/**
 * Type SSOT for `@sylphx/sdk/health` (ADR-111 §4).
 *
 * Pure runtime types — framework-free, no schema library required at the
 * SDK boundary. Apps that want Standard Schema validation (per ADR-084)
 * can wrap the wire-format `HealthSnapshot` in their own schema.
 *
 * The wire shape (`HealthSnapshot`) is the **stable contract** the
 * `sylphx-health-agent` sidecar parses (see ADR-111 §3.2.4 +
 * `apps/health-agent/src/app-poll.ts::parseAppHealthBody`). Do not break it.
 */
/**
 * One reading produced by a `Signal.read()`. The aggregator turns each
 * reading into a `factor` in `[0, 1]` then folds them into the score via
 * the configured `ScoringStrategy`.
 *
 * `value` is the raw observation (ms, ratio, count, …) — surfaced verbatim
 * in the wire snapshot so operators can debug from JSON without re-running
 * the signal logic.
 *
 * `healthFactor` is the normalised health in `[0, 1]`:
 *   - `1` = fully healthy
 *   - `0` = dead (or "we don't know" if `unknown=true` and the policy says so)
 *
 * `unknown=true` means the signal **could not be measured this tick** (e.g.
 * cgroup file unreadable). Scoring strategies treat unknown signals as
 * `factor=1` (don't penalise an app for our own missing data).
 */
interface SignalReading {
    readonly value: number | string | boolean;
    readonly healthFactor: number;
    readonly unknown?: boolean;
}
/**
 * A health signal — one named, weighted measurement the score is built from.
 *
 * Two variants:
 *   - `SyncSignal`  — `read(): SignalReading`            (e.g. event-loop lag)
 *   - `AsyncSignal` — `read(): Promise<SignalReading>`   (e.g. queue depth
 *                                                          fetched over IPC)
 *
 * The discriminated `Signal` union accepts both. The aggregator awaits
 * each reading uniformly via `Promise.resolve(signal.read())`.
 *
 * Implementations are pure — no internal mutation outside the closure-
 * captured monitor state (e.g. `monitorEventLoopDelay()`). Stop /
 * cleanup are exposed via `dispose()` for tests and graceful shutdown.
 */
interface SignalBase {
    /** Unique stable identifier; appears in the wire `signals.<name>` map. */
    readonly name: string;
    /**
     * Weight in the weighted-product score. Strictly `> 0` for active
     * signals; `0` is a no-op signal (kept for compatibility with
     * conditional registration but skipped in scoring).
     */
    readonly weight: number;
    /**
     * Tear down any background work (timers, monitors, file watchers).
     * Called during graceful shutdown and from test cleanup.
     */
    dispose?(): void;
}
interface SyncSignal extends SignalBase {
    read(): SignalReading;
}
interface AsyncSignal extends SignalBase {
    read(): Promise<SignalReading>;
}
type Signal = SyncSignal | AsyncSignal;
/**
 * The complete health score + signal breakdown produced by `health.evaluate()`.
 *
 * `score` is the normalised aggregate in `[0, 1]`. Signal payload is
 * verbatim values from each `SignalReading.value` so operators can
 * cross-reference Grafana dashboards with the JSON.
 */
interface HealthScore {
    readonly score: number;
    readonly signals: Record<string, number | string | boolean>;
    readonly lastTickAt: string;
}
/**
 * Wire format the sidecar's `app-poll.ts::parseAppHealthBody` consumes.
 *
 * Pinned by ADR-111 §3.2.4 — keep stable. The sidecar tolerates extra
 * keys; do NOT remove existing ones without sequencing the sidecar update
 * first.
 */
type HealthSnapshot = HealthScore;
/**
 * Tagged error type for the Effect API. Promise consumers see the same
 * `message` via `Error.message` — the tag is for `Effect.catchTag`.
 */
declare class HealthError extends Error {
    readonly _tag: "HealthError";
    readonly cause?: unknown;
    constructor(message: string, cause?: unknown);
}
/**
 * `ScoringStrategy` collapses N readings → one `score` in `[0, 1]`.
 *
 * Default is `weightedProduct` (see `scoring.ts`). Custom strategies can
 * be plugged in via `sylphxHealth({ scoringStrategy: myStrategy })`.
 */
type ScoringStrategy = (readings: ReadonlyArray<{
    signal: Signal;
    reading: SignalReading;
}>) => number;
interface SylphxHealthOptions {
    /**
     * Signals to register. If omitted, defaults to a single
     * `eventLoopLagSignal({ degradedMs: 5000, deadMs: 30000 })` per
     * ADR-111 §4.6 ("sane out-of-box").
     */
    readonly signals?: ReadonlyArray<Signal>;
    /**
     * Strategy used to fold readings into a score. Defaults to
     * `weightedProduct` from `scoring.ts`.
     */
    readonly scoringStrategy?: ScoringStrategy;
    /**
     * Optional injected clock — used by tests for deterministic
     * `lastTickAt` timestamps.
     */
    readonly now?: () => Date;
}

/**
 * Effect TS integration for `@sylphx/sdk/health` (Rule 21 / ADR-058 Amendment).
 *
 * Effect-native services should NEVER call `Effect.runPromise` inside
 * business logic — this module exposes `evaluateEffect` so they can fold
 * the health computation into their own fiber graph.
 *
 * `effect` is an OPTIONAL peer dependency — apps that don't import this
 * module never pull it in (sideEffects: false + tree-shaking guarantees
 * this; verified in tests). The `Effect` type is imported from the
 * peer-dep at runtime; consumers either provide it or never reach this
 * code path.
 */

/**
 * Lift a `() => Promise<HealthScore>` evaluator into an Effect-native value.
 *
 * Errors thrown by the evaluator are tagged `HealthError` so callers can
 * use `Effect.catchTag('HealthError', …)` for typed recovery.
 *
 * @example
 * ```ts
 * import { Effect } from 'effect'
 * import { sylphxHealth } from '@sylphx/sdk/health'
 *
 * const health = sylphxHealth({ signals: [...] })
 *
 * const program = Effect.gen(function* () {
 *   const { score, signals } = yield* health.evaluateEffect
 *   yield* Effect.log(`health=${score.toFixed(2)} signals=${JSON.stringify(signals)}`)
 *   return score
 * })
 *
 * // Only the entry point runs the Effect (Rule 21).
 * const finalScore = await Effect.runPromise(program)
 * ```
 */
declare function evaluateEffect(evaluator: () => Promise<HealthScore>): Effect.Effect<HealthScore, HealthError, never>;

/**
 * Universal HTTP handler for `@sylphx/sdk/health` (ADR-111 §4.2).
 *
 * Framework-agnostic: returns either a `Web Fetch API` `Response`
 * (Hono / Bun.serve / itty-router / Next.js routes) or, via thin adapters,
 * a Node `(req, res) => void` (Express / Fastify-as-classic-handler).
 *
 * The handler always returns **HTTP 200** unless the SDK itself failed to
 * compute a score (rare; caught and returned as 500 for ops to triage).
 * The three-tier 200 / 503 gate (ADR-111 §4.4) lives in the **sidecar**,
 * not here — the SDK's job ends at exposing the score so the sidecar
 * can decide. This separation is documented in the README ("apps don't
 * need to think about probe semantics").
 */

/**
 * Minimal contract a `health` instance must expose for the handler to
 * call. The full `health` object satisfies this implicitly via
 * `evaluate()` from `./index.ts`.
 */
interface HealthEvaluator {
    evaluate(): Promise<HealthScore>;
}
/**
 * Build a Web-Fetch-style handler. Suitable for:
 *   - Hono: `app.get('/healthz', health.handler())`
 *   - Bun.serve: `fetch: health.handler()`
 *   - Next.js route.ts: `export const GET = health.handler()`
 *   - itty-router / Hattip / standard `(Request) => Response` runtimes
 */
declare function createWebHandler(source: HealthEvaluator): (req?: Request) => Promise<Response>;
/**
 * Build a Node-style `(req, res)` handler — for Express / classic Fastify.
 *
 * Adapter that delegates to `createWebHandler()` so logic stays in one
 * place. Imported lazily by callers that need it; doesn't drag any node
 * types into Web-only code paths.
 */
interface NodeIncoming {
    method?: string;
    url?: string;
}
interface NodeOutgoing {
    statusCode: number;
    setHeader(name: string, value: string): void;
    end(body?: string): void;
}
declare function createNodeHandler(source: HealthEvaluator): (req: NodeIncoming, res: NodeOutgoing) => Promise<void>;

/**
 * Unix-socket server for `@sylphx/sdk/health` (ADR-111 §3.2.4 + §4.2).
 *
 * The sidecar polls the app over a Unix socket — `/var/run/sylphx/health.sock`
 * by default. The shared volume (`emptyDir` mount, see ADR-111 §3.2.2) is
 * provisioned by the reconciler when the sidecar is injected. This server
 * binds Bun's native `Bun.serve({ unix: <path> })` and serves the same
 * JSON the HTTP handler does.
 *
 * Graceful shutdown is essential — the socket file lingers on disk if not
 * cleaned, and the sidecar's first reconnect attempt after a redeploy
 * would hit a stale inode. `shutdown()` calls `server.stop()` AND
 * unlinks the socket file. Process signal ownership stays with the app
 * entry point; SDK library code only returns an explicit shutdown handle.
 */

/** Bun-typed minimum for the server we need to control. */
interface BunServer {
    stop(force?: boolean): void;
    url?: {
        href: string;
    } | null;
}
interface UnixSocketServerOptions {
    /** Absolute path to bind. Defaults to `/var/run/sylphx/health.sock`. */
    readonly path?: string;
    /**
     * Override unlink behavior — useful for tests where the test runner
     * already owns the socket cleanup.
     */
    readonly unlinkOnShutdown?: boolean;
    /**
     * Override the Bun runtime resolver. Used by tests to verify the
     * "no-Bun" error path without leaving a Bun-only test environment.
     * Production code reads `globalThis.Bun` directly.
     */
    readonly bunRuntime?: {
        serve: (cfg: unknown) => BunServer;
    } | null;
}
interface UnixSocketServerHandle {
    readonly path: string;
    readonly server: BunServer;
    /** Stop the server AND unlink the socket file (unless `unlinkOnShutdown=false`). */
    shutdown(): Promise<void>;
}

/**
 * Scoring strategies (ADR-111 §4 — three-tier health gate).
 *
 * The default `weightedProduct` strategy is multiplicative — a single bad
 * signal can drag the whole score down (any factor of 0 → score 0). This is
 * the right semantic for **liveness**: one critical subsystem dead means
 * the runtime is not ready, regardless of how healthy the rest is.
 *
 * Mathematics:
 *   score = ∏ factor_i ^ weight_i   (over signals where weight > 0 AND
 *                                    reading is not `unknown`)
 *
 * Where weights are normalised to sum=1 first, so absolute weight values
 * don't matter — only the ratios do. This keeps user expectations sane:
 * `[w=2, w=2]` and `[w=10, w=10]` produce identical scores.
 *
 * Edge cases (deterministic, never throw):
 *   - empty input            → 1 (perfect health, nothing to penalise)
 *   - all weights = 0        → 1 (no active signals)
 *   - all readings `unknown` → 1 (we can't see; cardinal-rule fallback
 *                                  lives at the sidecar boundary, not
 *                                  here — ADR-111 §3.2.5)
 *   - factor < 0 / NaN       → clamped to 0
 *   - factor > 1             → clamped to 1
 *   - weight < 0             → clamped to 0 (ignored)
 *
 * The clamps make us **safe by construction** — a misconfigured signal
 * cannot push the score outside `[0, 1]`. Tests exercise all branches.
 */

/**
 * Weighted geometric mean — the default scoring strategy.
 *
 * @example
 *   weightedProduct([
 *     { signal: { name: 'lag', weight: 0.4 }, reading: { healthFactor: 0.4 } },
 *     { signal: { name: 'q',   weight: 0.6 }, reading: { healthFactor: 1.0 } },
 *   ])
 *   // → 0.4^0.4 × 1.0^0.6 ≈ 0.693 — ADR-111 §4.5 worked example
 */
declare const weightedProduct: ScoringStrategy;
/**
 * Convenience: build a default scoring strategy.
 *
 * Reserved for future: weighted-min, weighted-mean, etc. For now there's
 * one strategy and `weightedProduct` is the only export — this keeps the
 * surface narrow until a concrete second use-case appears.
 */
declare function defaultScoringStrategy(): ScoringStrategy;

/**
 * `errorRateSignal` — request-error-rate over a sliding window (ADR-111 §4.3).
 *
 * Phase B uses an in-memory ring buffer of {timestamp, isError} samples.
 * Phase C will replace this with an OTel collector subscription so the
 * sidecar gets the same data without per-process bookkeeping; for now the
 * in-memory path keeps the SDK self-contained.
 *
 * Mapping observed-rate → healthFactor:
 *
 *      healthFactor
 *           ▲
 *      1.0  ┤━━━━━━━━━━━━━━━━━━━┓
 *           │                   ┃ linear interpolation
 *      0.0  ┤                   ┗━━━━━━━━━━
 *           ┼───────────────────┼────────►  error rate (0..1)
 *           0           degradedRate     deadRate
 *
 * Default thresholds match ADR-111 §4.3 row 3:
 *   degradedRate = 0.05  (5 % errors → degraded)
 *   deadRate     = 0.50  (50 % errors → dead)
 *
 * `recordSuccess()` / `recordError()` are pushed by the app on each
 * request (or wired into Hono / Express middleware — the SDK provides
 * primitives, not framework integrations). Zero-traffic windows produce
 * `factor=1` (no requests = no errors = healthy by convention).
 */

interface ErrorRateOptions {
    /** Sliding window length. Accepts ms (number) or '5s' / '1m' shorthand. */
    readonly window: number | `${number}s` | `${number}m`;
    /** Rate above this is considered degraded. Default 0.05 (5 %). */
    readonly degradedRate?: number;
    /** Rate at which the signal saturates to dead. Default 0.50 (50 %). */
    readonly deadRate?: number;
    /**
     * Soft minimum sample count: until this many samples land, factor=1
     * regardless of rate (avoids "1 error in 1 request → 100 %" panics).
     * Default 10.
     */
    readonly minSamples?: number;
    /** Weight in the weighted-product score. Default 0.2 (ADR-111 §4.3). */
    readonly weight?: number;
    /** Optional injected clock for tests. */
    readonly now?: () => number;
}
interface ErrorRateSignalHandle extends SyncSignal {
    /** Record a successful request (call from app middleware). */
    recordSuccess(): void;
    /** Record a failed request (call from app middleware). */
    recordError(): void;
    /** Erase the window. Useful for tests. */
    reset(): void;
}
declare function errorRateSignal(opts: ErrorRateOptions): ErrorRateSignalHandle;

/**
 * `eventLoopLagSignal` — main-thread blocking detector (ADR-111 §4.3).
 *
 * Measures Node/Bun's libuv event-loop delay using `monitorEventLoopDelay()`
 * from `node:perf_hooks`. The monitor is a histogram updated by libuv at a
 * configurable resolution (default 10 ms here — every tick measures lag
 * between expected wake and actual wake). We report the **max** observed
 * since the last `read()` then `reset()` — that's the worst-case stall
 * the app suffered in the polling window.
 *
 * Mapping observed-lag-ms → healthFactor ∈ [0, 1]:
 *
 *      healthFactor
 *           ▲
 *      1.0  ┤━━━━━━━━━┓
 *           │         ┃ linear interpolation
 *           │         ┃
 *      0.0  ┤         ┗━━━━━━━━━━━━━
 *           ┼─────────┼──────────┼──────►  observed lag (ms)
 *           0    degradedMs    deadMs
 *
 * Below `degradedMs` → factor 1 (healthy). Above `deadMs` → factor 0 (dead).
 * In-between → linear interpolation. ADR-111 §4.3 default thresholds:
 *   degradedMs = 5000  (5 s — same order as ADR-110's 10 s probe timeout)
 *   deadMs     = 30000 (30 s — definitely wedged)
 *
 * Bun-compatibility: Bun ships `monitorEventLoopDelay()` with the same
 * shape as Node 16+. Verified against `bun:1.3` in this repo's CI.
 */

interface EventLoopLagOptions {
    /** Lag below this is fully healthy (factor=1). Default 5000 ms. */
    readonly degradedMs?: number;
    /** Lag above this is fully dead (factor=0). Default 30000 ms. */
    readonly deadMs?: number;
    /**
     * Histogram resolution (ms). Default 10 ms — the smaller, the more
     * accurate the max but the higher the libuv accounting overhead.
     * Node defaults are also 10 ms.
     */
    readonly resolutionMs?: number;
    /** Weight in the weighted-product score. Default 0.4 (ADR-111 §4.3). */
    readonly weight?: number;
    /**
     * Optional injected monitor (tests). Defaults to a fresh
     * `monitorEventLoopDelay()` instance.
     */
    readonly monitor?: ReturnType<typeof monitorEventLoopDelay>;
}
/**
 * Build an `event-loop-lag` signal. The returned object owns a started
 * histogram monitor; call `dispose()` during shutdown / between tests.
 */
declare function eventLoopLagSignal(opts?: EventLoopLagOptions): SyncSignal;

/**
 * `memoryPressureSignal` — RSS / cgroup memory.max ratio (ADR-111 §4.3).
 *
 * On Linux containers we read the cgroup v2 memory limit from
 * `/sys/fs/cgroup/memory.max`. Then `pressure = process.memoryUsage().rss /
 * limit`. ADR-111 §4.3 default thresholds:
 *   degradedRatio = 0.85  (85 % → degraded)
 *   deadRatio     = 0.95  (95 % → dead)
 *
 * Mapping observed-pressure → healthFactor:
 *
 *      healthFactor
 *           ▲
 *      1.0  ┤━━━━━━━━━━━━━━━━━━┓
 *           │                  ┃
 *      0.0  ┤                  ┗━━━━━━━━━
 *           ┼──────────────────┼─────────►  pressure (0..1)
 *           0           degradedRatio    deadRatio
 *
 * Graceful fallback (the cardinal-rule deference):
 *   - cgroup file missing      → unknown=true (signal ignored)
 *   - cgroup file has 'max'    → unlimited container, ratio undefined → unknown
 *   - file unreadable / parse  → unknown=true
 *
 * `unknown=true` makes the scoring strategy ignore the signal — we never
 * pretend to know memory pressure on a host where we can't measure it.
 *
 * cgroup v1 (legacy) lives at `/sys/fs/cgroup/memory/memory.limit_in_bytes`
 * — supported via `cgroupV1Path` for operators on older kernels.
 */

interface MemoryPressureOptions {
    /** Pressure below this is fully healthy (factor=1). Default 0.85. */
    readonly degradedRatio?: number;
    /** Pressure above this is fully dead (factor=0). Default 0.95. */
    readonly deadRatio?: number;
    /**
     * Custom cgroup v2 memory limit path. Default `/sys/fs/cgroup/memory.max`.
     */
    readonly cgroupV2Path?: string;
    /**
     * Optional cgroup v1 fallback path. Default
     * `/sys/fs/cgroup/memory/memory.limit_in_bytes`. Used when v2 path is
     * unreadable AND `cgroupV1Path` is set or v2 doesn't exist.
     */
    readonly cgroupV1Path?: string;
    /** Weight in the weighted-product score. Default 0.2 (ADR-111 §4.3). */
    readonly weight?: number;
    /**
     * Optional injected `process.memoryUsage` for tests.
     * Default: `process.memoryUsage`.
     */
    readonly memoryUsage?: () => {
        rss: number;
    };
    /** Optional injected file reader for tests. */
    readonly readFile?: (path: string) => string;
}
declare function memoryPressureSignal(opts?: MemoryPressureOptions): SyncSignal;

/**
 * `queueDepthSignal` — backpressure indicator (ADR-111 §4.3).
 *
 * Generic signal: the app provides a `getter` that returns the current
 * length of whatever queue the operator wants probed (BullMQ, RabbitMQ,
 * in-memory work pool, …). The signal does NOT own the queue — the app
 * does. We just measure.
 *
 * Mapping observed-depth → healthFactor:
 *
 *      healthFactor
 *           ▲
 *      1.0  ┤━━━━━━━━━━━━━━━━━━┓
 *           │                  ┃ linear interpolation
 *      0.0  ┤                  ┗━━━━━━━━━━━━
 *           ┼──────────────────┼─────────►  depth
 *           0           fullThreshold
 *
 * Below `fullThreshold` → factor 1. At `fullThreshold` → factor 0. Above
 * → factor 0. The implicit "degraded" zone is `[0.5 × fullThreshold,
 * fullThreshold]` — depth at half-full produces factor 0.5. Operators
 * tune `fullThreshold` to whatever their queue reasonably hits at peak
 * load; "100% full" means "drain new traffic", not "kill the workload" (the
 * three-tier gate at the sidecar handles the kill decision).
 *
 * `getter` errors are swallowed — a thrown getter produces `unknown=true`
 * (so the scoring strategy ignores this signal, instead of falsely
 * reporting score=0). The app's bug shouldn't masquerade as a sidecar
 * decision.
 */

interface QueueDepthOptions {
    /**
     * Sync or async getter the SDK calls every poll tick. Must return a
     * non-negative integer. Throws → reading marked `unknown=true`.
     */
    readonly getter: () => number | Promise<number>;
    /**
     * Depth at which the queue is considered "full" (factor=0). Linear
     * interp from 0..fullThreshold. No default — operator-specific.
     */
    readonly fullThreshold: number;
    /**
     * Optional below-which factor is always 1 (a "soft floor"). Default 0
     * — the linear interp starts at depth 0.
     */
    readonly healthyBelow?: number;
    /** Weight in the weighted-product score. Default 0.2 (ADR-111 §4.3). */
    readonly weight?: number;
    /** Custom signal name. Default `queueDepth`. */
    readonly name?: string;
}
declare function queueDepthSignal(opts: QueueDepthOptions): AsyncSignal;

/**
 * `@sylphx/sdk/health` — Phase B multi-signal health score (ADR-111 §4).
 *
 * Apps register signals (event-loop lag, queue depth, error rate, memory
 * pressure, …); the SDK folds them into a continuous score in `[0, 1]`;
 * the **sidecar** maps the score to liveness / readiness / drain via the
 * three-tier gate. The SDK's responsibility ends at exposing the score.
 *
 * The wire format the sidecar parses (ADR-111 §3.2.4):
 *
 * ```json
 * {
 *   "score": 0.92,
 *   "signals": {
 *     "eventLoopLagMs": 12,
 *     "queueDepth": 3,
 *     "recent5sErrorRate": 0.001,
 *     "memoryPressure": 0.45
 *   },
 *   "lastTickAt": "2026-05-03T12:34:56.789Z"
 * }
 * ```
 *
 * Default signals (if `sylphxHealth()` called with no `signals`):
 *   - `eventLoopLagSignal({ degradedMs: 5000, deadMs: 30000 })` (weight 1.0)
 *
 * Three-tier gate (decided by **sidecar**, not SDK; ADR-111 §4.4):
 *
 * | Score          | Liveness | Readiness | Effect                |
 * | -------------- | -------- | --------- | --------------------- |
 * | > 0.8          | 200      | 200       | Normal traffic        |
 * | (0.5, 0.8]     | 200      | 503       | Drain new, no kill    |
 * | <= 0.5         | 503      | 503       | Kill after threshold  |
 *
 * Apps don't need to think about probe semantics — that's the sidecar's
 * job. The app just exposes the score. See `apps/health-agent/` for the
 * sidecar implementation.
 *
 * @example Worked example — OpenClaw under PDF-extract load (ADR-111 §4.5):
 *
 * ```text
 *   eventLoopLagMs = 6000 → factor 0.4
 *   queueDepth = 12       → factor 1.0
 *   errorRate = 0.002     → factor 1.0
 *   memoryPressure = 0.55 → factor 1.0
 *   score = 0.4^0.4 × 1.0^0.6 ≈ 0.69
 *
 *   → falls in [0.5, 0.8] → sidecar drains traffic, doesn't kill.
 *     Pod gets to finish PDF extraction.
 * ```
 */

/**
 * The handle returned by `sylphxHealth()`. Owns the registered signals,
 * exposes evaluation in both Promise + Effect form, and produces an HTTP
 * handler / Unix-socket server.
 *
 * Call `dispose()` during graceful shutdown to release per-signal
 * resources (e.g. the `monitorEventLoopDelay()` histogram).
 */
interface SylphxHealth extends HealthEvaluator {
    /** All signals registered (read-only). */
    readonly signals: ReadonlyArray<Signal>;
    /** Snapshot evaluation as a Promise. */
    evaluate(): Promise<HealthScore>;
    /** Snapshot evaluation as an Effect (per Rule 21 / ADR-058 Amendment). */
    readonly evaluateEffect: ReturnType<typeof evaluateEffect>;
    /**
     * Web Fetch API HTTP handler — works under Hono, Bun.serve, Next.js
     * route.ts, itty-router, Hattip. Always returns 200 + JSON; the
     * sidecar applies the three-tier 200/503 gate.
     */
    handler(): (req?: Request) => Promise<Response>;
    /** Node.js classic `(req, res)` handler — for Express / classic Fastify. */
    nodeHandler(): ReturnType<typeof createNodeHandler>;
    /**
     * Bind a Bun Unix-domain socket and serve the same JSON. The sidecar
     * polls `/var/run/sylphx/health.sock` by default (ADR-111 §3.2.4).
     */
    serveUnixSocket(opts?: UnixSocketServerOptions): UnixSocketServerHandle;
    /**
     * Tear down all registered signals. Idempotent. Call during graceful
     * shutdown to release histograms, file watchers, etc.
     */
    dispose(): void;
}
/**
 * Build a `SylphxHealth` instance.
 *
 * @example Hono integration:
 * ```ts
 * import { Hono } from 'hono'
 * import {
 *   sylphxHealth,
 *   eventLoopLagSignal,
 *   queueDepthSignal,
 *   errorRateSignal,
 *   memoryPressureSignal,
 * } from '@sylphx/sdk/health'
 *
 * const errors = errorRateSignal({ window: '5s', degradedRate: 0.05 })
 *
 * const health = sylphxHealth({
 *   signals: [
 *     eventLoopLagSignal({ degradedMs: 5000, deadMs: 30000 }),
 *     queueDepthSignal({ getter: () => queue.size, fullThreshold: 1000 }),
 *     errors,
 *     memoryPressureSignal({ degradedRatio: 0.85 }),
 *   ],
 * })
 *
 * const app = new Hono()
 * app.get('/healthz', health.handler())
 *
 * // Track requests for the error-rate signal
 * app.use(async (c, next) => {
 *   try { await next(); errors.recordSuccess() }
 *   catch (err) { errors.recordError(); throw err }
 * })
 *
 * // Or — primary transport for the sidecar:
 * health.serveUnixSocket() // → /var/run/sylphx/health.sock
 * ```
 *
 * @example Worked example — OpenClaw under PDF-extract load (ADR-111 §4.5):
 *
 * ```text
 *   eventLoopLagMs = 6000 → factor 0.4
 *   queueDepth = 12       → factor 1.0
 *   errorRate = 0.002     → factor 1.0
 *   memoryPressure = 0.55 → factor 1.0
 *   score = 0.4^0.4 × 1.0^0.6 ≈ 0.69
 *
 *   → falls in [0.5, 0.8] → sidecar drains traffic, doesn't kill.
 *     Pod gets to finish PDF extraction.
 * ```
 */
declare function sylphxHealth(opts?: SylphxHealthOptions): SylphxHealth;

export { type AsyncSignal, type ErrorRateOptions, type ErrorRateSignalHandle, type EventLoopLagOptions, HealthError, type HealthEvaluator, type HealthScore, type HealthSnapshot, type MemoryPressureOptions, type QueueDepthOptions, type ScoringStrategy, type Signal, type SignalBase, type SignalReading, type SylphxHealth, type SylphxHealthOptions, type SyncSignal, type UnixSocketServerHandle, type UnixSocketServerOptions, createNodeHandler, createWebHandler, defaultScoringStrategy, errorRateSignal, eventLoopLagSignal, memoryPressureSignal, queueDepthSignal, sylphxHealth, weightedProduct };
