diff --git a/doc/fleet-schedule-registry.md b/doc/fleet-schedule-registry.md index 01c4cb016..5100c9f52 100644 --- a/doc/fleet-schedule-registry.md +++ b/doc/fleet-schedule-registry.md @@ -262,6 +262,7 @@ The OS-timer half of surface 2. Cadence is the unit's own `OnCalendar`/`OnUnitAc | `laptop-backups-watchdog.timer` | `OnCalendar=*-*-* 06,12,18:30:00` | `laptop-backups-watchdog.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `laptop-repo-keeper.timer` | `OnCalendar=*-*-* *:23:00` | `laptop-repo-keeper.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `laptop-untracked-review.timer` | `OnCalendar=*-*-* 07:37:00` | `laptop-untracked-review.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | +| `meta-quota-export.timer` | `OnCalendar=*-*-* *:00/15:00` | `meta-quota-export.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-05 | | `openai-cred-watchdog.timer` | `OnCalendar=*-*-* *:00:00` | `openai-cred-watchdog.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `openclaw-backup.timer` | `OnCalendar=*-*-* 04:05:00` | `openclaw-backup.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | | `opencode-quota-freshness-summary.timer` (disabled) | `OnCalendar=*-*-* *:00:00` | `opencode-quota-freshness-summary.service` | laptop (user systemd) | not recorded | not recorded | not recorded | 2026-11-04 | diff --git a/pm-stack/meta-exporter/README.md b/pm-stack/meta-exporter/README.md new file mode 100644 index 000000000..7d6bced55 --- /dev/null +++ b/pm-stack/meta-exporter/README.md @@ -0,0 +1,113 @@ +# Meta quota exporter — Phase 1 (code#1301) + +Laptop-side exporter for the Meta "Muse Code High Usage" plan quota, +built on the #1167 investigation (report: usage-billing-hub goal, +`hidden_files/meta-console-investigation-2026-10-26.md`). Part of the +Stage-2 quota plane (epic #1149); the sandbox gatherer is #1151. + +## Why laptop-side + +The dev.meta.ai console is cookie-auth only; the session +(`llama_dev_sess`, expires 2027-10-27) lives in the laptop Helium +browser and Meta exposes a `sessionBindingId`, so Phase 1 replays the +console's own API calls **from the laptop session's own context**: +the exporter talks CDP (127.0.0.1:19222 on the laptop) and evaluates +`fetch()` inside the open dev.meta.ai page. Requests therefore carry +the session cookie and leave from the laptop's egress/device. The +cookie value never enters the exporter process, a file, or a log. + +Endpoints read per tick (both cookie-auth GETs, JSON): +- `/api/portal/teams/{team_id}/subscription-quota` — both windows + (weighted used/limit + reset epochs; % = used/limit). +- `/api/portal/teams/{team_id}/billing-banner` — remaining free + credits (minor units). +- Best-effort: the PAYG "Current balance" is read from the billing + iframe's DOM text when a billing tab is open (the balance itself is + behind a GraphQL/embed flow). Absent tab → `paygBalanceUsd: null`, + never an invented 0. + +## Export format (the gatherer file-export convention) + +The gatherer (#1151) had no file-export ingest convention yet, so +this exporter defines it; #1151 should adopt it as-is: + +- Location (on the laptop): + `~/atlas/meta-quota-export/latest.json` (written atomically, + tmp + rename) plus an append-only `history.jsonl` of every run. + The sandbox side reads it over the existing multiplexed SSH channel + (`~/tools/laptop-ssh.sh 'cat ~/atlas/meta-quota-export/latest.json'`). +- Success document: + +```json +{ "service": "meta", "source": "file-export/meta-laptop", + "status": "ok", "measuredAt": "", + "consoleAsOf": "", + "tier": "Muse Code High Usage", + "windows": [ { "name": "5h", "usedPct": 1.02, "resetAt": "" }, + { "name": "weekly", "usedPct": 8.83, "resetAt": "" } ], + "freeCreditsUsd": 148.57, "paygBalanceUsd": 0 } +``` + +## Failure states (fail-closed) + +A failed tick writes a failure document to `latest.json` (and +`history.jsonl`) with `status`, `attemptedAt`, `detail`, and +`measuredAt: null` — and **no** windows or values, so nothing stale +can render as a current reading: + +| status | meaning | exit | +|---|---|---| +| `session-expired` | API answered 401/403 or bounced to auth — laptop session needs a human re-login | 3 | +| `page-not-ready` | helium-cdp answers CDP but its renderer is wedged (readiness probe: target never navigates/evaluates, or a created tab never finishes loading) — names the browser, not the tab | 8 | +| `cdp-unavailable` | browser debug port did not answer | 4 | +| `no-console-page` | browser up, no dev.meta.ai tab open | 5 | +| `unparseable` | endpoint answered an unrecognised shape | 6 | +| `fetch-failed` | network/other error inside the page | 7 | + +## Readiness probe + bounded recovery (issue #5487) + +Before exporting, the exporter probes the browser: it creates a +throwaway target, navigates it to a `data:` URL, and evaluates `1`, +each step timeout-raced. CDP answering `/json/list` is not proof a +page can load — a wedged renderer passes every cheap health signal +while `Page.navigate` hangs forever (2026-11-04: ~30 h of lost Meta +quota measurement). On a wedge the exporter attempts ONE +`systemctl --user restart helium-cdp.service` — at most once per +15 minutes, with the attempt persisted in +`/.helium-restart.json` and recorded as `recovery` in the +export document — then re-probes. Still wedged (or restart on +cooldown) → the tick fails as `page-not-ready` (exit 8). +`session-expired` stays a separate state: a restart never fixes a +session that needs a human re-login. + +`laptop-unreachable` is a consumer-side derivation, by design: if the +laptop is down nothing runs, so the gatherer/hub treats a +`latest.json` older than 2 ticks (> 30 min) as laptop-unreachable. + +## Install / schedule (laptop) + +```sh +bash pm-stack/meta-exporter/install-laptop.sh # run ON the laptop +``` + +Installs the script to `~/atlas/meta-quota-export/`, renders +`meta-quota-export.service` (with the laptop's node path) + +`meta-quota-export.timer` into `~/.config/systemd/user/`, and enables +a user timer firing every 15 minutes (`OnCalendar=*:0/15`, +`Persistent=true`). Note: user timers run while the user has a +session; `loginctl enable-linger user` (needs sudo) would make them +fully boot-persistent — the laptop's graphical session is the normal +state, and staleness is visible via the age rule above either way. + +Manual run / debugging: + +```sh +node ~/atlas/meta-quota-export/meta-quota-export.mjs +journalctl --user -u meta-quota-export.service +``` + +## Tests + +```sh +node --test pm-stack/meta-exporter/meta-quota-export.test.mjs +``` diff --git a/pm-stack/meta-exporter/install-laptop.sh b/pm-stack/meta-exporter/install-laptop.sh new file mode 100644 index 000000000..416fef747 --- /dev/null +++ b/pm-stack/meta-exporter/install-laptop.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Install the Meta quota exporter on Drew's laptop (run ON the laptop). +# Copies the exporter next to its output directory, renders the systemd +# user units with the laptop's node path, enables the 15-minute timer, +# and starts one run immediately. Idempotent. +set -euo pipefail + +SRC_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +DEST_DIR="$HOME/atlas/meta-quota-export" +UNIT_DIR="$HOME/.config/systemd/user" +NODE_BIN="$(command -v node || true)" + +if [[ -z "$NODE_BIN" ]]; then + echo "install-laptop: node not found on PATH" >&2 + exit 1 +fi + +mkdir -p "$DEST_DIR" "$UNIT_DIR" +install -m 0755 "$SRC_DIR/meta-quota-export.mjs" "$DEST_DIR/meta-quota-export.mjs" +sed "s|@NODE@|$NODE_BIN|g" "$SRC_DIR/meta-quota-export.service" > "$UNIT_DIR/meta-quota-export.service" +install -m 0644 "$SRC_DIR/meta-quota-export.timer" "$UNIT_DIR/meta-quota-export.timer" + +systemctl --user daemon-reload +systemctl --user enable --now meta-quota-export.timer +systemctl --user start meta-quota-export.service || true + +echo "install-laptop: installed to $DEST_DIR; timer state:" +systemctl --user list-timers meta-quota-export.timer --no-pager || true +echo "install-laptop: latest export (if the first run succeeded):" +cat "$DEST_DIR/latest.json" 2>/dev/null || echo "(no latest.json yet — check: journalctl --user -u meta-quota-export.service)" diff --git a/pm-stack/meta-exporter/meta-quota-export.mjs b/pm-stack/meta-exporter/meta-quota-export.mjs new file mode 100755 index 000000000..dc5be43a5 --- /dev/null +++ b/pm-stack/meta-exporter/meta-quota-export.mjs @@ -0,0 +1,626 @@ +#!/usr/bin/env node +/** + * meta-quota-export — Meta (dev.meta.ai) quota exporter, Phase 1 of + * developing-today/code#1301 (epic #1149; investigation #1167). + * + * Runs ON Drew's laptop, inside the reach of the laptop Helium + * browser's live dev.meta.ai session (CDP debug port, default 19222). + * It evaluates fetch() calls in the console page's own context, so the + * requests carry the session cookie and leave from the laptop's own + * egress/device — no cookie value is ever read into this process, + * written to disk, or logged. + * + * Every run writes the export document atomically to + * /latest.json (default ~/atlas/meta-quota-export/) + * and appends the same document to /history.jsonl. + * + * Success document (the file-export format the #1151 quota gatherer + * ingests; source label fixed as "file-export/meta-laptop"): + * { service: "meta", source: "file-export/meta-laptop", + * status: "ok", measuredAt: , consoleAsOf: , + * tier: "Muse Code High Usage", + * windows: [ { name: "5h", usedPct: 1.02, resetAt: }, + * { name: "weekly", usedPct: 8.83, resetAt: } ], + * freeCreditsUsd: 148.57, paygBalanceUsd: 0 } + * + * Failure documents carry status + attemptedAt + detail and NO + * windows/values — a failed tick can never be mistaken for a reading: + * session-expired the console API answered 401/403 or bounced to + * an auth page; the laptop session needs a human + * re-login. Exit 3. + * cdp-unavailable the browser debug port did not answer. Exit 4. + * no-console-page browser is up, no dev.meta.ai tab is open, and + * creating one via the CDP targets API failed. + * Exit 5. (Since task 9492 / issue #5121 the exporter + * owns its tab: it creates a dev.meta.ai target when + * none exists and closes only the target it created.) + * page-not-ready the browser (helium-cdp) answers CDP but its + * renderer is wedged: the readiness probe's target + * never navigates/evaluates, or a created tab never + * finishes loading. Names the browser, not the tab. + * Exit 8. Before failing, the exporter attempts ONE + * bounded helium-cdp.service restart (max once per + * 15 min, recorded in the export document as + * `recovery`) and re-probes. (issue #5487) + * unparseable an endpoint answered something whose shape this + * parser does not recognise. Exit 6. + * fetch-failed network/other error inside the page. Exit 7. + * "laptop-unreachable" is deliberately NOT produced here: if the + * laptop is down nothing runs, so consumers derive it from the age of + * latest.json (> 2 ticks = > 30 min without a fresh document). + */ +import { appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises"; +import { execFile } from "node:child_process"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; + +export const SOURCE = "file-export/meta-laptop"; +export const DEFAULT_TEAM_ID = "1073226932208501"; // "My Team" (#1167) + +export class ExportError extends Error { + constructor(status, exitCode, detail, recovery = null) { + super(detail); + this.status = status; + this.exitCode = exitCode; + this.recovery = recovery; + } +} + +const round2 = (n) => Math.round(n * 100) / 100; + +/** Parse a subscription-quota payload into export windows. Throws on + * any shape drift — fail-closed, never partial zeros. The one tolerated + * absence is a not-yet-started window (used = 0) whose reset the + * console returns as null or omits: that window is emitted with + * resetAt: null instead of failing the whole export (#1301). */ +export function parseSubscriptionQuota(payload) { + const q = payload?.subscription_quota; + if (!q || typeof q !== "object") { + throw new ExportError("unparseable", 6, "subscription-quota: subscription_quota object missing"); + } + const num = (v) => (typeof v === "string" || typeof v === "number" ? Number(v) : NaN); + const windowUsed = num(q.window_weighted_used); + const windowLimit = num(q.window_weighted_limit); + const weeklyUsed = num(q.weekly_weighted_used); + const weeklyLimit = num(q.weekly_weighted_limit); + const durationSecs = num(q.window_duration_secs); + const fields = { windowUsed, windowLimit, weeklyUsed, weeklyLimit }; + for (const [k, v] of Object.entries(fields)) { + if (!Number.isFinite(v) || v < 0) { + throw new ExportError("unparseable", 6, `subscription-quota: field ${k} not a finite number`); + } + } + // A window the console has not started yet (no usage recorded in it) + // has no reset: window_resets_at / weekly_resets_at comes back null + // or the field is omitted entirely (observed live 2026-10-29, #1301: + // after the 16:15Z short-window roll the absent reset poisoned every + // export, including the healthy weekly window and free credits). + // Tolerate exactly that shape — emit the window with resetAt: null. + // A missing reset on a window WITH recorded usage, and any malformed + // reset value, still fail closed. + const resetField = (raw, used, label) => { + if (raw === null || raw === undefined) { + if (used === 0) return null; + throw new ExportError( + "unparseable", + 6, + `subscription-quota: field ${label} absent but the window has recorded usage`, + ); + } + const v = num(raw); + if (!Number.isFinite(v) || v < 0) { + throw new ExportError("unparseable", 6, `subscription-quota: field ${label} not a finite number`); + } + return v; + }; + const windowReset = resetField(q.window_resets_at, windowUsed, "windowReset"); + const weeklyReset = resetField(q.weekly_resets_at, weeklyUsed, "weeklyReset"); + if (windowLimit === 0 || weeklyLimit === 0) { + throw new ExportError("unparseable", 6, "subscription-quota: zero limit"); + } + if (!Number.isFinite(durationSecs) || durationSecs <= 0) { + throw new ExportError("unparseable", 6, "subscription-quota: field window_duration_secs not a finite positive number"); + } + const shortName = durationSecs === 18_000 ? "5h" : durationSecs === 3_600 ? "1h" : `window-${durationSecs}s`; + const iso = (epochSecs) => new Date(epochSecs * 1000).toISOString(); + return { + tier: typeof q.tier === "string" ? q.tier : null, + consoleAsOf: Number.isFinite(num(q.as_of)) ? iso(num(q.as_of)) : null, + windows: [ + { name: shortName, usedPct: round2((windowUsed / windowLimit) * 100), resetAt: windowReset === null ? null : iso(windowReset) }, + { name: "weekly", usedPct: round2((weeklyUsed / weeklyLimit) * 100), resetAt: weeklyReset === null ? null : iso(weeklyReset) }, + ], + }; +} + +/** Parse a billing-banner payload into remaining free credits (USD). */ +export function parseBillingBanner(payload) { + const minor = payload?.remaining_minor_units; + if (typeof minor !== "number" || !Number.isFinite(minor) || minor < 0) { + throw new ExportError("unparseable", 6, "billing-banner: remaining_minor_units missing/invalid"); + } + if (payload.currency !== "USD") { + throw new ExportError("unparseable", 6, `billing-banner: unexpected currency ${String(payload.currency)}`); + } + return minor / 100; +} + +/** Parse the PAYG current balance out of the billing iframe's text. + * Returns null (not 0) when the text does not contain the balance — + * an absent read must stay absent, never become a fake $0. */ +export function parsePaygBalance(iframeText) { + if (typeof iframeText !== "string") return null; + const m = iframeText.match(/Current balance\s*\n?\s*\$\s*([\d,]+(?:\.\d{2})?)/); + if (!m) return null; + const v = Number(m[1].replace(/,/g, "")); + return Number.isFinite(v) ? v : null; +} + +export function successDocument({ measuredAt, parsed, freeCreditsUsd, paygBalanceUsd, recovery = null }) { + const doc = { + service: "meta", + source: SOURCE, + status: "ok", + measuredAt, + consoleAsOf: parsed.consoleAsOf, + tier: parsed.tier, + windows: parsed.windows, + freeCreditsUsd, + paygBalanceUsd, + }; + if (recovery) doc.recovery = recovery; + return doc; +} + +export function failureDocument({ attemptedAt, status, detail, recovery = null }) { + const doc = { + service: "meta", + source: SOURCE, + status, + measuredAt: null, + attemptedAt, + detail, + }; + if (recovery) doc.recovery = recovery; + return doc; +} + +// ---------- CDP plumbing (only used by the main run) ---------- + +async function httpJson(url) { + const res = await fetch(url); + if (!res.ok) throw new Error(`HTTP ${res.status} for ${url}`); + return res.json(); +} + +function connectWs(wsUrl) { + return new Promise((resolve, reject) => { + const ws = new WebSocket(wsUrl); + const pending = new Map(); + let id = 0; + ws.onmessage = (ev) => { + const m = JSON.parse(ev.data); + if (m.id && pending.has(m.id)) { + const p = pending.get(m.id); + pending.delete(m.id); + if (m.error) p.reject(new Error(JSON.stringify(m.error))); + else p.resolve(m.result); + } + }; + ws.onopen = () => + resolve({ + send: (method, params = {}) => + new Promise((res, rej) => { + const i = ++id; + pending.set(i, { resolve: res, reject: rej }); + ws.send(JSON.stringify({ id: i, method, params })); + }), + close: () => ws.close(), + }); + ws.onerror = (e) => reject(new Error(`websocket error: ${e.message ?? "unknown"}`)); + }); +} + +async function evaluate(client, expression) { + const r = await client.send("Runtime.evaluate", { + expression, + returnByValue: true, + awaitPromise: true, + }); + if (r.exceptionDetails) { + throw new Error(`page eval exception: ${JSON.stringify(r.exceptionDetails).slice(0, 300)}`); + } + return r.result.value; +} + +/** Fetch both quota endpoints inside the console page's context. + * Returns { quota, banner } parsed JSON bodies; throws ExportError + * with the right failure state otherwise. */ +async function fetchQuotaPayloads(client, teamId) { + const expression = `(async () => { + const team = ${JSON.stringify(teamId)}; + const get = async (path) => { + const r = await fetch(path, { headers: { Accept: "application/json" }, credentials: "same-origin" }); + return { status: r.status, url: r.url, text: await r.text() }; + }; + const quota = await get("/api/portal/teams/" + team + "/subscription-quota"); + const banner = await get("/api/portal/teams/" + team + "/billing-banner"); + return JSON.stringify({ quota, banner }); + })()`; + let raw; + try { + raw = await evaluate(client, expression); + } catch (e) { + throw new ExportError("fetch-failed", 7, `in-page fetch failed: ${e.message}`); + } + let outer; + try { + outer = JSON.parse(raw); + } catch { + throw new ExportError("fetch-failed", 7, "in-page fetch returned a non-JSON envelope"); + } + const bodies = {}; + for (const key of ["quota", "banner"]) { + const r = outer[key]; + if (!r || typeof r.status !== "number") { + throw new ExportError("fetch-failed", 7, `${key}: no response captured`); + } + if (r.status === 401 || r.status === 403 || (typeof r.url === "string" && r.url.includes("auth"))) { + throw new ExportError( + "session-expired", + 3, + `${key}: HTTP ${r.status}${r.url ? ` (landed on ${new URL(r.url).pathname})` : ""} — laptop dev.meta.ai session needs re-login`, + ); + } + if (r.status !== 200) { + throw new ExportError("fetch-failed", 7, `${key}: HTTP ${r.status}`); + } + try { + bodies[key] = JSON.parse(r.text); + } catch { + throw new ExportError("unparseable", 6, `${key}: HTTP 200 but body is not JSON`); + } + } + return bodies; +} + +/** Best-effort PAYG balance from the billing iframe's DOM text. + * Absence is reported as null, never invented. */ +async function fetchPaygBalance(cdpBase) { + try { + const targets = await httpJson(`${cdpBase}/json/list`); + const frame = targets.find( + (t) => t.type === "iframe" && typeof t.url === "string" && t.url.includes("billing.dev.meta.ai"), + ); + if (!frame?.webSocketDebuggerUrl) return null; + const client = await connectWs(frame.webSocketDebuggerUrl); + try { + // Bound the read (Codex review on PR #6333): a frame that accepts + // CDP but never answers Runtime.evaluate must not hang the whole + // export — withTimeout resolves null, which parses to a null + // (absent) balance, never an invented one. + const text = await withTimeout( + evaluate(client, "document.body ? document.body.innerText : ''"), + 10000, + ); + return parsePaygBalance(text); + } finally { + client.close(); + } + } catch { + return null; + } +} + +async function writeOutputs(outDir, doc) { + await mkdir(outDir, { recursive: true }); + const latest = join(outDir, "latest.json"); + const tmp = join(outDir, `.latest.json.tmp-${process.pid}`); + await writeFile(tmp, `${JSON.stringify(doc, null, 2)}\n`, "utf8"); + await rename(tmp, latest); + await appendFile(join(outDir, "history.jsonl"), `${JSON.stringify(doc)}\n`, "utf8"); +} + + +async function createTarget(cdpBase, url) { + const res = await fetch(`${cdpBase}/json/new?${encodeURIComponent(url)}`, { method: "PUT" }); + if (!res.ok) throw new Error(`HTTP ${res.status} creating target`); + return res.json(); +} + +async function closeTarget(cdpBase, id) { + try { + await fetch(`${cdpBase}/json/close/${id}`); + } catch { + // best effort: a target that is already gone needs no closing + } +} + +/** Race a promise against a timeout; resolves null on timeout. + * CDP calls into a busy renderer can hang indefinitely, and the + * systemd unit kills the whole run at 2 minutes, so no single CDP + * call in the created-tab path may block unbounded. */ +function withTimeout(promise, ms) { + return Promise.race([ + promise, + new Promise((resolve) => setTimeout(() => resolve(null), ms)), + ]); +} + + +// ---------- Readiness probe + bounded recovery (issue #5487) ---------- + +export const HELIUM_UNIT = "helium-cdp.service"; +export const RESTART_MIN_INTERVAL_MS = 15 * 60 * 1000; +export const PAGE_NOT_READY_EXIT = 8; + +/** Readiness probe: create a throwaway target, navigate it to a data: + * URL, and evaluate `1` on it — each step timeout-raced. A healthy + * renderer answers in ~1 s; a wedged one (CDP answers /json/new but + * Page.navigate / Runtime.evaluate never reply) fails the probe. + * Returns { ok: true } or { ok: false, detail }. Never throws. */ +export async function probeCdpReadiness({ cdpBase, timeoutMs = 10000, deps = {} } = {}) { + const create = deps.createTarget ?? createTarget; + const connect = deps.connectWs ?? connectWs; + const close = deps.closeTarget ?? closeTarget; + const stepMs = Math.max(1000, Math.floor(timeoutMs / 2)); + let target = null; + let client = null; + try { + target = await withTimeout(create(cdpBase, "about:blank"), stepMs); + if (!target?.id || !target?.webSocketDebuggerUrl) { + return { ok: false, detail: "probe: creating a target returned no usable target" }; + } + client = await withTimeout(connect(target.webSocketDebuggerUrl), stepMs); + if (!client) return { ok: false, detail: "probe: websocket to the probe target never opened" }; + const nav = await withTimeout( + client.send("Page.navigate", { url: "data:text/html,probeok" }), + stepMs, + ); + if (nav === null) { + return { ok: false, detail: `probe: Page.navigate never replied within ${stepMs}ms — renderer wedged` }; + } + const val = await withTimeout(evaluate(client, "1"), stepMs); + if (val !== 1) { + return { ok: false, detail: `probe: Runtime.evaluate never replied within ${stepMs}ms — renderer wedged` }; + } + return { ok: true }; + } catch (e) { + return { ok: false, detail: `probe: ${e.message}` }; + } finally { + try { client?.close(); } catch { /* best effort */ } + if (target?.id) await close(cdpBase, target.id); + } +} + +/** Pure cooldown check for the bounded restart. */ +export function restartAllowed(lastRestartAtIso, nowMs) { + if (!lastRestartAtIso) return true; + const last = Date.parse(lastRestartAtIso); + if (!Number.isFinite(last)) return true; + return nowMs - last >= RESTART_MIN_INTERVAL_MS; +} + +function execFileAsync(file, args) { + return new Promise((resolve, reject) => { + execFile(file, args, { timeout: 30000 }, (err) => (err ? reject(err) : resolve())); + }); +} + +/** Attempt ONE bounded helium-cdp restart, at most once per + * RESTART_MIN_INTERVAL_MS, with the attempt persisted next to the + * export outputs so the bound holds across ticks. Returns a recovery + * record for the export document either way. */ +export async function attemptBoundedRestart({ outDir, now = new Date(), restart } = {}) { + const at = now.toISOString(); + const statePath = outDir ? join(outDir, ".helium-restart.json") : null; + let last = null; + if (statePath) { + try { last = JSON.parse(await readFile(statePath, "utf8")).lastRestartAt ?? null; } catch { last = null; } + } + if (!restartAllowed(last, now.getTime())) { + return { action: "restart", unit: HELIUM_UNIT, at, result: "skipped-cooldown", lastRestartAt: last }; + } + const doRestart = restart ?? (() => execFileAsync("systemctl", ["--user", "restart", HELIUM_UNIT])); + // Persist the attempt BEFORE calling restart (Codex review on + // PR #6333): a restart that rejects or times out must still obey the + // once-per-interval bound — callers such as the Meta session keeper + // can re-invoke the exporter independently of its timer. + if (statePath) { + try { + await mkdir(outDir, { recursive: true }); + await writeFile(statePath, `${JSON.stringify({ lastRestartAt: at })}\n`, "utf8"); + } catch { /* the record in the export document still stands */ } + } + try { + await doRestart(); + } catch (e) { + return { action: "restart", unit: HELIUM_UNIT, at, result: "restart-failed", detail: e.message }; + } + return { action: "restart", unit: HELIUM_UNIT, at, result: "restarted" }; +} + +/** Drive the created page to dev.meta.ai and wait until its document + * is usable on that origin; returns the final href. Throws + * no-console-page when the tab does not finish loading in time. + * Notes from live debugging (issue #5121, 2026-11-04): a target made + * via PUT /json/new lists the requested URL but its document stays + * about:blank until an explicit Page.navigate; and under laptop load + * the renderer can take tens of seconds to answer Runtime.evaluate, + * so every poll is timeout-raced and treated as still-loading. */ +async function waitForPageReady(client, timeoutMs = 75000) { + await withTimeout(client.send("Page.enable"), 5000); + await withTimeout( + client.send("Page.navigate", { url: "https://dev.meta.ai/" }), + 5000, + ); + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const state = await withTimeout( + evaluate(client, "document.readyState + '|' + location.href"), + 4000, + ); + if (typeof state === "string") { + const [ready, href] = state.split("|"); + if ( + (ready === "complete" || ready === "interactive") && + href && + href.startsWith("https://dev.meta.ai") + ) { + return href; + } + } + await new Promise((r) => setTimeout(r, 500)); + } + throw new ExportError( + "page-not-ready", + PAGE_NOT_READY_EXIT, + `helium-cdp page not ready: created dev.meta.ai tab did not finish loading within ${Math.round(timeoutMs / 1000)}s — the browser renderer, not the tab, is the culprit (issue #5487)`, + ); +} + +export async function run({ cdpPort = 19222, outDir, teamId = DEFAULT_TEAM_ID, probeFn, restartFn } = {}) { + const attemptedAt = new Date().toISOString(); + const cdpBase = `http://127.0.0.1:${cdpPort}`; + let targets; + try { + targets = await httpJson(`${cdpBase}/json/list`); + } catch (e) { + throw new ExportError("cdp-unavailable", 4, `CDP ${cdpBase}/json/list unreachable: ${e.message}`); + } + // Readiness probe (issue #5487): CDP answering /json/list does NOT + // mean a page can load — a wedged renderer answers every cheap + // health signal while Page.navigate hangs forever. Probe first; + // on a wedge, try ONE bounded helium-cdp restart and re-probe; + // if still wedged, fail as page-not-ready naming the browser. + const probe = probeFn ?? ((base) => probeCdpReadiness({ cdpBase: base })); + let recovery = null; + const firstProbe = await probe(cdpBase); + if (!firstProbe.ok) { + recovery = await attemptBoundedRestart({ outDir, restart: restartFn }); + if (recovery.result === "restarted") { + const secondProbe = await probe(cdpBase); + if (!secondProbe.ok) { + throw new ExportError( + "page-not-ready", + PAGE_NOT_READY_EXIT, + `helium-cdp wedged: ${secondProbe.detail}; still not ready after a bounded ${HELIUM_UNIT} restart`, + recovery, + ); + } + // The pre-restart target list is stale (Codex review on + // PR #6333): its dev.meta.ai entry carries the old debugger URL. + // Re-fetch before selecting or creating the console page. + try { + targets = await httpJson(`${cdpBase}/json/list`); + } catch (e) { + throw new ExportError("cdp-unavailable", 4, `CDP ${cdpBase}/json/list unreachable after restart: ${e.message}`, recovery); + } + } else { + throw new ExportError( + "page-not-ready", + PAGE_NOT_READY_EXIT, + `helium-cdp wedged: ${firstProbe.detail}; bounded restart not performed (${recovery.result})`, + recovery, + ); + } + } + let page = targets.find( + (t) => t.type === "page" && typeof t.url === "string" && t.url.startsWith("https://dev.meta.ai"), + ); + // Own the tab (issue #5121): when no dev.meta.ai target exists and CDP + // answers, create one, use it, and close only the target we created. + // cdp-unavailable above stays a real failure (exit 4). + let createdTargetId = null; + try { + if (!page?.webSocketDebuggerUrl) { + let created; + try { + created = await createTarget(cdpBase, "https://dev.meta.ai/"); + } catch (e) { + throw new ExportError( + "no-console-page", + 5, + `browser is up but no dev.meta.ai tab is open and creating one failed: ${e.message}`, + ); + } + if (!created?.id || !created?.webSocketDebuggerUrl) { + throw new ExportError( + "no-console-page", + 5, + "browser is up but no dev.meta.ai tab is open and the created target has no debugger URL", + ); + } + createdTargetId = created.id; + page = { ...created, url: created.url || "https://dev.meta.ai/" }; + } + const client = await connectWs(page.webSocketDebuggerUrl); + let bodies; + try { + let teamUrl = page.url; + if (createdTargetId) { + teamUrl = await waitForPageReady(client); + } + let teamParam = null; + try { + teamParam = new URL(teamUrl).searchParams.get("team_id"); + } catch { + teamParam = null; + } + bodies = await fetchQuotaPayloads(client, teamParam ?? teamId); + } finally { + client.close(); + } + const parsed = parseSubscriptionQuota(bodies.quota); + const freeCreditsUsd = parseBillingBanner(bodies.banner); + const paygBalanceUsd = await fetchPaygBalance(cdpBase); + return successDocument({ + measuredAt: new Date().toISOString(), + parsed, + freeCreditsUsd, + paygBalanceUsd, + recovery, + }); + } finally { + if (createdTargetId) await closeTarget(cdpBase, createdTargetId); + } +} + +async function main() { + const args = process.argv.slice(2); + const opt = (name, fallback) => { + const i = args.indexOf(name); + return i >= 0 && args[i + 1] ? args[i + 1] : fallback; + }; + const outDir = opt("--out-dir", join(homedir(), "atlas", "meta-quota-export")); + const cdpPort = Number(opt("--cdp-port", "19222")); + const teamId = opt("--team-id", process.env.META_TEAM_ID ?? DEFAULT_TEAM_ID); + try { + const doc = await run({ cdpPort, outDir, teamId }); + await writeOutputs(outDir, doc); + console.log(JSON.stringify({ status: doc.status, measuredAt: doc.measuredAt, outDir })); + } catch (e) { + const err = + e instanceof ExportError + ? e + : new ExportError("fetch-failed", 7, `unexpected: ${e.message ?? String(e)}`); + const doc = failureDocument({ + attemptedAt: new Date().toISOString(), + status: err.status, + detail: err.message, + recovery: err.recovery ?? null, + }); + try { + await writeOutputs(outDir, doc); + } catch (writeErr) { + console.error(`meta-quota-export: could not write outputs: ${writeErr.message}`); + } + console.error(`meta-quota-export: ${err.status}: ${err.message}`); + process.exit(err.exitCode); + } +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + await main(); +} diff --git a/pm-stack/meta-exporter/meta-quota-export.service b/pm-stack/meta-exporter/meta-quota-export.service new file mode 100644 index 000000000..e88a9ae53 --- /dev/null +++ b/pm-stack/meta-exporter/meta-quota-export.service @@ -0,0 +1,8 @@ +[Unit] +Description=Meta (dev.meta.ai) quota exporter — code#1301 Phase 1 +After=network-online.target + +[Service] +Type=oneshot +TimeoutStartSec=120 +ExecStart=@NODE@ %h/atlas/meta-quota-export/meta-quota-export.mjs --cdp-port 19222 --out-dir %h/atlas/meta-quota-export diff --git a/pm-stack/meta-exporter/meta-quota-export.test.mjs b/pm-stack/meta-exporter/meta-quota-export.test.mjs new file mode 100644 index 000000000..b16d23b02 --- /dev/null +++ b/pm-stack/meta-exporter/meta-quota-export.test.mjs @@ -0,0 +1,245 @@ +// Tests for the pure parsing core of meta-quota-export.mjs. +// Run: node --test pm-stack/meta-exporter/ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { createHash } from "node:crypto"; +import { mkdtemp, readFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + attemptBoundedRestart, + failureDocument, + PAGE_NOT_READY_EXIT, + probeCdpReadiness, + restartAllowed, + parseBillingBanner, + parsePaygBalance, + parseSubscriptionQuota, + successDocument, +} from "./meta-quota-export.mjs"; + +// The live payload captured 2026-10-27 (#1167): 1.02% / 8.83%. +const QUOTA = { + subscription_quota: { + tier_id: "27681527378179523", + tier: "Muse Code High Usage", + as_of: 1793077399, + window_weighted_limit: "100000000000", + window_duration_secs: 18000, + window_weighted_used: "1023570000", + window_resets_at: 1793090405, + weekly_weighted_limit: "300000000000", + weekly_weighted_used: "26484231500", + weekly_resets_at: 1793577600, + }, +}; + +test("parseSubscriptionQuota: percentages and resets match the console", () => { + const parsed = parseSubscriptionQuota(QUOTA); + assert.equal(parsed.tier, "Muse Code High Usage"); + assert.deepEqual(parsed.windows, [ + { name: "5h", usedPct: 1.02, resetAt: "2026-10-27T08:40:05.000Z" }, + { name: "weekly", usedPct: 8.83, resetAt: "2026-11-02T00:00:00.000Z" }, + ]); + assert.equal(parsed.consoleAsOf, "2026-10-27T05:03:19.000Z"); // 00:03:19 CDT +}); + +test("parseSubscriptionQuota: shape drift fails closed", () => { + assert.throws(() => parseSubscriptionQuota({}), /unparseable|missing/); + assert.throws(() => parseSubscriptionQuota({ subscription_quota: { window_weighted_used: "1" } })); + const zeroLimit = structuredClone(QUOTA); + zeroLimit.subscription_quota.window_weighted_limit = "0"; + assert.throws(() => parseSubscriptionQuota(zeroLimit), /zero limit/); +}); + +test("parseBillingBanner: minor units to USD, currency checked", () => { + assert.equal(parseBillingBanner({ kind: "free_partial", remaining_minor_units: 14857, currency: "USD" }), 148.57); + assert.throws(() => parseBillingBanner({ remaining_minor_units: 100, currency: "EUR" }), /currency/); + assert.throws(() => parseBillingBanner({})); +}); + +test("parsePaygBalance: reads the iframe text, absence stays null", () => { + assert.equal(parsePaygBalance("Pay as you go\nCurrent balance\n$0.00\nYour balance won't increase"), 0); + assert.equal(parsePaygBalance("Current balance\n$1,234.56"), 1234.56); + assert.equal(parsePaygBalance("nothing relevant here"), null); + assert.equal(parsePaygBalance(undefined), null); +}); + +test("documents: success carries the spec fields; failure carries none", () => { + const ok = successDocument({ + measuredAt: "2026-10-27T05:00:00.000Z", + parsed: parseSubscriptionQuota(QUOTA), + freeCreditsUsd: 148.57, + paygBalanceUsd: 0, + }); + assert.equal(ok.service, "meta"); + assert.equal(ok.source, "file-export/meta-laptop"); + assert.equal(ok.status, "ok"); + assert.equal(ok.windows.length, 2); + + const bad = failureDocument({ attemptedAt: "2026-10-27T05:00:00.000Z", status: "session-expired", detail: "HTTP 401" }); + assert.equal(bad.measuredAt, null); + assert.equal("windows" in bad, false); + assert.equal("freeCreditsUsd" in bad, false); +}); + +// ---------- Readiness probe fixtures (issue #5487) ---------- +// A fixture CDP endpoint: HTTP answers /json/new like a real browser, +// and the websocket either never replies (wedged renderer) or answers +// CDP calls (healthy renderer). The wedge case is the regression: the +// probe must report not-ready instead of hanging or passing. + +function wsAccept(key) { + return createHash("sha1").update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").digest("base64"); +} + +function wsFrame(text) { + const payload = Buffer.from(text); + let header; + if (payload.length < 126) { + header = Buffer.from([0x81, payload.length]); + } else if (payload.length < 65536) { + header = Buffer.alloc(4); + header[0] = 0x81; header[1] = 126; header.writeUInt16BE(payload.length, 2); + } else { + header = Buffer.alloc(10); + header[0] = 0x81; header[1] = 127; header.writeBigUInt64BE(BigInt(payload.length), 2); + } + return Buffer.concat([header, payload]); +} + +function startFixtureCdp({ wedged }) { + const sockets = new Set(); + const track = (sock) => { sockets.add(sock); sock.on("close", () => sockets.delete(sock)); }; + const server = createServer((req, res) => { + if (req.url.startsWith("/json/new")) { + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify({ + id: "probe-target-1", + type: "page", + url: "about:blank", + webSocketDebuggerUrl: `ws://127.0.0.1:${server.address().port}/ws`, + })); + } else if (req.url.startsWith("/json/close")) { + res.end("Target is closing"); + } else if (req.url.startsWith("/json/list")) { + res.setHeader("content-type", "application/json"); + res.end("[]"); + } else { + res.statusCode = 404; + res.end("nope"); + } + }); + server.on("connection", track); + server.on("upgrade", (req, socket) => { + track(socket); + socket.write( + "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" + + `Sec-WebSocket-Accept: ${wsAccept(req.headers["sec-websocket-key"])}\r\n\r\n`, + ); + if (wedged) return; // accept the socket, never reply — the wedge + let buf = Buffer.alloc(0); + socket.on("data", (chunk) => { + buf = Buffer.concat([buf, chunk]); + for (;;) { + if (buf.length < 2) return; + const masked = (buf[1] & 0x80) !== 0; + let len = buf[1] & 0x7f; + let off = 2; + if (len === 126) { if (buf.length < 4) return; len = buf.readUInt16BE(2); off = 4; } + else if (len === 127) { if (buf.length < 10) return; len = Number(buf.readBigUInt64BE(2)); off = 10; } + const maskOff = off; + if (masked) off += 4; + if (buf.length < off + len) return; + let payload = buf.subarray(off, off + len); + if (masked) { + const mask = buf.subarray(maskOff, maskOff + 4); + payload = Buffer.from(payload.map((b, i) => b ^ mask[i % 4])); + } + buf = buf.subarray(off + len); + let msg; + try { msg = JSON.parse(payload.toString()); } catch { continue; } + if (!msg.id) continue; + const result = msg.method === "Runtime.evaluate" ? { result: { value: 1 } } : {}; + socket.write(wsFrame(JSON.stringify({ id: msg.id, result }))); + } + }); + }); + return new Promise((resolve) => { + server.listen(0, "127.0.0.1", () => { + resolve({ + base: `http://127.0.0.1:${server.address().port}`, + close: () => new Promise((r) => { for (const sock of sockets) sock.destroy(); server.close(r); }), + }); + }); + }); +} + +test("probeCdpReadiness: a CDP that answers /json/new but never replies to navigate/evaluate is wedged", async () => { + const fx = await startFixtureCdp({ wedged: true }); + try { + const r = await probeCdpReadiness({ cdpBase: fx.base, timeoutMs: 2000 }); + assert.equal(r.ok, false); + assert.match(r.detail, /never replied|wedged/); + } finally { + await fx.close(); + } +}); + +test("probeCdpReadiness: a healthy renderer passes", async () => { + const fx = await startFixtureCdp({ wedged: false }); + try { + const r = await probeCdpReadiness({ cdpBase: fx.base, timeoutMs: 4000 }); + assert.deepEqual(r, { ok: true }); + } finally { + await fx.close(); + } +}); + +test("restartAllowed: at most once per 15 minutes", () => { + const now = Date.parse("2026-11-05T12:00:00.000Z"); + assert.equal(restartAllowed(null, now), true); + assert.equal(restartAllowed("2026-11-05T11:50:00.000Z", now), false); + assert.equal(restartAllowed("2026-11-05T11:45:00.000Z", now), true); + assert.equal(restartAllowed("not-a-date", now), true); +}); + +test("attemptBoundedRestart: restarts once, then the persisted bound skips", async () => { + const outDir = await mkdtemp(join(tmpdir(), "meta-exporter-restart-")); + let calls = 0; + const restart = async () => { calls += 1; }; + const first = await attemptBoundedRestart({ outDir, now: new Date("2026-11-05T12:00:00.000Z"), restart }); + assert.equal(first.result, "restarted"); + assert.equal(calls, 1); + const state = JSON.parse(await readFile(join(outDir, ".helium-restart.json"), "utf8")); + assert.equal(state.lastRestartAt, "2026-11-05T12:00:00.000Z"); + const second = await attemptBoundedRestart({ outDir, now: new Date("2026-11-05T12:05:00.000Z"), restart }); + assert.equal(second.result, "skipped-cooldown"); + assert.equal(calls, 1); +}); + +test("attemptBoundedRestart: a failed restart still persists the cooldown bound", async () => { + const outDir = await mkdtemp(join(tmpdir(), "meta-exporter-restart-fail-")); + let calls = 0; + const restart = async () => { calls += 1; throw new Error("restart boom"); }; + const first = await attemptBoundedRestart({ outDir, now: new Date("2026-11-05T12:00:00.000Z"), restart }); + assert.equal(first.result, "restart-failed"); + assert.equal(calls, 1); + const state = JSON.parse(await readFile(join(outDir, ".helium-restart.json"), "utf8")); + assert.equal(state.lastRestartAt, "2026-11-05T12:00:00.000Z"); + const second = await attemptBoundedRestart({ outDir, now: new Date("2026-11-05T12:05:00.000Z"), restart }); + assert.equal(second.result, "skipped-cooldown"); + assert.equal(calls, 1); +}); + +test("documents: page-not-ready is a distinct status/exit and recovery is recorded", () => { + assert.notEqual(PAGE_NOT_READY_EXIT, 5); + const recovery = { action: "restart", unit: "helium-cdp.service", at: "2026-11-05T12:00:00.000Z", result: "restarted" }; + const bad = failureDocument({ attemptedAt: "2026-11-05T12:00:00.000Z", status: "page-not-ready", detail: "wedged", recovery }); + assert.equal(bad.status, "page-not-ready"); + assert.deepEqual(bad.recovery, recovery); + assert.equal("windows" in bad, false); + const plain = failureDocument({ attemptedAt: "2026-11-05T12:00:00.000Z", status: "session-expired", detail: "HTTP 401" }); + assert.equal("recovery" in plain, false); +}); diff --git a/pm-stack/meta-exporter/meta-quota-export.timer b/pm-stack/meta-exporter/meta-quota-export.timer new file mode 100644 index 000000000..a639cf429 --- /dev/null +++ b/pm-stack/meta-exporter/meta-quota-export.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Run the Meta quota exporter every 15 minutes — code#1301 Phase 1 + +[Timer] +OnCalendar=*:0/15 +RandomizedDelaySec=20 +Persistent=true +Unit=meta-quota-export.service + +[Install] +WantedBy=timers.target