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
136 changes: 105 additions & 31 deletions pm-stack/aggregator/scripts/collect-fleet-feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@
// Any failure (no token, bws missing, GraphQL error) omits the
// section and logs only that it was omitted.
// - the AA cost explorer data — Supabase `ainventory` (the AA
// workbook import: v_rankings, v_threshold_metrics,
// import: v_rankings, v_threshold_metrics,
// benchmark_results — both the AA Intelligence Index rows and the
// Coding Agent Index rows, kept as separate benchmark families —
// the Test_Runs sheet, and the price event log's v_current_prices),
// read through v_latest_workbook_batch via the Management API SQL endpoint.
// the Test_Runs data, and the price event log's v_current_prices),
// read through v_latest_import_batch via the Management API SQL endpoint.
// Token plumbing mirrors the Projects read: the Bitwarden secret
// named `supabase.access-token-muse-cli` (the sbp_ management
// token), resolved by resolveBwsSecret and sent only to
Expand Down Expand Up @@ -73,11 +73,12 @@ import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { dnsSectionFromRegister } from "../src/dns.ts";
import { disabledProvidersFromConfig, aaAbsent, aaSectionFromSupabase, type AaRawPayload } from "../src/aa.ts";
import { disabledProvidersFromConfig, aaAbsent, aaSectionFromSupabase, isAaSection, type AaRawPayload } from "../src/aa.ts";
import { normalizeOrchestrationSection, orchestrationSectionProblem, type FleetFeed } from "../src/feed.ts";
import { computeCheckoutDrift } from "../src/checkout-drift.ts";
import type {
AaFeedSection,
AaSection,
DnsSection,
JulesSummary,
OrchestrationSection,
Expand Down Expand Up @@ -265,18 +266,18 @@ async function resolveProjectToken(): Promise<string | null> {
// --- AA cost explorer (Supabase ainventory) ---------------------------------
// One SQL statement returns the whole section payload as a single
// jsonb object (keys pre-renamed to the section's camelCase). The
// Test_Runs sheet rides as raw rows; src/aa.ts maps them by the
// sheet's own header row and computes pool/catalog coverage.
// Test_Runs data rides as raw rows; src/aa.ts maps them by
// their own header row and computes pool/catalog coverage.

const AA_SQL = `
select jsonb_build_object(
'batch', (select import_batch::text from ainventory.v_latest_workbook_batch),
'batch', (select import_batch::text from ainventory.v_latest_import_batch),
'sources', coalesce((
select jsonb_agg(jsonb_build_object(
'name', name, 'kind', kind, 'importedAt', imported_at, 'driveModifiedAt', drive_modified_at
) order by id)
from ainventory.sources
where import_batch = (select import_batch from ainventory.v_latest_workbook_batch)
where import_batch = (select import_batch from ainventory.v_latest_import_batch)
), '[]'::jsonb),
'rankings', coalesce((
select jsonb_agg(jsonb_build_object(
Expand Down Expand Up @@ -308,14 +309,14 @@ select jsonb_build_object(
'intelligence', value_num, 'costPerTaskUsd', cost_per_task_usd, 'speedTps', speed_tps
) order by model_name, effort)
from ainventory.benchmark_results br
where br.import_batch = (select import_batch from ainventory.v_latest_workbook_batch)
where br.import_batch = (select import_batch from ainventory.v_latest_import_batch)
and br.benchmark like 'AA Intelligence Index%'
and br.metric = 'intelligence_index'
), '[]'::jsonb),
'testRunRows', coalesce((
select jsonb_agg(jsonb_build_object('rowIndex', row_index, 'cells', data->'cells') order by row_index)
from ainventory.sheet_rows sr
where sr.import_batch = (select import_batch from ainventory.v_latest_workbook_batch)
where sr.import_batch = (select import_batch from ainventory.v_latest_import_batch)
and sr.sheet_name = 'Test_Runs'
), '[]'::jsonb),
'cai', coalesce((
Expand All @@ -332,7 +333,7 @@ select jsonb_build_object(
'snapshotDate', nullif(raw->>'snapshot_date', ''), 'sourceUrl', nullif(raw->>'source_url', '')
) order by value_num desc nulls last, model_name)
from ainventory.benchmark_results br
where br.import_batch = (select import_batch from ainventory.v_latest_workbook_batch)
where br.import_batch = (select import_batch from ainventory.v_latest_import_batch)
and br.benchmark like 'Artificial Analysis Coding Agent Index%'
and br.metric = 'cai_index_score'
), '[]'::jsonb),
Expand All @@ -347,48 +348,121 @@ select jsonb_build_object(
), '[]'::jsonb)
) as aa`;

const AA_BATCH_SQL = `select import_batch::text as batch from ainventory.v_latest_import_batch`;

/**
* Build the AA feed section. Fail-soft like every other section, but
* with the failure stated in the section itself (the absent form), so
* the dashboard explains the gap instead of silently going stale.
* The management token is only ever sent to api.supabase.com and is
* never logged or written to the feed.
* The last-good AA section store (code#3332): kept beside the feed so a
* transient Supabase failure degrades to the previous good payload
* instead of blanking the explorer. Keyed by the import batch and the
* opencode config fingerprint — the section is rebuilt when either
* changes and reused untouched while neither does.
*/
const aaLastGoodPath = join(dirname(outPath), "aa-last-good.json");

interface AaLastGood {
batch: string;
configFingerprint: string;
section: AaSection;
}

async function readAaLastGood(): Promise<AaLastGood | null> {
try {
const parsed = JSON.parse(await readFile(aaLastGoodPath, "utf8")) as Partial<AaLastGood>;
if (typeof parsed.batch !== "string" || typeof parsed.configFingerprint !== "string") return null;
if (!isAaSection(parsed.section) || parsed.section.status !== "ok") return null;
return { batch: parsed.batch, configFingerprint: parsed.configFingerprint, section: parsed.section };
} catch {
return null;
}
}

async function writeAaLastGood(entry: AaLastGood): Promise<void> {
try {
const tmp = `${aaLastGoodPath}.tmp`;
await writeFile(tmp, JSON.stringify(entry));
await rename(tmp, aaLastGoodPath);
} catch (err) {
console.error(`collector: AA last-good store write failed (${err instanceof Error ? err.message : "error"})`);
}
}

/** The coverage half of the AA section is computed from the opencode
* config, so the reuse key includes the config's fingerprint. */
async function opencodeConfigFingerprint(): Promise<string> {
try {
const st = await stat(opencodeConfigPath);
return `${st.mtimeMs}:${st.size}`;
} catch {
return "unreadable";
}
}

async function supabaseQuery(token: string, ref: string, sql: string): Promise<unknown> {
const res = await fetch(`https://api.supabase.com/v1/projects/${ref}/database/query`, {
method: "POST",
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
body: JSON.stringify({ query: sql }),
signal: AbortSignal.timeout(60_000),
});
if (!res.ok) throw new Error(`Supabase query failed (HTTP ${res.status})`);
return res.json();
}

/**
* Build the AA feed section. Fail-soft like every other section: a
* failed build degrades to the last good payload with a stale marker
* (code#3332), or to the absent form when no good payload exists yet,
* so the dashboard explains the gap. The management token is only ever
* sent to api.supabase.com and is never logged or written to the feed.
*/
async function collectAaSection(generatedAt: string): Promise<AaFeedSection> {
const lastGood = await readAaLastGood();
const degrade = (reason: string): AaFeedSection =>
lastGood ? { ...lastGood.section, stale: true, staleReason: reason } : aaAbsent(reason, generatedAt);
const token = await resolveBwsSecret("supabase.access-token-muse-cli");
if (!token) return aaAbsent("no Supabase management token available (bws)", generatedAt);
if (!token) return degrade("no Supabase management token available (bws)");
// Project ref: env override, else the Bitwarden supabase.project-ref
// secret (the same resolve-by-name discipline as the token), else the
// muse-dev2 project — never the retired muse-dev project.
const ref =
process.env.SUPABASE_PROJECT_REF ?? (await resolveBwsSecret("supabase.project-ref")) ?? "keihfchslgjetkmnmzra";
const fingerprint = await opencodeConfigFingerprint();
// Cheap batch probe first (code#3332): the payload only changes on a
// new import or a config change, so most ticks reuse the last good
// section instead of re-running the full payload query — the query
// pressure was itself causing intermittent Management API 403s.
try {
const rows = (await supabaseQuery(token, ref, AA_BATCH_SQL)) as { batch?: unknown }[];
const batchNow = Array.isArray(rows) && typeof rows[0]?.batch === "string" ? rows[0].batch : null;
if (batchNow && lastGood && batchNow === lastGood.batch && fingerprint === lastGood.configFingerprint) {
console.error("collector: AA section reused (import batch + config unchanged)");
return lastGood.section;
}
} catch {
// Probe failed — fall through to the full query, which produces
// the authoritative result or the degrade reason.
}
let raw: AaRawPayload;
try {
const res = await fetch(`https://api.supabase.com/v1/projects/${ref}/database/query`, {
method: "POST",
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
body: JSON.stringify({ query: AA_SQL }),
signal: AbortSignal.timeout(60_000),
});
if (!res.ok) return aaAbsent(`Supabase query failed (HTTP ${res.status})`, generatedAt);
const rows = (await res.json()) as { aa?: unknown }[];
const rows = (await supabaseQuery(token, ref, AA_SQL)) as { aa?: unknown }[];
if (!Array.isArray(rows) || typeof rows[0]?.aa !== "object" || rows[0].aa === null) {
return aaAbsent("Supabase returned no AA payload", generatedAt);
return degrade("Supabase returned no AA payload");
}
raw = rows[0].aa as AaRawPayload;
} catch (err) {
return aaAbsent(`Supabase unreachable (${err instanceof Error ? err.message : "error"})`, generatedAt);
const msg = err instanceof Error ? err.message : "error";
return degrade(msg.startsWith("Supabase query failed") ? msg : `Supabase unreachable (${msg})`);
}
let configText: string | null = null;
try {
configText = await readFile(opencodeConfigPath, "utf8");
} catch {
console.error("collector: opencode.jsonc unreadable; AA coverage omitted this run");
}
return (
aaSectionFromSupabase(raw, configText, generatedAt) ??
aaAbsent("Supabase payload failed its structural check", generatedAt)
);
const section = aaSectionFromSupabase(raw, configText, generatedAt);
if (!section) return degrade("Supabase payload failed its structural check");
await writeAaLastGood({ batch: section.batch, configFingerprint: fingerprint, section });
return section;
}

async function main(): Promise<void> {
Expand Down
18 changes: 9 additions & 9 deletions pm-stack/aggregator/src/aa.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// The AA cost explorer as data. The source of record is the Supabase
// `ainventory` schema (the AA workbook import: v_rankings,
// v_threshold_metrics, benchmark_results, and the Test_Runs sheet in
// sheet_rows, all read through v_latest_workbook_batch). The collector
// `ainventory` schema (the AA import: v_rankings,
// v_threshold_metrics, benchmark_results, and the Test_Runs data in
// sheet_rows, all read through v_latest_import_batch). The collector
// queries it, assembles the section with the helpers here, and embeds
// it in the fleet feed; the aggregator renders the section as-is.
// Everything in this module is pure and unit-tested (test/aa.test.ts),
Expand Down Expand Up @@ -44,9 +44,9 @@ function boolish(v: unknown): boolean {
return v === true || v === 1 || v === "1" || v === "true";
}

// --- Test_Runs sheet mapping -------------------------------------------------
// --- Test_Runs data mapping -------------------------------------------------

/** One raw sheet_rows row for the Test_Runs sheet: cells as stored. */
/** One raw sheet_rows row for the Test_Runs data: cells as stored. */
export interface SheetRow {
rowIndex: number;
cells: unknown[];
Expand All @@ -68,7 +68,7 @@ const TEST_RUN_FIELDS: Record<string, keyof AaTestRun> = {
/**
* Map raw Test_Runs rows to timing records, keyed off the sheet's own
* header row (the row carrying "test_run_key" among its cells) — a
* workbook column reorder changes nothing here. Rows without a key
* import column reorder changes nothing here. Rows without a key
* are dropped; empty cells become nulls.
*/
export function testRunsFromSheetRows(rows: SheetRow[]): AaTestRun[] {
Expand Down Expand Up @@ -262,7 +262,7 @@ const MODEL_ALIASES = new Map<string, string>([
["deepseek v4 flash", "deepseek v4 1 flash"],
// Meta's config ids carry the 1.0 version the AA family name drops.
["muse wonder 1 0", "muse wonder"],
// AA's workbook family for Qwen's max checkpoint carries its date.
// AA's import family for Qwen's max checkpoint carries its date.
["qwen3 8 max 0902", "qwen3 8 max"],
// Word order differs between the AA family and the config ids.
["claude haiku 4 5", "claude 4 5 haiku"],
Expand Down Expand Up @@ -293,7 +293,7 @@ const byAlpha = (a: string, b: string): number => a.toLowerCase().localeCompare(

/**
* Compare the AA-measured model names against the catalog + pooled
* sets. Display names in the first three lists are the AA/workbook
* sets. Display names in the first three lists are the AA/import
* names; the fourth lists catalog ids verbatim (that is where a human
* goes looking for them in the config).
*/
Expand Down Expand Up @@ -526,7 +526,7 @@ export function aaCaiPoints(rows: AaCaiRow[]): AaPoint[] {
pointsPerSecond: null,
scorePerDollar: b.score !== null && b.cost !== null && b.cost > 0 ? b.score / b.cost : null,
scorePerSecond: b.score !== null && b.time !== null && b.time > 0 ? b.score / b.time : null,
// CAI rows are published results; the workbook's "eligible" flag
// CAI rows are published results; the import's "eligible" flag
// is a rankings-view concept and does not exist for them.
eligible: true,
qualStatus: null,
Expand Down
2 changes: 1 addition & 1 deletion pm-stack/aggregator/src/feed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ export interface FleetFeed {
* state, read by the collector via GraphQL. Absent when the
* collector had no Projects token or the read failed. */
projects?: ProjectPoolItem[];
/** AA cost explorer section: the ainventory (AA workbook) data read
/** AA cost explorer section: the ainventory (AA import) data read
* by the collector from Supabase, plus pool/catalog coverage computed
* against the repo's opencode config. Present-but-absent
* ({status:"absent", reason}) when Supabase was unreachable — the
Expand Down
33 changes: 20 additions & 13 deletions pm-stack/aggregator/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -710,14 +710,14 @@ export interface DnsSection {
}

// ---------------------------------------------------------------------------
// AA cost explorer: the Artificial Analysis workbook data (Supabase
// AA cost explorer: the Artificial Analysis import data (Supabase
// `ainventory`, latest import batch) as the collector embeds it in the
// fleet feed. The figures are the workbook snapshot's — AA Intelligence
// fleet feed. The figures are the import snapshot's — AA Intelligence
// Index v4.3.2, Test_Runs snapshots of Sep–Oct 2026 — not a live AA pull;
// the section's provenance says exactly which batch and files they are.
// ---------------------------------------------------------------------------

/** One workbook source file behind the AA section (freshness evidence). */
/** One import source file behind the AA section (freshness evidence). */
export interface AaSourceInfo {
name: string;
kind: string;
Expand Down Expand Up @@ -776,7 +776,7 @@ export interface AaThreshold {
export interface AaConfig {
modelName: string;
benchmark: string;
/** The workbook's effort label, verbatim (e.g. "Adaptive Reasoning,
/** The import's effort label, verbatim (e.g. "Adaptive Reasoning,
* High Effort, Default Fallback") — never shortened or invented. */
effort: string | null;
intelligence: number | null;
Expand All @@ -785,7 +785,7 @@ export interface AaConfig {
}

/** One Test_Runs row, mapped by the sheet's own header row: per-config
* timing. Null timing = the workbook never measured it — the page says
* timing. Null timing = the import never measured it — the page says
* "not measured", it does not estimate. */
export interface AaTestRun {
testRunKey: string;
Expand All @@ -802,7 +802,7 @@ export interface AaTestRun {

/**
* One Coding Agent Index row of ainventory.benchmark_results (the
* workbook's Coding_Agent_Results import): a model + effort + agent
* import's Coding_Agent_Results rows): a model + effort + agent
* harness observation, kept strictly separate from the AA Intelligence
* Index — no score conversion between the indexes (the ChatGPT
* explorers' cross-benchmark rule). Component scores are the published
Expand Down Expand Up @@ -899,15 +899,15 @@ export interface AaPoint {
ttft: number | null;
pointsPerDollar: number | null;
pointsPerSecond: number | null;
/** score / cost, computed when the workbook's own column is absent. */
/** score / cost, computed when the import's own column is absent. */
scorePerDollar: number | null;
/** score / time, computed when the workbook's own column is absent. */
/** score / time, computed when the import's own column is absent. */
scorePerSecond: number | null;
eligible: boolean;
qualStatus: string | null;
/** Agent harness (CAI points only; null on AA points). */
harness: string | null;
/** Total tokens per task (CAI points only; the workbook's AA rows
/** Total tokens per task (CAI points only; the import's AA rows
* do not carry a per-task token count). */
tokensPerTask: number | null;
/** CAI component scores as published fractions (CAI points only). */
Expand All @@ -928,7 +928,7 @@ export interface AaPoint {
* (route ids whose expanded leaves include it), the plan the provider
* door belongs to (collector-carried registry facts — see
* AA_PLAN_FACTS in src/aa.ts), and its best AA measurement when the
* workbook measured a model of the same normalized name. Assembled by
* import measured a model of the same normalized name. Assembled by
* aaCatalogFromConfig() in src/aa.ts.
*/
export interface AaCatalogEntry {
Expand Down Expand Up @@ -996,7 +996,7 @@ export interface AaSection {
status: "ok";
/** ISO timestamp of the collector run that built the section. */
generatedAt: string;
/** ainventory import batch (v_latest_workbook_batch) the rows came from. */
/** ainventory import batch (v_latest_import_batch) the rows came from. */
batch: string;
sources: AaSourceInfo[];
rankings: AaRanking[];
Expand All @@ -1015,11 +1015,18 @@ export interface AaSection {
/** Current token prices from the ainventory price event log
* (v_current_prices); absent on the same condition as cai. */
prices?: AaPrice[];
/** Set by the collector when this section is the last good payload
* re-served after a failed collection (code#3332); absent on a fresh
* build. generatedAt stays the good build's time. */
stale?: boolean;
/** Why the latest collection failed, when stale. */
staleReason?: string;
}

/** The section's degraded form: the collector could not reach Supabase
* (or the payload failed its check) — the page renders the reason
* instead of stale numbers, and the feed never fails over it. */
* (or the payload failed its check) and no last good payload exists
* to fall back to (code#3332) — the page renders the reason, and the
* feed never fails over it. */
export interface AaAbsentSection {
status: "absent";
reason: string;
Expand Down
Loading