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
60 changes: 59 additions & 1 deletion pm-stack/aggregator/src/aa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import type {
AaThreshold,
} from "./model.ts";
import { isIsoDate } from "./validate.ts";
import { serviceIdFor } from "./quota-gather-map.ts";

// --- scalar coercion ---------------------------------------------------------
// The Supabase Management API serializes numeric columns as JSON
Expand Down Expand Up @@ -758,7 +759,7 @@ interface RawModelEntry {
}

/** Route id -> the leaf model ids it reaches (nested routes expanded). */
function routeLeafSets(cfg: { experimental?: { model_routes?: unknown } }): Map<string, Set<string>> {
export function routeLeafSets(cfg: { experimental?: { model_routes?: unknown } }): Map<string, Set<string>> {
const routes = new Map<string, unknown[]>();
const rawRoutes = cfg.experimental?.model_routes;
if (typeof rawRoutes === "object" && rawRoutes !== null) {
Expand Down Expand Up @@ -792,6 +793,63 @@ function routeLeafSets(cfg: { experimental?: { model_routes?: unknown } }): Map<
return out;
}

/** The major route sections the section-risk notification class
* (#8882) watches: exactly the sections Drew named — no scout.
* `small` reaches small-100k's leaves through its nested
* opencode-route/small-100k target, and the live leaf analysis
* (2026-11-12) shows small-100k's door set identical to small's, so
* small-100k rolls up under small with no extra mapping. Keep in
* sync with SECTION_RISK_SECTIONS in notifications.ts. */
export const SECTION_RISK_SECTIONS = ["workhorse", "speed", "specialist", "summit", "small"] as const;

/** Does quota pool `poolId` serve route door `door` (a leaf's
* provider part)? The join, pinned by #8882's unit tests:
* - exact: the gatherer's service-id spelling of the door is the
* pool id (serviceIdFor: _claude -> anthropic:claude-pro,
* _muse/meta -> meta, _openai -> _openai.main);
* - split pools: a pool id under the door with a dot suffix serves
* the door (_antigravity.gemini / _antigravity.claude-gpt serve
* _antigravity; opencode-go.<workspace> serves opencode-go);
* - plan doors: *-plan pseudo-providers in routes map to the pools
* of their base provider (opencode-go-plans -> opencode-go.*,
* openai-plan -> _openai.main/_openai.alt, mistral-plan -> mistral). */
export function poolServesDoor(poolId: string, door: string): boolean {
if (serviceIdFor(door) === poolId) return true;
if (poolId.startsWith(`${door}.`)) return true;
if (door.endsWith("-plan") || door.endsWith("-plans")) {
const base = door.replace(/-plans?$/, "");
const bare = poolId.replace(/^_/, "");
if (poolId === base || bare === base) return true;
if (poolId.startsWith(`${base}.`) || bare.startsWith(`${base}.`) || bare.startsWith(`${base}:`)) return true;
}
return false;
}

/** Section -> quota pool ids serving it, from the deployed OpenCode
* config text (#8882). Unparseable config yields {} — the caller
* derives no section candidates, never a guessed membership. */
export function sectionPoolIdsFromConfig(text: string, poolIds: readonly string[]): Record<string, string[]> {
let cfg: unknown;
try {
cfg = JSON.parse(stripJsonComments(text));
} catch {
return {};
}
if (typeof cfg !== "object" || cfg === null) return {};
const leafSets = routeLeafSets(cfg as { experimental?: { model_routes?: unknown } });
const out: Record<string, string[]> = {};
for (const section of SECTION_RISK_SECTIONS) {
const leaves = leafSets.get(section);
if (!leaves) {
out[section] = [];
continue;
}
const doors = new Set([...leaves].map((leaf) => leaf.split("/")[0]));
out[section] = [...new Set(poolIds.filter((poolId) => [...doors].some((door) => poolServesDoor(poolId, door))))].sort();
Comment on lines +847 to +848

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve the leaf model when joining split quota pools

For the configured speed section, the only Antigravity leaf is gemini-flash-plan → _antigravity/gemini-3.8-flash (.opencode/opencode.jsonc:2463,3337-3341), but dropping the model here causes poolServesDoor to include both Antigravity pools. The gatherer's antigravityPoolForModel explicitly attributes Gemini models only to _antigravity.gemini. Consequently, a healthy _antigravity.claude-gpt pool suppresses the failure/risk notification even when every pool actually serving speed is walled or pending wall. Preserve the model identity and apply the gatherer's split-pool attribution when deriving membership.

Useful? React with 👍 / 👎.

}
return out;
}

/**
* Build the Model Explorer catalog from the repo config + the AA
* measured rows (for the per-model AA match). Returns null when the
Expand Down
8 changes: 8 additions & 0 deletions pm-stack/aggregator/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,10 @@ export interface Config {
/** The quota gatherer's latest-state file (#1151), written into the
* aggregator's own data dir by scripts/gather-quota.ts. */
quotaCurrentFile: string;
/** The deployed OpenCode config (.opencode/opencode.jsonc of the
* code repo): the section-risk join (#8882) reads its model_routes
* leaf sets from here. */
opencodeConfigFile: string;
coverageSnapshotFile: string;
/** OpenChamber managed-opencode state file (laptop attention source). */
openchamberStateFile: string;
Expand Down Expand Up @@ -214,6 +218,10 @@ export function loadConfig(env: Record<string, string | undefined> = process.env
join(homedir(), "workspace/goals/keep-the-four-repos-healthy/hidden_files/provider-quota-registry.md"),
),
quotaCurrentFile: s(env.PM_AGG_QUOTA_CURRENT_FILE, join(process.cwd(), "quota-current.json")),
opencodeConfigFile: s(
env.PM_AGG_OPENCODE_CONFIG_FILE,
join(homedir(), "git", "code", ".opencode", "opencode.jsonc"),
),
itemHistoryFile: s(
env.PM_AGG_ITEM_HISTORY_FILE,
join(homedir(), ".local", "state", "pm-aggregator", "item-history.jsonl"),
Expand Down
131 changes: 130 additions & 1 deletion pm-stack/aggregator/src/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export const NOTIFICATION_CLASS_DEFAULTS: Record<string, boolean> = {
"needs-drew": true,
"quota-wall": true,
"quota-near-wall": true,
"section-risk": true,
"stack-health": true,
"blocked-age": true,
};
Expand Down Expand Up @@ -73,6 +74,11 @@ export const NOTIFICATION_CLASSES: NotificationClassMeta[] = [
label: "Quota near wall",
blurb: "A sole-door pool crosses 85% of a window.",
},
{
id: "section-risk",
label: "Section failure / severe risk",
blurb: "A whole route section (workhorse, speed, specialist, summit, small) fails or is at severe risk. Shows the pools pending wall, which are walled, and the soonest resets.",
},
{
id: "stack-health",
label: "Stack health",
Expand Down Expand Up @@ -121,6 +127,7 @@ export function notificationTestLanding(
return `${origin}/alerts#incident-test`;
case "quota-wall":
case "quota-near-wall":
case "section-risk":
return `${origin}/quota`;
case "stack-health":
return `${origin}/health`;
Expand All @@ -141,7 +148,7 @@ export const BLOCKED_AGE_BREAKTHROUGH_MS = 48 * 60 * 60_000;
export const QUOTA_WELL_BEFORE_RESET_MS = 24 * 60 * 60_000;

export interface NotificationCandidate {
class: "needs-drew" | "blocked-age" | "quota-wall" | "quota-near-wall" | "stack-health";
class: "needs-drew" | "blocked-age" | "quota-wall" | "quota-near-wall" | "section-risk" | "stack-health";
objectRef: string;
stateFingerprint: string;
title: string;
Expand Down Expand Up @@ -191,6 +198,10 @@ export interface NotificationSnapshot {
health: Pick<HealthView, "services">;
/** Pool ids identified as having no alternative route. */
soleDoorPoolIds?: ReadonlySet<string>;
/** #8882: route section -> quota pool ids serving it, joined from
* the deployed OpenCode config's route leaf sets (server.ts via
* aa.ts sectionPoolIdsFromConfig). Absent = no section derivation. */
sectionPools?: Readonly<Record<string, readonly string[]>>;
/** Drew-authored dashboard actions/comments, with their event times. */
drewActivity?: Array<{ objectRef: string; at: string }>;
/** #8568: open needs-Drew questions (unanswered, < 7 days old). */
Expand Down Expand Up @@ -389,6 +400,24 @@ export function decideNotification(
return "send";
}

/** #8882: the major route sections Drew named for the section-risk
* class — exactly these, no scout. Keep in sync with
* SECTION_RISK_SECTIONS in aa.ts (the config-side join). */
export const SECTION_RISK_SECTIONS = ["workhorse", "speed", "specialist", "summit", "small"] as const;
/** Pending wall = a measured window at or over this percent (the
* existing near-wall threshold), on a pool that is not walled. */
export const SECTION_RISK_PENDING_PERCENT = 85;

const RESET_WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];

/** Compact UTC reset stamp for push bodies: "Fri 14:28Z". */
export function formatResetCompact(ms: number): string {
const d = new Date(ms);
const hh = String(d.getUTCHours()).padStart(2, "0");
const mm = String(d.getUTCMinutes()).padStart(2, "0");
return `${RESET_WEEKDAYS[d.getUTCDay()]} ${hh}:${mm}Z`;
}

/** Derive stable, fixture-testable notifications from the same views the UI serves. */
export function buildNotificationCandidates(snapshot: NotificationSnapshot, now = Date.now()): NotificationCandidate[] {
const attentionItems: Array<TierItem | TieredEntry> = [
Expand Down Expand Up @@ -453,6 +482,106 @@ export function buildNotificationCandidates(snapshot: NotificationSnapshot, now
}
}

// #8882: section-risk — one candidate per major route section, and
// only when the section as a whole has FAILED (every serving pool
// walled) or is at SEVERE RISK (every non-walled serving pool is
// pending wall). Membership comes from the snapshot (the aa.ts leaf
// join over the deployed config); pools in error/stale/lapsed state
// never count as serving, exactly as in the per-pool quota loop.
for (const section of SECTION_RISK_SECTIONS) {
const memberIds = snapshot.sectionPools?.[section];
if (!memberIds || memberIds.length === 0) continue;
const memberSet = new Set(memberIds);
interface ServingPool {
id: string;
walled: boolean;
wallResetAt: number | null;
pendingPct: number | null;
pendingResetAt: number | null;
}
const serving: ServingPool[] = [];
for (const pool of snapshot.quota.pools) {
if (!memberSet.has(pool.id)) continue;
if (pool.state === "error" || pool.state === "stale" || pool.state === "lapsed") continue;
const windows = pool.windows.filter((w) => w.limit !== null);
const percentOf = (w: (typeof windows)[number]) => w.percent ?? (w.used / (w.limit || 1)) * 100;
const walled = pool.state === "walled" || windows.some((w) => percentOf(w) >= 100);
let wallResetAt: number | null = null;
let pendingPct: number | null = null;
let pendingResetAt: number | null = null;
if (walled) {
// Same wall-lift computation as the quota-wall candidate: the
// pool's authoritative wallLiftsAt, else the soonest reset of
// the exhausted windows.
const lifts = pool.wallLiftsAt ? Date.parse(pool.wallLiftsAt) : NaN;
if (Number.isFinite(lifts)) {
wallResetAt = lifts;
} else {
const exhausted = windows.filter((w) => percentOf(w) >= 100);
const resets = (exhausted.length ? exhausted : windows)
.map((w) => Date.parse(w.resetsAt ?? ""))
.filter(Number.isFinite)
.sort((a, b) => a - b);
wallResetAt = resets[0] ?? null;
}
} else {
for (const w of windows) {
const pct = percentOf(w);
if (pct >= SECTION_RISK_PENDING_PERCENT && (pendingPct === null || pct > pendingPct)) {
pendingPct = Math.floor(pct);
const reset = Date.parse(w.resetsAt ?? "");
pendingResetAt = Number.isFinite(reset) ? reset : null;
}
}
}
serving.push({ id: pool.id, walled, wallResetAt, pendingPct, pendingResetAt });
}
if (serving.length === 0) continue;
const walledPools = serving.filter((entry) => entry.walled);
const pendingPools = serving.filter((entry) => !entry.walled && entry.pendingPct !== null);
const failed = walledPools.length === serving.length;
const severeRisk = !failed && pendingPools.length > 0 && pendingPools.length === serving.length - walledPools.length;
if (!failed && !severeRisk) continue;
const resetSort = (a: number | null, b: number | null) => (a ?? Infinity) - (b ?? Infinity);
const walledPart = walledPools
.slice()
.sort((a, b) => resetSort(a.wallResetAt, b.wallResetAt))
.map((entry) => `${entry.id}${entry.wallResetAt !== null ? ` (resets ${formatResetCompact(entry.wallResetAt)})` : ""}`)
.join(", ");
const pendingPart = pendingPools
.slice()
.sort((a, b) => resetSort(a.pendingResetAt, b.pendingResetAt))
.map(
(entry) =>
`${entry.id} ${entry.pendingPct}%${entry.pendingResetAt !== null ? ` (resets ${formatResetCompact(entry.pendingResetAt)})` : ""}`,
)
.join(", ");
const body = [walledPart ? `walled: ${walledPart}` : "", pendingPart ? `pending: ${pendingPart}` : ""]
.filter(Boolean)
.join(" \u00b7 ");
const soonestReset =
[...walledPools.map((entry) => entry.wallResetAt), ...pendingPools.map((entry) => entry.pendingResetAt)]
.filter((value): value is number => value !== null)
.sort((a, b) => a - b)[0] ?? null;
candidates.push(
candidate({
class: "section-risk",
objectRef: `section:${section}`,
title: failed ? `Section failed: ${section}` : `Section at risk: ${section}`,
body,
url: "/quota",
observedAt: new Date(now).toISOString(),
state: {
state: failed ? "failed" : "severe-risk",
walled: walledPools.map((entry) => entry.id).sort(),
pending: pendingPools.map((entry) => [entry.id, entry.pendingPct]).sort(),
soonestReset: soonestReset !== null ? new Date(soonestReset).toISOString() : null,
},
breakthrough: failed,
}),
);
}

for (const service of snapshot.health.services) {
if (service.ok !== false) continue;
// #8568: the sentinel is authoritative for its service set — when
Expand Down
42 changes: 28 additions & 14 deletions pm-stack/aggregator/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
// its result companion) on the same pattern. Everything underneath
// (GitHub, Kaneo, Grist) stays read-only from here — the fleet jobs
// apply actions; the dashboard only records them.
import { stat } from "node:fs/promises";
import { readFile, stat } from "node:fs/promises";
import { createQuotaRefresher, systemdTrigger } from "./quota-refresh.ts";
import { decodePathSegment } from "./path-segment.ts";
import { errorBoundaryResponse, notFoundResponse } from "./error-boundary.ts";
Expand Down Expand Up @@ -54,7 +54,7 @@ import {
import { loadConfig } from "./config.ts";
import { itemServiceLinks } from "./service-links.ts";
import { loadFeed } from "./feed.ts";
import { AA_PLAN_FACTS } from "./aa.ts";
import { AA_PLAN_FACTS, sectionPoolIdsFromConfig } from "./aa.ts";
import {
getNeedsDrew,
listOpenNeedsDrew,
Expand Down Expand Up @@ -3507,18 +3507,31 @@ if (source.ingestSnapshots) {
// The alert throat's engine (#3676): the ~60s delivery/escalation
// tick (live mode only, fail-soft — see src/alerts.ts).
startAlertEngine(cfg, async (): Promise<NotificationSnapshot> => {
const [attention, quota, health, actions, comments, needsDrewRaised, decisionSets, stackHealthDown, stackHealthStates] =
await Promise.all([
attentionContext(),
source.quota().catch(() => emptyQuotaView()),
healthContext(false),
actionsStore.all().catch(() => []),
commentsStore.all().catch(() => []),
listOpenNeedsDrew(cfg.needsDrewFile).catch(() => []),
listOpenDecisionSets(cfg.decisionsFile).catch(() => []),
listStackHealthDown(cfg.stackHealthFile).catch(() => []),
readStackHealthStates(cfg.stackHealthFile).catch(() => ({})),
]);
const [
attention,
quota,
health,
actions,
comments,
needsDrewRaised,
decisionSets,
stackHealthDown,
stackHealthStates,
opencodeConfigText,
] = await Promise.all([
attentionContext(),
source.quota().catch(() => emptyQuotaView()),
healthContext(false),
actionsStore.all().catch(() => []),
commentsStore.all().catch(() => []),
listOpenNeedsDrew(cfg.needsDrewFile).catch(() => []),
listOpenDecisionSets(cfg.decisionsFile).catch(() => []),
listStackHealthDown(cfg.stackHealthFile).catch(() => []),
readStackHealthStates(cfg.stackHealthFile).catch(() => ({})),
// #8882: the section-risk join reads the deployed config's route
// leaf sets; a missing/unreadable config yields no membership.
readFile(cfg.opencodeConfigFile, "utf8").catch(() => ""),
]);
const drewActivity = [
...actions.filter((action) => action.author.kind === "drew").map((action) => ({ objectRef: action.objectRef, at: action.createdAt })),
...comments.filter((comment) => comment.author.kind === "drew").map((comment) => ({ objectRef: comment.objectRef, at: comment.createdAt })),
Expand All @@ -3529,6 +3542,7 @@ startAlertEngine(cfg, async (): Promise<NotificationSnapshot> => {
health,
drewActivity,
soleDoorPoolIds: deriveSoleDoorPoolIds(quota),
sectionPools: sectionPoolIdsFromConfig(opencodeConfigText, quota.pools.map((pool) => pool.id)),
needsDrewRaised,
decisionSets,
stackHealthDown,
Expand Down
2 changes: 2 additions & 0 deletions pm-stack/aggregator/test/alerts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ describe("class + quiet merges (design §1/§2)", () => {
"needs-drew": true,
"quota-wall": true,
"quota-near-wall": true,
"section-risk": true,
"stack-health": true,
"blocked-age": true,
});
Expand Down Expand Up @@ -344,6 +345,7 @@ describe("validation", () => {
"needs-drew": true,
"quota-wall": true,
"quota-near-wall": true,
"section-risk": true,
"stack-health": true,
"blocked-age": true,
});
Expand Down
Loading
Loading