diff --git a/.github/scripts/check-production-line-limit.sh b/.github/scripts/check-production-line-limit.sh index eaca2cdc1..edb5d2051 100755 --- a/.github/scripts/check-production-line-limit.sh +++ b/.github/scripts/check-production-line-limit.sh @@ -50,7 +50,6 @@ declare -A GRANDFATHERED=( # (re-pointed 2026-11-23 so every entry names the issue that # removes it, per this guard's convention). ["pm-stack/aggregator/src/render.ts"]="#13051" - ["pm-stack/aggregator/src/server.ts"]="#13052" ["pm-stack/aggregator/src/sources/live.ts"]="#13053" # The id-worlds files below moved from pkgs/id/src/ to # pkgs/id/crates/id-worlds/src/ in the id crate restructure; a key diff --git a/pm-stack/aggregator/src/server-alert-routes.ts b/pm-stack/aggregator/src/server-alert-routes.ts new file mode 100644 index 000000000..9ce5607b0 --- /dev/null +++ b/pm-stack/aggregator/src/server-alert-routes.ts @@ -0,0 +1,330 @@ +// Alert throat (#3676) routes: push subscriptions, test sends, the +// bearer-gated incident intake, and the alerts/notifications pages. +// Split out of server.ts (#13052). +import { healthHookAuditEvent } from "./health-hook-audit-event.ts"; +import { raiseNeedsDrew, validateNeedsDrew } from "./needs-drew.ts"; +import { getDecisionSet, raiseDecisionSet, validateDecisionSet } from "./decisions.ts"; +import { setStackHealth, validateStackHealth } from "./stack-health.ts"; +import { validateHealthHook, type HealthHookRecord } from "./health-hook.ts"; +import { timingSafeEqual } from "node:crypto"; +import { getAlertsStore, requestAlertTick, sendClassTestPush, sendTestPush, toPublicSubscription, validateNewIncident, validateNewSubscription } from "./alerts.ts"; +import { VAPID_PUBLIC_KEY } from "./push.ts"; +import { resolveBwsSecret } from "./secrets.ts"; +import { renderAlerts, renderNotificationPreferences, renderNotifications } from "./render.ts"; +import { isNotificationTestClass, NOTIFICATION_CLASS_DEFAULTS, NOTIFICATION_CLASSES, rollupNotificationSends } from "./notifications.ts"; +import { readJsonBody } from "./request-body.ts"; +import type { Source } from "./source.ts"; +import { cfg, eventsStore, source } from "./server-wiring.ts"; +import { json, html } from "./server-respond.ts"; +import { needsDrewAnswerUrl, decisionsPageUrl, logDecisionEvents } from "./server-pages.ts"; + +// --- Alert throat (#3676) ------------------------------------------------- + +/** Bearer check for POST /api/alerts: the intake token is resolved + * by name from Bitwarden (pm-aggregator.alerts-intake-token) and + * compared in constant time; its value is never logged. */ +export async function alertsIntakeAuthorized(req: Request): Promise { + const header = req.headers.get("authorization") ?? ""; + const presented = header.startsWith("Bearer ") ? header.slice("Bearer ".length).trim() : ""; + if (!presented) return false; + const expected = await resolveBwsSecret("pm-aggregator.alerts-intake-token"); + if (!expected) return false; + const a = Buffer.from(presented); + const b = Buffer.from(expected); + return a.length === b.length && timingSafeEqual(a, b); +} + +export const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +export async function handleAlertIntakeRoutes(req: Request, path: string): Promise { + // --- Alert throat (#3676): subscription API ------------------------- + if (path === "/api/push/subscriptions") { + const store = await getAlertsStore(); + if (!store) return json({ error: "alerts store unavailable" }, 503); + if (req.method === "POST") { + try { + const parsed = validateNewSubscription(await readJsonBody(req)); + if (!parsed.ok) return json({ error: parsed.error }, 400); + return json({ subscription: toPublicSubscription(await store.upsertSubscription(parsed.value)) }, 201); + } catch (err) { + return json({ error: `invalid subscription: ${err instanceof Error ? err.message : err}` }, 400); + } + } + if (req.method === "DELETE") { + try { + const body = (await readJsonBody(req)) as { endpoint?: unknown }; + if (typeof body.endpoint !== "string") return json({ error: "endpoint required" }, 400); + const deleted = await store.deleteSubscription(body.endpoint); + return deleted ? json({ deleted: true }) : json({ error: "no such subscription" }, 404); + } catch (err) { + return json({ error: `invalid delete: ${err instanceof Error ? err.message : err}` }, 400); + } + } + return json({ error: "method not allowed" }, 405); + } + + if (path === "/api/push/test") { + if (req.method !== "POST") return json({ error: "method not allowed" }, 405); + const store = await getAlertsStore(); + if (!store) return json({ error: "alerts store unavailable" }, 503); + const summary = await sendTestPush(store, cfg.publicOrigin); + return json(summary); + } + + // Per-class test sends (#3318): one test per preference class, + // honouring the stored class toggles, landing per design §3. + if (path === "/api/push/test-class") { + if (req.method !== "POST") return json({ error: "method not allowed" }, 405); + let cls: unknown; + try { + cls = ((await readJsonBody(req)) as { class?: unknown })?.class; + } catch { + return json({ error: "invalid test-class body" }, 400); + } + if (!isNotificationTestClass(cls)) return json({ error: "unknown notification class" }, 400); + const store = await getAlertsStore(); + if (!store) return json({ error: "alerts store unavailable" }, 503); + const summary = await sendClassTestPush(store, cfg.publicOrigin, cls); + return json(summary); + } + + // --- Alert throat (#3676): incident intake + ack/close -------------- + if (req.method === "POST" && path === "/api/alerts") { + if (!(await alertsIntakeAuthorized(req))) return json({ error: "unauthorized" }, 401); + const store = await getAlertsStore(); + if (!store) return json({ error: "alerts store unavailable" }, 503); + try { + const rawBody: unknown = await readJsonBody(req); + const parsed = validateNewIncident(rawBody); + if (!parsed.ok) return json({ error: parsed.error }, 400); + const ext = + rawBody && typeof rawBody === "object" && !Array.isArray(rawBody) ? (rawBody as Record) : {}; + const hasNeedsDrew = ext.needsDrew !== undefined; + const hasStackHealth = ext.stackHealth !== undefined; + const hasDecisionSet = ext.decisionSet !== undefined; + const hasHealthHook = ext.healthHook !== undefined; + // #12602 (#12599 decision b): the healthHook extension carries the + // full C3 incident record to the alerts ledger. It is gated and + // validated BEFORE the incident insert, unlike the extensions + // below, because a valid record rides the insert onto the opened + // event's detail; a malformed one is a 400 naming the field, + // before anything is stored. + let healthHook: HealthHookRecord | undefined; + if (hasHealthHook) { + if (parsed.value.source !== "health-hook") { + return json({ error: 'healthHook extension is only accepted for source "health-hook"' }, 400); + } + const hv = validateHealthHook(ext.healthHook); + if (!hv.ok) return json({ error: hv.error }, 400); + healthHook = hv.value; + } + const { incident, created } = await store.postIncident(parsed.value, healthHook ? { healthHook } : undefined); + const status = created ? 201 : 200; + // #8568/#8766 producer extensions: exactly one of needsDrew / + // stackHealth / decisionSet may ride an incident post; #12602 adds + // healthHook, which may co-ride with stackHealth (health-hook + // source only, gated above) and with nothing else. A VALIDATION + // failure of an extension is a 400 (the poster's bug should be + // loud at the poster), while a store failure is logged and never + // fails the incident post. + if ([hasNeedsDrew, hasStackHealth, hasDecisionSet].filter(Boolean).length > 1) { + return json({ error: "needsDrew, stackHealth and decisionSet extensions are mutually exclusive" }, 400); + } + if (hasHealthHook && (hasNeedsDrew || hasDecisionSet)) { + return json({ error: "healthHook extension may only co-ride with stackHealth" }, 400); + } + if (hasNeedsDrew) { + const v = validateNeedsDrew(ext.needsDrew); + if (!v.ok) return json({ error: v.error }, 400); + try { + const item = await raiseNeedsDrew(cfg.needsDrewFile, v.value, parsed.value.source); + requestAlertTick(); + return json( + { incident, created, needsDrew: { ledgerId: item.ledgerId, answerUrl: needsDrewAnswerUrl(item) } }, + status, + ); + } catch (err) { + console.error(`alerts intake: needsDrew raise failed (${err instanceof Error ? err.message : "error"})`); + return json({ incident, created }, status); + } + } + if (hasStackHealth) { + const v = validateStackHealth(ext.stackHealth); + if (!v.ok) return json({ error: v.error }, 400); + try { + await setStackHealth(cfg.stackHealthFile, v.value); + const auditEvent = healthHookAuditEvent({ + title: parsed.value.title, + source: parsed.value.source, + stackHealth: v.value, + }); + if (auditEvent) { + try { + await eventsStore.record(auditEvent); + } catch (err) { + console.error( + `alerts intake: health-hook audit append failed (${err instanceof Error ? err.message : "error"})`, + ); + } + } + if (v.value.state === "up") { + // #12602: a healthHook recovery record rides the closed + // event's detail of the incident it closes. + await store.closeOpenIncidentByKey( + parsed.value.source, + parsed.value.key, + healthHook?.state === "up" ? { healthHook } : undefined, + ); + } + requestAlertTick(); + } catch (err) { + console.error(`alerts intake: stackHealth update failed (${err instanceof Error ? err.message : "error"})`); + } + return json({ incident, created }, status); + } + if (hasDecisionSet) { + const v = validateDecisionSet(ext.decisionSet); + if (!v.ok) return json({ error: v.error }, 400); + try { + const beforeSet = await getDecisionSet(cfg.decisionsFile, v.value.setId).catch(() => null); + const set = await raiseDecisionSet(cfg.decisionsFile, v.value, parsed.value.source); + if (!beforeSet) { + await logDecisionEvents([ + { + setId: set.setId, + type: "set.created", + payload: { + via: "api/alerts", + source: parsed.value.source, + title: set.title, + items: set.items.length, + questions: set.items.reduce((n, i) => n + i.questions.length, 0), + }, + }, + ]); + } + requestAlertTick(); + return json({ incident, created, decisionSet: { setId: set.setId, pageUrl: decisionsPageUrl(set) } }, status); + } catch (err) { + console.error(`alerts intake: decisionSet raise failed (${err instanceof Error ? err.message : "error"})`); + return json({ incident, created }, status); + } + } + return json({ incident, created }, status); + } catch (err) { + return json({ error: `invalid incident: ${err instanceof Error ? err.message : err}` }, 400); + } + } + return null; +} + +export async function handleAlertAction(alertActionMatch: RegExpExecArray): Promise { + const id = alertActionMatch[1]; + if (!UUID_RE.test(id)) return json({ error: "incident id must be a uuid" }, 400); + const store = await getAlertsStore(); + if (!store) return json({ error: "alerts store unavailable" }, 503); + const result = alertActionMatch[2] === "ack" ? await store.ackIncident(id) : await store.closeIncident(id); + if (!result.incident) return json({ error: "no such incident", id }, 404); + return json({ incident: result.incident, transitioned: result.transitioned }); +} + +export async function handleAlertRead(alertReadMatch: RegExpExecArray): Promise { + const id = alertReadMatch[1]; + if (!UUID_RE.test(id)) return json({ error: "incident id must be a uuid" }, 400); + const store = await getAlertsStore(); + if (!store) return json({ error: "alerts store unavailable" }, 503); + const incident = await store.getIncident(id); + if (!incident) return json({ error: "no such incident", id }, 404); + const events = await store.listIncidentEvents(id); + return json({ incident, events }); +} + +export async function handleAlertsList(path: string, prov: () => ReturnType): Promise { + const store = await getAlertsStore(); + if (!store) { + return path === "/alerts" + ? html( + renderAlerts( + { available: false, incidents: [], events: [], subscriptions: [], ackWindowMin: cfg.alerts.ackWindowMin }, + prov(), + VAPID_PUBLIC_KEY, + ), + ) + : json({ error: "alerts store unavailable" }, 503); + } + try { + const [incidents, events, subscriptions] = await Promise.all([ + store.listIncidents(), + store.recentEvents(), + store.listSubscriptions(), + ]); + if (path === "/api/alerts.json") return json({ incidents, events }); + return html( + renderAlerts( + { available: true, incidents, events, subscriptions, ackWindowMin: cfg.alerts.ackWindowMin }, + prov(), + VAPID_PUBLIC_KEY, + ), + ); + } catch { + return path === "/alerts" + ? html( + renderAlerts( + { available: false, incidents: [], events: [], subscriptions: [], ackWindowMin: cfg.alerts.ackWindowMin }, + prov(), + VAPID_PUBLIC_KEY, + ), + ) + : json({ error: "alerts store unavailable" }, 503); + } +} + +export async function handleAlertPreferences(path: string, prov: () => ReturnType): Promise { + // #3318: subscription preferences — per-class toggles, quiet + // hours, this-browser state, per-class test sends. Writes go + // through the existing /api/push/subscriptions upsert; this + // route only reads the stored subscriptions for the form. + const store = await getAlertsStore(); + if (!store) { + return path === "/alerts/preferences" + ? html(renderNotificationPreferences({ available: false, subscriptions: [] }, prov(), VAPID_PUBLIC_KEY)) + : json({ error: "alerts store unavailable" }, 503); + } + try { + const subscriptions = await store.listSubscriptions(); + if (path === "/api/alerts/preferences.json") + return json({ + available: true, + subscriptions: subscriptions.map(toPublicSubscription), + classes: NOTIFICATION_CLASSES, + defaults: NOTIFICATION_CLASS_DEFAULTS, + }); + return html(renderNotificationPreferences({ available: true, subscriptions }, prov(), VAPID_PUBLIC_KEY)); + } catch { + return path === "/alerts/preferences" + ? html(renderNotificationPreferences({ available: false, subscriptions: [] }, prov(), VAPID_PUBLIC_KEY)) + : json({ error: "alerts store unavailable" }, 503); + } +} + +export async function handleNotificationsPage(path: string, prov: () => ReturnType): Promise { + // #3319: the weekly sent-vs-acted roll-up over the send ledger. + // Same reachability as every dashboard page (the tailnet origin); + // the only alerts write surface stays the bearer-gated intake. + const store = await getAlertsStore(); + if (!store) { + return path === "/notifications" + ? html(renderNotifications({ available: false, rollup: null }, prov())) + : json({ error: "alerts store unavailable" }, 503); + } + try { + const sends = await store.listSends(); + const rollup = rollupNotificationSends(sends, new Date()); + if (path === "/api/notifications.json") return json(rollup); + return html(renderNotifications({ available: true, rollup }, prov())); + } catch { + return path === "/notifications" + ? html(renderNotifications({ available: false, rollup: null }, prov())) + : json({ error: "alerts store unavailable" }, 503); + } +} diff --git a/pm-stack/aggregator/src/server-contexts.ts b/pm-stack/aggregator/src/server-contexts.ts new file mode 100644 index 000000000..5c500a4a5 --- /dev/null +++ b/pm-stack/aggregator/src/server-contexts.ts @@ -0,0 +1,809 @@ +// Page/API context assemblies: the cached board, roadmap, today, +// overview, attention, program and health assemblies the read routes +// render from. Split out of server.ts (#13052). +import { stat } from "node:fs/promises"; +import { type DashAction } from "./actions.ts"; +import { effectiveNeedsOrder } from "./tier-items.ts"; +import type { SavedView, ViewFilters, ViewItemLike } from "./views.ts"; +import { filtersFromQuery, ownerKey } from "./views.ts"; +import { createWatchdogGapSyncQueue, watchdogDeliveries } from "./activity.ts"; +import { loadFeed } from "./feed.ts"; +import { AA_PLAN_FACTS } from "./aa.ts"; +import { shouldFetchNeedsDrewCensus, type NeedsDrewCensus } from "./needs-drew.ts"; +import { buildHealth, summarizeItemCoverage, type HealthView, type ItemsCoverage } from "./health.ts"; +import { watchdogTierItems, WATCHDOG_PROBE_SERVICE_IDS } from "./watchdog.ts"; +import { readHostHealthSnapshot } from "./host-health.ts"; +import { allRefs, buildAttention, buildQuotaActions, deriveToday, quotaActionTierItems } from "./derive.ts"; +import { reconcileRoadmap, unavailableRoadmapReconciliation, type RoadmapReconciliation } from "./roadmap-reconcile.ts"; +import type { ProjectPoolItem, RefKey } from "./model.ts"; +import { isValidRef } from "./model.ts"; +import { programRefs } from "./program.ts"; +import { renderBoard, deriveOverview, renderOverview, buildRoadmapDrill } from "./render.ts"; +import { buildBriefs } from "./brief.ts"; +import { buildDigest, type Digest, type DigestKind } from "./digest.ts"; +import { searchWork } from "./search-view.ts"; +import type { Source } from "./source.ts"; +import { buildQueueView, queueInputsStale } from "./queue-view.ts"; +import { TodayCache, TODAY_CACHE_TTL_MS } from "./today-cache.ts"; +import { boardJsonBody, boardJsonViewBody } from "./board-json.ts"; +import { groupSamplesByFacet } from "./slo-journal.ts"; +import { SLO_DEFINITIONS, summarizeSloFacet, type SloFacetSummary } from "./slo.ts"; +import { watchdogHeartbeatLine } from "./watchdog-heartbeat.ts"; +import { createWatchdogHeartbeatRecorder, finishWatchdogGapSync } from "./watchdog-runner.ts"; +import { quotaForecastContract, subjectForecastContracts, type ForecastContract } from "./forecast-contract.ts"; +import { cfg, itemHistoryStore, sloJournal, actionsStore, commentsStore, viewsStore, freshnessStore, freshnessReconciler, activityStore, recordActivity, watchdogEpisodes, source, briefCommentsFor, assembleConflicts, commentFormOpts, emptyQuotaView } from "./server-wiring.ts"; + +export async function loadBoardContext() { + const board = await source.board().catch(() => []); + const refs = allRefs(board); + const items = await source.items(refs).catch(() => new Map()); + return { board, items }; +} + +// #5082: the board assembly is the stack's most expensive read — a +// Kaneo login + poll with per-project task pagination, one projector +// /links call per card, and the items() closure over every ref — and +// every board-family request used to pay it in full. Under ordinary +// fleet load the assembly outlives the 10 s dashboard deadline +// (assembly-deadline.ts), so /board, /api/board.json, and the overview +// (which embeds the board) 503'd even with every upstream healthy; +// concurrent cold loads each started their own assembly and multiplied +// the damage (measured 2026-11-08: 3 concurrent -> 3 assemblies, all +// 503). The assembly now gets the /today contract (#1179): a short TTL +// serves warm hits from the last successful read, and concurrent cold +// requests share one in-flight load. +// +// The cache sits BELOW the variant split, which is what makes it safe +// for every consumer: ?done=all, saved-view filters, and the HTML/JSON +// renderers are all derived per request from this one context +// (boardJsonBody / boardJsonViewBody / renderBoard), so no variant can +// ever be served another variant's body. Provenance stays truthful the +// same way it does for /today: prov()/provDetail() are still read live +// per request at the call sites. Fail-soft fallbacks (an empty board +// when Kaneo is down) are the honest degraded state of the read and +// are cached as-is until expiry, exactly as #1179 documents; a +// throwing load is never cached. +export const boardContextCache = new TodayCache>>(TODAY_CACHE_TTL_MS); +export async function boardContext(): Promise>> { + return boardContextCache.get(loadBoardContext); +} + +/** All shared forecast contracts (#3984): epic-completion + stall-risk + * per epic subject from the stored item history (#3981), and one + * quota-exhaustion contract per quota pool. The rate for a pool is + * only usable when the gatherer measured a token burn for a token + * window with ok freshness — anything else stays the contract's + * first-class quota_rate_unavailable state, never an invented date. */ +export async function allForecastContracts( + pool: ProjectPoolItem[], +): Promise<{ byRef: Map; contracts: ForecastContract[] }> { + const byRef = new Map(); + const contracts: ForecastContract[] = []; + const add = (c: ForecastContract) => { + contracts.push(c); + byRef.set(c.subjectRef, [...(byRef.get(c.subjectRef) ?? []), c]); + }; + const cutoffs = await itemHistoryStore.readAll().catch(() => []); + if (cutoffs.length) { + const poolByRef = new Map(pool.map((it) => [it.ref, it])); + const subjects = new Set(); + for (const cutoff of cutoffs) { + for (const item of cutoff.items) { + if (item.parentRef) subjects.add(item.parentRef); + } + } + for (const subjectRef of subjects) { + const poolItem = poolByRef.get(subjectRef); + const statusDisagreement = + poolItem && + poolItem.status && + ((poolItem.state === "closed" && poolItem.status !== "Done") || + (poolItem.state === "open" && poolItem.status === "Done")) + ? `GitHub state ${poolItem.state} disagrees with Project Status ${poolItem.status}; both are shown, neither is preferred` + : null; + for (const c of subjectForecastContracts(cutoffs, subjectRef, { + updatedAt: poolItem?.updatedAt ?? null, + statusDisagreement, + scope: `direct native children of ${subjectRef} in the Project #4 pool item history (curated pool scope, not a repo-wide backlog)`, + })) { + add(c); + } + } + } + const quota = await source.quota().catch(() => emptyQuotaView()); + const asOf = new Date().toISOString(); + for (const qpool of quota.pools) { + const window = qpool.windows + .filter((w) => w.limit !== null && w.limit > 0) + .sort((a, b) => (b.percent ?? 0) - (a.percent ?? 0))[0]; + const rate = + window && window.unit === "tokens" && qpool.burnTokensPerMin != null && qpool.freshness?.state === "ok" + ? { amountPerHour: qpool.burnTokensPerMin * 60, observedAt: qpool.freshness.measuredAt } + : null; + add( + quotaForecastContract({ + poolId: qpool.id, + provider: qpool.provider, + asOf, + unit: window?.unit ?? "tokens", + remainingAmount: window ? window.limit! - window.used : null, + limitAmount: window?.limit ?? null, + nextReset: window?.resetsAt ?? null, + rate, + scope: `quota pool ${qpool.id} (${qpool.provider}/${qpool.plan})`, + }), + ); + } + return { byRef, contracts }; +} + +export async function roadmapContext() { + const rows = await source.roadmap().catch(() => []); + const refs = allRefs(rows); + const [items, poolResult] = await Promise.all([ + source.items(refs).catch(() => new Map()), + source.projects().then( + (pool) => ({ pool, failed: false }), + () => ({ pool: [] as ProjectPoolItem[], failed: true }), + ), + ]); + // #1144: reconcile the Grist rows against the Project's Kind=Epic + // pool items on every roadmap read, so the page flag and the JSON + // drift report always describe the same pass as the rows themselves. + // Codex P2 on PR 2428: an unread source is NOT an empty source — in + // live mode, a Grist fixtures fallback or a fleet feed with no + // projects section means reconciliation is unavailable, and no + // drift may be asserted from it. + let reconciliation: RoadmapReconciliation; + if (cfg.source === "live") { + const reasons: string[] = []; + const roadmapProv = source.provenance().roadmap; + if (!roadmapProv.startsWith("live")) reasons.push(`Grist roadmap read unavailable (${roadmapProv})`); + if (poolResult.failed) reasons.push("Project pool read failed"); + const feed = await loadFeed(cfg.feedFile).catch(() => null); + if (!feed) reasons.push("fleet feed unreadable — Project pool availability unknown"); + else if (feed.projects === undefined) + reasons.push("fleet feed carries no projects section — Project pool availability unknown"); + reconciliation = reasons.length + ? unavailableRoadmapReconciliation(reasons.join("; ")) + : reconcileRoadmap(rows, poolResult.pool); + } else { + reconciliation = reconcileRoadmap(rows, poolResult.pool); + } + // #1168: the drill-down index rides the same pass as the + // reconciliation, and only exists when the reconciliation is + // available — an unavailable source must not render as "no epic yet". + const drill = + reconciliation.availability === "available" ? buildRoadmapDrill(rows, reconciliation, poolResult.pool) : undefined; + return { rows, items, pool: poolResult.pool, reconciliation, drill }; +} + +export async function searchContext(query: string) { + // #1212 slice 2: registry, DNS, services, and tier items join the + // board/roadmap subjects. Each extra source fails soft (empty on + // error) so one broken source never takes search down with it. + const [board, rows, registry, dns, usage, orchestration] = await Promise.all([ + source.board(), + source.roadmap(), + source.registry().catch(() => []), + source.dns().catch(() => null), + source.usage().catch(() => null), + source.orchestration().catch(() => null), + ]); + const tierItems = orchestration ? [...orchestration.tiers.needsDrew, ...orchestration.tiers.needsOrchestrator] : []; + // Codex P2 on PR #7331: refs carried only by the slice-2 sources + // (registry taskRefs, tier-item refs) join the resolution set, or + // their search badges always render unresolved even when the live + // pool/projector could resolve them. + const extraRefs = [...registry.flatMap((record) => record.taskRefs), ...tierItems.map((item) => item.ref)].filter( + isValidRef, + ); + const refs = [...new Set([...allRefs(board), ...allRefs(rows), ...extraRefs])]; + const items = await source.items(refs); + const extras = { registry, dns, services: usage?.services ?? [], tierItems }; + return { query, results: searchWork(board, rows, items, query, extras), items }; +} + +// #3321: watchdog gap-sync passes run whole and in observation +// order through this queue (Codex P2, PR #5141 round 5) — see +// createWatchdogGapSyncQueue in activity.ts for why the bare +// fire-and-forget sync interleaved. +export const enqueueWatchdogGapSync = createWatchdogGapSyncQueue(); +export const watchdogHeartbeatRecorder = createWatchdogHeartbeatRecorder(async (nowMs) => { + await sloJournal.append([watchdogHeartbeatLine(nowMs)]); +}); + +/** Record liveness only after a watchdog derivation completes. A timer here + * would stay green even if the watchdog work itself stopped making progress. */ +export async function recordWatchdogHeartbeat(nowMs: number, scheduled = false): Promise { + try { + await (scheduled ? watchdogHeartbeatRecorder.scheduled(nowMs) : watchdogHeartbeatRecorder.request(nowMs)); + } catch (error) { + console.error( + `[watchdog] WARNING: heartbeat append failed: ${error instanceof Error ? error.message : String(error)}`, + ); + } +} + +// #1148: the watchdog derives NEEDS ORCHESTRATOR items from the +// current diagnoses (feed age + probes via the health assembly — +// its probe cache keeps this cheap — plus the orchestration +// diagnosis and registry facet age). Live mode only: fixtures mode +// has no real inputs to watch. Derived on attention reads and on the +// server-owned watchdog tick below, so it does not depend on dashboard +// traffic. Recovery clears the cards on the next derivation. The health +// assembly here is deliberately UNPRIMED (see healthContext): the +// watchdog needs only the feed file, the cached probes, and the +// registry age from the source's already-loaded feed. +export async function deriveWatchdogItems( + diagnosis?: ReturnType>["orchestration"], + mode: "request" | "scheduled" = "request", +) { + if (cfg.source !== "live") return []; + const [health, projectAudit, hostHealth] = await Promise.all([ + healthContext(false), + source.projectAudit ? source.projectAudit().catch(() => null) : Promise.resolve(null), + // #10141: the host-health collector's snapshot (claimant mode + + // PM unit states). A read failure yields null, which the watchdog + // surfaces as the snapshot-absent item — the surfacer's own + // silence is a breach, never a pass. + readHostHealthSnapshot(cfg.hostHealthFile).catch(() => null), + ]); + const items = watchdogTierItems({ + now: Date.now(), + feedAgeMs: health.feed.ageMs, + feedGeneratedAt: health.feed.generatedAt, + ...(diagnosis ? { orchestration: diagnosis } : {}), + projectAudit, + ...(source.provenanceDetail ? { registryAgeMs: source.provenanceDetail().registry.ageMs } : {}), + probes: health.services + .filter((s) => WATCHDOG_PROBE_SERVICE_IDS.includes(s.def.id)) + .map((s) => ({ + id: s.def.id, + name: s.def.name, + ok: s.ok, + detail: s.detail, + ...(s.probedAt ? { probedAt: s.probedAt } : {}), + })), + hostHealth, + }); + // #3321: every derivation is also an ingestion pass — the current + // breach episodes go to the stream (dedupe makes re-derivation a + // no-op) and the gap records sync with the breach set. Episodes + // are stabilized first (first-observed `since` wins until the + // breach clears), so one continuous outage is one delivery. + const stableItems = watchdogEpisodes.stabilize(items); + void recordActivity(watchdogDeliveries(stableItems)); + await finishWatchdogGapSync({ + items, + sync: enqueueWatchdogGapSync(activityStore, stableItems), + mode, + recordHeartbeat: () => recordWatchdogHeartbeat(Date.now(), mode === "scheduled"), + onError: (err) => { + console.error( + `[activity] WARNING: watchdog gap sync failed: ${err instanceof Error ? err.message : String(err)}`, + ); + }, + }); + return items; +} + +export async function loadAttentionContext(opts: { census?: boolean } = {}) { + // #1226/#3970: the Needs-Drew census costs up to eight sequential + // GitHub search calls (up to ~64 s when the API is unreachable). Only + // the attention page render consumes it, so it opts in; the overview, + // Today, /api/attention.json and /api/coverage.json must not inherit + // that external dependency (Codex P2 on PR #3970). + const wantsCensus = shouldFetchNeedsDrewCensus(opts); + const [feed, summary, coverage, census] = await Promise.all([ + source.attention().catch(() => []), + source.orchestration().catch(() => null), + source.coverage().catch(() => []), + // A source without the census (or a failed sweep) yields null and + // the view renders it as unavailable, never as an empty queue. + wantsCensus + ? ((source.needsDrew?.() ?? Promise.resolve(null)).catch(() => null) as Promise) + : Promise.resolve(null), + ]); + // Read the diagnosis AFTER orchestration() has run: the live source + // recomputes it on every orchestration read (#1139). + const diagnosis = source.diagnostics?.().orchestration; + const watchdog = await deriveWatchdogItems(diagnosis); + const quota = await source.quota().catch(() => null); + const view = buildAttention(feed, summary, Date.now(), diagnosis, watchdog); + // #1174: the same eligible quota actions as /quota's strip and + // /today, as orchestrator-tier task items — derived once here from + // the same pure function, so entries clear on every surface the + // moment their source condition no longer holds. + const quotaItems = quota ? quotaActionTierItems(buildQuotaActions(quota, AA_PLAN_FACTS)) : []; + if (quota) { + view.orchestratorExtra = [...view.orchestratorExtra, ...quotaItems]; + } + return { + view, + quotaItems, + coverage, + orchestration: summary, + diagnosis, + census, + }; +} + +// #9850: /api/attention.json is a sentinel-probed health surface, but +// the assembly above re-reads every source leg on every request — under +// load that per-request cost is what flapped the feed (multi-second +// answers at load ~10). Same contract as the today/overview assemblies +// (#5082): a short-TTL cache with coalesced loads and +// stale-while-revalidate, one cache per census variant — the census +// assembly costs up to ~64 s of GitHub search calls and must never +// ride the JSON path, or vice versa. +export const attentionContextCache = new TodayCache>>(TODAY_CACHE_TTL_MS); +export const attentionCensusContextCache = new TodayCache>>( + TODAY_CACHE_TTL_MS, +); +export async function attentionContext(opts: { census?: boolean } = {}) { + return opts.census + ? attentionCensusContextCache.get(() => loadAttentionContext(opts)) + : attentionContextCache.get(() => loadAttentionContext(opts)); +} + +/** + * One Datastar patch-elements event (#1444). The fragment root carries + * its own id + `data-on:dashrefresh__window` refresh hook, so "outer" + * mode replaces the shell's placeholder with a self-refreshing + * container. The payload deliberately carries NO `data-init` (#10605): + * an outer-mode patch re-mounts the element, so an init trigger inside + * the payload would fetch itself again on every patch — a loop. First + * paint is driven by the shell placeholder's `data-init` instead. + */ +export function ssePatch(selector: string, elementHtml: string): string { + const lines = elementHtml + .split("\n") + .map((l) => `data: elements ${l}`) + .join("\n"); + return `event: datastar-patch-elements\ndata: mode outer\ndata: selector ${selector}\n${lines}\n\n`; +} + +export function sseResponse(body: string): Response { + return new Response(body, { + headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache" }, + }); +} + +/** The render inputs the board page and its fragment share. */ +export async function boardRender() { + const { board, items } = await boardContext(); + const [pool, orchestration, formOpts, actionsByObject, counts] = await Promise.all([ + source.projects().catch(() => []), + source.orchestration().catch(() => null), + commentFormOpts(), + actionsStore.byObject(), + commentsStore.countsDetailed(), + ]); + const poolByRef = new Map(pool.map((p) => [p.ref, p])); + const refs = [ + ...new Set(board.flatMap((item) => item.links.map((link) => link.ref)).filter((ref) => poolByRef.has(ref))), + ]; + const comments = refs.length ? await briefCommentsFor(refs) : []; + const orchestrationStatus = source.diagnostics?.().orchestration.state; + const briefs = buildBriefs(pool, { comments, orchestration, orchestrationStatus }); + const act = { + actionsByObject, + poolByRef, + identities: formOpts.identities, + briefs, + }; + return { board, items, counts, act }; +} + +/** The render inputs the attention page and its fragments share: + * the view, the action/comment stores grouped by object, and the + * effective Needs-you order preference (#1456). */ +export async function attentionRender() { + const { view, coverage, orchestration, diagnosis, census } = await attentionContext({ census: true }); + const [pool, formOpts, actionsByObject, commentsByObject, counts, allActions] = await Promise.all([ + source.projects().catch(() => []), + commentFormOpts(), + actionsStore.byObject(), + commentsStore.byObject(), + commentsStore.countsDetailed(), + actionsStore.all(), + ]); + const order = effectiveNeedsOrder(allActions); + const refs = [ + ...new Set([...view.drewExtra, ...view.orchestratorExtra].flatMap((item) => (item.ref ? [item.ref] : []))), + ]; + const comments = refs.length ? await briefCommentsFor(refs) : []; + const briefs = buildBriefs(pool, { comments, orchestration, orchestrationStatus: diagnosis?.state }); + const act = { + actionsByObject, + identities: formOpts.identities, + commentsByObject, + commentOpts: formOpts, + needsOrder: order.order, + needsOrderPending: order.pending, + }; + return { view, coverage, counts, act, briefs, census }; +} + +export async function loadTodaySignals() { + const [health, quotaResult] = await Promise.all([ + healthContext(false).catch(() => null), + source + .quota() + .then((quota) => ({ quota, unavailable: false })) + .catch(() => ({ quota: emptyQuotaView(), unavailable: true })), + ]); + return { health, quota: quotaResult.quota, quotaUnavailable: quotaResult.unavailable }; +} + +// #1179: the shell (/today) and the fragment (/frag/today) both need +// the health+quota strip, seconds apart on every page view. Bound the +// repeated live reads with a short TTL; concurrent cold requests share +// the in-flight load. Provenance stays truthful: prov()/provDetail() +// are still read live per request at the call sites below. +export const todaySignalsCache = new TodayCache>>(TODAY_CACHE_TTL_MS); +export async function todaySignals(): Promise>> { + return todaySignalsCache.get(loadTodaySignals); +} + +export async function loadTodayContext() { + const [{ board, items }, { rows, pool }, { view, coverage, orchestration }, signals] = await Promise.all([ + boardContext(), + roadmapContext(), + attentionContext(), + todaySignals(), + ]); + const diagnosis = source.diagnostics?.().orchestration; + const queue = buildQueueView({ board, pool, items, orchestration }); + return { + today: deriveToday(board, rows, items, orchestration, new Date(), diagnosis, pool), + view, + coverage, + ...signals, + queue, + queueStale: queueInputsStale(signals.health), + }; +} + +// #1179: /today?full=1, /frag/today, and /api/today.json all render +// from this one assembly. Same short-TTL + coalescing contract as the +// signals cache above; a throwing cold load is never cached (the +// fetch error boundary still 500s) and expiry serves the stale copy +// while one background refresh re-reads (#5082 SWR). +export const todayContextCache = new TodayCache>>(TODAY_CACHE_TTL_MS); +export async function todayContext(): Promise>> { + return todayContextCache.get(loadTodayContext); +} + +export async function queueContext() { + const [{ board, items }, pool, orchestration] = await Promise.all([ + boardContext(), + source.projects().catch(() => [] as ProjectPoolItem[]), + source.orchestration().catch(() => null), + ]); + return buildQueueView({ board, pool, items, orchestration }); +} + +/** The render inputs the overview (front door, #1134) assembles: + * the attention view, the Project pool, quota, the health view, and + * the board — the same contexts the dedicated pages render from. */ +export async function loadOverviewContext() { + const [{ view }, pool, quota, health, { board, items }, orchestration, actionsByObject] = await Promise.all([ + attentionContext(), + source.projects().catch(() => [] as ProjectPoolItem[]), + source.quota().catch(() => emptyQuotaView()), + healthContext(), + boardContext(), + source.orchestration().catch(() => null), + actionsStore.byObject().catch(() => new Map()), + ]); + return { attention: view, pool, quota, health, board, items, orchestration, actionsByObject }; +} + +// #5082: same contract as the board assembly above — the overview +// fan-out (attention + pool + quota + health + board + orchestration) +// was re-run live on every /, /frag/overview, and /api/overview.json +// request and tripped the same 10 s deadline. The per-request +// derivations (deriveOverview / renderOverview) and the provenance +// reads stay live; only the assembly is cached. The board leg inside +// rides the boardContext cache, so a cold overview and a cold board +// share one board assembly. +export const overviewContextCache = new TodayCache>>(TODAY_CACHE_TTL_MS); +export async function overviewContext(): Promise>> { + return overviewContextCache.get(loadOverviewContext); +} + +// #3976 (Codex review on PR #9193): a freshness notice means canonical +// data changed, but the TTL caches above could still serve an assembly +// built before the notice for up to 10s — and nothing re-requests when +// the TTL expires, so an accepted revision could stay invisible until +// a later notice or a manual refresh. Invalidate the two assemblies +// the freshness fragments reread (/frag/overview, /frag/today) the +// moment a notice becomes durable. The store seam covers every +// acceptance path — in-process recordFreshness, the IPC handler, and +// the reconciler's synthetic invalidations all publish through the +// same store. +// +// #5082 (2026-11-14): invalidate, don't clear. Notices land every few +// minutes (115 in the 3 h before steward run 379), and clear() dropped +// the cached assembly entirely, so the first post-notice request paid +// the full cold assembly on the request path. That request is +// routinely an hourly watch arriving after a quiet gap; when the +// assembly chain inflated past the 10 s dashboard deadline under load +// (steward runs 378/379: /api/overview.json 503 at 10.42 s, pass 2 +// clean), the deadline's last-good was always older than its 5-minute +// staleness cap at that cadence, so the fallback was a hard 503. +// invalidate() keeps the last assembly servable under the ordinary +// SWR contract — the first post-notice request serves it immediately +// and refreshes behind it — and the kick below starts that refresh +// at notice time, so an accepted revision becomes visible one +// assembly later without any request paying for the rebuild. +freshnessStore.onNotice(() => { + overviewContextCache.invalidate(); + todayContextCache.invalidate(); + attentionContextCache.invalidate(); + attentionCensusContextCache.invalidate(); + void overviewContext().catch(() => {}); + void todayContext().catch(() => {}); +}); + +/** The live-source half of the /program assembly (#1046 + #1121): the + * items closure for the program refs, the Project pool, the roadmap, + * orchestration, and the coverage census inputs. Everything + * view-dependent (saved-view filtering, briefs, forecasts, the + * render) is derived per request from this bundle in the handler. */ +export async function loadProgramSources() { + const [items, pool, rows, orchestration, census, poolAvailable] = await Promise.all([ + source.items(programRefs()).catch(() => new Map()), + source.projects().catch(() => []), + source.roadmap().catch(() => []), + source.orchestration().catch(() => null), + source.coverageCensus ? source.coverageCensus().catch(() => null) : Promise.resolve(null), + source.projectsAvailable ? source.projectsAvailable().catch(() => false) : Promise.resolve(true), + ]); + return { items, pool, rows, orchestration, census, poolAvailable }; +} + +// #5082: /program is a bounded dashboard route with the same failure +// shape — its source fan-out ran live on every request. Same TTL + +// single-flight contract as the board/overview assemblies above. +export const programSourcesCache = new TodayCache>>(TODAY_CACHE_TTL_MS); +export async function programSources(): Promise>> { + return programSourcesCache.get(loadProgramSources); +} + +// -- Saved views (#1276) ------------------------------------------------- +// A request names a view three ways, in precedence order: explicit +// vf.* filter params (the shareable-URL form — reproduces the view for +// any viewer with no store lookup), a view id (store lookup), or the +// viewer's own default view (the viewer is named by the `viewer` query +// param, the dashboard author key ":"). No view named = the +// pages render exactly as before. + +export interface ResolvedView { + filters: ViewFilters; + view: SavedView | null; +} + +export async function resolveView(url: URL): Promise { + const fromQuery = filtersFromQuery(url.searchParams); + if (fromQuery) { + const id = url.searchParams.get("view"); + return { filters: fromQuery, view: id ? await viewsStore.get(id).catch(() => null) : null }; + } + const id = url.searchParams.get("view"); + if (id) { + const view = await viewsStore.get(id).catch(() => null); + return view ? { filters: view.filters, view } : null; + } + const viewer = url.searchParams.get("viewer"); + if (viewer) { + const view = await viewsStore.defaultFor(viewer).catch(() => null); + return view ? { filters: view.filters, view } : null; + } + return null; +} + +export function poolItemLike(item: ProjectPoolItem): ViewItemLike { + return { + ref: item.ref, + repo: item.repo, + area: item.area, + horizon: item.horizon, + owner: item.author ?? null, + state: item.state, + epic: item.epicRef ?? null, + status: item.status, + kind: item.kind, + }; +} + +export function eventContextByRef(pool: readonly ProjectPoolItem[]): Map { + const context = new Map(); + for (const item of pool) { + const ref = item.ref.replace(/^gh:/i, "").toLowerCase(); + context.set(ref, { + project: item.projectUrl, + epic: item.epicRef ?? (item.kind?.toLowerCase() === "epic" ? item.ref : null), + }); + } + return context; +} + +export function eventFilterFromUrl( + url: URL, + itemContext: ReadonlyMap, +) { + return { + kind: url.searchParams.get("kind") ?? undefined, + refs: url.searchParams.getAll("ref"), + actor: url.searchParams.get("actor") ?? undefined, + project: url.searchParams.get("project") ?? undefined, + epic: url.searchParams.get("epic") ?? undefined, + search: url.searchParams.get("q") ?? undefined, + itemContext, + }; +} + +/** Apply a preference view verb to the views store (#1276). Returns a + * result note for the action record, or throws — the caller maps a + * throw to a rejected action so the audit trail says what happened. */ +export async function applyViewAction(action: DashAction): Promise { + const owner = ownerKey(action.author); + const pl = action.payload; + switch (action.verb) { + case "save-view": { + const view = await viewsStore.save({ owner, name: pl.viewName!, filters: pl.viewFilters! }); + return `saved view ${view.id} "${view.name}"`; + } + case "rename-view": { + const view = await viewsStore.rename(pl.viewId!, owner, pl.viewName!); + if (!view) throw new Error(`no view ${pl.viewId} for this owner`); + return `renamed view ${view.id} to "${view.name}"`; + } + case "delete-view": { + const gone = await viewsStore.remove(pl.viewId!, owner); + if (!gone) throw new Error(`no view ${pl.viewId} for this owner`); + return `deleted view ${pl.viewId}`; + } + case "set-default-view": { + if (pl.viewId === undefined) { + await viewsStore.setDefault(null, owner); + return "default view cleared"; + } + const view = await viewsStore.setDefault(pl.viewId, owner); + if (!view) throw new Error(`no view ${pl.viewId} for this owner`); + return `default view is now ${view.id} "${view.name}"`; + } + default: + throw new Error(`not a view verb: ${action.verb}`); + } +} + +/** The digest (#1278): built live from the same Source as every page; + * the archived form is the JSON the generator script wrote. */ +export async function digestContext(kind: DigestKind): Promise { + // Prime the items facet first (#1267 pattern): items() is the call + // that records the pool's feed freshness into provenance — without + // it the digest's pool sections would read an unprimed facet. + await source.items([]).catch(() => null); + const [pool, needsDrew, quota, poolAvailable] = await Promise.all([ + source.projects(), + source.needsDrew ? source.needsDrew().catch(() => null) : Promise.resolve(null), + source.quota().catch(() => null), + source.projectsAvailable ? source.projectsAvailable().catch(() => undefined) : Promise.resolve(undefined), + ]); + return buildDigest({ + pool, + needsDrew, + quota, + provenanceDetail: source.provenanceDetail?.() ?? null, + poolAvailable, + sourceKind: cfg.source, + now: new Date(), + kind, + }); +} + +export const GRAINS = new Set(["quarter", "month", "week", "3d", "today"]); + +/** + * #1267: the live source populates its provenance strings lazily, one + * facet per method call — so a consumer that reads provenance() + * without exercising the facets (exactly what /api/health did) + * reports "fixtures" for facets that are really live, and its answer + * depends on which pages were visited since boot. Health therefore + * exercises every facet method before reading provenance. Priming is + * cached for 60 s (the #1147 probe-cache cadence): facet reads are + * mostly cache- or file-backed, and a watchdog polling health must + * not fan out to every upstream on every hit. Facet failures never + * fail health — a failed facet keeps its honest fallback string, + * which is precisely what health exists to report. + */ +export let lastPrimedAt = 0; +/** #1141: item coverage measured by the latest priming pass (below), + * from the same board items() resolution that sets facet provenance. */ +export let lastItemsCoverage: ItemsCoverage | null = null; +export let priming: Promise | null = null; +export async function ensureProvenancePrimed(): Promise { + if (Date.now() - lastPrimedAt < 60_000) return; + priming ??= (async () => { + try { + const { items } = await boardContext(); + lastItemsCoverage = summarizeItemCoverage(items); + const refs = [...items.keys()]; + await Promise.allSettled([ + source.roadmap(), + source.comments(refs), + source.quota(), + source.usage(), + source.attention(), + source.orchestration(), + source.dns(), + source.aa(), + source.registry(), + source.projects(), + ]); + } catch { + /* facets that failed keep their fallback strings — health reports those */ + } + lastPrimedAt = Date.now(); + priming = null; + })(); + await priming; +} + +/** + * The one health assembly behind both /health and /api/health + * (#1147): primed provenance first (so facet truth never depends on + * request order, #1267), then the feed snapshot the section ages and + * job lines are measured from, then buildHealth's probes (cached + * 60 s inside health.ts). Page and API read this same view, so they + * cannot disagree. + */ +export async function healthContext(prime = true): Promise { + // Priming exercises every facet so /health provenance never depends + // on request order. Callers that only need the feed snapshot and the + // cached probes (the attention path's watchdog assembly, #1148) pass + // prime=false: a stalled unrelated facet (e.g. Grist's roadmap API + // and its 8s timeout) must not delay attention rendering (Codex P2 + // on PR #2431). The registry age the watchdog reads comes from the + // live source's lastFeed, which attention's own reads already load. + if (prime) await ensureProvenancePrimed(); + const [feed, feedFileMtimeMs, quota] = await Promise.all([ + loadFeed(cfg.feedFile).catch(() => null), + stat(cfg.feedFile) + .then((s) => s.mtimeMs) + .catch(() => null), + source.quota().catch(() => emptyQuotaView()), + ]); + return buildHealth({ + mode: cfg.source, + cfg, + feed, + feedFileMtimeMs, + quota, + diagnosis: source.diagnostics?.().orchestration, + detail: source.provenanceDetail?.(), + itemsCoverage: lastItemsCoverage, + comments: await commentsStore.pendingCounts().catch(() => undefined), + conflicts: await assembleConflicts().catch(() => null), + pushHealth: cfg.source === "fixtures" ? null : freshnessReconciler.health(new Date()), + slo: cfg.source === "fixtures" ? null : await sloSummaries(), + }); +} + +// SLO error budgets (#9988): summaries are read from the append-only journal +// and cached for a minute, the same cadence the sampler writes at. +export const SLO_SUMMARY_CACHE_MS = 60_000; +export async function sloSummaries(nowMs = Date.now()): Promise { + if (sloSummaryCache && nowMs - sloSummaryCache.at < SLO_SUMMARY_CACHE_MS) return sloSummaryCache.value; + const byFacet = groupSamplesByFacet(await sloJournal.readAll().catch(() => [])); + const value = SLO_DEFINITIONS.map((definition) => + summarizeSloFacet(definition, byFacet.get(definition.id) ?? [], nowMs), + ); + sloSummaryCache = { at: nowMs, value }; + return value; +} +export let sloSummaryCache: { at: number; value: SloFacetSummary[] } | null = null; diff --git a/pm-stack/aggregator/src/server-decision-routes.ts b/pm-stack/aggregator/src/server-decision-routes.ts new file mode 100644 index 000000000..220b6fe6e --- /dev/null +++ b/pm-stack/aggregator/src/server-decision-routes.ts @@ -0,0 +1,457 @@ +// Needs-Drew answer + decision-set routes (#8568/#8766/#9335): the +// token-authorized submit/defer/request-info/drafts APIs and the +// decision-set pages' dispatch. Each handler returns null when its +// routes do not match. Split out of server.ts (#13052). +import { decodePathSegment } from "./path-segment.ts"; +import { getNeedsDrew, needsDrewIncidentKey, recordAnswer } from "./needs-drew.ts"; +import { decisionSetOpenState, deferWithSubmissions, getDecisionDrafts, getDecisionSet, isDeferLean, isDecisionSetView, listDecisionSets, raiseDecisionSet, refreshDecisionSet, recordResolutions, requestInfoOpenQuestions, upsertDecisionDrafts, validateDecisionDraftUpsert, validateDecisionSet, withGeneratedSetId, type DecisionSet, type DecisionSetView, type DecisionSubmission } from "./decisions.ts"; +import { appendDecisionEvents, readDecisionEvents, validateDecisionEventInput, type DecisionEventInput } from "./decision-events.ts"; +import { getAlertsStore, requestAlertTick } from "./alerts.ts"; +import { readJsonBody } from "./request-body.ts"; +import { cfg, source } from "./server-wiring.ts"; +import { json, html } from "./server-respond.ts"; +import { renderAnswerPage, renderAnswerForbidden, decisionsPageUrl, logDecisionEvents, questionRefFor, eventTypeForKind, submissionEventPayload, parseDecisionSubmissions, renderDecisionsPage, renderDecisionsIndex, renderDecisionsForbidden } from "./server-pages.ts"; +import { alertsIntakeAuthorized } from "./server-alert-routes.ts"; + +export async function handleDecisionRoutes(req: Request, url: URL, path: string): Promise { + // --- Needs-Drew answers (#8568) -------------------------------------- + const needsDrewAnswerMatch = /^\/api\/needs-drew\/([^/]+)\/answer$/.exec(path); + if (req.method === "POST" && needsDrewAnswerMatch) { + const ledgerId = decodePathSegment(needsDrewAnswerMatch[1]); + if (ledgerId === null) return json({ error: "bad ledgerId" }, 400); + let body: { token?: unknown; optionId?: unknown; freeText?: unknown }; + try { + body = (await readJsonBody(req)) as typeof body; + } catch { + return json({ error: "invalid answer body" }, 400); + } + // No bearer: the per-question token is the authority. + const item = await getNeedsDrew(cfg.needsDrewFile, ledgerId).catch(() => null); + if (!item || typeof body.token !== "string" || body.token !== item.token) { + return json({ error: "unknown question or bad token" }, 403); + } + const optionId = typeof body.optionId === "string" ? body.optionId : undefined; + if (optionId !== undefined && !item.options.some((o) => o.id === optionId)) { + return json({ error: "optionId is not one of the question options" }, 400); + } + const freeText = typeof body.freeText === "string" ? body.freeText : undefined; + if (body.freeText !== undefined && freeText === undefined) { + return json({ error: "freeText must be a string" }, 400); + } + if (optionId === undefined && !freeText?.trim()) { + return json({ error: "optionId or freeText required" }, 400); + } + const updated = await recordAnswer(cfg.needsDrewFile, ledgerId, { + ...(optionId !== undefined ? { optionId } : {}), + ...(freeText !== undefined ? { freeText } : {}), + via: "api", + }); + if (!updated?.answer) return json({ error: "answer not recorded" }, 500); + // #8605: the answer resolves the question, so close its alert + // incident — the raiser posted it under this question's source with + // key needs-drew:, and until now nothing ever closed it. + // Best-effort, like the stack-health close in the intake above: a + // store failure is logged and never fails the recorded answer. + try { + const store = await getAlertsStore(); + if (store) { + await store.closeOpenIncidentByKey(item.source, needsDrewIncidentKey(ledgerId)); + requestAlertTick(); + } + } catch (err) { + console.error(`needs-drew answer: incident close failed (${err instanceof Error ? err.message : "error"})`); + } + return json({ + ledgerId, + answered: true, + answer: { + ...(updated.answer.optionId !== undefined ? { optionId: updated.answer.optionId } : {}), + ...(updated.answer.freeText !== undefined ? { freeText: updated.answer.freeText } : {}), + at: updated.answer.at, + via: updated.answer.via, + }, + }); + } + const answerPageMatch = /^\/answer\/([^/]+)$/.exec(path); + if (req.method === "GET" && answerPageMatch) { + const ledgerId = decodePathSegment(answerPageMatch[1]); + const token = url.searchParams.get("t") ?? ""; + const item = ledgerId === null ? null : await getNeedsDrew(cfg.needsDrewFile, ledgerId).catch(() => null); + // Unknown question or token mismatch: 403, and the question is + // never rendered — the token is the only authority here. + if (!item || !token || token !== item.token) return html(renderAnswerForbidden(), 403); + return html(renderAnswerPage(item)); + } + // --- Decision-set submit API + event log (#9335 v2) ----------------- + // POST /api/decision-sets (alias: /api/decision-sets/submit): the + // authenticated submit API. Intake-bearer auth, the same token as + // /api/alerts. Body: the bare v2 set object or { decisionSet: {...} } + // (a sibling `source` string is honored). setId may be omitted — a + // UUID is minted. The response returns the setId and the full token + // page URL to the authenticated submitter ONLY; the URL is never + // logged. Exactly one push per set: a fresh raise requests the alert + // tick exactly like the /api/alerts decisionSet path; a re-submit of + // an existing setId is idempotent and sends no second push. + if (req.method === "POST" && (path === "/api/decision-sets" || path === "/api/decision-sets/submit")) { + if (!(await alertsIntakeAuthorized(req))) return json({ error: "unauthorized" }, 401); + let rawBody: unknown; + try { + rawBody = await readJsonBody(req); + } catch { + return json({ error: "invalid submit body" }, 400); + } + const prepared = withGeneratedSetId(rawBody); + const ext = + prepared && typeof prepared === "object" && !Array.isArray(prepared) ? (prepared as Record) : {}; + const candidate = ext.decisionSet !== undefined ? ext.decisionSet : prepared; + const v = validateDecisionSet(candidate); + if (!v.ok) return json({ error: v.error }, 400); + const source = typeof ext.source === "string" && ext.source ? ext.source : "decisions-ledger"; + // #9354 refresh mode: a sibling `refresh: true` opts a standing + // (ledger-mirror) set into refreshDecisionSet — contents are + // replaced, token/createdAt/source and resolutions-by-qid are + // preserved. No push and no set.created event on a refresh: the + // set is not new, and a standing set refreshed hourly must not + // push hourly. Refresh of a not-yet-existing set is a normal + // create (201, created: true, push + set.created as usual). + const refresh = ext.refresh === true; + const before = await getDecisionSet(cfg.decisionsFile, v.value.setId).catch(() => null); + try { + if (refresh && before) { + const set = await refreshDecisionSet(cfg.decisionsFile, v.value, source); + // The event log accepts a set-level "edit" event without a + // questionRef (validateDecisionEventInput / the type enum + // include "edit"), so a refresh is recorded that way. + await logDecisionEvents([ + { + setId: set.setId, + type: "edit", + payload: { + via: "api/decision-sets", + refresh: true, + items: set.items.length, + questions: set.items.reduce((n, i) => n + i.questions.length, 0), + }, + }, + ]); + const pageUrl = decisionsPageUrl(set); + return json({ setId: set.setId, pageUrl, url: pageUrl, created: false, refreshed: true }, 200); + } + const set = await raiseDecisionSet(cfg.decisionsFile, v.value, source); + if (!before) { + await logDecisionEvents([ + { + setId: set.setId, + type: "set.created", + payload: { + via: "api/decision-sets", + source, + title: set.title, + items: set.items.length, + questions: set.items.reduce((n, i) => n + i.questions.length, 0), + }, + }, + ]); + requestAlertTick(); + } + const pageUrl = decisionsPageUrl(set); + return json({ setId: set.setId, pageUrl, url: pageUrl, created: !before }, before ? 200 : 201); + } catch (err) { + console.error(`decision-sets submit: raise failed (${err instanceof Error ? err.message : "error"})`); + return json({ error: "decision set raise failed" }, 500); + } + } + // Decision-set events: read (activity processor polling) + report + // (the page's draft/edit events). Two prefixes name the same routes: + // /api/decision-sets//events (the documented contract) and + // /api/decisions//events (the page's own prefix). + // Auth: the intake bearer OR the per-set token (as ?t=, as a bearer, + // or — for POST — as body.token). Nothing about the set's events is + // served without one of them. + const decisionEventsMatch = /^\/api\/(?:decision-sets|decisions)\/([^/]+)\/events$/.exec(path); + if ((req.method === "GET" || req.method === "POST") && decisionEventsMatch) { + const setId = decodePathSegment(decisionEventsMatch[1]); + if (setId === null) return json({ error: "bad setId" }, 400); + const set = await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); + if (!set) return json({ error: "unknown set" }, 404); + const bearer = (req.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim(); + const tokenOk = (t: unknown): boolean => typeof t === "string" && t.length > 0 && t === set.token; + if (req.method === "GET") { + const qToken = url.searchParams.get("t") ?? ""; + if (!tokenOk(qToken) && !tokenOk(bearer) && !(await alertsIntakeAuthorized(req))) { + return json({ error: "unknown set or bad token" }, 403); + } + const since = url.searchParams.get("since") ?? undefined; + const limitRaw = Number(url.searchParams.get("limit") ?? ""); + const page = await readDecisionEvents(cfg.decisionsEventsFile, setId, { + since, + ...(Number.isFinite(limitRaw) && limitRaw > 0 ? { limit: limitRaw } : {}), + }); + return json({ setId, events: page.events, nextCursor: page.nextCursor, count: page.count }); + } + let evBody: { token?: unknown; events?: unknown }; + try { + evBody = (await readJsonBody(req)) as typeof evBody; + } catch { + return json({ error: "invalid events body" }, 400); + } + if (!tokenOk(evBody.token) && !tokenOk(bearer) && !(await alertsIntakeAuthorized(req))) { + return json({ error: "unknown set or bad token" }, 403); + } + if (!Array.isArray(evBody.events) || evBody.events.length < 1 || evBody.events.length > 32) { + return json({ error: "events must be an array of 1-32 entries" }, 400); + } + const inputs: DecisionEventInput[] = []; + for (const rawEv of evBody.events) { + const ve = validateDecisionEventInput(rawEv); + if (!ve.ok) return json({ error: ve.error }, 400); + inputs.push({ + setId, + type: ve.value.type, + ...(ve.value.questionRef ? { questionRef: ve.value.questionRef } : {}), + payload: ve.value.payload, + }); + } + const stored = await appendDecisionEvents(cfg.decisionsEventsFile, cfg.decisionsOutboxFile, inputs).catch( + () => null, + ); + if (!stored) return json({ error: "event append failed" }, 500); + return json({ appended: stored.length, eventIds: stored.map((e) => e.eventId) }); + } + return null; +} + +export async function handleDecisionsIndex(url: URL): Promise { + const sets = await listDecisionSets(cfg.decisionsFile).catch(() => [] as DecisionSet[]); + const viewParam = url.searchParams.get("view"); + const view: DecisionSetView = isDecisionSetView(viewParam) ? viewParam : "all"; + return html(renderDecisionsIndex(sets, view, url.searchParams.get("open") === "1")); +} + +export async function handleDecisionTailRoutes(req: Request, url: URL, path: string): Promise { + const decisionsPageMatch = /^\/decisions\/([^/]+)$/.exec(path); + if (req.method === "GET" && decisionsPageMatch) { + const setId = decodePathSegment(decisionsPageMatch[1]); + const token = url.searchParams.get("t") ?? ""; + const set = setId === null ? null : await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); + // Unknown set or token mismatch: 403, and the set is never rendered + // — the per-set token is the only authority here. + if (!set || !token || token !== set.token) return html(renderDecisionsForbidden(), 403); + return html(renderDecisionsPage(set)); + } + const decisionsSubmitMatch = /^\/api\/decisions\/([^/]+)\/submit$/.exec(path); + if (req.method === "POST" && decisionsSubmitMatch) { + const setId = decodePathSegment(decisionsSubmitMatch[1]); + if (setId === null) return json({ error: "bad setId" }, 400); + let body: { token?: unknown; submissions?: unknown }; + try { + body = (await readJsonBody(req)) as typeof body; + } catch { + return json({ error: "invalid submit body" }, 400); + } + // No bearer: the per-set token is the authority. + const set = await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); + if (!set || typeof body.token !== "string" || body.token !== set.token) { + return json({ error: "unknown set or bad token" }, 403); + } + const parsedSubs = parseDecisionSubmissions(body.submissions); + if (!parsedSubs.ok) return json({ error: parsedSubs.error }, 400); + const result = await recordResolutions(cfg.decisionsFile, setId, parsedSubs.value); + if (!result) return json({ error: "unknown set" }, 404); + await logDecisionEvents( + result.outcomes + .filter((o) => o.applied) + .map((o) => { + const sub = parsedSubs.value.find((x) => x.qid === o.qid)!; + return { + setId, + type: eventTypeForKind(sub.kind), + questionRef: questionRefFor(set, sub.ledgerId, sub.qid), + payload: submissionEventPayload(sub), + } satisfies DecisionEventInput; + }), + ); + return json({ outcomes: result.outcomes, ...decisionSetOpenState(result.set) }); + } + const decisionsDeferMatch = /^\/api\/decisions\/([^/]+)\/defer$/.exec(path); + if (req.method === "POST" && decisionsDeferMatch) { + const setId = decodePathSegment(decisionsDeferMatch[1]); + if (setId === null) return json({ error: "bad setId" }, 400); + let body: { + token?: unknown; + lean?: unknown; + ledgerIds?: unknown; + allRemaining?: unknown; + submissions?: unknown; + comment?: unknown; + }; + try { + body = (await readJsonBody(req)) as typeof body; + } catch { + return json({ error: "invalid defer body" }, 400); + } + // No bearer: the per-set token is the authority. + const set = await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); + if (!set || typeof body.token !== "string" || body.token !== set.token) { + return json({ error: "unknown set or bad token" }, 403); + } + if (!isDeferLean(body.lean)) { + return json({ error: "lean must be none|skeptical|approve" }, 400); + } + const all = body.allRemaining === true; + const ledgerIds = Array.isArray(body.ledgerIds) + ? body.ledgerIds.filter((x): x is string => typeof x === "string") + : []; + if (!all && ledgerIds.length === 0) { + return json({ error: "ledgerIds or allRemaining required" }, 400); + } + // Filled answers win over the bulk defer (#8766): submissions the + // page gathered from filled-in fields are recorded FIRST, and only + // the still-unanswered questions in scope are deferred. + let submissions: DecisionSubmission[] = []; + if (body.submissions !== undefined) { + const parsedSubs = parseDecisionSubmissions(body.submissions); + if (!parsedSubs.ok) return json({ error: parsedSubs.error }, 400); + submissions = parsedSubs.value; + } + const result = await deferWithSubmissions( + cfg.decisionsFile, + setId, + submissions, + all ? { allRemaining: true as const } : { ledgerIds }, + body.lean, + typeof body.comment === "string" ? body.comment : undefined, + ); + if (!result) return json({ error: "unknown set" }, 404); + await logDecisionEvents([ + ...result.outcomes + .filter((o) => o.applied) + .map((o) => { + const sub = submissions.find((x) => x.qid === o.qid)!; + return { + setId, + type: eventTypeForKind(sub.kind), + questionRef: questionRefFor(set, sub.ledgerId, sub.qid), + payload: submissionEventPayload(sub), + } satisfies DecisionEventInput; + }), + ...(result.deferredCount > 0 + ? [ + { + setId, + type: "defer" as const, + payload: { + bulk: true, + deferredCount: result.deferredCount, + lean: body.lean as string, + scope: all ? "allRemaining" : "checked", + }, + } satisfies DecisionEventInput, + ] + : []), + ]); + return json({ + outcomes: result.outcomes, + deferredCount: result.deferredCount, + ...decisionSetOpenState(result.set), + }); + } + const decisionsReqInfoMatch = /^\/api\/decisions\/([^/]+)\/request-info$/.exec(path); + if (req.method === "POST" && decisionsReqInfoMatch) { + const setId = decodePathSegment(decisionsReqInfoMatch[1]); + if (setId === null) return json({ error: "bad setId" }, 400); + let body: { token?: unknown; note?: unknown; ledgerIds?: unknown; allRemaining?: unknown }; + try { + body = (await readJsonBody(req)) as typeof body; + } catch { + return json({ error: "invalid request-info body" }, 400); + } + // No bearer: the per-set token is the authority. + const set = await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); + if (!set || typeof body.token !== "string" || body.token !== set.token) { + return json({ error: "unknown set or bad token" }, 403); + } + const all = body.allRemaining === true; + const ledgerIds = Array.isArray(body.ledgerIds) + ? body.ledgerIds.filter((x): x is string => typeof x === "string") + : []; + if (!all && ledgerIds.length === 0) { + return json({ error: "ledgerIds or allRemaining required" }, 400); + } + const result = await requestInfoOpenQuestions( + cfg.decisionsFile, + setId, + all ? { allRemaining: true as const } : { ledgerIds }, + typeof body.note === "string" ? body.note : undefined, + ); + if (!result) return json({ error: "unknown set" }, 404); + if (result.requestedCount > 0) { + await logDecisionEvents([ + { + setId, + type: "request-info", + payload: { + bulk: true, + requestedCount: result.requestedCount, + scope: all ? "allRemaining" : "checked", + ...(typeof body.note === "string" && body.note ? { note: body.note.slice(0, 2000) } : {}), + }, + }, + ]); + } + return json({ requestedCount: result.requestedCount, ...decisionSetOpenState(result.set) }); + } + + const decisionsDraftsMatch = /^\/api\/decisions\/([^/]+)\/drafts$/.exec(path); + if ((req.method === "GET" || req.method === "POST") && decisionsDraftsMatch) { + const setId = decodePathSegment(decisionsDraftsMatch[1]); + if (setId === null) return json({ error: "bad setId" }, 400); + const set = await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); + if (req.method === "GET") { + const token = url.searchParams.get("t") ?? ""; + // Unknown set or token mismatch: 403, nothing about the set's + // drafts is shown without the correct link. + if (!set || !token || token !== set.token) { + return json({ error: "unknown set or bad token" }, 403); + } + const drafts = await getDecisionDrafts(cfg.decisionsFile, setId).catch(() => null); + return json({ + drafts: drafts ?? { questions: {}, bulk: [], bulkLean: "", bulkNote: "", updatedAt: "" }, + }); + } + let body: { token?: unknown; drafts?: unknown }; + try { + body = (await readJsonBody(req)) as typeof body; + } catch { + return json({ error: "invalid drafts body" }, 400); + } + // No bearer: the per-set token is the authority. + if (!set || typeof body.token !== "string" || body.token !== set.token) { + return json({ error: "unknown set or bad token" }, 403); + } + const parsedDrafts = validateDecisionDraftUpsert(body.drafts); + if (!parsedDrafts.ok) return json({ error: parsedDrafts.error }, 400); + const result = await upsertDecisionDrafts(cfg.decisionsFile, setId, parsedDrafts.value); + if (!result) return json({ error: "unknown set" }, 404); + await logDecisionEvents( + result.applied.map((qid) => { + const entry = result.drafts.questions[qid]; + const ledgerId = qid.slice(0, qid.lastIndexOf("#")) || qid; + return { + setId, + type: "draft" as const, + questionRef: questionRefFor(set, ledgerId, qid), + payload: { + ...(entry?.opt ? { opt: entry.opt } : {}), + ...(entry?.opts ? { opts: entry.opts } : {}), + ...(entry?.ft ? { freeText: entry.ft.slice(0, 2000) } : {}), + ...(entry?.lean ? { lean: entry.lean } : {}), + ...(entry?.note ? { note: entry.note.slice(0, 2000) } : {}), + }, + } satisfies DecisionEventInput; + }), + ); + return json({ drafts: result.drafts, applied: result.applied, skipped: result.skipped }); + } + return null; +} diff --git a/pm-stack/aggregator/src/server-pages.ts b/pm-stack/aggregator/src/server-pages.ts new file mode 100644 index 000000000..da32204c0 --- /dev/null +++ b/pm-stack/aggregator/src/server-pages.ts @@ -0,0 +1,716 @@ +// Standalone token-carrying pages rendered outside the dashboard +// shell: the Needs-Drew answer page (#8568) and the decision-set +// pages (#8766), plus the PWA manifest. Split out of server.ts (#13052). +import { type NeedsDrewQuestion } from "./needs-drew.ts"; +import { decisionSetProgress, isDeferLean, decisionSetSummary, decisionSetsForView, listDecisionSets, effectiveQuestionMode, type DecisionItem, type DecisionSet, type DecisionSetView, type DecisionSubmission, decisionsDraftScript } from "./decisions.ts"; +import { appendDecisionEvents, type DecisionEventInput } from "./decision-events.ts"; +import type { Comment } from "./model.ts"; +import { questionsSectionHtml } from "./render.ts"; +import { esc } from "./render.ts"; +import { cfg } from "./server-wiring.ts"; +import { json, html } from "./server-respond.ts"; + +// --- Needs-Drew questions (#8568) ------------------------------------------ + +/** The token-carrying answer-page URL for a raised question. */ +export function needsDrewAnswerUrl(item: NeedsDrewQuestion): string { + return `${cfg.publicOrigin}/answer/${encodeURIComponent(item.ledgerId)}?t=${item.token}`; +} + +export const ANSWER_PAGE_STYLE = ``; + +/** Render GET /answer/. The caller has already verified the + * token; the 403 shape renders nothing about the question. */ +export function renderAnswerPage(item: NeedsDrewQuestion): string { + const links = item.links + .filter((l) => /^https?:\/\//.test(l)) + .map((l) => `${esc(l)}`) + .join(""); + if (item.answer) { + const chosen = item.answer.optionId + ? (item.options.find((o) => o.id === item.answer?.optionId)?.label ?? item.answer.optionId) + : null; + return ` +Answered — PM Stack${ANSWER_PAGE_STYLE} +

${esc(item.question)}

+

Answered${chosen ? `: ${esc(chosen)}` : ""}.

+${item.answer.freeText ? `

${esc(item.answer.freeText)}

` : ""} +

Recorded at ${esc(item.answer.at)} — the fleet worker has been unblocked.

+
`; + } + const buttons = item.options + .map((o) => ``) + .join(""); + return ` +Needs Drew — PM Stack${ANSWER_PAGE_STYLE} +

${esc(item.question)}

+${item.context ? `

${esc(item.context)}

` : ""} +${links ? `` : ""} +
${buttons}
+ + +

+ +
`; +} + +export function renderAnswerForbidden(): string { + return ` +Not available — PM Stack${ANSWER_PAGE_STYLE} +

Answer link not available

+

This answer link is unknown or its token does not match. Nothing about the question is shown without the correct link.

+
`; +} + +// --- Decision sets (#8766) ------------------------------------------------- + +/** The token-carrying decisions-page URL for a raised set. */ +export function decisionsPageUrl(set: DecisionSet): string { + return `${cfg.publicOrigin}/decisions/${encodeURIComponent(set.setId)}?t=${set.token}`; +} + +/** + * The live Questions section for Today / Needs-you (#9354): reads the + * decision-set store at request time, keeps sets with open questions, + * newest first. A store read failure renders the honest unavailable + * section (questionsSectionHtml(null, ...)), never a confident zero. + * (listDecisionSets itself reads an absent/corrupt store as empty, + * following the store's existing contract.) + */ +export async function questionsHtml(): Promise { + try { + const sets = await listDecisionSets(cfg.decisionsFile); + const byId = new Map(sets.map((s) => [s.setId, s])); + const summaries = sets + .map((s) => decisionSetSummary(s)) + .filter((s) => s.openQuestions > 0) + .sort((a, b) => b.createdAt.localeCompare(a.createdAt)); + return questionsSectionHtml(summaries, (s) => { + const set = byId.get(s.setId); + return set ? decisionsPageUrl(set) : `/decisions/${encodeURIComponent(s.setId)}`; + }); + } catch { + return questionsSectionHtml(null, () => "/decisions"); + } +} + +/** Append decision-set events (#9335 v2): best-effort — an event-log + * failure is logged and never fails the interaction it records. */ +export async function logDecisionEvents(inputs: DecisionEventInput[]): Promise { + if (!inputs.length) return; + try { + await appendDecisionEvents(cfg.decisionsEventsFile, cfg.decisionsOutboxFile, inputs); + } catch (err) { + console.error(`decision events: append failed (${err instanceof Error ? err.message : "error"})`); + } +} + +export function questionRefFor( + set: DecisionSet, + ledgerId: string, + qid: string, +): { ledgerId: string; qid: string; questionIndex?: number } { + const item = set.items.find((i) => i.ledgerId === ledgerId); + const idx = item ? item.questions.findIndex((q) => q.qid === qid) : -1; + return { ledgerId, qid, ...(idx >= 0 ? { questionIndex: idx + 1 } : {}) }; +} + +export function eventTypeForKind(kind: DecisionSubmission["kind"]): "submit" | "defer" | "request-info" { + return kind === "answered" ? "submit" : kind === "deferred" ? "defer" : "request-info"; +} + +export function submissionEventPayload(sub: DecisionSubmission): Record { + return { + kind: sub.kind, + ...(sub.optionId ? { optionId: sub.optionId } : {}), + ...(sub.optionIds ? { optionIds: sub.optionIds } : {}), + ...(sub.freeText ? { freeText: sub.freeText.slice(0, 2000) } : {}), + ...(sub.customAnswer ? { customAnswer: sub.customAnswer.slice(0, 2000) } : {}), + ...(sub.lean ? { lean: sub.lean } : {}), + ...(sub.note ? { note: sub.note.slice(0, 2000) } : {}), + ...(sub.comment ? { comment: sub.comment.slice(0, 2000) } : {}), + }; +} + +/** Parse a decisions submissions array — shared by /submit and by + * /defer's filled-answers-win payload (#8766). */ +export function parseDecisionSubmissions( + raw: unknown, +): { ok: true; value: DecisionSubmission[] } | { ok: false; error: string } { + if (!Array.isArray(raw) || raw.length < 1 || raw.length > 256) { + return { ok: false, error: "submissions must be an array of 1-256 entries" }; + } + const submissions: DecisionSubmission[] = []; + for (const entry of raw) { + if (!entry || typeof entry !== "object" || Array.isArray(entry)) { + return { ok: false, error: "submissions entries must be objects" }; + } + const s = entry as Record; + const ledgerId = typeof s.ledgerId === "string" ? s.ledgerId : ""; + const qid = typeof s.qid === "string" ? s.qid : ""; + const kind = s.kind; + if (!ledgerId || !qid || (kind !== "answered" && kind !== "deferred" && kind !== "request-info")) { + return { ok: false, error: "submissions entries require ledgerId, qid and kind answered|deferred|request-info" }; + } + if (kind === "deferred" && !isDeferLean(s.lean)) { + return { ok: false, error: "deferred submissions require a lean of none|skeptical|approve" }; + } + submissions.push({ + ledgerId, + qid, + kind, + ...(typeof s.optionId === "string" ? { optionId: s.optionId } : {}), + ...(Array.isArray(s.optionIds) + ? { optionIds: s.optionIds.filter((x): x is string => typeof x === "string") } + : {}), + ...(typeof s.freeText === "string" ? { freeText: s.freeText } : {}), + ...(typeof s.customAnswer === "string" ? { customAnswer: s.customAnswer } : {}), + ...(isDeferLean(s.lean) ? { lean: s.lean } : {}), + ...(typeof s.note === "string" ? { note: s.note } : {}), + ...(typeof s.comment === "string" ? { comment: s.comment } : {}), + }); + } + return { ok: true, value: submissions }; +} + +export const DECISIONS_PAGE_STYLE = `${ANSWER_PAGE_STYLE}`; + +/** Render GET /decisions/. The caller has already verified the + * token; the 403 shape renders nothing about the set. Only open + * questions are interactive; resolved ones show as a compact recorded + * line. An item whose questions are all resolved renders as a + * submitted card, hidden by default (Drew, 2026-11-13): the page's + * "Show submitted items" toggle brings it back for review, since the + * page has no undo. */ +export function renderDecisionsPage(set: DecisionSet): string { + const progress = decisionSetProgress(set); + const groups: string[] = []; + for (const item of set.items) if (!groups.includes(item.group)) groups.push(item.group); + const itemCard = (item: DecisionItem): string => { + const open = item.questions.filter((q) => !q.resolution); + const links = item.links + .filter((l) => /^https?:\/\//.test(l)) + .map((l) => `${esc(l)}`) + .join(""); + const resolvedLines = item.questions + .filter((q) => q.resolution) + .map((q) => { + const r = q.resolution!; + const what = + r.kind === "deferred" + ? `deferred to the orchestrator${r.lean && r.lean !== "none" ? ` (lean: ${esc(r.lean)})` : ""}${r.optionLabel ? ` — your tentative pick: ${esc(r.optionLabel)}` : ""}${r.comment ? ` — comment: ${esc(r.comment)}` : ""}` + : r.kind === "request-info" + ? `more information requested${r.note ? ` — you said: ${esc(r.note)}` : ""}` + : `answered${ + r.optionLabels && r.optionLabels.length > 1 + ? `: ${esc(r.optionLabels.join(" + "))}` + : r.optionLabel + ? `: ${esc(r.optionLabel)}` + : r.freeText + ? `: ${esc(r.freeText)}` + : "" + }${r.customAnswer ? ` — own answer: ${esc(r.customAnswer)}` : ""}`; + return `
✓ ${esc(q.question)} — ${what}
`; + }) + .join(""); + if (open.length === 0) { + return ``; + } + const sortedOpen = open + .map((q, i) => ({ q, i })) + .sort((a, b) => (a.q.order ?? a.i) - (b.q.order ?? b.i)) + .map((x) => x.q); + const questionBlocks = sortedOpen + .map((q) => { + const mode = effectiveQuestionMode(q); + const recommended = q.recommendedOptionIds ?? []; + const chips = (tags?: string[]): string => + (tags ?? []).map((t) => `${esc(t)}`).join(""); + const inputs = q.options + .map((o) => { + const combo = + o.combinationOf && o.combinationOf.length + ? ` combines ${o.combinationOf + .map((cid) => esc(q.options.find((x) => x.id === cid)?.label ?? cid)) + .join(" + ")}` + : ""; + const isReco = recommended.includes(o.id); + return ``; + }) + .join(""); + return `
+

${esc(q.question)}${chips(q.tags)}

+${q.description ? `
${esc(q.description)}
` : ""} +${q.infoProvided ? `

Information you requested

${esc(q.infoProvided)}

` : ""} +${q.context ? `

${esc(q.context)}

` : ""} +${recommended.length ? `

Recommended default preselected — it is not recorded until you submit.

` : ""} +${inputs} + + + + +
`; + }) + .join(""); + const submitBtn = (cls: string): string => + ``; + return `
+ +

${esc(item.title)}

+${links ? `` : ""} +${resolvedLines} +${open.length > 1 ? submitBtn("submit top") : ""} +${questionBlocks} +${submitBtn("submit")} +
`; + }; + const isSubmittedItem = (i: DecisionItem): boolean => i.questions.every((q) => q.resolution); + const submittedCount = set.items.filter(isSubmittedItem).length; + const body = groups + .map((g) => { + const groupItems = set.items + .filter((i) => i.group === g) + .map((item, i) => ({ item, i })) + .sort((a, b) => (a.item.order ?? a.i) - (b.item.order ?? b.i)) + .map((x) => x.item); + const cards = groupItems.map(itemCard).join(""); + const allSubmitted = groupItems.length > 0 && groupItems.every(isSubmittedItem); + return cards ? `
${esc(g)}
${cards}` : ""; + }) + .join(""); + const caughtUp = progress.openQuestions === 0; + return ` +Decisions — PM Stack${DECISIONS_PAGE_STYLE} +

${esc(set.title)}

+

${progress.openQuestions} question${progress.openQuestions === 1 ? "" : "s"} open across ${progress.openItems} item${progress.openItems === 1 ? "" : "s"} · ${progress.answered} answered · ${progress.deferred} deferred · ${progress.infoRequested} sent back for more information so far. Fill in what you want — you can submit a partially-filled item; what you filled in is recorded and the rest stays here.

+${caughtUp ? `

All caught up — every question in this set has been answered or sent back. Nothing left on this page.

` : ""} + +${body} +
+

Bulk actions

+ + +

Submit defaults records the raiser's recommended preselection for every open question that has one (plus any "my own answer" text you typed on those questions). Preselected defaults are shown selected, but they are NOT an answer until you submit them.

+

Defer checked items to the orchestrator instead of answering — they leave this page and become the orchestrator's job. Precedence per question: (1) the question's own defer setting wins, with its tentative pick and comment riding along as guidance; (2) a filled-in answer submits as an answer; (3) only a question nobody touched uses the default flavor picked here:

+ + + +

Or request more information for the checked items — they leave this page and come back in a later set once the information has been gathered:

+ + +
+

+ +
`; +} + +/** Render GET /decisions — the decision-sets index (#8867). Lists every + * set in the store with counts live from decisionSetSummary (the same + * numbers the set page itself reports), in today / this-week / all + * views with an open-only toggle, newest first. Each row links to the + * set's own token-carrying page; the index carries no token of its own + * and sits behind the same access as every other aggregator page + * (tailnet origin / Cloudflare Access on pm.security.cab) — no new + * public surface, and the per-set token model is untouched. */ +export const CHICAGO_STAMP = new Intl.DateTimeFormat("en-US", { + timeZone: "America/Chicago", + year: "numeric", + month: "short", + day: "numeric", + hour: "numeric", + minute: "2-digit", + timeZoneName: "short", +}); + +export function renderDecisionsIndex(allSets: DecisionSet[], view: DecisionSetView, openOnly: boolean): string { + const inView = decisionSetsForView(allSets, view); + const visible = openOnly ? inView.filter((s) => decisionSetSummary(s).openQuestions > 0) : inView; + const totalOpen = inView.reduce((n, s) => n + decisionSetSummary(s).openQuestions, 0); + const viewTab = (v: DecisionSetView, label: string): string => + v === view + ? `${label}` + : `${label}`; + const toggle = openOnly + ? `Open only · Show all` + : `Open only`; + const rows = visible + .map((set) => { + const s = decisionSetSummary(set); + const stamp = Number.isFinite(Date.parse(s.createdAt)) + ? CHICAGO_STAMP.format(new Date(s.createdAt)) + : s.createdAt; + const breakdown = `${s.answered} answered · ${s.deferred} deferred · ${s.infoRequested} sent back for more info`; + const state = s.fullyResolved ? `all settled — ${breakdown}` : `${s.openQuestions} open · ${breakdown}`; + return `

${esc(s.title)}

+

Raised ${esc(stamp)} · ${s.items} item${s.items === 1 ? "" : "s"} · ${s.questions} question${s.questions === 1 ? "" : "s"} · ${state}

+

Set ${esc(s.setId)}

`; + }) + .join(""); + const empty = + allSets.length === 0 + ? `

No decision sets have been raised yet.

` + : `

No sets in this view${openOnly ? " with open questions" : ""}.

`; + return ` +Decision sets — PM Stack${DECISIONS_PAGE_STYLE} +

Decision sets

+

${inView.length} set${inView.length === 1 ? "" : "s"} · ${totalOpen} question${totalOpen === 1 ? "" : "s"} open. Newest first. Each set opens its own page — the same link its push notification carried.

+

${viewTab("today", "New today")} · ${viewTab("week", "This week")} · ${viewTab("all", "All")}  |  ${toggle}

+${visible.length ? rows : empty} +
`; +} + +export function renderDecisionsForbidden(): string { + return ` +Not available — PM Stack${ANSWER_PAGE_STYLE} +

Decisions link not available

+

This decisions link is unknown or its token does not match. Nothing about the set is shown without the correct link.

+
`; +} + +/** The PWA manifest (#3315 slice a, landed with #3676): start_url is + * the attention view per the design; icons incl. maskable + iOS. */ +export const PWA_MANIFEST = { + name: "PM Aggregator", + short_name: "PM Stack", + description: "The PM-stack aggregator: needs-you queues, quotas, health \u2014 and the alert throat.", + start_url: "/attention", + scope: "/", + display: "standalone", + background_color: "#0e1117", + theme_color: "#161b22", + icons: [ + { src: "/icons/icon-192.png", sizes: "192x192", type: "image/png", purpose: "any" }, + { src: "/icons/icon-512.png", sizes: "512x512", type: "image/png", purpose: "any" }, + { src: "/icons/icon-maskable-512.png", sizes: "512x512", type: "image/png", purpose: "maskable" }, + ], +}; + diff --git a/pm-stack/aggregator/src/server-respond.ts b/pm-stack/aggregator/src/server-respond.ts new file mode 100644 index 000000000..8c7d7f5e8 --- /dev/null +++ b/pm-stack/aggregator/src/server-respond.ts @@ -0,0 +1,34 @@ +// The server's Response constructors. Split out of server.ts (#13052). +import { SW_SOURCE } from "./sw-source.ts"; + +export function json(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body, null, 2), { + status, + headers: { "content-type": "application/json; charset=utf-8" }, + }); +} + +/** Same response shape as {@link json} without the 2-space pretty-print: + * the board JSON legitimately carries seconds of data and the pretty + * form adds ~10% bytes for nothing a machine consumer reads (#5082). */ +export function jsonCompact(body: unknown, status = 200): Response { + return new Response(JSON.stringify(body), { + status, + headers: { "content-type": "application/json; charset=utf-8" }, + }); +} + +export function html(body: string, status = 200): Response { + return new Response(body, { status, headers: { "content-type": "text/html; charset=utf-8" } }); +} + +// The real service worker (#3676 — design 2026-11-01T03-54-00Z §6 +// step 2): push + notificationclick handlers, with the kill switch's +// eviction job carried forward per the §6 fallback (cache purge on +// activate in the worker; foreign-registration unregister in the +// page-side probe script). Worker source + history: src/sw-source.ts. +export function serviceWorkerResponse(): Response { + return new Response(SW_SOURCE, { + headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "no-cache" }, + }); +} diff --git a/pm-stack/aggregator/src/server-wiring.ts b/pm-stack/aggregator/src/server-wiring.ts new file mode 100644 index 000000000..1a5f67e4d --- /dev/null +++ b/pm-stack/aggregator/src/server-wiring.ts @@ -0,0 +1,412 @@ +// Server wiring: config, stores, source selection, consumers and the +// source-side sinks. Split out of server.ts (#13052) — the stores and +// the Source are process-wide singletons created once at import. +import { createQuotaRefresher, systemdTrigger } from "./quota-refresh.ts"; +import { ActionsStore } from "./actions.ts"; +import { effectiveStandingAuto } from "./tier-items.ts"; +import { CommentsStore } from "./comments.ts"; +import { PromptsStore } from "./prompts.ts"; +import { ViewsStore } from "./views.ts"; +import { EventsStore, emitEvent } from "./events.ts"; +import { FreshnessStore, type FreshnessInput } from "./freshness.ts"; +import { fleetFeedRevisionReader, FreshnessReconciler } from "./freshness-reconcile.ts"; +import { IngestionStore, WatchdogEpisodeStabilizer, ingestActivity, type ActivitySourceStatus } from "./activity.ts"; +import { GithubHotListConsumer, unconfiguredGithubStatus } from "./github-hot-list.ts"; +import { FileOutcomeBindingSource, GithubOutcomeConsumer } from "./outcome-consumer.ts"; +import { OutcomeFactStore } from "./outcome-attribution.ts"; +import { RoadmapAnnotationsStore } from "./roadmap-annotations.ts"; +import { IdentityRegistryStore } from "./identity-registry.ts"; +import { BreakGlassTokenStore } from "./break-glass.ts"; +import { computeCoverage, CoverageSnapshotStore, nextCoverageSnapshot, type CoverageSnapshotFile, type RepoCensus } from "./coverage.ts"; +import { loadConfig } from "./config.ts"; +import { getTursoStoreClient } from "./turso-stores.ts"; +import { createTursoRemotes } from "./remote-stores.ts"; +import { conflictInbox, type ConflictInbox } from "./conflicts.ts"; +import { watchdogTierItems } from "./watchdog.ts"; +import { buildAttention } from "./derive.ts"; +import type { Comment, GhItem, ProjectPoolItem, QuotaView, RefKey, UsageView } from "./model.ts"; +import { SpendRollupStore } from "./spend-rollups.ts"; +import { buildSpendCards, type SpendCardsView } from "./spend-cards.ts"; +import { identitiesFromRecords, type AuthorIdentity } from "./registry.ts"; +import { type CommentFormOpts } from "./render.ts"; +import type { Source } from "./source.ts"; +import { fixtureSource } from "./sources/fixtures.ts"; +import { liveSource } from "./sources/live.ts"; +import { createDashboardResponseDeadline } from "./assembly-deadline.ts"; +import { dispatchStateFor, fetchRfaState, RFA_NOT_PICKED_UP } from "./sources/ready-for-agent.ts"; +import { TodayCache, TODAY_CACHE_TTL_MS } from "./today-cache.ts"; +import { ItemHistoryStore } from "./item-history.ts"; +import { SloJournal } from "./slo-journal.ts"; +import { fireOpenCodeWorkingHook } from "./health-hook-fire.ts"; +import { defaultReportRecordsFile } from "./report-records.ts"; + +// Cap `t` at `max` UTF-16 code units, but never leave half of a surrogate +// pair at the cut (#7740, mirroring the #7694-family capUnits guard): an +// astral character straddling the cap is dropped whole, so a persisted +// event field can never end in a lone high surrogate. +export function capUnits(t: string, max: number): string { + if (t.length <= max) return t; + let end = max; + const before = t.charCodeAt(end - 1); + const after = t.charCodeAt(end); + if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) end--; + return t.slice(0, end); +} + +export const cfg = loadConfig(); +// #10383: the bounded routes' last-good survives a restart on disk, so +// the first request after a deploy serves it instead of a 503. +export const dashboardResponseWithinDeadline = createDashboardResponseDeadline({ persistDir: cfg.lastGoodDir }); +export const promptsStore = new PromptsStore(cfg.promptsFile); +export const roadmapAnnotationsStore = new RoadmapAnnotationsStore(cfg.roadmapAnnotationsFile); +export const coverageStore = new CoverageSnapshotStore(cfg.coverageSnapshotFile); +export const itemHistoryStore = new ItemHistoryStore(cfg.itemHistoryFile); +export const sloJournal = new SloJournal(cfg.sloJournalFile); +export const spendRollupStore = new SpendRollupStore(cfg.snapshotsDir); +/** #4824: the Projects/Roadmap spend-beside-progress view over the + * #4823 rollup store. A failed read renders no spend block (the + * store's absence is already the honest state — ingestion is a + * separate slice); it never fabricates zeroed cards. */ +export const loadSpendCards = async (): Promise => { + try { + return buildSpendCards(await spendRollupStore.readAll()); + } catch { + return null; + } +}; + +export async function readyAgentDispatchStates(items: Map) { + const targets = [...items.values()].filter( + (item) => item.labels.some((label) => label.toLowerCase() === "ready-for-agent") && /#\d+$/.test(item.ref), + ); + if (!targets.length) return []; + const observedAt = new Date().toISOString(); + if (cfg.source !== "live") { + // #4969 (Codex on PR #5283): fixtures mode must never read the live + // harness — deterministic fixture dispatch data, mirroring the + // health.ts fixtures boundary. The canned set has no picked-up + // work item, so every labelled fixture item is honestly + // "not picked up". + return targets.map((item) => ({ + ref: item.ref, + state: RFA_NOT_PICKED_UP, + provenance: { source: "ready-for-agent", observedAt, repository: item.ref.split("#")[0], mode: "fixtures" }, + })); + } + try { + const state = await fetchRfaState(cfg.readyForAgent.baseUrl); + return targets + .map((item) => { + const match = /^(.*)#(\d+)$/.exec(item.ref); + if (!match) return null; + return { + ref: item.ref, + state: dispatchStateFor(state, match[1], Number(match[2])) || RFA_NOT_PICKED_UP, + provenance: { source: "ready-for-agent", observedAt, repository: match[1] }, + }; + }) + .filter((entry): entry is NonNullable => entry !== null); + } catch { + return targets.map((item) => ({ + ref: item.ref, + state: "unavailable", + provenance: { + source: "ready-for-agent", + observedAt, + repository: item.ref.split("#")[0], + error: "harness read failed", + }, + })); + } +} + +/** #1220: the coverage snapshot behind the /projects panel — computed + * from the feed's items + the Project pool, rotated weekly by + * nextCoverageSnapshot, persisted only when it actually changes. */ +export async function coverageSnapshot( + census: RepoCensus[] | null, + pool: ProjectPoolItem[], + poolAvailable: boolean, +): Promise { + const stored = await coverageStore.read(); + const next = nextCoverageSnapshot(stored, computeCoverage(census, poolAvailable ? pool : null)); + const strip = (s: CoverageSnapshotFile | null): string => + s + ? JSON.stringify({ + baseline: s.baseline, + weekly: s.weekly ?? null, + anchorAt: s.anchorAt ?? "", + current: { ...s.current, generatedAt: "" }, + }) + : ""; + if (strip(next) !== strip(stored)) { + await coverageStore.write(next).catch(() => {}); + } + return next; +} +// #6815: the four formerly laptop-local stores (actions, activity +// ingestion, usage snapshots, aa-last-good) live in Turso when +// PM_AGG_STORE_BACKEND=turso. Exactly one backend is active: with +// "file" (the default) no remote exists and no database call is made. +export const storeRemotes = cfg.storeBackend === "turso" ? createTursoRemotes(getTursoStoreClient) : null; +export const actionsStore = new ActionsStore(cfg.actionsFile, undefined, storeRemotes?.actions); +// #1744 (Move 1, step 2): dashboard comments join the same switch — +// canonical in public.shared_comments under the turso backend. +export const commentsStore = new CommentsStore(cfg.commentsFile, undefined, storeRemotes?.comments); +export const viewsStore = new ViewsStore(cfg.viewsFile); +export const eventsStore = new EventsStore(cfg.eventsFile); +export const reportRecordsLocation = storeRemotes?.aaLastGood ?? defaultReportRecordsFile(); +export const identityRegistryStore = new IdentityRegistryStore(cfg.identityRegistryFile); +export const breakGlassTokenStore = new BreakGlassTokenStore(cfg.breakGlassFile); +export const freshnessStore = new FreshnessStore(cfg.freshnessFile); + +/** #3976: the 5-minute anti-entropy reconciler over the freshness + * journal. Its one wired canonical reader is the fleet feed — the + * aggregator's own canonical source, fingerprinted exactly as the + * collector's notice identity (generatedAt + sha256 of the file). + * Its health view feeds /health + /api/health via healthContext. */ +export const freshnessReconciler = new FreshnessReconciler(freshnessStore, [fleetFeedRevisionReader(cfg.feedFile)]); +export const activityStore = new IngestionStore(cfg.activityFile, storeRemotes?.activity); +export const githubHotListConsumer = + cfg.source === "live" && cfg.projector.baseUrl && cfg.projector.apiToken + ? new GithubHotListConsumer({ + baseUrl: cfg.projector.baseUrl, + token: cfg.projector.apiToken, + store: activityStore, + events: eventsStore, + }) + : null; + +/** #10910: the outcome consumer rides the same sweep as the hot-list + * consumer, under its own projector checkpoint: it projects each fixed + * high-water into the append-only outcome-fact ledger, joining events + * to jobs/sessions/models only through the binding records. */ +export const githubOutcomeConsumer = + cfg.source === "live" && cfg.projector.baseUrl && cfg.projector.apiToken + ? new GithubOutcomeConsumer({ + baseUrl: cfg.projector.baseUrl, + token: cfg.projector.apiToken, + store: new OutcomeFactStore(cfg.outcomeFile), + bindings: new FileOutcomeBindingSource(cfg.outcomeBindingsFile), + }) + : null; + +export async function githubActivityStatus(): Promise { + return ( + (await activityStore.sourceStatuses()).find((status) => status.source === "github") ?? unconfiguredGithubStatus() + ); +} + +export function activitySourceStatusHtml(status: ActivitySourceStatus): string { + const cursorDistance = + status.checkpointCursor !== null && status.highWater !== null + ? Math.max(0, status.highWater - status.checkpointCursor) + : null; + const cursorText = status.cursor === null ? "not checkpointed" : String(status.cursor); + const checkpointText = status.checkpointCursor === null ? "not checkpointed" : String(status.checkpointCursor); + const highWaterText = status.highWater === null ? "unknown" : String(status.highWater); + const lagText = cursorDistance === null ? "unknown" : String(cursorDistance); + const escapeHtml = (value: string) => + value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); + const error = status.error ? `; detail: ${escapeHtml(status.error)}` : ""; + return ( + `

GitHub hot-list consumer: ${status.state}; processed cursor ${cursorText}; ` + + `acknowledged cursor ${checkpointText}; high-water ${highWaterText}; unacknowledged cursor distance ${lagText}; ` + + `last successful sweep ${escapeHtml(status.lastSuccessAt ?? "never")}${error}. ` + + `Current means caught up to the hot-list high-water, not complete GitHub history.

` + ); +} + +/** #1739: the event log's fire-and-forget sink for source-side + * writers (orchestration publishes, registry merges). Never awaited, + * never throws: a failed event write loses the event, nothing else. */ +export function recordStreamEvent(event: Parameters[1]): void { + void emitEvent(eventsStore, event); +} + +/** #3321: the activity-ingestion sink for the source-side writers + * (watchdog episodes, Kaneo board changes, GitHub hot-list rows). Dedupe + checkpoints + * live in the store. The returned promise resolves true only when + * every delivery is durable (ingested or already seen): the live + * source awaits it as the acknowledgment that lets it discard its + * Kaneo baseline (Codex P2, PR #5141) — failed deliveries retain + * their cards' baseline entries so the next poll retries the same + * stable delivery ids, while acknowledged cards advance. */ +export async function recordActivity( + deliveries: Parameters[2], +): Promise<{ failed: number; failedIds: string[] }> { + const result = await ingestActivity(activityStore, eventsStore, deliveries); + return { failed: result.failed, failedIds: result.failedIds }; +} + +/** #3977: source freshness notices are not #1739 activity records. + * This store is owned by the aggregator process; the projector and + * collector reach it only through the loopback publisher listener. */ +export async function recordFreshness(input: FreshnessInput): Promise { + await freshnessStore.publish(input); +} + +/** #3321: the source-gap sink for the live source's polling gaps + * (Codex P2, PR #5141): a non-null `to` records (or extends) the + * open gap for the source; a null `to` is recovery — the open gap + * resolves as backfilled, since polling has resumed and the next + * diff lands against the preserved baseline. Never throws into the + * source's read path. */ +export async function recordSourceGap(source: string, from: string, to: string | null): Promise { + try { + if (to !== null) { + await activityStore.recordGap(source, from, to); + return; + } + for (const gap of await activityStore.gaps()) { + if (gap.source === source && gap.status === "open") { + // Recovery happened now, not at the last failed poll: extend + // the gap window to the recovery moment as it resolves + // (Codex P2, PR #5141). + await activityStore.resolveGap(gap.id, "backfilled", new Date().toISOString()); + } + } + } catch (err) { + console.error( + `[activity] WARNING: source gap record failed for ${source}: ${err instanceof Error ? err.message : String(err)}`, + ); + } +} + +/** #3321: pins watchdog episodes to their first-observed `since` + * (Codex P2, PR #5141) — watchdogTierItems assigns `now` for + * several breach kinds, so without this the stream would gain a + * new "episode" on every attention render of one outage. */ +export const watchdogEpisodes = new WatchdogEpisodeStabilizer(); +export async function hasStreamEvent(kind: string, ref: string): Promise { + return eventsStore.has(kind, ref); +} + +export function pickSource(): Source { + // #1290: the live source reads the standing delegation default from + // the actions store's preference records when it stamps the + // needs-user fallbacks onto tier items. + return cfg.source === "live" + ? liveSource(cfg, { + standingAuto: async () => effectiveStandingAuto(await actionsStore.all()).standingAuto, + onEvent: recordStreamEvent, + hasEvent: hasStreamEvent, + onActivity: recordActivity, + onFreshness: recordFreshness, + onSourceGap: recordSourceGap, + seenActivityIds: (source) => activityStore.seenIds(source), + snapshotRemote: storeRemotes?.usage, + onLaptopUnreachable: (detail) => { + fireOpenCodeWorkingHook("aggregator-tick", detail); + }, + }) + : fixtureSource(); +} + +export const source = pickSource(); + +/** Lazy quota refresh (#1171): stale page/API loads ask the deployed + * gatherer unit to run again; single-flight + cooldown live in the module. */ +export const quotaRefresher = createQuotaRefresher({ trigger: systemdTrigger() }); + +// #1279: prefer the latest-comment-per-ref read so a busy batch cannot +// truncate an item's most recent activity out of its brief. +export const briefCommentsFor = async (refs: RefKey[]): Promise => + (source.latestComments ? source.latestComments(refs) : source.comments(refs)).catch(() => []); + +/** + * The source-conflict inbox (#1282 slice 1), assembled from the same facets + * the rest of the dashboard reads. Read-only: detection collects what the + * facets already report, and no render changes because of it. + */ +export async function assembleConflicts(): Promise { + const [pool, orchestration, usage] = await Promise.all([ + source.projects().catch(() => []), + source.orchestration().catch(() => null), + source.usage().catch(() => emptyUsageView()), + ]); + return conflictInbox({ pool, orchestration, services: usage.services }); +} + +/** The identities half of the comment form options, behind a + * stale-while-revalidate cache (#5082, 2026-11-14). commentFormOpts + * is awaited on the request path of /program, /api/program.json and + * /board, and the registry read behind the identities merges the + * feed with a live map of the laptop OpenCode server — ~0.5 s when + * that server is healthy, but 6-10.5 s per call when it stalls under + * load (mapServerSessions' sequential fetches burn their 10 s + * aborts; a failed map was not cached, so every assembly paid the + * stall again). Pool-quota-steward run 381 measured the result: + * /program and /api/program.json 503 at ~10.5 s, /board 200 at + * 10.5 s, everything else fast. Identities are comment-form picker + * metadata — they change when sessions start or end, on a minutes + * timescale — so they take the same contract as the page + * assemblies: the first load is awaited (and warmed at boot, + * below); an expired entry serves stale behind a single-flight + * background refresh, so no request ever waits on the registry + * merge again. The per-request githubRefs half is never cached. */ +export const commentIdentitiesCache = new TodayCache(TODAY_CACHE_TTL_MS); +export async function commentIdentities(): Promise { + return commentIdentitiesCache.get(async () => { + const records = await source.registry().catch(() => []); + return identitiesFromRecords(records); + }); +} + +/** Author identities for the comment form: standing + registry sessions. */ +export async function commentFormOpts(githubRefs: RefKey[] = []): Promise { + return { githubRefs, identities: await commentIdentities() }; +} + +/** Resolve a discuss-page title for any object ref, best-effort. */ +export async function discussTitle(objectRef: string): Promise<{ title: string; githubRefs: RefKey[] }> { + if (objectRef.startsWith("gh:")) { + const ref = objectRef.slice(3); + const items = await source.items([ref]).catch(() => new Map()); + return { title: items.get(ref)?.title ?? `Comments — ${ref}`, githubRefs: [ref] }; + } + if (objectRef.startsWith("session:")) { + const id = objectRef.slice("session:".length); + const records = await source.registry().catch(() => []); + const rec = records.find((r) => r.id === id); + return { title: `Comments — ${rec?.label ?? id}`, githubRefs: rec?.taskRefs ?? [] }; + } + if (objectRef.startsWith("orch:")) { + const id = objectRef.slice("orch:".length); + const section = await source.orchestration().catch(() => null); + const item = [...(section?.tiers.needsDrew ?? []), ...(section?.tiers.needsOrchestrator ?? [])].find( + (i) => i.id === id, + ); + return { + title: `Comments — ${item?.title ?? id}`, + githubRefs: item?.ref ? [item.ref] : [], + }; + } + const [board, rows] = await Promise.all([source.board().catch(() => []), source.roadmap().catch(() => [])]); + const item = board.find((b) => b.id === objectRef); + if (item) return { title: `Comments — ${item.title}`, githubRefs: item.links.map((l) => l.ref) }; + const row = rows.find((r) => r.subject === objectRef); + if (row) return { title: `Comments — ${row.title}`, githubRefs: row.links.map((l) => l.ref) }; + return { title: `Comments — ${objectRef}`, githubRefs: [] }; +} + +/** #1211: the fail-soft facet fallbacks — an empty view is the honest + * degraded form of a facet whose read threw (the renderers already + * banner absent data, e.g. buildAttention's tier-source-missing + * flag); a throwing facet must never 500 a whole page. */ +export function emptyQuotaView(): QuotaView { + return { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }; +} +export function emptyUsageView(): UsageView { + return { + services: [], + uninstrumentedServices: [], + payg: [], + charges: [], + attention: [], + domains: null, + subscriptions: [], + history: {}, + }; +} + diff --git a/pm-stack/aggregator/src/server-write-routes.ts b/pm-stack/aggregator/src/server-write-routes.ts new file mode 100644 index 000000000..25609485a --- /dev/null +++ b/pm-stack/aggregator/src/server-write-routes.ts @@ -0,0 +1,744 @@ +// The server's write surface: report-record resolution, the +// identity-registry admin + stack-token exchange, and the prompt / +// comment / action route families. Each handler returns null when +// its routes do not match, so server.ts keeps the dispatch order. +// Split out of server.ts (#13052). +import { validateNewAction } from "./actions.ts"; +import { checkActionAgainstItem, findTierItem, questionIdForOption } from "./tier-items.ts"; +import { authorizeCommentAuthor, validateNewComment } from "./comments.ts"; +import { PROMPT_STATUSES, validateNewPrompt, type PromptStatus } from "./prompts.ts"; +import { validateNewRoadmapAnnotation } from "./roadmap-annotations.ts"; +import { createAccessAuthorEnforcer, enforceAccessAuthor } from "./access-identity.ts"; +import { identityMappingAuditEvent, validateIdentityMapping } from "./identity-registry.ts"; +import { authorizeWithBreakGlassToken, presentedBreakGlassToken } from "./break-glass.ts"; +import { STACK_TOKEN_TTL_SECONDS, mintStackToken, type StackTokenRole } from "./stack-token.ts"; +import { resolveBwsSecretLookup } from "./secrets.ts"; +import { readJsonBody } from "./request-body.ts"; +import { appendReportBlockConflictResolution, appendReportLateUpdate, compareReportBlock, ReportRecordConflictError, readReportRecords, readReportSnapshots, selectCurrentReportRecords, type ReportLateUpdateOperation, type ReportRecordSource } from "./report-records.ts"; +import { renderReportReview, reportBlockReviews } from "./report-review.ts"; +import { capUnits, cfg, promptsStore, roadmapAnnotationsStore, actionsStore, commentsStore, eventsStore, reportRecordsLocation, identityRegistryStore, breakGlassTokenStore, recordStreamEvent, source } from "./server-wiring.ts"; +import { json, html } from "./server-respond.ts"; +import { applyViewAction } from "./server-contexts.ts"; + +export async function handleReportsRead(req: Request, path: string): Promise { + try { + const records = await readReportRecords(reportRecordsLocation); + const snapshots = await readReportSnapshots(reportRecordsLocation); + const current = selectCurrentReportRecords(records); + if (path === "/api/reports.json") { + return json({ + records: current, + conflicts: reportBlockReviews(records, current).map((review) => ({ + periodId: review.periodId, + blockId: review.blockId, + storedRecordId: review.storedRecord.id, + renderedRecordId: review.renderedRecord.id, + comparison: review.comparison, + })), + }); + } + return html( + renderReportReview( + reportBlockReviews(records, current), + records.length, + new Date(), + current, + new Set(snapshots.map((snapshot) => snapshot.record.period.id)), + ), + ); + } catch { + if (path === "/api/reports.json") return json({ error: "report records unavailable" }, 503); + return html(`

Report review unavailable

Could not read retained report records.

`, 503); + } +} + +export async function handleReportWriteRoutes(req: Request, path: string): Promise { + if (req.method === "POST" && path === "/api/reports/resolve") { + const access = await enforceAccessAuthor(req, { kind: "drew", id: "drew", label: "Drew" }); + if (!access.ok || !access.verified || access.author.kind !== "drew") { + return json({ error: "verified Access owner required" }, 403); + } + let body: Record; + try { + const parsed = await readJsonBody(req); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) + return json({ error: "invalid resolution body" }, 400); + body = parsed as Record; + } catch { + return json({ error: "invalid resolution body" }, 400); + } + const storedRecordId = typeof body.storedRecordId === "string" ? body.storedRecordId : ""; + const renderedRecordId = typeof body.renderedRecordId === "string" ? body.renderedRecordId : ""; + const blockId = typeof body.blockId === "string" ? body.blockId : ""; + const strategy = body.strategy; + if ( + !storedRecordId || + !renderedRecordId || + !blockId || + typeof strategy !== "string" || + !["stored", "rendered", "edited", "combined"].includes(strategy) + ) { + return json({ error: "storedRecordId, renderedRecordId, blockId and a valid strategy are required" }, 400); + } + if (body.resolvedText !== undefined && typeof body.resolvedText !== "string") { + return json({ error: "resolvedText must be text" }, 400); + } + let records; + try { + records = await readReportRecords(reportRecordsLocation); + } catch { + return json({ error: "report records unavailable" }, 503); + } + const storedRecord = records.find((record) => record.id === storedRecordId); + const renderedRecord = records.find((record) => record.id === renderedRecordId); + if (!storedRecord || !renderedRecord) return json({ error: "unknown report record" }, 404); + if ( + storedRecord.period.id !== renderedRecord.period.id || + storedRecord.templateVersion !== renderedRecord.templateVersion + ) { + return json({ error: "compared records must have the same period and template" }, 400); + } + const storedBlock = storedRecord.blocks.find((block) => block.id === blockId); + const renderedBlock = renderedRecord.blocks.find((block) => block.id === blockId); + if (!storedBlock || !renderedBlock) return json({ error: "compared block is missing" }, 400); + const comparison = compareReportBlock(storedBlock.text, renderedBlock.text); + if (!comparison.conflict) return json({ error: "report block has no substantive conflict" }, 400); + const selectedPair = reportBlockReviews(records, selectCurrentReportRecords(records)).some( + (review) => + review.blockId === blockId && + review.storedRecord.id === storedRecordId && + review.renderedRecord.id === renderedRecordId, + ); + const selectedText = + strategy === "stored" ? storedBlock.text : strategy === "rendered" ? renderedBlock.text : body.resolvedText; + const exactRetry = records.some((candidate) => + candidate.blocks.some( + (block) => + block.id === blockId && + block.text === selectedText && + block.resolution?.sourceRecordId === storedRecordId && + block.resolution.comparedRecordId === renderedRecordId && + block.resolution.strategy === strategy, + ), + ); + if (!selectedPair && !exactRetry) { + return json({ error: "compared records are not the current review selection" }, 409); + } + try { + const result = await appendReportBlockConflictResolution( + reportRecordsLocation, + storedRecord, + blockId, + comparison, + strategy as "stored" | "rendered" | "edited" | "combined", + new Date().toISOString(), + typeof body.resolvedText === "string" ? body.resolvedText : undefined, + renderedRecordId, + ); + return json({ inserted: result.inserted, record: result.record }); + } catch (error) { + const message = error instanceof Error ? error.message : "report resolution failed"; + const status = + error instanceof ReportRecordConflictError || message.startsWith("stale report block comparison:") + ? 409 + : /^(report block comparison|compared report record|resolvedAt must be later|report operation |(?:stored|rendered|edited|combined) report block resolution)/.test( + message, + ) + ? 400 + : 500; + return json({ error: message }, status); + } + } + + if (req.method === "POST" && path === "/api/reports/late-update") { + const access = await enforceAccessAuthor(req, { kind: "drew", id: "drew", label: "Drew" }); + if (!access.ok || !access.verified || access.author.kind !== "drew") { + return json({ error: "verified Access owner required" }, 403); + } + let body: Record; + try { + const parsed = await readJsonBody(req); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) + return json({ error: "invalid late update body" }, 400); + body = parsed as Record; + } catch { + return json({ error: "invalid late update body" }, 400); + } + const reportRecordId = typeof body.reportRecordId === "string" ? body.reportRecordId : ""; + const operation = body.operation; + const blockId = typeof body.blockId === "string" ? body.blockId : ""; + const text = typeof body.text === "string" ? body.text : ""; + const relatedAt = typeof body.relatedAt === "string" ? body.relatedAt : ""; + const lateOperations = ["quote", "append", "banner", "event-log", "feedback"]; + if ( + !reportRecordId || + !blockId || + !text.trim() || + !relatedAt || + typeof operation !== "string" || + !lateOperations.includes(operation) + ) { + return json({ error: "reportRecordId, a permitted operation, blockId, text and relatedAt are required" }, 400); + } + let source: ReportRecordSource | undefined; + if (body.source !== undefined) { + if (!body.source || typeof body.source !== "object" || Array.isArray(body.source)) + return json({ error: "invalid late update source" }, 400); + const candidate = body.source as Record; + if ( + typeof candidate.id !== "string" || + typeof candidate.uri !== "string" || + typeof candidate.observedAt !== "string" + ) { + return json({ error: "late update source requires id, uri and observedAt" }, 400); + } + source = { id: candidate.id, uri: candidate.uri, observedAt: candidate.observedAt }; + } + let records; + try { + records = await readReportRecords(reportRecordsLocation); + } catch { + return json({ error: "report records unavailable" }, 503); + } + const current = records.find((record) => record.id === reportRecordId); + if (!current) return json({ error: "unknown report record" }, 404); + try { + const result = await appendReportLateUpdate( + reportRecordsLocation, + current, + operation as ReportLateUpdateOperation, + { id: blockId, text, relatedAt }, + new Date().toISOString(), + source, + ); + return json({ inserted: result.inserted, record: result.record }); + } catch (error) { + const message = error instanceof Error ? error.message : "late report update failed"; + const status = + error instanceof ReportRecordConflictError || message.startsWith("stale report block comparison:") + ? 409 + : /^(report operation |quote report update|feedback report update|each late report update|block relatedAt|source observedAt|late update source|duplicate report block)/.test( + message, + ) + ? 400 + : 500; + return json({ error: message }, status); + } + } + return null; +} + +export async function handleIdentityRoutes(req: Request, path: string): Promise { + // #9604: role mappings are managed only by a verified Access owner. + // The asserted author here is deliberately fixed; request-body identity + // or role claims never authorize registry changes. + if ( + path === "/api/admin/identity-registry" && + (req.method === "GET" || req.method === "POST" || req.method === "DELETE") + ) { + const access = await enforceAccessAuthor(req, { kind: "drew", id: "drew", label: "Drew" }); + if (!access.ok) return json({ error: access.error }, access.status); + let auditActor: string; + if (access.verified && access.author.kind === "drew") { + // Access-verified owner proceeds exactly as before; a presented + // break-glass token is never touched on this path. + auditActor = access.identity?.sub || access.identity?.email || access.author.id; + } else { + // #9608: the Access/IdP-outage path. A presented single-use + // break-glass token is consumed atomically (with its audit + // event) and authorizes exactly this one admin request; + // anything invalid — or no token at all — fails closed. + const presented = presentedBreakGlassToken(req); + if (!presented) return json({ error: "verified Access owner required" }, 403); + const grant = await authorizeWithBreakGlassToken({ + store: breakGlassTokenStore, + events: eventsStore, + token: presented, + }); + if (!grant.ok) return json({ error: grant.error }, 403); + auditActor = grant.auditActor; + } + if (req.method === "GET") return json({ registry: await identityRegistryStore.list() }); + try { + const body = await readJsonBody(req); + if (req.method === "POST") { + const parsed = validateIdentityMapping(body); + if (!parsed.ok) return json({ error: parsed.error }, 400); + const result = await identityRegistryStore.set(parsed.identity, parsed.role, auditActor); + await eventsStore.record( + identityMappingAuditEvent({ + identity: parsed.identity, + previousRole: result.previousRole, + role: parsed.role, + revision: result.registry.revision, + actor: auditActor, + }), + ); + return json({ registry: result.registry, previousRole: result.previousRole }); + } + const identity = + typeof body === "object" && body !== null ? (body as { identity?: unknown }).identity : undefined; + if ( + typeof identity !== "string" || + identity.trim() === "" || + identity.trim().length > 200 || + /\s/.test(identity.trim()) + ) { + return json({ error: "identity must be a non-empty whitespace-free string (max 200 chars)" }, 400); + } + const result = await identityRegistryStore.remove(identity.trim()); + if (result.previousRole !== null) { + await eventsStore.record( + identityMappingAuditEvent({ + identity: identity.trim(), + previousRole: result.previousRole, + role: null, + revision: result.registry.revision, + actor: auditActor, + }), + ); + } + return json({ registry: result.registry, previousRole: result.previousRole }); + } catch (error) { + return json( + { error: `identity registry operation failed: ${error instanceof Error ? error.message : error}` }, + 500, + ); + } + } + + // #9605: exchange the already-verified Access identity for a short-lived + // layer-scoped token. The target and action are request metadata; the + // principal and role always come from verified Access + the registry. + if (req.method === "POST" && path === "/api/stack-token/exchange") { + const access = await enforceAccessAuthor(req, { kind: "agent", id: "exchange", label: "exchange" }); + if (!access.ok) return json({ error: access.error }, access.status); + if (!access.verified || !access.identity) return json({ error: "verified Access identity required" }, 403); + const secret = cfg.stackTokenSecret; + if (!secret) return json({ error: "stack token exchange is not configured" }, 503); + const identity = access.identity.sub || access.identity.email; + const role: StackTokenRole = + access.author.kind === "drew" ? "owner" : await identityRegistryStore.roleFor(identity); + if (role === "read-only") return json({ error: "identity role cannot mint write tokens" }, 403); + try { + const body = await readJsonBody(req); + const target = + typeof body === "object" && body !== null && typeof (body as { target?: unknown }).target === "string" + ? (body as { target: string }).target.trim() + : ""; + const action = + typeof body === "object" && body !== null && typeof (body as { action?: unknown }).action === "string" + ? (body as { action: string }).action.trim() + : ""; + if (!["kaneo", "pad", "grist"].includes(target)) return json({ error: "target must be kaneo, pad, or grist" }, 400); + if (!/^[A-Za-z][A-Za-z0-9._:-]{0,63}$/.test(action)) return json({ error: "action is invalid" }, 400); + const token = mintStackToken({ sub: identity, role, aud: target, act: action }, secret); + return json({ token, tokenType: "Bearer", audience: target, expiresIn: STACK_TOKEN_TTL_SECONDS }); + } catch (error) { + return json({ error: `stack token exchange failed: ${error instanceof Error ? error.message : error}` }, 400); + } + } + return null; +} + +export async function handleWriteRoutes(req: Request, url: URL, path: string): Promise { + // --- Dashboard comment writes (#906 §2) -------------------------------- + if (req.method === "POST" && path === "/api/roadmap/annotations") { + try { + const parsed = validateNewRoadmapAnnotation(await readJsonBody(req)); + if (!parsed.ok) return json({ error: parsed.error }, 400); + // #1253 slice: when Access is configured, authorship derives from + // the verified JWT, never the caller-supplied author. + const annotationAccess = await enforceAccessAuthor(req, parsed.value.author); + if (!annotationAccess.ok) return json({ error: annotationAccess.error }, annotationAccess.status); + parsed.value.author = annotationAccess.author; + const rows = await source.roadmap().catch(() => []); + if (!rows.some((row) => row.subject === parsed.value.objectRef)) { + return json({ error: "objectRef is not a current roadmap row" }, 404); + } + try { + const annotation = await roadmapAnnotationsStore.add(parsed.value); + return json({ annotation }, 201); + } catch (err) { + return json({ error: `annotation persistence failed: ${err instanceof Error ? err.message : err}` }, 500); + } + } catch (err) { + return json({ error: `invalid annotation: ${err instanceof Error ? err.message : err}` }, 400); + } + } + if (req.method === "POST" && path === "/api/roadmap/annotations/alias") { + try { + const body = (await readJsonBody(req)) as { aliasRef?: unknown; stableRef?: unknown }; + if (typeof body.aliasRef !== "string" || typeof body.stableRef !== "string") { + return json({ error: "aliasRef and stableRef are required" }, 400); + } + const rows = await source.roadmap().catch(() => []); + if (!rows.some((row) => row.subject === body.aliasRef)) { + return json({ error: "aliasRef is not a current roadmap row" }, 404); + } + if (!(await roadmapAnnotationsStore.forObject(body.stableRef)).length) { + return json({ error: "stableRef has no existing annotation history" }, 404); + } + await roadmapAnnotationsStore.addAlias(body.aliasRef, body.stableRef); + return json({ aliases: await roadmapAnnotationsStore.aliasEntries() }); + } catch (err) { + return json({ error: `invalid annotation alias: ${err instanceof Error ? err.message : err}` }, 400); + } + } + + if (req.method === "POST" && path === "/api/prompt") { + const parsed = validateNewPrompt(await readJsonBody(req).catch(() => null)); + if (!parsed.ok) return json({ error: parsed.error }, 400); + try { + return json({ prompt: await promptsStore.add(parsed.value) }, 201); + } catch (err) { + return json({ error: `prompt persistence failed: ${err instanceof Error ? err.message : err}` }, 500); + } + } + if (req.method === "GET" && path === "/api/prompt/unread-count") { + const count = await promptsStore.unreadCount(); + return json({ count, unread: count, total: count }); + } + if (req.method === "GET" && path === "/api/prompt/threads") { + return json({ threads: await promptsStore.threads() }); + } + if (req.method === "GET" && path.startsWith("/api/prompt/thread/")) { + const threadId = decodeURIComponent(path.slice("/api/prompt/thread/".length)); + return json({ threadId, prompts: await promptsStore.thread(threadId) }); + } + if (req.method === "GET" && path === "/api/prompt") { + const status = url.searchParams.get("status"); + const page = url.searchParams.get("page") ?? undefined; + const threadId = url.searchParams.get("threadId") ?? undefined; + const replyTo = url.searchParams.get("replyTo") ?? undefined; + const archivedParam = url.searchParams.get("archived"); + const includeArchived = + url.searchParams.get("includeArchived") === "1" || url.searchParams.get("includeArchived") === "true"; + const archived = archivedParam === "true" ? true : archivedParam === "false" ? false : undefined; + const filter: Parameters[0] = { + page, + status: PROMPT_STATUSES.includes(status as PromptStatus) ? (status as PromptStatus) : undefined, + threadId, + replyTo, + archived, + includeArchived, + }; + const prompts = await promptsStore.list(filter); + // newest first + prompts.sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0)); + return json({ prompts }); + } + if (req.method === "GET" && path.startsWith("/api/prompt/")) { + const rest = decodeURIComponent(path.slice("/api/prompt/".length)); + if (rest === "thread" || rest.startsWith("thread/")) { + // handled above via query; fall through to 404 + } + const id = rest; + const prompt = await promptsStore.get(id); + if (!prompt) return json({ error: "prompt not found" }, 404); + return json({ + id: prompt.id, + status: prompt.status, + answer: prompt.answer, + error: prompt.error, + threadId: prompt.threadId, + archived: prompt.archived, + read: prompt.read, + replyTo: prompt.replyTo, + refs: prompt.refs, + }); + } + if (req.method === "PATCH" && path.startsWith("/api/prompt/")) { + const id = decodeURIComponent(path.slice("/api/prompt/".length)); + let body: unknown = null; + try { + body = await readJsonBody(req); + } catch { + body = null; + } + const b = body && typeof body === "object" && !Array.isArray(body) ? (body as Record) : {}; + const patch: Parameters[1] = {}; + if (typeof b.status === "string" && PROMPT_STATUSES.includes(b.status as PromptStatus)) + patch.status = b.status as PromptStatus; + if (typeof b.answer === "string") patch.answer = b.answer; + if (typeof b.error === "string") patch.error = b.error; + if (typeof b.archived === "boolean") patch.archived = b.archived; + if (typeof b.read === "boolean") patch.read = b.read; + if (Array.isArray(b.refs) && b.refs.every((x) => typeof x === "string")) patch.refs = b.refs as string[]; + if (b.replyTo === null || typeof b.replyTo === "string") patch.replyTo = b.replyTo as string | null; + const updated = await promptsStore.update(id, patch); + if (!updated) return json({ error: "prompt not found" }, 404); + return json({ prompt: updated }); + } + if (req.method === "POST" && path === "/api/comments") { + try { + const parsed = validateNewComment(await readJsonBody(req)); + if (!parsed.ok) return json({ error: parsed.error }, 400); + // #1253 slice: when Access is configured, authorship derives from + // the verified JWT, never the caller-supplied author. + const commentAccess = await enforceAccessAuthor(req, parsed.value.author); + if (!commentAccess.ok) return json({ error: commentAccess.error }, commentAccess.status); + parsed.value.author = commentAccess.author; + // #941: a privileged author additionally requires the operator + // token when one is configured (fail closed on a secret-store + // outage); with no secret configured the write stays unverified. + // Runs on the Access-derived author above, so the two gates + // compose: identity first, privilege second. + const authorization = authorizeCommentAuthor( + parsed.value.author, + req.headers.get("authorization"), + await resolveBwsSecretLookup("pm-aggregator.comments-operator-token"), + ); + if (!authorization.ok) return json({ error: authorization.error }, authorization.status); + // #1509: a persistence failure is a server error, not bad input - + // only the validation/body-parse path above earns a 400. + let comment; + try { + comment = await commentsStore.add(parsed.value, { + authorVerified: authorization.authorVerified, + // #1253 split 4 (#9606): "verified" only when the author came + // from the Access JWT above, never from the request body. + provenance: commentAccess.verified ? "verified" : "asserted-legacy", + }); + } catch (err) { + return json({ error: `comment persistence failed: ${err instanceof Error ? err.message : err}` }, 500); + } + return json({ comment }, 201); + } catch (err) { + return json({ error: `invalid comment: ${err instanceof Error ? err.message : err}` }, 400); + } + } + if (req.method === "POST" && path === "/api/comments/triage") { + try { + const body = (await readJsonBody(req)) as { ids?: unknown }; + const ids = Array.isArray(body.ids) ? body.ids.filter((x): x is string => typeof x === "string") : []; + return json({ triaged: await commentsStore.markTriaged(ids) }); + } catch (err) { + return json({ error: `invalid triage: ${err instanceof Error ? err.message : err}` }, 400); + } + } + if (req.method === "POST" && path === "/api/comments/github-result") { + try { + const body = (await readJsonBody(req)) as { id?: unknown; url?: unknown; error?: unknown }; + if (typeof body.id !== "string") return json({ error: "id required" }, 400); + const updated = await commentsStore.markGithubResult(body.id, { + url: typeof body.url === "string" ? body.url : undefined, + error: typeof body.error === "string" ? body.error : undefined, + }); + return updated ? json({ comment: updated }) : json({ error: "no such github comment" }, 404); + } catch (err) { + return json({ error: `invalid result: ${err instanceof Error ? err.message : err}` }, 400); + } + } + // --- Dashboard action writes (#1152/#1154/#1156) ----------------------- + // The triage write path: forms POST DashActions here; the fleet + // consumers (orchestration pass) poll state=new and + // report outcomes to /api/actions/result. The dashboard itself never + // writes GitHub, the Project, or a session server. + if (req.method === "POST" && path === "/api/actions") { + try { + const parsed = validateNewAction(await readJsonBody(req)); + if (!parsed.ok) return json({ error: parsed.error }, 400); + // #1253 slice: gate every action write, including non-triage and + // preference actions, on the configured Access identity. + const actionAccess = await enforceAccessAuthor(req, parsed.value.author); + if (!actionAccess.ok) return json({ error: actionAccess.error }, actionAccess.status); + parsed.value.author = actionAccess.author; + // #1291/#1293: checks that need the currently published item — + // option/survey membership, required-question coverage, proposal + // identity, the access/policy auto ban. Enforced only when the + // aggregator actually holds a section; with none, the store + // stays the permissive boundary of the triage slice and the + // consumer rejects what it cannot apply. + if (parsed.value.kind === "triage") { + const section = await source.orchestration().catch(() => null); + let item: ReturnType; + if (section) { + item = findTierItem(section, parsed.value.objectRef); + const problem = checkActionAgainstItem(parsed.value, item, Date.now()); + if (problem) return json({ error: problem }, 400); + } + if (parsed.value.verb === "answer" && parsed.value.payload.optionId) { + parsed.value.payload.questionId = questionIdForOption(item, parsed.value.payload.optionId) ?? "$options"; + } + } + // #1509: persistence failure -> 5xx (see /api/comments above). + let added; + try { + added = await actionsStore.add(parsed.value); + } catch (err) { + return json({ error: `action persistence failed: ${err instanceof Error ? err.message : err}` }, 500); + } + const { action, created } = added; + if (added.duplicateOf) { + return json( + { + error: `duplicate answer recorded as ${action.id}; it points to existing answer action ${added.duplicateOf}`, + action, + duplicateOf: added.duplicateOf, + }, + 409, + ); + } + // A client-token replay of an already-persisted duplicate attempt + // keeps the rejected semantics instead of reading as a fresh + // "sent · pending" success (Codex P2 on PR #4024). + if (!created && action.duplicateOf) { + return json( + { + error: `duplicate answer recorded as ${action.id}; it points to existing answer action ${action.duplicateOf}`, + action, + duplicateOf: action.duplicateOf, + }, + 409, + ); + } + // #1276: saved-view preference verbs are applied by the + // aggregator itself to the views store and marked applied (or + // rejected, with the reason) in the same request — the action + // record stays the audit trail for every view change. + if ( + created && + action.kind === "preference" && + (action.verb === "save-view" || + action.verb === "rename-view" || + action.verb === "delete-view" || + action.verb === "set-default-view") + ) { + try { + const note = await applyViewAction(action); + const updated = await actionsStore.markResult(action.id, { + outcome: "applied", + byRun: "aggregator-views", + note, + }); + return json({ action: updated ?? action }, 201); + } catch (err) { + const updated = await actionsStore.markResult(action.id, { + outcome: "rejected", + byRun: "aggregator-views", + note: err instanceof Error ? err.message : String(err), + }); + return json({ action: updated ?? action, error: err instanceof Error ? err.message : String(err) }, 400); + } + } + return json(created ? { action } : { action, deduped: true }, created ? 201 : 200); + } catch (err) { + return json({ error: `invalid action: ${err instanceof Error ? err.message : err}` }, 400); + } + } + // #1277: bulk triage — one mediated batch, validated and appended + // item by item under the exact single-action rules above. Every + // accepted item becomes its OWN attributed audit entry (never one + // opaque batch record), so the batch is recoverable from the + // entries themselves; every rejected item is reported by ref with + // its error and appends nothing, so a partial batch never silently + // drops work — the failed items simply remain in Needs-you. + if (req.method === "POST" && path === "/api/actions/batch") { + try { + const body = (await readJsonBody(req)) as { actions?: unknown }; + if (!Array.isArray(body.actions) || body.actions.length === 0 || body.actions.length > 100) { + return json({ error: "actions must be an array of 1-100 action objects" }, 400); + } + const entries: unknown[] = body.actions; + // The published-item checks (#1291/#1293) need the section once, + // not once per item. + const section = entries.some( + (a) => typeof a === "object" && a !== null && (a as { kind?: unknown }).kind === "triage", + ) + ? await source.orchestration().catch(() => null) + : null; + const results: { + index: number; + objectRef: string | null; + ok: boolean; + action?: unknown; + deduped?: boolean; + error?: string; + }[] = []; + // One enforcer for the whole batch: the request's JWT is + // verified once, not once per action (see access-identity.ts). + const enforceBatchAuthor = createAccessAuthorEnforcer(req); + for (const [index, raw] of entries.entries()) { + const objectRef = + typeof raw === "object" && raw !== null && typeof (raw as { objectRef?: unknown }).objectRef === "string" + ? (raw as { objectRef: string }).objectRef + : null; + const parsed = validateNewAction(raw); + if (!parsed.ok) { + results.push({ index, objectRef, ok: false, error: parsed.error }); + continue; + } + const batchAccess = await enforceBatchAuthor(parsed.value.author); + if (!batchAccess.ok) { + results.push({ index, objectRef, ok: false, error: batchAccess.error }); + continue; + } + parsed.value.author = batchAccess.author; + if (parsed.value.kind === "triage" && section) { + const problem = checkActionAgainstItem( + parsed.value, + findTierItem(section, parsed.value.objectRef), + Date.now(), + ); + if (problem) { + results.push({ index, objectRef, ok: false, error: problem }); + continue; + } + } + try { + const { action, created } = await actionsStore.add(parsed.value); + results.push({ index, objectRef, ok: true, action, ...(created ? {} : { deduped: true }) }); + } catch (err) { + results.push({ + index, + objectRef, + ok: false, + error: `action persistence failed: ${err instanceof Error ? err.message : err}`, + }); + } + } + const recorded = results.filter((r) => r.ok).length; + return json({ results, recorded, failed: results.length - recorded }, 200); + } catch (err) { + return json({ error: `invalid batch: ${err instanceof Error ? err.message : err}` }, 400); + } + } + if (req.method === "POST" && path === "/api/actions/result") { + try { + const body = (await readJsonBody(req)) as { id?: unknown; outcome?: unknown; byRun?: unknown; note?: unknown }; + if (typeof body.id !== "string") return json({ error: "id required" }, 400); + if (body.outcome !== "applied" && body.outcome !== "rejected") { + return json({ error: 'outcome must be "applied" | "rejected"' }, 400); + } + if (typeof body.byRun !== "string" || body.byRun.trim() === "") return json({ error: "byRun required" }, 400); + const result = await actionsStore.markResultTransition(body.id, { + outcome: body.outcome, + byRun: body.byRun, + note: typeof body.note === "string" ? body.note : undefined, + }); + if (result?.transitioned) { + const updated = result.action; + // #1739: the action-result route is one of the event log's + // writers — the outcome lands in the cross-stack stream. + // Fire-and-forget: the response never waits on, and is never + // failed by, the event append. + recordStreamEvent({ + actor: updated.appliedByRun ?? capUnits(body.byRun, 200), + kind: body.outcome === "applied" ? "action-applied" : "action-rejected", + ref: updated.objectRef, + summary: capUnits( + `${updated.kind}/${updated.verb} ${body.outcome} by ${body.byRun}` + + (typeof body.note === "string" && body.note ? ` — ${body.note}` : ""), + 500, + ), + }); + } + const updated = result?.action; + return updated ? json({ action: updated }) : json({ error: "no such action" }, 404); + } catch (err) { + return json({ error: `invalid result: ${err instanceof Error ? err.message : err}` }, 400); + } + } + return null; +} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index cedd0faf2..85d0ddbc0 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -6,2386 +6,87 @@ // its result companion) on the same pattern. Everything underneath // (GitHub, Kaneo, Grist) stays read-only from here — the fleet jobs // apply actions; the dashboard only records them. -import { readFile, stat } from "node:fs/promises"; -import { createQuotaRefresher, systemdTrigger } from "./quota-refresh.ts"; +// +// Split (#13052): the wiring lives in server-wiring.ts, the context +// assemblies in server-contexts.ts, the standalone token pages in +// server-pages.ts, the Response constructors in server-respond.ts, +// and the write / alert / decision route families in +// server-write-routes.ts, server-alert-routes.ts and +// server-decision-routes.ts. This file keeps the read routes, the +// dispatch order, and the bootstrap. +import { readFile } from "node:fs/promises"; import { buildQuotaAnalytics, primeAttemptAggregates, type QuotaAnalytics } from "./analytics-store.ts"; import { decodePathSegment } from "./path-segment.ts"; import { errorBoundaryResponse, notFoundResponse } from "./error-boundary.ts"; -import { ACTION_STATES, ActionsStore, validateNewAction, type DashAction } from "./actions.ts"; -import { - checkActionAgainstItem, - effectiveNeedsOrder, - effectiveStandingAuto, - findTierItem, - questionIdForOption, -} from "./tier-items.ts"; -import { - authorizeCommentAuthor, - commentKindCounts, - CommentsStore, - queuedComments, - validateNewComment, -} from "./comments.ts"; -import { PROMPT_STATUSES, PromptsStore, validateNewPrompt, type PromptStatus } from "./prompts.ts"; -import type { SavedView, ViewFilters, ViewItemLike } from "./views.ts"; -import { ViewsStore, filtersFromQuery, itemMatchesView, ownerKey } from "./views.ts"; +import { ACTION_STATES } from "./actions.ts"; +import { commentKindCounts, queuedComments } from "./comments.ts"; +import { itemMatchesView } from "./views.ts"; import { filterBoardForView, filterRoadmapForView, fragBoardUrl, linkedLike } from "./board-view.ts"; -import { EventsStore, emitEvent, pageEvents } from "./events.ts"; -import { FreshnessStore, type FreshnessInput } from "./freshness.ts"; +import { pageEvents } from "./events.ts"; import { createFreshnessIpcHandler } from "./freshness-ipc.ts"; import { freshnessDeliveryResponse } from "./freshness-delivery.ts"; -import { fleetFeedRevisionReader, FreshnessReconciler } from "./freshness-reconcile.ts"; -import { - IngestionStore, - WatchdogEpisodeStabilizer, - ingestActivity, - createWatchdogGapSyncQueue, - watchdogDeliveries, - activityCoverageHtml, - gapsHtml, - ACTIVITY_SOURCE_COVERAGE, - type ActivitySourceStatus, -} from "./activity.ts"; -import { GithubHotListConsumer, unconfiguredGithubStatus } from "./github-hot-list.ts"; -import { FileOutcomeBindingSource, GithubOutcomeConsumer } from "./outcome-consumer.ts"; +import { activityCoverageHtml, gapsHtml, ACTIVITY_SOURCE_COVERAGE } from "./activity.ts"; +import { unconfiguredGithubStatus } from "./github-hot-list.ts"; import { buildOutcomeView, drillOutcomeFacts, type OutcomeDrillSelector } from "./outcome-view.ts"; import { OutcomeFactStore } from "./outcome-attribution.ts"; -import { RoadmapAnnotationsStore, validateNewRoadmapAnnotation } from "./roadmap-annotations.ts"; -import { createAccessAuthorEnforcer, enforceAccessAuthor } from "./access-identity.ts"; -import { IdentityRegistryStore, identityMappingAuditEvent, validateIdentityMapping } from "./identity-registry.ts"; -import { - BreakGlassTokenStore, - authorizeWithBreakGlassToken, - presentedBreakGlassToken, -} from "./break-glass.ts"; -import { STACK_TOKEN_TTL_SECONDS, mintStackToken, type StackTokenRole } from "./stack-token.ts"; -import { healthHookAuditEvent } from "./health-hook-audit-event.ts"; -import { - computeCoverage, - CoverageSnapshotStore, - nextCoverageSnapshot, - type CoverageSnapshotFile, - type RepoCensus, -} from "./coverage.ts"; -import { loadConfig } from "./config.ts"; -import { getTursoStoreClient } from "./turso-stores.ts"; -import { createTursoRemotes } from "./remote-stores.ts"; import { itemServiceLinks } from "./service-links.ts"; -import { loadFeed } from "./feed.ts"; -import { AA_PLAN_FACTS, sectionPoolIdsFromConfig } from "./aa.ts"; -import { - getNeedsDrew, - listOpenNeedsDrew, - raiseNeedsDrew, - needsDrewIncidentKey, - recordAnswer, - shouldFetchNeedsDrewCensus, - validateNeedsDrew, - type NeedsDrewCensus, - type NeedsDrewQuestion, -} from "./needs-drew.ts"; -import { - decisionSetOpenState, - decisionSetProgress, - deferWithSubmissions, - getDecisionDrafts, - getDecisionSet, - isDeferLean, - decisionSetSummary, - decisionSetsForView, - isDecisionSetView, - listDecisionSets, - listOpenDecisionSets, - raiseDecisionSet, - refreshDecisionSet, - recordResolutions, - requestInfoOpenQuestions, - upsertDecisionDrafts, - validateDecisionDraftUpsert, - validateDecisionSet, - withGeneratedSetId, - effectiveQuestionMode, - type DecisionItem, - type DecisionSet, - type DecisionSetView, - type DecisionSubmission, - decisionsDraftScript, -} from "./decisions.ts"; -import { - appendDecisionEvents, - readDecisionEvents, - validateDecisionEventInput, - type DecisionEventInput, -} from "./decision-events.ts"; -import { listStackHealthDown, readStackHealthStates, setStackHealth, validateStackHealth } from "./stack-health.ts"; -import { validateHealthHook, type HealthHookRecord } from "./health-hook.ts"; -import { - buildHealth, - pageRenderHealth, - recordRender, - summarizeItemCoverage, - type HealthView, - type ItemsCoverage, -} from "./health.ts"; +import { sectionPoolIdsFromConfig } from "./aa.ts"; +import { listOpenNeedsDrew } from "./needs-drew.ts"; +import { listOpenDecisionSets } from "./decisions.ts"; +import { listStackHealthDown, readStackHealthStates } from "./stack-health.ts"; +import { buildHealth, pageRenderHealth, recordRender } from "./health.ts"; import { manifestRouteFor } from "./pages.ts"; -import { conflictInbox, type ConflictInbox } from "./conflicts.ts"; -import { watchdogTierItems, WATCHDOG_PROBE_SERVICE_IDS } from "./watchdog.ts"; -import { readHostHealthSnapshot } from "./host-health.ts"; -import { - allRefs, - buildAttention, - buildQuotaActions, - deriveToday, - filterAttentionViewByRefs, - projectPace, - quotaActionTierItems, - type RoadmapGrain, -} from "./derive.ts"; -import { - reconcileRoadmap, - roadmapDriftReport, - unavailableRoadmapReconciliation, - type RoadmapReconciliation, -} from "./roadmap-reconcile.ts"; -import type { Comment, DashComment, GhItem, ProjectPoolItem, QuotaView, RefKey, UsageView } from "./model.ts"; -import { isValidRef } from "./model.ts"; +import { allRefs, filterAttentionViewByRefs, projectPace, type RoadmapGrain } from "./derive.ts"; +import { roadmapDriftReport } from "./roadmap-reconcile.ts"; +import type { DashComment, ProjectPoolItem } from "./model.ts"; import { buildEpicRollups } from "./epics.ts"; -import { SpendRollupStore } from "./spend-rollups.ts"; -import { buildSpendCards, type SpendCardsView } from "./spend-cards.ts"; -import { buildProgramData, programRefs } from "./program.ts"; +import { buildProgramData } from "./program.ts"; import { buildReleaseSnapshots } from "./releases.ts"; import { deriveGenealogy, enrichRoadmapRows } from "./genealogy.ts"; -import { - PROJECT_CONFIGS, - allProjectRefs, - buildProjectDetail, - buildProjectSummaries, - projectDocTarget, - projectConfigById, -} from "./project-config.ts"; +import { PROJECT_CONFIGS, allProjectRefs, buildProjectDetail, buildProjectSummaries, projectDocTarget, projectConfigById } from "./project-config.ts"; import { PHASE12_REPO, parsePhase12Steps, type Phase12Snapshot } from "./phase12.ts"; import { PHASE_MAPPING_REPO, type PhaseMappingSnapshot } from "./phase-mapping.ts"; import type { BuildHealthSnapshot } from "./build-health.ts"; import { parseF12Items, type F12PrRef } from "./f12-readiness.ts"; -import { identitiesFromRecords, type AuthorIdentity } from "./registry.ts"; -import { - attentionFragment, - attentionSections, - ghObjectRef, - renderAa, - renderAttention, - renderAttentionShell, - renderBoard, - renderBoardBody, - renderDiscuss, - renderDns, - renderConflicts, - renderHealth, - renderItem, - deriveOverview, - renderOverview, - renderOverviewBody, - renderOverviewShell, - renderCommentsQueue, - renderPages, - renderProgram, - renderProgramProject, - renderQuota, - renderQueue, - renderQueueBody, - renderQueueShell, - buildRoadmapDrill, - renderRoadmap, - renderSearch, - renderServiceDetail, - renderSessions, - renderToday, - renderTodayBody, - renderTodayShell, - questionsSectionHtml, - type CommentFormOpts, - eventTableHtml, -} from "./render.ts"; +import { identitiesFromRecords } from "./registry.ts"; +import { attentionFragment, attentionSections, ghObjectRef, renderAa, renderAttention, renderAttentionShell, renderBoard, renderBoardBody, renderDiscuss, renderDns, renderConflicts, renderHealth, renderItem, deriveOverview, renderOverview, renderOverviewBody, renderOverviewShell, renderCommentsQueue, renderPages, renderProgram, renderProgramProject, renderQuota, renderQueue, renderQueueBody, renderQueueShell, renderRoadmap, renderSearch, renderServiceDetail, renderSessions, renderToday, renderTodayBody, renderTodayShell, eventTableHtml } from "./render.ts"; import { buildBriefs } from "./brief.ts"; -import { buildDigest, listDigestArchives, readDigestArchive, type Digest, type DigestKind } from "./digest.ts"; -import { timingSafeEqual } from "node:crypto"; -import { - classEnabled, - getAlertsStore, - requestAlertTick, - sendClassTestPush, - sendTestPush, - startAlertEngine, - toPublicSubscription, - validateNewIncident, - validateNewSubscription, - type PushPayload, -} from "./alerts.ts"; -import { recordSwProbe, sendPush, swProbeSummary, VAPID_PUBLIC_KEY } from "./push.ts"; -import { resolveBwsSecret, resolveBwsSecretLookup } from "./secrets.ts"; -import { SW_SOURCE } from "./sw-source.ts"; -import { renderAlerts, renderNotificationPreferences, renderNotifications, renderDigest, esc } from "./render.ts"; +import { listDigestArchives, readDigestArchive } from "./digest.ts"; +import { classEnabled, getAlertsStore, startAlertEngine, type PushPayload } from "./alerts.ts"; +import { recordSwProbe, sendPush, swProbeSummary } from "./push.ts"; +import { renderDigest, esc } from "./render.ts"; import type { QueueSnapshot } from "./queue.ts"; -import { - deriveSoleDoorPoolIds, - isNotificationTestClass, - NOTIFICATION_CLASS_DEFAULTS, - NOTIFICATION_CLASSES, - rollupNotificationSends, - type NotificationSnapshot, -} from "./notifications.ts"; +import { deriveSoleDoorPoolIds, type NotificationSnapshot } from "./notifications.ts"; import { readJsonBody } from "./request-body.ts"; import { parseRegistryQuery, queryRegistry } from "./registry-view.ts"; import { addConsoleShortcut } from "./console-gate.ts"; -import { searchWork } from "./search-view.ts"; import type { Source } from "./source.ts"; -import { fixtureSource } from "./sources/fixtures.ts"; -import { liveSource } from "./sources/live.ts"; -import { buildQueueView, queueInputsStale } from "./queue-view.ts"; -import { createDashboardResponseDeadline } from "./assembly-deadline.ts"; -import { dispatchStateFor, fetchRfaState, RFA_NOT_PICKED_UP } from "./sources/ready-for-agent.ts"; -import { TodayCache, TODAY_CACHE_TTL_MS } from "./today-cache.ts"; import { boardJsonBody, boardJsonViewBody } from "./board-json.ts"; -import { ItemHistoryStore } from "./item-history.ts"; -import { SloJournal, groupSamplesByFacet } from "./slo-journal.ts"; import { sampleSloFacets } from "./slo-sampler.ts"; -import { SLO_DEFINITIONS, summarizeSloFacet, type SloFacetSummary } from "./slo.ts"; -import { watchdogHeartbeatLine } from "./watchdog-heartbeat.ts"; -import { createWatchdogHeartbeatRecorder, finishWatchdogGapSync } from "./watchdog-runner.ts"; import type { EscalationSink } from "./escalation.ts"; import { createEscalationTicker, escalationDelivery, escalationJournalLine } from "./escalation-tick.ts"; import { emptyState } from "./remediation.ts"; import { computeFlowAnalytics } from "./flow-analytics.ts"; -import { fireOpenCodeWorkingHook } from "./health-hook-fire.ts"; -import { - appendReportBlockConflictResolution, - appendReportLateUpdate, - compareReportBlock, - defaultReportRecordsFile, - ReportRecordConflictError, - readReportRecords, - readReportSnapshots, - selectCurrentReportRecords, - type ReportLateUpdateOperation, - type ReportRecordSource, -} from "./report-records.ts"; -import { renderReportReview, reportBlockReviews } from "./report-review.ts"; -import { - FORECAST_CONTRACT_VERSION, - quotaForecastContract, - subjectForecastContracts, - type ForecastContract, -} from "./forecast-contract.ts"; - -// Cap `t` at `max` UTF-16 code units, but never leave half of a surrogate -// pair at the cut (#7740, mirroring the #7694-family capUnits guard): an -// astral character straddling the cap is dropped whole, so a persisted -// event field can never end in a lone high surrogate. -function capUnits(t: string, max: number): string { - if (t.length <= max) return t; - let end = max; - const before = t.charCodeAt(end - 1); - const after = t.charCodeAt(end); - if (before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff) end--; - return t.slice(0, end); -} - -const cfg = loadConfig(); -// #10383: the bounded routes' last-good survives a restart on disk, so -// the first request after a deploy serves it instead of a 503. -const dashboardResponseWithinDeadline = createDashboardResponseDeadline({ persistDir: cfg.lastGoodDir }); -const promptsStore = new PromptsStore(cfg.promptsFile); -const roadmapAnnotationsStore = new RoadmapAnnotationsStore(cfg.roadmapAnnotationsFile); -const coverageStore = new CoverageSnapshotStore(cfg.coverageSnapshotFile); -const itemHistoryStore = new ItemHistoryStore(cfg.itemHistoryFile); -const sloJournal = new SloJournal(cfg.sloJournalFile); -let sloSummaryCache: { at: number; value: SloFacetSummary[] } | null = null; -const spendRollupStore = new SpendRollupStore(cfg.snapshotsDir); -/** #4824: the Projects/Roadmap spend-beside-progress view over the - * #4823 rollup store. A failed read renders no spend block (the - * store's absence is already the honest state — ingestion is a - * separate slice); it never fabricates zeroed cards. */ -const loadSpendCards = async (): Promise => { - try { - return buildSpendCards(await spendRollupStore.readAll()); - } catch { - return null; - } -}; - -async function readyAgentDispatchStates(items: Map) { - const targets = [...items.values()].filter( - (item) => item.labels.some((label) => label.toLowerCase() === "ready-for-agent") && /#\d+$/.test(item.ref), - ); - if (!targets.length) return []; - const observedAt = new Date().toISOString(); - if (cfg.source !== "live") { - // #4969 (Codex on PR #5283): fixtures mode must never read the live - // harness — deterministic fixture dispatch data, mirroring the - // health.ts fixtures boundary. The canned set has no picked-up - // work item, so every labelled fixture item is honestly - // "not picked up". - return targets.map((item) => ({ - ref: item.ref, - state: RFA_NOT_PICKED_UP, - provenance: { source: "ready-for-agent", observedAt, repository: item.ref.split("#")[0], mode: "fixtures" }, - })); - } - try { - const state = await fetchRfaState(cfg.readyForAgent.baseUrl); - return targets - .map((item) => { - const match = /^(.*)#(\d+)$/.exec(item.ref); - if (!match) return null; - return { - ref: item.ref, - state: dispatchStateFor(state, match[1], Number(match[2])) || RFA_NOT_PICKED_UP, - provenance: { source: "ready-for-agent", observedAt, repository: match[1] }, - }; - }) - .filter((entry): entry is NonNullable => entry !== null); - } catch { - return targets.map((item) => ({ - ref: item.ref, - state: "unavailable", - provenance: { - source: "ready-for-agent", - observedAt, - repository: item.ref.split("#")[0], - error: "harness read failed", - }, - })); - } -} - -/** #1220: the coverage snapshot behind the /projects panel — computed - * from the feed's items + the Project pool, rotated weekly by - * nextCoverageSnapshot, persisted only when it actually changes. */ -async function coverageSnapshot( - census: RepoCensus[] | null, - pool: ProjectPoolItem[], - poolAvailable: boolean, -): Promise { - const stored = await coverageStore.read(); - const next = nextCoverageSnapshot(stored, computeCoverage(census, poolAvailable ? pool : null)); - const strip = (s: CoverageSnapshotFile | null): string => - s - ? JSON.stringify({ - baseline: s.baseline, - weekly: s.weekly ?? null, - anchorAt: s.anchorAt ?? "", - current: { ...s.current, generatedAt: "" }, - }) - : ""; - if (strip(next) !== strip(stored)) { - await coverageStore.write(next).catch(() => {}); - } - return next; -} -// #6815: the four formerly laptop-local stores (actions, activity -// ingestion, usage snapshots, aa-last-good) live in Turso when -// PM_AGG_STORE_BACKEND=turso. Exactly one backend is active: with -// "file" (the default) no remote exists and no database call is made. -const storeRemotes = cfg.storeBackend === "turso" ? createTursoRemotes(getTursoStoreClient) : null; -const actionsStore = new ActionsStore(cfg.actionsFile, undefined, storeRemotes?.actions); -// #1744 (Move 1, step 2): dashboard comments join the same switch — -// canonical in public.shared_comments under the turso backend. -const commentsStore = new CommentsStore(cfg.commentsFile, undefined, storeRemotes?.comments); -const viewsStore = new ViewsStore(cfg.viewsFile); -const eventsStore = new EventsStore(cfg.eventsFile); -const reportRecordsLocation = storeRemotes?.aaLastGood ?? defaultReportRecordsFile(); -const identityRegistryStore = new IdentityRegistryStore(cfg.identityRegistryFile); -const breakGlassTokenStore = new BreakGlassTokenStore(cfg.breakGlassFile); -const freshnessStore = new FreshnessStore(cfg.freshnessFile); - -/** #3976: the 5-minute anti-entropy reconciler over the freshness - * journal. Its one wired canonical reader is the fleet feed — the - * aggregator's own canonical source, fingerprinted exactly as the - * collector's notice identity (generatedAt + sha256 of the file). - * Its health view feeds /health + /api/health via healthContext. */ -const freshnessReconciler = new FreshnessReconciler(freshnessStore, [fleetFeedRevisionReader(cfg.feedFile)]); -const activityStore = new IngestionStore(cfg.activityFile, storeRemotes?.activity); -const githubHotListConsumer = - cfg.source === "live" && cfg.projector.baseUrl && cfg.projector.apiToken - ? new GithubHotListConsumer({ - baseUrl: cfg.projector.baseUrl, - token: cfg.projector.apiToken, - store: activityStore, - events: eventsStore, - }) - : null; - -/** #10910: the outcome consumer rides the same sweep as the hot-list - * consumer, under its own projector checkpoint: it projects each fixed - * high-water into the append-only outcome-fact ledger, joining events - * to jobs/sessions/models only through the binding records. */ -const githubOutcomeConsumer = - cfg.source === "live" && cfg.projector.baseUrl && cfg.projector.apiToken - ? new GithubOutcomeConsumer({ - baseUrl: cfg.projector.baseUrl, - token: cfg.projector.apiToken, - store: new OutcomeFactStore(cfg.outcomeFile), - bindings: new FileOutcomeBindingSource(cfg.outcomeBindingsFile), - }) - : null; - -async function githubActivityStatus(): Promise { - return ( - (await activityStore.sourceStatuses()).find((status) => status.source === "github") ?? unconfiguredGithubStatus() - ); -} - -function activitySourceStatusHtml(status: ActivitySourceStatus): string { - const cursorDistance = - status.checkpointCursor !== null && status.highWater !== null - ? Math.max(0, status.highWater - status.checkpointCursor) - : null; - const cursorText = status.cursor === null ? "not checkpointed" : String(status.cursor); - const checkpointText = status.checkpointCursor === null ? "not checkpointed" : String(status.checkpointCursor); - const highWaterText = status.highWater === null ? "unknown" : String(status.highWater); - const lagText = cursorDistance === null ? "unknown" : String(cursorDistance); - const escapeHtml = (value: string) => - value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); - const error = status.error ? `; detail: ${escapeHtml(status.error)}` : ""; - return ( - `

GitHub hot-list consumer: ${status.state}; processed cursor ${cursorText}; ` + - `acknowledged cursor ${checkpointText}; high-water ${highWaterText}; unacknowledged cursor distance ${lagText}; ` + - `last successful sweep ${escapeHtml(status.lastSuccessAt ?? "never")}${error}. ` + - `Current means caught up to the hot-list high-water, not complete GitHub history.

` - ); -} - -/** #1739: the event log's fire-and-forget sink for source-side - * writers (orchestration publishes, registry merges). Never awaited, - * never throws: a failed event write loses the event, nothing else. */ -function recordStreamEvent(event: Parameters[1]): void { - void emitEvent(eventsStore, event); -} - -/** #3321: the activity-ingestion sink for the source-side writers - * (watchdog episodes, Kaneo board changes, GitHub hot-list rows). Dedupe + checkpoints - * live in the store. The returned promise resolves true only when - * every delivery is durable (ingested or already seen): the live - * source awaits it as the acknowledgment that lets it discard its - * Kaneo baseline (Codex P2, PR #5141) — failed deliveries retain - * their cards' baseline entries so the next poll retries the same - * stable delivery ids, while acknowledged cards advance. */ -async function recordActivity( - deliveries: Parameters[2], -): Promise<{ failed: number; failedIds: string[] }> { - const result = await ingestActivity(activityStore, eventsStore, deliveries); - return { failed: result.failed, failedIds: result.failedIds }; -} - -/** #3977: source freshness notices are not #1739 activity records. - * This store is owned by the aggregator process; the projector and - * collector reach it only through the loopback publisher listener. */ -async function recordFreshness(input: FreshnessInput): Promise { - await freshnessStore.publish(input); -} - -/** #3321: the source-gap sink for the live source's polling gaps - * (Codex P2, PR #5141): a non-null `to` records (or extends) the - * open gap for the source; a null `to` is recovery — the open gap - * resolves as backfilled, since polling has resumed and the next - * diff lands against the preserved baseline. Never throws into the - * source's read path. */ -async function recordSourceGap(source: string, from: string, to: string | null): Promise { - try { - if (to !== null) { - await activityStore.recordGap(source, from, to); - return; - } - for (const gap of await activityStore.gaps()) { - if (gap.source === source && gap.status === "open") { - // Recovery happened now, not at the last failed poll: extend - // the gap window to the recovery moment as it resolves - // (Codex P2, PR #5141). - await activityStore.resolveGap(gap.id, "backfilled", new Date().toISOString()); - } - } - } catch (err) { - console.error( - `[activity] WARNING: source gap record failed for ${source}: ${err instanceof Error ? err.message : String(err)}`, - ); - } -} - -/** #3321: pins watchdog episodes to their first-observed `since` - * (Codex P2, PR #5141) — watchdogTierItems assigns `now` for - * several breach kinds, so without this the stream would gain a - * new "episode" on every attention render of one outage. */ -const watchdogEpisodes = new WatchdogEpisodeStabilizer(); -async function hasStreamEvent(kind: string, ref: string): Promise { - return eventsStore.has(kind, ref); -} - -function pickSource(): Source { - // #1290: the live source reads the standing delegation default from - // the actions store's preference records when it stamps the - // needs-user fallbacks onto tier items. - return cfg.source === "live" - ? liveSource(cfg, { - standingAuto: async () => effectiveStandingAuto(await actionsStore.all()).standingAuto, - onEvent: recordStreamEvent, - hasEvent: hasStreamEvent, - onActivity: recordActivity, - onFreshness: recordFreshness, - onSourceGap: recordSourceGap, - seenActivityIds: (source) => activityStore.seenIds(source), - snapshotRemote: storeRemotes?.usage, - onLaptopUnreachable: (detail) => { - fireOpenCodeWorkingHook("aggregator-tick", detail); - }, - }) - : fixtureSource(); -} - -const source = pickSource(); - -/** Lazy quota refresh (#1171): stale page/API loads ask the deployed - * gatherer unit to run again; single-flight + cooldown live in the module. */ -const quotaRefresher = createQuotaRefresher({ trigger: systemdTrigger() }); - -// #1279: prefer the latest-comment-per-ref read so a busy batch cannot -// truncate an item's most recent activity out of its brief. -const briefCommentsFor = async (refs: RefKey[]): Promise => - (source.latestComments ? source.latestComments(refs) : source.comments(refs)).catch(() => []); - -/** - * #1267: the live source populates its provenance strings lazily, one - * facet per method call — so a consumer that reads provenance() - * without exercising the facets (exactly what /api/health did) - * reports "fixtures" for facets that are really live, and its answer - * depends on which pages were visited since boot. Health therefore - * exercises every facet method before reading provenance. Priming is - * cached for 60 s (the #1147 probe-cache cadence): facet reads are - * mostly cache- or file-backed, and a watchdog polling health must - * not fan out to every upstream on every hit. Facet failures never - * fail health — a failed facet keeps its honest fallback string, - * which is precisely what health exists to report. - */ -let lastPrimedAt = 0; -/** #1141: item coverage measured by the latest priming pass (below), - * from the same board items() resolution that sets facet provenance. */ -let lastItemsCoverage: ItemsCoverage | null = null; -let priming: Promise | null = null; -async function ensureProvenancePrimed(): Promise { - if (Date.now() - lastPrimedAt < 60_000) return; - priming ??= (async () => { - try { - const { items } = await boardContext(); - lastItemsCoverage = summarizeItemCoverage(items); - const refs = [...items.keys()]; - await Promise.allSettled([ - source.roadmap(), - source.comments(refs), - source.quota(), - source.usage(), - source.attention(), - source.orchestration(), - source.dns(), - source.aa(), - source.registry(), - source.projects(), - ]); - } catch { - /* facets that failed keep their fallback strings — health reports those */ - } - lastPrimedAt = Date.now(); - priming = null; - })(); - await priming; -} - -/** - * The source-conflict inbox (#1282 slice 1), assembled from the same facets - * the rest of the dashboard reads. Read-only: detection collects what the - * facets already report, and no render changes because of it. - */ -async function assembleConflicts(): Promise { - const [pool, orchestration, usage] = await Promise.all([ - source.projects().catch(() => []), - source.orchestration().catch(() => null), - source.usage().catch(() => emptyUsageView()), - ]); - return conflictInbox({ pool, orchestration, services: usage.services }); -} - -/** - * The one health assembly behind both /health and /api/health - * (#1147): primed provenance first (so facet truth never depends on - * request order, #1267), then the feed snapshot the section ages and - * job lines are measured from, then buildHealth's probes (cached - * 60 s inside health.ts). Page and API read this same view, so they - * cannot disagree. - */ -async function healthContext(prime = true): Promise { - // Priming exercises every facet so /health provenance never depends - // on request order. Callers that only need the feed snapshot and the - // cached probes (the attention path's watchdog assembly, #1148) pass - // prime=false: a stalled unrelated facet (e.g. Grist's roadmap API - // and its 8s timeout) must not delay attention rendering (Codex P2 - // on PR #2431). The registry age the watchdog reads comes from the - // live source's lastFeed, which attention's own reads already load. - if (prime) await ensureProvenancePrimed(); - const [feed, feedFileMtimeMs, quota] = await Promise.all([ - loadFeed(cfg.feedFile).catch(() => null), - stat(cfg.feedFile) - .then((s) => s.mtimeMs) - .catch(() => null), - source.quota().catch(() => emptyQuotaView()), - ]); - return buildHealth({ - mode: cfg.source, - cfg, - feed, - feedFileMtimeMs, - quota, - diagnosis: source.diagnostics?.().orchestration, - detail: source.provenanceDetail?.(), - itemsCoverage: lastItemsCoverage, - comments: await commentsStore.pendingCounts().catch(() => undefined), - conflicts: await assembleConflicts().catch(() => null), - pushHealth: cfg.source === "fixtures" ? null : freshnessReconciler.health(new Date()), - slo: cfg.source === "fixtures" ? null : await sloSummaries(), - }); -} - -// SLO error budgets (#9988): summaries are read from the append-only journal -// and cached for a minute, the same cadence the sampler writes at. -const SLO_SUMMARY_CACHE_MS = 60_000; -async function sloSummaries(nowMs = Date.now()): Promise { - if (sloSummaryCache && nowMs - sloSummaryCache.at < SLO_SUMMARY_CACHE_MS) return sloSummaryCache.value; - const byFacet = groupSamplesByFacet(await sloJournal.readAll().catch(() => [])); - const value = SLO_DEFINITIONS.map((definition) => - summarizeSloFacet(definition, byFacet.get(definition.id) ?? [], nowMs), - ); - sloSummaryCache = { at: nowMs, value }; - return value; -} - -/** The identities half of the comment form options, behind a - * stale-while-revalidate cache (#5082, 2026-11-14). commentFormOpts - * is awaited on the request path of /program, /api/program.json and - * /board, and the registry read behind the identities merges the - * feed with a live map of the laptop OpenCode server — ~0.5 s when - * that server is healthy, but 6-10.5 s per call when it stalls under - * load (mapServerSessions' sequential fetches burn their 10 s - * aborts; a failed map was not cached, so every assembly paid the - * stall again). Pool-quota-steward run 381 measured the result: - * /program and /api/program.json 503 at ~10.5 s, /board 200 at - * 10.5 s, everything else fast. Identities are comment-form picker - * metadata — they change when sessions start or end, on a minutes - * timescale — so they take the same contract as the page - * assemblies: the first load is awaited (and warmed at boot, - * below); an expired entry serves stale behind a single-flight - * background refresh, so no request ever waits on the registry - * merge again. The per-request githubRefs half is never cached. */ -const commentIdentitiesCache = new TodayCache(TODAY_CACHE_TTL_MS); -async function commentIdentities(): Promise { - return commentIdentitiesCache.get(async () => { - const records = await source.registry().catch(() => []); - return identitiesFromRecords(records); - }); -} - -/** Author identities for the comment form: standing + registry sessions. */ -async function commentFormOpts(githubRefs: RefKey[] = []): Promise { - return { githubRefs, identities: await commentIdentities() }; -} - -/** Resolve a discuss-page title for any object ref, best-effort. */ -async function discussTitle(objectRef: string): Promise<{ title: string; githubRefs: RefKey[] }> { - if (objectRef.startsWith("gh:")) { - const ref = objectRef.slice(3); - const items = await source.items([ref]).catch(() => new Map()); - return { title: items.get(ref)?.title ?? `Comments — ${ref}`, githubRefs: [ref] }; - } - if (objectRef.startsWith("session:")) { - const id = objectRef.slice("session:".length); - const records = await source.registry().catch(() => []); - const rec = records.find((r) => r.id === id); - return { title: `Comments — ${rec?.label ?? id}`, githubRefs: rec?.taskRefs ?? [] }; - } - if (objectRef.startsWith("orch:")) { - const id = objectRef.slice("orch:".length); - const section = await source.orchestration().catch(() => null); - const item = [...(section?.tiers.needsDrew ?? []), ...(section?.tiers.needsOrchestrator ?? [])].find( - (i) => i.id === id, - ); - return { - title: `Comments — ${item?.title ?? id}`, - githubRefs: item?.ref ? [item.ref] : [], - }; - } - const [board, rows] = await Promise.all([source.board().catch(() => []), source.roadmap().catch(() => [])]); - const item = board.find((b) => b.id === objectRef); - if (item) return { title: `Comments — ${item.title}`, githubRefs: item.links.map((l) => l.ref) }; - const row = rows.find((r) => r.subject === objectRef); - if (row) return { title: `Comments — ${row.title}`, githubRefs: row.links.map((l) => l.ref) }; - return { title: `Comments — ${objectRef}`, githubRefs: [] }; -} - -function json(body: unknown, status = 200): Response { - return new Response(JSON.stringify(body, null, 2), { - status, - headers: { "content-type": "application/json; charset=utf-8" }, - }); -} - -/** Same response shape as {@link json} without the 2-space pretty-print: - * the board JSON legitimately carries seconds of data and the pretty - * form adds ~10% bytes for nothing a machine consumer reads (#5082). */ -function jsonCompact(body: unknown, status = 200): Response { - return new Response(JSON.stringify(body), { - status, - headers: { "content-type": "application/json; charset=utf-8" }, - }); -} - -function html(body: string, status = 200): Response { - return new Response(body, { status, headers: { "content-type": "text/html; charset=utf-8" } }); -} - -// The real service worker (#3676 — design 2026-11-01T03-54-00Z §6 -// step 2): push + notificationclick handlers, with the kill switch's -// eviction job carried forward per the §6 fallback (cache purge on -// activate in the worker; foreign-registration unregister in the -// page-side probe script). Worker source + history: src/sw-source.ts. -function serviceWorkerResponse(): Response { - return new Response(SW_SOURCE, { - headers: { "content-type": "text/javascript; charset=utf-8", "cache-control": "no-cache" }, - }); -} - -// --- Alert throat (#3676) ------------------------------------------------- - -/** Bearer check for POST /api/alerts: the intake token is resolved - * by name from Bitwarden (pm-aggregator.alerts-intake-token) and - * compared in constant time; its value is never logged. */ -async function alertsIntakeAuthorized(req: Request): Promise { - const header = req.headers.get("authorization") ?? ""; - const presented = header.startsWith("Bearer ") ? header.slice("Bearer ".length).trim() : ""; - if (!presented) return false; - const expected = await resolveBwsSecret("pm-aggregator.alerts-intake-token"); - if (!expected) return false; - const a = Buffer.from(presented); - const b = Buffer.from(expected); - return a.length === b.length && timingSafeEqual(a, b); -} - -const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - -// --- Needs-Drew questions (#8568) ------------------------------------------ - -/** The token-carrying answer-page URL for a raised question. */ -function needsDrewAnswerUrl(item: NeedsDrewQuestion): string { - return `${cfg.publicOrigin}/answer/${encodeURIComponent(item.ledgerId)}?t=${item.token}`; -} - -const ANSWER_PAGE_STYLE = ``; - -/** Render GET /answer/. The caller has already verified the - * token; the 403 shape renders nothing about the question. */ -function renderAnswerPage(item: NeedsDrewQuestion): string { - const links = item.links - .filter((l) => /^https?:\/\//.test(l)) - .map((l) => `${esc(l)}`) - .join(""); - if (item.answer) { - const chosen = item.answer.optionId - ? (item.options.find((o) => o.id === item.answer?.optionId)?.label ?? item.answer.optionId) - : null; - return ` -Answered — PM Stack${ANSWER_PAGE_STYLE} -

${esc(item.question)}

-

Answered${chosen ? `: ${esc(chosen)}` : ""}.

-${item.answer.freeText ? `

${esc(item.answer.freeText)}

` : ""} -

Recorded at ${esc(item.answer.at)} — the fleet worker has been unblocked.

-
`; - } - const buttons = item.options - .map((o) => ``) - .join(""); - return ` -Needs Drew — PM Stack${ANSWER_PAGE_STYLE} -

${esc(item.question)}

-${item.context ? `

${esc(item.context)}

` : ""} -${links ? `` : ""} -
${buttons}
- - -

- -
`; -} - -function renderAnswerForbidden(): string { - return ` -Not available — PM Stack${ANSWER_PAGE_STYLE} -

Answer link not available

-

This answer link is unknown or its token does not match. Nothing about the question is shown without the correct link.

-
`; -} - -// --- Decision sets (#8766) ------------------------------------------------- - -/** The token-carrying decisions-page URL for a raised set. */ -function decisionsPageUrl(set: DecisionSet): string { - return `${cfg.publicOrigin}/decisions/${encodeURIComponent(set.setId)}?t=${set.token}`; -} - -/** - * The live Questions section for Today / Needs-you (#9354): reads the - * decision-set store at request time, keeps sets with open questions, - * newest first. A store read failure renders the honest unavailable - * section (questionsSectionHtml(null, ...)), never a confident zero. - * (listDecisionSets itself reads an absent/corrupt store as empty, - * following the store's existing contract.) - */ -async function questionsHtml(): Promise { - try { - const sets = await listDecisionSets(cfg.decisionsFile); - const byId = new Map(sets.map((s) => [s.setId, s])); - const summaries = sets - .map((s) => decisionSetSummary(s)) - .filter((s) => s.openQuestions > 0) - .sort((a, b) => b.createdAt.localeCompare(a.createdAt)); - return questionsSectionHtml(summaries, (s) => { - const set = byId.get(s.setId); - return set ? decisionsPageUrl(set) : `/decisions/${encodeURIComponent(s.setId)}`; - }); - } catch { - return questionsSectionHtml(null, () => "/decisions"); - } -} - -/** Append decision-set events (#9335 v2): best-effort — an event-log - * failure is logged and never fails the interaction it records. */ -async function logDecisionEvents(inputs: DecisionEventInput[]): Promise { - if (!inputs.length) return; - try { - await appendDecisionEvents(cfg.decisionsEventsFile, cfg.decisionsOutboxFile, inputs); - } catch (err) { - console.error(`decision events: append failed (${err instanceof Error ? err.message : "error"})`); - } -} - -function questionRefFor( - set: DecisionSet, - ledgerId: string, - qid: string, -): { ledgerId: string; qid: string; questionIndex?: number } { - const item = set.items.find((i) => i.ledgerId === ledgerId); - const idx = item ? item.questions.findIndex((q) => q.qid === qid) : -1; - return { ledgerId, qid, ...(idx >= 0 ? { questionIndex: idx + 1 } : {}) }; -} - -function eventTypeForKind(kind: DecisionSubmission["kind"]): "submit" | "defer" | "request-info" { - return kind === "answered" ? "submit" : kind === "deferred" ? "defer" : "request-info"; -} - -function submissionEventPayload(sub: DecisionSubmission): Record { - return { - kind: sub.kind, - ...(sub.optionId ? { optionId: sub.optionId } : {}), - ...(sub.optionIds ? { optionIds: sub.optionIds } : {}), - ...(sub.freeText ? { freeText: sub.freeText.slice(0, 2000) } : {}), - ...(sub.customAnswer ? { customAnswer: sub.customAnswer.slice(0, 2000) } : {}), - ...(sub.lean ? { lean: sub.lean } : {}), - ...(sub.note ? { note: sub.note.slice(0, 2000) } : {}), - ...(sub.comment ? { comment: sub.comment.slice(0, 2000) } : {}), - }; -} - -/** Parse a decisions submissions array — shared by /submit and by - * /defer's filled-answers-win payload (#8766). */ -function parseDecisionSubmissions( - raw: unknown, -): { ok: true; value: DecisionSubmission[] } | { ok: false; error: string } { - if (!Array.isArray(raw) || raw.length < 1 || raw.length > 256) { - return { ok: false, error: "submissions must be an array of 1-256 entries" }; - } - const submissions: DecisionSubmission[] = []; - for (const entry of raw) { - if (!entry || typeof entry !== "object" || Array.isArray(entry)) { - return { ok: false, error: "submissions entries must be objects" }; - } - const s = entry as Record; - const ledgerId = typeof s.ledgerId === "string" ? s.ledgerId : ""; - const qid = typeof s.qid === "string" ? s.qid : ""; - const kind = s.kind; - if (!ledgerId || !qid || (kind !== "answered" && kind !== "deferred" && kind !== "request-info")) { - return { ok: false, error: "submissions entries require ledgerId, qid and kind answered|deferred|request-info" }; - } - if (kind === "deferred" && !isDeferLean(s.lean)) { - return { ok: false, error: "deferred submissions require a lean of none|skeptical|approve" }; - } - submissions.push({ - ledgerId, - qid, - kind, - ...(typeof s.optionId === "string" ? { optionId: s.optionId } : {}), - ...(Array.isArray(s.optionIds) - ? { optionIds: s.optionIds.filter((x): x is string => typeof x === "string") } - : {}), - ...(typeof s.freeText === "string" ? { freeText: s.freeText } : {}), - ...(typeof s.customAnswer === "string" ? { customAnswer: s.customAnswer } : {}), - ...(isDeferLean(s.lean) ? { lean: s.lean } : {}), - ...(typeof s.note === "string" ? { note: s.note } : {}), - ...(typeof s.comment === "string" ? { comment: s.comment } : {}), - }); - } - return { ok: true, value: submissions }; -} - -const DECISIONS_PAGE_STYLE = `${ANSWER_PAGE_STYLE}`; - -/** Render GET /decisions/. The caller has already verified the - * token; the 403 shape renders nothing about the set. Only open - * questions are interactive; resolved ones show as a compact recorded - * line. An item whose questions are all resolved renders as a - * submitted card, hidden by default (Drew, 2026-11-13): the page's - * "Show submitted items" toggle brings it back for review, since the - * page has no undo. */ -function renderDecisionsPage(set: DecisionSet): string { - const progress = decisionSetProgress(set); - const groups: string[] = []; - for (const item of set.items) if (!groups.includes(item.group)) groups.push(item.group); - const itemCard = (item: DecisionItem): string => { - const open = item.questions.filter((q) => !q.resolution); - const links = item.links - .filter((l) => /^https?:\/\//.test(l)) - .map((l) => `${esc(l)}`) - .join(""); - const resolvedLines = item.questions - .filter((q) => q.resolution) - .map((q) => { - const r = q.resolution!; - const what = - r.kind === "deferred" - ? `deferred to the orchestrator${r.lean && r.lean !== "none" ? ` (lean: ${esc(r.lean)})` : ""}${r.optionLabel ? ` — your tentative pick: ${esc(r.optionLabel)}` : ""}${r.comment ? ` — comment: ${esc(r.comment)}` : ""}` - : r.kind === "request-info" - ? `more information requested${r.note ? ` — you said: ${esc(r.note)}` : ""}` - : `answered${ - r.optionLabels && r.optionLabels.length > 1 - ? `: ${esc(r.optionLabels.join(" + "))}` - : r.optionLabel - ? `: ${esc(r.optionLabel)}` - : r.freeText - ? `: ${esc(r.freeText)}` - : "" - }${r.customAnswer ? ` — own answer: ${esc(r.customAnswer)}` : ""}`; - return `
✓ ${esc(q.question)} — ${what}
`; - }) - .join(""); - if (open.length === 0) { - return ``; - } - const sortedOpen = open - .map((q, i) => ({ q, i })) - .sort((a, b) => (a.q.order ?? a.i) - (b.q.order ?? b.i)) - .map((x) => x.q); - const questionBlocks = sortedOpen - .map((q) => { - const mode = effectiveQuestionMode(q); - const recommended = q.recommendedOptionIds ?? []; - const chips = (tags?: string[]): string => - (tags ?? []).map((t) => `${esc(t)}`).join(""); - const inputs = q.options - .map((o) => { - const combo = - o.combinationOf && o.combinationOf.length - ? ` combines ${o.combinationOf - .map((cid) => esc(q.options.find((x) => x.id === cid)?.label ?? cid)) - .join(" + ")}` - : ""; - const isReco = recommended.includes(o.id); - return ``; - }) - .join(""); - return `
-

${esc(q.question)}${chips(q.tags)}

-${q.description ? `
${esc(q.description)}
` : ""} -${q.infoProvided ? `

Information you requested

${esc(q.infoProvided)}

` : ""} -${q.context ? `

${esc(q.context)}

` : ""} -${recommended.length ? `

Recommended default preselected — it is not recorded until you submit.

` : ""} -${inputs} - - - - -
`; - }) - .join(""); - const submitBtn = (cls: string): string => - ``; - return `
- -

${esc(item.title)}

-${links ? `` : ""} -${resolvedLines} -${open.length > 1 ? submitBtn("submit top") : ""} -${questionBlocks} -${submitBtn("submit")} -
`; - }; - const isSubmittedItem = (i: DecisionItem): boolean => i.questions.every((q) => q.resolution); - const submittedCount = set.items.filter(isSubmittedItem).length; - const body = groups - .map((g) => { - const groupItems = set.items - .filter((i) => i.group === g) - .map((item, i) => ({ item, i })) - .sort((a, b) => (a.item.order ?? a.i) - (b.item.order ?? b.i)) - .map((x) => x.item); - const cards = groupItems.map(itemCard).join(""); - const allSubmitted = groupItems.length > 0 && groupItems.every(isSubmittedItem); - return cards ? `
${esc(g)}
${cards}` : ""; - }) - .join(""); - const caughtUp = progress.openQuestions === 0; - return ` -Decisions — PM Stack${DECISIONS_PAGE_STYLE} -

${esc(set.title)}

-

${progress.openQuestions} question${progress.openQuestions === 1 ? "" : "s"} open across ${progress.openItems} item${progress.openItems === 1 ? "" : "s"} · ${progress.answered} answered · ${progress.deferred} deferred · ${progress.infoRequested} sent back for more information so far. Fill in what you want — you can submit a partially-filled item; what you filled in is recorded and the rest stays here.

-${caughtUp ? `

All caught up — every question in this set has been answered or sent back. Nothing left on this page.

` : ""} - -${body} -
-

Bulk actions

- - -

Submit defaults records the raiser's recommended preselection for every open question that has one (plus any "my own answer" text you typed on those questions). Preselected defaults are shown selected, but they are NOT an answer until you submit them.

-

Defer checked items to the orchestrator instead of answering — they leave this page and become the orchestrator's job. Precedence per question: (1) the question's own defer setting wins, with its tentative pick and comment riding along as guidance; (2) a filled-in answer submits as an answer; (3) only a question nobody touched uses the default flavor picked here:

- - - -

Or request more information for the checked items — they leave this page and come back in a later set once the information has been gathered:

- - -
-

- -
`; -} - -/** Render GET /decisions — the decision-sets index (#8867). Lists every - * set in the store with counts live from decisionSetSummary (the same - * numbers the set page itself reports), in today / this-week / all - * views with an open-only toggle, newest first. Each row links to the - * set's own token-carrying page; the index carries no token of its own - * and sits behind the same access as every other aggregator page - * (tailnet origin / Cloudflare Access on pm.security.cab) — no new - * public surface, and the per-set token model is untouched. */ -const CHICAGO_STAMP = new Intl.DateTimeFormat("en-US", { - timeZone: "America/Chicago", - year: "numeric", - month: "short", - day: "numeric", - hour: "numeric", - minute: "2-digit", - timeZoneName: "short", -}); - -function renderDecisionsIndex(allSets: DecisionSet[], view: DecisionSetView, openOnly: boolean): string { - const inView = decisionSetsForView(allSets, view); - const visible = openOnly ? inView.filter((s) => decisionSetSummary(s).openQuestions > 0) : inView; - const totalOpen = inView.reduce((n, s) => n + decisionSetSummary(s).openQuestions, 0); - const viewTab = (v: DecisionSetView, label: string): string => - v === view - ? `${label}` - : `${label}`; - const toggle = openOnly - ? `Open only · Show all` - : `Open only`; - const rows = visible - .map((set) => { - const s = decisionSetSummary(set); - const stamp = Number.isFinite(Date.parse(s.createdAt)) - ? CHICAGO_STAMP.format(new Date(s.createdAt)) - : s.createdAt; - const breakdown = `${s.answered} answered · ${s.deferred} deferred · ${s.infoRequested} sent back for more info`; - const state = s.fullyResolved ? `all settled — ${breakdown}` : `${s.openQuestions} open · ${breakdown}`; - return `

${esc(s.title)}

-

Raised ${esc(stamp)} · ${s.items} item${s.items === 1 ? "" : "s"} · ${s.questions} question${s.questions === 1 ? "" : "s"} · ${state}

-

Set ${esc(s.setId)}

`; - }) - .join(""); - const empty = - allSets.length === 0 - ? `

No decision sets have been raised yet.

` - : `

No sets in this view${openOnly ? " with open questions" : ""}.

`; - return ` -Decision sets — PM Stack${DECISIONS_PAGE_STYLE} -

Decision sets

-

${inView.length} set${inView.length === 1 ? "" : "s"} · ${totalOpen} question${totalOpen === 1 ? "" : "s"} open. Newest first. Each set opens its own page — the same link its push notification carried.

-

${viewTab("today", "New today")} · ${viewTab("week", "This week")} · ${viewTab("all", "All")}  |  ${toggle}

-${visible.length ? rows : empty} -
`; -} - -function renderDecisionsForbidden(): string { - return ` -Not available — PM Stack${ANSWER_PAGE_STYLE} -

Decisions link not available

-

This decisions link is unknown or its token does not match. Nothing about the set is shown without the correct link.

-
`; -} - -/** The PWA manifest (#3315 slice a, landed with #3676): start_url is - * the attention view per the design; icons incl. maskable + iOS. */ -const PWA_MANIFEST = { - name: "PM Aggregator", - short_name: "PM Stack", - description: "The PM-stack aggregator: needs-you queues, quotas, health \u2014 and the alert throat.", - start_url: "/attention", - scope: "/", - display: "standalone", - background_color: "#0e1117", - theme_color: "#161b22", - icons: [ - { src: "/icons/icon-192.png", sizes: "192x192", type: "image/png", purpose: "any" }, - { src: "/icons/icon-512.png", sizes: "512x512", type: "image/png", purpose: "any" }, - { src: "/icons/icon-maskable-512.png", sizes: "512x512", type: "image/png", purpose: "maskable" }, - ], -}; - -/** #1211: the fail-soft facet fallbacks — an empty view is the honest - * degraded form of a facet whose read threw (the renderers already - * banner absent data, e.g. buildAttention's tier-source-missing - * flag); a throwing facet must never 500 a whole page. */ -function emptyQuotaView(): QuotaView { - return { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }; -} -function emptyUsageView(): UsageView { - return { - services: [], - uninstrumentedServices: [], - payg: [], - charges: [], - attention: [], - domains: null, - subscriptions: [], - history: {}, - }; -} - -async function loadBoardContext() { - const board = await source.board().catch(() => []); - const refs = allRefs(board); - const items = await source.items(refs).catch(() => new Map()); - return { board, items }; -} - -// #5082: the board assembly is the stack's most expensive read — a -// Kaneo login + poll with per-project task pagination, one projector -// /links call per card, and the items() closure over every ref — and -// every board-family request used to pay it in full. Under ordinary -// fleet load the assembly outlives the 10 s dashboard deadline -// (assembly-deadline.ts), so /board, /api/board.json, and the overview -// (which embeds the board) 503'd even with every upstream healthy; -// concurrent cold loads each started their own assembly and multiplied -// the damage (measured 2026-11-08: 3 concurrent -> 3 assemblies, all -// 503). The assembly now gets the /today contract (#1179): a short TTL -// serves warm hits from the last successful read, and concurrent cold -// requests share one in-flight load. -// -// The cache sits BELOW the variant split, which is what makes it safe -// for every consumer: ?done=all, saved-view filters, and the HTML/JSON -// renderers are all derived per request from this one context -// (boardJsonBody / boardJsonViewBody / renderBoard), so no variant can -// ever be served another variant's body. Provenance stays truthful the -// same way it does for /today: prov()/provDetail() are still read live -// per request at the call sites. Fail-soft fallbacks (an empty board -// when Kaneo is down) are the honest degraded state of the read and -// are cached as-is until expiry, exactly as #1179 documents; a -// throwing load is never cached. -const boardContextCache = new TodayCache>>(TODAY_CACHE_TTL_MS); -async function boardContext(): Promise>> { - return boardContextCache.get(loadBoardContext); -} - -/** All shared forecast contracts (#3984): epic-completion + stall-risk - * per epic subject from the stored item history (#3981), and one - * quota-exhaustion contract per quota pool. The rate for a pool is - * only usable when the gatherer measured a token burn for a token - * window with ok freshness — anything else stays the contract's - * first-class quota_rate_unavailable state, never an invented date. */ -async function allForecastContracts( - pool: ProjectPoolItem[], -): Promise<{ byRef: Map; contracts: ForecastContract[] }> { - const byRef = new Map(); - const contracts: ForecastContract[] = []; - const add = (c: ForecastContract) => { - contracts.push(c); - byRef.set(c.subjectRef, [...(byRef.get(c.subjectRef) ?? []), c]); - }; - const cutoffs = await itemHistoryStore.readAll().catch(() => []); - if (cutoffs.length) { - const poolByRef = new Map(pool.map((it) => [it.ref, it])); - const subjects = new Set(); - for (const cutoff of cutoffs) { - for (const item of cutoff.items) { - if (item.parentRef) subjects.add(item.parentRef); - } - } - for (const subjectRef of subjects) { - const poolItem = poolByRef.get(subjectRef); - const statusDisagreement = - poolItem && - poolItem.status && - ((poolItem.state === "closed" && poolItem.status !== "Done") || - (poolItem.state === "open" && poolItem.status === "Done")) - ? `GitHub state ${poolItem.state} disagrees with Project Status ${poolItem.status}; both are shown, neither is preferred` - : null; - for (const c of subjectForecastContracts(cutoffs, subjectRef, { - updatedAt: poolItem?.updatedAt ?? null, - statusDisagreement, - scope: `direct native children of ${subjectRef} in the Project #4 pool item history (curated pool scope, not a repo-wide backlog)`, - })) { - add(c); - } - } - } - const quota = await source.quota().catch(() => emptyQuotaView()); - const asOf = new Date().toISOString(); - for (const qpool of quota.pools) { - const window = qpool.windows - .filter((w) => w.limit !== null && w.limit > 0) - .sort((a, b) => (b.percent ?? 0) - (a.percent ?? 0))[0]; - const rate = - window && window.unit === "tokens" && qpool.burnTokensPerMin != null && qpool.freshness?.state === "ok" - ? { amountPerHour: qpool.burnTokensPerMin * 60, observedAt: qpool.freshness.measuredAt } - : null; - add( - quotaForecastContract({ - poolId: qpool.id, - provider: qpool.provider, - asOf, - unit: window?.unit ?? "tokens", - remainingAmount: window ? window.limit! - window.used : null, - limitAmount: window?.limit ?? null, - nextReset: window?.resetsAt ?? null, - rate, - scope: `quota pool ${qpool.id} (${qpool.provider}/${qpool.plan})`, - }), - ); - } - return { byRef, contracts }; -} - -async function roadmapContext() { - const rows = await source.roadmap().catch(() => []); - const refs = allRefs(rows); - const [items, poolResult] = await Promise.all([ - source.items(refs).catch(() => new Map()), - source.projects().then( - (pool) => ({ pool, failed: false }), - () => ({ pool: [] as ProjectPoolItem[], failed: true }), - ), - ]); - // #1144: reconcile the Grist rows against the Project's Kind=Epic - // pool items on every roadmap read, so the page flag and the JSON - // drift report always describe the same pass as the rows themselves. - // Codex P2 on PR 2428: an unread source is NOT an empty source — in - // live mode, a Grist fixtures fallback or a fleet feed with no - // projects section means reconciliation is unavailable, and no - // drift may be asserted from it. - let reconciliation: RoadmapReconciliation; - if (cfg.source === "live") { - const reasons: string[] = []; - const roadmapProv = source.provenance().roadmap; - if (!roadmapProv.startsWith("live")) reasons.push(`Grist roadmap read unavailable (${roadmapProv})`); - if (poolResult.failed) reasons.push("Project pool read failed"); - const feed = await loadFeed(cfg.feedFile).catch(() => null); - if (!feed) reasons.push("fleet feed unreadable — Project pool availability unknown"); - else if (feed.projects === undefined) - reasons.push("fleet feed carries no projects section — Project pool availability unknown"); - reconciliation = reasons.length - ? unavailableRoadmapReconciliation(reasons.join("; ")) - : reconcileRoadmap(rows, poolResult.pool); - } else { - reconciliation = reconcileRoadmap(rows, poolResult.pool); - } - // #1168: the drill-down index rides the same pass as the - // reconciliation, and only exists when the reconciliation is - // available — an unavailable source must not render as "no epic yet". - const drill = - reconciliation.availability === "available" ? buildRoadmapDrill(rows, reconciliation, poolResult.pool) : undefined; - return { rows, items, pool: poolResult.pool, reconciliation, drill }; -} - -async function searchContext(query: string) { - // #1212 slice 2: registry, DNS, services, and tier items join the - // board/roadmap subjects. Each extra source fails soft (empty on - // error) so one broken source never takes search down with it. - const [board, rows, registry, dns, usage, orchestration] = await Promise.all([ - source.board(), - source.roadmap(), - source.registry().catch(() => []), - source.dns().catch(() => null), - source.usage().catch(() => null), - source.orchestration().catch(() => null), - ]); - const tierItems = orchestration ? [...orchestration.tiers.needsDrew, ...orchestration.tiers.needsOrchestrator] : []; - // Codex P2 on PR #7331: refs carried only by the slice-2 sources - // (registry taskRefs, tier-item refs) join the resolution set, or - // their search badges always render unresolved even when the live - // pool/projector could resolve them. - const extraRefs = [...registry.flatMap((record) => record.taskRefs), ...tierItems.map((item) => item.ref)].filter( - isValidRef, - ); - const refs = [...new Set([...allRefs(board), ...allRefs(rows), ...extraRefs])]; - const items = await source.items(refs); - const extras = { registry, dns, services: usage?.services ?? [], tierItems }; - return { query, results: searchWork(board, rows, items, query, extras), items }; -} - -// #3321: watchdog gap-sync passes run whole and in observation -// order through this queue (Codex P2, PR #5141 round 5) — see -// createWatchdogGapSyncQueue in activity.ts for why the bare -// fire-and-forget sync interleaved. -const enqueueWatchdogGapSync = createWatchdogGapSyncQueue(); -const watchdogHeartbeatRecorder = createWatchdogHeartbeatRecorder(async (nowMs) => { - await sloJournal.append([watchdogHeartbeatLine(nowMs)]); -}); - -/** Record liveness only after a watchdog derivation completes. A timer here - * would stay green even if the watchdog work itself stopped making progress. */ -async function recordWatchdogHeartbeat(nowMs: number, scheduled = false): Promise { - try { - await (scheduled ? watchdogHeartbeatRecorder.scheduled(nowMs) : watchdogHeartbeatRecorder.request(nowMs)); - } catch (error) { - console.error( - `[watchdog] WARNING: heartbeat append failed: ${error instanceof Error ? error.message : String(error)}`, - ); - } -} - -// #1148: the watchdog derives NEEDS ORCHESTRATOR items from the -// current diagnoses (feed age + probes via the health assembly — -// its probe cache keeps this cheap — plus the orchestration -// diagnosis and registry facet age). Live mode only: fixtures mode -// has no real inputs to watch. Derived on attention reads and on the -// server-owned watchdog tick below, so it does not depend on dashboard -// traffic. Recovery clears the cards on the next derivation. The health -// assembly here is deliberately UNPRIMED (see healthContext): the -// watchdog needs only the feed file, the cached probes, and the -// registry age from the source's already-loaded feed. -async function deriveWatchdogItems( - diagnosis?: ReturnType>["orchestration"], - mode: "request" | "scheduled" = "request", -) { - if (cfg.source !== "live") return []; - const [health, projectAudit, hostHealth] = await Promise.all([ - healthContext(false), - source.projectAudit ? source.projectAudit().catch(() => null) : Promise.resolve(null), - // #10141: the host-health collector's snapshot (claimant mode + - // PM unit states). A read failure yields null, which the watchdog - // surfaces as the snapshot-absent item — the surfacer's own - // silence is a breach, never a pass. - readHostHealthSnapshot(cfg.hostHealthFile).catch(() => null), - ]); - const items = watchdogTierItems({ - now: Date.now(), - feedAgeMs: health.feed.ageMs, - feedGeneratedAt: health.feed.generatedAt, - ...(diagnosis ? { orchestration: diagnosis } : {}), - projectAudit, - ...(source.provenanceDetail ? { registryAgeMs: source.provenanceDetail().registry.ageMs } : {}), - probes: health.services - .filter((s) => WATCHDOG_PROBE_SERVICE_IDS.includes(s.def.id)) - .map((s) => ({ - id: s.def.id, - name: s.def.name, - ok: s.ok, - detail: s.detail, - ...(s.probedAt ? { probedAt: s.probedAt } : {}), - })), - hostHealth, - }); - // #3321: every derivation is also an ingestion pass — the current - // breach episodes go to the stream (dedupe makes re-derivation a - // no-op) and the gap records sync with the breach set. Episodes - // are stabilized first (first-observed `since` wins until the - // breach clears), so one continuous outage is one delivery. - const stableItems = watchdogEpisodes.stabilize(items); - void recordActivity(watchdogDeliveries(stableItems)); - await finishWatchdogGapSync({ - items, - sync: enqueueWatchdogGapSync(activityStore, stableItems), - mode, - recordHeartbeat: () => recordWatchdogHeartbeat(Date.now(), mode === "scheduled"), - onError: (err) => { - console.error( - `[activity] WARNING: watchdog gap sync failed: ${err instanceof Error ? err.message : String(err)}`, - ); - }, - }); - return items; -} - -async function loadAttentionContext(opts: { census?: boolean } = {}) { - // #1226/#3970: the Needs-Drew census costs up to eight sequential - // GitHub search calls (up to ~64 s when the API is unreachable). Only - // the attention page render consumes it, so it opts in; the overview, - // Today, /api/attention.json and /api/coverage.json must not inherit - // that external dependency (Codex P2 on PR #3970). - const wantsCensus = shouldFetchNeedsDrewCensus(opts); - const [feed, summary, coverage, census] = await Promise.all([ - source.attention().catch(() => []), - source.orchestration().catch(() => null), - source.coverage().catch(() => []), - // A source without the census (or a failed sweep) yields null and - // the view renders it as unavailable, never as an empty queue. - wantsCensus - ? ((source.needsDrew?.() ?? Promise.resolve(null)).catch(() => null) as Promise) - : Promise.resolve(null), - ]); - // Read the diagnosis AFTER orchestration() has run: the live source - // recomputes it on every orchestration read (#1139). - const diagnosis = source.diagnostics?.().orchestration; - const watchdog = await deriveWatchdogItems(diagnosis); - const quota = await source.quota().catch(() => null); - const view = buildAttention(feed, summary, Date.now(), diagnosis, watchdog); - // #1174: the same eligible quota actions as /quota's strip and - // /today, as orchestrator-tier task items — derived once here from - // the same pure function, so entries clear on every surface the - // moment their source condition no longer holds. - const quotaItems = quota ? quotaActionTierItems(buildQuotaActions(quota, AA_PLAN_FACTS)) : []; - if (quota) { - view.orchestratorExtra = [...view.orchestratorExtra, ...quotaItems]; - } - return { - view, - quotaItems, - coverage, - orchestration: summary, - diagnosis, - census, - }; -} - -// #9850: /api/attention.json is a sentinel-probed health surface, but -// the assembly above re-reads every source leg on every request — under -// load that per-request cost is what flapped the feed (multi-second -// answers at load ~10). Same contract as the today/overview assemblies -// (#5082): a short-TTL cache with coalesced loads and -// stale-while-revalidate, one cache per census variant — the census -// assembly costs up to ~64 s of GitHub search calls and must never -// ride the JSON path, or vice versa. -const attentionContextCache = new TodayCache>>(TODAY_CACHE_TTL_MS); -const attentionCensusContextCache = new TodayCache>>( - TODAY_CACHE_TTL_MS, -); -async function attentionContext(opts: { census?: boolean } = {}) { - return opts.census - ? attentionCensusContextCache.get(() => loadAttentionContext(opts)) - : attentionContextCache.get(() => loadAttentionContext(opts)); -} - -/** - * One Datastar patch-elements event (#1444). The fragment root carries - * its own id + `data-on:dashrefresh__window` refresh hook, so "outer" - * mode replaces the shell's placeholder with a self-refreshing - * container. The payload deliberately carries NO `data-init` (#10605): - * an outer-mode patch re-mounts the element, so an init trigger inside - * the payload would fetch itself again on every patch — a loop. First - * paint is driven by the shell placeholder's `data-init` instead. - */ -function ssePatch(selector: string, elementHtml: string): string { - const lines = elementHtml - .split("\n") - .map((l) => `data: elements ${l}`) - .join("\n"); - return `event: datastar-patch-elements\ndata: mode outer\ndata: selector ${selector}\n${lines}\n\n`; -} - -function sseResponse(body: string): Response { - return new Response(body, { - headers: { "content-type": "text/event-stream; charset=utf-8", "cache-control": "no-cache" }, - }); -} - -/** The render inputs the board page and its fragment share. */ -async function boardRender() { - const { board, items } = await boardContext(); - const [pool, orchestration, formOpts, actionsByObject, counts] = await Promise.all([ - source.projects().catch(() => []), - source.orchestration().catch(() => null), - commentFormOpts(), - actionsStore.byObject(), - commentsStore.countsDetailed(), - ]); - const poolByRef = new Map(pool.map((p) => [p.ref, p])); - const refs = [ - ...new Set(board.flatMap((item) => item.links.map((link) => link.ref)).filter((ref) => poolByRef.has(ref))), - ]; - const comments = refs.length ? await briefCommentsFor(refs) : []; - const orchestrationStatus = source.diagnostics?.().orchestration.state; - const briefs = buildBriefs(pool, { comments, orchestration, orchestrationStatus }); - const act = { - actionsByObject, - poolByRef, - identities: formOpts.identities, - briefs, - }; - return { board, items, counts, act }; -} - -/** The render inputs the attention page and its fragments share: - * the view, the action/comment stores grouped by object, and the - * effective Needs-you order preference (#1456). */ -async function attentionRender() { - const { view, coverage, orchestration, diagnosis, census } = await attentionContext({ census: true }); - const [pool, formOpts, actionsByObject, commentsByObject, counts, allActions] = await Promise.all([ - source.projects().catch(() => []), - commentFormOpts(), - actionsStore.byObject(), - commentsStore.byObject(), - commentsStore.countsDetailed(), - actionsStore.all(), - ]); - const order = effectiveNeedsOrder(allActions); - const refs = [ - ...new Set([...view.drewExtra, ...view.orchestratorExtra].flatMap((item) => (item.ref ? [item.ref] : []))), - ]; - const comments = refs.length ? await briefCommentsFor(refs) : []; - const briefs = buildBriefs(pool, { comments, orchestration, orchestrationStatus: diagnosis?.state }); - const act = { - actionsByObject, - identities: formOpts.identities, - commentsByObject, - commentOpts: formOpts, - needsOrder: order.order, - needsOrderPending: order.pending, - }; - return { view, coverage, counts, act, briefs, census }; -} - -async function loadTodaySignals() { - const [health, quotaResult] = await Promise.all([ - healthContext(false).catch(() => null), - source - .quota() - .then((quota) => ({ quota, unavailable: false })) - .catch(() => ({ quota: emptyQuotaView(), unavailable: true })), - ]); - return { health, quota: quotaResult.quota, quotaUnavailable: quotaResult.unavailable }; -} - -// #1179: the shell (/today) and the fragment (/frag/today) both need -// the health+quota strip, seconds apart on every page view. Bound the -// repeated live reads with a short TTL; concurrent cold requests share -// the in-flight load. Provenance stays truthful: prov()/provDetail() -// are still read live per request at the call sites below. -const todaySignalsCache = new TodayCache>>(TODAY_CACHE_TTL_MS); -async function todaySignals(): Promise>> { - return todaySignalsCache.get(loadTodaySignals); -} - -async function loadTodayContext() { - const [{ board, items }, { rows, pool }, { view, coverage, orchestration }, signals] = await Promise.all([ - boardContext(), - roadmapContext(), - attentionContext(), - todaySignals(), - ]); - const diagnosis = source.diagnostics?.().orchestration; - const queue = buildQueueView({ board, pool, items, orchestration }); - return { - today: deriveToday(board, rows, items, orchestration, new Date(), diagnosis, pool), - view, - coverage, - ...signals, - queue, - queueStale: queueInputsStale(signals.health), - }; -} - -// #1179: /today?full=1, /frag/today, and /api/today.json all render -// from this one assembly. Same short-TTL + coalescing contract as the -// signals cache above; a throwing cold load is never cached (the -// fetch error boundary still 500s) and expiry serves the stale copy -// while one background refresh re-reads (#5082 SWR). -const todayContextCache = new TodayCache>>(TODAY_CACHE_TTL_MS); -async function todayContext(): Promise>> { - return todayContextCache.get(loadTodayContext); -} - -async function queueContext() { - const [{ board, items }, pool, orchestration] = await Promise.all([ - boardContext(), - source.projects().catch(() => [] as ProjectPoolItem[]), - source.orchestration().catch(() => null), - ]); - return buildQueueView({ board, pool, items, orchestration }); -} - -/** The render inputs the overview (front door, #1134) assembles: - * the attention view, the Project pool, quota, the health view, and - * the board — the same contexts the dedicated pages render from. */ -async function loadOverviewContext() { - const [{ view }, pool, quota, health, { board, items }, orchestration, actionsByObject] = await Promise.all([ - attentionContext(), - source.projects().catch(() => [] as ProjectPoolItem[]), - source.quota().catch(() => emptyQuotaView()), - healthContext(), - boardContext(), - source.orchestration().catch(() => null), - actionsStore.byObject().catch(() => new Map()), - ]); - return { attention: view, pool, quota, health, board, items, orchestration, actionsByObject }; -} - -// #5082: same contract as the board assembly above — the overview -// fan-out (attention + pool + quota + health + board + orchestration) -// was re-run live on every /, /frag/overview, and /api/overview.json -// request and tripped the same 10 s deadline. The per-request -// derivations (deriveOverview / renderOverview) and the provenance -// reads stay live; only the assembly is cached. The board leg inside -// rides the boardContext cache, so a cold overview and a cold board -// share one board assembly. -const overviewContextCache = new TodayCache>>(TODAY_CACHE_TTL_MS); -async function overviewContext(): Promise>> { - return overviewContextCache.get(loadOverviewContext); -} - -// #3976 (Codex review on PR #9193): a freshness notice means canonical -// data changed, but the TTL caches above could still serve an assembly -// built before the notice for up to 10s — and nothing re-requests when -// the TTL expires, so an accepted revision could stay invisible until -// a later notice or a manual refresh. Invalidate the two assemblies -// the freshness fragments reread (/frag/overview, /frag/today) the -// moment a notice becomes durable. The store seam covers every -// acceptance path — in-process recordFreshness, the IPC handler, and -// the reconciler's synthetic invalidations all publish through the -// same store. -// -// #5082 (2026-11-14): invalidate, don't clear. Notices land every few -// minutes (115 in the 3 h before steward run 379), and clear() dropped -// the cached assembly entirely, so the first post-notice request paid -// the full cold assembly on the request path. That request is -// routinely an hourly watch arriving after a quiet gap; when the -// assembly chain inflated past the 10 s dashboard deadline under load -// (steward runs 378/379: /api/overview.json 503 at 10.42 s, pass 2 -// clean), the deadline's last-good was always older than its 5-minute -// staleness cap at that cadence, so the fallback was a hard 503. -// invalidate() keeps the last assembly servable under the ordinary -// SWR contract — the first post-notice request serves it immediately -// and refreshes behind it — and the kick below starts that refresh -// at notice time, so an accepted revision becomes visible one -// assembly later without any request paying for the rebuild. -freshnessStore.onNotice(() => { - overviewContextCache.invalidate(); - todayContextCache.invalidate(); - attentionContextCache.invalidate(); - attentionCensusContextCache.invalidate(); - void overviewContext().catch(() => {}); - void todayContext().catch(() => {}); -}); - -/** The live-source half of the /program assembly (#1046 + #1121): the - * items closure for the program refs, the Project pool, the roadmap, - * orchestration, and the coverage census inputs. Everything - * view-dependent (saved-view filtering, briefs, forecasts, the - * render) is derived per request from this bundle in the handler. */ -async function loadProgramSources() { - const [items, pool, rows, orchestration, census, poolAvailable] = await Promise.all([ - source.items(programRefs()).catch(() => new Map()), - source.projects().catch(() => []), - source.roadmap().catch(() => []), - source.orchestration().catch(() => null), - source.coverageCensus ? source.coverageCensus().catch(() => null) : Promise.resolve(null), - source.projectsAvailable ? source.projectsAvailable().catch(() => false) : Promise.resolve(true), - ]); - return { items, pool, rows, orchestration, census, poolAvailable }; -} - -// #5082: /program is a bounded dashboard route with the same failure -// shape — its source fan-out ran live on every request. Same TTL + -// single-flight contract as the board/overview assemblies above. -const programSourcesCache = new TodayCache>>(TODAY_CACHE_TTL_MS); -async function programSources(): Promise>> { - return programSourcesCache.get(loadProgramSources); -} - -// -- Saved views (#1276) ------------------------------------------------- -// A request names a view three ways, in precedence order: explicit -// vf.* filter params (the shareable-URL form — reproduces the view for -// any viewer with no store lookup), a view id (store lookup), or the -// viewer's own default view (the viewer is named by the `viewer` query -// param, the dashboard author key ":"). No view named = the -// pages render exactly as before. - -interface ResolvedView { - filters: ViewFilters; - view: SavedView | null; -} - -async function resolveView(url: URL): Promise { - const fromQuery = filtersFromQuery(url.searchParams); - if (fromQuery) { - const id = url.searchParams.get("view"); - return { filters: fromQuery, view: id ? await viewsStore.get(id).catch(() => null) : null }; - } - const id = url.searchParams.get("view"); - if (id) { - const view = await viewsStore.get(id).catch(() => null); - return view ? { filters: view.filters, view } : null; - } - const viewer = url.searchParams.get("viewer"); - if (viewer) { - const view = await viewsStore.defaultFor(viewer).catch(() => null); - return view ? { filters: view.filters, view } : null; - } - return null; -} - -function poolItemLike(item: ProjectPoolItem): ViewItemLike { - return { - ref: item.ref, - repo: item.repo, - area: item.area, - horizon: item.horizon, - owner: item.author ?? null, - state: item.state, - epic: item.epicRef ?? null, - status: item.status, - kind: item.kind, - }; -} - -function eventContextByRef(pool: readonly ProjectPoolItem[]): Map { - const context = new Map(); - for (const item of pool) { - const ref = item.ref.replace(/^gh:/i, "").toLowerCase(); - context.set(ref, { - project: item.projectUrl, - epic: item.epicRef ?? (item.kind?.toLowerCase() === "epic" ? item.ref : null), - }); - } - return context; -} - -function eventFilterFromUrl( - url: URL, - itemContext: ReadonlyMap, -) { - return { - kind: url.searchParams.get("kind") ?? undefined, - refs: url.searchParams.getAll("ref"), - actor: url.searchParams.get("actor") ?? undefined, - project: url.searchParams.get("project") ?? undefined, - epic: url.searchParams.get("epic") ?? undefined, - search: url.searchParams.get("q") ?? undefined, - itemContext, - }; -} - -/** Apply a preference view verb to the views store (#1276). Returns a - * result note for the action record, or throws — the caller maps a - * throw to a rejected action so the audit trail says what happened. */ -async function applyViewAction(action: DashAction): Promise { - const owner = ownerKey(action.author); - const pl = action.payload; - switch (action.verb) { - case "save-view": { - const view = await viewsStore.save({ owner, name: pl.viewName!, filters: pl.viewFilters! }); - return `saved view ${view.id} "${view.name}"`; - } - case "rename-view": { - const view = await viewsStore.rename(pl.viewId!, owner, pl.viewName!); - if (!view) throw new Error(`no view ${pl.viewId} for this owner`); - return `renamed view ${view.id} to "${view.name}"`; - } - case "delete-view": { - const gone = await viewsStore.remove(pl.viewId!, owner); - if (!gone) throw new Error(`no view ${pl.viewId} for this owner`); - return `deleted view ${pl.viewId}`; - } - case "set-default-view": { - if (pl.viewId === undefined) { - await viewsStore.setDefault(null, owner); - return "default view cleared"; - } - const view = await viewsStore.setDefault(pl.viewId, owner); - if (!view) throw new Error(`no view ${pl.viewId} for this owner`); - return `default view is now ${view.id} "${view.name}"`; - } - default: - throw new Error(`not a view verb: ${action.verb}`); - } -} - -/** The digest (#1278): built live from the same Source as every page; - * the archived form is the JSON the generator script wrote. */ -async function digestContext(kind: DigestKind): Promise { - // Prime the items facet first (#1267 pattern): items() is the call - // that records the pool's feed freshness into provenance — without - // it the digest's pool sections would read an unprimed facet. - await source.items([]).catch(() => null); - const [pool, needsDrew, quota, poolAvailable] = await Promise.all([ - source.projects(), - source.needsDrew ? source.needsDrew().catch(() => null) : Promise.resolve(null), - source.quota().catch(() => null), - source.projectsAvailable ? source.projectsAvailable().catch(() => undefined) : Promise.resolve(undefined), - ]); - return buildDigest({ - pool, - needsDrew, - quota, - provenanceDetail: source.provenanceDetail?.() ?? null, - poolAvailable, - sourceKind: cfg.source, - now: new Date(), - kind, - }); -} - -const GRAINS = new Set(["quarter", "month", "week", "3d", "today"]); +import { FORECAST_CONTRACT_VERSION } from "./forecast-contract.ts"; +import { cfg, dashboardResponseWithinDeadline, roadmapAnnotationsStore, itemHistoryStore, sloJournal, loadSpendCards, readyAgentDispatchStates, coverageSnapshot, actionsStore, commentsStore, viewsStore, eventsStore, freshnessStore, freshnessReconciler, activityStore, githubHotListConsumer, githubOutcomeConsumer, githubActivityStatus, activitySourceStatusHtml, recordActivity, source, quotaRefresher, briefCommentsFor, assembleConflicts, commentIdentities, commentFormOpts, discussTitle, emptyQuotaView, emptyUsageView } from "./server-wiring.ts"; +import { json, jsonCompact, html, serviceWorkerResponse } from "./server-respond.ts"; +import { questionsHtml, PWA_MANIFEST } from "./server-pages.ts"; +import { boardContext, allForecastContracts, roadmapContext, searchContext, deriveWatchdogItems, attentionContext, ssePatch, sseResponse, boardRender, attentionRender, todaySignals, todayContext, queueContext, overviewContext, programSources, resolveView, poolItemLike, eventContextByRef, eventFilterFromUrl, digestContext, GRAINS, healthContext, sloSummaries } from "./server-contexts.ts"; +import { handleReportsRead, handleReportWriteRoutes, handleIdentityRoutes, handleWriteRoutes } from "./server-write-routes.ts"; +import { handleAlertIntakeRoutes, handleAlertAction, handleAlertRead, handleAlertsList, handleAlertPreferences, handleNotificationsPage } from "./server-alert-routes.ts"; +import { handleDecisionRoutes, handleDecisionsIndex, handleDecisionTailRoutes } from "./server-decision-routes.ts"; async function handler(req: Request): Promise { - const url = new URL(req.url); - const path = url.pathname; - const prov = () => source.provenance(); - const provDetail = () => source.provenanceDetail?.(); - - if (req.method === "GET" && (path === "/reports" || path === "/api/reports.json")) { - try { - const records = await readReportRecords(reportRecordsLocation); - const snapshots = await readReportSnapshots(reportRecordsLocation); - const current = selectCurrentReportRecords(records); - if (path === "/api/reports.json") { - return json({ - records: current, - conflicts: reportBlockReviews(records, current).map((review) => ({ - periodId: review.periodId, - blockId: review.blockId, - storedRecordId: review.storedRecord.id, - renderedRecordId: review.renderedRecord.id, - comparison: review.comparison, - })), - }); - } - return html( - renderReportReview( - reportBlockReviews(records, current), - records.length, - new Date(), - current, - new Set(snapshots.map((snapshot) => snapshot.record.period.id)), - ), - ); - } catch { - if (path === "/api/reports.json") return json({ error: "report records unavailable" }, 503); - return html(`

Report review unavailable

Could not read retained report records.

`, 503); - } - } - - if (req.method === "POST" && path === "/api/reports/resolve") { - const access = await enforceAccessAuthor(req, { kind: "drew", id: "drew", label: "Drew" }); - if (!access.ok || !access.verified || access.author.kind !== "drew") { - return json({ error: "verified Access owner required" }, 403); - } - let body: Record; - try { - const parsed = await readJsonBody(req); - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) - return json({ error: "invalid resolution body" }, 400); - body = parsed as Record; - } catch { - return json({ error: "invalid resolution body" }, 400); - } - const storedRecordId = typeof body.storedRecordId === "string" ? body.storedRecordId : ""; - const renderedRecordId = typeof body.renderedRecordId === "string" ? body.renderedRecordId : ""; - const blockId = typeof body.blockId === "string" ? body.blockId : ""; - const strategy = body.strategy; - if ( - !storedRecordId || - !renderedRecordId || - !blockId || - typeof strategy !== "string" || - !["stored", "rendered", "edited", "combined"].includes(strategy) - ) { - return json({ error: "storedRecordId, renderedRecordId, blockId and a valid strategy are required" }, 400); - } - if (body.resolvedText !== undefined && typeof body.resolvedText !== "string") { - return json({ error: "resolvedText must be text" }, 400); - } - let records; - try { - records = await readReportRecords(reportRecordsLocation); - } catch { - return json({ error: "report records unavailable" }, 503); - } - const storedRecord = records.find((record) => record.id === storedRecordId); - const renderedRecord = records.find((record) => record.id === renderedRecordId); - if (!storedRecord || !renderedRecord) return json({ error: "unknown report record" }, 404); - if ( - storedRecord.period.id !== renderedRecord.period.id || - storedRecord.templateVersion !== renderedRecord.templateVersion - ) { - return json({ error: "compared records must have the same period and template" }, 400); - } - const storedBlock = storedRecord.blocks.find((block) => block.id === blockId); - const renderedBlock = renderedRecord.blocks.find((block) => block.id === blockId); - if (!storedBlock || !renderedBlock) return json({ error: "compared block is missing" }, 400); - const comparison = compareReportBlock(storedBlock.text, renderedBlock.text); - if (!comparison.conflict) return json({ error: "report block has no substantive conflict" }, 400); - const selectedPair = reportBlockReviews(records, selectCurrentReportRecords(records)).some( - (review) => - review.blockId === blockId && - review.storedRecord.id === storedRecordId && - review.renderedRecord.id === renderedRecordId, - ); - const selectedText = - strategy === "stored" ? storedBlock.text : strategy === "rendered" ? renderedBlock.text : body.resolvedText; - const exactRetry = records.some((candidate) => - candidate.blocks.some( - (block) => - block.id === blockId && - block.text === selectedText && - block.resolution?.sourceRecordId === storedRecordId && - block.resolution.comparedRecordId === renderedRecordId && - block.resolution.strategy === strategy, - ), - ); - if (!selectedPair && !exactRetry) { - return json({ error: "compared records are not the current review selection" }, 409); - } - try { - const result = await appendReportBlockConflictResolution( - reportRecordsLocation, - storedRecord, - blockId, - comparison, - strategy as "stored" | "rendered" | "edited" | "combined", - new Date().toISOString(), - typeof body.resolvedText === "string" ? body.resolvedText : undefined, - renderedRecordId, - ); - return json({ inserted: result.inserted, record: result.record }); - } catch (error) { - const message = error instanceof Error ? error.message : "report resolution failed"; - const status = - error instanceof ReportRecordConflictError || message.startsWith("stale report block comparison:") - ? 409 - : /^(report block comparison|compared report record|resolvedAt must be later|report operation |(?:stored|rendered|edited|combined) report block resolution)/.test( - message, - ) - ? 400 - : 500; - return json({ error: message }, status); - } - } + const url = new URL(req.url); + const path = url.pathname; + const prov = () => source.provenance(); + const provDetail = () => source.provenanceDetail?.(); - if (req.method === "POST" && path === "/api/reports/late-update") { - const access = await enforceAccessAuthor(req, { kind: "drew", id: "drew", label: "Drew" }); - if (!access.ok || !access.verified || access.author.kind !== "drew") { - return json({ error: "verified Access owner required" }, 403); - } - let body: Record; - try { - const parsed = await readJsonBody(req); - if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) - return json({ error: "invalid late update body" }, 400); - body = parsed as Record; - } catch { - return json({ error: "invalid late update body" }, 400); - } - const reportRecordId = typeof body.reportRecordId === "string" ? body.reportRecordId : ""; - const operation = body.operation; - const blockId = typeof body.blockId === "string" ? body.blockId : ""; - const text = typeof body.text === "string" ? body.text : ""; - const relatedAt = typeof body.relatedAt === "string" ? body.relatedAt : ""; - const lateOperations = ["quote", "append", "banner", "event-log", "feedback"]; - if ( - !reportRecordId || - !blockId || - !text.trim() || - !relatedAt || - typeof operation !== "string" || - !lateOperations.includes(operation) - ) { - return json({ error: "reportRecordId, a permitted operation, blockId, text and relatedAt are required" }, 400); - } - let source: ReportRecordSource | undefined; - if (body.source !== undefined) { - if (!body.source || typeof body.source !== "object" || Array.isArray(body.source)) - return json({ error: "invalid late update source" }, 400); - const candidate = body.source as Record; - if ( - typeof candidate.id !== "string" || - typeof candidate.uri !== "string" || - typeof candidate.observedAt !== "string" - ) { - return json({ error: "late update source requires id, uri and observedAt" }, 400); - } - source = { id: candidate.id, uri: candidate.uri, observedAt: candidate.observedAt }; - } - let records; - try { - records = await readReportRecords(reportRecordsLocation); - } catch { - return json({ error: "report records unavailable" }, 503); - } - const current = records.find((record) => record.id === reportRecordId); - if (!current) return json({ error: "unknown report record" }, 404); - try { - const result = await appendReportLateUpdate( - reportRecordsLocation, - current, - operation as ReportLateUpdateOperation, - { id: blockId, text, relatedAt }, - new Date().toISOString(), - source, - ); - return json({ inserted: result.inserted, record: result.record }); - } catch (error) { - const message = error instanceof Error ? error.message : "late report update failed"; - const status = - error instanceof ReportRecordConflictError || message.startsWith("stale report block comparison:") - ? 409 - : /^(report operation |quote report update|feedback report update|each late report update|block relatedAt|source observedAt|late update source|duplicate report block)/.test( - message, - ) - ? 400 - : 500; - return json({ error: message }, status); - } + if (req.method === "GET" && (path === "/reports" || path === "/api/reports.json")) { + return handleReportsRead(req, path); } + const reportWriteResponse = await handleReportWriteRoutes(req, path); + if (reportWriteResponse) return reportWriteResponse; // --- #3978: freshness delivery for browsers ------------------------------ // GET /freshness/stream (SSE) and GET /api/freshness-events.json read the @@ -2404,514 +105,15 @@ async function handler(req: Request): Promise { return json({ identities: identitiesFromRecords(records) }); } - // #9604: role mappings are managed only by a verified Access owner. - // The asserted author here is deliberately fixed; request-body identity - // or role claims never authorize registry changes. - if ( - path === "/api/admin/identity-registry" && - (req.method === "GET" || req.method === "POST" || req.method === "DELETE") - ) { - const access = await enforceAccessAuthor(req, { kind: "drew", id: "drew", label: "Drew" }); - if (!access.ok) return json({ error: access.error }, access.status); - let auditActor: string; - if (access.verified && access.author.kind === "drew") { - // Access-verified owner proceeds exactly as before; a presented - // break-glass token is never touched on this path. - auditActor = access.identity?.sub || access.identity?.email || access.author.id; - } else { - // #9608: the Access/IdP-outage path. A presented single-use - // break-glass token is consumed atomically (with its audit - // event) and authorizes exactly this one admin request; - // anything invalid — or no token at all — fails closed. - const presented = presentedBreakGlassToken(req); - if (!presented) return json({ error: "verified Access owner required" }, 403); - const grant = await authorizeWithBreakGlassToken({ - store: breakGlassTokenStore, - events: eventsStore, - token: presented, - }); - if (!grant.ok) return json({ error: grant.error }, 403); - auditActor = grant.auditActor; - } - if (req.method === "GET") return json({ registry: await identityRegistryStore.list() }); - try { - const body = await readJsonBody(req); - if (req.method === "POST") { - const parsed = validateIdentityMapping(body); - if (!parsed.ok) return json({ error: parsed.error }, 400); - const result = await identityRegistryStore.set(parsed.identity, parsed.role, auditActor); - await eventsStore.record( - identityMappingAuditEvent({ - identity: parsed.identity, - previousRole: result.previousRole, - role: parsed.role, - revision: result.registry.revision, - actor: auditActor, - }), - ); - return json({ registry: result.registry, previousRole: result.previousRole }); - } - const identity = - typeof body === "object" && body !== null ? (body as { identity?: unknown }).identity : undefined; - if ( - typeof identity !== "string" || - identity.trim() === "" || - identity.trim().length > 200 || - /\s/.test(identity.trim()) - ) { - return json({ error: "identity must be a non-empty whitespace-free string (max 200 chars)" }, 400); - } - const result = await identityRegistryStore.remove(identity.trim()); - if (result.previousRole !== null) { - await eventsStore.record( - identityMappingAuditEvent({ - identity: identity.trim(), - previousRole: result.previousRole, - role: null, - revision: result.registry.revision, - actor: auditActor, - }), - ); - } - return json({ registry: result.registry, previousRole: result.previousRole }); - } catch (error) { - return json( - { error: `identity registry operation failed: ${error instanceof Error ? error.message : error}` }, - 500, - ); - } - } - - // #9605: exchange the already-verified Access identity for a short-lived - // layer-scoped token. The target and action are request metadata; the - // principal and role always come from verified Access + the registry. - if (req.method === "POST" && path === "/api/stack-token/exchange") { - const access = await enforceAccessAuthor(req, { kind: "agent", id: "exchange", label: "exchange" }); - if (!access.ok) return json({ error: access.error }, access.status); - if (!access.verified || !access.identity) return json({ error: "verified Access identity required" }, 403); - const secret = cfg.stackTokenSecret; - if (!secret) return json({ error: "stack token exchange is not configured" }, 503); - const identity = access.identity.sub || access.identity.email; - const role: StackTokenRole = - access.author.kind === "drew" ? "owner" : await identityRegistryStore.roleFor(identity); - if (role === "read-only") return json({ error: "identity role cannot mint write tokens" }, 403); - try { - const body = await readJsonBody(req); - const target = - typeof body === "object" && body !== null && typeof (body as { target?: unknown }).target === "string" - ? (body as { target: string }).target.trim() - : ""; - const action = - typeof body === "object" && body !== null && typeof (body as { action?: unknown }).action === "string" - ? (body as { action: string }).action.trim() - : ""; - if (!["kaneo", "pad", "grist"].includes(target)) return json({ error: "target must be kaneo, pad, or grist" }, 400); - if (!/^[A-Za-z][A-Za-z0-9._:-]{0,63}$/.test(action)) return json({ error: "action is invalid" }, 400); - const token = mintStackToken({ sub: identity, role, aud: target, act: action }, secret); - return json({ token, tokenType: "Bearer", audience: target, expiresIn: STACK_TOKEN_TTL_SECONDS }); - } catch (error) { - return json({ error: `stack token exchange failed: ${error instanceof Error ? error.message : error}` }, 400); - } - } + // #9604/#9605: identity-registry admin + stack-token exchange — server-write-routes.ts (#13052). + const identityResponse = await handleIdentityRoutes(req, path); + if (identityResponse) return identityResponse; - // --- Dashboard comment writes (#906 §2) -------------------------------- - if (req.method === "POST" && path === "/api/roadmap/annotations") { - try { - const parsed = validateNewRoadmapAnnotation(await readJsonBody(req)); - if (!parsed.ok) return json({ error: parsed.error }, 400); - // #1253 slice: when Access is configured, authorship derives from - // the verified JWT, never the caller-supplied author. - const annotationAccess = await enforceAccessAuthor(req, parsed.value.author); - if (!annotationAccess.ok) return json({ error: annotationAccess.error }, annotationAccess.status); - parsed.value.author = annotationAccess.author; - const rows = await source.roadmap().catch(() => []); - if (!rows.some((row) => row.subject === parsed.value.objectRef)) { - return json({ error: "objectRef is not a current roadmap row" }, 404); - } - try { - const annotation = await roadmapAnnotationsStore.add(parsed.value); - return json({ annotation }, 201); - } catch (err) { - return json({ error: `annotation persistence failed: ${err instanceof Error ? err.message : err}` }, 500); - } - } catch (err) { - return json({ error: `invalid annotation: ${err instanceof Error ? err.message : err}` }, 400); - } - } - if (req.method === "POST" && path === "/api/roadmap/annotations/alias") { - try { - const body = (await readJsonBody(req)) as { aliasRef?: unknown; stableRef?: unknown }; - if (typeof body.aliasRef !== "string" || typeof body.stableRef !== "string") { - return json({ error: "aliasRef and stableRef are required" }, 400); - } - const rows = await source.roadmap().catch(() => []); - if (!rows.some((row) => row.subject === body.aliasRef)) { - return json({ error: "aliasRef is not a current roadmap row" }, 404); - } - if (!(await roadmapAnnotationsStore.forObject(body.stableRef)).length) { - return json({ error: "stableRef has no existing annotation history" }, 404); - } - await roadmapAnnotationsStore.addAlias(body.aliasRef, body.stableRef); - return json({ aliases: await roadmapAnnotationsStore.aliasEntries() }); - } catch (err) { - return json({ error: `invalid annotation alias: ${err instanceof Error ? err.message : err}` }, 400); - } - } + // Dashboard writes (#906 §2, #1152/#1154/#1156, #1276/#1277): prompt, comment and + // action route families — server-write-routes.ts (#13052). + const writeResponse = await handleWriteRoutes(req, url, path); + if (writeResponse) return writeResponse; - if (req.method === "POST" && path === "/api/prompt") { - const parsed = validateNewPrompt(await readJsonBody(req).catch(() => null)); - if (!parsed.ok) return json({ error: parsed.error }, 400); - try { - return json({ prompt: await promptsStore.add(parsed.value) }, 201); - } catch (err) { - return json({ error: `prompt persistence failed: ${err instanceof Error ? err.message : err}` }, 500); - } - } - if (req.method === "GET" && path === "/api/prompt/unread-count") { - const count = await promptsStore.unreadCount(); - return json({ count, unread: count, total: count }); - } - if (req.method === "GET" && path === "/api/prompt/threads") { - return json({ threads: await promptsStore.threads() }); - } - if (req.method === "GET" && path.startsWith("/api/prompt/thread/")) { - const threadId = decodeURIComponent(path.slice("/api/prompt/thread/".length)); - return json({ threadId, prompts: await promptsStore.thread(threadId) }); - } - if (req.method === "GET" && path === "/api/prompt") { - const status = url.searchParams.get("status"); - const page = url.searchParams.get("page") ?? undefined; - const threadId = url.searchParams.get("threadId") ?? undefined; - const replyTo = url.searchParams.get("replyTo") ?? undefined; - const archivedParam = url.searchParams.get("archived"); - const includeArchived = - url.searchParams.get("includeArchived") === "1" || url.searchParams.get("includeArchived") === "true"; - const archived = archivedParam === "true" ? true : archivedParam === "false" ? false : undefined; - const filter: Parameters[0] = { - page, - status: PROMPT_STATUSES.includes(status as PromptStatus) ? (status as PromptStatus) : undefined, - threadId, - replyTo, - archived, - includeArchived, - }; - const prompts = await promptsStore.list(filter); - // newest first - prompts.sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : 0)); - return json({ prompts }); - } - if (req.method === "GET" && path.startsWith("/api/prompt/")) { - const rest = decodeURIComponent(path.slice("/api/prompt/".length)); - if (rest === "thread" || rest.startsWith("thread/")) { - // handled above via query; fall through to 404 - } - const id = rest; - const prompt = await promptsStore.get(id); - if (!prompt) return json({ error: "prompt not found" }, 404); - return json({ - id: prompt.id, - status: prompt.status, - answer: prompt.answer, - error: prompt.error, - threadId: prompt.threadId, - archived: prompt.archived, - read: prompt.read, - replyTo: prompt.replyTo, - refs: prompt.refs, - }); - } - if (req.method === "PATCH" && path.startsWith("/api/prompt/")) { - const id = decodeURIComponent(path.slice("/api/prompt/".length)); - let body: unknown = null; - try { - body = await readJsonBody(req); - } catch { - body = null; - } - const b = body && typeof body === "object" && !Array.isArray(body) ? (body as Record) : {}; - const patch: Parameters[1] = {}; - if (typeof b.status === "string" && PROMPT_STATUSES.includes(b.status as PromptStatus)) - patch.status = b.status as PromptStatus; - if (typeof b.answer === "string") patch.answer = b.answer; - if (typeof b.error === "string") patch.error = b.error; - if (typeof b.archived === "boolean") patch.archived = b.archived; - if (typeof b.read === "boolean") patch.read = b.read; - if (Array.isArray(b.refs) && b.refs.every((x) => typeof x === "string")) patch.refs = b.refs as string[]; - if (b.replyTo === null || typeof b.replyTo === "string") patch.replyTo = b.replyTo as string | null; - const updated = await promptsStore.update(id, patch); - if (!updated) return json({ error: "prompt not found" }, 404); - return json({ prompt: updated }); - } - if (req.method === "POST" && path === "/api/comments") { - try { - const parsed = validateNewComment(await readJsonBody(req)); - if (!parsed.ok) return json({ error: parsed.error }, 400); - // #1253 slice: when Access is configured, authorship derives from - // the verified JWT, never the caller-supplied author. - const commentAccess = await enforceAccessAuthor(req, parsed.value.author); - if (!commentAccess.ok) return json({ error: commentAccess.error }, commentAccess.status); - parsed.value.author = commentAccess.author; - // #941: a privileged author additionally requires the operator - // token when one is configured (fail closed on a secret-store - // outage); with no secret configured the write stays unverified. - // Runs on the Access-derived author above, so the two gates - // compose: identity first, privilege second. - const authorization = authorizeCommentAuthor( - parsed.value.author, - req.headers.get("authorization"), - await resolveBwsSecretLookup("pm-aggregator.comments-operator-token"), - ); - if (!authorization.ok) return json({ error: authorization.error }, authorization.status); - // #1509: a persistence failure is a server error, not bad input - - // only the validation/body-parse path above earns a 400. - let comment; - try { - comment = await commentsStore.add(parsed.value, { - authorVerified: authorization.authorVerified, - // #1253 split 4 (#9606): "verified" only when the author came - // from the Access JWT above, never from the request body. - provenance: commentAccess.verified ? "verified" : "asserted-legacy", - }); - } catch (err) { - return json({ error: `comment persistence failed: ${err instanceof Error ? err.message : err}` }, 500); - } - return json({ comment }, 201); - } catch (err) { - return json({ error: `invalid comment: ${err instanceof Error ? err.message : err}` }, 400); - } - } - if (req.method === "POST" && path === "/api/comments/triage") { - try { - const body = (await readJsonBody(req)) as { ids?: unknown }; - const ids = Array.isArray(body.ids) ? body.ids.filter((x): x is string => typeof x === "string") : []; - return json({ triaged: await commentsStore.markTriaged(ids) }); - } catch (err) { - return json({ error: `invalid triage: ${err instanceof Error ? err.message : err}` }, 400); - } - } - if (req.method === "POST" && path === "/api/comments/github-result") { - try { - const body = (await readJsonBody(req)) as { id?: unknown; url?: unknown; error?: unknown }; - if (typeof body.id !== "string") return json({ error: "id required" }, 400); - const updated = await commentsStore.markGithubResult(body.id, { - url: typeof body.url === "string" ? body.url : undefined, - error: typeof body.error === "string" ? body.error : undefined, - }); - return updated ? json({ comment: updated }) : json({ error: "no such github comment" }, 404); - } catch (err) { - return json({ error: `invalid result: ${err instanceof Error ? err.message : err}` }, 400); - } - } - // --- Dashboard action writes (#1152/#1154/#1156) ----------------------- - // The triage write path: forms POST DashActions here; the fleet - // consumers (orchestration pass) poll state=new and - // report outcomes to /api/actions/result. The dashboard itself never - // writes GitHub, the Project, or a session server. - if (req.method === "POST" && path === "/api/actions") { - try { - const parsed = validateNewAction(await readJsonBody(req)); - if (!parsed.ok) return json({ error: parsed.error }, 400); - // #1253 slice: gate every action write, including non-triage and - // preference actions, on the configured Access identity. - const actionAccess = await enforceAccessAuthor(req, parsed.value.author); - if (!actionAccess.ok) return json({ error: actionAccess.error }, actionAccess.status); - parsed.value.author = actionAccess.author; - // #1291/#1293: checks that need the currently published item — - // option/survey membership, required-question coverage, proposal - // identity, the access/policy auto ban. Enforced only when the - // aggregator actually holds a section; with none, the store - // stays the permissive boundary of the triage slice and the - // consumer rejects what it cannot apply. - if (parsed.value.kind === "triage") { - const section = await source.orchestration().catch(() => null); - let item: ReturnType; - if (section) { - item = findTierItem(section, parsed.value.objectRef); - const problem = checkActionAgainstItem(parsed.value, item, Date.now()); - if (problem) return json({ error: problem }, 400); - } - if (parsed.value.verb === "answer" && parsed.value.payload.optionId) { - parsed.value.payload.questionId = questionIdForOption(item, parsed.value.payload.optionId) ?? "$options"; - } - } - // #1509: persistence failure -> 5xx (see /api/comments above). - let added; - try { - added = await actionsStore.add(parsed.value); - } catch (err) { - return json({ error: `action persistence failed: ${err instanceof Error ? err.message : err}` }, 500); - } - const { action, created } = added; - if (added.duplicateOf) { - return json( - { - error: `duplicate answer recorded as ${action.id}; it points to existing answer action ${added.duplicateOf}`, - action, - duplicateOf: added.duplicateOf, - }, - 409, - ); - } - // A client-token replay of an already-persisted duplicate attempt - // keeps the rejected semantics instead of reading as a fresh - // "sent · pending" success (Codex P2 on PR #4024). - if (!created && action.duplicateOf) { - return json( - { - error: `duplicate answer recorded as ${action.id}; it points to existing answer action ${action.duplicateOf}`, - action, - duplicateOf: action.duplicateOf, - }, - 409, - ); - } - // #1276: saved-view preference verbs are applied by the - // aggregator itself to the views store and marked applied (or - // rejected, with the reason) in the same request — the action - // record stays the audit trail for every view change. - if ( - created && - action.kind === "preference" && - (action.verb === "save-view" || - action.verb === "rename-view" || - action.verb === "delete-view" || - action.verb === "set-default-view") - ) { - try { - const note = await applyViewAction(action); - const updated = await actionsStore.markResult(action.id, { - outcome: "applied", - byRun: "aggregator-views", - note, - }); - return json({ action: updated ?? action }, 201); - } catch (err) { - const updated = await actionsStore.markResult(action.id, { - outcome: "rejected", - byRun: "aggregator-views", - note: err instanceof Error ? err.message : String(err), - }); - return json({ action: updated ?? action, error: err instanceof Error ? err.message : String(err) }, 400); - } - } - return json(created ? { action } : { action, deduped: true }, created ? 201 : 200); - } catch (err) { - return json({ error: `invalid action: ${err instanceof Error ? err.message : err}` }, 400); - } - } - // #1277: bulk triage — one mediated batch, validated and appended - // item by item under the exact single-action rules above. Every - // accepted item becomes its OWN attributed audit entry (never one - // opaque batch record), so the batch is recoverable from the - // entries themselves; every rejected item is reported by ref with - // its error and appends nothing, so a partial batch never silently - // drops work — the failed items simply remain in Needs-you. - if (req.method === "POST" && path === "/api/actions/batch") { - try { - const body = (await readJsonBody(req)) as { actions?: unknown }; - if (!Array.isArray(body.actions) || body.actions.length === 0 || body.actions.length > 100) { - return json({ error: "actions must be an array of 1-100 action objects" }, 400); - } - const entries: unknown[] = body.actions; - // The published-item checks (#1291/#1293) need the section once, - // not once per item. - const section = entries.some( - (a) => typeof a === "object" && a !== null && (a as { kind?: unknown }).kind === "triage", - ) - ? await source.orchestration().catch(() => null) - : null; - const results: { - index: number; - objectRef: string | null; - ok: boolean; - action?: unknown; - deduped?: boolean; - error?: string; - }[] = []; - // One enforcer for the whole batch: the request's JWT is - // verified once, not once per action (see access-identity.ts). - const enforceBatchAuthor = createAccessAuthorEnforcer(req); - for (const [index, raw] of entries.entries()) { - const objectRef = - typeof raw === "object" && raw !== null && typeof (raw as { objectRef?: unknown }).objectRef === "string" - ? (raw as { objectRef: string }).objectRef - : null; - const parsed = validateNewAction(raw); - if (!parsed.ok) { - results.push({ index, objectRef, ok: false, error: parsed.error }); - continue; - } - const batchAccess = await enforceBatchAuthor(parsed.value.author); - if (!batchAccess.ok) { - results.push({ index, objectRef, ok: false, error: batchAccess.error }); - continue; - } - parsed.value.author = batchAccess.author; - if (parsed.value.kind === "triage" && section) { - const problem = checkActionAgainstItem( - parsed.value, - findTierItem(section, parsed.value.objectRef), - Date.now(), - ); - if (problem) { - results.push({ index, objectRef, ok: false, error: problem }); - continue; - } - } - try { - const { action, created } = await actionsStore.add(parsed.value); - results.push({ index, objectRef, ok: true, action, ...(created ? {} : { deduped: true }) }); - } catch (err) { - results.push({ - index, - objectRef, - ok: false, - error: `action persistence failed: ${err instanceof Error ? err.message : err}`, - }); - } - } - const recorded = results.filter((r) => r.ok).length; - return json({ results, recorded, failed: results.length - recorded }, 200); - } catch (err) { - return json({ error: `invalid batch: ${err instanceof Error ? err.message : err}` }, 400); - } - } - if (req.method === "POST" && path === "/api/actions/result") { - try { - const body = (await readJsonBody(req)) as { id?: unknown; outcome?: unknown; byRun?: unknown; note?: unknown }; - if (typeof body.id !== "string") return json({ error: "id required" }, 400); - if (body.outcome !== "applied" && body.outcome !== "rejected") { - return json({ error: 'outcome must be "applied" | "rejected"' }, 400); - } - if (typeof body.byRun !== "string" || body.byRun.trim() === "") return json({ error: "byRun required" }, 400); - const result = await actionsStore.markResultTransition(body.id, { - outcome: body.outcome, - byRun: body.byRun, - note: typeof body.note === "string" ? body.note : undefined, - }); - if (result?.transitioned) { - const updated = result.action; - // #1739: the action-result route is one of the event log's - // writers — the outcome lands in the cross-stack stream. - // Fire-and-forget: the response never waits on, and is never - // failed by, the event append. - recordStreamEvent({ - actor: updated.appliedByRun ?? capUnits(body.byRun, 200), - kind: body.outcome === "applied" ? "action-applied" : "action-rejected", - ref: updated.objectRef, - summary: capUnits( - `${updated.kind}/${updated.verb} ${body.outcome} by ${body.byRun}` + - (typeof body.note === "string" && body.note ? ` — ${body.note}` : ""), - 500, - ), - }); - } - const updated = result?.action; - return updated ? json({ action: updated }) : json({ error: "no such action" }, 404); - } catch (err) { - return json({ error: `invalid result: ${err instanceof Error ? err.message : err}` }, 400); - } - } if (path === "/api/events.json") { // #1739/#3323: the same source-native stream and filters as /events. const pool = await source.projects().catch(() => [] as ProjectPoolItem[]); @@ -4077,388 +1279,14 @@ async function handler(req: Request): Promise { return json(swProbeSummary()); } - // --- Alert throat (#3676): subscription API ------------------------- - if (path === "/api/push/subscriptions") { - const store = await getAlertsStore(); - if (!store) return json({ error: "alerts store unavailable" }, 503); - if (req.method === "POST") { - try { - const parsed = validateNewSubscription(await readJsonBody(req)); - if (!parsed.ok) return json({ error: parsed.error }, 400); - return json({ subscription: toPublicSubscription(await store.upsertSubscription(parsed.value)) }, 201); - } catch (err) { - return json({ error: `invalid subscription: ${err instanceof Error ? err.message : err}` }, 400); - } - } - if (req.method === "DELETE") { - try { - const body = (await readJsonBody(req)) as { endpoint?: unknown }; - if (typeof body.endpoint !== "string") return json({ error: "endpoint required" }, 400); - const deleted = await store.deleteSubscription(body.endpoint); - return deleted ? json({ deleted: true }) : json({ error: "no such subscription" }, 404); - } catch (err) { - return json({ error: `invalid delete: ${err instanceof Error ? err.message : err}` }, 400); - } - } - return json({ error: "method not allowed" }, 405); - } - - if (path === "/api/push/test") { - if (req.method !== "POST") return json({ error: "method not allowed" }, 405); - const store = await getAlertsStore(); - if (!store) return json({ error: "alerts store unavailable" }, 503); - const summary = await sendTestPush(store, cfg.publicOrigin); - return json(summary); - } + // Alert throat (#3676): subscription API + incident intake — server-alert-routes.ts (#13052). + const alertIntakeResponse = await handleAlertIntakeRoutes(req, path); + if (alertIntakeResponse) return alertIntakeResponse; - // Per-class test sends (#3318): one test per preference class, - // honouring the stored class toggles, landing per design §3. - if (path === "/api/push/test-class") { - if (req.method !== "POST") return json({ error: "method not allowed" }, 405); - let cls: unknown; - try { - cls = ((await readJsonBody(req)) as { class?: unknown })?.class; - } catch { - return json({ error: "invalid test-class body" }, 400); - } - if (!isNotificationTestClass(cls)) return json({ error: "unknown notification class" }, 400); - const store = await getAlertsStore(); - if (!store) return json({ error: "alerts store unavailable" }, 503); - const summary = await sendClassTestPush(store, cfg.publicOrigin, cls); - return json(summary); - } + // Needs-Drew answers (#8568) + decision-set APIs (#8766/#9335) — server-decision-routes.ts (#13052). + const decisionResponse = await handleDecisionRoutes(req, url, path); + if (decisionResponse) return decisionResponse; - // --- Alert throat (#3676): incident intake + ack/close -------------- - if (req.method === "POST" && path === "/api/alerts") { - if (!(await alertsIntakeAuthorized(req))) return json({ error: "unauthorized" }, 401); - const store = await getAlertsStore(); - if (!store) return json({ error: "alerts store unavailable" }, 503); - try { - const rawBody: unknown = await readJsonBody(req); - const parsed = validateNewIncident(rawBody); - if (!parsed.ok) return json({ error: parsed.error }, 400); - const ext = - rawBody && typeof rawBody === "object" && !Array.isArray(rawBody) ? (rawBody as Record) : {}; - const hasNeedsDrew = ext.needsDrew !== undefined; - const hasStackHealth = ext.stackHealth !== undefined; - const hasDecisionSet = ext.decisionSet !== undefined; - const hasHealthHook = ext.healthHook !== undefined; - // #12602 (#12599 decision b): the healthHook extension carries the - // full C3 incident record to the alerts ledger. It is gated and - // validated BEFORE the incident insert, unlike the extensions - // below, because a valid record rides the insert onto the opened - // event's detail; a malformed one is a 400 naming the field, - // before anything is stored. - let healthHook: HealthHookRecord | undefined; - if (hasHealthHook) { - if (parsed.value.source !== "health-hook") { - return json({ error: 'healthHook extension is only accepted for source "health-hook"' }, 400); - } - const hv = validateHealthHook(ext.healthHook); - if (!hv.ok) return json({ error: hv.error }, 400); - healthHook = hv.value; - } - const { incident, created } = await store.postIncident(parsed.value, healthHook ? { healthHook } : undefined); - const status = created ? 201 : 200; - // #8568/#8766 producer extensions: exactly one of needsDrew / - // stackHealth / decisionSet may ride an incident post; #12602 adds - // healthHook, which may co-ride with stackHealth (health-hook - // source only, gated above) and with nothing else. A VALIDATION - // failure of an extension is a 400 (the poster's bug should be - // loud at the poster), while a store failure is logged and never - // fails the incident post. - if ([hasNeedsDrew, hasStackHealth, hasDecisionSet].filter(Boolean).length > 1) { - return json({ error: "needsDrew, stackHealth and decisionSet extensions are mutually exclusive" }, 400); - } - if (hasHealthHook && (hasNeedsDrew || hasDecisionSet)) { - return json({ error: "healthHook extension may only co-ride with stackHealth" }, 400); - } - if (hasNeedsDrew) { - const v = validateNeedsDrew(ext.needsDrew); - if (!v.ok) return json({ error: v.error }, 400); - try { - const item = await raiseNeedsDrew(cfg.needsDrewFile, v.value, parsed.value.source); - requestAlertTick(); - return json( - { incident, created, needsDrew: { ledgerId: item.ledgerId, answerUrl: needsDrewAnswerUrl(item) } }, - status, - ); - } catch (err) { - console.error(`alerts intake: needsDrew raise failed (${err instanceof Error ? err.message : "error"})`); - return json({ incident, created }, status); - } - } - if (hasStackHealth) { - const v = validateStackHealth(ext.stackHealth); - if (!v.ok) return json({ error: v.error }, 400); - try { - await setStackHealth(cfg.stackHealthFile, v.value); - const auditEvent = healthHookAuditEvent({ - title: parsed.value.title, - source: parsed.value.source, - stackHealth: v.value, - }); - if (auditEvent) { - try { - await eventsStore.record(auditEvent); - } catch (err) { - console.error( - `alerts intake: health-hook audit append failed (${err instanceof Error ? err.message : "error"})`, - ); - } - } - if (v.value.state === "up") { - // #12602: a healthHook recovery record rides the closed - // event's detail of the incident it closes. - await store.closeOpenIncidentByKey( - parsed.value.source, - parsed.value.key, - healthHook?.state === "up" ? { healthHook } : undefined, - ); - } - requestAlertTick(); - } catch (err) { - console.error(`alerts intake: stackHealth update failed (${err instanceof Error ? err.message : "error"})`); - } - return json({ incident, created }, status); - } - if (hasDecisionSet) { - const v = validateDecisionSet(ext.decisionSet); - if (!v.ok) return json({ error: v.error }, 400); - try { - const beforeSet = await getDecisionSet(cfg.decisionsFile, v.value.setId).catch(() => null); - const set = await raiseDecisionSet(cfg.decisionsFile, v.value, parsed.value.source); - if (!beforeSet) { - await logDecisionEvents([ - { - setId: set.setId, - type: "set.created", - payload: { - via: "api/alerts", - source: parsed.value.source, - title: set.title, - items: set.items.length, - questions: set.items.reduce((n, i) => n + i.questions.length, 0), - }, - }, - ]); - } - requestAlertTick(); - return json({ incident, created, decisionSet: { setId: set.setId, pageUrl: decisionsPageUrl(set) } }, status); - } catch (err) { - console.error(`alerts intake: decisionSet raise failed (${err instanceof Error ? err.message : "error"})`); - return json({ incident, created }, status); - } - } - return json({ incident, created }, status); - } catch (err) { - return json({ error: `invalid incident: ${err instanceof Error ? err.message : err}` }, 400); - } - } - // --- Needs-Drew answers (#8568) -------------------------------------- - const needsDrewAnswerMatch = /^\/api\/needs-drew\/([^/]+)\/answer$/.exec(path); - if (req.method === "POST" && needsDrewAnswerMatch) { - const ledgerId = decodePathSegment(needsDrewAnswerMatch[1]); - if (ledgerId === null) return json({ error: "bad ledgerId" }, 400); - let body: { token?: unknown; optionId?: unknown; freeText?: unknown }; - try { - body = (await readJsonBody(req)) as typeof body; - } catch { - return json({ error: "invalid answer body" }, 400); - } - // No bearer: the per-question token is the authority. - const item = await getNeedsDrew(cfg.needsDrewFile, ledgerId).catch(() => null); - if (!item || typeof body.token !== "string" || body.token !== item.token) { - return json({ error: "unknown question or bad token" }, 403); - } - const optionId = typeof body.optionId === "string" ? body.optionId : undefined; - if (optionId !== undefined && !item.options.some((o) => o.id === optionId)) { - return json({ error: "optionId is not one of the question options" }, 400); - } - const freeText = typeof body.freeText === "string" ? body.freeText : undefined; - if (body.freeText !== undefined && freeText === undefined) { - return json({ error: "freeText must be a string" }, 400); - } - if (optionId === undefined && !freeText?.trim()) { - return json({ error: "optionId or freeText required" }, 400); - } - const updated = await recordAnswer(cfg.needsDrewFile, ledgerId, { - ...(optionId !== undefined ? { optionId } : {}), - ...(freeText !== undefined ? { freeText } : {}), - via: "api", - }); - if (!updated?.answer) return json({ error: "answer not recorded" }, 500); - // #8605: the answer resolves the question, so close its alert - // incident — the raiser posted it under this question's source with - // key needs-drew:, and until now nothing ever closed it. - // Best-effort, like the stack-health close in the intake above: a - // store failure is logged and never fails the recorded answer. - try { - const store = await getAlertsStore(); - if (store) { - await store.closeOpenIncidentByKey(item.source, needsDrewIncidentKey(ledgerId)); - requestAlertTick(); - } - } catch (err) { - console.error(`needs-drew answer: incident close failed (${err instanceof Error ? err.message : "error"})`); - } - return json({ - ledgerId, - answered: true, - answer: { - ...(updated.answer.optionId !== undefined ? { optionId: updated.answer.optionId } : {}), - ...(updated.answer.freeText !== undefined ? { freeText: updated.answer.freeText } : {}), - at: updated.answer.at, - via: updated.answer.via, - }, - }); - } - const answerPageMatch = /^\/answer\/([^/]+)$/.exec(path); - if (req.method === "GET" && answerPageMatch) { - const ledgerId = decodePathSegment(answerPageMatch[1]); - const token = url.searchParams.get("t") ?? ""; - const item = ledgerId === null ? null : await getNeedsDrew(cfg.needsDrewFile, ledgerId).catch(() => null); - // Unknown question or token mismatch: 403, and the question is - // never rendered — the token is the only authority here. - if (!item || !token || token !== item.token) return html(renderAnswerForbidden(), 403); - return html(renderAnswerPage(item)); - } - // --- Decision-set submit API + event log (#9335 v2) ----------------- - // POST /api/decision-sets (alias: /api/decision-sets/submit): the - // authenticated submit API. Intake-bearer auth, the same token as - // /api/alerts. Body: the bare v2 set object or { decisionSet: {...} } - // (a sibling `source` string is honored). setId may be omitted — a - // UUID is minted. The response returns the setId and the full token - // page URL to the authenticated submitter ONLY; the URL is never - // logged. Exactly one push per set: a fresh raise requests the alert - // tick exactly like the /api/alerts decisionSet path; a re-submit of - // an existing setId is idempotent and sends no second push. - if (req.method === "POST" && (path === "/api/decision-sets" || path === "/api/decision-sets/submit")) { - if (!(await alertsIntakeAuthorized(req))) return json({ error: "unauthorized" }, 401); - let rawBody: unknown; - try { - rawBody = await readJsonBody(req); - } catch { - return json({ error: "invalid submit body" }, 400); - } - const prepared = withGeneratedSetId(rawBody); - const ext = - prepared && typeof prepared === "object" && !Array.isArray(prepared) ? (prepared as Record) : {}; - const candidate = ext.decisionSet !== undefined ? ext.decisionSet : prepared; - const v = validateDecisionSet(candidate); - if (!v.ok) return json({ error: v.error }, 400); - const source = typeof ext.source === "string" && ext.source ? ext.source : "decisions-ledger"; - // #9354 refresh mode: a sibling `refresh: true` opts a standing - // (ledger-mirror) set into refreshDecisionSet — contents are - // replaced, token/createdAt/source and resolutions-by-qid are - // preserved. No push and no set.created event on a refresh: the - // set is not new, and a standing set refreshed hourly must not - // push hourly. Refresh of a not-yet-existing set is a normal - // create (201, created: true, push + set.created as usual). - const refresh = ext.refresh === true; - const before = await getDecisionSet(cfg.decisionsFile, v.value.setId).catch(() => null); - try { - if (refresh && before) { - const set = await refreshDecisionSet(cfg.decisionsFile, v.value, source); - // The event log accepts a set-level "edit" event without a - // questionRef (validateDecisionEventInput / the type enum - // include "edit"), so a refresh is recorded that way. - await logDecisionEvents([ - { - setId: set.setId, - type: "edit", - payload: { - via: "api/decision-sets", - refresh: true, - items: set.items.length, - questions: set.items.reduce((n, i) => n + i.questions.length, 0), - }, - }, - ]); - const pageUrl = decisionsPageUrl(set); - return json({ setId: set.setId, pageUrl, url: pageUrl, created: false, refreshed: true }, 200); - } - const set = await raiseDecisionSet(cfg.decisionsFile, v.value, source); - if (!before) { - await logDecisionEvents([ - { - setId: set.setId, - type: "set.created", - payload: { - via: "api/decision-sets", - source, - title: set.title, - items: set.items.length, - questions: set.items.reduce((n, i) => n + i.questions.length, 0), - }, - }, - ]); - requestAlertTick(); - } - const pageUrl = decisionsPageUrl(set); - return json({ setId: set.setId, pageUrl, url: pageUrl, created: !before }, before ? 200 : 201); - } catch (err) { - console.error(`decision-sets submit: raise failed (${err instanceof Error ? err.message : "error"})`); - return json({ error: "decision set raise failed" }, 500); - } - } - // Decision-set events: read (activity processor polling) + report - // (the page's draft/edit events). Two prefixes name the same routes: - // /api/decision-sets//events (the documented contract) and - // /api/decisions//events (the page's own prefix). - // Auth: the intake bearer OR the per-set token (as ?t=, as a bearer, - // or — for POST — as body.token). Nothing about the set's events is - // served without one of them. - const decisionEventsMatch = /^\/api\/(?:decision-sets|decisions)\/([^/]+)\/events$/.exec(path); - if ((req.method === "GET" || req.method === "POST") && decisionEventsMatch) { - const setId = decodePathSegment(decisionEventsMatch[1]); - if (setId === null) return json({ error: "bad setId" }, 400); - const set = await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); - if (!set) return json({ error: "unknown set" }, 404); - const bearer = (req.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "").trim(); - const tokenOk = (t: unknown): boolean => typeof t === "string" && t.length > 0 && t === set.token; - if (req.method === "GET") { - const qToken = url.searchParams.get("t") ?? ""; - if (!tokenOk(qToken) && !tokenOk(bearer) && !(await alertsIntakeAuthorized(req))) { - return json({ error: "unknown set or bad token" }, 403); - } - const since = url.searchParams.get("since") ?? undefined; - const limitRaw = Number(url.searchParams.get("limit") ?? ""); - const page = await readDecisionEvents(cfg.decisionsEventsFile, setId, { - since, - ...(Number.isFinite(limitRaw) && limitRaw > 0 ? { limit: limitRaw } : {}), - }); - return json({ setId, events: page.events, nextCursor: page.nextCursor, count: page.count }); - } - let evBody: { token?: unknown; events?: unknown }; - try { - evBody = (await readJsonBody(req)) as typeof evBody; - } catch { - return json({ error: "invalid events body" }, 400); - } - if (!tokenOk(evBody.token) && !tokenOk(bearer) && !(await alertsIntakeAuthorized(req))) { - return json({ error: "unknown set or bad token" }, 403); - } - if (!Array.isArray(evBody.events) || evBody.events.length < 1 || evBody.events.length > 32) { - return json({ error: "events must be an array of 1-32 entries" }, 400); - } - const inputs: DecisionEventInput[] = []; - for (const rawEv of evBody.events) { - const ve = validateDecisionEventInput(rawEv); - if (!ve.ok) return json({ error: ve.error }, 400); - inputs.push({ - setId, - type: ve.value.type, - ...(ve.value.questionRef ? { questionRef: ve.value.questionRef } : {}), - payload: ve.value.payload, - }); - } - const stored = await appendDecisionEvents(cfg.decisionsEventsFile, cfg.decisionsOutboxFile, inputs).catch( - () => null, - ); - if (!stored) return json({ error: "event append failed" }, 500); - return json({ appended: stored.length, eventIds: stored.map((e) => e.eventId) }); - } // --- Decision sets (#8766) ------------------------------------------- // --- Decision-sets index (#8867) -------------------------------------- // GET /decisions: every set in the store, counts computed live at @@ -4467,345 +1295,30 @@ async function handler(req: Request): Promise { // Cloudflare Access), and each row links onward to the set's own // token-carrying page. if (req.method === "GET" && path === "/decisions") { - const sets = await listDecisionSets(cfg.decisionsFile).catch(() => [] as DecisionSet[]); - const viewParam = url.searchParams.get("view"); - const view: DecisionSetView = isDecisionSetView(viewParam) ? viewParam : "all"; - return html(renderDecisionsIndex(sets, view, url.searchParams.get("open") === "1")); - } - const decisionsPageMatch = /^\/decisions\/([^/]+)$/.exec(path); - if (req.method === "GET" && decisionsPageMatch) { - const setId = decodePathSegment(decisionsPageMatch[1]); - const token = url.searchParams.get("t") ?? ""; - const set = setId === null ? null : await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); - // Unknown set or token mismatch: 403, and the set is never rendered - // — the per-set token is the only authority here. - if (!set || !token || token !== set.token) return html(renderDecisionsForbidden(), 403); - return html(renderDecisionsPage(set)); - } - const decisionsSubmitMatch = /^\/api\/decisions\/([^/]+)\/submit$/.exec(path); - if (req.method === "POST" && decisionsSubmitMatch) { - const setId = decodePathSegment(decisionsSubmitMatch[1]); - if (setId === null) return json({ error: "bad setId" }, 400); - let body: { token?: unknown; submissions?: unknown }; - try { - body = (await readJsonBody(req)) as typeof body; - } catch { - return json({ error: "invalid submit body" }, 400); - } - // No bearer: the per-set token is the authority. - const set = await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); - if (!set || typeof body.token !== "string" || body.token !== set.token) { - return json({ error: "unknown set or bad token" }, 403); - } - const parsedSubs = parseDecisionSubmissions(body.submissions); - if (!parsedSubs.ok) return json({ error: parsedSubs.error }, 400); - const result = await recordResolutions(cfg.decisionsFile, setId, parsedSubs.value); - if (!result) return json({ error: "unknown set" }, 404); - await logDecisionEvents( - result.outcomes - .filter((o) => o.applied) - .map((o) => { - const sub = parsedSubs.value.find((x) => x.qid === o.qid)!; - return { - setId, - type: eventTypeForKind(sub.kind), - questionRef: questionRefFor(set, sub.ledgerId, sub.qid), - payload: submissionEventPayload(sub), - } satisfies DecisionEventInput; - }), - ); - return json({ outcomes: result.outcomes, ...decisionSetOpenState(result.set) }); - } - const decisionsDeferMatch = /^\/api\/decisions\/([^/]+)\/defer$/.exec(path); - if (req.method === "POST" && decisionsDeferMatch) { - const setId = decodePathSegment(decisionsDeferMatch[1]); - if (setId === null) return json({ error: "bad setId" }, 400); - let body: { - token?: unknown; - lean?: unknown; - ledgerIds?: unknown; - allRemaining?: unknown; - submissions?: unknown; - comment?: unknown; - }; - try { - body = (await readJsonBody(req)) as typeof body; - } catch { - return json({ error: "invalid defer body" }, 400); - } - // No bearer: the per-set token is the authority. - const set = await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); - if (!set || typeof body.token !== "string" || body.token !== set.token) { - return json({ error: "unknown set or bad token" }, 403); - } - if (!isDeferLean(body.lean)) { - return json({ error: "lean must be none|skeptical|approve" }, 400); - } - const all = body.allRemaining === true; - const ledgerIds = Array.isArray(body.ledgerIds) - ? body.ledgerIds.filter((x): x is string => typeof x === "string") - : []; - if (!all && ledgerIds.length === 0) { - return json({ error: "ledgerIds or allRemaining required" }, 400); - } - // Filled answers win over the bulk defer (#8766): submissions the - // page gathered from filled-in fields are recorded FIRST, and only - // the still-unanswered questions in scope are deferred. - let submissions: DecisionSubmission[] = []; - if (body.submissions !== undefined) { - const parsedSubs = parseDecisionSubmissions(body.submissions); - if (!parsedSubs.ok) return json({ error: parsedSubs.error }, 400); - submissions = parsedSubs.value; - } - const result = await deferWithSubmissions( - cfg.decisionsFile, - setId, - submissions, - all ? { allRemaining: true as const } : { ledgerIds }, - body.lean, - typeof body.comment === "string" ? body.comment : undefined, - ); - if (!result) return json({ error: "unknown set" }, 404); - await logDecisionEvents([ - ...result.outcomes - .filter((o) => o.applied) - .map((o) => { - const sub = submissions.find((x) => x.qid === o.qid)!; - return { - setId, - type: eventTypeForKind(sub.kind), - questionRef: questionRefFor(set, sub.ledgerId, sub.qid), - payload: submissionEventPayload(sub), - } satisfies DecisionEventInput; - }), - ...(result.deferredCount > 0 - ? [ - { - setId, - type: "defer" as const, - payload: { - bulk: true, - deferredCount: result.deferredCount, - lean: body.lean as string, - scope: all ? "allRemaining" : "checked", - }, - } satisfies DecisionEventInput, - ] - : []), - ]); - return json({ - outcomes: result.outcomes, - deferredCount: result.deferredCount, - ...decisionSetOpenState(result.set), - }); - } - const decisionsReqInfoMatch = /^\/api\/decisions\/([^/]+)\/request-info$/.exec(path); - if (req.method === "POST" && decisionsReqInfoMatch) { - const setId = decodePathSegment(decisionsReqInfoMatch[1]); - if (setId === null) return json({ error: "bad setId" }, 400); - let body: { token?: unknown; note?: unknown; ledgerIds?: unknown; allRemaining?: unknown }; - try { - body = (await readJsonBody(req)) as typeof body; - } catch { - return json({ error: "invalid request-info body" }, 400); - } - // No bearer: the per-set token is the authority. - const set = await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); - if (!set || typeof body.token !== "string" || body.token !== set.token) { - return json({ error: "unknown set or bad token" }, 403); - } - const all = body.allRemaining === true; - const ledgerIds = Array.isArray(body.ledgerIds) - ? body.ledgerIds.filter((x): x is string => typeof x === "string") - : []; - if (!all && ledgerIds.length === 0) { - return json({ error: "ledgerIds or allRemaining required" }, 400); - } - const result = await requestInfoOpenQuestions( - cfg.decisionsFile, - setId, - all ? { allRemaining: true as const } : { ledgerIds }, - typeof body.note === "string" ? body.note : undefined, - ); - if (!result) return json({ error: "unknown set" }, 404); - if (result.requestedCount > 0) { - await logDecisionEvents([ - { - setId, - type: "request-info", - payload: { - bulk: true, - requestedCount: result.requestedCount, - scope: all ? "allRemaining" : "checked", - ...(typeof body.note === "string" && body.note ? { note: body.note.slice(0, 2000) } : {}), - }, - }, - ]); - } - return json({ requestedCount: result.requestedCount, ...decisionSetOpenState(result.set) }); + return handleDecisionsIndex(url); } + const decisionTailResponse = await handleDecisionTailRoutes(req, url, path); + if (decisionTailResponse) return decisionTailResponse; - const decisionsDraftsMatch = /^\/api\/decisions\/([^/]+)\/drafts$/.exec(path); - if ((req.method === "GET" || req.method === "POST") && decisionsDraftsMatch) { - const setId = decodePathSegment(decisionsDraftsMatch[1]); - if (setId === null) return json({ error: "bad setId" }, 400); - const set = await getDecisionSet(cfg.decisionsFile, setId).catch(() => null); - if (req.method === "GET") { - const token = url.searchParams.get("t") ?? ""; - // Unknown set or token mismatch: 403, nothing about the set's - // drafts is shown without the correct link. - if (!set || !token || token !== set.token) { - return json({ error: "unknown set or bad token" }, 403); - } - const drafts = await getDecisionDrafts(cfg.decisionsFile, setId).catch(() => null); - return json({ - drafts: drafts ?? { questions: {}, bulk: [], bulkLean: "", bulkNote: "", updatedAt: "" }, - }); - } - let body: { token?: unknown; drafts?: unknown }; - try { - body = (await readJsonBody(req)) as typeof body; - } catch { - return json({ error: "invalid drafts body" }, 400); - } - // No bearer: the per-set token is the authority. - if (!set || typeof body.token !== "string" || body.token !== set.token) { - return json({ error: "unknown set or bad token" }, 403); - } - const parsedDrafts = validateDecisionDraftUpsert(body.drafts); - if (!parsedDrafts.ok) return json({ error: parsedDrafts.error }, 400); - const result = await upsertDecisionDrafts(cfg.decisionsFile, setId, parsedDrafts.value); - if (!result) return json({ error: "unknown set" }, 404); - await logDecisionEvents( - result.applied.map((qid) => { - const entry = result.drafts.questions[qid]; - const ledgerId = qid.slice(0, qid.lastIndexOf("#")) || qid; - return { - setId, - type: "draft" as const, - questionRef: questionRefFor(set, ledgerId, qid), - payload: { - ...(entry?.opt ? { opt: entry.opt } : {}), - ...(entry?.opts ? { opts: entry.opts } : {}), - ...(entry?.ft ? { freeText: entry.ft.slice(0, 2000) } : {}), - ...(entry?.lean ? { lean: entry.lean } : {}), - ...(entry?.note ? { note: entry.note.slice(0, 2000) } : {}), - }, - } satisfies DecisionEventInput; - }), - ); - return json({ drafts: result.drafts, applied: result.applied, skipped: result.skipped }); - } const alertActionMatch = /^\/api\/alerts\/([\w-]+)\/(ack|close)$/.exec(path); if (req.method === "POST" && alertActionMatch) { - const id = alertActionMatch[1]; - if (!UUID_RE.test(id)) return json({ error: "incident id must be a uuid" }, 400); - const store = await getAlertsStore(); - if (!store) return json({ error: "alerts store unavailable" }, 503); - const result = alertActionMatch[2] === "ack" ? await store.ackIncident(id) : await store.closeIncident(id); - if (!result.incident) return json({ error: "no such incident", id }, 404); - return json({ incident: result.incident, transitioned: result.transitioned }); + return handleAlertAction(alertActionMatch); } // Per-incident read (#12602): the incident plus its full ledger // event history — C6's detail path for the healthHook incident // records stored on the opened/closed event details. const alertReadMatch = /^\/api\/alerts\/([\w-]+)$/.exec(path); if (req.method === "GET" && alertReadMatch) { - const id = alertReadMatch[1]; - if (!UUID_RE.test(id)) return json({ error: "incident id must be a uuid" }, 400); - const store = await getAlertsStore(); - if (!store) return json({ error: "alerts store unavailable" }, 503); - const incident = await store.getIncident(id); - if (!incident) return json({ error: "no such incident", id }, 404); - const events = await store.listIncidentEvents(id); - return json({ incident, events }); + return handleAlertRead(alertReadMatch); } if (path === "/alerts" || path === "/api/alerts.json") { - const store = await getAlertsStore(); - if (!store) { - return path === "/alerts" - ? html( - renderAlerts( - { available: false, incidents: [], events: [], subscriptions: [], ackWindowMin: cfg.alerts.ackWindowMin }, - prov(), - VAPID_PUBLIC_KEY, - ), - ) - : json({ error: "alerts store unavailable" }, 503); - } - try { - const [incidents, events, subscriptions] = await Promise.all([ - store.listIncidents(), - store.recentEvents(), - store.listSubscriptions(), - ]); - if (path === "/api/alerts.json") return json({ incidents, events }); - return html( - renderAlerts( - { available: true, incidents, events, subscriptions, ackWindowMin: cfg.alerts.ackWindowMin }, - prov(), - VAPID_PUBLIC_KEY, - ), - ); - } catch { - return path === "/alerts" - ? html( - renderAlerts( - { available: false, incidents: [], events: [], subscriptions: [], ackWindowMin: cfg.alerts.ackWindowMin }, - prov(), - VAPID_PUBLIC_KEY, - ), - ) - : json({ error: "alerts store unavailable" }, 503); - } + return handleAlertsList(path, prov); } if (path === "/alerts/preferences" || path === "/api/alerts/preferences.json") { - // #3318: subscription preferences — per-class toggles, quiet - // hours, this-browser state, per-class test sends. Writes go - // through the existing /api/push/subscriptions upsert; this - // route only reads the stored subscriptions for the form. - const store = await getAlertsStore(); - if (!store) { - return path === "/alerts/preferences" - ? html(renderNotificationPreferences({ available: false, subscriptions: [] }, prov(), VAPID_PUBLIC_KEY)) - : json({ error: "alerts store unavailable" }, 503); - } - try { - const subscriptions = await store.listSubscriptions(); - if (path === "/api/alerts/preferences.json") - return json({ - available: true, - subscriptions: subscriptions.map(toPublicSubscription), - classes: NOTIFICATION_CLASSES, - defaults: NOTIFICATION_CLASS_DEFAULTS, - }); - return html(renderNotificationPreferences({ available: true, subscriptions }, prov(), VAPID_PUBLIC_KEY)); - } catch { - return path === "/alerts/preferences" - ? html(renderNotificationPreferences({ available: false, subscriptions: [] }, prov(), VAPID_PUBLIC_KEY)) - : json({ error: "alerts store unavailable" }, 503); - } + return handleAlertPreferences(path, prov); } if (path === "/notifications" || path === "/api/notifications.json") { - // #3319: the weekly sent-vs-acted roll-up over the send ledger. - // Same reachability as every dashboard page (the tailnet origin); - // the only alerts write surface stays the bearer-gated intake. - const store = await getAlertsStore(); - if (!store) { - return path === "/notifications" - ? html(renderNotifications({ available: false, rollup: null }, prov())) - : json({ error: "alerts store unavailable" }, 503); - } - try { - const sends = await store.listSends(); - const rollup = rollupNotificationSends(sends, new Date()); - if (path === "/api/notifications.json") return json(rollup); - return html(renderNotifications({ available: true, rollup }, prov())); - } catch { - return path === "/notifications" - ? html(renderNotifications({ available: false, rollup: null }, prov())) - : json({ error: "alerts store unavailable" }, 503); - } + return handleNotificationsPage(path, prov); } if (path === "/api/health") { // #1267: prime first — health's answer must not depend on @@ -5083,12 +1596,13 @@ if (source.ingestSnapshots) { // checkpoint untouched and is retried on the next tick. const GITHUB_HOT_LIST_INTERVAL_MS = 60_000; if (githubHotListConsumer) { + const hotListConsumer = githubHotListConsumer; let githubSyncRunning = false; const syncGithubHotList = async (): Promise => { if (githubSyncRunning) return; githubSyncRunning = true; try { - await githubHotListConsumer.sync(); + await hotListConsumer.sync(); if (githubOutcomeConsumer) { const outcome = await githubOutcomeConsumer.sync(); if (outcome.error) {