The import's Coding Agent Index rows — a model plus its agent harness and settings, checked as published. Kept strictly separate from the AA Intelligence Index rows above: no score is converted between the indexes. "Not published" costs stay blank rather than estimated. These rows power the explorer's Coding agents perspective.
The alerts ledger (Turso fleet-platform alerts_* tables) is unreachable from this process right now — intake, delivery, and ack are paused with it. The rest of the dashboard is unaffected.
`,
+ )
+ .join("");
+ // The push form's initial state is rendered from the newest stored
+ // subscription (Drew 2026-11-01): the page shows the saved truth on
+ // load even before — or entirely without — the client script
+ // matching this browser's own subscription. The client script
+ // still refines it per-browser via applyPrefs once it runs.
+ const formSub = [...view.subscriptions].sort((a, b) => (a.last_seen_at < b.last_seen_at ? 1 : -1))[0];
+ const formIncidentChecked = !formSub || formSub.classes?.incident !== false;
+ const formQuietOn = !formSub || formSub.quiet?.enabled !== false;
+ const formQuietStart = formSub?.quiet?.start ?? "23:00";
+ const formQuietEnd = formSub?.quiet?.end ?? "07:00";
+ const body = `
Alerts
+
The alert throat (#3676): every sentinel posts to one intake; this page is the ack surface. Critical incidents push immediately to subscribed browsers; an unacknowledged critical escalates once after ${view.ackWindowMin} minutes. Warnings are recorded here and in the ledger — no push in v1. Machine-first: /api/alerts.json. Per-class toggles, quiet hours, and per-class test sends live on the notification preferences page.
+
+
Push delivery on this browser
+
+checking…
+
+
+
On iPhone, Apple only allows web push from the installed app:
+
+
Open this page in Safari — if you got here from inside another app, use its menu to open the page in Safari instead.
+
Tap the Share button, then Add to Home Screen.
+
Open the dashboard from the new home-screen icon, come back to this Alerts page, and tap Enable push on this browser — and tap Allow when it asks about notifications.
+
+
+
+
This browser can't receive web push — most often because the page is open inside another app (an in-app browser) or in a browser without push support. Open this page's address in your regular browser (Chrome, Safari, or Firefox) and enable push there.
+
+
+
+A watchdog reports something down. Incident alerts always come through immediately, the moment they're posted.
+
+Pause non-urgent notifications overnight, between and (Chicago time). Untick the box for no time-of-day limit at all. Incident alerts always come through immediately, quiet hours or not.
`;
+ const script = ``;
+ return layout("Alerts", body, provenance, "/alerts", script);
+}
+
+// --- Notification preferences page (#3318, slice (d) of #1254) ------------
+
+export interface NotificationPreferencesView {
+ available: boolean;
+ subscriptions: PushSubscriptionRow[];
+}
+
+/** The /alerts/preferences page: per-class subscription toggles,
+ * quiet-hours editing, this browser's subscription state, and a
+ * send-test button per class. Preferences are subscription state —
+ * saving writes through the same /api/push/subscriptions upsert the
+ * Alerts form uses (provided-classes merge: only the keys sent
+ * change), and the engine reads the stored map via classEnabled /
+ * inQuietHours on its next tick, so a toggle here IS the next
+ * engine decision. The route is /alerts/preferences, not
+ * /notifications: that route is the #3319 measurement page and
+ * stays read-only. */
+export function renderNotificationPreferences(
+ view: NotificationPreferencesView,
+ provenance: Provenance,
+ vapidPublicKey: string,
+): string {
+ if (!view.available) {
+ return layout(
+ "Notification preferences",
+ `
Notification preferences
The alerts ledger (Turso fleet-platform alerts_* tables) is unreachable from this process right now — subscription preferences cannot be read or saved until it is back. The rest of the dashboard is unaffected.
`,
+ provenance,
+ "/alerts/preferences",
+ );
+ }
+ // Same initial-state rule as the Alerts form: render the newest
+ // stored subscription's saved truth server-side; the client
+ // script refines it to this browser's own subscription.
+ const formSub = [...view.subscriptions].sort((a, b) => (a.last_seen_at < b.last_seen_at ? 1 : -1))[0];
+ const quietOn = !formSub || formSub.quiet?.enabled !== false;
+ const quietStart = formSub?.quiet?.start ?? "23:00";
+ const quietEnd = formSub?.quiet?.end ?? "07:00";
+ const classRows = NOTIFICATION_CLASSES.map((c) => {
+ const checked = !formSub || (formSub.classes?.[c.id] ?? NOTIFICATION_CLASS_DEFAULTS[c.id]) !== false;
+ return `
+${esc(c.blurb)}
+
`;
+ }).join("\n");
+ const body = `
Notification preferences
+
Per-class push preferences for this browser's subscription (#3318, slice (d) of the #1254 design). Toggling a class or editing quiet hours and saving changes the stored subscription; the notification engine reads the stored values on its next tick, so the change is the next engine decision. This browser's subscription state is shown below. Machine-first: /api/alerts/preferences.json. The /notifications page stays the read-only measurement roll-up (#3319).
+
This browser
+
+checking…
+
+
+
+
Classes
+${classRows}
+
+Pause non-urgent notifications between and (Chicago time). Untick for no time-of-day limit at all. Incident alerts always come through immediately, quiet hours or not; digest-only notifications wait for the quiet window to end.
+
+The digest is the one list-shaped landing allowed: the attention view filtered to the digest's refs.
The notification send ledger (Turso fleet-platform alerts_notification_sends) is unreachable from this process right now — the roll-up is paused with it. The rest of the dashboard is unaffected.
Proposal: default class ${esc(c.class)} off — acted-on ratio ${pct(c.ratio)} over the rolling window (${c.acted} of ${c.sent} sends acted on within 24h), under the 10% threshold. Proposal only — this page never changes a preference or a default. Turning a class off by default is Drew's call, made on the notification preferences page.
`,
+ )
+ .join("")}`
+ : `
Default-off proposals
No class is under the 10% acted-on threshold over the rolling window.
`;
+ const body = `
Notifications
+
Weekly sent-vs-acted-on roll-up over the alert throat's send ledger (alerts.notification_sends), rolling four weeks ending ${esc(fmtDate(rollup.asOf))}. Read-only: this page measures; it never changes a notification preference or default. Machine-first: /api/notifications.json.
+
How acted-on is counted (attribution)
+
A send counts as acted-on when the incident's Ack lands within 24 hours of the send: Ack is the exactly-once transition that stamps the send's acted_on_at, so it is the durable acted-on signal. Only ledger rows with outcome sent count as sends — suppressed (quiet hours / dedupe), gone, and error attempts never reached a device and never enter the denominator, and no send is inferred from delivered/escalated incident events. What this cannot attribute: reading a notification without acking, acting on the incident through another surface (GitHub, chat, a later dashboard visit that does not ack), and sends to subscriptions that were later removed — those count as sent-but-not-acted even when a human did see them. Test sends (class test) are real ledger rows and are reported as their own class.
+${rollup.undated ? `
${rollup.undated} ledger row(s) carried no usable send timestamp and were excluded from the roll-up.
` : ""}
+
Per class, per week
+${
+ rollup.classes.length
+ ? `
Sent vs acted-on by class and rolling week
class
${weekHeads}
rolling 4 weeks
${rows}
`
+ : `
No sends in the rolling four-week window.
`
+}
+${proposalHtml}`;
+ return layout("Notifications", body, provenance, "/notifications");
+}
+
+/** The digest page (#1278): renders a Digest verbatim — the archived
+ * JSON is the page's data, so a re-read shows exactly what was
+ * delivered to chat. /digest?date= renders that day's archive;
+ * /digest renders today's live build with the archive index. */
+export function renderDigest(
+ digest: Digest,
+ archives: { kind: DigestKind; date: string; route: string }[],
+ provenance: Provenance,
+ detail?: ProvenanceDetail,
+): string {
+ const freshness = digest.freshness.length
+ ? `
`;
+}
+
+const HORIZON_RANK: Record = { today: 0, "3d": 1, week: 2, month: 3, quarter: 4 };
+
+/** #1456: the order control for the Needs-you list — a preference
+ * action; the render applies the saved order immediately. */
+function needsOrderHtml(act: AttentionAct | undefined): string {
+ if (!act?.identities) return "";
+ const order = act.needsOrder ?? "urgency";
+ const labels: Record = {
+ urgency: "Urgency (orchestrator's order)",
+ newest: "Newest first",
+ oldest: "Oldest first",
+ deadline: "Deadline (horizon)",
+ };
+ const options = (Object.keys(labels) as NeedsOrder[])
+ .map((o) => ``)
+ .join("");
+ const form = aformHtml({
+ kind: "preference",
+ verb: "set-needs-order",
+ objectRef: NEEDS_ORDER_OBJECT_REF,
+ inner: `${act.needsOrderPending ? `⏳ change pending — the orchestrator's canonical order follows on its next pass` : ""}`,
+ });
+ return `
Needs-you list order: ${esc(labels[order])}${actboxHtml({ identities: act.identities }, form)}
`;
+}
+
+/** #1277: the per-card bulk-triage pick for one queue card. Renders
+ * only when the action surface is up (identities present); a card
+ * whose own controls are disabled (stale tier source) gets a disabled
+ * pick, so it cannot be submitted against an unconfirmed item. */
+function bulkPickHtml(
+ objectRef: string,
+ title: string,
+ act: AttentionAct | undefined,
+ disabledReason?: string,
+): string {
+ if (!act?.identities) return "";
+ return ``;
+}
+
+function bulkSnoozeOptions(): string {
+ const now = new Date();
+ const tonight = new Date(now);
+ tonight.setHours(23, 59, 0, 0);
+ const tomorrow = new Date(now);
+ tomorrow.setDate(tomorrow.getDate() + 1);
+ tomorrow.setHours(9, 0, 0, 0);
+ const nextWeek = new Date(now);
+ nextWeek.setDate(nextWeek.getDate() + 7);
+ nextWeek.setHours(9, 0, 0, 0);
+ return ``;
+}
+
+/** #1277: the bulk triage bar for the Needs-you queues — one verb
+ * applied to every picked card, with a review step that lists every
+ * selected item + the chosen action before anything is submitted.
+ * Submission goes to POST /api/actions/batch (BULK_SCRIPT below);
+ * each item lands as its own attributed action record. */
+function bulkBarHtml(act: AttentionAct | undefined): string {
+ if (!act?.identities) return "";
+ return `
`;
+}
+
+/**
+ * The client side of bulk triage (#1277): delegated listeners in the
+ * COMMENT_SCRIPT/ACTION_SCRIPT pattern, so Datastar fragment swaps
+ * keep working. Review builds nothing server-side; confirm POSTs one
+ * action object per picked card to /api/actions/batch and renders
+ * the per-item results — succeeded picks clear, failed picks stay
+ * checked (their items remain in Needs-you) with the error named.
+ */
+const BULK_SCRIPT = ``;
+
+/**
+ * The live "Questions" section (#9354): the open decision sets from
+ * the decision-set store, newest first, each linking to its own
+ * token page via `pageUrlFor`. Pure HTML from already-computed
+ * summaries — no I/O here, so tests render it directly.
+ * summaries === null means the store could not be read: the section
+ * says "unavailable" rather than rendering a confident zero (the
+ * needsDrewCensusHtml pattern). summaries === undefined means the
+ * caller predates the section and it is omitted entirely.
+ * Fully-resolved sets are excluded here as well as by callers, so
+ * the counts can never include a settled set.
+ */
+const QUESTIONS_STAMP = new Intl.DateTimeFormat("en-US", {
+ timeZone: "America/Chicago",
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ timeZoneName: "short",
+});
+
+export function questionsSectionHtml(
+ summaries: DecisionSetSummary[] | null | undefined,
+ pageUrlFor: (summary: DecisionSetSummary) => string,
+): string {
+ if (summaries === undefined) return "";
+ const allSetsLink = `
The NEEDS USER queue is an intake the orchestrator works first — it resolves what it can and escalates only what genuinely requires the user, each escalated item with its reason. Everything else the fleet can work is the orchestrator's own queue. Finished runs and stale items expire out (2 h after a run finishes, 24 h at the latest). Machine-first: /api/attention.json · /api/coverage.json. Incident alerts (watchdog push + ack) live on Alerts.
+${sections.header}${sections.queues}${sections.sessions}${questionsHtml}`,
+ provenance,
+ "/attention",
+ act?.identities ? ACTION_SCRIPT + COMMENT_SCRIPT + BULK_SCRIPT : "",
+ detail ? freshnessChips(detail, ["orchestration", "attention", "registry"]) : "",
+ );
+}
+
+/**
+ * The Needs-Drew label census section (#1226): open user/review +
+ * user/escalated items across the four repos, straight from GitHub —
+ * the labels are the system of record and this view only reads them.
+ * census === null means the source cannot census: the section says
+ * "unavailable" rather than rendering an empty, confident zero.
+ * census === undefined means the caller predates the census (tests,
+ * fragments) and the section is omitted entirely.
+ */
+export function needsDrewCensusHtml(census: NeedsDrewCensus | null | undefined): string {
+ if (census === undefined) return "";
+ if (census === null) {
+ return `
Needs Drew — GitHub label census
Unavailable — this source cannot census the user/review and user/escalated labels, so this queue cannot be reported here.
Label census incomplete — ${failed
+ .map((x) => {
+ if (!x.ok) return `${esc(x.repo)} ${esc(x.label)}: ${esc(x.error ?? "failed")}`;
+ // Truncation and GitHub's partial-search signal are different
+ // failures: say which one it was instead of blurring them.
+ const why = x.incomplete
+ ? "search returned incomplete results, count is a floor"
+ : "page cap reached, count is a floor";
+ return `${esc(x.repo)} ${esc(x.label)}: ${why}`;
+ })
+ .join("; ")}. The list below may be missing items from those sources.
`
+ : "";
+ // FDR-0013: only hands items and review requests are the owner's.
+ // A choice an agent parked on the owner is fleet work, listed apart
+ // so the page never presents it as waiting on him.
+ const hands = census.items.filter((i) => needsDrewWait(i) === "hands");
+ const review = census.items.filter((i) => needsDrewWait(i) === "review");
+ const parked = census.items.filter((i) => needsDrewWait(i) === "agent-decides");
+ const line = (i: NeedsDrewItem, note: string): string =>
+ `
`;
+ const reasonOf = (i: NeedsDrewItem): string =>
+ i.reason ? esc(i.reason) : "no reason recorded on the item — open it for context";
+ const answered = census.complete ? "" : " in the sources that answered";
+ const handsRows = hands.length
+ ? `
${hands
+ .map((i) =>
+ line(
+ i,
+ `${esc(i.hands?.kind ?? "hands")}: ${
+ i.hands?.action ? esc(i.hands.action) : "the item states the one action"
+ }`,
+ ),
+ )
+ .join("")}
`
+ : `
No open item needs a person's hands right now${answered}.
No open item carries user/review right now${answered}.
`;
+ const parkedRows = parked.length
+ ? `
An agent parked each of these on the owner without a hands action. They do not wait on him: an agent decides, records the decision on the item and continues (FDR-0013). This count should fall to zero.
Nothing is parked on the owner by an agent${answered}.
`;
+ const rows = `
Needs a person's hands (${hands.length})
${handsRows}
Review requested (${review.length})
${reviewRows}
Parked on the owner by an agent — fleet work (${parked.length})
${parkedRows}`;
+ return `
Needs Drew — GitHub label census (${hands.length + review.length})
Every open issue and PR carrying user/review or user/escalated across the four repos (#1226), split by how it waits. The count in the heading is hands items and review requests only. The labels are the system of record; this view reads them and never writes them. Census taken ${esc(census.fetchedAt)}${census.complete ? "" : " — incomplete, see below"}. Machine form: /api/needs-drew.json.
${failureNote}${rows}`;
+}
+
+/**
+ * The attention page in three independently loadable sections
+ * (#1444): header (banner / chips / coverage / standing default),
+ * queues (Needs User + Needs Orchestrator + the snoozed & hidden
+ * strips), sessions. The full page assembles them; the shell serves
+ * them as Datastar fragments from /frag/attention/*.
+ */
+export function attentionSections(
+ view: AttentionView,
+ coverage: SourceCoverage[],
+ counts?: Map,
+ act?: AttentionAct,
+ briefs?: Map,
+ census?: NeedsDrewCensus | null,
+): { header: string; queues: string; sessions: string } {
+ const children = sessionChildren(view.all);
+ const roots = sessionRoots(view.all);
+ // #1139: the tier source's state decides what the counts may claim.
+ // Absent/invalid → the orchestrator's published queues are NOT
+ // reflected here, so the banner says so and the headings render
+ // "unknown" rather than a confident number; stale → the numbers
+ // render, badged with the section's age. This banner is also
+ // #1148's aggregator-side dead-man's switch: if the orchestration
+ // job dies, this is the surface that says so.
+ const ts = view.tierSource;
+ const tierBanner = !ts.present
+ ? ts.state === "invalid"
+ ? `
Tier source invalid — the orchestration section is present but failed validation (${esc((ts.failedChecks ?? []).join(", ") || "unknown check")}); showing session-derived items only — the orchestrator's published queues are NOT reflected in the counts below.
`
+ : `
Tier source missing — showing session-derived items only; the orchestrator's published queues are NOT reflected in the counts below.
`
+ : ts.state === "stale"
+ ? `
Tier source stale — the last orchestration section (${esc(ts.runId ?? "unknown run")}) is ${esc(ts.generatedAt ? feedAgeText(ts.generatedAt) : "old")}; the queues below are its last published state and may have moved since.
`
+ : "";
+ const sectionStamp =
+ ts.present && ts.runId
+ ? ` · section ${esc(ts.runId)} · ${esc(ts.generatedAt ? feedAgeText(ts.generatedAt) : "")}`
+ : "";
+ // #1152: section-derived items disable their controls whenever the
+ // tier source is not live — stale items come from the publisher's
+ // last section and may no longer exist in its current view (absent/
+ // invalid sources serve no section items at all). Session-derived
+ // items stay enabled: the session feed is live.
+ const sectionDisabledReason =
+ ts.state !== "live"
+ ? `the tier source is ${ts.state}, so this item cannot be confirmed against the orchestrator's current published queues`
+ : undefined;
+ const tierAct = (item: TierItem) => {
+ const objectRef = tierItemObjectRef(item);
+ // #1148 watchdog cards describe the aggregator's CURRENT diagnosis,
+ // not the publisher's possibly-obsolete section, so the #1152 gate
+ // must not disable them: the orchestration-outage card is exactly
+ // the one that has to stay actionable while the tier source is
+ // absent/invalid/stale (Codex P2, PR #2431).
+ const disabledReason = item.source === "watchdog" ? undefined : sectionDisabledReason;
+ return {
+ actions: act?.actionsByObject?.get(objectRef),
+ identities: act?.identities,
+ ...(disabledReason ? { disabledReason } : {}),
+ comments: act?.commentsByObject?.get(objectRef),
+ commentOpts: act?.commentOpts,
+ };
+ };
+ const sessionAct = act
+ ? {
+ actionsByObject: act.actionsByObject,
+ identities: act.identities,
+ commentsByObject: act.commentsByObject,
+ commentOpts: act.commentOpts,
+ }
+ : undefined;
+
+ // #1443/#1449/#1450: partition every queue entry by its render-time
+ // effective state. A suppressed entry (active snooze, dismiss, or
+ // mark-done — pending counts, exactly like applied) leaves its list
+ // NOW and lands in the matching strip with its way back; the counts
+ // below are the VISIBLE counts, so acting on a card visibly moves
+ // the numbers.
+ const now = Date.now();
+ const snoozedList: StripEntry[] = [];
+ const hiddenList: StripEntry[] = [];
+ const inViewRefs = new Set();
+ const partition = (
+ objectRef: string,
+ title: string | null | undefined,
+ actions: DashAction[] | undefined,
+ ): CardState => {
+ inViewRefs.add(objectRef);
+ const cs = cardState(actions, now);
+ if (cs.suppressed) {
+ (cs.suppressed.kind === "snoozed" ? snoozedList : hiddenList).push({ objectRef, title: title ?? undefined, cs });
+ }
+ return cs;
+ };
+ interface QueuedCard {
+ html: string;
+ sinceMs: number;
+ seenMs: number;
+ rank: number;
+ }
+ const drewCardsList: QueuedCard[] = [];
+ for (const e of view.drew) {
+ const objectRef = sessionObjectRef(e.sessionId);
+ const cs = partition(objectRef, e.title ?? e.sessionId, act?.actionsByObject?.get(objectRef));
+ if (cs.suppressed) continue;
+ drewCardsList.push({
+ html: bulkPickHtml(objectRef, e.title ?? e.sessionId, act) + sessionCard(e, children, 0, counts, sessionAct),
+ sinceMs: Date.parse(e.lastActivityAt ?? "") || 0,
+ seenMs: Date.parse(e.lastActivityAt ?? "") || 0,
+ rank: 5,
+ });
+ }
+ for (const item of view.drewExtra) {
+ const objectRef = tierItemObjectRef(item);
+ const cs = partition(objectRef, item.title, act?.actionsByObject?.get(objectRef));
+ if (cs.suppressed) continue;
+ const drewAct = tierAct(item);
+ drewCardsList.push({
+ html:
+ bulkPickHtml(objectRef, item.title, act, drewAct.disabledReason) +
+ tierItemCard(item, "Why you", counts, drewAct) +
+ (item.ref ? briefPanelsForRefs([item.ref], briefs) : ""),
+ sinceMs: Date.parse(item.since) || 0,
+ seenMs: Date.parse(item.lastSeenAt) || 0,
+ rank: item.horizon ? (HORIZON_RANK[item.horizon] ?? 5) : 5,
+ });
+ }
+ // #1456: the saved card order applies at render. "urgency" is the
+ // published order (no sort); the rest sort the visible list.
+ // #1485: every order sorts on the single sinceMs axis (when the card
+ // entered the queue), so newest and oldest are exact reverses. seenMs
+ // (lastSeenAt) is NOT the axis: a stale card seen recently would lead
+ // both orders. Deadline ties break oldest-waiting first (ascending
+ // sinceMs), matching the deadline/urgency reading.
+ const order = act?.needsOrder ?? "urgency";
+ if (order === "newest") drewCardsList.sort((a, b) => b.sinceMs - a.sinceMs);
+ else if (order === "oldest") drewCardsList.sort((a, b) => a.sinceMs - b.sinceMs);
+ else if (order === "deadline") drewCardsList.sort((a, b) => a.rank - b.rank || a.sinceMs - b.sinceMs);
+ const orchCardsList: string[] = [];
+ for (const e of view.orchestrator) {
+ const objectRef = sessionObjectRef(e.sessionId);
+ const cs = partition(objectRef, e.title ?? e.sessionId, act?.actionsByObject?.get(objectRef));
+ if (cs.suppressed) continue;
+ orchCardsList.push(
+ bulkPickHtml(objectRef, e.title ?? e.sessionId, act) + sessionCard(e, children, 0, counts, sessionAct),
+ );
+ }
+ for (const item of view.orchestratorExtra) {
+ const objectRef = tierItemObjectRef(item);
+ const cs = partition(objectRef, item.title, act?.actionsByObject?.get(objectRef));
+ if (cs.suppressed) continue;
+ const orchAct = tierAct(item);
+ orchCardsList.push(
+ bulkPickHtml(objectRef, item.title, act, orchAct.disabledReason) +
+ tierItemCard(item, "Why the fleet", counts, orchAct) +
+ (item.ref ? briefPanelsForRefs([item.ref], briefs) : ""),
+ );
+ }
+ // Store-only suppressed refs: items the publisher no longer lists
+ // (their dismissal was applied and they left the tiers) stay visible
+ // — and restorable — here, never silently gone (#1450).
+ for (const [objectRef, actions] of act?.actionsByObject?.entries() ?? []) {
+ if (inViewRefs.has(objectRef)) continue;
+ const cs = cardState(actions, now);
+ if (cs.suppressed) {
+ (cs.suppressed.kind === "snoozed" ? snoozedList : hiddenList).push({ objectRef, cs });
+ }
+ }
+
+ const drewVisible = drewCardsList.length;
+ const orchVisible = orchCardsList.length;
+ const drewCount = ts.present ? String(drewVisible) : "unknown";
+ const orchCount = ts.present ? String(orchVisible) : "unknown";
+ const chips = `
These items are out of the queues until their snooze expires — the orchestration pass omits them, and they resurface on their own. Unsnoozing records a superseding action.
${snoozedList.map((e) => stripCardHtml(e, act?.identities)).join("")}`
+ : "";
+ const hiddenStrip = hiddenList.length
+ ? `Dismissed / done by you (${hiddenList.length}) — hidden from the queues; restore any of them to re-review or add a note${hiddenList.map((e) => stripCardHtml(e, act?.identities)).join("")}`
+ : "";
+ const queues = `${bulkBarHtml(act)}${needsOrderHtml(act)}
Needs User (${drewCount})${sectionStamp}
${drewCards}
+${snoozedStrip}${hiddenStrip}
Needs Orchestrator (${orchCount})${sectionStamp}
The orchestration job (#899) reviews this queue and pushes work back into motion; it escalates to the user queue only what truly needs the user.
Every current session with its source and state; sub-sessions collapse under their parent.
${sessionCards}
+${view.expiredCount ? `
${view.expiredCount} finished or stale ${view.expiredCount === 1 ? "entry" : "entries"} expired out of this view.
` : ""}`;
+ return { header, queues, sessions };
+}
+
+/** Wrap one attention section as a Datastar fragment container: the
+ * shell's placeholder and the fragment payload share this shape, so
+ * a refresh re-patches the container with itself (attrs included).
+ *
+ * `initial` marks the shell placeholder (#10605): it carries
+ * `data-init` so the first paint fetches the section with no
+ * freshness event. The `/frag/*` payload that replaces it (outer
+ * mode) must leave `initial` off — a re-initialising element would
+ * fetch itself again on every patch, i.e. loop.
+ */
+export function attentionFragment(
+ section: "header" | "queues" | "sessions",
+ innerHtml: string,
+ query = "",
+ options: { initial?: boolean } = {},
+): string {
+ const q = query ? `?${query}` : "";
+ const init = options.initial ? ` data-init="@get('/frag/attention/${section}${q}')"` : "";
+ return `
${innerHtml}
`;
+}
+
+/**
+ * The Datastar shell for /attention (#1444): nav + headings paint
+ * immediately; the three heavy sections stream in as fragments.
+ * Without JS, a meta refresh lands on the full server render.
+ */
+export function renderAttentionShell(
+ provenance: Provenance,
+ detail?: ProvenanceDetail,
+ refs?: string,
+ questionsHtml = "",
+): string {
+ const refsQuery = refs ? `refs=${encodeURIComponent(refs)}` : "";
+ const skel = (label: string) => `
Loading ${label}…
`;
+ const body = `
Needs you
Loading the Needs User and Needs Orchestrator queues…
+${attentionFragment("header", skel("queue status"), refsQuery, { initial: true })}
+${attentionFragment("queues", skel("the queues"), refsQuery, { initial: true })}
+${attentionFragment("sessions", skel("sessions"), refsQuery, { initial: true })}${questionsHtml}`;
+ return layout(
+ "Needs you",
+ body,
+ provenance,
+ "/attention",
+ ACTION_SCRIPT + COMMENT_SCRIPT + BULK_SCRIPT + FRAG_WATCHDOG_SCRIPT,
+ detail ? freshnessChips(detail, ["orchestration", "attention", "registry"]) : "",
+ );
+}
diff --git a/pm-stack/aggregator/src/render-board.ts b/pm-stack/aggregator/src/render-board.ts
new file mode 100644
index 0000000000..671f213168
--- /dev/null
+++ b/pm-stack/aggregator/src/render-board.ts
@@ -0,0 +1,758 @@
+// render.ts split (#13051): board, roadmap and item-detail views.
+// render.ts re-exports every public name from here; callers keep importing "./render.ts".
+
+import {
+ type RoadmapGrain,
+ allRefs,
+ commentStream,
+ executionStrip,
+ monthTimeline,
+ roadmapDayGrain,
+ timeline as buildTimeline,
+} from "./derive.ts";
+import type { RoadmapReconciliation } from "./roadmap-reconcile.ts";
+import type { RoadmapAnnotation } from "./roadmap-annotations.ts";
+import type { ReleaseSnapshot } from "./releases.ts";
+import { formatForecastSummary, type ForecastContract } from "./forecast-contract.ts";
+import type { FlowAnalytics } from "./flow-analytics.ts";
+import { flowChartsHtml } from "./flow-charts.ts";
+import type { DashAction } from "./actions.ts";
+import { applyBoardDonePolicy, DONE_STRIP_RENDER_LIMIT, selectVisibleDoneCards } from "./board-policy.ts";
+import { summarizeWipLanes } from "./wip-limits.ts";
+import type { CommentKindCounts } from "./comments.ts";
+import type { ItemServiceLink } from "./service-links.ts";
+import { activityCoverageHtml, gapsHtml, type ActivityCoverage, type GapRecord } from "./activity.ts";
+import type { AuditEvent } from "./events.ts";
+import {
+ type BoardItem,
+ type Comment,
+ type DashComment,
+ type GhItem,
+ type ProjectPoolItem,
+ type Provenance,
+ type ProvenanceDetail,
+ type RefKey,
+ type RoadmapRow,
+ type SessionRecord,
+ isValidRef,
+ refUrl,
+} from "./model.ts";
+import { canonicalStatusFor, ghItemDerivedStatus } from "./status-taxonomy.ts";
+import type { ItemBrief } from "./brief.ts";
+import { isEpicChildDone, uniqueProjectItemsByRef, type EpicRollup } from "./epics.ts";
+import { spendCardHtml, unattributedSpendHtml, type SpendCardsView } from "./spend-cards.ts";
+import type { AuthorIdentity } from "./registry.ts";
+
+import {
+ esc,
+ fmtDate,
+ COMMENT_SCRIPT,
+ ROADMAP_ANNOTATION_SCRIPT,
+ FRAG_WATCHDOG_SCRIPT,
+ ACTION_SCRIPT,
+ freshnessChips,
+ layout,
+ ghObjectRef,
+ commentBadge,
+ authorBadge,
+ dashCommentHtml,
+ type CommentFormOpts,
+ authorOptionsHtml,
+ commentFormHtml,
+ actionBadgesHtml,
+ statusRequestHtml,
+ sessionActionsHtml,
+ sessionRecordIsLive,
+ itemBadge,
+ stripHtml,
+ briefPanelsForRefs,
+} from "./render-core.ts";
+
+// --- Board view -----------------------------------------------------------
+
+/** The board's card grid alone (#1444 fragment payload). */
+export function renderBoardBody(
+ board: BoardItem[],
+ items: Map,
+ counts?: Map,
+ act?: {
+ actionsByObject?: Map;
+ poolByRef?: Map;
+ identities?: AuthorIdentity[];
+ briefs?: Map;
+ },
+ renderOpts?: { showAllDone?: boolean },
+): string {
+ // #1146: finished work is not WIP — aged-out done items and the
+ // retired ROADMAP Done-table class never reach the board, whatever
+ // source assembled it (the Kaneo source filters too; see
+ // board-policy.ts). Surviving done renders collapsed, below.
+ board = applyBoardDonePolicy(board);
+ const wipByLane = new Map(
+ summarizeWipLanes(board, [...(act?.poolByRef?.values() ?? [])]).map((summary) => [summary.lane, summary]),
+ );
+ const cols = new Map();
+ for (const item of board) {
+ const key = item.status === "done" ? "done" : item.status;
+ const k = key === "to-do" ? "to-do" : key;
+ cols.set(k, [...(cols.get(k) ?? []), item]);
+ }
+ for (const lane of wipByLane.keys()) {
+ if (!cols.has(lane)) cols.set(lane, []);
+ }
+ const order = ["in-flight", "to-do", "in-progress", "in-review", "done"];
+ const extra = [...cols.keys()].filter((k) => !order.includes(k));
+ const bodies = [...order, ...extra]
+ .filter((k) => cols.has(k))
+ .map((k) => {
+ const colItems = cols.get(k) ?? [];
+ // #1179: the done strip renders only the most recent
+ // DONE_STRIP_RENDER_LIMIT cards (newest first); the rest are
+ // one click away (?done=all). Rendering all ~950 cost ~1 MB.
+ let visibleItems = colItems;
+ let doneNote = "";
+ if (k === "done" && colItems.length > DONE_STRIP_RENDER_LIMIT) {
+ visibleItems = selectVisibleDoneCards(colItems, { showAll: renderOpts?.showAllDone ?? false });
+ if (renderOpts?.showAllDone) {
+ doneNote = ` — showing all, newest first; show fewer`;
+ } else {
+ doneNote = ` — showing the ${DONE_STRIP_RENDER_LIMIT} most recent; show all ${colItems.length}`;
+ }
+ }
+ const cards = visibleItems
+ .map((item) => {
+ const repo = item.repo ? `${esc(item.repo)} ` : "";
+ const cmt = counts ? commentBadge(item.id, counts) : "";
+ const briefs = briefPanelsForRefs(
+ item.links.map((link) => link.ref),
+ act?.briefs,
+ );
+ if (item.source === "orchestrator") {
+ // Synthetic in-flight entry: visibly not a Kaneo card. Its
+ // GitHub refs link directly (no execution strip — the
+ // projector may not know these refs yet).
+ const status = item.orchStatus ? `${esc(item.orchStatus)} ` : "";
+ const goal = item.goal ? ` goal: ${esc(item.goal)}` : "";
+ const blocked = item.blockedBy?.length
+ ? ` Blocked by: ${item.blockedBy.map(esc).join("; ")}`
+ : "";
+ const refs = item.links.length
+ ? `
`;
+ })
+ .join("");
+ // The in-flight lane is dated by the orchestration section that
+ // produced it (stamped on every synthetic entry as updatedAt).
+ if (k === "done") {
+ // Collapsed by default (#1146): a count + the last 7 days
+ // behind an expander, never a full column of finished cards.
+ return `Done recently (${colItems.length}) — done in the last 7 days, collapsed by default; older done is aged off the board (GitHub is the record)${doneNote}${cards}`;
+ }
+ const heading =
+ k === "in-flight"
+ ? `in flight — orchestrator · in flight · section ${fmtDate(colItems[0]?.updatedAt)} (${colItems.length}/${wipByLane.get(k)?.cap ?? 0})`
+ : `${esc(k)} (${colItems.length}/${wipByLane.get(k)?.cap ?? 0})`;
+ const summary = wipByLane.get(k);
+ const scopeFlags = [
+ ...(summary?.projects ?? [])
+ .filter((scope) => scope.overCap)
+ .map((scope) => `project ${scope.key} ${scope.count}/${scope.cap}`),
+ ...(summary?.epics ?? [])
+ .filter((scope) => scope.overCap)
+ .map((scope) => `epic ${scope.key} ${scope.count}/${scope.cap}`),
+ ];
+ if (summary?.overCap) scopeFlags.unshift(`lane over cap by ${summary.count - summary.cap}`);
+ const overCapBadges = scopeFlags
+ .map((flag) => `${esc(flag)}`)
+ .join(" ");
+ return `
What is being worked on now is the in-flight lane: synthetic entries from the orchestrator's lined-up tasks (the fleet feed's orchestration section), not Kaneo cards. The other columns are the curated Kaneo board across the four repos, including its completion history — on their own they are a record of finished and in-review work, not a live WIP list. Each Kaneo card's execution strip is derived from its linked issues/PRs: implementing → review → merged.
What is being worked on now is the in-flight lane: synthetic entries from the orchestrator's lined-up tasks (the fleet feed's orchestration section), not Kaneo cards.
Loading the board…
`,
+ provenance,
+ "/board",
+ ACTION_SCRIPT + FRAG_WATCHDOG_SCRIPT,
+ detail ? freshnessChips(detail, ["board", "items", "orchestration"]) : "",
+ );
+}
+
+// --- Roadmap view ----------------------------------------------------------
+
+const GRAINS: [RoadmapGrain, string][] = [
+ ["quarter", "Quarter"],
+ ["month", "Month"],
+ ["week", "Week"],
+ ["3d", "Next 3 days"],
+ ["today", "Today"],
+];
+
+/** One roadmap row's drill-down (#1168): its matched Project epic
+ * (absent when the row is unmatched) and the epic's pool children —
+ * the pool items whose epicRef names the epic (#2399). */
+export interface RoadmapDrill {
+ epic?: ProjectPoolItem;
+ children: ProjectPoolItem[];
+}
+
+/** Build the per-row drill-down index from a reconciliation and the
+ * Project pool, keyed by the row's registry subject. Every row gets
+ * an entry, so an unmatched row is distinguishable from drill data
+ * never having been supplied. Callers pass no index at all when the
+ * reconciliation is unavailable — a failed source read must not
+ * masquerade as "no epic yet" (#1144's availability rule). */
+export function buildRoadmapDrill(
+ rows: RoadmapRow[],
+ reconciliation: RoadmapReconciliation,
+ pool: ProjectPoolItem[],
+): Map {
+ const epicByRow = new Map(reconciliation.matched.map((m) => [m.row.subject, m.epic] as const));
+ const childrenByEpic = new Map();
+ for (const item of uniqueProjectItemsByRef(pool)) {
+ if (!item.epicRef) continue;
+ const list = childrenByEpic.get(item.epicRef) ?? [];
+ list.push(item);
+ childrenByEpic.set(item.epicRef, list);
+ }
+ return new Map(
+ rows.map((row) => {
+ const epic = epicByRow.get(row.subject);
+ return [row.subject, { epic, children: epic ? (childrenByEpic.get(epic.ref) ?? []) : [] }] as const;
+ }),
+ );
+}
+
+/** The shared forecast contract (§4, #3984) as page lines: the same
+ * one-line summaries the API serves, never a bare date. */
+export function forecastSummaryHtml(contracts: ForecastContract[] | undefined): string {
+ if (!contracts?.length) return "";
+ const lines = contracts.map((c) => `
`;
+}
+
+export function renderRoadmap(
+ rows: RoadmapRow[],
+ items: Map,
+ provenance: Provenance,
+ grain: RoadmapGrain = "quarter",
+ counts?: Map,
+ detail?: ProvenanceDetail,
+ reconciliation?: RoadmapReconciliation,
+ drill?: Map,
+ annotations?: Map,
+ viewQuery = "",
+ briefs?: Map,
+ forecasts?: Map,
+ flowAnalytics?: FlowAnalytics,
+ spend?: SpendCardsView | null,
+ releases: ReleaseSnapshot[] = [],
+ prioritiesView = false,
+): string {
+ // #1144: when the Grist rows and the Project's Kind=Epic pool items
+ // disagree, say so on the page itself — drift the reader can see,
+ // with the full lists published in /api/roadmap.json.
+ const driftFlag =
+ reconciliation?.availability === "unavailable"
+ ? `
Roadmap reconciliation unavailable: ${esc(reconciliation.unavailableReason ?? "a roadmap source could not be read")} — no drift is asserted when a source read failed (#1144).
Roadmap drift: ${reconciliation.unmatchedRows.length} Grist row${reconciliation.unmatchedRows.length === 1 ? "" : "s"} with no matching Project epic · ${reconciliation.unmatchedEpics.length} Project epic${reconciliation.unmatchedEpics.length === 1 ? "" : "s"} with no roadmap row (#1144 — the two roadmap sources disagree; both lists are in /api/roadmap.json).
${invalidHorizons.length} roadmap row${invalidHorizons.length === 1 ? " has" : "s have"} an invalid Horizon value. Original values are preserved and marked on their cards; correct them in Grist using the documented Horizon grammar.
Grist's Program roadmap table at every grain — one data model, switchable horizon. Rows with a calendar date land on their day; quarter-labelled rows stay at quarter grain. Every row remains visible at every grain.
${chips}
${driftFlag}${horizonFlag}${body}${releasesHtml}${spend?.unattributed ? unattributedSpendHtml(spend.unattributed) : ""}${flowAnalytics ? flowChartsHtml(flowAnalytics) : ""}`,
+ provenance,
+ "/roadmap",
+ "",
+ detail ? freshnessChips(detail, ["roadmap", "items"]) : "",
+ );
+}
+
+// --- Item drill-down -------------------------------------------------------
+
+export interface ItemExtras {
+ /** Dashboard comments (#906 §2) across this item's object refs. */
+ dashComments: DashComment[];
+ /** Present only on roadmap rows; undefined on ordinary board items. */
+ roadmapAnnotations?: RoadmapAnnotation[];
+ /** The object ref the inline form posts to (the item's subject). */
+ formRef: string;
+ formOpts: CommentFormOpts;
+ /** Registry sessions loosely linked to this item's refs (#906 §3). */
+ sessions: SessionRecord[];
+ /** Dashboard actions across this item's object refs (#1152/#1154). */
+ actions?: DashAction[];
+ /** Set when one of the item's refs is in the Project pool (#1154). */
+ statusRequest?: { objectRef: string; targetRef: RefKey; currentStatus: string | null };
+ /** Outbound links to the live services this item lives in (#1136). */
+ serviceLinks?: ItemServiceLink[];
+ /** Present when this item's Project-pool entry is an epic. */
+ epicRollup?: EpicRollup;
+ /** Honest chain summary derived from the live Project pool. */
+ genealogySentence?: string;
+ /** Project-pool briefs for linked refs (#1279). */
+ briefs?: Map;
+ /** Real ready-for-agent dispatch state for explicitly labelled linked issues. */
+ dispatchStates?: { ref: RefKey; state: string; provenance: { source: string; observedAt: string } }[];
+ /** The shared audit stream, scoped to the item's canonical refs. */
+ activity?: { events: AuditEvent[]; globalHref: string; gaps: GapRecord[]; coverage?: readonly ActivityCoverage[] };
+}
+
+function roadmapAnnotationFormHtml(objectRef: string, identities: AuthorIdentity[]): string {
+ return ``;
+}
+
+export function epicRollupHtml(rollup: EpicRollup): string {
+ const statusMix = rollup.statusMix.length
+ ? rollup.statusMix.map(({ status, count }) => `${esc(status)} ${count}`).join(" · ")
+ : "none";
+ const children = rollup.total
+ ? `Children: ${rollup.done}/${rollup.total} done`
+ : `Children: 0 resolved · completion unknown`;
+ return `
No matching events; this does not establish complete coverage.
'}
`;
+}
+
+/** #1500: the honest empty-section wording, keyed off the provenance
+ * strings the renderers already receive — no new data plumbing. The
+ * comment stream is fixture-sourced while the projector is off (#1199),
+ * so a bare "no comments" would claim a fact about the work when it is
+ * really a fact about the dashboard's resolution path. */
+export const FIXTURE_COMMENTS_CAUSE = "the comment stream is fixture-sourced while the projector is off (#1199)";
+
+export function commentsFixtureSourced(provenance: Provenance): boolean {
+ return provenance.comments.startsWith("fixtures");
+}
+
+export function fixtureCommentsBannerHtml(provenance: Provenance): string {
+ return commentsFixtureSourced(provenance)
+ ? `
The comment stream is fixture-sourced while the projector is off (#1199) — GitHub comments may be missing or stale, and an empty stream does not mean the work has no discussion.
`,
+ )
+ .join("");
+ // #1500: when some linked refs did not resolve, the Linked header
+ // carries the tally and the cause; when every ref resolves it stays
+ // plain. The fixture cause is keyed off the items provenance string
+ // only (the partial-fixtures shape from sources/live.ts, or a fully
+ // fixture-sourced items facet).
+ const linkedResolved = all.length;
+ const linkedHeader =
+ links.length > 0 && linkedResolved < links.length
+ ? `Linked issues / PRs — ${links.length} linked · ${linkedResolved} resolved — ${
+ /\+ fixtures for \d+ ref\(s\) outside the pool/.test(provenance.items) ||
+ provenance.items.startsWith("fixtures")
+ ? "resolution fell back to fixtures (projector off, #1199)"
+ : "some linked refs could not be resolved from the current sources"
+ }`
+ : "Linked issues / PRs";
+ const commentsBanner = fixtureCommentsBannerHtml(provenance);
+ const emptyCommentRow = commentsFixtureSourced(provenance)
+ ? `
Freshness: unknown. The ingestion checkpoint records deliveries, not successful source polls. An empty event list does not establish complete coverage. Known gaps and documented source coverage are shown below.
${eventTableHtml(extras.activity.events)}
Known activity gaps
Gap records are source-scoped and do not currently identify affected item refs, so this is the global known-gap list.
+ ${activitySection}${sessionSection}${statusSection}${roadmapAnnotationSection}${dashSection}`,
+ provenance,
+ "/board",
+ extras
+ ? COMMENT_SCRIPT +
+ (extras.roadmapAnnotations !== undefined ? ROADMAP_ANNOTATION_SCRIPT : "") +
+ (extras.statusRequest ? ACTION_SCRIPT : "")
+ : "",
+ );
+}
+
+/** One registry record as a compact line (item page, sessions page). */
+export function sessionRecordLine(
+ r: SessionRecord,
+ act?: { actions?: DashAction[]; identities?: AuthorIdentity[] },
+): string {
+ const tokens = r.tokensTotal != null ? ` · ${r.tokensTotal.toLocaleString()} tok` : "";
+ const parent = r.parentId
+ ? ` · sub of ${esc(r.parentId)}`
+ : "";
+ const renderedRefs = r.taskRefs.map((ref) => {
+ // #6243 (ref contract rule 4, #6242): a malformed ref may still
+ // exist in an older or ungated in-memory record. Keep the session
+ // visible and render the invalid ref as plain text — the same
+ // treatment tierItemCard (#6149) and poolRefLink give it — never
+ // a throw, and never silently omitted.
+ return isValidRef(ref) ? `${esc(ref)}` : esc(ref);
+ });
+ const refs = renderedRefs.length ? ` · ${renderedRefs.join(" ")}` : "";
+ // #1156: live records carry the session action set on the merged
+ // registry identity; historical records render no controls.
+ const badges = actionBadgesHtml(act?.actions);
+ const controls =
+ act?.identities && sessionRecordIsLive(r) ? sessionActionsHtml(r.id, r.source, { identities: act.identities }) : "";
+ const provenance =
+ r.provenance === "verified"
+ ? `verified identity`
+ : `asserted-legacy — identity is a claim`;
+ return `
${esc(r.label)}${esc(r.source)}${esc(r.agentLabel)} ${provenance}${badges} ${esc(r.id)} · ${esc(r.status)}${r.model ? ` · ${esc(r.model)}` : ""} · started ${fmtDate(r.startedAt)} · last seen ${fmtDate(r.lastSeenAt)}${tokens}${parent}${refs}${controls}
`;
+}
diff --git a/pm-stack/aggregator/src/render-core.ts b/pm-stack/aggregator/src/render-core.ts
new file mode 100644
index 0000000000..678e56c07c
--- /dev/null
+++ b/pm-stack/aggregator/src/render-core.ts
@@ -0,0 +1,1460 @@
+// render.ts split (#13051): shared primitives: escaping/formatting, page layout and nav, comment and action forms, session helpers, coverage strip, item briefs.
+// render.ts re-exports every public name from here; callers keep importing "./render.ts".
+
+import { executionStrip } from "./derive.ts";
+import { latestInFamily, newClientToken, type DashAction } from "./actions.ts";
+import { cardState, pendingVerb, type CardState } from "./card-state.ts";
+import {
+ DELEGATION_DEFAULT_OBJECT_REF,
+ effectiveStandingAuto,
+ proposalExpired,
+ proposalIdentity,
+ questionIdForOption,
+} from "./tier-items.ts";
+import type { CommentKindCounts } from "./comments.ts";
+import { ageMsText } from "./feed.ts";
+import {
+ type BoardItem,
+ type DashAuthor,
+ type DashComment,
+ type DelegationMode,
+ type GhItem,
+ type Provenance,
+ type ProvenanceDetail,
+ type RefKey,
+ type SessionRecord,
+ type SourceCoverage,
+ type TierItem,
+ type TierItemQuestion,
+ type WhyUserClass,
+ isValidRef,
+ refUrl,
+} from "./model.ts";
+import { groupedPages, primaryGroupedPages, manifestRouteFor, pageByRoute } from "./pages.ts";
+import { KEY_HINT, KEYBOARD_SCRIPT, paletteHtml } from "./keyboard.ts";
+import { CANONICAL_STATUSES } from "./status-taxonomy.ts";
+import type { ItemBrief } from "./brief.ts";
+import type { AuthorIdentity } from "./registry.ts";
+import type { SearchResult } from "./search-view.ts";
+
+export function esc(s: unknown): string {
+ return String(s ?? "")
+ .replace(/&/g, "&")
+ .replace(//g, ">")
+ .replace(/"/g, """)
+ .replace(/'/g, "'");
+}
+
+export function fmtDate(iso: string | null | undefined): string {
+ if (!iso) return "—";
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return iso;
+ return d
+ .toISOString()
+ .replace("T", " ")
+ .replace(/\.\d+Z$/, "Z");
+}
+
+/** Central-time stamp for Drew-facing quota/reset surfaces (#9553):
+ * "Sat, Nov 14, 8:00 AM CST". fmtDate above renders raw UTC ISO; the
+ * /quota page (pool resets, wall lifts, freshness, burn windows) must
+ * never show UTC to Drew, so renderQuota uses this formatter. */
+const centralFmt = new Intl.DateTimeFormat("en-US", {
+ timeZone: "America/Chicago",
+ weekday: "short",
+ month: "short",
+ day: "numeric",
+ hour: "numeric",
+ minute: "2-digit",
+ timeZoneName: "short",
+});
+
+export function fmtCentral(iso: string | null | undefined): string {
+ if (!iso) return "—";
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return iso;
+ return centralFmt.format(d);
+}
+
+/* The stylesheet lives in src/ui.css (Tailwind v4 + DaisyUI v5 plus the
+ legacy component rules below it) and is built to the committed static
+ asset src/assets/app.css by `bun run build:css` — see the README's
+ "Styling" section. Do not inline page CSS here. */
+
+/** Canonical tailnet URL for this dashboard (MagicDNS — never the raw IP). */
+export const TAILNET_URL = "http://amd-6.raptor-pumpkinseed.ts.net:4870";
+
+/**
+ * Shared post-submit feedback (#1443): the click must visibly land.
+ * The card's controls disable, a "✓ sent · pending" line appears in
+ * place, and a suppressing verb (snooze / dismiss / mark-done)
+ * tombstones the card immediately — the server render (via the
+ * Datastar fragment refresh this dispatches, or the next page load)
+ * then moves it to its strip for real. Pages without Datastar
+ * fragment containers keep the historical full reload.
+ */
+export const DASH_AFTER_JS = `
+window.__dashAfter = window.__dashAfter || function (form, msg) {
+ var card = form.closest(".card");
+ form.querySelectorAll("button, input, select, textarea").forEach(function (b) { b.disabled = true; });
+ if (card) {
+ var line = document.createElement("div");
+ line.className = "sentline";
+ line.textContent = msg;
+ card.appendChild(line);
+ var verb = form.dataset.verb;
+ if (verb === "snooze" || verb === "dismiss" || verb === "mark-done") card.classList.add("tombstone");
+ }
+ window.dispatchEvent(new CustomEvent("dashrefresh"));
+ if (!document.querySelector("[data-frag]")) location.reload();
+};
+window.__dashAuthorPickers = window.__dashAuthorPickers || function () {
+ var fill = function (list) {
+ document.querySelectorAll("select[name=author][data-author-picker]").forEach(function (s) {
+ if (s.dataset.hydrated) return;
+ var cur = s.value;
+ var frag = document.createDocumentFragment();
+ list.forEach(function (i) {
+ var o = document.createElement("option");
+ o.value = i.kind + "|" + i.id + "|" + (i.sessionId || "");
+ o.textContent = i.label + (i.kind === "agent" ? " (agent)" : "");
+ if (i.id === "drew") o.defaultSelected = true;
+ frag.appendChild(o);
+ });
+ s.replaceChildren(frag);
+ s.value = cur;
+ s.dataset.hydrated = "1";
+ });
+ };
+ if (window.__dashIdentities) { fill(window.__dashIdentities); return; }
+ if (window.__dashIdentitiesPromise) return;
+ window.__dashIdentitiesPromise = fetch("/api/author-identities")
+ .then(function (r) { return r.json(); })
+ .then(function (d) { window.__dashIdentities = (d && d.identities) || []; fill(window.__dashIdentities); })
+ .catch(function () { window.__dashIdentitiesPromise = null; });
+};
+if (!window.__dashAuthorPickerHook) {
+ window.__dashAuthorPickerHook = true;
+ document.addEventListener("pointerdown", function (ev) {
+ var t = ev.target;
+ if (t && t.closest && t.closest("select[name=author][data-author-picker], .actbox, .cbox")) window.__dashAuthorPickers();
+ });
+ document.addEventListener("focusin", function (ev) {
+ var t = ev.target;
+ if (t && t.matches && t.matches("select[name=author][data-author-picker]")) window.__dashAuthorPickers();
+ });
+}
+`;
+
+/**
+ * The client side of the comment form (one delegated submit handler;
+ * pages without a form never notice it). Kept dependency-free and
+ * inline, like everything else in this app. The card comment box
+ * (#1446) posts kind "message" for the orchestrator and — when its
+ * "also post publicly" box is ticked and the card carries a gh: ref
+ * in data-ghref — a second, kind "github" comment the orchestrator
+ * posts to the issue (the aggregator holds no GitHub credentials).
+ */
+export const COMMENT_SCRIPT = ``;
+
+export const ROADMAP_ANNOTATION_SCRIPT = ``;
+
+/**
+ * The client side of the dashboard action forms (#1152/#1154/#1156):
+ * one delegated submit handler, exactly the COMMENT_SCRIPT pattern —
+ * POST /api/actions, reload on success, inline error on failure. The
+ * form's data-* attributes carry the envelope's fixed fields; named
+ * inputs carry the payload. A stop form must have its confirm box
+ * ticked before the script will send it (two-step confirm).
+ */
+/** Shell fragment watchdog (#1503): the shell pages stream their real
+ * content in as Datastar fragments; if a fragment request fails or stalls
+ * there is no error path in the markup, so the page would sit on its
+ * skeleton forever. Ten seconds after the shell renders, any [data-frag]
+ * container still holding its .skel skeleton gets the skeleton swapped for
+ * an inline notice linking the ?full=1 server render (the no-JS path).
+ * A fragment that lands in time removes the skeleton itself, so the
+ * watchdog no-ops; a fragment that lands late replaces the notice. */
+export const FRAG_WATCHDOG_MS = 10_000;
+export const FRAG_WATCHDOG_SCRIPT = ``;
+
+export const ACTION_SCRIPT = ``;
+
+/** Facet labels for the freshness chips (#1138) — the footer nouns. */
+const FACET_LABELS: Record = {
+ board: "board",
+ roadmap: "roadmap",
+ items: "items",
+ comments: "comments",
+ quota: "quota",
+ usage: "usage",
+ attention: "attention",
+ orchestration: "orchestration",
+ dns: "dns",
+ registry: "registry",
+ aa: "aa",
+};
+
+/**
+ * Per-source freshness chips (#1138): only the sources the page being
+ * rendered actually uses, each with its state word, its age when the
+ * source carries one, and any count WITH its noun — a chip count and
+ * a page header counting the same thing read the same variable, so
+ * the two can never disagree unexplained. The facet's full provenance
+ * string rides in the title attribute for whoever is debugging.
+ */
+export function freshnessChips(detail: ProvenanceDetail, keys: (keyof Provenance)[]): string {
+ const chips = keys
+ .map((key) => {
+ const facet = detail[key];
+ const count = facet.count !== undefined ? ` · ${facet.count} ${esc(facet.countLabel ?? "")}`.trimEnd() : "";
+ const age = facet.ageMs !== undefined && facet.state !== "fixtures" ? ` · ${ageMsText(facet.ageMs)}` : "";
+ return `${FACET_LABELS[key]} · ${facet.state}${count}${age}`;
+ })
+ .join("");
+ return `
${chips}
`;
+}
+
+/**
+ * The grouped nav links (#1135, #1215, #1497): one labelled section
+ * per PAGE_GROUP, in bar order, marking the active page's section.
+ * Since the #1497 curation the bar renders the PRIMARY-tier pages
+ * only; the Pages dropdown keeps every manifest page under the same
+ * sections, so demoted pages stay one click away.
+ */
+export function navLinks(active: string, activeGroup?: string): string {
+ // A sub-route (/program/, /quota/service/) marks the page that
+ // reaches it, so the bar always shows where you are (#1135).
+ const activeRoute = manifestRouteFor(active) ?? active;
+ const groupOfActive = activeGroup ?? pageByRoute(activeRoute)?.group;
+ let activeMarked = false;
+ return primaryGroupedPages()
+ .map(({ group, pages }) => {
+ const anchors = pages
+ .map((p) => {
+ const isActive = p.route === activeRoute && !activeMarked;
+ if (isActive) activeMarked = true;
+ return `${esc(p.title)}`;
+ })
+ .join("");
+ const current = group.id === groupOfActive ? ' data-current="true"' : "";
+ return `${esc(group.title)}${anchors}`;
+ })
+ .join("");
+}
+
+/**
+ * The Pages dropdown (#906 §1, #1215, #1497): the same grouped model
+ * as the bar — one