From da589766432b0dda1bce8f51c9413e1d8e4532a3 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Tue, 17 Nov 2026 04:58:44 -0600 Subject: [PATCH] =?UTF-8?q?feat(pm-stack):=20quota=20watchdog=20core=20?= =?UTF-8?q?=E2=80=94=20oneshot=20entry=20point,=20adapter=20loader,=20rung?= =?UTF-8?q?=202/3=20executors,=20producer=20template,=20systemd=20timer=20?= =?UTF-8?q?(#6032)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pm-stack/exporters/README.md | 85 ++- pm-stack/exporters/adapters/fixture.json | 1 + .../exporters/producers/producer-template.mjs | 153 +++++ pm-stack/exporters/src/adapters.ts | 188 ++++++ pm-stack/exporters/src/watchdog.ts | 635 ++++++++++++++++++ .../test/fixtures/fixture-producer.mjs | 61 ++ pm-stack/exporters/test/watchdog.test.ts | 269 ++++++++ pm-stack/systemd/pm-quota-watchdog.service | 12 + pm-stack/systemd/pm-quota-watchdog.timer | 11 + 9 files changed, 1397 insertions(+), 18 deletions(-) create mode 100644 pm-stack/exporters/adapters/fixture.json create mode 100644 pm-stack/exporters/producers/producer-template.mjs create mode 100644 pm-stack/exporters/src/adapters.ts create mode 100644 pm-stack/exporters/src/watchdog.ts create mode 100644 pm-stack/exporters/test/fixtures/fixture-producer.mjs create mode 100644 pm-stack/exporters/test/watchdog.test.ts create mode 100644 pm-stack/systemd/pm-quota-watchdog.service create mode 100644 pm-stack/systemd/pm-quota-watchdog.timer diff --git a/pm-stack/exporters/README.md b/pm-stack/exporters/README.md index 99124d57c0..ff08cad34b 100644 --- a/pm-stack/exporters/README.md +++ b/pm-stack/exporters/README.md @@ -26,6 +26,64 @@ 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. +`src/watchdog-escalation.ts` — the **rung-4 hand-off** (#6033): plans the +deduped queue-task + incident-issue effects behind injected effectors, +records the refs on the incident, plans recovery (comment + close + +complete), and renders the NEEDS DREW surfacing line (immediate when +human-blocked, after 24 h unresolved otherwise). + +`src/adapters.ts` + `adapters/` — the **adapter loader**. An adapter is a +per-provider JSON file (origins allowlist, CDP port, producer document +path and/or gatherer heartbeat key, cookie names — names only, login +hints, class/rung map overrides, thresholds, owning repo). The loader +validates structurally and reports defects per file instead of throwing: +a broken adapter degrades to "that source is unobserved", never to a +crashed tick. `adapters/fixture.json` is the synthetic adapter the +acceptance tests and demos run on; real provider adapters are follow-ons +(Mistral's is the openchamber-side follow-on named in #6032). + +`src/watchdog.ts` — the **oneshot entry point**. One tick: load adapters, +read the state file back through `coerceHealth`, observe each source +(producer document + gatherer heartbeat + a live CDP liveness probe), +classify — including the classes the producer cannot see itself (missing +document, stale read while the browser lives, dead CDP endpoint) — call +`decide`, execute the chosen rung, run rung-4 escalation/recovery effects, +write the state file back atomically (tmp+rename), and append one line per +source to `quota-watchdog-history.jsonl`. Nothing decision-relevant lives +in process memory (#5928). Rung executors: + +- rung 2 — CDP session re-validation: `/json/version` + `/json/list`, an + allowlist origin open, adapter cookies present **by name** via the CDP + websocket (values never enter the process); a dead endpoint gets one + bounded supervised restart of the adapter's browser unit; +- rung 3 — re-login driver: opens the adapter's login URL (allowlist + origins only), stops dead at a human-only challenge marker and marks + the incident human-blocked via `recordRungOutcome`, otherwise confirms + the session by cookie presence. + +Browser repairs run only with `QUOTA_WATCHDOG_LIVE_REPAIRS=1` and the +rung-4 production effectors (fleet queue enqueue / `gh`) only with +`QUOTA_WATCHDOG_LIVE=1`; without them the tick journals its plans as dry +runs and creates nothing. The systemd unit sets both. + +`producers/producer-template.mjs` — the forkable producer scaffold +distilled from the retired Meta producer: timeout-bounded CDP plumbing, +tab ownership (a producer closes only tabs it created), failure-class +exit codes with a written failure document, atomic `latest.json` + +`history.jsonl`. Registering a fork with the gatherer means adding its +document to the aggregator's file-export inputs (`FILE_EXPORTS` in the +pm-aggregator package); the watchdog watches the document directly either +way. `test/fixtures/fixture-producer.mjs` is the scenario-driven stub the +acceptance tests use in place of a browser producer. + +`../systemd/pm-quota-watchdog.service` + `.timer` — the oneshot + timer, +on the gatherer's 15-minute rhythm offset to `*:3/15` so each tick judges +fresh producer documents. Installed on the laptop as user units; the +service runs this directory as deployed under `~/pm-stack/exporters/` +with adapters from `~/.config/quota-watchdog/adapters/`. + +## Tests + `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 @@ -33,25 +91,16 @@ the ladder stepped in lockstep with the implementation, and the four acceptance fixtures (broken-source walk, rate-limited cooldown, human challenge, quiet-when-healthy). +`test/watchdog.test.ts` covers the entry point end to end against a +scratch tree: the same four acceptance fixtures driven through `runTick` +(the ladder walk escalates exactly once and dedupes on later ticks; +recovery comments/closes/completes the hand-off), cross-invocation +persistence (every tick re-reads the state file from disk — the #5928 +oracle), the classification of missing-document / stale-read / dead-CDP +observations, and the adapter loader's defect handling. + Run them: ```bash -cd pm-stack/aggregator && bun test ../exporters/test/watchdog-state.test.ts +cd pm-stack/aggregator && bun test ../exporters/test/ ``` - -## 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 module (#6033): plans the deduped queue-task + incident-issue effects behind injected effectors, records the refs on the incident, plans recovery (comment + close + complete), and renders the NEEDS DREW surfacing line (immediate when human-blocked, after 24 h unresolved otherwise). Production effectors (fleet CLI / gh) are wired by the entry point below. -- 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/adapters/fixture.json b/pm-stack/exporters/adapters/fixture.json new file mode 100644 index 0000000000..e17d73a7fb --- /dev/null +++ b/pm-stack/exporters/adapters/fixture.json @@ -0,0 +1 @@ +{"browserUnit":"fixture-browser.service","cdpPort":19299,"challengeMarkers":["verify-it","2fa","passkey"],"classMap":{},"cookieNames":["fixture-session"],"cooldownMs":900000,"enabled":true,"issueRepo":"developing-today/code","latestPath":"${FIXTURE_STATE_DIR}/latest.json","loginUrl":"https://fixture.invalid/login","name":"fixture","origins":["https://fixture.invalid"],"staleAfterMs":1800000} \ No newline at end of file diff --git a/pm-stack/exporters/producers/producer-template.mjs b/pm-stack/exporters/producers/producer-template.mjs new file mode 100644 index 0000000000..76ed68710c --- /dev/null +++ b/pm-stack/exporters/producers/producer-template.mjs @@ -0,0 +1,153 @@ +#!/usr/bin/env node +// Producer template for browser-dependent quota sources (#6032). +// +// Fork this file to add a source. It carries the plumbing discipline +// distilled from the retired Meta producer +// (~/atlas/meta-quota-export/meta-quota-export.mjs): +// +// - CDP plumbing with a per-call timeout on EVERY browser call — +// a wedged renderer must never hang the producer past its unit's +// TimeoutStartSec; +// - tab ownership: a producer closes only tabs it created +// (code#5121), never the browser's standing tabs; +// - failure-class exit codes: the producer pre-classifies its own +// failures into the watchdog's vocabulary and writes a failure +// DOCUMENT (not just a log line), so the watchdog can classify +// without scraping journals; +// - atomic latest.json (tmp + rename) + append-only history.jsonl, +// so readers never observe a torn document; +// - no secret value in any document, log, or exit message: cookie +// checks are presence-by-name, extracted tokens go straight to +// fleet secrets under their registered name. +// +// What a fork fills in: ADAPTER (origins, cookie names, the read +// itself in `readQuota`), and its adapter JSON (see +// ../adapters/fixture.json for the shape). Register the fork with the +// gatherer by adding its document to the aggregator's file-export +// inputs (the `FILE_EXPORTS` list in the pm-aggregator package) — +// until that lands, the watchdog still watches the document directly. +// +// Exit codes (failure classes the watchdog maps, watchdog-state.ts): +// 0 ok · 3 session-expired · 4 cdp-unreachable · 5 rate-limited +// 6 cookie-missing · 7 endpoint-changed · 8 unknown + +import { appendFile, mkdir, rename, writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +const ADAPTER = { + name: "template", + cdpPort: 19222, + origins: ["https://example.invalid"], + cookieNames: [], + outDir: process.env.PRODUCER_OUT_DIR ?? "", +}; + +export class ExportError extends Error { + constructor(status, exitCode, detail) { + super(detail); + this.status = status; + this.exitCode = exitCode; + } +} + +const EXIT = { + ok: 0, + "session-expired": 3, + "cdp-unreachable": 4, + "rate-limited": 5, + "cookie-missing": 6, + "endpoint-changed": 7, + unknown: 8, +}; + +/** One CDP HTTP call, timeout-bounded. */ +async function cdpJson(cdpBase, path, { method = "GET", timeoutMs = 10000 } = {}) { + const ctl = new AbortController(); + const t = setTimeout(() => ctl.abort(), timeoutMs); + try { + const res = await fetch(`${cdpBase}${path}`, { method, signal: ctl.signal }); + if (!res.ok) throw new Error(`CDP ${path}: HTTP ${res.status}`); + return await res.json(); + } finally { + clearTimeout(t); + } +} + +export function failureDocument({ attemptedAt, status, detail }) { + return { + service: ADAPTER.name, + source: `file-export/${ADAPTER.name}`, + status, + measuredAt: attemptedAt, + detail, + windows: [], + }; +} + +async function publish(outDir, doc) { + await mkdir(outDir, { recursive: true }); + const latest = join(outDir, "latest.json"); + const tmp = `${latest}.tmp-${process.pid}`; + await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`); + await rename(tmp, latest); + await appendFile(join(outDir, "history.jsonl"), `${JSON.stringify({ at: doc.measuredAt, status: doc.status })}\n`); +} + +/** The fork's actual read: open (and OWN) a tab on an allowlist + * origin, scrape the quota windows, return the success document. + * Throw ExportError with a pre-classified status on any failure. */ +async function readQuota(cdpBase) { + let target = null; + try { + target = await cdpJson(cdpBase, `/json/new?${encodeURIComponent(ADAPTER.origins[0])}`, { method: "PUT" }); + // TODO(fork): drive the page, extract windows, build the doc. + return { + service: ADAPTER.name, + source: `file-export/${ADAPTER.name}`, + status: "ok", + measuredAt: new Date().toISOString(), + windows: [], + }; + } finally { + if (target?.id) { + // Tab ownership: close only the tab this run created. + await cdpJson(cdpBase, `/json/close/${target.id}`).catch(() => {}); + } + } +} + +export async function run({ cdpPort = ADAPTER.cdpPort, outDir = ADAPTER.outDir } = {}) { + if (!outDir) throw new Error("PRODUCER_OUT_DIR is required"); + const attemptedAt = new Date().toISOString(); + const cdpBase = `http://127.0.0.1:${cdpPort}`; + try { + await cdpJson(cdpBase, "/json/version", { timeoutMs: 5000 }); + } catch (e) { + const doc = failureDocument({ + attemptedAt, + status: "cdp-unavailable", + detail: `CDP ${cdpBase}/json/version unreachable: ${e.message}`, + }); + await publish(outDir, doc); + return EXIT["cdp-unreachable"]; + } + try { + const doc = await readQuota(cdpBase); + await publish(outDir, doc); + return EXIT.ok; + } catch (e) { + const status = e instanceof ExportError ? e.status : "unknown"; + const doc = failureDocument({ + attemptedAt, + status, + detail: e instanceof Error ? e.message : String(e), + }); + await publish(outDir, doc); + return e instanceof ExportError ? e.exitCode : EXIT.unknown; + } +} + +import { fileURLToPath } from "node:url"; +if (process.argv[1] === fileURLToPath(import.meta.url)) { + process.exit(await run()); +} diff --git a/pm-stack/exporters/src/adapters.ts b/pm-stack/exporters/src/adapters.ts new file mode 100644 index 0000000000..859300f042 --- /dev/null +++ b/pm-stack/exporters/src/adapters.ts @@ -0,0 +1,188 @@ +// Adapter loader for the quota watchdog (#6032, design #6031). +// +// An adapter is a per-provider JSON file in the adapters directory. It +// carries everything provider-specific — origins allowlist, CDP port, +// producer document path, cookie names (names only, never values), +// login hints, class-map overrides, thresholds — so the watchdog core +// (watchdog.ts + watchdog-state.ts) contains zero provider names. +// +// Adapter files are data, not code: the loader validates them +// structurally and reports every defect instead of throwing, because a +// broken adapter must degrade to "that source is unobserved" (a +// watchdog-visible error), never to a crashed tick that leaves every +// other source unwatched. + +import { readdir, readFile } from "node:fs/promises"; +import { join } from "node:path"; +import type { FailureClass, Rung } from "./watchdog-state.ts"; +import { FAILURE_CLASSES, RUNGS } from "./watchdog-state.ts"; + +export interface WatchdogAdapter { + /** Source name — the key used in the state file and history. */ + name: string; + enabled: boolean; + /** Producer document (`~/atlas/-export/latest.json` shape). + * Supports $HOME and ${ENV_VAR} expansion. Optional when + * heartbeatKey is set. */ + latestPath?: string; + /** Key into the gatherer heartbeat's perProvider map, used when the + * producer has no document of its own (its read lives inside the + * gatherer) and as corroborating evidence otherwise. */ + heartbeatKey?: string; + /** Chrome DevTools Protocol port of the supervised browser. */ + cdpPort?: number; + /** systemd user unit that supervises the browser, for rung 2's + * bounded restart. */ + browserUnit?: string; + /** Browser automation may touch only these origins. */ + origins: string[]; + /** Cookie names whose PRESENCE rung 2/3 check. Values are never + * read into the watchdog process. */ + cookieNames: string[]; + /** Where rung 3 starts the provider's own SSO login flow. */ + loginUrl?: string; + /** Substrings (URL or page title) that mean a human-only challenge: + * rung 3 stops dead when one appears. */ + challengeMarkers: string[]; + /** Producer status string -> failure class overrides. */ + classMap: Record; + /** Producer status string -> rung overrides (via decide's classMap + * is class-keyed; this maps a status onto a class first). */ + rungMap: Partial>; + /** A producer document older than this is a stale read. */ + staleAfterMs: number; + /** Rate-limit cooldown written to disk on rung 0. */ + cooldownMs: number; + /** Repo that owns the adapter — rung 4 files its incident there. */ + issueRepo: string; +} + +const DEFAULT_STALE_AFTER_MS = 30 * 60_000; // two missed 15-min ticks +const DEFAULT_COOLDOWN_MS = 15 * 60_000; + +function expandPath(p: string, env: Record): string { + return p + .replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, k: string) => env[k] ?? "") + .replace(/\$HOME\b/g, env.HOME ?? "") + .replace(/^~\//, env.HOME ? `${env.HOME}/` : "~/"); +} + +function strList(v: unknown): string[] { + return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []; +} + +function isFailureClass(v: unknown): v is FailureClass { + return typeof v === "string" && (FAILURE_CLASSES as readonly string[]).includes(v); +} + +function isRung(v: unknown): v is Rung { + return typeof v === "number" && (RUNGS as readonly number[]).includes(v); +} + +/** + * Validate one parsed adapter document. Returns the normalized adapter + * or the list of defects (never throws — see the header). + */ +export function parseAdapter( + raw: unknown, + env: Record = process.env, +): { adapter: WatchdogAdapter | null; errors: string[] } { + const errors: string[] = []; + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { + return { adapter: null, errors: ["adapter is not a JSON object"] }; + } + const r = raw as Record; + const name = typeof r.name === "string" && r.name.length > 0 ? r.name : null; + if (!name) errors.push("missing or empty `name`"); + const latestPath = typeof r.latestPath === "string" ? expandPath(r.latestPath, env) : undefined; + const heartbeatKey = typeof r.heartbeatKey === "string" ? r.heartbeatKey : undefined; + if (!latestPath && !heartbeatKey) { + errors.push("adapter declares neither `latestPath` nor `heartbeatKey` — nothing to observe"); + } + const issueRepo = typeof r.issueRepo === "string" && /^[^/\s]+\/[^/\s]+$/.test(r.issueRepo) ? r.issueRepo : null; + if (!issueRepo) errors.push("missing or malformed `issueRepo` (owner/repo)"); + const cdpPort = typeof r.cdpPort === "number" && r.cdpPort > 0 && r.cdpPort < 65536 ? r.cdpPort : undefined; + if (r.cdpPort !== undefined && cdpPort === undefined) errors.push("`cdpPort` is not a valid port"); + const origins = strList(r.origins); + for (const o of origins) { + if (!/^https?:\/\/[^/\s]+/.test(o)) errors.push(`origin is not an http(s) origin: ${o}`); + } + const classMap: Record = {}; + if (typeof r.classMap === "object" && r.classMap !== null) { + for (const [k, v] of Object.entries(r.classMap as Record)) { + if (isFailureClass(v)) classMap[k] = v; + else errors.push(`classMap[${JSON.stringify(k)}] is not a failure class: ${JSON.stringify(v)}`); + } + } + const rungMap: Partial> = {}; + if (typeof r.rungMap === "object" && r.rungMap !== null) { + for (const [k, v] of Object.entries(r.rungMap as Record)) { + if (isFailureClass(k) && isRung(v)) rungMap[k] = v; + else errors.push(`rungMap[${JSON.stringify(k)}] is not class->rung: ${JSON.stringify(v)}`); + } + } + const posMs = (v: unknown, dflt: number) => + typeof v === "number" && Number.isFinite(v) && v > 0 ? v : dflt; + if (errors.length > 0 || !name || !issueRepo) return { adapter: null, errors }; + return { + errors, + adapter: { + name, + enabled: r.enabled !== false, + latestPath, + heartbeatKey, + cdpPort, + browserUnit: typeof r.browserUnit === "string" ? r.browserUnit : undefined, + origins, + cookieNames: strList(r.cookieNames), + loginUrl: typeof r.loginUrl === "string" ? r.loginUrl : undefined, + challengeMarkers: strList(r.challengeMarkers), + classMap, + rungMap, + staleAfterMs: posMs(r.staleAfterMs, DEFAULT_STALE_AFTER_MS), + cooldownMs: posMs(r.cooldownMs, DEFAULT_COOLDOWN_MS), + issueRepo, + }, + }; +} + +/** + * Load every `*.json` adapter in a directory, in filename order. + * A missing directory is an empty result with one error entry — the + * caller decides whether that is fatal (it is, for a oneshot whose + * whole job is watching the configured sources). + */ +export async function loadAdapters( + dir: string, + env: Record = process.env, +): Promise<{ adapters: WatchdogAdapter[]; errors: string[] }> { + const adapters: WatchdogAdapter[] = []; + const errors: string[] = []; + let files: string[]; + try { + files = (await readdir(dir)).filter((f) => f.endsWith(".json")).sort(); + } catch (e) { + return { adapters, errors: [`adapters dir unreadable: ${dir}: ${e instanceof Error ? e.message : String(e)}`] }; + } + const seen = new Set(); + for (const file of files) { + const path = join(dir, file); + let parsed: unknown; + try { + parsed = JSON.parse(await readFile(path, "utf8")); + } catch (e) { + errors.push(`${file}: invalid JSON: ${e instanceof Error ? e.message : String(e)}`); + continue; + } + const { adapter, errors: perFile } = parseAdapter(parsed, env); + for (const err of perFile) errors.push(`${file}: ${err}`); + if (!adapter) continue; + if (seen.has(adapter.name)) { + errors.push(`${file}: duplicate source name ${JSON.stringify(adapter.name)} — skipped`); + continue; + } + seen.add(adapter.name); + if (adapter.enabled) adapters.push(adapter); + } + return { adapters, errors }; +} diff --git a/pm-stack/exporters/src/watchdog.ts b/pm-stack/exporters/src/watchdog.ts new file mode 100644 index 0000000000..8762db373b --- /dev/null +++ b/pm-stack/exporters/src/watchdog.ts @@ -0,0 +1,635 @@ +// Quota watchdog oneshot entry point (#6032, design #6031). +// +// Slice 1 (watchdog-state.ts) decides; the rung-4 module +// (watchdog-escalation.ts) plans hand-offs; THIS file owns everything +// with side effects, in one tick: +// +// 1. load adapters (adapters.ts — provider specifics live there); +// 2. read the persisted state file (never trust it: coerceHealth); +// 3. observe each source — producer document + gatherer heartbeat + +// a live CDP liveness probe — and classify the observation, +// including the stale-read case (producer silent while the +// browser lives: the back half of the 2026-11-13→16 outage); +// 4. `decide` the ladder step, execute rungs 2/3 against the real +// browser when live repairs are enabled, record outcomes; +// 5. run rung-4 escalation / recovery effects when the decision +// layer asks (production effectors shell to the fleet CLI / gh, +// and only when QUOTA_WATCHDOG_LIVE=1 — otherwise the plan is +// journalled as a dry run and nothing is created); +// 6. write the state file back ATOMICALLY (tmp + rename) and append +// one history line per source. Nothing decision-relevant lives +// in process memory (#5928): the next tick is a fresh process +// that re-reads all of it from disk. +// +// Quiet when healthy: a healthy tick prints nothing beyond the +// surfacing lines of incidents that need a human (surfacingLine). +// +// Usage (bun): +// bun watchdog.ts [--adapters-dir DIR] [--state-file F] +// [--history-file F] [--heartbeat-file F] +// Defaults follow the laptop layout; every path is overridable so +// tests and fixture demos run against a scratch tree. + +import { appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import { homedir } from "node:os"; +import { + coerceHealth, + decide, + emptyState, + initialHealth, + recordRungOutcome, + sanitizeDetail, + type FailureClass, + type Observation, + type Rung, + type SourceHealth, + type WatchdogState, +} from "./watchdog-state.ts"; +import { + applyEscalationActions, + EscalationPartialError, + planEscalation, + planRecovery, + recordEscalation, + surfacingLine, + type EscalationContext, + type EscalationEffectors, +} from "./watchdog-escalation.ts"; +import { loadAdapters, type WatchdogAdapter } from "./adapters.ts"; + +// --------------------------------------------------------------------------- +// Effects — everything the tick can do to the world, behind one seam so +// tests drive the whole tick with fakes and no browser, queue, or network. +// --------------------------------------------------------------------------- + +export interface RungOutcome { + outcome: "succeeded" | "failed" | "skipped"; + detail: string; +} + +export interface WatchdogEffects { + /** Live CDP liveness: does the browser's /json/version answer? */ + probeCdp(port: number): Promise<{ ok: boolean; detail: string }>; + /** Rung 2: re-validate the CDP session (browser alive, an allowlist + * origin open, adapter cookies present BY NAME). */ + rung2(adapter: WatchdogAdapter): Promise; + /** Rung 3: re-login driver via the provider's own SSO flow. Stops + * dead at a human-only challenge. */ + rung3(adapter: WatchdogAdapter): Promise; + /** Rung 4 effectors (#6033). */ + escalation: EscalationEffectors; + log(line: string): void; +} + +const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +async function fetchJson(url: string, timeoutMs: number, init?: RequestInit): Promise { + const ctl = new AbortController(); + const t = setTimeout(() => ctl.abort(), timeoutMs); + try { + const res = await fetch(url, { ...init, signal: ctl.signal }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + return await res.json(); + } finally { + clearTimeout(t); + } +} + +/** Cookie NAMES present on any of the adapter's origins, via the CDP + * browser websocket. Values are never read into this process: the + * protocol reply is reduced to a name set before anything is kept. */ +async function cdpCookieNames(port: number, origins: string[], timeoutMs = 5000): Promise { + let version: { webSocketDebuggerUrl?: string }; + try { + version = (await fetchJson(`http://127.0.0.1:${port}/json/version`, timeoutMs)) as typeof version; + } catch { + return null; + } + if (!version.webSocketDebuggerUrl) return null; + return await new Promise((resolve) => { + const ws = new WebSocket(version.webSocketDebuggerUrl!); + const timer = setTimeout(() => { + try { ws.close(); } catch { /* already closed */ } + resolve(null); + }, timeoutMs); + ws.onopen = () => { + ws.send(JSON.stringify({ id: 1, method: "Storage.getCookies" })); + }; + ws.onmessage = (ev) => { + try { + const msg = JSON.parse(String(ev.data)) as { + id?: number; + result?: { cookies?: { name: string; domain: string }[] }; + }; + if (msg.id !== 1) return; + clearTimeout(timer); + ws.close(); + const cookies = msg.result?.cookies ?? []; + const names = new Set(); + for (const c of cookies) { + // Keep only cookies scoped to an allowlist origin's host. + if (origins.some((o) => { + try { return new URL(o).hostname.endsWith(c.domain.replace(/^\./, "")) || c.domain.endsWith(new URL(o).hostname); } + catch { return false; } + })) names.add(c.name); + } + resolve([...names]); + } catch { + clearTimeout(timer); + resolve(null); + } + }; + ws.onerror = () => { + clearTimeout(timer); + resolve(null); + }; + }); +} + +async function systemctlUser(args: string[], timeoutMs = 30000): Promise<{ ok: boolean; detail: string }> { + try { + const proc = Bun.spawn(["systemctl", "--user", ...args], { stdout: "pipe", stderr: "pipe" }); + const timer = setTimeout(() => proc.kill(), timeoutMs); + const code = await proc.exited; + clearTimeout(timer); + const err = (await new Response(proc.stderr).text()).trim().slice(0, 200); + return { ok: code === 0, detail: err || `exit ${code}` }; + } catch (e) { + return { ok: false, detail: e instanceof Error ? e.message : String(e) }; + } +} + +/** Production effects. Rung 2/3 touch the browser only when + * QUOTA_WATCHDOG_LIVE_REPAIRS=1 (the systemd unit sets it); without + * it they report `skipped`, which the ladder records honestly. */ +export function productionEffects(env: Record = process.env): WatchdogEffects { + const liveRepairs = env.QUOTA_WATCHDOG_LIVE_REPAIRS === "1"; + const liveEscalation = env.QUOTA_WATCHDOG_LIVE === "1"; + const probeCdp = async (port: number) => { + try { + const v = (await fetchJson(`http://127.0.0.1:${port}/json/version`, 3000)) as { Browser?: string }; + return { ok: true, detail: `CDP answered (${v.Browser ?? "browser"})` }; + } catch (e) { + return { ok: false, detail: `CDP /json/version unreachable: ${e instanceof Error ? e.message : String(e)}` }; + } + }; + return { + probeCdp, + async rung2(adapter) { + if (!adapter.cdpPort) return { outcome: "skipped", detail: "adapter declares no CDP port" }; + if (!liveRepairs) return { outcome: "skipped", detail: "live repairs not enabled (QUOTA_WATCHDOG_LIVE_REPAIRS != 1)" }; + const probe = await probeCdp(adapter.cdpPort); + if (!probe.ok) { + // Browser down: one bounded supervised restart, then re-probe. + if (adapter.browserUnit) { + const rs = await systemctlUser(["restart", adapter.browserUnit]); + if (rs.ok) { + await sleep(3000); + const again = await probeCdp(adapter.cdpPort); + if (again.ok) return { outcome: "succeeded", detail: `browser unit ${adapter.browserUnit} restarted; ${again.detail}` }; + return { outcome: "failed", detail: `browser unit restarted but CDP still unreachable: ${again.detail}` }; + } + return { outcome: "failed", detail: `CDP unreachable and restart of ${adapter.browserUnit} failed: ${rs.detail}` }; + } + return { outcome: "failed", detail: probe.detail }; + } + // Browser answers: an allowlist origin must be open, and the + // adapter's cookies must be present by name. + let targets: { url?: string }[] = []; + try { + targets = (await fetchJson(`http://127.0.0.1:${adapter.cdpPort}/json/list`, 3000)) as typeof targets; + } catch (e) { + return { outcome: "failed", detail: `CDP /json/list failed: ${e instanceof Error ? e.message : String(e)}` }; + } + const open = targets.some((t) => adapter.origins.some((o) => (t.url ?? "").startsWith(o))); + if (adapter.origins.length > 0 && !open) { + return { outcome: "failed", detail: "no tab on an adapter allowlist origin" }; + } + if (adapter.cookieNames.length > 0) { + const names = await cdpCookieNames(adapter.cdpPort, adapter.origins); + if (names === null) return { outcome: "failed", detail: "cookie presence check could not run (CDP websocket)" }; + const missing = adapter.cookieNames.filter((n) => !names.includes(n)); + if (missing.length > 0) return { outcome: "failed", detail: `cookies missing by name: ${missing.join(", ")}` }; + } + return { outcome: "succeeded", detail: "CDP session re-validated: browser live, allowlist origin open, cookies present by name" }; + }, + async rung3(adapter) { + if (!adapter.cdpPort || !adapter.loginUrl) return { outcome: "skipped", detail: "adapter declares no CDP port or login URL" }; + if (!liveRepairs) return { outcome: "skipped", detail: "live repairs not enabled (QUOTA_WATCHDOG_LIVE_REPAIRS != 1)" }; + const originOk = adapter.origins.some((o) => adapter.loginUrl!.startsWith(o)); + if (!originOk) return { outcome: "failed", detail: "login URL is outside the adapter origin allowlist — refusing" }; + let targetId: string | null = null; + try { + const created = (await fetchJson( + `http://127.0.0.1:${adapter.cdpPort}/json/new?${encodeURIComponent(adapter.loginUrl)}`, + 5000, + { method: "PUT" }, + )) as { id?: string }; + targetId = created.id ?? null; + await sleep(5000); + const targets = (await fetchJson(`http://127.0.0.1:${adapter.cdpPort}/json/list`, 3000)) as { id?: string; url?: string; title?: string }[]; + const tab = targets.find((t) => t.id === targetId) ?? targets.find((t) => (t.url ?? "").startsWith(adapter.loginUrl!)); + const where = `${tab?.url ?? ""} ${tab?.title ?? ""}`; + const marker = adapter.challengeMarkers.find((m) => where.toLowerCase().includes(m.toLowerCase())); + if (marker) { + return { outcome: "failed", detail: `human-only challenge at login (${marker}) — stopping; a human must complete it` }; + } + if (adapter.cookieNames.length > 0) { + const names = await cdpCookieNames(adapter.cdpPort, adapter.origins); + if (names !== null) { + const missing = adapter.cookieNames.filter((n) => !names.includes(n)); + if (missing.length === 0) return { outcome: "succeeded", detail: "re-login restored the adapter cookies (present by name)" }; + return { outcome: "failed", detail: `re-login did not restore cookies: ${missing.join(", ")} still missing` }; + } + } + return { outcome: "failed", detail: `login flow landed on ${tab?.url ?? "unknown page"} without confirming a session` }; + } catch (e) { + return { outcome: "failed", detail: `re-login driver error: ${e instanceof Error ? e.message : String(e)}` }; + } finally { + if (targetId) { + try { await fetchJson(`http://127.0.0.1:${adapter.cdpPort}/json/close/${targetId}`, 2000); } catch { /* tab already gone */ } + } + } + }, + escalation: productionEscalationEffectors(liveEscalation), + log: (line) => console.log(line), + }; +} + +/** Rung-4 production effectors (#6033): fleet queue + gh, behind the + * QUOTA_WATCHDOG_LIVE gate. Dry-run mode plans are journalled by the + * caller and these effectors are never invoked. */ +function productionEscalationEffectors(live: boolean): EscalationEffectors { + const run = async (cmd: string[], timeoutMs = 60000): Promise => { + const proc = Bun.spawn(cmd, { stdout: "pipe", stderr: "pipe" }); + const timer = setTimeout(() => proc.kill(), timeoutMs); + const code = await proc.exited; + clearTimeout(timer); + const out = await new Response(proc.stdout).text(); + if (code !== 0) { + const err = (await new Response(proc.stderr).text()).trim().slice(0, 300); + throw new Error(`${cmd[0]} ${cmd[1] ?? ""} exit ${code}: ${err}`); + } + return out; + }; + const guard = () => { + if (!live) throw new Error("escalation effectors invoked without QUOTA_WATCHDOG_LIVE=1"); + }; + return { + async enqueueTask(packet) { + guard(); + const wrapper = { + title: `watchdog incident: ${packet.source} (${packet.failure.class ?? "unknown"})`, + body: packet.outcomeWanted, + dedupe_key: packet.dedupeKey, + priority: 30, + payload: { + schema: "repo-task/v1", + kind: packet.kind, + packet, + }, + }; + const file = join("/tmp", `watchdog-escalation-${packet.source}-${Date.now()}.json`); + await writeFile(file, JSON.stringify(wrapper)); + const out = await run(["fleet", "queue", "enqueue", "--queue", "repo-health-code-pilot", file]); + const m = out.match(/"id"\s*:\s*(\d+)/); + if (!m) throw new Error(`enqueue output carried no task id: ${out.slice(0, 200)}`); + return m[1]; + }, + async openIssue(action) { + guard(); + await run(["gh", "label", "create", "watchdog-incident", "--repo", action.repo, "--force"]).catch(() => ""); + const file = join("/tmp", `watchdog-issue-${Date.now()}.md`); + await writeFile(file, action.body); + const out = await run([ + "gh", "issue", "create", "--repo", action.repo, "--title", action.title, + "--body-file", file, "--label", "watchdog-incident", + ]); + const m = out.match(/\/issues\/(\d+)/); + if (!m) throw new Error(`issue create output carried no number: ${out.slice(0, 200)}`); + return Number(m[1]); + }, + async commentIssue(action) { + guard(); + const file = join("/tmp", `watchdog-comment-${Date.now()}.md`); + await writeFile(file, action.body); + await run(["gh", "issue", "comment", String(action.issueNumber), "--repo", action.repo, "--body-file", file]); + }, + async closeIssue(action) { + guard(); + await run(["gh", "issue", "close", String(action.issueNumber), "--repo", action.repo]); + }, + async completeTask(action) { + guard(); + // The escalation task is completed by whoever claimed and fixed + // it in the normal case; the watchdog's recovery completion is + // best-effort (the task may already be claimed/done). + await run([ + "fleet", "queue", "complete", action.queueTaskId, "--worker", "repo-worker-code", + "--result", JSON.stringify({ outcome: "already_done", note: "watchdog recovery: source healthy again (#6033)" }), + ]).catch(() => ""); + }, + }; +} + +// --------------------------------------------------------------------------- +// Observation + classification — the watchdog owns the classes the +// producer cannot see: missing document, stale read, browser state. +// --------------------------------------------------------------------------- + +interface ProducerDoc { + status?: string; + measuredAt?: string; + detail?: string; + error?: string; + failureClass?: string; +} + +const STATUS_CLASS: Record = { + "cdp-unavailable": "cdp-unreachable", + "cdp-unreachable": "cdp-unreachable", + "browser-down": "browser-down", + "session-expired": "session-expired", + "login-required": "session-expired", + "cookie-missing": "cookie-missing", + "endpoint-changed": "endpoint-changed", + "rate-limited": "rate-limited", + "rate_limited": "rate-limited", +}; + +function classifyText(text: string): FailureClass | null { + const t = text.toLowerCase(); + if (t.includes("rate-limit") || t.includes("rate limit") || t.includes("429")) return "rate-limited"; + if (t.includes("cdp-unavailable") || t.includes("cdp unavailable") || t.includes("cdp-unreachable")) return "cdp-unreachable"; + if (t.includes("session") && (t.includes("expired") || t.includes("login"))) return "session-expired"; + if (t.includes("cookie") && t.includes("missing")) return "cookie-missing"; + if (t.includes("login page") || t.includes("sign-in") || t.includes("sign in")) return "session-expired"; + return null; +} + +export interface ObservationInputs { + doc: ProducerDoc | null; + docError: string | null; + heartbeatEntry: { state?: string; error?: string } | null; + heartbeatStale: boolean; + cdp: { ok: boolean; detail: string } | null; + nowMs: number; +} + +export function buildObservation(adapter: WatchdogAdapter, inp: ObservationInputs): Observation { + const at = new Date(inp.nowMs).toISOString(); + const { doc } = inp; + + if (doc && typeof doc.status === "string") { + if (doc.status === "ok") { + const measured = doc.measuredAt ? Date.parse(doc.measuredAt) : NaN; + if (Number.isFinite(measured) && inp.nowMs - measured > adapter.staleAfterMs) { + // Stale read: the document claims health but is old — the + // producer has gone silent while everything looks alive. + // A dead CDP endpoint at the same moment names the culprit. + if (inp.cdp && !inp.cdp.ok) { + return { kind: "failed", at, class: "cdp-unreachable", detail: `stale read (${Math.round((inp.nowMs - measured) / 60000)} min old) and ${inp.cdp.detail}` }; + } + return { kind: "failed", at, class: "unknown", detail: `stale read: producer document is ${Math.round((inp.nowMs - measured) / 60000)} min old (limit ${Math.round(adapter.staleAfterMs / 60000)} min)` }; + } + return { kind: "healthy", at, detail: "producer ok" }; + } + // Producer pre-classified its own failure. + const detail = sanitizeDetail(doc.detail ?? doc.error ?? doc.status); + const cls = + (doc.failureClass && (FAILURE_CLASS_SET.has(doc.failureClass) ? (doc.failureClass as FailureClass) : null)) || + adapter.classMap[doc.status] || + STATUS_CLASS[doc.status] || + classifyText(detail) || + "unknown"; + return { kind: "failed", at, class: cls, detail: detail || doc.status }; + } + + if (inp.docError) { + // Missing/unreadable document — a class the producer cannot see. + if (inp.cdp && !inp.cdp.ok) { + return { kind: "failed", at, class: "browser-down", detail: `producer document missing (${inp.docError}); ${inp.cdp.detail}` }; + } + return { kind: "failed", at, class: "unknown", detail: `producer document missing or unreadable: ${inp.docError}` }; + } + + // No document configured for this source: the gatherer heartbeat is + // the observation. + if (adapter.heartbeatKey) { + if (inp.heartbeatStale) { + return { kind: "failed", at, class: "unknown", detail: "stale read: gatherer heartbeat is stale" }; + } + const entry = inp.heartbeatEntry; + if (!entry) return { kind: "failed", at, class: "unknown", detail: `no heartbeat entry for ${adapter.heartbeatKey}` }; + if (entry.state === "ok") return { kind: "healthy", at, detail: "gatherer heartbeat ok" }; + const detail = sanitizeDetail(entry.error ?? `heartbeat state ${entry.state ?? "?"}`); + return { kind: "failed", at, class: classifyText(detail) ?? "unknown", detail }; + } + + return { kind: "failed", at, class: "unknown", detail: "no observation source produced data" }; +} + +const FAILURE_CLASS_SET = new Set([ + "session-expired", "cookie-missing", "endpoint-changed", "browser-down", + "cdp-unreachable", "rate-limited", "unknown", +]); + +// --------------------------------------------------------------------------- +// One tick over all sources. +// --------------------------------------------------------------------------- + +export interface TickOptions { + adaptersDir: string; + stateFile: string; + historyFile: string; + heartbeatFile?: string; + effects: WatchdogEffects; + liveEscalation: boolean; + now?: Date; +} + +export interface HistoryEntry { + at: string; + source: string; + observation: string; + class: FailureClass | null; + decision: string; + surfacing: string | null; +} + +export async function runTick(opts: TickOptions): Promise<{ state: WatchdogState; history: HistoryEntry[]; errors: string[] }> { + const now = opts.now ?? new Date(); + const at = now.toISOString(); + const { adapters, errors } = await loadAdapters(opts.adaptersDir); + + let state: WatchdogState = emptyState(at); + try { + const raw = JSON.parse(await readFile(opts.stateFile, "utf8")) as Partial; + if (raw && typeof raw === "object" && typeof raw.sources === "object" && raw.sources !== null) { + state = { + version: 1, + updatedAt: typeof raw.updatedAt === "string" ? raw.updatedAt : at, + sources: Object.fromEntries( + Object.entries(raw.sources).map(([k, v]) => [k, coerceHealth(k, v)]), + ), + }; + } + } catch { + // Missing or corrupt state file: start fresh (fail open to + // re-observe, never to assume healthy). + state = emptyState(at); + } + + let heartbeat: { tickAt?: string; perProvider?: Record } | null = null; + if (opts.heartbeatFile) { + try { + heartbeat = JSON.parse(await readFile(opts.heartbeatFile, "utf8")); + } catch { + heartbeat = null; + } + } + const heartbeatStale = + heartbeat?.tickAt !== undefined + ? now.getTime() - Date.parse(heartbeat.tickAt) > 30 * 60_000 + : false; + + const history: HistoryEntry[] = []; + + for (const adapter of adapters) { + const prev = state.sources[adapter.name] ?? initialHealth(adapter.name); + + // --- observe --- + let doc: ProducerDoc | null = null; + let docError: string | null = null; + if (adapter.latestPath) { + try { + doc = JSON.parse(await readFile(adapter.latestPath, "utf8")) as ProducerDoc; + } catch (e) { + docError = e instanceof Error ? e.message.split("\n")[0] : String(e); + } + } + const cdp = adapter.cdpPort ? await opts.effects.probeCdp(adapter.cdpPort) : null; + const obs = buildObservation(adapter, { + doc, + docError, + heartbeatEntry: adapter.heartbeatKey ? heartbeat?.perProvider?.[adapter.heartbeatKey] ?? null : null, + heartbeatStale, + cdp, + nowMs: now.getTime(), + }); + + // --- recovery effects for an escalated incident that just healed --- + if (obs.kind === "healthy" && prev.incident?.escalation) { + const recovery = planRecovery(prev, at); + if (recovery.length > 0) { + if (opts.liveEscalation) { + await applyEscalationActions(recovery, opts.effects.escalation).catch((e) => { + opts.effects.log(`watchdog: recovery effects for ${adapter.name} failed: ${e instanceof Error ? e.message : String(e)}`); + }); + } else { + opts.effects.log(`watchdog: dry-run recovery plan for ${adapter.name}: ${recovery.map((a) => a.type).join(", ")}`); + } + } + } + + // --- decide + execute the chosen rung --- + const { decision, next } = decide(prev, obs, { classMap: adapter.rungMap, cooldownMs: adapter.cooldownMs }); + let health = next; + + if (decision.action === "repair") { + const rung = decision.rung; + const res = rung === 2 + ? await opts.effects.rung2(adapter) + : rung === 3 + ? await opts.effects.rung3(adapter) + : { outcome: "skipped" as const, detail: `rung ${rung} has no executor` }; + health = recordRungOutcome(health, at, rung, res.outcome, res.detail); + } + + // --- rung 4: escalation hand-off --- + if (decision.action === "escalate" || health.incident?.surfacing === "escalate") { + const ctx: EscalationContext = { + issueRepo: adapter.issueRepo, + stateFilePath: opts.stateFile, + adapterRef: `adapters/${adapter.name}.json`, + historyRef: opts.historyFile, + }; + const plan = planEscalation(health, ctx); + if (plan.actions.length > 0) { + if (opts.liveEscalation) { + try { + const refs = await applyEscalationActions(plan.actions, opts.effects.escalation); + health = recordEscalation(health, ctx, refs, at); + } catch (e) { + if (e instanceof EscalationPartialError) { + health = recordEscalation(health, ctx, e.refs, at); + } + opts.effects.log(`watchdog: escalation for ${adapter.name} failed: ${e instanceof Error ? e.message : String(e)}`); + } + } else { + opts.effects.log( + `watchdog: dry-run escalation plan for ${adapter.name}: ${plan.actions.map((a) => a.type).join(", ")} (set QUOTA_WATCHDOG_LIVE=1 to execute)`, + ); + } + } + } + + state.sources[adapter.name] = health; + const line = surfacingLine(health, now.getTime()); + if (line) opts.effects.log(line); + history.push({ + at, + source: adapter.name, + observation: obs.kind, + class: obs.kind === "failed" ? obs.class : null, + decision: decision.action, + surfacing: health.incident?.surfacing ?? null, + }); + } + + // --- persist: atomic state write + history append --- + state.updatedAt = at; + await mkdir(dirname(opts.stateFile), { recursive: true }); + const tmp = `${opts.stateFile}.tmp-${process.pid}`; + await writeFile(tmp, `${JSON.stringify(state, null, 2)}\n`); + await rename(tmp, opts.stateFile); + if (history.length > 0) { + await mkdir(dirname(opts.historyFile), { recursive: true }); + await appendFile(opts.historyFile, history.map((h) => JSON.stringify(h)).join("\n") + "\n"); + } + return { state, history, errors }; +} + +// --------------------------------------------------------------------------- +// CLI +// --------------------------------------------------------------------------- + +function argValue(args: string[], flag: string): string | undefined { + const i = args.indexOf(flag); + return i >= 0 ? args[i + 1] : undefined; +} + +export async function main(args: string[] = process.argv.slice(2), env: Record = process.env): Promise { + const home = homedir(); + const stateDir = join(home, ".local", "state", "pm-aggregator"); + const adaptersDir = argValue(args, "--adapters-dir") ?? env.QUOTA_WATCHDOG_ADAPTERS_DIR ?? join(home, ".config", "quota-watchdog", "adapters"); + const stateFile = argValue(args, "--state-file") ?? join(stateDir, "quota-watchdog-state.json"); + const historyFile = argValue(args, "--history-file") ?? join(stateDir, "quota-watchdog-history.jsonl"); + const heartbeatFile = argValue(args, "--heartbeat-file") ?? join(stateDir, "quota-gatherer-heartbeat.json"); + const effects = productionEffects(env); + const { errors } = await runTick({ + adaptersDir, + stateFile, + historyFile, + heartbeatFile, + effects, + liveEscalation: env.QUOTA_WATCHDOG_LIVE === "1", + }); + for (const e of errors) effects.log(`watchdog: adapter error: ${e}`); + return errors.length > 0 ? 1 : 0; +} + +if (import.meta.main) { + process.exit(await main()); +} diff --git a/pm-stack/exporters/test/fixtures/fixture-producer.mjs b/pm-stack/exporters/test/fixtures/fixture-producer.mjs new file mode 100644 index 0000000000..545923f40f --- /dev/null +++ b/pm-stack/exporters/test/fixtures/fixture-producer.mjs @@ -0,0 +1,61 @@ +#!/usr/bin/env node +// Fixture producer stub for the quota watchdog (#6032 acceptance). +// +// Stands in for a real browser-dependent producer: each invocation +// reads a scenario file and writes the producer document +// (`latest.json`, atomically) plus one `history.jsonl` line, in the +// exact shape the watchdog observes. Tests and live demos drive the +// watchdog through its acceptance cases by rewriting the scenario +// between ticks — no browser, no network, no secrets. +// +// Scenario file (JSON, path from FIXTURE_SCENARIO or argv[2]): +// { "status": "ok" } healthy tick +// { "status": "session-expired", "detail": "..." } pre-classified failure +// { "status": "rate-limited" } rung-0 cooldown case +// { "status": "error", "detail": "human-only challenge: 2fa required" } +// { "status": "ok", "measuredAt": "" } stale-read case +// { "missing": true } writes NO document +// +// Environment: +// FIXTURE_STATE_DIR where latest.json/history.jsonl land (required) +// FIXTURE_SCENARIO scenario file path (or argv[2]) + +import { mkdir, readFile, rename, writeFile, appendFile, rm } from "node:fs/promises"; +import { join } from "node:path"; + +const stateDir = process.env.FIXTURE_STATE_DIR; +if (!stateDir) { + console.error("fixture-producer: FIXTURE_STATE_DIR is required"); + process.exit(2); +} +const scenarioPath = process.argv[2] ?? process.env.FIXTURE_SCENARIO; +if (!scenarioPath) { + console.error("fixture-producer: scenario path required (argv[2] or FIXTURE_SCENARIO)"); + process.exit(2); +} + +const scenario = JSON.parse(await readFile(scenarioPath, "utf8")); +await mkdir(stateDir, { recursive: true }); +const latestPath = join(stateDir, "latest.json"); + +if (scenario.missing === true) { + await rm(latestPath, { force: true }); + process.exit(0); +} + +const now = new Date().toISOString(); +const doc = { + service: "fixture", + source: "file-export/fixture", + status: scenario.status ?? "ok", + measuredAt: scenario.measuredAt ?? now, + ...(scenario.detail ? { detail: scenario.detail } : {}), + ...(scenario.failureClass ? { failureClass: scenario.failureClass } : {}), + windows: scenario.status === "ok" || !scenario.status ? [{ name: "fixture", usedPct: 0, resetAt: null }] : [], +}; + +// Atomic publish, the producer discipline the watchdog relies on. +const tmp = `${latestPath}.tmp-${process.pid}`; +await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`); +await rename(tmp, latestPath); +await appendFile(join(stateDir, "history.jsonl"), `${JSON.stringify({ at: now, status: doc.status })}\n`); diff --git a/pm-stack/exporters/test/watchdog.test.ts b/pm-stack/exporters/test/watchdog.test.ts new file mode 100644 index 0000000000..9ccffc55a4 --- /dev/null +++ b/pm-stack/exporters/test/watchdog.test.ts @@ -0,0 +1,269 @@ +// Tests for the quota-watchdog oneshot entry point (#6032). +// +// Oracles, named per the testing doctrine (AGENTS.md): +// - Acceptance fixtures: the issue's own checklist, driven end to +// end through runTick against a scratch tree — the broken-source +// ladder walk with caps honored, the rate-limited cooldown +// honored from DISK by a fresh tick, the human-only challenge +// marking the incident human-blocked with its surfacing flag, +// and quiet-when-healthy. +// - Cross-invocation persistence (#5928 oracle): every tick is a +// separate runTick call that re-reads the state file from disk; +// no state is shared in memory between ticks in these tests, so +// a pass proves the disk record — not a cache — carries the +// ladder. +// - Classification oracle: observation classes match the design's +// table for the cases the producer cannot see itself (missing +// document, stale read, dead CDP endpoint). + +import { describe, expect, test } from "bun:test"; +import { mkdtemp, readFile, rm, writeFile, mkdir } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { runTick, type WatchdogEffects, type RungOutcome } from "../src/watchdog.ts"; +import { loadAdapters, parseAdapter } from "../src/adapters.ts"; +import type { EscalationEffectors } from "../src/watchdog-escalation.ts"; + +const T0 = Date.parse("2026-11-17T00:00:00Z"); +const iso = (min: number) => new Date(T0 + min * 60_000).toISOString(); + +interface Harness { + dir: string; + stateFile: string; + historyFile: string; + fixtureDir: string; + logs: string[]; + rung2Calls: number; + rung3Calls: number; + escCalls: string[]; + effects: WatchdogEffects; + setDoc(doc: unknown | null): Promise; + tick(min: number, liveEscalation?: boolean): ReturnType; +} + +async function harness(opts: { + rung2?: () => RungOutcome; + rung3?: () => RungOutcome; + cdpOk?: boolean; +} = {}): Promise { + const dir = await mkdtemp(join(tmpdir(), "watchdog-test-")); + const adaptersDir = join(dir, "adapters"); + const fixtureDir = join(dir, "fixture"); + await mkdir(adaptersDir, { recursive: true }); + await mkdir(fixtureDir, { recursive: true }); + await writeFile(join(adaptersDir, "fixture.json"), JSON.stringify({ + name: "fixture", + latestPath: join(fixtureDir, "latest.json"), + cdpPort: 19299, + origins: ["https://fixture.invalid"], + cookieNames: ["fixture-session"], + loginUrl: "https://fixture.invalid/login", + challengeMarkers: ["verify-it", "2fa"], + issueRepo: "developing-today/code", + staleAfterMs: 30 * 60_000, + cooldownMs: 15 * 60_000, + })); + const logs: string[] = []; + const escCalls: string[] = []; + const h: Harness = { + dir, + stateFile: join(dir, "quota-watchdog-state.json"), + historyFile: join(dir, "quota-watchdog-history.jsonl"), + fixtureDir, + logs, + rung2Calls: 0, + rung3Calls: 0, + escCalls, + effects: { + probeCdp: async () => opts.cdpOk === false + ? { ok: false, detail: "CDP /json/version unreachable: connection refused" } + : { ok: true, detail: "CDP answered" }, + rung2: async () => { + h.rung2Calls++; + return opts.rung2?.() ?? { outcome: "failed", detail: "re-validation failed" }; + }, + rung3: async () => { + h.rung3Calls++; + return opts.rung3?.() ?? { outcome: "failed", detail: "re-login failed" }; + }, + escalation: { + enqueueTask: async (packet) => { escCalls.push(`enqueue:${packet.dedupeKey}`); return "4242"; }, + openIssue: async (a) => { escCalls.push(`open:${a.repo}`); return 777; }, + commentIssue: async (a) => { escCalls.push(`comment:${a.issueNumber}`); }, + closeIssue: async (a) => { escCalls.push(`close:${a.issueNumber}`); }, + completeTask: async (a) => { escCalls.push(`complete:${a.queueTaskId}`); }, + } satisfies EscalationEffectors, + log: (line) => logs.push(line), + }, + async setDoc(doc) { + const p = join(fixtureDir, "latest.json"); + if (doc === null) await rm(p, { force: true }); + else await writeFile(p, JSON.stringify(doc)); + }, + tick(min, liveEscalation = true) { + return runTick({ + adaptersDir, + stateFile: h.stateFile, + historyFile: h.historyFile, + effects: h.effects, + liveEscalation, + now: new Date(T0 + min * 60_000), + }); + }, + }; + return h; +} + +const okDoc = (min: number) => ({ service: "fixture", status: "ok", measuredAt: iso(min) }); +const failDoc = (min: number, status: string, detail = "producer failed") => ({ + service: "fixture", status, measuredAt: iso(min), detail, +}); + +describe("watchdog entry point — acceptance fixtures", () => { + test("quiet when healthy: state + history written, no repairs, no output", async () => { + const h = await harness(); + await h.setDoc(okDoc(0)); + const { state, history } = await h.tick(0); + expect(state.sources.fixture.consecutiveFailures).toBe(0); + expect(state.sources.fixture.incident).toBeNull(); + expect(history).toHaveLength(1); + expect(history[0].decision).toBe("quiet"); + expect(h.rung2Calls + h.rung3Calls).toBe(0); + expect(h.escCalls).toHaveLength(0); + expect(h.logs).toHaveLength(0); + // The state file exists on disk and round-trips. + const onDisk = JSON.parse(await readFile(h.stateFile, "utf8")); + expect(onDisk.sources.fixture.lastSuccessAt).toBe(iso(0)); + const histLines = (await readFile(h.historyFile, "utf8")).trim().split("\n"); + expect(histLines).toHaveLength(1); + await rm(h.dir, { recursive: true, force: true }); + }); + + test("broken source walks the ladder rung by rung, caps honored, then escalates exactly once", async () => { + const h = await harness(); + // class `unknown` enters at rung 1: retry, retry, CDP re-validate x2, + // re-login x2, then every rung is spent -> escalate. + let last; + for (let min = 0; min <= 6; min++) { + await h.setDoc(failDoc(min, "mystery-failure")); + last = await h.tick(min); + } + const health = last!.state.sources.fixture; + expect(health.rungAttempts).toEqual({ 0: 0, 1: 2, 2: 2, 3: 2 }); + expect(h.rung2Calls).toBe(2); + expect(h.rung3Calls).toBe(2); + expect(health.incident?.surfacing).toBe("escalate"); + expect(health.incident?.escalation?.queueTaskId).toBe("4242"); + expect(health.incident?.escalation?.issueNumber).toBe(777); + expect(h.escCalls.filter((c) => c.startsWith("enqueue"))).toHaveLength(1); + expect(h.escCalls.filter((c) => c.startsWith("open"))).toHaveLength(1); + // Repair log records every rung attempt and stays within its bound. + const rungs = health.repairLog.filter((e) => e.outcome === "attempted").map((e) => e.rung); + expect(rungs).toEqual([1, 1, 2, 2, 3, 3]); + // A further failing tick dedupes: no second task, no second issue. + await h.setDoc(failDoc(7, "mystery-failure")); + await h.tick(7); + expect(h.escCalls.filter((c) => c.startsWith("enqueue"))).toHaveLength(1); + expect(h.escCalls.filter((c) => c.startsWith("open"))).toHaveLength(1); + await rm(h.dir, { recursive: true, force: true }); + }); + + test("rate-limited fixture: cooldown is set on disk and the next fresh tick honors it with no repair action", async () => { + const h = await harness(); + await h.setDoc(failDoc(0, "rate-limited", "429 from provider")); + const first = await h.tick(0); + expect(first.state.sources.fixture.cooldownUntil).toBe(iso(15)); + expect(first.history[0].decision).toBe("wait-cooldown"); + // Next tick is a fresh invocation re-reading disk; still cooling down. + await h.setDoc(failDoc(5, "rate-limited", "429 from provider")); + const second = await h.tick(5); + expect(second.history[0].decision).toBe("wait-cooldown"); + expect(second.state.sources.fixture.rungAttempts[0]).toBe(1); + expect(h.rung2Calls + h.rung3Calls).toBe(0); + await rm(h.dir, { recursive: true, force: true }); + }); + + test("human-only challenge at re-login marks the incident human-blocked and surfaces it the same tick", async () => { + const h = await harness({ + rung3: () => ({ outcome: "failed", detail: "human-only challenge at login (2fa) — stopping" }), + }); + await h.setDoc(failDoc(0, "session-expired", "landed on login page")); + const { state } = await h.tick(0); + const health = state.sources.fixture; + expect(health.incident?.humanBlocked).toBe(true); + expect(health.incident?.surfacing).toBe("human-blocked"); + expect(h.logs.some((l) => l.startsWith("NEEDS DREW: fixture"))).toBe(true); + // The ladder stops dead: a later tick attempts no further repairs. + await h.setDoc(failDoc(5, "session-expired", "landed on login page")); + const later = await h.tick(5); + expect(later.history[0].decision).toBe("human-blocked"); + expect(h.rung3Calls).toBe(1); + await rm(h.dir, { recursive: true, force: true }); + }); + + test("recovery: a healthy tick after escalation comments, closes, and completes the hand-off", async () => { + const h = await harness(); + for (let min = 0; min <= 6; min++) { + await h.setDoc(failDoc(min, "mystery-failure")); + await h.tick(min); + } + expect(h.escCalls.filter((c) => c.startsWith("enqueue"))).toHaveLength(1); + await h.setDoc(okDoc(10)); + const { state } = await h.tick(10); + expect(state.sources.fixture.incident).toBeNull(); + expect(h.escCalls).toContain("comment:777"); + expect(h.escCalls).toContain("close:777"); + expect(h.escCalls).toContain("complete:4242"); + await rm(h.dir, { recursive: true, force: true }); + }); +}); + +describe("watchdog entry point — classification of what the producer cannot see", () => { + test("stale read: a fresh-looking ok document older than the limit is a failure", async () => { + const h = await harness(); + await h.setDoc({ service: "fixture", status: "ok", measuredAt: iso(-120) }); + const { state, history } = await h.tick(0); + expect(history[0].observation).toBe("failed"); + expect(history[0].class).toBe("unknown"); + expect(state.sources.fixture.lastDetail).toContain("stale read"); + expect(state.sources.fixture.consecutiveFailures).toBe(1); + await rm(h.dir, { recursive: true, force: true }); + }); + + test("missing document with a dead CDP endpoint classifies as browser-down", async () => { + const h = await harness({ cdpOk: false }); + await h.setDoc(null); + const { history } = await h.tick(0); + expect(history[0].observation).toBe("failed"); + expect(history[0].class).toBe("browser-down"); + await rm(h.dir, { recursive: true, force: true }); + }); + + test("producer pre-classification passes through (cdp-unavailable -> cdp-unreachable)", async () => { + const h = await harness(); + await h.setDoc(failDoc(0, "cdp-unavailable", "browser produced no response")); + const { history } = await h.tick(0); + expect(history[0].class).toBe("cdp-unreachable"); + await rm(h.dir, { recursive: true, force: true }); + }); +}); + +describe("adapter loader", () => { + test("parseAdapter rejects adapters with nothing to observe or no issue repo", () => { + expect(parseAdapter({ name: "x", issueRepo: "a/b" }).adapter).toBeNull(); + expect(parseAdapter({ name: "x", latestPath: "/tmp/l.json" }).adapter).toBeNull(); + const ok = parseAdapter({ name: "x", latestPath: "/tmp/l.json", issueRepo: "a/b" }); + expect(ok.adapter?.name).toBe("x"); + expect(ok.adapter?.staleAfterMs).toBeGreaterThan(0); + }); + + test("loadAdapters skips a broken file and reports it, keeping the good ones", async () => { + const dir = await mkdtemp(join(tmpdir(), "watchdog-adapters-")); + await writeFile(join(dir, "good.json"), JSON.stringify({ name: "good", latestPath: "/tmp/l.json", issueRepo: "a/b" })); + await writeFile(join(dir, "bad.json"), "{not json"); + const { adapters, errors } = await loadAdapters(dir); + expect(adapters.map((a) => a.name)).toEqual(["good"]); + expect(errors.some((e) => e.includes("bad.json"))).toBe(true); + await rm(dir, { recursive: true, force: true }); + }); +}); diff --git a/pm-stack/systemd/pm-quota-watchdog.service b/pm-stack/systemd/pm-quota-watchdog.service new file mode 100644 index 0000000000..803d9a839d --- /dev/null +++ b/pm-stack/systemd/pm-quota-watchdog.service @@ -0,0 +1,12 @@ +[Unit] +Description=Quota watchdog — browser-dependent quota sources, ladder + state (code#6032) +After=network-online.target quota-gatherer.service helium-cdp.service +Wants=network-online.target + +[Service] +Type=oneshot +ExecStart=/run/current-system/sw/bin/bun /home/user/pm-stack/exporters/src/watchdog.ts +Environment=QUOTA_WATCHDOG_ADAPTERS_DIR=/home/user/.config/quota-watchdog/adapters +Environment=QUOTA_WATCHDOG_LIVE=1 +Environment=QUOTA_WATCHDOG_LIVE_REPAIRS=1 +TimeoutStartSec=240 diff --git a/pm-stack/systemd/pm-quota-watchdog.timer b/pm-stack/systemd/pm-quota-watchdog.timer new file mode 100644 index 0000000000..c1e8c1151b --- /dev/null +++ b/pm-stack/systemd/pm-quota-watchdog.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Run the quota watchdog every 15 minutes, offset from the gatherer (code#6032) + +[Timer] +OnCalendar=*:3/15 +Persistent=true +RandomizedDelaySec=20 +Unit=pm-quota-watchdog.service + +[Install] +WantedBy=timers.target