Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 67 additions & 18 deletions pm-stack/exporters/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,32 +26,81 @@ 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
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/<provider>-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.
1 change: 1 addition & 0 deletions pm-stack/exporters/adapters/fixture.json
Original file line number Diff line number Diff line change
@@ -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}
153 changes: 153 additions & 0 deletions pm-stack/exporters/producers/producer-template.mjs
Original file line number Diff line number Diff line change
@@ -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());
}
Loading