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
42 changes: 42 additions & 0 deletions pm-stack/aggregator/scripts/gather-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -296,6 +306,37 @@ async function runOpenDesignRenewal(tickAt: string): Promise<void> {
}
}

/**
* 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<void> {
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";
Expand Down Expand Up @@ -608,6 +649,7 @@ async function main(): Promise<number> {
// 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
Expand Down
125 changes: 125 additions & 0 deletions pm-stack/aggregator/src/meta-renewal.test.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
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");
});
});
Loading