diff --git a/pm-stack/aggregator/src/alerts.ts b/pm-stack/aggregator/src/alerts.ts index aa99ef9f29..35d56aa55a 100644 --- a/pm-stack/aggregator/src/alerts.ts +++ b/pm-stack/aggregator/src/alerts.ts @@ -23,6 +23,15 @@ 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 { + buildNotificationCandidates, + decideNotification, + nextNotificationDigestAt, + NOTIFICATION_CLASS_DEFAULTS, + type NotificationHistoryEntry, + type NotificationSnapshot, +} from "./notifications.ts"; +import { JsonlNotificationHistory, type NotificationHistoryStore } from "./notification-history.ts"; // --- Shapes ---------------------------------------------------------------- @@ -127,7 +136,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 +181,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)? @@ -231,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 { @@ -294,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; } @@ -310,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: { @@ -317,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, }, @@ -387,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 *`, @@ -721,7 +747,268 @@ 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); + + 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); + } + + // 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))); + const suppressedOutcome: NotificationHistoryEntry["outcome"] = + decision === "digest" + ? "suppressed-quiet" + : decision === "suppress-dedupe" + ? "suppressed-dedupe" + : 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") { + 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: suppressedOutcome, + subscriptionId: sub.id, + }; + 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, + 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 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, + subscriptionId: sub.id, + }; + 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; + // #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, + 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); + } +} + +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) { @@ -746,12 +1033,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; @@ -760,7 +1048,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/derive.ts b/pm-stack/aggregator/src/derive.ts index da25fc337a..44637ce262 100644 --- a/pm-stack/aggregator/src/derive.ts +++ b/pm-stack/aggregator/src/derive.ts @@ -333,12 +333,18 @@ 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}` }; } 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; @@ -347,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}`, }; } @@ -355,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}`, }; } @@ -403,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/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/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 90eb44815c..52057a647e 100644 --- a/pm-stack/aggregator/src/notifications.ts +++ b/pm-stack/aggregator/src/notifications.ts @@ -22,8 +22,349 @@ // 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, + "needs-drew": true, + "quota-wall": true, + "quota-near-wall": true, + "stack-health": true, + "blocked-age": true, +}; + +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 | "weekly"; + /** Dashboard object-ref aliases used to stop escalation after Drew acts. */ + actedRefs?: string[]; +} + +export interface NotificationHistoryEntry { + at: string; + class: NotificationCandidate["class"]; + objectRef: string; + stateFingerprint: string; + outcome: + | "sent" + | "suppressed-quiet" + | "suppressed-dedupe" + | "suppressed-cooldown" + | "gone" + | "error" + | "queued" + | "queue-cancelled" + | "recovered"; + 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"; + +export interface NotificationSnapshot { + attention: AttentionView; + quota: QuotaView; + 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( + value: Omit & { + state: unknown; + breakthrough?: boolean; + }, +): NotificationCandidate { + const { state, breakthrough = false, ...rest } = value; + return { ...rest, stateFingerprint: JSON.stringify(state), breakthrough }; +} + +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.lastActivityAt ?? item.createdAt ?? new Date(now).toISOString(); + const actedRefs = [ + objectRef, + ...(itemId ? [`orch:${itemId}`] : []), + ...(itemRef ? [`gh:${itemRef}`] : []), + ]; + const entry = candidate({ + class: "needs-drew", + objectRef, + title: item.title ?? itemId ?? "Needs-Drew item", + 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); + if (!Number.isFinite(since) || now - since < BLOCKED_AGE_REMINDER_MS) return [entry]; + const step: 24 | 48 = now - since >= BLOCKED_AGE_BREAKTHROUGH_MS ? 48 : 24; + const reminders = [ + 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, + actedRefs, + state: { step }, + breakthrough: step === 48, + digestOnly: step === 24, + 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, + actedRefs, + state: { step: "weekly", week }, + digestOnly: true, + escalationStep: "weekly", + }), + ); + } + } + return reminders; +} + +/** 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"); + // 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 && + Date.parse(entry.at) > recoveredAt, + ) + ) { + 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 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) { + // #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 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) { + // #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( + 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)]) }, + }), + ); + } + } + + 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; +} + +/** 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; 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 6ce7233109..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 } 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 @@ -1981,9 +1990,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(); @@ -2402,4 +2416,17 @@ 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, actions, comments] = await Promise.all([ + attentionContext(), + source.quota().catch(() => emptyQuotaView()), + healthContext(false), + actionsStore.all().catch(() => []), + commentsStore.all().catch(() => []), + ]); + const drewActivity = [ + ...actions.filter((action) => action.author.kind === "drew").map((action) => ({ objectRef: action.objectRef, at: action.createdAt })), + ...comments.filter((comment) => comment.author.kind === "drew").map((comment) => ({ objectRef: comment.objectRef, at: comment.createdAt })), + ]; + 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 302e4e5515..4d941bb321 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 () => { @@ -91,15 +93,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": true, + "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 +305,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": true, + "stack-health": true, + "blocked-age": true, + }); expect(ok.value.quiet.tz).toBe("America/Chicago"); } expect( @@ -469,6 +487,107 @@ 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("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(); @@ -888,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/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..26c3cff313 100644 --- a/pm-stack/aggregator/test/notifications.test.ts +++ b/pm-stack/aggregator/test/notifications.test.ts @@ -1,14 +1,241 @@ -// 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 { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + buildNotificationCandidates, + decideNotification, + deriveSoleDoorPoolIds, + nextNotificationDigestAt, + NOTIFICATION_CLASS_DEFAULTS, + rollupNotificationSends, + sendTimestamp, + type NotificationCandidate, + type NotificationSnapshot, +} from "../src/notifications.ts"; import { AlertsStore, type NotificationSendRow } from "../src/alerts.ts"; -import { rollupNotificationSends, sendTimestamp } from "../src/notifications.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"; +const TASK_NOW = Date.parse("2026-11-03T18:00:00Z"); + +function snapshot(overrides: Partial = {}): NotificationSnapshot { + return { + attention: { drew: [], drewExtra: [] } as unknown as NotificationSnapshot["attention"], + quota: { pools: [] } as unknown as NotificationSnapshot["quota"], + health: { services: [] }, + ...overrides, + }; +} + +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(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"] }), + TASK_NOW, + ); + + 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("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 = { + 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: [ + { + 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"]) }), + TASK_NOW, + ); + + expect(candidates.map((entry) => [entry.class, entry.objectRef])).toEqual([ + ["quota-near-wall", "quota:sole"], + ["quota-wall", "quota:multi"], + ]); + }); + + 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"] }), + TASK_NOW, + ); + + expect(candidates).toHaveLength(1); + expect(candidates[0]).toMatchObject({ class: "stack-health", objectRef: "health:aggregator" }); + }); +}); + +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(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(TASK_NOW - 7 * 60 * 60_000).toISOString(), + class: base.class, + objectRef: base.objectRef, + stateFingerprint: base.stateFingerprint, + outcome: "sent" as const, + }, + ]; + 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(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, 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: 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"); + }); + + 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", () => { + 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. @@ -177,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"]); + }); +}); 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); }); });