From f4b1bd8aea36fe3e419cf7cb14073b501ecaa0b1 Mon Sep 17 00:00:00 2001 From: Archer Date: Thu, 5 Nov 2026 10:39:28 -0600 Subject: [PATCH] =?UTF-8?q?feat(quota):=20Meta=20session=20keeper=20?= =?UTF-8?q?=E2=80=94=20exporter-probe=20watch,=20unit=20re-arm,=20first-ti?= =?UTF-8?q?ck=20alert=20(#6079)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Meta auth lives entirely in the laptop Helium dev.meta.ai session: no stored credential to slide or re-capture, no expiry the portal exposes. Its Nov 3-5 death went unalerted for ~40h because the meta-quota-export units had been renamed to .backup (Nov 1) and the gatherer silently retained last-known. The keeper runs on every gather tick: fresh+ok exporter document = session valid; expired or stale = re-arm units (restoring .backup renames), take a fresh probe; still expired = attention + alert in meta-renewal.json from the first bad tick, naming the human re-login step (Meta emails a code). Fail-soft like the OpenDesign keeper. 6 new tests; aggregator suite 1501 pass / 19 fail (the known pre-existing named set); tsc clean. --- pm-stack/aggregator/scripts/gather-quota.ts | 42 ++++ pm-stack/aggregator/src/meta-renewal.test.ts | 125 ++++++++++ pm-stack/aggregator/src/meta-renewal.ts | 244 +++++++++++++++++++ 3 files changed, 411 insertions(+) create mode 100644 pm-stack/aggregator/src/meta-renewal.test.ts create mode 100644 pm-stack/aggregator/src/meta-renewal.ts diff --git a/pm-stack/aggregator/scripts/gather-quota.ts b/pm-stack/aggregator/scripts/gather-quota.ts index 69a514849a..089d57a65b 100755 --- a/pm-stack/aggregator/scripts/gather-quota.ts +++ b/pm-stack/aggregator/scripts/gather-quota.ts @@ -28,6 +28,15 @@ // a quota source. Fail-soft: a keeper error never fails the tick. // (Its credential-store accessors live in the OpenChamber lib // the store was born in — store plumbing, not a reading path.) +// 1b. The Meta session keeper (src/meta-renewal.ts, same rule): +// Meta's quota functions ride the laptop Helium profile's +// dev.meta.ai session — no stored credential exists to +// maintain — so the keeper watches the meta-quota-export probe +// document each tick, re-arms the exporter units if they were +// renamed away (the 2026-11-01 failure), takes a fresh probe, +// and records the verdict in meta-renewal.json with an alert +// from the first bad tick when the session is truly logged +// out. Fail-soft like the OpenDesign keeper. // 2. The subcommand, twice: the configured listing // (`opencode quota --json`) and the explicit ask // (`opencode quota --json meta command-code`) — providers whose @@ -110,6 +119,7 @@ import { import { SnapshotStore, isSnapshotRecord, snapshotKey } from "../src/snapshots.ts"; import { safeProviderReason } from "../src/credential-lifecycle.ts"; import { renewOpenDesignSession, type OpenDesignCredentialLike } from "../src/opendesign-renewal.ts"; +import { renewMetaSession } from "../src/meta-renewal.ts"; const PKG = join(dirname(fileURLToPath(import.meta.url)), ".."); const HOME = homedir(); @@ -296,6 +306,37 @@ async function runOpenDesignRenewal(tickAt: string): Promise { } } +/** + * The Meta session keeper run (src/meta-renewal.ts, Drew's + * 2026-11-05 auto-renewal rule). Meta's quota functions ride the + * laptop Helium profile's dev.meta.ai session — no stored credential + * exists for a keeper to maintain, so this keeper watches the + * meta-quota-export probe document instead: fresh + ok = session + * valid; expired or silent = re-arm the exporter units if they were + * renamed away, take a fresh probe, and if the session is truly + * logged out raise an alert in meta-renewal.json from the first bad + * tick (re-login is a human step — Meta emails a code). Fail-soft, + * same contract as the OpenDesign keeper. + */ +async function runMetaRenewal(tickAt: string): Promise { + if (process.env.META_RENEWAL_DISABLED === "1") return; + try { + const state = await renewMetaSession({ + statePath: process.env.META_RENEWAL_STATE_PATH ?? join(dirname(currentPath), "meta-renewal.json"), + ...(process.env.META_EXPORTER_LATEST_PATH ? { latestPath: process.env.META_EXPORTER_LATEST_PATH } : {}), + now: () => new Date(tickAt), + log: (line) => console.log(`quota-gatherer: ${line}`), + }); + if (state.status === "attention") { + console.log(`quota-gatherer: meta-renewal ATTENTION ${state.alert ?? ""}`); + } + } catch (err) { + console.log( + `quota-gatherer: meta-renewal failed-soft: ${safeProviderReason(err instanceof Error ? err.message : String(err))}`, + ); + } +} + interface ProviderRun { id: string; state: "ok" | "error"; @@ -608,6 +649,7 @@ async function main(): Promise { // The OpenDesign keeper runs first: a session renewed this tick is // the one the subcommand's OpenDesign read uses. await runOpenDesignRenewal(tickAt); + await runMetaRenewal(tickAt); // The single source: every reading this tick comes from the // opencode quota subcommand. A failure to run it, or output that diff --git a/pm-stack/aggregator/src/meta-renewal.test.ts b/pm-stack/aggregator/src/meta-renewal.test.ts new file mode 100644 index 0000000000..9d3c804e05 --- /dev/null +++ b/pm-stack/aggregator/src/meta-renewal.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, test } from "bun:test"; +import { mkdtemp, readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + renewMetaSession, + type MetaExporterDoc, + type MetaRenewalState, +} from "./meta-renewal.ts"; + +const NOW = new Date("2026-11-05T16:45:00.000Z"); +const fresh = (minsAgo: number): string => + new Date(NOW.getTime() - minsAgo * 60_000).toISOString(); + +async function statePath(): Promise { + const dir = await mkdtemp(join(tmpdir(), "meta-renewal-")); + return join(dir, "meta-renewal.json"); +} + +const okDoc = (minsAgo = 5): MetaExporterDoc => ({ + status: "ok", + measuredAt: fresh(minsAgo), + attemptedAt: fresh(minsAgo), +}); +const expiredDoc = (): MetaExporterDoc => ({ + status: "session-expired", + measuredAt: null, + attemptedAt: fresh(1), +}); + +describe("meta session keeper", () => { + test("a fresh ok exporter document is a valid session, no recovery attempted", async () => { + let ran = false; + const state = await renewMetaSession({ + statePath: await statePath(), + now: () => NOW, + readLatest: async () => okDoc(), + ensureExporterArmed: async () => "armed", + runExporter: async () => { + ran = true; + }, + }); + expect(state.status).toBe("valid"); + expect(state.recovery.attempted).toBe(false); + expect(state.alert).toBeNull(); + expect(state.lastGoodAt).toBe(fresh(5)); + expect(ran).toBe(false); + }); + + test("an expired session that a fresh probe fixes is recovered", async () => { + let probes = 0; + const state = await renewMetaSession({ + statePath: await statePath(), + now: () => NOW, + readLatest: async () => (++probes === 1 ? expiredDoc() : okDoc(0)), + ensureExporterArmed: async () => "armed", + runExporter: async () => undefined, + }); + expect(state.status).toBe("recovered"); + expect(state.recovery).toEqual({ attempted: true, result: "recovered" }); + expect(state.alert).toBeNull(); + }); + + test("units restored from .backup during recovery are reported as such", async () => { + let probes = 0; + const state = await renewMetaSession({ + statePath: await statePath(), + now: () => NOW, + readLatest: async () => (++probes === 1 ? expiredDoc() : okDoc(0)), + ensureExporterArmed: async () => "restored", + runExporter: async () => undefined, + }); + expect(state.status).toBe("recovered"); + expect(state.recovery.result).toBe("recovered-units-restored"); + }); + + test("a still-expired session raises an alert from the first bad tick, and alertSince persists", async () => { + const path = await statePath(); + const deps = { + statePath: path, + readLatest: async () => expiredDoc(), + ensureExporterArmed: async () => "armed" as const, + runExporter: async () => undefined, + }; + const first = await renewMetaSession({ ...deps, now: () => NOW }); + expect(first.status).toBe("attention"); + expect(first.alert).toContain("emails a login code"); + expect(first.alertSince).toBe(NOW.toISOString()); + + const later = new Date(NOW.getTime() + 15 * 60_000); + const second = await renewMetaSession({ ...deps, now: () => later }); + expect(second.status).toBe("attention"); + expect(second.alertSince).toBe(NOW.toISOString()); + + const onDisk = JSON.parse(await readFile(path, "utf8")) as MetaRenewalState; + expect(onDisk.provider).toBe("meta"); + expect(onDisk.alertSince).toBe(NOW.toISOString()); + }); + + test("a stale ok document (exporter silent) is attention, not valid", async () => { + const state = await renewMetaSession({ + statePath: await statePath(), + now: () => NOW, + readLatest: async () => okDoc(120), + ensureExporterArmed: async () => "armed", + runExporter: async () => undefined, + }); + expect(state.status).toBe("attention"); + expect(state.lastGoodAt).toBe(fresh(120)); + expect(state.alert).toContain("not producing fresh readings"); + }); + + test("missing exporter units produce the units-missing alert", async () => { + const state = await renewMetaSession({ + statePath: await statePath(), + now: () => NOW, + readLatest: async () => null, + ensureExporterArmed: async () => "missing", + runExporter: async () => undefined, + }); + expect(state.status).toBe("attention"); + expect(state.recovery.result).toBe("exporter-missing"); + expect(state.alert).toContain("units"); + }); +}); diff --git a/pm-stack/aggregator/src/meta-renewal.ts b/pm-stack/aggregator/src/meta-renewal.ts new file mode 100644 index 0000000000..a28b6e14ad --- /dev/null +++ b/pm-stack/aggregator/src/meta-renewal.ts @@ -0,0 +1,244 @@ +/** + * Meta (dev.meta.ai) session keeper — Drew's provider browser-auth + * auto-renewal rule (2026-11-05) applied to the one provider whose + * auth lives ENTIRELY in a browser profile. + * + * Why Meta needs a different keeper shape than OpenDesign: both Meta + * quota read paths — the portal read inside the opencode meta quota + * provider, and the meta-quota-export file exporter — ride the + * laptop Helium profile's dev.meta.ai session. There is no stored + * credential for a keeper to slide or re-capture, and the portal + * exposes no session expiry to watch. What CAN be watched is the + * probe the exporter already makes: meta-quota-export evaluates its + * fetch inside the browser's own page context every 15 minutes and + * writes the verdict to ~/atlas/meta-quota-export/latest.json. + * + * How the last death went (2026-11-01 → 2026-11-05): the exporter's + * systemd units were renamed to .backup on Nov 1, so nothing even + * attempted a read; the session expired; the gatherer retained + * last-known for ~40h with no alert anywhere. This keeper exists so + * that sequence cannot repeat silently: + * + * 1. Every gather tick: read the exporter's latest document. + * Fresh + status "ok" = the browser session is valid. + * 2. Session-expired, or the exporter silent past the stale + * horizon: attempt recovery — first verify the exporter units + * are armed, restoring them from their .backup names if the + * Nov-1 rename is ever found again, then run the exporter once + * and re-read its document. A fresh "ok" = recovered. + * 3. Still expired: the session is truly logged out and re-login + * is a human step (Meta emails a login code). The state file + * carries an alert from the FIRST bad tick — while last-good + * data is still on the board — instead of silence at zero. + * + * The state file (meta-renewal.json beside quota-current.json) is + * rewritten every run. No credential value is read, logged, or + * written anywhere in this module: the probe document carries no + * secrets, and the session itself never leaves the browser. + */ + +import { execFile } from "node:child_process"; +import { access, mkdir, readFile, rename } from "node:fs/promises"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { promisify } from "node:util"; + +const execFileAsync = promisify(execFile); + +/** Two exporter ticks (2 × 15 min) without a fresh document = stale. */ +export const STALE_MS = 30 * 60 * 1000; + +export interface MetaExporterDoc { + status: string | null; + measuredAt: string | null; + attemptedAt: string | null; +} + +export type EnsureArmedResult = "armed" | "restored" | "missing"; + +export interface MetaRenewalState { + provider: "meta"; + checkedAt: string; + status: "valid" | "recovered" | "attention"; + exporterStatus: string | null; + lastGoodAt: string | null; + recovery: { attempted: boolean; result: string | null }; + alert: string | null; + alertSince: string | null; +} + +export interface MetaRenewalDeps { + statePath: string; + latestPath?: string; + now?: () => Date; + staleMs?: number; + /** Injectable for tests; defaults read the exporter's document. */ + readLatest?: () => Promise; + ensureExporterArmed?: () => Promise; + runExporter?: () => Promise; + log?: (line: string) => void; +} + +export const defaultLatestPath = (): string => + join(homedir(), "atlas", "meta-quota-export", "latest.json"); + +const defaultReadLatest = async (latestPath: string): Promise => { + try { + const parsed = JSON.parse(await readFile(latestPath, "utf8")) as { + status?: unknown; + measuredAt?: unknown; + attemptedAt?: unknown; + }; + return { + status: typeof parsed.status === "string" ? parsed.status : null, + measuredAt: typeof parsed.measuredAt === "string" ? parsed.measuredAt : null, + attemptedAt: typeof parsed.attemptedAt === "string" ? parsed.attemptedAt : null, + }; + } catch { + return null; + } +}; + +const defaultEnsureExporterArmed = async (): Promise => { + const unitDir = join(homedir(), ".config", "systemd", "user"); + const timer = join(unitDir, "meta-quota-export.timer"); + const service = join(unitDir, "meta-quota-export.service"); + const exists = async (p: string): Promise => + access(p).then( + () => true, + () => false, + ); + if ((await exists(timer)) && (await exists(service))) return "armed"; + const timerBackup = `${timer}.backup`; + const serviceBackup = `${service}.backup`; + if ((await exists(timerBackup)) && (await exists(serviceBackup))) { + await rename(serviceBackup, service); + await rename(timerBackup, timer); + await execFileAsync("systemctl", ["--user", "daemon-reload"]).catch(() => undefined); + await execFileAsync("systemctl", ["--user", "enable", "--now", "meta-quota-export.timer"]).catch( + () => undefined, + ); + return "restored"; + } + return "missing"; +}; + +const defaultRunExporter = async (): Promise => { + await execFileAsync("systemctl", ["--user", "start", "meta-quota-export.service"], { + timeout: 130_000, + }); +}; + +const readPreviousState = async (statePath: string): Promise => { + try { + return JSON.parse(await readFile(statePath, "utf8")) as MetaRenewalState; + } catch { + return null; + } +}; + +const writeState = async (statePath: string, state: MetaRenewalState): Promise => { + await mkdir(dirname(statePath), { recursive: true }); + const tmp = `${statePath}.tmp-${process.pid}`; + const { writeFile } = await import("node:fs/promises"); + await writeFile(tmp, JSON.stringify(state, null, 2) + "\n", "utf8"); + await rename(tmp, statePath); +}; + +const isFresh = (doc: MetaExporterDoc | null, now: Date, staleMs: number): boolean => { + if (!doc?.measuredAt) return false; + const t = Date.parse(doc.measuredAt); + return Number.isFinite(t) && now.getTime() - t < staleMs; +}; + +/** + * One keeper cycle. Fail-soft by contract: it always resolves with a + * state object (which it also persists); it never throws, so the + * gatherer's tick can call it unconditionally. + */ +export async function renewMetaSession(deps: MetaRenewalDeps): Promise { + const now = (deps.now ?? (() => new Date()))(); + const staleMs = deps.staleMs ?? STALE_MS; + const latestPath = deps.latestPath ?? defaultLatestPath(); + const readLatest = deps.readLatest ?? (() => defaultReadLatest(latestPath)); + const ensureExporterArmed = deps.ensureExporterArmed ?? defaultEnsureExporterArmed; + const runExporter = deps.runExporter ?? defaultRunExporter; + const log = deps.log ?? (() => undefined); + const previous = await readPreviousState(deps.statePath); + + const finish = async ( + partial: Omit, + ): Promise => { + const state: MetaRenewalState = { + provider: "meta", + checkedAt: now.toISOString(), + alertSince: partial.alert ? (previous?.alert ? previous.alertSince : now.toISOString()) : null, + ...partial, + }; + await writeState(deps.statePath, state).catch(() => undefined); + log( + `meta-renewal: status=${state.status} exporter=${state.exporterStatus ?? "none"} lastGoodAt=${state.lastGoodAt ?? "never"} recovery=${state.recovery.result ?? "not-attempted"}${state.alert ? ` alert=${state.alert}` : ""}`, + ); + return state; + }; + + let doc = await readLatest().catch(() => null); + const lastGoodAt = + doc?.status === "ok" && doc.measuredAt ? doc.measuredAt : (previous?.lastGoodAt ?? null); + + if (doc?.status === "ok" && isFresh(doc, now, staleMs)) { + return finish({ + status: "valid", + exporterStatus: doc.status, + lastGoodAt, + recovery: { attempted: false, result: "not-attempted" }, + alert: null, + }); + } + + // Recovery: re-arm the exporter if its units were renamed away, + // then take a fresh probe. + let recoveryResult: string; + try { + const armed = await ensureExporterArmed(); + if (armed === "missing") { + recoveryResult = "exporter-missing"; + } else { + await runExporter(); + doc = await readLatest().catch(() => null); + recoveryResult = + doc?.status === "ok" && isFresh(doc, now, staleMs) + ? armed === "restored" + ? "recovered-units-restored" + : "recovered" + : "still-expired"; + } + } catch (error) { + recoveryResult = `error:${error instanceof Error ? error.message : String(error)}`; + } + + if (recoveryResult === "recovered" || recoveryResult === "recovered-units-restored") { + return finish({ + status: "recovered", + exporterStatus: doc?.status ?? null, + lastGoodAt: doc?.measuredAt ?? lastGoodAt, + recovery: { attempted: true, result: recoveryResult }, + alert: null, + }); + } + + const darkSince = lastGoodAt ?? previous?.lastGoodAt ?? null; + const alert = + recoveryResult === "exporter-missing" + ? "Meta quota exporter units (meta-quota-export.service/.timer) are missing from ~/.config/systemd/user and no .backup copies exist; Meta measurement has no probe. Restore the units to re-arm the Meta session keeper." + : doc?.status === "session-expired" + ? `dev.meta.ai session is logged out in the laptop Helium profile; Meta re-login needs a human step (Meta emails a login code) in that profile. Meta measurement is dark${darkSince ? ` since last good ${darkSince}` : ""} until then.` + : `Meta quota exporter is not producing fresh readings (status=${doc?.status ?? "no document"}, recovery=${recoveryResult}); check meta-quota-export.timer and the laptop Helium dev.meta.ai session.`; + return finish({ + status: "attention", + exporterStatus: doc?.status ?? null, + lastGoodAt: darkSince, + recovery: { attempted: true, result: recoveryResult }, + alert, + }); +}