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
92 changes: 79 additions & 13 deletions pm-stack/aggregator/scripts/gather-quota.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,29 @@
// itself uses.
// 3. The Turso org usage API (#1049): usage + subscription over
// the verified route, token from Bitwarden by name.
// 2. File exports (the Meta Phase-1 convention, #1301): producers
// the module cannot reach write latest.json documents on the
// laptop (v1: Meta, ~/atlas/meta-quota-export/latest.json);
// 2. File exports (the Phase-1 convention, #1301): producers the
// module cannot reach write latest.json documents on the laptop;
// the gatherer ingests them in the same tick. A document older
// than 30 minutes means the producer is unreachable — an error
// entry, never zeros.
// entry, never zeros. The v1 producer (Meta's dev.meta.ai
// console scrape) was retired 2026-11-03: Drew's ruling is that
// quota is gathered by asking OpenCode — family 5 below is its
// replacement, and the producer list is empty today.
// 4. The native ClinePass token adapter (#1159, src/clinepass-
// adapter.ts on the #1153 framework): fills the ClinePass row
// when the OpenChamber module did not already produce a fresh
// one this tick, and only when CLINEPASS_CREDENTIAL_REF names
// a credential reference on this host. An expired token is
// session-expired / re-login with the last-known row retained
// (#1268) — never a 0% row.
// 5. The Meta module ask (2026-11-03): the provider listing
// (family 1) filters providers whose session door is disabled
// in the opencode config, and `meta` is disabled as a direct
// door — sessions reach the pool through model routes — so the
// listing never names it. The gatherer asks the module for meta
// explicitly (runMetaModule): the read runs through OpenCode's
// own credential machinery, which is what gathering quota by
// asking OpenCode means for a route-only pool.
//
// Outputs:
// - quota-current.json — the latest-state contract (model.ts
Expand Down Expand Up @@ -65,7 +75,7 @@
// OPENCODE_DB_PATH (~/.local/share/opencode/opencode.db),
// QUOTA_CURRENT_PATH, QUOTA_HEARTBEAT_PATH,
// QUOTA_GATHERER_STATE_PATH, QUOTA_SNAPSHOTS_DIR (./snapshots),
// USAGE_SNAPSHOT_OUTBOX_PATH, META_QUOTA_EXPORT_PATH,
// USAGE_SNAPSHOT_OUTBOX_PATH,
// QUOTA_GATHER_TIMEOUT_MS (15000),
// QUOTA_GATHER_CONCURRENCY (6), TURSO_API_TOKEN (else the
// Bitwarden secret turso.platform-api-token-muse-cli, resolved
Expand Down Expand Up @@ -135,14 +145,16 @@ const timeoutMs = Number(process.env.QUOTA_GATHER_TIMEOUT_MS ?? 15_000);
const gatherConcurrency = Number(process.env.QUOTA_GATHER_CONCURRENCY ?? 6);
const OBSERVED_BY = "quota-gatherer";

/** File-export producers ingested each tick (the #1301 convention). */
const FILE_EXPORTS = [
{
key: "meta",
path: process.env.META_QUOTA_EXPORT_PATH ?? join(HOME, "atlas/meta-quota-export/latest.json"),
staleMs: 30 * 60_000,
},
];
/**
* File-export producers ingested each tick (the #1301 convention).
* The v1 producer — Meta, ~/atlas/meta-quota-export/latest.json, a
* dev.meta.ai console scrape — was retired 2026-11-03: quota is
* gathered by asking OpenCode (Drew's ruling), and the module's own
* Meta provider replaced the scrape (see runMetaModule). The list
* stays, empty, for the next producer the module cannot reach;
* entryFromFileExport keeps the convention's mapping tested.
*/
const FILE_EXPORTS: { key: string; path: string; staleMs: number }[] = [];

interface QuotaModule {
listConfiguredQuotaProviders: (opts?: { includeDisabled?: boolean }) => Promise<string[]>;
Expand Down Expand Up @@ -420,6 +432,46 @@ async function runClinePass(tickIso: string): Promise<ProviderRun | null> {
};
}

/**
* The Meta module ask (2026-11-03, Drew's ask-OpenCode ruling): the
* quota module's provider listing filters out providers whose
* session door is disabled in the opencode config, and `meta` is
* disabled as a direct door (sessions reach the pool through model
* routes), so the listing never names it and the plain tick never
* asked — the board's Meta row went dark even though OpenCode holds
* the pool's credential and the module's Meta provider reads the
* plan's own usage endpoint with it. The gatherer asks explicitly,
* the same out-of-band registration pattern as the native ClinePass
* adapter. No outer timeout wraps the ask: the provider self-times
* out per request (15s), and its account-token fallback is a second
* request — clipping the pair at the generic 15s cap could turn a
* slow success into a false error row.
*/
async function runMetaModule(quota: QuotaModule, tickIso: string): Promise<ProviderRun> {
const t0 = Date.now();
try {
const results = await quota.fetchQuotaForProviderInstances("meta");
const entries = results.map((r) => entryFromResult(r, tickIso));
const anyOk = entries.some((e) => e.state === "ok");
const firstBad = entries.find((e) => e.state !== "ok");
return {
id: "meta",
state: anyOk ? "ok" : "error",
ms: Date.now() - t0,
entries,
...(!anyOk && firstBad?.error ? { error: firstBad.error } : {}),
};
} catch (err) {
return {
id: "meta",
state: "error",
ms: Date.now() - t0,
entries: [],
error: safeProviderReason(err instanceof Error ? err.message : String(err)),
};
}
}

interface ProviderRun {
id: string;
state: "ok" | "error";
Expand Down Expand Up @@ -559,6 +611,20 @@ async function main(): Promise<number> {
}
}

// 2026-11-03: the Meta module ask (see runMetaModule). Exactly one
// meta run survives, mirroring the ClinePass discipline above: a
// fresh listed run (the door re-enabled someday) wins and the ask
// is skipped; otherwise the ask replaces the listed run, or is
// appended when the listing never named meta.
const metaIdx = runs.findIndex((r) => r.id === "meta");
if (metaIdx !== -1 && runs[metaIdx].entries.some((e) => e.state === "ok")) {
console.log("quota-gatherer: meta ok via provider listing - explicit module ask skipped");
} else {
const metaRun = await runMetaModule(quota, tickAt);
if (metaIdx === -1) runs.push(metaRun);
else runs[metaIdx] = metaRun;
}

// The Claude auth source exposes an expiry timestamp. Persist only that
// metadata and its source class, never the credential object or values.
const claudeRun = runs.find((run) => run.id === "claude");
Expand Down
28 changes: 25 additions & 3 deletions pm-stack/aggregator/src/quota-extract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -559,7 +559,7 @@ const SHELL_POOLS: QuotaPool[] = [
plan: "Go",
state: "healthy",
windows: [],
note: "Usage uninstrumented — no current read. API route verified; a manual dashboard read is required for a percentage.",
note: "No dated read. Live windows arrive through the quota gatherer (the OpenCode opendesign credential, read by the OpenChamber quota module) and are overlaid onto this pool by overlayQuotaCurrent.",
},
{
id: "deepseek:api",
Expand Down Expand Up @@ -621,6 +621,28 @@ export function poolFilteredByDisabled(poolId: string, disabledProviderIds: Read
return poolProviderIds(poolId).every((id) => disabledProviderIds.has(id));
}

/**
* Pools that stay on the board even when every door provider is
* disabled — #1114's filter yields to this list. The filter exists so
* the board never presents a pool nobody can burn; an exempt pool IS
* burned (through the route layer, not the disabled direct door) and
* its quota is measured through OpenCode's credential machinery, so
* hiding it would leave a live pool unreported. Drew, 2026-11-03:
* meta and opendesign are standard report members and must show real
* quotas gathered by asking OpenCode. Today the list holds only
* meta:high-usage: the deployed config disables the `meta` provider
* as a direct session door, which otherwise filtered the pool at
* assembly and left the board with no Meta row at all, while the
* gatherer's module read (serviceId meta:high-usage) had no pool to
* land on.
*/
export const FILTER_EXEMPT_POOL_IDS: ReadonlySet<string> = new Set(["meta:high-usage"]);

/** True when the disabled-door filter must not drop this pool. */
export function poolFilterExempt(poolId: string): boolean {
return FILTER_EXEMPT_POOL_IDS.has(poolId);
}

/**
* Extract every pool's freshest dated read from the quota view text.
*
Expand All @@ -644,7 +666,7 @@ export function extractQuotaPools(
): QuotaPool[] {
const pools: QuotaPool[] = [];
for (const spec of POOL_SPECS) {
if (poolFilteredByDisabled(spec.id, disabledProviderIds)) {
if (!poolFilterExempt(spec.id) && poolFilteredByDisabled(spec.id, disabledProviderIds)) {
onFiltered?.(spec.id, poolProviderIds(spec.id).join(","));
continue;
}
Expand Down Expand Up @@ -683,7 +705,7 @@ export function extractQuotaPools(
pools.push(pool);
}
const shells = SHELL_POOLS.filter((p) => {
if (!poolFilteredByDisabled(p.id, disabledProviderIds)) return true;
if (poolFilterExempt(p.id) || !poolFilteredByDisabled(p.id, disabledProviderIds)) return true;
onFiltered?.(p.id, poolProviderIds(p.id).join(","));
return false;
});
Expand Down
4 changes: 4 additions & 0 deletions pm-stack/aggregator/src/quota-gather-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,10 @@ export function serviceIdFor(providerId: string): string {
return "cline-pass:cline-pass";
case "deepseek":
return "deepseek:api";
case "meta":
return "meta:high-usage";
case "opendesign":
return "opendesign:go";
default:
return providerId;
}
Expand Down
2 changes: 2 additions & 0 deletions pm-stack/aggregator/test/quota-gather-map.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -532,6 +532,8 @@ describe("serviceIdFor", () => {
test("known pools map to hub ids; others pass through", () => {
expect(serviceIdFor("codex")).toBe("openai:codex");
expect(serviceIdFor("deepseek")).toBe("deepseek:api");
expect(serviceIdFor("meta")).toBe("meta:high-usage");
expect(serviceIdFor("opendesign")).toBe("opendesign:go");
expect(serviceIdFor("openai.alternate")).toBe("openai.alternate");
});
});
Expand Down
18 changes: 11 additions & 7 deletions pm-stack/aggregator/test/quota.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -372,16 +372,20 @@ describe("disabled_providers enforcement (#1114)", () => {
const pools = extractQuotaPools(VIEW, NOW, disabled, (poolId, providerId) => filtered.push([poolId, providerId]));
const ids = pools.map((p) => p.id);
expect(ids).not.toContain("openai:codex");
expect(ids).not.toContain("meta:high-usage");
expect(filtered).toEqual([
["meta:high-usage", "meta"],
["openai:codex", "openai"],
]);
expect(filtered).toEqual([["openai:codex", "openai"]]);
const choices = computeChoices(pools, NOW.getTime());
const named = [...choices.hasHeadroom, ...choices.burnBeforeReset, ...choices.doNotStart];
expect(named).not.toContain("openai:codex");
expect(named).not.toContain("meta:high-usage");
for (const id of named) expect(disabled.has(poolProviderId(id))).toBe(false);
// The one exemption (Drew, 2026-11-03): meta:high-usage is a
// standard report member whose quota is gathered by asking
// OpenCode; its disabled entry is the direct session door only,
// so the pool stays on the board — and in guidance — while
// every other named pool still answers to an enabled door.
expect(ids).toContain("meta:high-usage");
for (const id of named) {
if (id === "meta:high-usage") continue;
expect(disabled.has(poolProviderId(id))).toBe(false);
}
});

test("the Claude pool's door is claude-code: disabling it filters anthropic:claude-pro", () => {
Expand Down