Skip to content
Closed
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
300 changes: 180 additions & 120 deletions pm-stack/aggregator/scripts/collect-fleet-feed.ts

Large diffs are not rendered by default.

619 changes: 619 additions & 0 deletions pm-stack/aggregator/src/aa-batch-sql.ts

Large diffs are not rendered by default.

179 changes: 179 additions & 0 deletions pm-stack/aggregator/src/aa-batches.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
// AA dataset-version index and per-batch cache shape (#3302).
//
// The selectable versions come from ainventory.sources rows with
// kind='drive-workbook' — the complete register. ingest_batches is optional
// metadata: recent workbook rows have no matching row, so a missing join
// must never hide a batch.
//
// Carriers of the same workbook (re-imports with different timestamps) are
// collapsed only when a stable fingerprint of the batch-bound semantic data
// matches. source_ref, inserted_counts, names and timestamps are NOT dedupe
// keys: the packet records repeated refs/count metadata that do not imply
// identical content.
import { createHash } from "node:crypto";
import type { AaBatchSummary, AaSection } from "./model.ts";
import { isBatchUuid } from "./aa-batch-sql.ts";

/** One raw ainventory.sources workbook row (AA_BATCH_INDEX_SQL shape). */
export interface AaBatchIndexRow {
importBatch: string;
name: string | null;
importedAt: string | null;
driveModifiedAt: string | null;
ranAt: string | null;
insertedCounts: Record<string, number> | null;
}

/** The on-disk shape of one cached batch payload. */
export interface AaBatchCacheEntry {
batch: string;
configFingerprint: string;
fingerprint: string;
builtAt: string;
section: AaSection;
}

function str(v: unknown): string | null {
return typeof v === "string" && v !== "" ? v : null;
}

function counts(v: unknown): Record<string, number> | null {
if (typeof v !== "object" || v === null || Array.isArray(v)) return null;
const out: Record<string, number> = {};
for (const [k, n] of Object.entries(v)) {
if (typeof n === "number" && Number.isFinite(n)) out[k] = n;
}
return Object.keys(out).length > 0 ? out : null;
}

/**
* Parse AA_BATCH_INDEX_SQL's `batches` array. Rows without a uuid batch id
* are dropped; everything else is optional metadata. Sorted newest first.
*/
export function parseBatchIndex(raw: unknown): AaBatchIndexRow[] {
if (!Array.isArray(raw)) return [];
const rows: AaBatchIndexRow[] = [];
const seen = new Set<string>();
for (const entry of raw) {
if (typeof entry !== "object" || entry === null) continue;
const r = entry as Record<string, unknown>;
const importBatch = str(r.importBatch);
if (!importBatch || !isBatchUuid(importBatch) || seen.has(importBatch)) continue;
seen.add(importBatch);
rows.push({
importBatch,
name: str(r.name),
importedAt: str(r.importedAt),
driveModifiedAt: str(r.driveModifiedAt),
ranAt: str(r.ranAt),
insertedCounts: counts(r.insertedCounts),
});
}
return rows.sort((a, b) => (b.importedAt ?? "").localeCompare(a.importedAt ?? ""));
}

/** Human label: import date plus a shortened workbook name. */
export function batchLabel(row: Pick<AaBatchIndexRow, "name" | "importedAt" | "driveModifiedAt">): string {
const date = (row.importedAt ?? row.driveModifiedAt ?? "").slice(0, 10);
const name = row.name?.trim() ?? "";
const short = name.length > 46 ? `${name.slice(0, 45)}…` : name;
if (date && short) return `${date} · ${short}`;
return date || short || "unnamed workbook";
}

/** Stable JSON: object keys sorted at every level. */
export function canonicalJson(value: unknown): string {
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
if (typeof value === "object" && value !== null) {
const entries = Object.entries(value as Record<string, unknown>)
.filter(([, v]) => v !== undefined)
.sort(([a], [b]) => a.localeCompare(b));
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
}
return JSON.stringify(value) ?? "null";
}

/**
* Fingerprint of the batch-bound semantic data only. `prices` is the
* non-batch v_current_prices overlay and source timestamps are carrier
* identity, so neither takes part. Two batches with the same fingerprint
* render the same tables/charts and are offered once.
*/
export function aaBatchFingerprint(raw: {
rankings?: unknown;
thresholds?: unknown;
configs?: unknown;
testRunRows?: unknown;
cai?: unknown;
sources?: unknown;
}): string {
const sources = Array.isArray(raw.sources)
? raw.sources.map((s) => {
const r = (s ?? {}) as Record<string, unknown>;
return { name: str(r.name), kind: str(r.kind) };
})
: [];
const semantic = {
rankings: raw.rankings ?? [],
thresholds: raw.thresholds ?? [],
configs: raw.configs ?? [],
testRunRows: raw.testRunRows ?? [],
cai: raw.cai ?? [],
sources,
};
return createHash("sha256").update(canonicalJson(semantic)).digest("hex");
}

/**
* Turn the index + known cache fingerprints into the section's selector
* list. Newest first; a carrier whose fingerprint matches an already-kept
* entry is dropped. Null fingerprints (not built yet) are never collapsed
* because identity is unproven.
*/
export function summarizeBatches(
rows: AaBatchIndexRow[],
cache: Map<string, { fingerprint: string | null; cached: boolean }>,
): AaBatchSummary[] {
const kept: AaBatchSummary[] = [];
const seen = new Set<string>();
for (const row of rows) {
const meta = cache.get(row.importBatch);
const fingerprint = meta?.fingerprint ?? null;
if (fingerprint && seen.has(fingerprint)) continue;
if (fingerprint) seen.add(fingerprint);
kept.push({
importBatch: row.importBatch,
name: row.name,
importedAt: row.importedAt,
driveModifiedAt: row.driveModifiedAt,
ranAt: row.ranAt,
insertedCounts: row.insertedCounts,
label: batchLabel(row),
fingerprint,
cached: meta?.cached ?? false,
latest: kept.length === 0,
});
}
return kept;
}

/** The per-batch cache filename; uuids only, so the name is path-safe. */
export function aaCacheFileName(batch: string): string {
if (!isBatchUuid(batch)) throw new Error("aa cache: invalid batch uuid");
return `aa-batch-${batch}.json`;
}

/** Structural check for a cached payload file. */
export function isAaBatchCacheEntry(v: unknown): v is AaBatchCacheEntry {
if (typeof v !== "object" || v === null) return false;
const e = v as Partial<AaBatchCacheEntry>;
return (
typeof e.batch === "string" &&
isBatchUuid(e.batch) &&
typeof e.configFingerprint === "string" &&
typeof e.fingerprint === "string" &&
typeof e.builtAt === "string" &&
typeof e.section === "object" &&
e.section !== null
);
}
33 changes: 33 additions & 0 deletions pm-stack/aggregator/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1004,13 +1004,46 @@ export interface AaCatalogEntry {
} | null;
}

/**
* One selectable AA workbook version (#3302). The index is built from
* ainventory.sources rows with kind='drive-workbook' — the complete
* register; ingest_batches is optional metadata only. Carriers whose
* batch-bound semantic content has the same fingerprint are collapsed
* into the newest entry.
*/
export interface AaBatchSummary {
/** ainventory import batch id (the ?batch= value). */
importBatch: string;
/** Workbook file name from sources.name. */
name: string | null;
/** When ainventory imported the workbook. */
importedAt: string | null;
/** The workbook file's own Drive modification time. */
driveModifiedAt: string | null;
/** ingest_batches.ran_at when a metadata row exists, else null. */
ranAt: string | null;
/** ingest_batches.inserted_counts when a metadata row exists. */
insertedCounts: Record<string, number> | null;
/** Human label: date + short file name. */
label: string;
/** sha256 of the batch-bound semantic payload; null until built. */
fingerprint: string | null;
/** Whether a usable per-batch payload file exists. */
cached: boolean;
/** True for the newest surviving entry. */
latest: boolean;
}

/** The AA explorer section as the collector embeds it in the fleet feed. */
export interface AaSection {
status: "ok";
/** ISO timestamp of the collector run that built the section. */
generatedAt: string;
/** ainventory import batch (v_latest_import_batch) the rows came from. */
batch: string;
/** Selectable workbook versions, newest first, carrier duplicates
* collapsed by content fingerprint (#3302). Absent in older feeds. */
batches?: AaBatchSummary[];
sources: AaSourceInfo[];
rankings: AaRanking[];
thresholds: AaThreshold[];
Expand Down
32 changes: 28 additions & 4 deletions pm-stack/aggregator/src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5795,7 +5795,7 @@ const AA_EXPLORER_SCRIPT = `<script>
});
function csvCell(v) { return '"' + String(v == null ? "" : v).replace(/"/g, '""') + '"'; }
var dlJsonEl = document.getElementById("xf-dl-json");
if (dlJsonEl) dlJsonEl.addEventListener("click", function () { downloadFile("cost-explorer-data.json", JSON.stringify(DATA, null, 2), "application/json"); });
if (dlJsonEl) dlJsonEl.addEventListener("click", function () { downloadFile("cost-explorer-data-" + String(DATA.batch || "latest").slice(0, 8) + ".json", JSON.stringify(DATA, null, 2), "application/json"); });
var dlCsvEl = document.getElementById("xf-dl-csv");
if (dlCsvEl) dlCsvEl.addEventListener("click", function () {
var lines = [];
Expand Down Expand Up @@ -5955,13 +5955,37 @@ export function renderAa(section: AaFeedSection | null, provenance: Provenance,
</div>`
: `<div class="banner">The collector has not carried the fleet catalog yet — it is built from the same <code>.opencode/opencode.jsonc</code> read as the coverage section and appears once a collector build that knows it has run. No catalog is shown rather than a stale one.</div>`;
const explorerJson = jsonForScript(
JSON.stringify({ points: aaPoints(s), caiPoints: s.cai ? aaCaiPoints(s.cai) : [], catalog: catalog ?? null }),
JSON.stringify({
batch: s.batch,
points: aaPoints(s),
caiPoints: s.cai ? aaCaiPoints(s.cai) : [],
catalog: catalog ?? null,
}),
);
// #3302: dataset-version selector. The selected batch scopes the whole
// explorer (charts, tables, recommendations) because the server hands
// renderAa that batch's section; downloads read the same embedded DATA.
const batches = s.batches ?? [];
const latestBatch = batches.find((b) => b.latest)?.importBatch ?? batches[0]?.importBatch ?? s.batch;
const selectedIsLatest = s.batch === latestBatch;
const batchOptions = batches
.map(
(b) =>
`<option value="${esc(b.importBatch)}"${b.importBatch === s.batch ? " selected" : ""}>${esc(b.label)}${b.importBatch === latestBatch ? " (latest)" : ""}${b.cached ? "" : " — not cached yet"}</option>`,
)
.join("");
const batchSelector =
batches.length > 1
? `<div class="card" id="aa-batch-picker"><label><strong>Dataset version</strong>
<select id="xf-batch" onchange="location.href = this.value ? '/aa?batch=' + encodeURIComponent(this.value) : '/aa'">${batchOptions}</select></label>
<span class="muted">Older versions show that import's rankings, thresholds, timings and coding-agent rows. The latest is the default. Token prices remain the current <code>v_current_prices</code> overlay, not a historical price snapshot.</span></div>`
: "";
const body = `<h1>Cost Explorer</h1>
${s.stale ? `<div class="banner">The latest collection failed (${esc(s.staleReason ?? "unknown error")}) — showing the last good data, collected ${fmtDate(s.generatedAt)}. It refreshes automatically on the next successful collection.</div>` : ""}
<p class="muted">${s.rankings.length} ranked configurations · ${s.configs.length} AA Intelligence Index configurations · ${s.testRuns.length} timing rows${s.cai ? ` · ${s.cai.length} Coding Agent Index observations` : ""}${catalog ? ` · ${catalog.length} catalog models` : ""} · collected ${fmtDate(s.generatedAt)} from ainventory batch <code>${esc(s.batch.slice(0, 8))}…</code>. Machine-first: <a href="/api/aa.json">/api/aa.json</a>.</p>
${batchSelector}
<p class="muted">${s.rankings.length} ranked configurations · ${s.configs.length} AA Intelligence Index configurations · ${s.testRuns.length} timing rows${s.cai ? ` · ${s.cai.length} Coding Agent Index observations` : ""}${catalog ? ` · ${catalog.length} catalog models` : ""} · collected ${fmtDate(s.generatedAt)} from ainventory batch <code>${esc(s.batch.slice(0, 8))}…</code>${selectedIsLatest ? " (latest)" : " (historical version)"}. Machine-first: <a href="/api/aa.json${selectedIsLatest ? "" : `?batch=${encodeURIComponent(s.batch)}`}">/api/aa.json${selectedIsLatest ? "" : `?batch=${encodeURIComponent(s.batch)}`}</a>.</p>
<div class="card"><strong>Provenance</strong><br>
<span class="muted">These are the import snapshot's figures, not a live Artificial Analysis pull.${summary.snapshotVintage ? ` Test_Runs snapshots in this batch: ${esc(summary.snapshotVintage.min)} – ${esc(summary.snapshotVintage.max)}.` : ""} A new import (coding-plan-watch) flips the batch; the feed collector picks it up within minutes. The explorer renders from the feed alone — when the data pipeline lands new models (Terra, Beam), they appear here with no page change.</span>
<span class="muted">These are the import snapshot's figures, not a live Artificial Analysis pull.${summary.snapshotVintage ? ` Test_Runs snapshots in this batch: ${esc(summary.snapshotVintage.min)} – ${esc(summary.snapshotVintage.max)}.` : ""} A new import (coding-plan-watch) flips the batch; the feed collector picks it up within minutes. The explorer renders from the feed alone — when the data pipeline lands new models (Terra, Beam), they appear here with no page change. Token prices come from <code>v_current_prices</code>, a current-price overlay that is not scoped to the selected dataset version.</span>
<ul>${sourcesHtml || '<li class="muted">source files not recorded for this batch</li>'}</ul></div>
<div class="xtabs" role="tablist"><button type="button" class="xtab" data-xtab="aa">AA Explorer</button><button type="button" class="xtab" data-xtab="models">Model Explorer</button></div>
<div class="card xpl-filters" id="xpl-filters">
Expand Down
4 changes: 2 additions & 2 deletions pm-stack/aggregator/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1241,10 +1241,10 @@ async function handler(req: Request): Promise<Response> {
}

if (path === "/aa") {
return html(renderAa(await source.aa(), prov(), provDetail()));
return html(renderAa(await source.aa(url.searchParams.get("batch")), prov(), provDetail()));
}
if (path === "/api/aa.json") {
const section = await source.aa();
const section = await source.aa(url.searchParams.get("batch"));
return json(section ?? { status: "absent", reason: "no AA explorer section in the fleet feed yet" });
}

Expand Down
6 changes: 4 additions & 2 deletions pm-stack/aggregator/src/source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,10 @@ export interface Source {
dns(): Promise<DnsSection | null>;
/** The AA cost explorer section (ainventory import data via the
* fleet feed); null = not collected yet. The absent form
* ({status:"absent"}) is a real section: it renders its reason. */
aa(): Promise<AaFeedSection | null>;
* ({status:"absent"}) is a real section: it renders its reason.
* `batch` selects a cached historical workbook version (#3302);
* omitted keeps the latest/default behaviour. */
aa(batch?: string | null): Promise<AaFeedSection | null>;
/** The identity registry (#906 §3): durable session records, oldest sources merged. */
registry(): Promise<SessionRecord[]>;
/** The GitHub Project pool (#910 stage 5) from the fleet feed; empty when not collected. */
Expand Down
34 changes: 32 additions & 2 deletions pm-stack/aggregator/src/sources/live.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
// projection. Anything a reader cannot reach falls back to fixtures, and the
// provenance strings say exactly which facet is live vs fixture-backed.
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
import { dirname } from "node:path";
import { dirname, join } from "node:path";
import type { Config } from "../config.ts";
import { applyBoardDonePolicy, isRetiredDoneTableTitle } from "../board-policy.ts";
import { isAaSection } from "../aa.ts";
import { aaCacheFileName, isAaBatchCacheEntry } from "../aa-batches.ts";
import { isBatchUuid } from "../aa-batch-sql.ts";
import { isDnsSection } from "../dns.ts";
import {
diagnoseOrchestrationSection,
Expand Down Expand Up @@ -1342,13 +1344,41 @@ export function liveSource(
: "fixtures (no fleet feed file yet)";
return null;
},
async aa(): Promise<AaFeedSection | null> {
async aa(batch?: string | null): Promise<AaFeedSection | null> {
// AA cost explorer: the section rides the fleet feed, read from
// Supabase ainventory by the collector. Its absent form is a real
// section (the page renders the reason); a missing section means
// the collector has not embedded one yet.
const feed = await getFeed();
const collection = feed?.meta?.sections.aa;
// #3302: a selected historical batch is a collector-built cache file
// beside the feed. The feed's latest section carries the index, so the
// historical render keeps the same selector list.
if (batch !== undefined && batch !== null && batch !== "") {
const batchList =
feed?.aa && isAaSection(feed.aa) && feed.aa.status === "ok" ? (feed.aa.batches ?? []) : [];
if (!isBatchUuid(batch)) {
provenance.aa = "live (fleet feed · invalid ?batch value)";
return { status: "absent", reason: "invalid batch id", generatedAt: feed?.generatedAt ?? new Date().toISOString() };
}
try {
const parsed: unknown = JSON.parse(
await readFile(join(dirname(cfg.feedFile), "aa-batches", aaCacheFileName(batch)), "utf8"),
);
if (isAaBatchCacheEntry(parsed) && isAaSection(parsed.section) && parsed.section.status === "ok") {
provenance.aa = `live (fleet feed · historical batch ${batch.slice(0, 8)} · collected ${parsed.section.generatedAt})`;
return { ...parsed.section, batches: batchList };
}
} catch {
// No cache file yet — fall through to the honest absent form.
}
provenance.aa = `live (fleet feed · batch ${batch.slice(0, 8)} not cached yet)`;
return {
status: "absent",
reason: `batch ${batch} is indexed but its payload has not been built yet — the collector builds a few versions per tick`,
generatedAt: feed?.generatedAt ?? new Date().toISOString(),
};
}
if (feed?.aa && isAaSection(feed.aa)) {
const detail =
feed.aa.status === "ok"
Expand Down
Loading