diff --git a/pm-stack/exporters/README.md b/pm-stack/exporters/README.md new file mode 100644 index 000000000..5acac95ca --- /dev/null +++ b/pm-stack/exporters/README.md @@ -0,0 +1,57 @@ +# pm-stack/exporters — browser-dependent quota sources (#6032, design #6031) + +Producers and the watchdog core for quota sources whose data is only +reachable through a logged-in website (Mistral first; Claude console and +Open Design are named later adopters). The design lives in #6031; the +core implementation is #6032. + +## What is here today + +`src/watchdog-state.ts` — the **decision layer** of the watchdog core: + +- the failure-class vocabulary (`session-expired`, `cookie-missing`, + `endpoint-changed`, `browser-down`, `cdp-unreachable`, `rate-limited`, + `unknown`) and the one place a class maps to a repair rung; +- the repair ladder decision (`decide`) with per-rung attempt caps + (`MAX_ATTEMPTS_PER_RUNG`), a disk-honored rate-limit cooldown, and + escalation once every rung is spent; +- the persisted per-source health record (`SourceHealth`) with a bounded + repair log, and `coerceHealth` for reading a state file back without + trusting it; +- `sanitizeDetail`, which strips credential-shaped text before anything + reaches the state file or a log. + +It is pure: no I/O, no browser, no secrets, no provider names. That is +deliberate — the ladder is the part worth testing exhaustively, and the +testing doctrine (AGENTS.md) asks for property- and model-based coverage +of exactly this kind of state machine. + +`test/watchdog-state.test.ts` names its oracles: PBT invariants over +generated tick sequences (attempt caps, log bound, monotonic failure +counts, cooldown honored, no secret survives), an MBT reference model of +the ladder stepped in lockstep with the implementation, and the four +acceptance fixtures (broken-source walk, rate-limited cooldown, human +challenge, quiet-when-healthy). + +Run them: + +```bash +cd pm-stack/aggregator && bun test ../exporters/test/watchdog-state.test.ts +``` + +## What is NOT here yet (#6032 remainder) + +- `src/watchdog.ts` — the oneshot entry point: read the state file, read + each source's `~/atlas/-export/latest.json` plus the gatherer + heartbeat, classify, call `decide`, run the chosen rung, write the state + file atomically (tmp+rename), append `quota-watchdog-history.jsonl`. +- `src/adapters.ts` — the adapter loader (origins allowlist, CDP port, + data-path order, cookie names, login hints, class map, thresholds) and + `adapters/` itself. +- The repair executors for rungs 2 and 3 (CDP session re-validation, + browser re-login driver), which stop dead at a human-only challenge and + hand off to `recordRungOutcome`. +- The rung-4 escalation hand-off (contract owned by #6033). +- Producer scaffolding under `pm-stack/exporters/` from the retired Meta + producer pattern, and the gatherer `FILE_EXPORTS` registration. +- `pm-stack/systemd/` oneshot + timer units on the gatherer cadence. diff --git a/pm-stack/exporters/src/watchdog-state.ts b/pm-stack/exporters/src/watchdog-state.ts new file mode 100644 index 000000000..d5e8a30c0 --- /dev/null +++ b/pm-stack/exporters/src/watchdog-state.ts @@ -0,0 +1,415 @@ +// Generic browser-dependent quota watchdog core — state machine (#6032, +// design #6031). +// +// This module is the DECISION layer only: pure functions that turn a +// per-source observation into the next persisted health record and name +// the repair rung to attempt. It performs no I/O, spawns no browser, and +// reads no secrets — the oneshot entry point (watchdog.ts) owns disk and +// side effects, and the adapter loader owns provider specifics. Keeping +// the decision layer pure is what makes the ladder testable with +// property- and model-based tests (testing doctrine, AGENTS.md). +// +// The lesson from code#5928 is structural here: every decision-relevant +// value (consecutive failure count, cooldown deadline, per-rung attempt +// counts, incident identity) lives in the record that is written to disk +// each tick. Nothing is cached in process memory, because the watchdog is +// a oneshot and the next tick is a fresh process. + +/** Failure classes the watchdog can diagnose (#6031 health model). */ +export type FailureClass = + | "session-expired" + | "cookie-missing" + | "endpoint-changed" + | "browser-down" + | "cdp-unreachable" + | "rate-limited" + | "unknown"; + +export const FAILURE_CLASSES: readonly FailureClass[] = [ + "session-expired", + "cookie-missing", + "endpoint-changed", + "browser-down", + "cdp-unreachable", + "rate-limited", + "unknown", +]; + +/** Repair rungs, cheapest first. Rung 4 (escalation) is #6033's contract. */ +export type Rung = 0 | 1 | 2 | 3; + +export const RUNGS: readonly Rung[] = [0, 1, 2, 3]; + +/** Max attempts per rung per incident (design + acceptance criteria). */ +export const MAX_ATTEMPTS_PER_RUNG = 2; + +/** Repair log is bounded so the state file cannot grow without limit. */ +export const REPAIR_LOG_LIMIT = 20; + +/** One line of the persisted repair log. */ +export interface RepairLogEntry { + at: string; + rung: Rung; + outcome: "attempted" | "succeeded" | "failed" | "skipped"; + detail: string; +} + +/** One source's health record. This is what is written to disk per tick. */ +export interface SourceHealth { + source: string; + lastAttemptAt: string | null; + lastSuccessAt: string | null; + consecutiveFailures: number; + currentClass: FailureClass | null; + /** Sanitized — never a secret value, cookie, or token. */ + lastDetail: string; + /** ISO deadline before which no browser action is taken (rate-limited). */ + cooldownUntil: string | null; + /** Attempts spent per rung in the CURRENT incident. Reset on success. */ + rungAttempts: Record; + repairLog: RepairLogEntry[]; + /** Incident identity, or null when healthy. */ + incident: Incident | null; +} + +export interface Incident { + /** Stable id: `:` — dedupe key for the GitHub issue. */ + id: string; + openedAt: string; + /** Set when a human-only challenge stops the ladder dead. */ + humanBlocked: boolean; + /** Surfacing flag the stewardship/orchestration sweeps read. */ + surfacing: "none" | "human-blocked" | "escalate"; +} + +/** What one tick saw for one source. */ +export type Observation = + | { kind: "healthy"; at: string; detail?: string } + | { kind: "failed"; at: string; class: FailureClass; detail?: string }; + +/** What the ladder says to do this tick. */ +export type Decision = + | { action: "quiet" } + | { action: "wait-cooldown"; until: string } + | { action: "retry" } + | { action: "repair"; rung: Rung } + | { action: "human-blocked" } + | { action: "escalate" }; + +/** Fresh record for a source the watchdog has not seen before. */ +export function initialHealth(source: string): SourceHealth { + return { + source, + lastAttemptAt: null, + lastSuccessAt: null, + consecutiveFailures: 0, + currentClass: null, + lastDetail: "", + cooldownUntil: null, + rungAttempts: { 0: 0, 1: 0, 2: 0, 3: 0 }, + repairLog: [], + incident: null, + }; +} + +/** Strip anything that could carry a secret out of a free-text detail. */ +export function sanitizeDetail(detail: string | undefined): string { + if (!detail) return ""; + // Collapse whitespace and cap length; drop obvious credential shapes. + const collapsed = detail.replace(/\s+/g, " ").trim(); + const redacted = collapsed + .replace(/(cookie|authorization|token|bearer|session|password|secret)\s*[:=]\s*\S+/gi, "$1=") + .replace(/[A-Za-z0-9_-]{32,}/g, ""); + return redacted.slice(0, 500); +} + +function appendLog(log: RepairLogEntry[], entry: RepairLogEntry): RepairLogEntry[] { + const next = [...log, entry]; + return next.length > REPAIR_LOG_LIMIT ? next.slice(next.length - REPAIR_LOG_LIMIT) : next; +} + +function ms(iso: string): number { + const t = Date.parse(iso); + return Number.isFinite(t) ? t : NaN; +} + +/** + * The ONE place a failure class maps to its repair rung. Adapters may + * override via their class map, but the core default is here and it + * contains no provider names. + */ +export function defaultRungFor(cls: FailureClass): Rung { + switch (cls) { + case "rate-limited": + return 0; // cooldown on disk; no browser action + case "browser-down": + case "cdp-unreachable": + return 2; // re-validate the CDP session / bring the browser back + case "session-expired": + case "cookie-missing": + return 3; // re-login via the standing SSO session + case "endpoint-changed": + return 1; // retry next tick; a changed endpoint is often transient + case "unknown": + return 1; + } +} + +function rungExhausted(h: SourceHealth, rung: Rung): boolean { + return (h.rungAttempts[rung] ?? 0) >= MAX_ATTEMPTS_PER_RUNG; +} + +/** + * Decide what this tick should do, given the persisted record and the + * fresh observation. Pure: same inputs always produce the same decision + * and the same next record. + */ +export function decide( + health: SourceHealth, + obs: Observation, + opts: { classMap?: Partial>; cooldownMs?: number } = {}, +): { decision: Decision; next: SourceHealth } { + const at = obs.at; + const classMap = opts.classMap ?? {}; + const cooldownMs = opts.cooldownMs ?? 15 * 60_000; + + // --- healthy tick: quiet, clear the incident, reset per-rung counts --- + if (obs.kind === "healthy") { + const next: SourceHealth = { + ...health, + lastAttemptAt: at, + lastSuccessAt: at, + consecutiveFailures: 0, + currentClass: null, + lastDetail: sanitizeDetail(obs.detail), + cooldownUntil: null, + rungAttempts: { 0: 0, 1: 0, 2: 0, 3: 0 }, + repairLog: + health.incident === null + ? health.repairLog + : appendLog(health.repairLog, { + at, + rung: 1, + outcome: "succeeded", + detail: "source recovered; incident closed", + }), + incident: null, + }; + return { decision: { action: "quiet" }, next }; + } + + // --- failure tick --- + const cls = obs.class; + const consecutiveFailures = health.consecutiveFailures + 1; + const incident: Incident = + health.incident ?? { + id: `${health.source}:${at}`, + openedAt: at, + humanBlocked: false, + surfacing: "none", + }; + + // A human-blocked incident stays blocked until a human clears it or the + // source recovers — the ladder must not hammer a login challenge. + if (incident.humanBlocked) { + const next: SourceHealth = { + ...health, + lastAttemptAt: at, + consecutiveFailures, + currentClass: cls, + lastDetail: sanitizeDetail(obs.detail), + incident, + }; + return { decision: { action: "human-blocked" }, next }; + } + + // Rung 0: a persisted cooldown is honored without any browser action. + if (health.cooldownUntil !== null) { + const until = ms(health.cooldownUntil); + const now = ms(at); + if (Number.isFinite(until) && Number.isFinite(now) && now < until) { + const next: SourceHealth = { + ...health, + lastAttemptAt: at, + consecutiveFailures, + currentClass: cls, + lastDetail: sanitizeDetail(obs.detail), + incident, + }; + return { decision: { action: "wait-cooldown", until: health.cooldownUntil }, next }; + } + } + + const desired = classMap[cls] ?? defaultRungFor(cls); + + // A rate limit whose cooldown rung is spent does not climb to browser + // repairs — the provider is still refusing us; escalate instead. + let rung: Rung | null = null; + if (desired === 0 && rungExhausted(health, 0)) { + rung = null; + } else { + for (let r = desired; r <= 3; r++) { + if (!rungExhausted(health, r as Rung)) { + rung = r as Rung; + break; + } + } + } + + if (rung === null) { + const next: SourceHealth = { + ...health, + lastAttemptAt: at, + consecutiveFailures, + currentClass: cls, + lastDetail: sanitizeDetail(obs.detail), + incident: { ...incident, surfacing: "escalate" }, + repairLog: appendLog(health.repairLog, { + at, + rung: 3, + outcome: "failed", + detail: "all rungs exhausted; escalating", + }), + }; + return { decision: { action: "escalate" }, next }; + } + + // Rung 0 is the cooldown rung: set the deadline on disk and take no + // browser action this tick. + if (rung === 0) { + const now = ms(at); + const untilIso = Number.isFinite(now) ? new Date(now + cooldownMs).toISOString() : null; + const next: SourceHealth = { + ...health, + lastAttemptAt: at, + consecutiveFailures, + currentClass: cls, + lastDetail: sanitizeDetail(obs.detail), + cooldownUntil: untilIso, + rungAttempts: { ...health.rungAttempts, 0: (health.rungAttempts[0] ?? 0) + 1 }, + incident, + repairLog: appendLog(health.repairLog, { + at, + rung: 0, + outcome: "attempted", + detail: `rate-limited; cooldown until ${untilIso ?? "unknown"}`, + }), + }; + return { decision: { action: "wait-cooldown", until: untilIso ?? "" }, next }; + } + + const next: SourceHealth = { + ...health, + lastAttemptAt: at, + consecutiveFailures, + currentClass: cls, + lastDetail: sanitizeDetail(obs.detail), + cooldownUntil: null, + rungAttempts: { ...health.rungAttempts, [rung]: (health.rungAttempts[rung] ?? 0) + 1 }, + incident, + repairLog: appendLog(health.repairLog, { + at, + rung, + outcome: "attempted", + detail: `${cls}; attempting rung ${rung}`, + }), + }; + return { decision: { action: rung === 1 ? "retry" : "repair", rung }, next }; +} + +/** + * Record the outcome of the rung the previous tick chose. Called by the + * entry point after it actually ran (or refused) the repair, so the log + * reflects reality rather than intent. + */ +export function recordRungOutcome( + health: SourceHealth, + at: string, + rung: Rung, + outcome: "succeeded" | "failed" | "skipped", + detail: string, +): SourceHealth { + const incident = health.incident; + // A human-only challenge stops the ladder dead and surfaces immediately. + const humanBlocked = outcome === "failed" && /human[- ]only|2fa|passkey|verify[- ]it/i.test(detail); + return { + ...health, + incident: + incident === null + ? null + : humanBlocked + ? { ...incident, humanBlocked: true, surfacing: "human-blocked" } + : incident, + repairLog: appendLog(health.repairLog, { + at, + rung, + outcome, + detail: sanitizeDetail(detail), + }), + }; +} + +/** The whole state file: one record per source. */ +export interface WatchdogState { + version: 1; + updatedAt: string; + sources: Record; +} + +export function emptyState(now: string): WatchdogState { + return { version: 1, updatedAt: now, sources: {} }; +} + +/** + * Structural validation of a state file read back from disk. A corrupt + * or older file must not crash the tick: unknown shapes yield a fresh + * record for that source rather than a thrown error (fail open to + * "re-observe", never to "assume healthy"). + */ +export function coerceHealth(source: string, raw: unknown): SourceHealth { + const base = initialHealth(source); + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return base; + const r = raw as Record; + const num = (v: unknown, d: number) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : d); + const str = (v: unknown) => (typeof v === "string" ? v : null); + const cls = FAILURE_CLASSES.includes(r.currentClass as FailureClass) ? (r.currentClass as FailureClass) : null; + const attemptsRaw = (r.rungAttempts ?? {}) as Record; + const attempts = { 0: 0, 1: 0, 2: 0, 3: 0 } as Record; + for (const rung of RUNGS) attempts[rung] = num(attemptsRaw[String(rung)], 0); + const logRaw = Array.isArray(r.repairLog) ? r.repairLog : []; + const repairLog: RepairLogEntry[] = logRaw + .filter((e): e is Record => typeof e === "object" && e !== null) + .map((e) => ({ + at: typeof e.at === "string" ? e.at : "", + rung: (RUNGS.includes(e.rung as Rung) ? e.rung : 0) as Rung, + outcome: (["attempted", "succeeded", "failed", "skipped"].includes(e.outcome as string) + ? e.outcome + : "skipped") as RepairLogEntry["outcome"], + detail: sanitizeDetail(typeof e.detail === "string" ? e.detail : ""), + })) + .slice(-REPAIR_LOG_LIMIT); + const incidentRaw = r.incident as Record | null | undefined; + const incident: Incident | null = + typeof incidentRaw === "object" && incidentRaw !== null && typeof incidentRaw.id === "string" + ? { + id: incidentRaw.id, + openedAt: typeof incidentRaw.openedAt === "string" ? incidentRaw.openedAt : "", + humanBlocked: incidentRaw.humanBlocked === true, + surfacing: (["none", "human-blocked", "escalate"].includes(incidentRaw.surfacing as string) + ? incidentRaw.surfacing + : "none") as Incident["surfacing"], + } + : null; + return { + source, + lastAttemptAt: str(r.lastAttemptAt), + lastSuccessAt: str(r.lastSuccessAt), + consecutiveFailures: num(r.consecutiveFailures, 0), + currentClass: cls, + lastDetail: sanitizeDetail(typeof r.lastDetail === "string" ? r.lastDetail : ""), + cooldownUntil: str(r.cooldownUntil), + rungAttempts: attempts, + repairLog, + incident, + }; +} diff --git a/pm-stack/exporters/test/watchdog-state.test.ts b/pm-stack/exporters/test/watchdog-state.test.ts new file mode 100644 index 000000000..4c879d3d0 --- /dev/null +++ b/pm-stack/exporters/test/watchdog-state.test.ts @@ -0,0 +1,257 @@ +// Tests for the quota-watchdog state machine (#6032, design #6031). +// +// Oracles, named per the testing doctrine (AGENTS.md): +// - PBT invariants: properties that must hold for EVERY observation +// sequence (attempt caps, log bound, monotonic failure counts, +// cooldown honored, no secret survives sanitization). +// - MBT: a small reference model of the ladder, stepped in lockstep with +// the implementation over generated tick sequences; any divergence in +// decision or in the decision-relevant fields is a failure. +// - Example tests: the four fixtures the acceptance criteria name +// (broken-source walk, rate-limited cooldown, human challenge, quiet +// when healthy). +import { describe, expect, test } from "bun:test"; +import { + FAILURE_CLASSES, + MAX_ATTEMPTS_PER_RUNG, + REPAIR_LOG_LIMIT, + RUNGS, + type FailureClass, + type Observation, + type Rung, + type SourceHealth, + type Decision, + coerceHealth, + decide, + initialHealth, + recordRungOutcome, + sanitizeDetail, +} from "../src/watchdog-state.ts"; + +const T0 = Date.parse("2026-11-08T00:00:00Z"); +const iso = (min: number) => new Date(T0 + min * 60_000).toISOString(); + +// --- tiny deterministic PRNG so a failing case is reproducible ----------- +function rng(seed: number) { + let s = seed >>> 0; + return () => { + s = (s * 1664525 + 1013904223) >>> 0; + return s / 0x100000000; + }; +} + +function genObs(r: () => number, at: string): Observation { + if (r() < 0.35) return { kind: "healthy", at }; + const cls = FAILURE_CLASSES[Math.floor(r() * FAILURE_CLASSES.length)]!; + return { kind: "failed", at, class: cls, detail: r() < 0.2 ? "cookie: abc123" : "probe" }; +} + +function runSequence(seed: number, ticks: number) { + const r = rng(seed); + let h: SourceHealth = initialHealth("fixture"); + const decisions: string[] = []; + for (let i = 0; i < ticks; i++) { + const at = iso(i * 15); + const { decision, next } = decide(h, genObs(r, at)); + decisions.push(decision.action); + h = next; + } + return { health: h, decisions }; +} + +describe("watchdog-state: PBT invariants", () => { + test("per-rung attempts never exceed the cap within one incident", () => { + for (let seed = 1; seed <= 200; seed++) { + const r = rng(seed); + let h = initialHealth("fixture"); + for (let i = 0; i < 40; i++) { + h = decide(h, genObs(r, iso(i * 15))).next; + for (const rung of RUNGS) { + expect(h.rungAttempts[rung]).toBeLessThanOrEqual(MAX_ATTEMPTS_PER_RUNG); + } + } + } + }); + + test("repair log stays bounded", () => { + for (let seed = 1; seed <= 200; seed++) { + const { health } = runSequence(seed, 60); + expect(health.repairLog.length).toBeLessThanOrEqual(REPAIR_LOG_LIMIT); + } + }); + + test("consecutiveFailures is monotonic while failing and resets on success", () => { + for (let seed = 1; seed <= 100; seed++) { + const r = rng(seed); + let h = initialHealth("fixture"); + let prev = 0; + for (let i = 0; i < 40; i++) { + const obs = genObs(r, iso(i * 15)); + h = decide(h, obs).next; + if (obs.kind === "healthy") expect(h.consecutiveFailures).toBe(0); + else expect(h.consecutiveFailures).toBe(prev + 1); + prev = h.consecutiveFailures; + } + } + }); + + test("a healthy tick always clears the incident and is quiet", () => { + for (let seed = 1; seed <= 100; seed++) { + const r = rng(seed); + let h = initialHealth("fixture"); + for (let i = 0; i < 30; i++) { + const obs = genObs(r, iso(i * 15)); + const out = decide(h, obs); + if (obs.kind === "healthy") { + expect(out.decision.action).toBe("quiet"); + expect(out.next.incident).toBeNull(); + expect(out.next.cooldownUntil).toBeNull(); + } + h = out.next; + } + } + }); + + test("no secret-shaped value survives sanitization", () => { + for (let seed = 1; seed <= 100; seed++) { + const { health } = runSequence(seed, 40); + expect(health.lastDetail).not.toMatch(/abc123/); + for (const entry of health.repairLog) { + expect(entry.detail).not.toMatch(/abc123/); + } + } + }); +}); + +// --- MBT: reference model of the ladder ---------------------------------- +// +// The model holds only what the ladder decides from: failure count, the +// per-rung attempt counts, and whether a cooldown is live. It is written +// independently of the implementation so agreement is meaningful. +function modelStep( + m: { fails: number; attempts: Record; cooldownUntil: number | null }, + obs: Observation, +): { action: Decision["action"]; rung?: Rung } { + if (obs.kind === "healthy") { + m.fails = 0; + m.attempts = { 0: 0, 1: 0, 2: 0, 3: 0 }; + m.cooldownUntil = null; + return { action: "quiet" }; + } + m.fails += 1; + const now = Date.parse(obs.at); + if (m.cooldownUntil !== null && now < m.cooldownUntil) return { action: "wait-cooldown" }; + const desired: Rung = + obs.class === "rate-limited" ? 0 : obs.class === "endpoint-changed" || obs.class === "unknown" ? 1 : obs.class === "browser-down" || obs.class === "cdp-unreachable" ? 2 : 3; + let rung: Rung | null = null; + if (desired === 0 && m.attempts[0] >= MAX_ATTEMPTS_PER_RUNG) return { action: "escalate" }; + for (let r = desired; r <= 3; r++) if (m.attempts[r as Rung] < MAX_ATTEMPTS_PER_RUNG) { rung = r as Rung; break; } + if (rung === null) return { action: "escalate" }; + m.attempts[rung] += 1; + if (rung === 0) { + m.cooldownUntil = now + 15 * 60_000; + return { action: "wait-cooldown", rung }; + } + return { action: rung === 1 ? "retry" : "repair", rung }; +} + +describe("watchdog-state: MBT against the reference ladder model", () => { + test("implementation agrees with the model on every tick", () => { + for (let seed = 1; seed <= 300; seed++) { + const r = rng(seed); + let h = initialHealth("fixture"); + const m = { fails: 0, attempts: { 0: 0, 1: 0, 2: 0, 3: 0 } as Record, cooldownUntil: null as number | null }; + for (let i = 0; i < 40; i++) { + const obs = genObs(r, iso(i * 15)); + const expected = modelStep(m, obs); + const actual = decide(h, obs); + expect(actual.decision.action).toBe(expected.action); + if ( + expected.rung !== undefined && + expected.rung !== 0 && + actual.decision.action !== "quiet" && + actual.decision.action !== "human-blocked" + ) { + expect((actual.decision as { rung?: Rung }).rung).toBe(expected.rung); + } + expect(actual.next.consecutiveFailures).toBe(m.fails); + h = actual.next; + } + } + }); +}); + +// --- Fixtures named by the acceptance criteria --------------------------- + +describe("watchdog-state: acceptance fixtures", () => { + test("broken source walks retry -> CDP re-validation -> re-login -> escalation", () => { + let h = initialHealth("broken"); + const seen: string[] = []; + for (let i = 0; i < 20; i++) { + const { decision, next } = decide(h, { kind: "failed", at: iso(i * 15), class: "session-expired" }); + if (decision.action === "repair") seen.push(`rung${decision.rung}`); + else seen.push(decision.action); + h = next; + } + // desired rung for session-expired is 3; two attempts then escalate. + expect(seen.filter((s) => s === "rung3").length).toBe(MAX_ATTEMPTS_PER_RUNG); + expect(seen).toContain("escalate"); + expect(h.incident?.surfacing).toBe("escalate"); + }); + + test("rate-limited sets cooldownUntil on disk and the next tick honors it without browser action", () => { + const first = decide(initialHealth("rl"), { kind: "failed", at: iso(0), class: "rate-limited" }); + expect(first.decision.action).toBe("wait-cooldown"); + expect(first.next.cooldownUntil).toBe(iso(15)); + const second = decide(first.next, { kind: "failed", at: iso(5), class: "rate-limited" }); + expect(second.decision).toEqual({ action: "wait-cooldown", until: iso(15) }); + // No rung beyond 0 was spent while cooling down. + expect(second.next.rungAttempts[2]).toBe(0); + expect(second.next.rungAttempts[3]).toBe(0); + // Cooldown expiry resumes the ladder. + const third = decide(second.next, { kind: "failed", at: iso(16), class: "rate-limited" }); + expect(third.decision.action).toBe("wait-cooldown"); // rung 0 again (attempt 2) + const fourth = decide(third.next, { kind: "failed", at: iso(40), class: "rate-limited" }); + expect(fourth.decision.action).toBe("escalate"); // rung 0 exhausted -> escalate + }); + + test("human-only challenge marks the incident human-blocked and surfaces", () => { + const first = decide(initialHealth("human"), { kind: "failed", at: iso(0), class: "session-expired" }); + expect(first.decision.action).toBe("repair"); + const blocked = recordRungOutcome(first.next, iso(0), 3, "failed", "human-only challenge: verify it's you"); + expect(blocked.incident?.humanBlocked).toBe(true); + expect(blocked.incident?.surfacing).toBe("human-blocked"); + // Subsequent ticks do not hammer the challenge. + const again = decide(blocked, { kind: "failed", at: iso(15), class: "session-expired" }); + expect(again.decision.action).toBe("human-blocked"); + }); + + test("quiet when healthy: no rung, no incident, no cooldown", () => { + const { decision, next } = decide(initialHealth("ok"), { kind: "healthy", at: iso(0) }); + expect(decision.action).toBe("quiet"); + expect(next.incident).toBeNull(); + expect(next.currentClass).toBeNull(); + expect(Object.values(next.rungAttempts).every((n) => n === 0)).toBe(true); + }); +}); + +describe("watchdog-state: disk round-trip", () => { + test("coerceHealth restores the decision-relevant fields and survives garbage", () => { + const h = decide(initialHealth("rl"), { kind: "failed", at: iso(0), class: "rate-limited" }).next; + const back = coerceHealth("rl", JSON.parse(JSON.stringify(h))); + expect(back.cooldownUntil).toBe(h.cooldownUntil); + expect(back.rungAttempts).toEqual(h.rungAttempts); + expect(back.consecutiveFailures).toBe(1); + // Garbage never throws; it yields a fresh record. + const fresh = coerceHealth("x", { rungAttempts: "nope", repairLog: [1, 2], incident: { id: 5 } }); + expect(fresh.rungAttempts).toEqual({ 0: 0, 1: 0, 2: 0, 3: 0 }); + expect(fresh.incident).toBeNull(); + }); + + test("sanitizeDetail redacts credential-shaped text", () => { + expect(sanitizeDetail("cookie: abcdef")).toBe("cookie="); + expect(sanitizeDetail("token=deadbeef")).toBe("token="); + expect(sanitizeDetail("x".repeat(600)).length).toBeLessThanOrEqual(500); + expect(sanitizeDetail("a b c").length).toBe(5); + }); +});