From 1855bef814bc6ad26be33da7d443558ab470bd6c Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:01:33 -0600 Subject: [PATCH 1/6] feat(aggregator): derive notification candidates --- pm-stack/aggregator/src/alerts.ts | 9 +- pm-stack/aggregator/src/derive.ts | 3 +- pm-stack/aggregator/src/model.ts | 2 + pm-stack/aggregator/src/notifications.ts | 293 +++++++++++------- pm-stack/aggregator/src/server.ts | 9 +- pm-stack/aggregator/test/alerts.test.ts | 28 +- pm-stack/aggregator/test/boot.test.ts | 6 +- .../aggregator/test/notifications.test.ts | 269 +++++++--------- .../aggregator/test/watchdog-priming.test.ts | 19 +- 9 files changed, 353 insertions(+), 285 deletions(-) diff --git a/pm-stack/aggregator/src/alerts.ts b/pm-stack/aggregator/src/alerts.ts index aa99ef9f29..b55b861e4c 100644 --- a/pm-stack/aggregator/src/alerts.ts +++ b/pm-stack/aggregator/src/alerts.ts @@ -23,6 +23,7 @@ import type { Config } from "./config.ts"; import { sendPush, type PushOutcome, type PushTarget } from "./push.ts"; import { getSupabaseClient, sqlInt, sqlJson, sqlStr, type SupabaseClient } from "./supabase.ts"; +import { NOTIFICATION_CLASS_DEFAULTS } from "./notifications.ts"; // --- Shapes ---------------------------------------------------------------- @@ -127,7 +128,7 @@ export function toPublicSubscription(sub: PushSubscriptionRow): PublicPushSubscr // --- Pure helpers (unit-tested) --------------------------------------------- /** Design §1: the incident class defaults ON for new subscriptions. */ -export const DEFAULT_CLASSES: Record = { incident: true }; +export const DEFAULT_CLASSES: Record = NOTIFICATION_CLASS_DEFAULTS; /** Design §2: default quiet window 23:00–07:00 America/Chicago. */ export const DEFAULT_QUIET: QuietPrefs = { start: "23:00", end: "07:00", tz: "America/Chicago", enabled: true }; @@ -172,9 +173,11 @@ export function mergeQuiet(input: unknown): QuietPrefs { return out; } -/** A class is on unless the subscription explicitly turned it off. */ +/** Preserve existing subscription choices when new classes are added: + * only the original incident class defaults on for old rows; new rows + * receive the reviewed defaults from mergeClasses at creation. */ export function classEnabled(sub: { classes: Record }, cls: string): boolean { - return sub.classes?.[cls] !== false; + return sub.classes?.[cls] ?? (cls === "incident"); } /** Is `now` inside the quiet window (evaluated in the prefs' timezone)? diff --git a/pm-stack/aggregator/src/derive.ts b/pm-stack/aggregator/src/derive.ts index da25fc337a..78c0a592e4 100644 --- a/pm-stack/aggregator/src/derive.ts +++ b/pm-stack/aggregator/src/derive.ts @@ -333,7 +333,8 @@ export interface SectionMatch { */ export function tierEntry(e: AttentionEntry, match?: SectionMatch | null): TieredEntry { if (match && e.state !== "in-motion") { - if (match.tier === "needs-drew") return { ...e, tier: "needs-drew", drewReason: match.item.reason }; + if (match.tier === "needs-drew") + return { ...e, tier: "needs-drew", tierSince: match.item.since, drewReason: match.item.reason }; const next = match.item.recommendedAction ? ` Next: ${match.item.recommendedAction}` : ""; return { ...e, tier: "needs-orchestrator", orchestratorNote: `${match.item.reason}${next}` }; } diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index a3598d0650..5a731c6f72 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -471,6 +471,8 @@ export type AttentionTier = "needs-drew" | "needs-orchestrator" | "in-motion"; export interface TieredEntry extends AttentionEntry { tier: AttentionTier; + /** When the orchestration job first observed this session in its tier. */ + tierSince?: string; /** Why this needs Drew — present iff tier is "needs-drew". */ drewReason?: string; /** What the fleet will do with it — present iff tier is "needs-orchestrator". */ diff --git a/pm-stack/aggregator/src/notifications.ts b/pm-stack/aggregator/src/notifications.ts index 90eb44815c..4647808ee8 100644 --- a/pm-stack/aggregator/src/notifications.ts +++ b/pm-stack/aggregator/src/notifications.ts @@ -1,130 +1,191 @@ -// Notification measurement (#3319, slice (e) of the #1254 design): -// the weekly sent-vs-acted-on roll-up over the alert throat's send -// ledger (alerts.notification_sends, written by AlertsStore.logSend). -// -// The roll-up is a pure derivation over ledger rows so it can be -// pinned by fixture tests without a database; the /notifications page -// and its /api twin render exactly this shape. -// -// Counting rules (the page states them in plain words too): -// - Only outcome = "sent" rows are sends. suppressed-quiet, -// suppressed-dedupe, gone, and error rows are attempts that never -// reached a device; they never enter the denominator, and a send -// is never inferred from delivered/escalated incident events. -// - A send counts as acted-on when its acted_on_at (stamped by the -// exactly-once Ack transition in AlertsStore.ackIncident) falls -// within 24 hours of the send. Ack is the durable v1 acted-on -// signal; acting through any other surface is not attributable -// to a specific send (see the page's attribution note). -// - Weeks are rolling 7-day buckets ending at `now`, four of them: -// the window is the last 28 days, not calendar weeks. -// - A class whose rolling-window acted-on ratio is under 10% (with -// at least one send) is flagged as a default-off PROPOSAL. The -// flag is display-only: nothing here mutates a preference or a -// default; default changes are Drew's call (design Q1). -import type { NotificationSendRow } from "./alerts.ts"; +import type { AttentionView } from "./derive.ts"; +import type { HealthView } from "./health.ts"; +import type { QuotaView, TierItem, TieredEntry } from "./model.ts"; -export const ACTED_WINDOW_MS = 24 * 60 * 60 * 1000; -export const ROLLING_WEEKS = 4; -export const WEEK_MS = 7 * 24 * 60 * 60 * 1000; -export const PROPOSAL_THRESHOLD = 0.1; +export const NOTIFICATION_CLASS_DEFAULTS: Record = { + incident: true, + "needs-drew": true, + "quota-wall": true, + "quota-near-wall": false, + "stack-health": true, + "blocked-age": true, +}; -/** The send's timestamp: the ledger's insert-time column. Rows the - * store writes carry no explicit timestamp, so the row's defaulted - * created_at is the send time; sent_at wins when a row carries one. */ -export function sendTimestamp(row: NotificationSendRow): string | null { - return row.sent_at ?? row.created_at ?? null; +export const NOTIFICATION_COOLDOWN_MS = 6 * 60 * 60_000; +export const BLOCKED_AGE_REMINDER_MS = 24 * 60 * 60_000; +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"; + objectRef: string; + stateFingerprint: string; + title: string; + body: string; + url: string; + observedAt: string; + breakthrough: boolean; + digestOnly?: boolean; + escalationStep?: 24 | 48; } -export interface NotificationWeekRollup { - /** Inclusive bucket start (ISO); the bucket is [start, start + 7d). */ - start: string; - sent: number; - acted: number; - /** acted / sent, or null when nothing was sent that week. */ - ratio: number | null; +export interface NotificationHistoryEntry { + at: string; + class: NotificationCandidate["class"]; + objectRef: string; + stateFingerprint: string; + outcome: "sent" | "suppressed-quiet" | "suppressed-dedupe" | "suppressed-cooldown" | "error"; } -export interface NotificationClassRollup { - class: string; - /** Oldest week first; always ROLLING_WEEKS entries. */ - weeks: NotificationWeekRollup[]; - sent: number; - acted: number; - /** acted / sent over the whole rolling window; null when sent = 0. */ - ratio: number | null; - /** Display-only default-off proposal (ratio under the threshold). */ - proposal: boolean; +export type NotificationDecision = "send" | "digest" | "suppress-dedupe" | "suppress-cooldown"; + +export interface NotificationSnapshot { + attention: AttentionView; + quota: QuotaView; + health: Pick; + /** Pool ids identified as having no alternative route. */ + soleDoorPoolIds?: ReadonlySet; } -export interface NotificationRollup { - /** The instant the rolling window ends (ISO). */ - asOf: string; - /** Inclusive window start (ISO): asOf - ROLLING_WEEKS weeks. */ - windowStart: string; - classes: NotificationClassRollup[]; - /** Ledger rows skipped because they carry no usable send timestamp. */ - undated: number; +function candidate( + value: Omit & { + state: unknown; + breakthrough?: boolean; + }, +): NotificationCandidate { + const { state, breakthrough = false, ...rest } = value; + return { ...rest, stateFingerprint: JSON.stringify(state), breakthrough }; } -export function rollupNotificationSends( - rows: NotificationSendRow[], - now: Date, - weeks: number = ROLLING_WEEKS, -): NotificationRollup { - const asOfMs = now.getTime(); - const windowStartMs = asOfMs - weeks * WEEK_MS; - const byClass = new Map(); - let undated = 0; - for (const row of rows) { - if (row.outcome !== "sent") continue; - const tsRaw = sendTimestamp(row); - const ts = tsRaw ? Date.parse(tsRaw) : Number.NaN; - if (!Number.isFinite(ts)) { - undated += 1; - continue; - } - if (ts < windowStartMs || ts > asOfMs) continue; - // Bucket 0 is the oldest week in the window. - const bucket = Math.min(weeks - 1, Math.floor((ts - windowStartMs) / WEEK_MS)); - let entry = byClass.get(row.class); - if (!entry) { - entry = { sent: new Array(weeks).fill(0), acted: new Array(weeks).fill(0) }; - byClass.set(row.class, entry); - } - entry.sent[bucket] += 1; - if (row.acted_on_at) { - const actedMs = Date.parse(row.acted_on_at); - if (Number.isFinite(actedMs) && actedMs >= ts && actedMs - ts <= ACTED_WINDOW_MS) { - entry.acted[bucket] += 1; +function tierItemCandidate(item: TierItem | TieredEntry, now: number): NotificationCandidate[] { + const isTierItem = "id" in item; + const sessionId = item.sessionId; + const itemId = isTierItem ? item.id : sessionId; + const itemRef = isTierItem ? item.ref : undefined; + const objectRef = sessionId ? `session:${sessionId}` : `item:${itemId}`; + const url = sessionId + ? `/sessions?id=${encodeURIComponent(sessionId)}` + : itemRef && /^[-\w.]+\/[-\w.]+#\d+$/.test(itemRef) + ? `https://github.com/${itemRef.replace("#", "/issues/")}` + : `/attention#${encodeURIComponent(itemId ?? "unknown")}`; + const observedAt = isTierItem ? item.since : item.tierSince ?? item.createdAt ?? item.lastActivityAt ?? new Date(now).toISOString(); + const entry = candidate({ + class: "needs-drew", + objectRef, + title: item.title ?? itemId ?? "Needs-Drew item", + body: "This item entered the needs-Drew tier.", + url, + observedAt, + state: { tier: "needs-drew", state: "state" in item ? item.state : undefined, kind: isTierItem ? item.kind : undefined }, + }); + const since = Date.parse(observedAt); + if (!Number.isFinite(since) || now - since < BLOCKED_AGE_REMINDER_MS) return [entry]; + const step: 24 | 48 = now - since >= BLOCKED_AGE_BREAKTHROUGH_MS ? 48 : 24; + return [ + entry, + candidate({ + class: "blocked-age", + objectRef, + title: step === 48 ? `Blocked for 48 hours: ${item.title ?? itemId}` : `Needs attention: ${item.title ?? itemId}`, + body: "This needs-Drew item remains unacted.", + url, + observedAt, + state: { step }, + breakthrough: step === 48, + digestOnly: step === 24, + escalationStep: step, + }), + ]; +} + +/** Apply enter-state dedupe, the per-item cooldown, and quiet/digest policy. */ +export function decideNotification( + candidate: NotificationCandidate, + history: NotificationHistoryEntry[], + now: number, + quietHours: boolean, +): NotificationDecision { + const sent = history.filter((entry) => entry.outcome === "sent"); + if ( + sent.some( + (entry) => + entry.class === candidate.class && + entry.objectRef === candidate.objectRef && + entry.stateFingerprint === candidate.stateFingerprint, + ) + ) { + return "suppress-dedupe"; + } + const lastForItem = sent + .filter((entry) => entry.class === candidate.class && entry.objectRef === candidate.objectRef) + .map((entry) => Date.parse(entry.at)) + .filter(Number.isFinite) + .sort((a, b) => b - a)[0]; + const escalation = candidate.escalationStep !== undefined; + if (!escalation && lastForItem !== undefined && now - lastForItem < NOTIFICATION_COOLDOWN_MS) { + return "suppress-cooldown"; + } + if (candidate.digestOnly || (quietHours && !candidate.breakthrough)) return "digest"; + return "send"; +} + +/** Derive stable, fixture-testable notifications from the same views the UI serves. */ +export function buildNotificationCandidates(snapshot: NotificationSnapshot, now = Date.now()): NotificationCandidate[] { + const attentionItems: Array = [ + ...snapshot.attention.drew, + ...snapshot.attention.drewExtra, + ]; + const candidates = attentionItems.flatMap((item) => tierItemCandidate(item, now)); + + for (const pool of snapshot.quota.pools) { + const soleDoor = snapshot.soleDoorPoolIds?.has(pool.id) ?? false; + const windows = pool.windows.filter((w) => w.limit !== null); + const wall = pool.state === "walled" || windows.some((w) => (w.percent ?? (w.used / (w.limit || 1)) * 100) >= 100); + if (wall) { + const resetAt = windows.map((w) => Date.parse(w.resetsAt ?? "")).filter(Number.isFinite).sort((a, b) => a - b)[0]; + const wellBeforeReset = resetAt !== undefined && resetAt - now >= QUOTA_WELL_BEFORE_RESET_MS; + if (soleDoor || wellBeforeReset) { + candidates.push( + candidate({ + class: "quota-wall", + objectRef: `quota:${pool.id}`, + title: `Quota wall: ${pool.provider} ${pool.plan}`, + body: `Pool ${pool.id} is walled${soleDoor ? " and has no alternative route" : " well before reset"}.`, + url: "/quota", + observedAt: new Date(now).toISOString(), + state: { state: "walled", resetAt: Number.isFinite(resetAt) ? new Date(resetAt).toISOString() : null }, + breakthrough: soleDoor, + }), + ); } + } else if (soleDoor && windows.some((w) => (w.percent ?? 0) >= 85 && (w.percent ?? 0) < 100)) { + candidates.push( + candidate({ + class: "quota-near-wall", + objectRef: `quota:${pool.id}`, + title: `Quota near wall: ${pool.provider} ${pool.plan}`, + body: `Sole-door pool ${pool.id} has crossed 85%.`, + url: "/quota", + observedAt: new Date(now).toISOString(), + state: { state: "near", windows: windows.map((w) => [w.name, Math.floor(w.percent ?? 0)]) }, + }), + ); } } - const classes: NotificationClassRollup[] = [...byClass.entries()] - .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) - .map(([cls, entry]) => { - const weekRollups: NotificationWeekRollup[] = entry.sent.map((sent, i) => ({ - start: new Date(windowStartMs + i * WEEK_MS).toISOString(), - sent, - acted: entry.acted[i], - ratio: sent > 0 ? entry.acted[i] / sent : null, - })); - const sent = entry.sent.reduce((a, b) => a + b, 0); - const acted = entry.acted.reduce((a, b) => a + b, 0); - const ratio = sent > 0 ? acted / sent : null; - return { - class: cls, - weeks: weekRollups, - sent, - acted, - ratio, - proposal: ratio !== null && ratio < PROPOSAL_THRESHOLD, - }; - }); - return { - asOf: now.toISOString(), - windowStart: new Date(windowStartMs).toISOString(), - classes, - undated, - }; + + for (const service of snapshot.health.services) { + if (service.ok !== false) continue; + candidates.push( + candidate({ + class: "stack-health", + objectRef: `health:${service.def.id}`, + title: `Stack health: ${service.def.name}`, + body: "The monitored service is failing.", + url: "/health", + observedAt: service.probedAt ?? new Date(now).toISOString(), + state: { state: service.state }, + }), + ); + } + return candidates; } diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 6ce7233109..3c79f3f02b 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -1981,9 +1981,14 @@ async function handler(req: Request): Promise { // tier items are appended in their TierItem shape (tier-annotated // needs-orchestrator) so machine consumers see the same queue the // HTML renders — the array shape itself is unchanged (Codex P2 - // on PR #2431). + // on PR #2431). #3317: include non-session needs-drew items too, + // matching the full queue rendered by the attention page. const { view } = await attentionContext(); - return json([...view.all, ...view.watchdog.map((i) => ({ ...i, tier: "needs-orchestrator" as const }))]); + return json([ + ...view.all, + ...view.drewExtra.map((i) => ({ ...i, tier: "needs-drew" as const })), + ...view.watchdog.map((i) => ({ ...i, tier: "needs-orchestrator" as const })), + ]); } if (path === "/api/coverage.json") { const { view, coverage } = await attentionContext(); diff --git a/pm-stack/aggregator/test/alerts.test.ts b/pm-stack/aggregator/test/alerts.test.ts index 302e4e5515..1befef894f 100644 --- a/pm-stack/aggregator/test/alerts.test.ts +++ b/pm-stack/aggregator/test/alerts.test.ts @@ -91,15 +91,24 @@ describe("sql literals", () => { describe("class + quiet merges (design §1/§2)", () => { test("incident defaults on; explicit off survives", () => { - expect(mergeClasses(undefined)).toEqual({ incident: true }); - expect(mergeClasses({ incident: false })).toEqual({ incident: false }); - expect(mergeClasses({ incident: true, "quota-wall": false })).toEqual({ incident: true, "quota-wall": false }); - expect(mergeClasses({ incident: "yes" })).toEqual({ incident: true }); // non-boolean ignored + expect(mergeClasses(undefined)).toEqual({ + incident: true, + "needs-drew": true, + "quota-wall": true, + "quota-near-wall": false, + "stack-health": true, + "blocked-age": true, + }); + expect(mergeClasses({ incident: false }).incident).toBe(false); + expect(mergeClasses({ incident: true, "quota-wall": false })["quota-wall"]).toBe(false); + expect(mergeClasses({ incident: "yes" }).incident).toBe(true); // non-boolean ignored }); - test("classEnabled: only an explicit false disables", () => { + test("classEnabled preserves old rows while new rows get defaults", () => { expect(classEnabled({ classes: {} }, "incident")).toBe(true); expect(classEnabled({ classes: { incident: false } }, "incident")).toBe(false); expect(classEnabled({ classes: { incident: true } }, "incident")).toBe(true); + expect(classEnabled({ classes: {} }, "needs-drew")).toBe(false); + expect(classEnabled({ classes: mergeClasses(undefined) }, "needs-drew")).toBe(true); }); test("quiet defaults 23:00–07:00 America/Chicago; partial overrides merge", () => { expect(mergeQuiet(undefined)).toEqual({ start: "23:00", end: "07:00", tz: "America/Chicago", enabled: true }); @@ -294,7 +303,14 @@ describe("validation", () => { }); expect(ok.ok).toBe(true); if (ok.ok) { - expect(ok.value.classes).toEqual({ incident: true }); + expect(ok.value.classes).toEqual({ + incident: true, + "needs-drew": true, + "quota-wall": true, + "quota-near-wall": false, + "stack-health": true, + "blocked-age": true, + }); expect(ok.value.quiet.tz).toBe("America/Chicago"); } expect( diff --git a/pm-stack/aggregator/test/boot.test.ts b/pm-stack/aggregator/test/boot.test.ts index f0fbd5339b..96aa6170bf 100644 --- a/pm-stack/aggregator/test/boot.test.ts +++ b/pm-stack/aggregator/test/boot.test.ts @@ -218,8 +218,12 @@ describe("server boots from fixtures", () => { expect(board.board.every((item) => !("notes" in item))).toBe(true); const quota = (await (await fetch(`http://127.0.0.1:${port}/api/quota.json`)).json()) as { pools: unknown[] }; expect(quota.pools.length).toBeGreaterThan(0); - const attention = (await (await fetch(`http://127.0.0.1:${port}/api/attention.json`)).json()) as unknown[]; + const attention = (await (await fetch(`http://127.0.0.1:${port}/api/attention.json`)).json()) as { + id?: string; + tier?: string; + }[]; expect(attention.length).toBeGreaterThan(0); + expect(attention.some((entry) => entry.tier === "needs-drew")).toBe(true); }); test("unknown project page is a styled 404; a known project stays 200 (#1186)", async () => { diff --git a/pm-stack/aggregator/test/notifications.test.ts b/pm-stack/aggregator/test/notifications.test.ts index 366eb1b58d..3aabae7025 100644 --- a/pm-stack/aggregator/test/notifications.test.ts +++ b/pm-stack/aggregator/test/notifications.test.ts @@ -1,179 +1,138 @@ -// Notification measurement (#3319): the sent-vs-acted-on roll-up over -// the notification_sends ledger. The roll-up is pure, so the counting -// rules are pinned here with a hand-checked fixture; the store read -// is pinned against a fake Supabase client. import { describe, expect, test } from "bun:test"; -import { AlertsStore, type NotificationSendRow } from "../src/alerts.ts"; -import { rollupNotificationSends, sendTimestamp } from "../src/notifications.ts"; -import { renderNotifications } from "../src/render.ts"; -import type { Provenance } from "../src/model.ts"; -import type { SupabaseClient } from "../src/supabase.ts"; +import { + buildNotificationCandidates, + decideNotification, + type NotificationCandidate, + type NotificationSnapshot, +} from "../src/notifications.ts"; -const NOW = new Date("2026-11-03T12:00:00Z"); -// Rolling window: [2026-10-06T12:00Z, 2026-11-03T12:00Z], buckets of -// 7 days starting Oct 6, Oct 13, Oct 20, Oct 27. +const NOW = Date.parse("2026-11-03T18:00:00Z"); -const PROV: Provenance = { - board: "x", - roadmap: "x", - items: "x", - comments: "x", - quota: "x", - usage: "x", - attention: "x", - orchestration: "x", - dns: "x", - registry: "x", - aa: "x", -}; - -function send(partial: Partial): NotificationSendRow { +function snapshot(overrides: Partial = {}): NotificationSnapshot { return { - class: "incident", - object_ref: "incident:x", - incident_id: "inc-1", - outcome: "sent", - created_at: "2026-11-01T00:00:00Z", - acted_on_at: null, - ...partial, + attention: { drew: [], drewExtra: [] } as unknown as NotificationSnapshot["attention"], + quota: { pools: [] } as unknown as NotificationSnapshot["quota"], + health: { services: [] }, + ...overrides, }; } -describe("rollupNotificationSends", () => { - test("hand-checked fixture week: per-class, per-week sent/acted/ratio", () => { - const rows: NotificationSendRow[] = []; - // Week of Oct 27 (newest bucket): 10 incident sends, 3 acked in 24h. - for (let i = 0; i < 10; i++) { - rows.push( - send({ - created_at: "2026-10-28T08:00:00Z", - acted_on_at: i < 3 ? "2026-10-28T20:00:00Z" : null, - }), - ); - } - // Week of Oct 6 (oldest bucket): 2 incident sends, 1 acked. - rows.push(send({ created_at: "2026-10-07T08:00:00Z", acted_on_at: "2026-10-07T09:00:00Z" })); - rows.push(send({ created_at: "2026-10-07T10:00:00Z" })); - const rollup = rollupNotificationSends(rows, NOW); - expect(rollup.windowStart).toBe("2026-10-06T12:00:00.000Z"); - expect(rollup.classes).toHaveLength(1); - const incident = rollup.classes[0]; - expect(incident.class).toBe("incident"); - expect(incident.weeks.map((w) => w.sent)).toEqual([2, 0, 0, 10]); - expect(incident.weeks.map((w) => w.acted)).toEqual([1, 0, 0, 3]); - expect(incident.weeks[0].start).toBe("2026-10-06T12:00:00.000Z"); - expect(incident.weeks[3].start).toBe("2026-10-27T12:00:00.000Z"); - expect(incident.sent).toBe(12); - expect(incident.acted).toBe(4); - expect(incident.ratio).toBeCloseTo(4 / 12); - expect(incident.proposal).toBe(false); - }); - - test("only outcome=sent counts; suppressed/gone/error never enter the denominator", () => { - const rows = [ - send({ outcome: "suppressed-quiet", created_at: "2026-11-01T00:00:00Z" }), - send({ outcome: "suppressed-dedupe", created_at: "2026-11-01T00:00:00Z" }), - send({ outcome: "gone", created_at: "2026-11-01T00:00:00Z" }), - send({ outcome: "error", created_at: "2026-11-01T00:00:00Z" }), - send({ outcome: "sent", created_at: "2026-11-01T00:00:00Z", acted_on_at: "2026-11-01T01:00:00Z" }), - ]; - const rollup = rollupNotificationSends(rows, NOW); - expect(rollup.classes).toHaveLength(1); - expect(rollup.classes[0].sent).toBe(1); - expect(rollup.classes[0].acted).toBe(1); - expect(rollup.classes[0].ratio).toBe(1); - }); +describe("dashboard notification candidate derivation", () => { + test("includes non-session needs-drew items and emits the 48-hour breakthrough step", () => { + const item = { + id: "developing-today/code#3317", + kind: "task", + title: "Queue engine task", + source: "github", + reason: "Waiting for a decision", + since: new Date(NOW - 49 * 60 * 60_000).toISOString(), + lastSeenAt: new Date(NOW).toISOString(), + ref: "developing-today/code#3317", + }; + const candidates = buildNotificationCandidates( + snapshot({ attention: { drew: [], drewExtra: [item] } as unknown as NotificationSnapshot["attention"] }), + NOW, + ); - test("the 24-hour acted window is inclusive at exactly 24h and closed after it", () => { - const at = "2026-11-01T00:00:00Z"; - const rows = [ - send({ created_at: at, acted_on_at: "2026-11-02T00:00:00Z" }), // exactly 24h — counts - send({ created_at: at, acted_on_at: "2026-11-02T00:00:01Z" }), // 24h + 1s — does not - send({ created_at: at, acted_on_at: "2026-10-31T23:59:59Z" }), // before the send — does not - send({ created_at: at, acted_on_at: null }), // never acked — does not - ]; - const rollup = rollupNotificationSends(rows, NOW); - expect(rollup.classes[0].sent).toBe(4); - expect(rollup.classes[0].acted).toBe(1); + expect(candidates.map((entry) => entry.class)).toEqual(["needs-drew", "blocked-age"]); + expect(candidates[0].objectRef).toBe("item:developing-today/code#3317"); + expect(candidates[1].escalationStep).toBe(48); + expect(candidates[1].breakthrough).toBe(true); }); - test("the rolling four-week window excludes older sends and future sends", () => { - const rows = [ - send({ created_at: "2026-10-06T11:59:59Z", acted_on_at: "2026-10-06T12:30:00Z" }), // just before the window - send({ created_at: "2026-10-06T12:00:00Z" }), // window start — included, oldest bucket - send({ created_at: "2026-11-03T12:00:01Z" }), // after `now` — excluded - ]; - const rollup = rollupNotificationSends(rows, NOW); - expect(rollup.classes[0].sent).toBe(1); - expect(rollup.classes[0].weeks[0].sent).toBe(1); - }); + test("only an explicitly sole-door pool gets near-wall warnings; wall candidates need time before reset", () => { + const quota = { + pools: [ + { + id: "sole", + provider: "Example", + plan: "Pro", + state: "near", + windows: [{ name: "weekly", unit: "requests", limit: 100, used: 90, percent: 90, resetsAt: "2026-11-10T00:00:00Z" }], + }, + { + id: "multi", + provider: "Other", + plan: "Plus", + state: "walled", + windows: [{ name: "weekly", unit: "tokens", limit: 100, used: 100, percent: 100, resetsAt: "2026-11-05T00:00:00Z" }], + }, + ], + }; + const candidates = buildNotificationCandidates( + snapshot({ quota: quota as unknown as NotificationSnapshot["quota"], soleDoorPoolIds: new Set(["sole"]) }), + NOW, + ); - test("classes group separately; an undated sent row is counted as excluded, not as a send", () => { - const rows = [ - send({ class: "test", object_ref: "test:push", incident_id: null, created_at: "2026-11-02T00:00:00Z" }), - send({ class: "incident", created_at: null, sent_at: null }), - ]; - const rollup = rollupNotificationSends(rows, NOW); - expect(rollup.classes.map((c) => c.class)).toEqual(["test"]); - expect(rollup.undated).toBe(1); + expect(candidates.map((entry) => [entry.class, entry.objectRef])).toEqual([ + ["quota-near-wall", "quota:sole"], + ["quota-wall", "quota:multi"], + ]); }); - test("proposal: under 10% over the window proposes; exactly 10% and zero sends do not", () => { - const rows: NotificationSendRow[] = []; - for (let i = 0; i < 20; i++) { - rows.push(send({ class: "digest", created_at: "2026-11-01T00:00:00Z", acted_on_at: i === 0 ? "2026-11-01T01:00:00Z" : null })); - } - for (let i = 0; i < 10; i++) { - rows.push(send({ class: "edge", created_at: "2026-11-01T00:00:00Z", acted_on_at: i === 0 ? "2026-11-01T01:00:00Z" : null })); - } - const rollup = rollupNotificationSends(rows, NOW); - const digest = rollup.classes.find((c) => c.class === "digest")!; - const edge = rollup.classes.find((c) => c.class === "edge")!; - expect(digest.ratio).toBeCloseTo(0.05); - expect(digest.proposal).toBe(true); - expect(edge.ratio).toBeCloseTo(0.1); - expect(edge.proposal).toBe(false); - }); + test("reports failing stack services, not unknown health", () => { + const health = { + services: [ + { def: { id: "aggregator", name: "Aggregator" }, state: "down", ok: false, detail: "probe failed" }, + { def: { id: "unknown", name: "Unknown" }, state: "unknown", ok: null, detail: "not measured" }, + ], + }; + const candidates = buildNotificationCandidates( + snapshot({ health: health as unknown as NotificationSnapshot["health"] }), + NOW, + ); - test("sent_at wins over created_at when a row carries both", () => { - const row = send({ sent_at: "2026-10-07T00:00:00Z", created_at: "2026-11-02T00:00:00Z" }); - expect(sendTimestamp(row)).toBe("2026-10-07T00:00:00Z"); - const rollup = rollupNotificationSends([row], NOW); - expect(rollup.classes[0].weeks[0].sent).toBe(1); + expect(candidates).toHaveLength(1); + expect(candidates[0]).toMatchObject({ class: "stack-health", objectRef: "health:aggregator" }); }); }); -describe("AlertsStore.listSends", () => { - test("reads the notification_sends ledger", async () => { - const rows = [send({})]; - const db: SupabaseClient = { - ref: "test", - async query(sql: string): Promise { - expect(sql).toContain("alerts.notification_sends"); - return rows as T[]; +describe("notification transition policy", () => { + const base: NotificationCandidate = { + class: "needs-drew", + objectRef: "item:task-1", + stateFingerprint: "enter", + title: "Task 1", + body: "Waiting", + url: "/attention#task-1", + observedAt: new Date(NOW).toISOString(), + breakthrough: false, + }; + + test("fires on entry once, suppresses a steady state, and permits a changed state after cooldown", () => { + const history = [ + { + at: new Date(NOW - 7 * 60 * 60_000).toISOString(), + class: base.class, + objectRef: base.objectRef, + stateFingerprint: base.stateFingerprint, + outcome: "sent" as const, }, - }; - const store = new AlertsStore(db); - expect(await store.listSends()).toEqual(rows); + ]; + expect(decideNotification(base, [], NOW, false)).toBe("send"); + expect(decideNotification(base, history, NOW, false)).toBe("suppress-dedupe"); + expect(decideNotification({ ...base, stateFingerprint: "changed" }, history, NOW, false)).toBe("send"); }); -}); -describe("renderNotifications", () => { - test("renders the roll-up, the attribution note, and a display-only proposal", () => { - const rows: NotificationSendRow[] = []; - for (let i = 0; i < 20; i++) { - rows.push(send({ class: "digest", created_at: "2026-11-01T00:00:00Z", acted_on_at: i === 0 ? "2026-11-01T01:00:00Z" : null })); - } - const html = renderNotifications({ available: true, rollup: rollupNotificationSends(rows, NOW) }, PROV); - expect(html).toContain("digest"); - expect(html).toContain("Proposal: default class"); - expect(html).toContain("never changes a preference or a default"); - expect(html).toContain("acted_on_at"); - expect(html).toContain("/api/notifications.json"); + test("applies cooldown and quiet-hours digest, but allows the breakthrough set", () => { + const recent = [ + { + at: new Date(NOW - 60 * 60_000).toISOString(), + class: base.class, + objectRef: base.objectRef, + stateFingerprint: "older-state", + outcome: "sent" as const, + }, + ]; + expect(decideNotification({ ...base, stateFingerprint: "changed" }, recent, NOW, false)).toBe("suppress-cooldown"); + expect(decideNotification({ ...base, objectRef: "other" }, [], NOW, true)).toBe("digest"); + expect(decideNotification({ ...base, class: "quota-wall", breakthrough: true }, [], NOW, true)).toBe("send"); }); - test("unavailable renders the paused message, not an empty roll-up", () => { - const html = renderNotifications({ available: false, rollup: null }, PROV); - expect(html).toContain("unreachable"); + test("the 24-hour blocked-age reminder is digest-only; 48-hour escalation breaks through", () => { + const age24 = { ...base, class: "blocked-age", stateFingerprint: '{"step":24}', digestOnly: true, escalationStep: 24 as const }; + const age48 = { ...age24, stateFingerprint: '{"step":48}', digestOnly: false, escalationStep: 48 as const, breakthrough: true }; + expect(decideNotification(age24, [], NOW, false)).toBe("digest"); + expect(decideNotification(age48, [], NOW, true)).toBe("send"); }); }); diff --git a/pm-stack/aggregator/test/watchdog-priming.test.ts b/pm-stack/aggregator/test/watchdog-priming.test.ts index c04e5b2963..8e2369d3c4 100644 --- a/pm-stack/aggregator/test/watchdog-priming.test.ts +++ b/pm-stack/aggregator/test/watchdog-priming.test.ts @@ -14,6 +14,8 @@ import { join } from "node:path"; interface AttentionEntry { id?: string; + title?: string; + tier?: string; } let proc: Subprocess | undefined; @@ -32,7 +34,21 @@ beforeAll(async () => { generatedAt: twoHoursAgo, runId: "orch-watchdog-test", provenance: { sources: ["watchdog priming test"], runId: "orch-watchdog-test" }, - tiers: { needsDrew: [], needsOrchestrator: [] }, + tiers: { + needsDrew: [ + { + id: "task:attention-json-extra", + kind: "task", + title: "Non-session needs-Drew fixture", + source: "github", + reason: "Waiting on a decision", + since: twoHoursAgo, + lastSeenAt: twoHoursAgo, + ref: "developing-today/code#3317", + }, + ], + needsOrchestrator: [], + }, dependencies: [], goals: [], actions: [], @@ -90,5 +106,6 @@ describe("watchdog registry derivation needs no registry priming (#1148, Codex P expect(ids.filter((id) => id === "watchdog:registry")).toHaveLength(1); // The 2h-old feed breaches the 15m feed threshold too. expect(ids.filter((id) => id === "watchdog:fleet-feed")).toHaveLength(1); + expect(firstAttention?.some((entry) => entry.id === "task:attention-json-extra" && entry.tier === "needs-drew")).toBe(true); }); }); From e4fe2f0cce721c8e970cd5c6d70bda01eabde412 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 19:56:22 -0600 Subject: [PATCH 2/6] Merge notification engine and metrics tests --- .../aggregator/test/notifications.test.ts | 213 ++++++++++++++++-- 1 file changed, 194 insertions(+), 19 deletions(-) diff --git a/pm-stack/aggregator/test/notifications.test.ts b/pm-stack/aggregator/test/notifications.test.ts index 3aabae7025..ca357c0e13 100644 --- a/pm-stack/aggregator/test/notifications.test.ts +++ b/pm-stack/aggregator/test/notifications.test.ts @@ -2,11 +2,17 @@ import { describe, expect, test } from "bun:test"; import { buildNotificationCandidates, decideNotification, + rollupNotificationSends, + sendTimestamp, type NotificationCandidate, type NotificationSnapshot, } from "../src/notifications.ts"; +import { AlertsStore, type NotificationSendRow } from "../src/alerts.ts"; +import { renderNotifications } from "../src/render.ts"; +import type { Provenance } from "../src/model.ts"; +import type { SupabaseClient } from "../src/supabase.ts"; -const NOW = Date.parse("2026-11-03T18:00:00Z"); +const TASK_NOW = Date.parse("2026-11-03T18:00:00Z"); function snapshot(overrides: Partial = {}): NotificationSnapshot { return { @@ -25,13 +31,13 @@ describe("dashboard notification candidate derivation", () => { title: "Queue engine task", source: "github", reason: "Waiting for a decision", - since: new Date(NOW - 49 * 60 * 60_000).toISOString(), - lastSeenAt: new Date(NOW).toISOString(), + since: new Date(TASK_NOW - 49 * 60 * 60_000).toISOString(), + lastSeenAt: new Date(TASK_NOW).toISOString(), ref: "developing-today/code#3317", }; const candidates = buildNotificationCandidates( snapshot({ attention: { drew: [], drewExtra: [item] } as unknown as NotificationSnapshot["attention"] }), - NOW, + TASK_NOW, ); expect(candidates.map((entry) => entry.class)).toEqual(["needs-drew", "blocked-age"]); @@ -61,7 +67,7 @@ describe("dashboard notification candidate derivation", () => { }; const candidates = buildNotificationCandidates( snapshot({ quota: quota as unknown as NotificationSnapshot["quota"], soleDoorPoolIds: new Set(["sole"]) }), - NOW, + TASK_NOW, ); expect(candidates.map((entry) => [entry.class, entry.objectRef])).toEqual([ @@ -79,7 +85,7 @@ describe("dashboard notification candidate derivation", () => { }; const candidates = buildNotificationCandidates( snapshot({ health: health as unknown as NotificationSnapshot["health"] }), - NOW, + TASK_NOW, ); expect(candidates).toHaveLength(1); @@ -95,44 +101,213 @@ describe("notification transition policy", () => { title: "Task 1", body: "Waiting", url: "/attention#task-1", - observedAt: new Date(NOW).toISOString(), + observedAt: new Date(TASK_NOW).toISOString(), breakthrough: false, }; test("fires on entry once, suppresses a steady state, and permits a changed state after cooldown", () => { const history = [ { - at: new Date(NOW - 7 * 60 * 60_000).toISOString(), + at: new Date(TASK_NOW - 7 * 60 * 60_000).toISOString(), class: base.class, objectRef: base.objectRef, stateFingerprint: base.stateFingerprint, outcome: "sent" as const, }, ]; - expect(decideNotification(base, [], NOW, false)).toBe("send"); - expect(decideNotification(base, history, NOW, false)).toBe("suppress-dedupe"); - expect(decideNotification({ ...base, stateFingerprint: "changed" }, history, NOW, false)).toBe("send"); + expect(decideNotification(base, [], TASK_NOW, false)).toBe("send"); + expect(decideNotification(base, history, TASK_NOW, false)).toBe("suppress-dedupe"); + expect(decideNotification({ ...base, stateFingerprint: "changed" }, history, TASK_NOW, false)).toBe("send"); }); test("applies cooldown and quiet-hours digest, but allows the breakthrough set", () => { const recent = [ { - at: new Date(NOW - 60 * 60_000).toISOString(), + at: new Date(TASK_NOW - 60 * 60_000).toISOString(), class: base.class, objectRef: base.objectRef, stateFingerprint: "older-state", outcome: "sent" as const, }, ]; - expect(decideNotification({ ...base, stateFingerprint: "changed" }, recent, NOW, false)).toBe("suppress-cooldown"); - expect(decideNotification({ ...base, objectRef: "other" }, [], NOW, true)).toBe("digest"); - expect(decideNotification({ ...base, class: "quota-wall", breakthrough: true }, [], NOW, true)).toBe("send"); + expect(decideNotification({ ...base, stateFingerprint: "changed" }, recent, TASK_NOW, false)).toBe("suppress-cooldown"); + expect(decideNotification({ ...base, objectRef: "other" }, [], TASK_NOW, true)).toBe("digest"); + expect(decideNotification({ ...base, class: "quota-wall", breakthrough: true }, [], TASK_NOW, true)).toBe("send"); }); test("the 24-hour blocked-age reminder is digest-only; 48-hour escalation breaks through", () => { - const age24 = { ...base, class: "blocked-age", stateFingerprint: '{"step":24}', digestOnly: true, escalationStep: 24 as const }; - const age48 = { ...age24, stateFingerprint: '{"step":48}', digestOnly: false, escalationStep: 48 as const, breakthrough: true }; - expect(decideNotification(age24, [], NOW, false)).toBe("digest"); - expect(decideNotification(age48, [], NOW, true)).toBe("send"); + const age24: NotificationCandidate = { ...base, class: "blocked-age", stateFingerprint: '{"step":24}', digestOnly: true, escalationStep: 24 as const }; + const age48: NotificationCandidate = { ...age24, stateFingerprint: '{"step":48}', digestOnly: false, escalationStep: 48 as const, breakthrough: true }; + expect(decideNotification(age24, [], TASK_NOW, false)).toBe("digest"); + expect(decideNotification(age48, [], TASK_NOW, true)).toBe("send"); + }); +}); + +const NOW = new Date("2026-11-03T12:00:00Z"); +// Rolling window: [2026-10-06T12:00Z, 2026-11-03T12:00Z], buckets of +// 7 days starting Oct 6, Oct 13, Oct 20, Oct 27. + +const PROV: Provenance = { + board: "x", + roadmap: "x", + items: "x", + comments: "x", + quota: "x", + usage: "x", + attention: "x", + orchestration: "x", + dns: "x", + registry: "x", + aa: "x", +}; + +function send(partial: Partial): NotificationSendRow { + return { + class: "incident", + object_ref: "incident:x", + incident_id: "inc-1", + outcome: "sent", + created_at: "2026-11-01T00:00:00Z", + acted_on_at: null, + ...partial, + }; +} + +describe("rollupNotificationSends", () => { + test("hand-checked fixture week: per-class, per-week sent/acted/ratio", () => { + const rows: NotificationSendRow[] = []; + // Week of Oct 27 (newest bucket): 10 incident sends, 3 acked in 24h. + for (let i = 0; i < 10; i++) { + rows.push( + send({ + created_at: "2026-10-28T08:00:00Z", + acted_on_at: i < 3 ? "2026-10-28T20:00:00Z" : null, + }), + ); + } + // Week of Oct 6 (oldest bucket): 2 incident sends, 1 acked. + rows.push(send({ created_at: "2026-10-07T08:00:00Z", acted_on_at: "2026-10-07T09:00:00Z" })); + rows.push(send({ created_at: "2026-10-07T10:00:00Z" })); + const rollup = rollupNotificationSends(rows, NOW); + expect(rollup.windowStart).toBe("2026-10-06T12:00:00.000Z"); + expect(rollup.classes).toHaveLength(1); + const incident = rollup.classes[0]; + expect(incident.class).toBe("incident"); + expect(incident.weeks.map((w) => w.sent)).toEqual([2, 0, 0, 10]); + expect(incident.weeks.map((w) => w.acted)).toEqual([1, 0, 0, 3]); + expect(incident.weeks[0].start).toBe("2026-10-06T12:00:00.000Z"); + expect(incident.weeks[3].start).toBe("2026-10-27T12:00:00.000Z"); + expect(incident.sent).toBe(12); + expect(incident.acted).toBe(4); + expect(incident.ratio).toBeCloseTo(4 / 12); + expect(incident.proposal).toBe(false); + }); + + test("only outcome=sent counts; suppressed/gone/error never enter the denominator", () => { + const rows = [ + send({ outcome: "suppressed-quiet", created_at: "2026-11-01T00:00:00Z" }), + send({ outcome: "suppressed-dedupe", created_at: "2026-11-01T00:00:00Z" }), + send({ outcome: "gone", created_at: "2026-11-01T00:00:00Z" }), + send({ outcome: "error", created_at: "2026-11-01T00:00:00Z" }), + send({ outcome: "sent", created_at: "2026-11-01T00:00:00Z", acted_on_at: "2026-11-01T01:00:00Z" }), + ]; + const rollup = rollupNotificationSends(rows, NOW); + expect(rollup.classes).toHaveLength(1); + expect(rollup.classes[0].sent).toBe(1); + expect(rollup.classes[0].acted).toBe(1); + expect(rollup.classes[0].ratio).toBe(1); + }); + + test("the 24-hour acted window is inclusive at exactly 24h and closed after it", () => { + const at = "2026-11-01T00:00:00Z"; + const rows = [ + send({ created_at: at, acted_on_at: "2026-11-02T00:00:00Z" }), // exactly 24h — counts + send({ created_at: at, acted_on_at: "2026-11-02T00:00:01Z" }), // 24h + 1s — does not + send({ created_at: at, acted_on_at: "2026-10-31T23:59:59Z" }), // before the send — does not + send({ created_at: at, acted_on_at: null }), // never acked — does not + ]; + const rollup = rollupNotificationSends(rows, NOW); + expect(rollup.classes[0].sent).toBe(4); + expect(rollup.classes[0].acted).toBe(1); + }); + + test("the rolling four-week window excludes older sends and future sends", () => { + const rows = [ + send({ created_at: "2026-10-06T11:59:59Z", acted_on_at: "2026-10-06T12:30:00Z" }), // just before the window + send({ created_at: "2026-10-06T12:00:00Z" }), // window start — included, oldest bucket + send({ created_at: "2026-11-03T12:00:01Z" }), // after `now` — excluded + ]; + const rollup = rollupNotificationSends(rows, NOW); + expect(rollup.classes[0].sent).toBe(1); + expect(rollup.classes[0].weeks[0].sent).toBe(1); + }); + + test("classes group separately; an undated sent row is counted as excluded, not as a send", () => { + const rows = [ + send({ class: "test", object_ref: "test:push", incident_id: null, created_at: "2026-11-02T00:00:00Z" }), + send({ class: "incident", created_at: null, sent_at: null }), + ]; + const rollup = rollupNotificationSends(rows, NOW); + expect(rollup.classes.map((c) => c.class)).toEqual(["test"]); + expect(rollup.undated).toBe(1); + }); + + test("proposal: under 10% over the window proposes; exactly 10% and zero sends do not", () => { + const rows: NotificationSendRow[] = []; + for (let i = 0; i < 20; i++) { + rows.push(send({ class: "digest", created_at: "2026-11-01T00:00:00Z", acted_on_at: i === 0 ? "2026-11-01T01:00:00Z" : null })); + } + for (let i = 0; i < 10; i++) { + rows.push(send({ class: "edge", created_at: "2026-11-01T00:00:00Z", acted_on_at: i === 0 ? "2026-11-01T01:00:00Z" : null })); + } + const rollup = rollupNotificationSends(rows, NOW); + const digest = rollup.classes.find((c) => c.class === "digest")!; + const edge = rollup.classes.find((c) => c.class === "edge")!; + expect(digest.ratio).toBeCloseTo(0.05); + expect(digest.proposal).toBe(true); + expect(edge.ratio).toBeCloseTo(0.1); + expect(edge.proposal).toBe(false); + }); + + test("sent_at wins over created_at when a row carries both", () => { + const row = send({ sent_at: "2026-10-07T00:00:00Z", created_at: "2026-11-02T00:00:00Z" }); + expect(sendTimestamp(row)).toBe("2026-10-07T00:00:00Z"); + const rollup = rollupNotificationSends([row], NOW); + expect(rollup.classes[0].weeks[0].sent).toBe(1); + }); +}); + +describe("AlertsStore.listSends", () => { + test("reads the notification_sends ledger", async () => { + const rows = [send({})]; + const db: SupabaseClient = { + ref: "test", + async query(sql: string): Promise { + expect(sql).toContain("alerts.notification_sends"); + return rows as T[]; + }, + }; + const store = new AlertsStore(db); + expect(await store.listSends()).toEqual(rows); + }); +}); + +describe("renderNotifications", () => { + test("renders the roll-up, the attribution note, and a display-only proposal", () => { + const rows: NotificationSendRow[] = []; + for (let i = 0; i < 20; i++) { + rows.push(send({ class: "digest", created_at: "2026-11-01T00:00:00Z", acted_on_at: i === 0 ? "2026-11-01T01:00:00Z" : null })); + } + const html = renderNotifications({ available: true, rollup: rollupNotificationSends(rows, NOW) }, PROV); + expect(html).toContain("digest"); + expect(html).toContain("Proposal: default class"); + expect(html).toContain("never changes a preference or a default"); + expect(html).toContain("acted_on_at"); + expect(html).toContain("/api/notifications.json"); + }); + + test("unavailable renders the paused message, not an empty roll-up", () => { + const html = renderNotifications({ available: false, rollup: null }, PROV); + expect(html).toContain("unreachable"); }); }); From 56b318081f2fa3a14aef682b009935e8f9c06be0 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:21:34 -0600 Subject: [PATCH 3/6] feat(aggregator): wire dashboard notification tick --- pm-stack/aggregator/src/alerts.ts | 111 +++++++++++++++++- pm-stack/aggregator/src/config.ts | 6 + .../aggregator/src/notification-history.ts | 34 ++++++ pm-stack/aggregator/src/notifications.ts | 3 +- pm-stack/aggregator/src/server.ts | 11 +- pm-stack/aggregator/test/alerts.test.ts | 51 ++++++++ .../aggregator/test/notifications.test.ts | 27 +++++ 7 files changed, 236 insertions(+), 7 deletions(-) create mode 100644 pm-stack/aggregator/src/notification-history.ts diff --git a/pm-stack/aggregator/src/alerts.ts b/pm-stack/aggregator/src/alerts.ts index b55b861e4c..2080be0966 100644 --- a/pm-stack/aggregator/src/alerts.ts +++ b/pm-stack/aggregator/src/alerts.ts @@ -23,7 +23,14 @@ import type { Config } from "./config.ts"; import { sendPush, type PushOutcome, type PushTarget } from "./push.ts"; import { getSupabaseClient, sqlInt, sqlJson, sqlStr, type SupabaseClient } from "./supabase.ts"; -import { NOTIFICATION_CLASS_DEFAULTS } from "./notifications.ts"; +import { + buildNotificationCandidates, + decideNotification, + NOTIFICATION_CLASS_DEFAULTS, + type NotificationHistoryEntry, + type NotificationSnapshot, +} from "./notifications.ts"; +import { JsonlNotificationHistory, type NotificationHistoryStore } from "./notification-history.ts"; // --- Shapes ---------------------------------------------------------------- @@ -724,7 +731,102 @@ async function deliverToAll( * incident stays undelivered (and unescalated) until someone * subscribes — a later subscription still gets the push. */ -export async function runAlertTick(cfg: Config, store: AlertsStore, push: PushSender = sendPush): Promise { +export interface AlertTickOptions { + dashboardSnapshot?: () => Promise; + notificationHistory?: NotificationHistoryStore; + now?: number; +} + +async function runDashboardNotificationTick( + cfg: Config, + store: AlertsStore, + subscriptions: PushSubscriptionRow[], + push: PushSender, + options: AlertTickOptions, +): Promise { + if (!options.dashboardSnapshot || subscriptions.length === 0) return; + const now = options.now ?? Date.now(); + const historyStore = options.notificationHistory ?? new JsonlNotificationHistory(cfg.notificationsFile); + const [snapshot, history] = await Promise.all([options.dashboardSnapshot(), historyStore.read()]); + const candidates = buildNotificationCandidates(snapshot, now); + + for (const candidate of candidates) { + for (const sub of subscriptions) { + if (!classEnabled(sub, candidate.class)) continue; + const subHistory = history.filter((entry) => entry.subscriptionId === sub.id); + const decision = decideNotification(candidate, subHistory, now, inQuietHours(sub.quiet, new Date(now))); + const outcome: NotificationHistoryEntry["outcome"] = + decision === "digest" + ? "suppressed-quiet" + : decision === "suppress-dedupe" + ? "suppressed-dedupe" + : decision === "suppress-cooldown" + ? "suppressed-cooldown" + : "sent"; + if (decision !== "send") { + // One durable suppression marker per item state and reason; do not + // append the same unchanged state on every 60-second engine tick. + if ( + !subHistory.some( + (entry) => + entry.class === candidate.class && + entry.objectRef === candidate.objectRef && + entry.stateFingerprint === candidate.stateFingerprint && + entry.outcome === outcome, + ) + ) { + const entry: NotificationHistoryEntry = { + at: new Date(now).toISOString(), + class: candidate.class, + objectRef: candidate.objectRef, + stateFingerprint: candidate.stateFingerprint, + outcome, + subscriptionId: sub.id, + }; + await historyStore.append(entry); + history.push(entry); + } + continue; + } + + const url = /^https?:\/\//.test(candidate.url) ? candidate.url : `${cfg.publicOrigin}${candidate.url}`; + const payload: PushPayload = { + class: candidate.class, + objectRef: candidate.objectRef, + url, + title: candidate.title, + body: candidate.body, + ...(candidate.escalationStep ? { escalation: true } : {}), + }; + const target: PushTarget = { endpoint: sub.endpoint, p256dh: sub.p256dh, auth: sub.auth }; + const result = await push(target, payload); + const entry: NotificationHistoryEntry = { + at: new Date(now).toISOString(), + class: candidate.class, + objectRef: candidate.objectRef, + stateFingerprint: candidate.stateFingerprint, + outcome: result.ok ? "sent" : result.gone ? "gone" : "error", + subscriptionId: sub.id, + }; + await historyStore.append(entry); + history.push(entry); + await store.logSend({ + class: candidate.class, + objectRef: candidate.objectRef, + outcome: result.ok ? "sent" : result.gone ? "gone" : "error", + }); + if (result.ok) await store.noteSubscriptionAlive(sub.endpoint); + else if (result.gone) await store.noteSubscriptionGone(sub.endpoint); + } + } +} + +export async function runAlertTick( + cfg: Config, + store: AlertsStore, + push: PushSender = sendPush, + options: AlertTickOptions = {}, +): Promise { const subs = await store.listSubscriptions(); const targets = subs.filter((s) => classEnabled(s, "incident")); if (targets.length > 0) { @@ -749,12 +851,13 @@ export async function runAlertTick(cfg: Config, store: AlertsStore, push: PushSe } } } + await runDashboardNotificationTick(cfg, store, subs, push, options); } let engineStarted = false; /** Start the ~60s engine loop (live mode only; fail-soft per tick). */ -export function startAlertEngine(cfg: Config): void { +export function startAlertEngine(cfg: Config, dashboardSnapshot?: () => Promise): void { if (engineStarted || cfg.source !== "live") return; engineStarted = true; let ticking = false; @@ -763,7 +866,7 @@ export function startAlertEngine(cfg: Config): void { ticking = true; try { const store = await getAlertsStore(); - if (store) await runAlertTick(cfg, store); + if (store) await runAlertTick(cfg, store, sendPush, { dashboardSnapshot }); } catch (err) { console.error(`alerts engine: tick failed (${err instanceof Error ? err.message : "error"})`); } finally { diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index 2f84edd0db..35bc82e6d0 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -59,6 +59,8 @@ export interface Config { snapshotsDir: string; /** Scheduled-digest archive (#1278): one JSON file per digest. */ digestsDir: string; + /** Append-only notification state/send/suppression log (#3317). */ + notificationsFile: string; /** The stewardship quota view; the hub's live fallback source when the * fleet feed carries no saas/payg sections yet (hub §2.3). */ quotaViewFile: string; @@ -161,6 +163,10 @@ export function loadConfig(env: Record = process.env registryFile: s(env.PM_AGG_REGISTRY_FILE, join(process.cwd(), "registry.json")), snapshotsDir: s(env.PM_AGG_SNAPSHOTS_DIR, join(process.cwd(), "snapshots")), digestsDir: s(env.PM_AGG_DIGESTS_DIR, join(process.cwd(), "digests")), + notificationsFile: s( + env.PM_AGG_NOTIFICATIONS_FILE, + join(homedir(), ".local", "state", "pm-aggregator", "notifications.jsonl"), + ), quotaViewFile: s( env.PM_AGG_QUOTA_VIEW, join( diff --git a/pm-stack/aggregator/src/notification-history.ts b/pm-stack/aggregator/src/notification-history.ts new file mode 100644 index 0000000000..f0f18af562 --- /dev/null +++ b/pm-stack/aggregator/src/notification-history.ts @@ -0,0 +1,34 @@ +import { appendFile, mkdir, readFile } from "node:fs/promises"; +import { dirname } from "node:path"; +import type { NotificationHistoryEntry } from "./notifications.ts"; + +/** Durable append-only history used by the notification transition policy. */ +export interface NotificationHistoryStore { + read(): Promise; + append(entry: NotificationHistoryEntry): Promise; +} + +export class JsonlNotificationHistory implements NotificationHistoryStore { + private writes: Promise = Promise.resolve(); + + constructor(private readonly file: string) {} + + async read(): Promise { + const raw = await readFile(this.file, "utf8").catch((error: NodeJS.ErrnoException) => { + if (error.code === "ENOENT") return ""; + throw error; + }); + return raw + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as NotificationHistoryEntry); + } + + append(entry: NotificationHistoryEntry): Promise { + this.writes = this.writes.then(async () => { + await mkdir(dirname(this.file), { recursive: true }); + await appendFile(this.file, `${JSON.stringify(entry)}\n`, "utf8"); + }); + return this.writes; + } +} diff --git a/pm-stack/aggregator/src/notifications.ts b/pm-stack/aggregator/src/notifications.ts index 4647808ee8..58c51f7f58 100644 --- a/pm-stack/aggregator/src/notifications.ts +++ b/pm-stack/aggregator/src/notifications.ts @@ -34,7 +34,8 @@ export interface NotificationHistoryEntry { class: NotificationCandidate["class"]; objectRef: string; stateFingerprint: string; - outcome: "sent" | "suppressed-quiet" | "suppressed-dedupe" | "suppressed-cooldown" | "error"; + outcome: "sent" | "suppressed-quiet" | "suppressed-dedupe" | "suppressed-cooldown" | "gone" | "error"; + subscriptionId?: string; } export type NotificationDecision = "send" | "digest" | "suppress-dedupe" | "suppress-cooldown"; diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 3c79f3f02b..f7a2dc6c9a 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -128,7 +128,7 @@ import { recordSwProbe, swProbeSummary, VAPID_PUBLIC_KEY } from "./push.ts"; import { resolveBwsSecret } from "./secrets.ts"; import { SW_SOURCE } from "./sw-source.ts"; import { renderAlerts, renderNotifications, renderDigest, esc } from "./render.ts"; -import { rollupNotificationSends } from "./notifications.ts"; +import { rollupNotificationSends, type NotificationSnapshot } from "./notifications.ts"; import { readJsonBody } from "./request-body.ts"; import { parseRegistryQuery, queryRegistry } from "./registry-view.ts"; import { searchWork } from "./search-view.ts"; @@ -2407,4 +2407,11 @@ 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); +startAlertEngine(cfg, async (): Promise => { + const [attention, quota, health] = await Promise.all([ + attentionContext(), + source.quota().catch(() => emptyQuotaView()), + healthContext(false), + ]); + return { attention: attention.view, quota, health }; +}); diff --git a/pm-stack/aggregator/test/alerts.test.ts b/pm-stack/aggregator/test/alerts.test.ts index 1befef894f..4781f726f8 100644 --- a/pm-stack/aggregator/test/alerts.test.ts +++ b/pm-stack/aggregator/test/alerts.test.ts @@ -23,6 +23,7 @@ import { validateNewIncident, validateNewSubscription, AlertsStore, + type AlertTickOptions, type AlertsStore as AlertsStoreType, type Incident, type PushSubscriptionRow, @@ -32,6 +33,7 @@ import { renderAlerts } from "../src/render.ts"; import type { Provenance } from "../src/model.ts"; import { sqlInt, sqlJson, sqlStr, type SupabaseClient } from "../src/supabase.ts"; import type { Config } from "../src/config.ts"; +import type { NotificationHistoryEntry, NotificationSnapshot } from "../src/notifications.ts"; describe("getAlertsStore retry-after-null memoization", () => { test("retries a null client, shares the next in-flight attempt, and caches success", async () => { @@ -485,6 +487,55 @@ describe("pending alert batch fairness", () => { }); describe("alert tick delivery state", () => { + test("dashboard candidates are delivered once and their state is persisted for dedupe", async () => { + const now = Date.parse("2026-11-03T18:00:00Z"); + const { store } = alertTickStore({ deliveries: [], escalations: [] }); + const sub: PushSubscriptionRow = { + id: "sub-dashboard", + endpoint: "https://push.example/sub-dashboard", + p256dh: "p256dh", + auth: "auth", + classes: { incident: true, "needs-drew": true }, + quiet: { start: "23:00", end: "07:00", tz: "UTC" }, + user_agent: null, + created_at: "2026-11-01T00:00:00Z", + last_seen_at: "2026-11-01T00:00:00Z", + gone_count: 0, + }; + store.listSubscriptions = async () => [sub]; + const historyRows: NotificationHistoryEntry[] = []; + const notificationHistory: NonNullable = { + read: async () => [...historyRows], + append: async (entry) => { + historyRows.push(entry); + }, + }; + let dashboardPushes = 0; + const push: typeof successfulSend = async (_target, payload) => { + if ((payload as { class: string }).class === "needs-drew") dashboardPushes += 1; + return successfulSend(_target, payload); + }; + const item = { + id: "task-1", + kind: "task", + title: "Needs-Drew task", + since: new Date(now - 60_000).toISOString(), + state: "open", + }; + const dashboardSnapshot = async (): Promise => ({ + attention: { drew: [item], drewExtra: [] } as unknown as NotificationSnapshot["attention"], + quota: { pools: [] } as unknown as NotificationSnapshot["quota"], + health: { services: [] }, + }); + + await runAlertTick(tickConfig, store, push, { dashboardSnapshot, notificationHistory, now }); + await runAlertTick(tickConfig, store, push, { dashboardSnapshot, notificationHistory, now: now + 60_000 }); + + expect(dashboardPushes).toBe(1); + expect(historyRows.map((row) => row.outcome)).toEqual(["sent", "suppressed-dedupe"]); + expect(historyRows.every((row) => row.subscriptionId === sub.id)).toBe(true); + }); + test("all-error delivery stays pending and a later successful tick marks it delivered once", async () => { const { store, calls } = alertTickStore(); diff --git a/pm-stack/aggregator/test/notifications.test.ts b/pm-stack/aggregator/test/notifications.test.ts index ca357c0e13..ae51f6514f 100644 --- a/pm-stack/aggregator/test/notifications.test.ts +++ b/pm-stack/aggregator/test/notifications.test.ts @@ -1,4 +1,7 @@ import { describe, expect, test } from "bun:test"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { buildNotificationCandidates, decideNotification, @@ -9,6 +12,7 @@ import { } from "../src/notifications.ts"; import { AlertsStore, type NotificationSendRow } from "../src/alerts.ts"; import { renderNotifications } from "../src/render.ts"; +import { JsonlNotificationHistory } from "../src/notification-history.ts"; import type { Provenance } from "../src/model.ts"; import type { SupabaseClient } from "../src/supabase.ts"; @@ -143,6 +147,29 @@ describe("notification transition policy", () => { }); }); +describe("JsonlNotificationHistory", () => { + test("records a decision durably and reloads it after store recreation", async () => { + const dir = await mkdtemp(join(tmpdir(), "notification-history-")); + const file = join(dir, "notifications.jsonl"); + const entry = { + at: "2026-11-04T12:00:00.000Z", + class: "needs-drew" as const, + objectRef: "item:task-1", + stateFingerprint: "entered-needs-drew", + outcome: "sent" as const, + subscriptionId: "sub-1", + }; + try { + const history = new JsonlNotificationHistory(file); + await history.append(entry); + + expect(await new JsonlNotificationHistory(file).read()).toEqual([entry]); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); + const NOW = new Date("2026-11-03T12:00:00Z"); // Rolling window: [2026-10-06T12:00Z, 2026-11-03T12:00Z], buckets of // 7 days starting Oct 6, Oct 13, Oct 20, Oct 27. From 985396a77dc22bb33a29cee94821a7b2ae151849 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:56:13 -0600 Subject: [PATCH 4/6] feat(aggregator): derive weekly blocked-age reminders --- pm-stack/aggregator/src/notifications.ts | 23 ++++++++++++++++-- .../aggregator/test/notifications.test.ts | 24 +++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/pm-stack/aggregator/src/notifications.ts b/pm-stack/aggregator/src/notifications.ts index 58c51f7f58..623d763547 100644 --- a/pm-stack/aggregator/src/notifications.ts +++ b/pm-stack/aggregator/src/notifications.ts @@ -26,7 +26,7 @@ export interface NotificationCandidate { observedAt: string; breakthrough: boolean; digestOnly?: boolean; - escalationStep?: 24 | 48; + escalationStep?: 24 | 48 | "weekly"; } export interface NotificationHistoryEntry { @@ -82,7 +82,7 @@ function tierItemCandidate(item: TierItem | TieredEntry, now: number): Notificat const since = Date.parse(observedAt); if (!Number.isFinite(since) || now - since < BLOCKED_AGE_REMINDER_MS) return [entry]; const step: 24 | 48 = now - since >= BLOCKED_AGE_BREAKTHROUGH_MS ? 48 : 24; - return [ + const reminders = [ entry, candidate({ class: "blocked-age", @@ -97,6 +97,25 @@ function tierItemCandidate(item: TierItem | TieredEntry, now: number): Notificat escalationStep: step, }), ]; + if (step === 48) { + const week = Math.floor((now - since - BLOCKED_AGE_BREAKTHROUGH_MS) / WEEK_MS); + if (week > 0) { + reminders.push( + candidate({ + class: "blocked-age", + objectRef, + title: `Weekly reminder: ${item.title ?? itemId}`, + body: `This needs-Drew item remains unacted (week ${week} after the 48-hour breakthrough).`, + url, + observedAt, + state: { step: "weekly", week }, + digestOnly: true, + escalationStep: "weekly", + }), + ); + } + } + return reminders; } /** Apply enter-state dedupe, the per-item cooldown, and quiet/digest policy. */ diff --git a/pm-stack/aggregator/test/notifications.test.ts b/pm-stack/aggregator/test/notifications.test.ts index ae51f6514f..1582314645 100644 --- a/pm-stack/aggregator/test/notifications.test.ts +++ b/pm-stack/aggregator/test/notifications.test.ts @@ -50,6 +50,30 @@ describe("dashboard notification candidate derivation", () => { expect(candidates[1].breakthrough).toBe(true); }); + test("emits one digest-only needs-Drew reminder per week after the 48-hour breakthrough", () => { + const since = TASK_NOW - (48 * 60 * 60_000 + 8 * 24 * 60 * 60_000); + const item = { + id: "developing-today/code#3317", + kind: "task", + title: "Queue engine task", + since: new Date(since).toISOString(), + lastSeenAt: new Date(TASK_NOW).toISOString(), + ref: "developing-today/code#3317", + }; + const make = (now: number) => + buildNotificationCandidates( + snapshot({ attention: { drew: [], drewExtra: [item] } as unknown as NotificationSnapshot["attention"] }), + now, + ).filter((entry) => entry.class === "blocked-age" && entry.escalationStep === "weekly"); + + const first = make(TASK_NOW); + const nextWeek = make(TASK_NOW + 7 * 24 * 60 * 60_000); + expect(first).toHaveLength(1); + expect(first[0]).toMatchObject({ digestOnly: true, breakthrough: false, escalationStep: "weekly" }); + expect(decideNotification(first[0], [], TASK_NOW, false)).toBe("digest"); + expect(nextWeek[0].stateFingerprint).not.toBe(first[0].stateFingerprint); + }); + test("only an explicitly sole-door pool gets near-wall warnings; wall candidates need time before reset", () => { const quota = { pools: [ From 0a17290a30786efdf39efeb4df77a947f1c0b5ed Mon Sep 17 00:00:00 2001 From: Archer Date: Sat, 7 Nov 2026 22:10:23 -0600 Subject: [PATCH 5/6] notification engine: alerts/notifications/server + tests (branch disposition 2026-11-07) --- pm-stack/aggregator/src/alerts.ts | 170 +++++++++++++++--- pm-stack/aggregator/src/notifications.ts | 102 ++++++++++- pm-stack/aggregator/src/server.ts | 10 +- pm-stack/aggregator/test/alerts.test.ts | 56 +++++- .../aggregator/test/notifications.test.ts | 41 +++++ 5 files changed, 351 insertions(+), 28 deletions(-) diff --git a/pm-stack/aggregator/src/alerts.ts b/pm-stack/aggregator/src/alerts.ts index 2080be0966..d522c6c336 100644 --- a/pm-stack/aggregator/src/alerts.ts +++ b/pm-stack/aggregator/src/alerts.ts @@ -26,6 +26,7 @@ import { getSupabaseClient, sqlInt, sqlJson, sqlStr, type SupabaseClient } from import { buildNotificationCandidates, decideNotification, + nextNotificationDigestAt, NOTIFICATION_CLASS_DEFAULTS, type NotificationHistoryEntry, type NotificationSnapshot, @@ -241,6 +242,7 @@ export interface PushPayload { title: string; body: string; escalation?: boolean; + items?: Array<{ class: string; objectRef: string; title: string; url: string }>; } export function buildIncidentPayload(incident: Incident, origin: string, escalation: boolean): PushPayload { @@ -750,12 +752,47 @@ async function runDashboardNotificationTick( const [snapshot, history] = await Promise.all([options.dashboardSnapshot(), historyStore.read()]); const candidates = buildNotificationCandidates(snapshot, now); - for (const candidate of candidates) { - for (const sub of subscriptions) { - if (!classEnabled(sub, candidate.class)) continue; - const subHistory = history.filter((entry) => entry.subscriptionId === sub.id); + const keyOf = (entry: Pick) => + `${entry.subscriptionId ?? ""}\u0000${entry.class}\u0000${entry.objectRef}\u0000${entry.stateFingerprint}`; + const pendingFor = (subId: string): Map => { + const pending = new Map(); + for (const entry of history) { + if (entry.subscriptionId !== subId) continue; + const key = keyOf(entry); + if (entry.outcome === "queued") pending.set(key, entry); + else if (entry.outcome === "queue-cancelled" || entry.outcome === "sent" || entry.outcome === "gone") pending.delete(key); + } + return pending; + }; + const append = async (entry: NotificationHistoryEntry) => { + await historyStore.append(entry); + history.push(entry); + }; + + for (const sub of subscriptions) { + const enabledCandidates = candidates.filter((candidate) => classEnabled(sub, candidate.class)); + const currentKeys = new Set(enabledCandidates.map((candidate) => keyOf({ ...candidate, subscriptionId: sub.id }))); + const pending = pendingFor(sub.id); + const subHistory = history.filter((entry) => entry.subscriptionId === sub.id); + + // A disappeared state or a muted class cancels its pending digest entry. + for (const [key, queued] of pending) { + if (currentKeys.has(key)) continue; + await append({ + at: new Date(now).toISOString(), + class: queued.class, + objectRef: queued.objectRef, + stateFingerprint: queued.stateFingerprint, + outcome: "queue-cancelled", + subscriptionId: sub.id, + }); + pending.delete(key); + } + + for (const candidate of enabledCandidates) { + const key = keyOf({ ...candidate, subscriptionId: sub.id }); const decision = decideNotification(candidate, subHistory, now, inQuietHours(sub.quiet, new Date(now))); - const outcome: NotificationHistoryEntry["outcome"] = + const suppressedOutcome: NotificationHistoryEntry["outcome"] = decision === "digest" ? "suppressed-quiet" : decision === "suppress-dedupe" @@ -763,32 +800,67 @@ async function runDashboardNotificationTick( : decision === "suppress-cooldown" ? "suppressed-cooldown" : "sent"; + if (decision === "digest") { + if ( + !subHistory.some( + (entry) => + entry.class === candidate.class && + entry.objectRef === candidate.objectRef && + entry.stateFingerprint === candidate.stateFingerprint && + entry.outcome === suppressedOutcome, + ) + ) { + const suppressed: NotificationHistoryEntry = { + at: new Date(now).toISOString(), + class: candidate.class, + objectRef: candidate.objectRef, + stateFingerprint: candidate.stateFingerprint, + outcome: "suppressed-quiet", + subscriptionId: sub.id, + }; + await append(suppressed); + subHistory.push(suppressed); + } + if (!pending.has(key)) { + const queued: NotificationHistoryEntry = { + at: new Date(now).toISOString(), + class: candidate.class, + objectRef: candidate.objectRef, + stateFingerprint: candidate.stateFingerprint, + outcome: "queued", + subscriptionId: sub.id, + candidate, + dueAt: new Date(nextNotificationDigestAt(now, sub.quiet)).toISOString(), + }; + await append(queued); + pending.set(key, queued); + } + continue; + } if (decision !== "send") { - // One durable suppression marker per item state and reason; do not - // append the same unchanged state on every 60-second engine tick. if ( !subHistory.some( (entry) => entry.class === candidate.class && entry.objectRef === candidate.objectRef && entry.stateFingerprint === candidate.stateFingerprint && - entry.outcome === outcome, + entry.outcome === suppressedOutcome, ) ) { - const entry: NotificationHistoryEntry = { + const suppressed: NotificationHistoryEntry = { at: new Date(now).toISOString(), class: candidate.class, objectRef: candidate.objectRef, stateFingerprint: candidate.stateFingerprint, - outcome, + outcome: suppressedOutcome, subscriptionId: sub.id, }; - await historyStore.append(entry); - history.push(entry); + await append(suppressed); + subHistory.push(suppressed); } continue; } - + if (pending.has(key)) continue; // due entries are sent together below const url = /^https?:\/\//.test(candidate.url) ? candidate.url : `${cfg.publicOrigin}${candidate.url}`; const payload: PushPayload = { class: candidate.class, @@ -800,24 +872,80 @@ async function runDashboardNotificationTick( }; const target: PushTarget = { endpoint: sub.endpoint, p256dh: sub.p256dh, auth: sub.auth }; const result = await push(target, payload); + const outcome = result.ok ? "sent" : result.gone ? "gone" : "error"; const entry: NotificationHistoryEntry = { at: new Date(now).toISOString(), class: candidate.class, objectRef: candidate.objectRef, stateFingerprint: candidate.stateFingerprint, - outcome: result.ok ? "sent" : result.gone ? "gone" : "error", + outcome, subscriptionId: sub.id, }; - await historyStore.append(entry); - history.push(entry); - await store.logSend({ - class: candidate.class, - objectRef: candidate.objectRef, - outcome: result.ok ? "sent" : result.gone ? "gone" : "error", - }); + await append(entry); + subHistory.push(entry); + await store.logSend({ class: candidate.class, objectRef: candidate.objectRef, outcome }); if (result.ok) await store.noteSubscriptionAlive(sub.endpoint); else if (result.gone) await store.noteSubscriptionGone(sub.endpoint); } + + const due = [...pending.entries()].filter(([, entry]) => Date.parse(entry.dueAt ?? "") <= now); + const digestCandidates = due.map(([, entry]) => entry.candidate).filter((candidate): candidate is NonNullable => !!candidate); + if (digestCandidates.length === 0) continue; + const refs = digestCandidates.map((candidate) => candidate.objectRef); + const items = digestCandidates.map((candidate) => ({ + class: candidate.class, + objectRef: candidate.objectRef, + title: candidate.title, + url: /^https?:\/\//.test(candidate.url) ? candidate.url : `${cfg.publicOrigin}${candidate.url}`, + })); + const payload: PushPayload = { + class: "digest", + objectRef: `digest:${new Date(now).toISOString().slice(0, 10)}`, + url: `${cfg.publicOrigin}/attention?refs=${encodeURIComponent(refs.join(","))}`, + title: `${digestCandidates.length} dashboard update${digestCandidates.length === 1 ? "" : "s"}`, + body: digestCandidates.map((candidate) => candidate.title).join(" · "), + items, + }; + const result = await push({ endpoint: sub.endpoint, p256dh: sub.p256dh, auth: sub.auth }, payload); + const isGone = "gone" in result && result.gone; + const outcome = result.ok ? "sent" : isGone ? "gone" : "error"; + for (const [key, queued] of due) { + const candidate = queued.candidate; + if (candidate) { + await append({ + at: new Date(now).toISOString(), + class: candidate.class, + objectRef: candidate.objectRef, + stateFingerprint: candidate.stateFingerprint, + outcome, + subscriptionId: sub.id, + }); + } + if (!result.ok && !isGone && candidate) { + const retry: NotificationHistoryEntry = { + ...queued, + at: new Date(now).toISOString(), + dueAt: new Date(nextNotificationDigestAt(now + 60_000, sub.quiet)).toISOString(), + }; + await append(retry); + pending.set(key, retry); + } else { + if (isGone && candidate) { + await append({ + at: new Date(now).toISOString(), + class: candidate.class, + objectRef: candidate.objectRef, + stateFingerprint: candidate.stateFingerprint, + outcome: "queue-cancelled", + subscriptionId: sub.id, + }); + } + pending.delete(key); + } + } + await store.logSend({ class: "digest", objectRef: payload.objectRef, outcome }); + if (result.ok) await store.noteSubscriptionAlive(sub.endpoint); + else if (isGone) await store.noteSubscriptionGone(sub.endpoint); } } diff --git a/pm-stack/aggregator/src/notifications.ts b/pm-stack/aggregator/src/notifications.ts index 623d763547..35484a1f14 100644 --- a/pm-stack/aggregator/src/notifications.ts +++ b/pm-stack/aggregator/src/notifications.ts @@ -6,7 +6,7 @@ export const NOTIFICATION_CLASS_DEFAULTS: Record = { incident: true, "needs-drew": true, "quota-wall": true, - "quota-near-wall": false, + "quota-near-wall": true, "stack-health": true, "blocked-age": true, }; @@ -27,6 +27,8 @@ export interface NotificationCandidate { breakthrough: boolean; digestOnly?: boolean; escalationStep?: 24 | 48 | "weekly"; + /** Dashboard object-ref aliases used to stop escalation after Drew acts. */ + actedRefs?: string[]; } export interface NotificationHistoryEntry { @@ -34,8 +36,19 @@ export interface NotificationHistoryEntry { class: NotificationCandidate["class"]; objectRef: string; stateFingerprint: string; - outcome: "sent" | "suppressed-quiet" | "suppressed-dedupe" | "suppressed-cooldown" | "gone" | "error"; + outcome: + | "sent" + | "suppressed-quiet" + | "suppressed-dedupe" + | "suppressed-cooldown" + | "gone" + | "error" + | "queued" + | "queue-cancelled"; subscriptionId?: string; + /** Queue events carry enough data to recover and deliver after restart. */ + candidate?: NotificationCandidate; + dueAt?: string; } export type NotificationDecision = "send" | "digest" | "suppress-dedupe" | "suppress-cooldown"; @@ -46,6 +59,74 @@ export interface NotificationSnapshot { health: Pick; /** Pool ids identified as having no alternative route. */ soleDoorPoolIds?: ReadonlySet; + /** Drew-authored dashboard actions/comments, with their event times. */ + drewActivity?: Array<{ objectRef: string; at: string }>; +} + +interface LocalClock { + year: number; + month: number; + day: number; + hour: number; + minute: number; +} + +function localClock(at: number, timeZone: string): LocalClock { + const parts = new Intl.DateTimeFormat("en-US", { + timeZone, + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + hourCycle: "h23", + }).formatToParts(new Date(at)); + const value = (type: Intl.DateTimeFormatPartTypes) => Number(parts.find((part) => part.type === type)?.value); + return { year: value("year"), month: value("month"), day: value("day"), hour: value("hour"), minute: value("minute") }; +} + +function localTimeToInstant(clock: LocalClock, timeZone: string): number { + const wanted = Date.UTC(clock.year, clock.month - 1, clock.day, clock.hour, clock.minute); + let result = wanted; + // Resolve the zone offset from the requested wall time. Digest times are + // daytime boundaries (noon and quiet-window end), so they never land in + // the repeated hour at a DST transition. + for (let attempt = 0; attempt < 3; attempt += 1) { + const seen = localClock(result, timeZone); + const represented = Date.UTC(seen.year, seen.month - 1, seen.day, seen.hour, seen.minute); + const correction = wanted - represented; + result += correction; + if (correction === 0) break; + } + return result; +} + +/** Next per-subscription batch point: quiet-window end or local noon. */ +export function nextNotificationDigestAt( + now: number, + quiet: { start: string; end: string; tz: string; enabled?: boolean }, +): number { + const clock = localClock(now, quiet.tz); + const minute = clock.hour * 60 + clock.minute; + const toMinute = (value: string) => { + const [hour, min] = value.split(":").map(Number); + return hour * 60 + min; + }; + const start = toMinute(quiet.start); + const end = toMinute(quiet.end); + const inQuiet = quiet.enabled !== false && (start <= end ? minute >= start && minute < end : minute >= start || minute < end); + const useEndToday = minute < end; + const dayOffset = inQuiet ? (minute >= start && start > end ? 1 : 0) : minute < 12 * 60 ? 0 : useEndToday ? 0 : 1; + const day = new Date(Date.UTC(clock.year, clock.month - 1, clock.day + dayOffset)); + const endDigest = inQuiet || minute >= 12 * 60; + const targetClock: LocalClock = { + year: day.getUTCFullYear(), + month: day.getUTCMonth() + 1, + day: day.getUTCDate(), + hour: endDigest ? Number(quiet.end.slice(0, 2)) : 12, + minute: endDigest ? Number(quiet.end.slice(3, 5)) : 0, + }; + return localTimeToInstant(targetClock, quiet.tz); } function candidate( @@ -70,6 +151,11 @@ function tierItemCandidate(item: TierItem | TieredEntry, now: number): Notificat ? `https://github.com/${itemRef.replace("#", "/issues/")}` : `/attention#${encodeURIComponent(itemId ?? "unknown")}`; const observedAt = isTierItem ? item.since : item.tierSince ?? item.createdAt ?? item.lastActivityAt ?? new Date(now).toISOString(); + const actedRefs = [ + objectRef, + ...(itemId ? [`orch:${itemId}`] : []), + ...(itemRef ? [`gh:${itemRef}`] : []), + ]; const entry = candidate({ class: "needs-drew", objectRef, @@ -77,6 +163,7 @@ function tierItemCandidate(item: TierItem | TieredEntry, now: number): Notificat body: "This item entered the needs-Drew tier.", url, observedAt, + actedRefs, state: { tier: "needs-drew", state: "state" in item ? item.state : undefined, kind: isTierItem ? item.kind : undefined }, }); const since = Date.parse(observedAt); @@ -91,6 +178,7 @@ function tierItemCandidate(item: TierItem | TieredEntry, now: number): Notificat body: "This needs-Drew item remains unacted.", url, observedAt, + actedRefs, state: { step }, breakthrough: step === 48, digestOnly: step === 24, @@ -108,6 +196,7 @@ function tierItemCandidate(item: TierItem | TieredEntry, now: number): Notificat body: `This needs-Drew item remains unacted (week ${week} after the 48-hour breakthrough).`, url, observedAt, + actedRefs, state: { step: "weekly", week }, digestOnly: true, escalationStep: "weekly", @@ -155,7 +244,14 @@ export function buildNotificationCandidates(snapshot: NotificationSnapshot, now ...snapshot.attention.drew, ...snapshot.attention.drewExtra, ]; - const candidates = attentionItems.flatMap((item) => tierItemCandidate(item, now)); + const attentionCandidates = attentionItems.flatMap((item) => tierItemCandidate(item, now)); + const drewActivity = snapshot.drewActivity ?? []; + const candidates = attentionCandidates.filter((entry) => { + const observedAt = Date.parse(entry.observedAt); + return !(entry.actedRefs ?? []).some((ref) => + drewActivity.some((activity) => activity.objectRef === ref && Date.parse(activity.at) >= observedAt), + ); + }); for (const pool of snapshot.quota.pools) { const soleDoor = snapshot.soleDoorPoolIds?.has(pool.id) ?? false; diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index f7a2dc6c9a..686fce4881 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -2408,10 +2408,16 @@ 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 => { - const [attention, quota, health] = await Promise.all([ + const [attention, quota, health, actions, comments] = await Promise.all([ attentionContext(), source.quota().catch(() => emptyQuotaView()), healthContext(false), + actionsStore.all().catch(() => []), + commentsStore.all().catch(() => []), ]); - return { attention: attention.view, quota, health }; + 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 })), + ]; + return { attention: attention.view, quota, health, drewActivity }; }); diff --git a/pm-stack/aggregator/test/alerts.test.ts b/pm-stack/aggregator/test/alerts.test.ts index 4781f726f8..0d7fdccc61 100644 --- a/pm-stack/aggregator/test/alerts.test.ts +++ b/pm-stack/aggregator/test/alerts.test.ts @@ -97,7 +97,7 @@ describe("class + quiet merges (design §1/§2)", () => { incident: true, "needs-drew": true, "quota-wall": true, - "quota-near-wall": false, + "quota-near-wall": true, "stack-health": true, "blocked-age": true, }); @@ -309,7 +309,7 @@ describe("validation", () => { incident: true, "needs-drew": true, "quota-wall": true, - "quota-near-wall": false, + "quota-near-wall": true, "stack-health": true, "blocked-age": true, }); @@ -536,6 +536,58 @@ describe("alert tick delivery state", () => { expect(historyRows.every((row) => row.subscriptionId === sub.id)).toBe(true); }); + test("quiet-hour candidates persist across ticks and drain as one digest at window end", async () => { + const now = Date.parse("2026-11-04T01:00:00Z"); + const { store } = alertTickStore({ deliveries: [], escalations: [] }); + const sub: PushSubscriptionRow = { + id: "sub-digest", + endpoint: "https://push.example/sub-digest", + p256dh: "p256dh", + auth: "auth", + classes: { incident: true, "needs-drew": true }, + quiet: { start: "23:00", end: "07:00", tz: "UTC" }, + user_agent: null, + created_at: "2026-11-01T00:00:00Z", + last_seen_at: "2026-11-01T00:00:00Z", + gone_count: 0, + }; + store.listSubscriptions = async () => [sub]; + const historyRows: NotificationHistoryEntry[] = []; + const notificationHistory: NonNullable = { + read: async () => [...historyRows], + append: async (entry) => { + historyRows.push(entry); + }, + }; + const pushed: unknown[] = []; + const push: typeof successfulSend = async (_target, payload) => { + pushed.push(payload); + return successfulSend(_target, payload); + }; + const item = { + id: "quiet-task", + kind: "task", + title: "Quiet-hour task", + since: new Date(now - 60_000).toISOString(), + state: "open", + }; + const dashboardSnapshot = async (): Promise => ({ + attention: { drew: [item], drewExtra: [] } as unknown as NotificationSnapshot["attention"], + quota: { pools: [] } as unknown as NotificationSnapshot["quota"], + health: { services: [] }, + }); + + await runAlertTick(tickConfig, store, push, { dashboardSnapshot, notificationHistory, now }); + expect(pushed).toHaveLength(0); + expect(historyRows.map((row) => row.outcome)).toEqual(["suppressed-quiet", "queued"]); + + // Recreate the tick over the same durable history at quiet-window end. + await runAlertTick(tickConfig, store, push, { dashboardSnapshot, notificationHistory, now: Date.parse("2026-11-04T07:00:00Z") }); + expect(pushed).toHaveLength(1); + expect(pushed[0]).toMatchObject({ class: "digest", items: [{ title: "Quiet-hour task" }] }); + expect(historyRows.map((row) => row.outcome)).toEqual(["suppressed-quiet", "queued", "sent"]); + }); + test("all-error delivery stays pending and a later successful tick marks it delivered once", async () => { const { store, calls } = alertTickStore(); diff --git a/pm-stack/aggregator/test/notifications.test.ts b/pm-stack/aggregator/test/notifications.test.ts index 1582314645..542346b52d 100644 --- a/pm-stack/aggregator/test/notifications.test.ts +++ b/pm-stack/aggregator/test/notifications.test.ts @@ -5,6 +5,8 @@ import { join } from "node:path"; import { buildNotificationCandidates, decideNotification, + nextNotificationDigestAt, + NOTIFICATION_CLASS_DEFAULTS, rollupNotificationSends, sendTimestamp, type NotificationCandidate, @@ -50,6 +52,34 @@ describe("dashboard notification candidate derivation", () => { expect(candidates[1].breakthrough).toBe(true); }); + test("a later Drew action/comment on the matched dashboard object stops the needs-Drew ladder", () => { + const since = new Date(TASK_NOW - 3 * 24 * 60 * 60_000).toISOString(); + const item = { + id: "developing-today/code#3317", + kind: "task", + title: "Queue engine task", + since, + ref: "developing-today/code#3317", + }; + const acted = buildNotificationCandidates( + snapshot({ + attention: { drew: [], drewExtra: [item] } as unknown as NotificationSnapshot["attention"], + drewActivity: [{ objectRef: "gh:developing-today/code#3317", at: new Date(TASK_NOW - 60_000).toISOString() }], + }), + TASK_NOW, + ); + const preEntry = buildNotificationCandidates( + snapshot({ + attention: { drew: [], drewExtra: [item] } as unknown as NotificationSnapshot["attention"], + drewActivity: [{ objectRef: "gh:developing-today/code#3317", at: new Date(TASK_NOW - 4 * 24 * 60 * 60_000).toISOString() }], + }), + TASK_NOW, + ); + + expect(acted).toHaveLength(0); + expect(preEntry.some((entry) => entry.class === "blocked-age")).toBe(true); + }); + test("emits one digest-only needs-Drew reminder per week after the 48-hour breakthrough", () => { const since = TASK_NOW - (48 * 60 * 60_000 + 8 * 24 * 60 * 60_000); const item = { @@ -169,6 +199,17 @@ describe("notification transition policy", () => { expect(decideNotification(age24, [], TASK_NOW, false)).toBe("digest"); expect(decideNotification(age48, [], TASK_NOW, true)).toBe("send"); }); + + test("digest scheduling uses each subscription timezone and the next noon/window-end boundary", () => { + const quiet = { start: "23:00", end: "07:00", tz: "America/Chicago" }; + expect(new Date(nextNotificationDigestAt(Date.parse("2026-11-04T12:00:00Z"), quiet)).toISOString()).toBe("2026-11-04T13:00:00.000Z"); + expect(new Date(nextNotificationDigestAt(Date.parse("2026-11-04T14:00:00Z"), quiet)).toISOString()).toBe("2026-11-04T18:00:00.000Z"); + expect(new Date(nextNotificationDigestAt(Date.parse("2026-11-04T20:00:00Z"), quiet)).toISOString()).toBe("2026-11-05T13:00:00.000Z"); + }); + + test("sole-door near-wall class is enabled for new subscriptions by the recommended defaults", () => { + expect(NOTIFICATION_CLASS_DEFAULTS["quota-near-wall"]).toBe(true); + }); }); describe("JsonlNotificationHistory", () => { From b4b41446c1798a48582f42f89261a0cf434f551d Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 16:48:55 -0600 Subject: [PATCH 6/6] fix(aggregator): disposition the 8 Codex findings on the notification engine - stack-health dedupe is episode-scoped: a recovered marker (written by the tick when a candidate state disappears) ends the episode, so a recurrence of the same failure notifies again (P1) - production snapshot now supplies soleDoorPoolIds via deriveSoleDoorPoolIds (single-pool providers), wired in server.ts - quota-wall reset is taken from the exhausted windows (or the pool wallLiftsAt), never from a healthy window - stale/errored quota pools no longer derive wall candidates from retained windows - locally classified needs-Drew sessions carry tierSince (last activity), so blocked age is not measured from session creation - due digests re-check the current quiet window before draining and defer to the next allowed boundary - subscription upserts preserve stored class choices: only explicitly sent class keys (providedClasses) override on conflict - /attention honours ?refs= from digest links (full render, shell and fragments), and the service worker carries digest items and deep-links single-item digests --- pm-stack/aggregator/src/alerts.ts | 56 +++++- pm-stack/aggregator/src/derive.ts | 42 ++++- pm-stack/aggregator/src/notifications.ts | 174 +++++++++++++++++- pm-stack/aggregator/src/render.ts | 14 +- pm-stack/aggregator/src/server.ts | 27 ++- pm-stack/aggregator/src/sw-source.ts | 7 +- pm-stack/aggregator/test/alerts.test.ts | 23 +++ .../test/attention-classification.test.ts | 17 ++ .../aggregator/test/notifications.test.ts | 94 ++++++++++ 9 files changed, 429 insertions(+), 25 deletions(-) diff --git a/pm-stack/aggregator/src/alerts.ts b/pm-stack/aggregator/src/alerts.ts index d522c6c336..35d56aa55a 100644 --- a/pm-stack/aggregator/src/alerts.ts +++ b/pm-stack/aggregator/src/alerts.ts @@ -306,6 +306,12 @@ export interface NewSubscription { p256dh: string; auth: string; classes: Record; + /** The class keys the caller explicitly sent (#7193 Codex): on an + * upsert of an existing endpoint only these keys change; the stored + * choices for every other class survive (the dashboard Alerts form + * submits only classes.incident, and mergeClasses would otherwise + * silently re-enable every other class from the defaults). */ + providedClasses?: Record; quiet: QuietPrefs; userAgent?: string; } @@ -322,6 +328,12 @@ export function validateNewSubscription( if (!endpoint || !/^https:\/\//.test(endpoint)) return { ok: false, error: "endpoint must be an https URL" }; if (!p256dh) return { ok: false, error: "keys.p256dh required" }; if (!auth) return { ok: false, error: "keys.auth required" }; + const providedClasses: Record = {}; + if (b.classes && typeof b.classes === "object") { + for (const [k, v] of Object.entries(b.classes as Record)) { + if (typeof v === "boolean") providedClasses[k] = v; + } + } return { ok: true, value: { @@ -329,6 +341,7 @@ export function validateNewSubscription( p256dh, auth, classes: mergeClasses(b.classes), + providedClasses, quiet: mergeQuiet(b.quiet), userAgent: typeof b.userAgent === "string" ? b.userAgent : undefined, }, @@ -399,7 +412,8 @@ export class AlertsStore { sub.userAgent ? sqlStr(sub.userAgent) : "null" }) on conflict (endpoint) do update set - p256dh = excluded.p256dh, auth = excluded.auth, classes = excluded.classes, + p256dh = excluded.p256dh, auth = excluded.auth, + classes = push_subscriptions.classes || ${sqlJson(sub.providedClasses ?? {})}, quiet = excluded.quiet, user_agent = excluded.user_agent, last_seen_at = now(), gone_count = 0 returning *`, @@ -789,6 +803,30 @@ async function runDashboardNotificationTick( pending.delete(key); } + // Recovery markers: a previously recorded candidate state that is no + // longer among this subscription's current candidates has ended its + // episode. decideNotification dedupes only against sends recorded + // after the latest recovery, so a recurrence notifies again. + const latestByKey = new Map(); + for (const entry of subHistory) { + const key = keyOf(entry); + const prev = latestByKey.get(key); + if (!prev || Date.parse(entry.at) >= Date.parse(prev.at)) latestByKey.set(key, entry); + } + for (const [key, latest] of latestByKey) { + if (currentKeys.has(key) || latest.outcome === "recovered") continue; + const marker: NotificationHistoryEntry = { + at: new Date(now).toISOString(), + class: latest.class, + objectRef: latest.objectRef, + stateFingerprint: latest.stateFingerprint, + outcome: "recovered", + subscriptionId: sub.id, + }; + await append(marker); + subHistory.push(marker); + } + for (const candidate of enabledCandidates) { const key = keyOf({ ...candidate, subscriptionId: sub.id }); const decision = decideNotification(candidate, subHistory, now, inQuietHours(sub.quiet, new Date(now))); @@ -891,6 +929,22 @@ async function runDashboardNotificationTick( const due = [...pending.entries()].filter(([, entry]) => Date.parse(entry.dueAt ?? "") <= now); const digestCandidates = due.map(([, entry]) => entry.candidate).filter((candidate): candidate is NonNullable => !!candidate); if (digestCandidates.length === 0) continue; + // #7193 Codex: revalidate the CURRENT quiet window before draining — + // the persisted dueAt was computed under an earlier window (or the + // server was offline past it into a new quiet period). Defer to the + // next allowed boundary instead of sending inside quiet hours. + if (inQuietHours(sub.quiet, new Date(now))) { + for (const [key, queued] of due) { + const retry: NotificationHistoryEntry = { + ...queued, + at: new Date(now).toISOString(), + dueAt: new Date(nextNotificationDigestAt(now + 60_000, sub.quiet)).toISOString(), + }; + await append(retry); + pending.set(key, retry); + } + continue; + } const refs = digestCandidates.map((candidate) => candidate.objectRef); const items = digestCandidates.map((candidate) => ({ class: candidate.class, diff --git a/pm-stack/aggregator/src/derive.ts b/pm-stack/aggregator/src/derive.ts index 78c0a592e4..44637ce262 100644 --- a/pm-stack/aggregator/src/derive.ts +++ b/pm-stack/aggregator/src/derive.ts @@ -339,7 +339,12 @@ export function tierEntry(e: AttentionEntry, match?: SectionMatch | null): Tiere return { ...e, tier: "needs-orchestrator", orchestratorNote: `${match.item.reason}${next}` }; } if (e.state !== "in-motion" && e.supervisionNote && ESCALATION_NOTE.test(e.supervisionNote)) { - return { ...e, tier: "needs-drew", drewReason: `Keeper escalated this session — ${e.supervisionNote}` }; + return { + ...e, + tier: "needs-drew", + tierSince: e.lastActivityAt ?? undefined, + drewReason: `Keeper escalated this session — ${e.supervisionNote}`, + }; } if (e.state !== "in-motion" && e.awaitingQuestion) { const q = e.awaitingQuestion; @@ -348,6 +353,7 @@ export function tierEntry(e: AttentionEntry, match?: SectionMatch | null): Tiere return { ...e, tier: "needs-drew", + tierSince: e.lastActivityAt ?? undefined, drewReason: `A session is asking permission for something destructive — ${q}`, }; } @@ -356,13 +362,19 @@ export function tierEntry(e: AttentionEntry, match?: SectionMatch | null): Tiere // Jules questions are the keeper's to answer (it replies with the // standard proceed/feedback messages) — they never need Drew // unless the orchestration job escalates them explicitly. - return { ...e, tier: "needs-drew", drewReason: `Waiting on your decision — ${q}` }; + return { + ...e, + tier: "needs-drew", + tierSince: e.lastActivityAt ?? undefined, + drewReason: `Waiting on your decision — ${q}`, + }; } } if (e.state !== "in-motion" && e.lastTurnError && CREDENTIAL_ERR.test(e.lastTurnError)) { return { ...e, tier: "needs-drew", + tierSince: e.lastActivityAt ?? undefined, drewReason: `Blocked on a sign-in only you can complete — ${e.lastTurnError}`, }; } @@ -404,6 +416,32 @@ export interface AttentionView { tierSource: TierSourceInfo; } +/** Digest landing filter (#7193 Codex): the alert digest links to + * /attention?refs=; keep only the entries those refs name. + * Ref forms mirror NotificationCandidate.objectRef: session:, + * item:, a bare session/item id, a GitHub ref (owner/repo#n), or + * gh:. Quota/health refs name no attention entries (their own + * pages carry them), so they simply match nothing here. */ +export function filterAttentionViewByRefs(view: AttentionView, refs: string[]): AttentionView { + const wanted = new Set(refs.map((ref) => ref.trim()).filter(Boolean)); + if (wanted.size === 0) return view; + const matchEntry = (e: TieredEntry) => wanted.has(`session:${e.sessionId}`) || wanted.has(e.sessionId); + const matchItem = (item: TierItem) => + wanted.has(`item:${item.id}`) || + wanted.has(item.id) || + (item.sessionId ? wanted.has(`session:${item.sessionId}`) || wanted.has(item.sessionId) : false) || + (item.ref ? wanted.has(item.ref) || wanted.has(`gh:${item.ref}`) : false); + return { + ...view, + drew: view.drew.filter(matchEntry), + orchestrator: view.orchestrator.filter(matchEntry), + drewExtra: view.drewExtra.filter(matchItem), + orchestratorExtra: view.orchestratorExtra.filter(matchItem), + watchdog: view.watchdog.filter(matchItem), + all: view.all.filter(matchEntry), + }; +} + /** Classify, expire, and tier a raw session feed in one pass. */ export function buildAttention( feed: SessionFeedEntry[], diff --git a/pm-stack/aggregator/src/notifications.ts b/pm-stack/aggregator/src/notifications.ts index 35484a1f14..52057a647e 100644 --- a/pm-stack/aggregator/src/notifications.ts +++ b/pm-stack/aggregator/src/notifications.ts @@ -1,6 +1,32 @@ +// Notification measurement (#3319, slice (e) of the #1254 design): +// the weekly sent-vs-acted-on roll-up over the alert throat's send +// ledger (alerts.notification_sends, written by AlertsStore.logSend). +// +// The roll-up is a pure derivation over ledger rows so it can be +// pinned by fixture tests without a database; the /notifications page +// and its /api twin render exactly this shape. +// +// Counting rules (the page states them in plain words too): +// - Only outcome = "sent" rows are sends. suppressed-quiet, +// suppressed-dedupe, gone, and error rows are attempts that never +// reached a device; they never enter the denominator, and a send +// is never inferred from delivered/escalated incident events. +// - A send counts as acted-on when its acted_on_at (stamped by the +// exactly-once Ack transition in AlertsStore.ackIncident) falls +// within 24 hours of the send. Ack is the durable v1 acted-on +// signal; acting through any other surface is not attributable +// to a specific send (see the page's attribution note). +// - Weeks are rolling 7-day buckets ending at `now`, four of them: +// the window is the last 28 days, not calendar weeks. +// - A class whose rolling-window acted-on ratio is under 10% (with +// at least one send) is flagged as a default-off PROPOSAL. The +// flag is display-only: nothing here mutates a preference or a +// default; default changes are Drew's call (design Q1). + import type { AttentionView } from "./derive.ts"; import type { HealthView } from "./health.ts"; import type { QuotaView, TierItem, TieredEntry } from "./model.ts"; +import type { NotificationSendRow } from "./alerts.ts"; export const NOTIFICATION_CLASS_DEFAULTS: Record = { incident: true, @@ -44,7 +70,8 @@ export interface NotificationHistoryEntry { | "gone" | "error" | "queued" - | "queue-cancelled"; + | "queue-cancelled" + | "recovered"; subscriptionId?: string; /** Queue events carry enough data to recover and deliver after restart. */ candidate?: NotificationCandidate; @@ -150,7 +177,7 @@ function tierItemCandidate(item: TierItem | TieredEntry, now: number): Notificat : itemRef && /^[-\w.]+\/[-\w.]+#\d+$/.test(itemRef) ? `https://github.com/${itemRef.replace("#", "/issues/")}` : `/attention#${encodeURIComponent(itemId ?? "unknown")}`; - const observedAt = isTierItem ? item.since : item.tierSince ?? item.createdAt ?? item.lastActivityAt ?? new Date(now).toISOString(); + const observedAt = isTierItem ? item.since : item.tierSince ?? item.lastActivityAt ?? item.createdAt ?? new Date(now).toISOString(); const actedRefs = [ objectRef, ...(itemId ? [`orch:${itemId}`] : []), @@ -215,12 +242,22 @@ export function decideNotification( quietHours: boolean, ): NotificationDecision { const sent = history.filter((entry) => entry.outcome === "sent"); + // Episode-scoped dedupe (#7193 Codex P1): a "recovered" marker ends the + // episode a send belonged to, so only sends after the latest recovery + // for this class+object suppress a recurrence of the same state. + const recoveredAt = + history + .filter((entry) => entry.outcome === "recovered" && entry.class === candidate.class && entry.objectRef === candidate.objectRef) + .map((entry) => Date.parse(entry.at)) + .filter(Number.isFinite) + .sort((a, b) => b - a)[0] ?? -Infinity; if ( sent.some( (entry) => entry.class === candidate.class && entry.objectRef === candidate.objectRef && - entry.stateFingerprint === candidate.stateFingerprint, + entry.stateFingerprint === candidate.stateFingerprint && + Date.parse(entry.at) > recoveredAt, ) ) { return "suppress-dedupe"; @@ -254,11 +291,23 @@ export function buildNotificationCandidates(snapshot: NotificationSnapshot, now }); for (const pool of snapshot.quota.pools) { + // #7193 Codex: a pool whose quota read errored or went stale keeps its + // last windows, but the measurement is marked unavailable — never + // derive wall notifications from retained windows in that state. + if (pool.state === "error" || pool.state === "stale") continue; const soleDoor = snapshot.soleDoorPoolIds?.has(pool.id) ?? false; const windows = pool.windows.filter((w) => w.limit !== null); - const wall = pool.state === "walled" || windows.some((w) => (w.percent ?? (w.used / (w.limit || 1)) * 100) >= 100); + const percentOf = (w: (typeof windows)[number]) => w.percent ?? (w.used / (w.limit || 1)) * 100; + const wall = pool.state === "walled" || windows.some((w) => percentOf(w) >= 100); if (wall) { - const resetAt = windows.map((w) => Date.parse(w.resetsAt ?? "")).filter(Number.isFinite).sort((a, b) => a - b)[0]; + // #7193 Codex: the wall lifts when the EXHAUSTED windows reset (or at + // the pool's authoritative wallLiftsAt) — an unrelated healthy + // window's earlier reset must not suppress a genuine wall. + const exhausted = windows.filter((w) => percentOf(w) >= 100); + const wallLifts = pool.wallLiftsAt ? Date.parse(pool.wallLiftsAt) : NaN; + const resetAt = Number.isFinite(wallLifts) + ? wallLifts + : (exhausted.length ? exhausted : windows).map((w) => Date.parse(w.resetsAt ?? "")).filter(Number.isFinite).sort((a, b) => a - b)[0]; const wellBeforeReset = resetAt !== undefined && resetAt - now >= QUOTA_WELL_BEFORE_RESET_MS; if (soleDoor || wellBeforeReset) { candidates.push( @@ -305,3 +354,118 @@ export function buildNotificationCandidates(snapshot: NotificationSnapshot, now } return candidates; } + +/** Production sole-door classification (#7193 Codex): a pool is the only + * route to its provider when no other pool in the view shares that + * provider. server.ts supplies this on the live snapshot; tests may + * still inject soleDoorPoolIds directly. */ +export function deriveSoleDoorPoolIds(quota: QuotaView): Set { + const perProvider = new Map(); + for (const pool of quota.pools) perProvider.set(pool.provider, (perProvider.get(pool.provider) ?? 0) + 1); + return new Set(quota.pools.filter((pool) => perProvider.get(pool.provider) === 1).map((pool) => pool.id)); +} + +export const ACTED_WINDOW_MS = 24 * 60 * 60 * 1000; +export const ROLLING_WEEKS = 4; +export const WEEK_MS = 7 * 24 * 60 * 60 * 1000; +export const PROPOSAL_THRESHOLD = 0.1; + +/** The send's timestamp: the ledger's insert-time column. Rows the + * store writes carry no explicit timestamp, so the row's defaulted + * created_at is the send time; sent_at wins when a row carries one. */ +export function sendTimestamp(row: NotificationSendRow): string | null { + return row.sent_at ?? row.created_at ?? null; +} + +export interface NotificationWeekRollup { + /** Inclusive bucket start (ISO); the bucket is [start, start + 7d). */ + start: string; + sent: number; + acted: number; + /** acted / sent, or null when nothing was sent that week. */ + ratio: number | null; +} + +export interface NotificationClassRollup { + class: string; + /** Oldest week first; always ROLLING_WEEKS entries. */ + weeks: NotificationWeekRollup[]; + sent: number; + acted: number; + /** acted / sent over the whole rolling window; null when sent = 0. */ + ratio: number | null; + /** Display-only default-off proposal (ratio under the threshold). */ + proposal: boolean; +} + +export interface NotificationRollup { + /** The instant the rolling window ends (ISO). */ + asOf: string; + /** Inclusive window start (ISO): asOf - ROLLING_WEEKS weeks. */ + windowStart: string; + classes: NotificationClassRollup[]; + /** Ledger rows skipped because they carry no usable send timestamp. */ + undated: number; +} + +export function rollupNotificationSends( + rows: NotificationSendRow[], + now: Date, + weeks: number = ROLLING_WEEKS, +): NotificationRollup { + const asOfMs = now.getTime(); + const windowStartMs = asOfMs - weeks * WEEK_MS; + const byClass = new Map(); + let undated = 0; + for (const row of rows) { + if (row.outcome !== "sent") continue; + const tsRaw = sendTimestamp(row); + const ts = tsRaw ? Date.parse(tsRaw) : Number.NaN; + if (!Number.isFinite(ts)) { + undated += 1; + continue; + } + if (ts < windowStartMs || ts > asOfMs) continue; + // Bucket 0 is the oldest week in the window. + const bucket = Math.min(weeks - 1, Math.floor((ts - windowStartMs) / WEEK_MS)); + let entry = byClass.get(row.class); + if (!entry) { + entry = { sent: new Array(weeks).fill(0), acted: new Array(weeks).fill(0) }; + byClass.set(row.class, entry); + } + entry.sent[bucket] += 1; + if (row.acted_on_at) { + const actedMs = Date.parse(row.acted_on_at); + if (Number.isFinite(actedMs) && actedMs >= ts && actedMs - ts <= ACTED_WINDOW_MS) { + entry.acted[bucket] += 1; + } + } + } + const classes: NotificationClassRollup[] = [...byClass.entries()] + .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)) + .map(([cls, entry]) => { + const weekRollups: NotificationWeekRollup[] = entry.sent.map((sent, i) => ({ + start: new Date(windowStartMs + i * WEEK_MS).toISOString(), + sent, + acted: entry.acted[i], + ratio: sent > 0 ? entry.acted[i] / sent : null, + })); + const sent = entry.sent.reduce((a, b) => a + b, 0); + const acted = entry.acted.reduce((a, b) => a + b, 0); + const ratio = sent > 0 ? acted / sent : null; + return { + class: cls, + weeks: weekRollups, + sent, + acted, + ratio, + proposal: ratio !== null && ratio < PROPOSAL_THRESHOLD, + }; + }); + return { + asOf: now.toISOString(), + windowStart: new Date(windowStartMs).toISOString(), + classes, + undated, + }; +} diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index d5929bfc19..9182c197d8 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -3307,8 +3307,9 @@ ${view.expiredCount ? `

${view.expiredCount} finished or stale $ /** Wrap one attention section as a Datastar fragment container: the * shell's placeholder and the fragment payload share this shape, so * a refresh re-patches the container with itself (attrs included). */ -export function attentionFragment(section: "header" | "queues" | "sessions", innerHtml: string): string { - return `

${innerHtml}
`; +export function attentionFragment(section: "header" | "queues" | "sessions", innerHtml: string, query = ""): string { + const q = query ? `?${query}` : ""; + return `
${innerHtml}
`; } /** @@ -3316,12 +3317,13 @@ export function attentionFragment(section: "header" | "queues" | "sessions", inn * immediately; the three heavy sections stream in as fragments. * Without JS, a meta refresh lands on the full server render. */ -export function renderAttentionShell(provenance: Provenance, detail?: ProvenanceDetail): string { +export function renderAttentionShell(provenance: Provenance, detail?: ProvenanceDetail, refs?: string): string { + const refsQuery = refs ? `refs=${encodeURIComponent(refs)}` : ""; const skel = (label: string) => `
Loading ${label}…
`; const body = `

Needs you

Loading the Needs User and Needs Orchestrator queues…

-${attentionFragment("header", skel("queue status"))} -${attentionFragment("queues", skel("the queues"))} -${attentionFragment("sessions", skel("sessions"))}`; +${attentionFragment("header", skel("queue status"), refsQuery)} +${attentionFragment("queues", skel("the queues"), refsQuery)} +${attentionFragment("sessions", skel("sessions"), refsQuery)}`; return layout( "Needs you", body, diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 686fce4881..eec67cf6d3 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -57,7 +57,7 @@ import { import { manifestRouteFor } from "./pages.ts"; import { conflictInbox, type ConflictInbox } from "./conflicts.ts"; import { watchdogTierItems, WATCHDOG_PROBE_SERVICE_IDS } from "./watchdog.ts"; -import { allRefs, buildAttention, deriveToday, projectPace, type RoadmapGrain } from "./derive.ts"; +import { allRefs, buildAttention, deriveToday, filterAttentionViewByRefs, projectPace, type RoadmapGrain } from "./derive.ts"; import { reconcileRoadmap, roadmapDriftReport, @@ -128,7 +128,7 @@ import { recordSwProbe, swProbeSummary, VAPID_PUBLIC_KEY } from "./push.ts"; import { resolveBwsSecret } from "./secrets.ts"; import { SW_SOURCE } from "./sw-source.ts"; import { renderAlerts, renderNotifications, renderDigest, esc } from "./render.ts"; -import { rollupNotificationSends, type NotificationSnapshot } from "./notifications.ts"; +import { deriveSoleDoorPoolIds, rollupNotificationSends, type NotificationSnapshot } from "./notifications.ts"; import { readJsonBody } from "./request-body.ts"; import { parseRegistryQuery, queryRegistry } from "./registry-view.ts"; import { searchWork } from "./search-view.ts"; @@ -1603,18 +1603,27 @@ async function handler(req: Request): Promise { if (path === "/attention") { // #1444: shell first; header/queues/sessions stream in as // fragments. ?full=1 keeps the full server render (no-JS path). + // ?refs= is the digest landing filter (#7193 Codex): + // only the named entries render, and the refs ride the fragment + // URLs so the streamed sections stay filtered. + const refsParam = url.searchParams.get("refs"); + const refs = refsParam ? refsParam.split(",").map((ref) => ref.trim()).filter(Boolean) : []; if (url.searchParams.get("full") !== "1") { - return html(renderAttentionShell(prov(), provDetail())); + return html(renderAttentionShell(prov(), provDetail(), refsParam ?? undefined)); } - const { view, coverage, counts, act, briefs, census } = await attentionRender(); - return html(renderAttention(view, coverage, prov(), counts, provDetail(), act, briefs, census)); + const rendered = await attentionRender(); + const view = refs.length ? filterAttentionViewByRefs(rendered.view, refs) : rendered.view; + return html(renderAttention(view, rendered.coverage, prov(), rendered.counts, provDetail(), rendered.act, rendered.briefs, rendered.census)); } const attnFragMatch = /^\/frag\/attention\/(header|queues|sessions)$/.exec(path); if (attnFragMatch) { const section = attnFragMatch[1] as "header" | "queues" | "sessions"; - const { view, coverage, counts, act, briefs, census } = await attentionRender(); - const sections = attentionSections(view, coverage, counts, act, briefs, census); - return sseResponse(ssePatch(`#attn-${section}`, attentionFragment(section, sections[section]))); + const refsParam = url.searchParams.get("refs"); + const refs = refsParam ? refsParam.split(",").map((ref) => ref.trim()).filter(Boolean) : []; + const rendered = await attentionRender(); + const view = refs.length ? filterAttentionViewByRefs(rendered.view, refs) : rendered.view; + const sections = attentionSections(view, rendered.coverage, rendered.counts, rendered.act, rendered.briefs, rendered.census); + return sseResponse(ssePatch(`#attn-${section}`, attentionFragment(section, sections[section], refsParam ?? undefined))); } if (path === "/assets/app.css") { // The committed Tailwind + DaisyUI build (Phase C): source is @@ -2419,5 +2428,5 @@ startAlertEngine(cfg, async (): Promise => { ...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 })), ]; - return { attention: attention.view, quota, health, drewActivity }; + return { attention: attention.view, quota, health, drewActivity, soleDoorPoolIds: deriveSoleDoorPoolIds(quota) }; }); diff --git a/pm-stack/aggregator/src/sw-source.ts b/pm-stack/aggregator/src/sw-source.ts index e457495e25..489c70e7ef 100644 --- a/pm-stack/aggregator/src/sw-source.ts +++ b/pm-stack/aggregator/src/sw-source.ts @@ -35,13 +35,16 @@ self.addEventListener('push', (event) => { body: data.body || '', tag: data.objectRef || undefined, renotify: !!data.escalation, - data: { url: data.url || '/alerts', class: data.class || null, objectRef: data.objectRef || null }, + data: { url: data.url || '/alerts', class: data.class || null, objectRef: data.objectRef || null, items: Array.isArray(data.items) ? data.items : null }, }; event.waitUntil(self.registration.showNotification(title, options)); }); self.addEventListener('notificationclick', (event) => { event.notification.close(); - const target = (event.notification.data && event.notification.data.url) || '/alerts'; + const nd = event.notification.data || {}; + // A single-item digest deep-links to that item; multi-item digests open + // their (refs-filtered) landing URL with the items carried in data. + const target = (Array.isArray(nd.items) && nd.items.length === 1 && nd.items[0] && nd.items[0].url) || nd.url || '/alerts'; event.waitUntil((async () => { const url = new URL(target, self.location.origin); const windows = await self.clients.matchAll({ type: 'window', includeUncontrolled: true }); diff --git a/pm-stack/aggregator/test/alerts.test.ts b/pm-stack/aggregator/test/alerts.test.ts index 0d7fdccc61..4d941bb321 100644 --- a/pm-stack/aggregator/test/alerts.test.ts +++ b/pm-stack/aggregator/test/alerts.test.ts @@ -1007,3 +1007,26 @@ describe("push subscription redaction (#3693)", () => { expect(verbatim).toContain(sentinelAuth); }); }); + +describe("subscription class preservation (#7193 Codex)", () => { + test("validateNewSubscription records only the explicitly sent class keys", () => { + const parsed = validateNewSubscription({ + endpoint: "https://push.example/x", + keys: { p256dh: "p", auth: "a" }, + classes: { incident: true }, + quiet: { start: "22:00", end: "06:00" }, + }); + expect(parsed.ok).toBe(true); + if (parsed.ok) { + expect(parsed.value.providedClasses).toEqual({ incident: true }); + // The expanded map is still the full default set for NEW rows. + expect(parsed.value.classes["quota-wall"]).toBe(true); + } + }); + + test("no classes sent records an empty provided set", () => { + const parsed = validateNewSubscription({ endpoint: "https://push.example/x", keys: { p256dh: "p", auth: "a" } }); + expect(parsed.ok).toBe(true); + if (parsed.ok) expect(parsed.value.providedClasses).toEqual({}); + }); +}); diff --git a/pm-stack/aggregator/test/attention-classification.test.ts b/pm-stack/aggregator/test/attention-classification.test.ts index 684ff31b1c..c30b3373ad 100644 --- a/pm-stack/aggregator/test/attention-classification.test.ts +++ b/pm-stack/aggregator/test/attention-classification.test.ts @@ -67,3 +67,20 @@ describe("attention classification", () => { expect(classifyAttention(phase13!, now).state).toBe("stuck-retrying"); }); }); + +describe("tierEntry tierSince (#7193 Codex)", () => { + test("a locally classified decision question carries tierSince from last activity, not creation", () => { + const entry = classifyAttention( + { + sessionId: "old-session-new-question", + createdAt: "2026-10-20T00:00:00Z", + lastActivityAt: "2026-10-25T01:30:00Z", + awaitingQuestion: "Which option should we pick for the migration?", + }, + Date.parse("2026-10-25T02:00:00Z"), + ); + const tiered = tierEntry(entry); + expect(tiered.tier).toBe("needs-drew"); + expect(tiered.tierSince).toBe("2026-10-25T01:30:00Z"); + }); +}); diff --git a/pm-stack/aggregator/test/notifications.test.ts b/pm-stack/aggregator/test/notifications.test.ts index 542346b52d..26c3cff313 100644 --- a/pm-stack/aggregator/test/notifications.test.ts +++ b/pm-stack/aggregator/test/notifications.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import { buildNotificationCandidates, decideNotification, + deriveSoleDoorPoolIds, nextNotificationDigestAt, NOTIFICATION_CLASS_DEFAULTS, rollupNotificationSends, @@ -403,3 +404,96 @@ describe("renderNotifications", () => { expect(html).toContain("unreachable"); }); }); + +describe("#7193 Codex regression fixes", () => { + const pool = (over: Record) => ({ + id: "p1", + provider: "Example", + plan: "Pro", + state: "ok", + windows: [], + ...over, + }); + + test("stale and errored quota reads never produce wall candidates", () => { + for (const state of ["stale", "error"]) { + const quota = { + pools: [ + pool({ + state, + windows: [{ name: "weekly", unit: "tokens", limit: 100, used: 100, percent: 100, resetsAt: "2026-11-20T00:00:00Z" }], + }), + ], + }; + const candidates = buildNotificationCandidates( + snapshot({ quota: quota as unknown as NotificationSnapshot["quota"], soleDoorPoolIds: new Set(["p1"]) }), + TASK_NOW, + ); + expect(candidates.filter((c) => c.class.startsWith("quota"))).toEqual([]); + } + }); + + test("wall reset comes from the exhausted window, not a healthy short window", () => { + const quota = { + pools: [ + pool({ + windows: [ + { name: "5h", unit: "tokens", limit: 100, used: 10, percent: 10, resetsAt: "2026-11-03T19:00:00Z" }, + { name: "weekly", unit: "tokens", limit: 100, used: 100, percent: 100, resetsAt: "2026-11-06T18:00:00Z" }, + ], + }), + ], + }; + const candidates = buildNotificationCandidates(snapshot({ quota: quota as unknown as NotificationSnapshot["quota"] }), TASK_NOW); + expect(candidates.map((c) => c.class)).toEqual(["quota-wall"]); + }); + + test("dedupe resets after a recovery marker, and only then", () => { + const candidate: NotificationCandidate = { + class: "stack-health", + objectRef: "health:aggregator", + stateFingerprint: '{"state":"down"}', + title: "t", + body: "b", + url: "/health", + observedAt: new Date(TASK_NOW).toISOString(), + breakthrough: false, + }; + const sent = { + at: new Date(TASK_NOW - 7 * 24 * 60 * 60_000).toISOString(), + class: "stack-health" as const, + objectRef: "health:aggregator", + stateFingerprint: '{"state":"down"}', + outcome: "sent" as const, + }; + expect(decideNotification(candidate, [sent], TASK_NOW, false)).toBe("suppress-dedupe"); + const recovered = { ...sent, at: new Date(TASK_NOW - 6 * 24 * 60 * 60_000).toISOString(), outcome: "recovered" as const }; + expect(decideNotification(candidate, [sent, recovered], TASK_NOW, false)).toBe("send"); + }); + + test("deriveSoleDoorPoolIds marks only single-pool providers", () => { + const quota = { + pools: [pool({ id: "a", provider: "Solo" }), pool({ id: "b", provider: "Duo" }), pool({ id: "c", provider: "Duo" })], + } as unknown as NotificationSnapshot["quota"]; + expect([...deriveSoleDoorPoolIds(quota)]).toEqual(["a"]); + }); + + test("filterAttentionViewByRefs keeps only the named entries", async () => { + const { filterAttentionViewByRefs } = await import("../src/derive.ts"); + const entry = (sessionId: string) => ({ sessionId, state: "errored", order: 1, evidence: "", tier: "needs-drew", lastActivityAt: null }); + const view = { + drew: [entry("s1"), entry("s2")], + orchestrator: [], + drewExtra: [{ id: "i1", kind: "task", title: "t", source: "github", reason: "r", since: "2026-11-03T00:00:00Z", lastSeenAt: "2026-11-03T00:00:00Z", ref: "developing-today/code#1" }], + orchestratorExtra: [], + watchdog: [], + all: [entry("s1"), entry("s2")], + expiredCount: 0, + tierSource: { present: true, state: "fresh" }, + } as unknown as Parameters[0]; + const filtered = filterAttentionViewByRefs(view, ["session:s2", "gh:developing-today/code#1"]); + expect(filtered.drew.map((e) => e.sessionId)).toEqual(["s2"]); + expect(filtered.drewExtra.map((i) => i.id)).toEqual(["i1"]); + expect(filtered.all.map((e) => e.sessionId)).toEqual(["s2"]); + }); +});