From fc08943b19e6c73f409371696702ae522acc3771 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 08:03:44 +0000 Subject: [PATCH] pm-stack: split render.ts (8,515 lines) into render-*.ts view modules (#13051) render.ts is now a barrel re-exporting every public name, so server.ts, error-boundary.ts and the test suites keep importing the same names from ./render.ts. The split is a mechanical move of contiguous regions behind the existing renderX exports; cross-module references became imports and shared private helpers were export-promoted in their home module. No behavior change: module bodies are verbatim. Removes render.ts's grandfather entry from check-production-line-limit.sh in the same PR, per the guard convention. Six test files read src/render.ts as source text (a11y table scan, freshness wiring, mobile targets, nav, setups store, UI overhaul); they now scan the render module set (render.ts + render-*.ts) - the same code at its new locations, assertions unchanged. The freshness oracle's per-file list names the three fragment-shell modules that carry the dashrefresh listener form. --- .../scripts/check-production-line-limit.sh | 1 - pm-stack/aggregator/src/render-aa.ts | 2009 ++++ pm-stack/aggregator/src/render-alerts.ts | 561 ++ pm-stack/aggregator/src/render-attention.ts | 827 ++ pm-stack/aggregator/src/render-board.ts | 758 ++ pm-stack/aggregator/src/render-core.ts | 1460 +++ pm-stack/aggregator/src/render-dns.ts | 101 + pm-stack/aggregator/src/render-program.ts | 1235 +++ pm-stack/aggregator/src/render-quota.ts | 720 ++ pm-stack/aggregator/src/render-today.ts | 558 ++ pm-stack/aggregator/src/render-views.ts | 493 + pm-stack/aggregator/src/render.ts | 8627 +---------------- pm-stack/aggregator/test/a11y-1215.test.ts | 10 +- .../test/freshness-fallback-3976.test.ts | 15 +- .../aggregator/test/mobile-targets.test.ts | 13 +- pm-stack/aggregator/test/nav.test.ts | 13 +- .../aggregator/test/setups-store-2851.test.ts | 11 +- pm-stack/aggregator/test/ui-overhaul.test.ts | 10 +- 18 files changed, 8895 insertions(+), 8527 deletions(-) create mode 100644 pm-stack/aggregator/src/render-aa.ts create mode 100644 pm-stack/aggregator/src/render-alerts.ts create mode 100644 pm-stack/aggregator/src/render-attention.ts create mode 100644 pm-stack/aggregator/src/render-board.ts create mode 100644 pm-stack/aggregator/src/render-core.ts create mode 100644 pm-stack/aggregator/src/render-dns.ts create mode 100644 pm-stack/aggregator/src/render-program.ts create mode 100644 pm-stack/aggregator/src/render-quota.ts create mode 100644 pm-stack/aggregator/src/render-today.ts create mode 100644 pm-stack/aggregator/src/render-views.ts diff --git a/.github/scripts/check-production-line-limit.sh b/.github/scripts/check-production-line-limit.sh index eaca2cdc16..c7815e8d3d 100755 --- a/.github/scripts/check-production-line-limit.sh +++ b/.github/scripts/check-production-line-limit.sh @@ -49,7 +49,6 @@ declare -A GRANDFATHERED=( # guard was extended to TypeScript; each split has its own issue # (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 diff --git a/pm-stack/aggregator/src/render-aa.ts b/pm-stack/aggregator/src/render-aa.ts new file mode 100644 index 0000000000..43acee6289 --- /dev/null +++ b/pm-stack/aggregator/src/render-aa.ts @@ -0,0 +1,2009 @@ +// render.ts split (#13051): AA cost-explorer view and its inline explorer script. +// render.ts re-exports every public name from here; callers keep importing "./render.ts". + +import { aaCaiPoints, aaPoints, summarizeAa } from "./aa.ts"; +import { ageMsText } from "./feed.ts"; +import type { AaCaiRow, AaConfig, AaFeedSection, AaSection, AaTestRun, Provenance, ProvenanceDetail } from "./model.ts"; + +import { esc, fmtDate, freshnessChips, layout } from "./render-core.ts"; + +// --- AA cost explorer page (ainventory import data via the fleet feed) ----- + +/** + * The Cost Explorer's client side: tabs, the shared filter bar, the + * three frontier charts, and both tables, all rendered from the + * #xpl-data JSON the server embeds (aaPoints + catalog, computed in + * src/aa.ts). Dependency-free inline script, like COMMENT_SCRIPT. + * Written without template literals on purpose — it lives inside one. + */ +const AA_EXPLORER_SCRIPT = ``; + +function fmtCost(v: number | null): string { + return v == null ? "—" : `$${Number(v.toFixed(4))}`; +} + +function fmtSec(v: number | null): string { + if (v == null) return "—"; + if (v < 60) return `${Number(v.toFixed(1))}s`; + return `${Math.floor(v / 60)}m ${Math.round(v % 60)}s`; +} + +function fmtTimed(v: number | null): string { + return v == null ? 'not measured' : fmtSec(v); +} + +/** "openai|gpt-6-luna|max|reasoning|fallback-na" -> "gpt-6-luna · max". */ +function variantLabel(modelVariantKey: string): string { + const parts = modelVariantKey.split("|"); + return parts.length >= 3 ? `${parts[1]} · ${parts[2]}` : modelVariantKey; +} + +function aaTimingsTable(testRuns: AaTestRun[]): string { + const rows = testRuns + .map( + (r) => + `${esc(variantLabel(r.modelVariantKey))}
${esc(r.snapshotDate ?? "no snapshot date")}${r.intelligence ?? "—"}${fmtCost(r.costPerTaskUsd)}${fmtTimed(r.ttftSeconds)}${fmtTimed(r.firstAnswerSeconds)}${fmtTimed(r.e2e500Seconds)}${fmtTimed(r.timePerTaskSeconds)}${r.outputSpeedTps ?? "—"}`, + ) + .join(""); + return `
${rows || ''}
Model configurations — intelligence and cost
ConfigurationIntelligence$/taskTTFTFirst answerE2E (500 tok)Time / taskSpeed (t/s)
none
`; +} + +function aaConfigsTable(configs: AaConfig[]): string { + const rows = configs + .map( + (c) => + `${esc(c.modelName)}${esc(c.effort ?? "—")}${c.intelligence ?? "—"}${fmtCost(c.costPerTaskUsd)}${c.speedTps ?? "—"}`, + ) + .join(""); + return `
${rows || ''}
Models — effort, intelligence, cost, and speed
ModelEffort (AA label)Intelligence$/taskSpeed (t/s)
none
`; +} + +function aaCaiTable(rowsIn: AaCaiRow[]): string { + const pct = (v: number | null): string => (v == null ? "—" : `${Number((v * 100).toFixed(1))}%`); + const rows = rowsIn + .map( + (r) => + `${esc(r.family)}
${esc(r.creator)}${r.snapshotDate ? ` · ${esc(r.snapshotDate)}` : ""}${esc(r.effort ?? "—")}${esc(r.harness ?? "—")}${esc(r.version ?? "—")}${r.score ?? "—"}${pct(r.deepSwe)}${pct(r.terminalBench)}${pct(r.sweAtlas)}${fmtCost(r.cost)}${fmtTimed(r.wallSec)}${r.tokensPerTask != null ? Math.round(r.tokensPerTask).toLocaleString("en-US") : "—"}`, + ) + .join(""); + return `

Coding Agent Index observations

+

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.

+
${rows || ''}
Model benchmark scores
ModelEffortHarnessVersionCAI scoreDeepSWE v1.1Terminal-Bench 4.0SWE-Atlas-QnA$/taskAgent wall time / taskTokens / task
none
`; +} + +function aaNameList(names: string[]): string { + return names.length + ? `
${names.map((n) => `${esc(n)}`).join("")}
` + : '

none

'; +} + +/** JSON for a `; + return layout("Cost Explorer", body, provenance, "/aa", AA_EXPLORER_SCRIPT, aaFreshnessChips(detail, section)); +} diff --git a/pm-stack/aggregator/src/render-alerts.ts b/pm-stack/aggregator/src/render-alerts.ts new file mode 100644 index 0000000000..f3e5a2f7d7 --- /dev/null +++ b/pm-stack/aggregator/src/render-alerts.ts @@ -0,0 +1,561 @@ +// render.ts split (#13051): alerts, notification preferences, notifications and digest views. +// render.ts re-exports every public name from here; callers keep importing "./render.ts". + +import { DIGEST_SECTION_LIMIT, type Digest, type DigestKind } from "./digest.ts"; +import type { Incident, IncidentEvent, PushSubscriptionRow } from "./alerts.ts"; +import type { NotificationRollup } from "./notifications.ts"; +import { NOTIFICATION_CLASS_DEFAULTS, NOTIFICATION_CLASSES } from "./notifications.ts"; +import type { Provenance, ProvenanceDetail } from "./model.ts"; + +import { esc, fmtDate, freshnessChips, layout } from "./render-core.ts"; + +// --- Alerts page (#3676, the alert throat) --------------------------------- + +export interface AlertsPageView { + available: boolean; + incidents: Incident[]; + events: IncidentEvent[]; + subscriptions: PushSubscriptionRow[]; + ackWindowMin: number; +} + +function incidentCard(i: Incident): string { + const sev = i.severity === "critical" ? "closed" : i.severity === "warning" ? "implementing" : "open"; + const times = [ + `first seen ${fmtDate(i.first_seen_at)}`, + i.occurrences > 1 ? `${i.occurrences} occurrences, last ${fmtDate(i.last_seen_at)}` : null, + i.delivered_at + ? `pushed ${fmtDate(i.delivered_at)}` + : i.severity === "critical" && i.status === "open" + ? "not yet pushed" + : null, + i.escalated_at ? `escalated ${fmtDate(i.escalated_at)}` : null, + i.acked_at ? `acked ${fmtDate(i.acked_at)}` : null, + i.closed_at ? `closed ${fmtDate(i.closed_at)}` : null, + ] + .filter(Boolean) + .join(" · "); + const actions = + i.status === "open" + ? ` ` + : i.status === "acked" + ? `` + : ""; + return `
+${esc(i.title)} ${esc(i.severity)} ${esc(i.status)} +${i.body ? `
${esc(i.body)}` : ""} +
source ${esc(i.source)} · key ${esc(i.incident_key)} · ${esc(times)} +${actions ? `
${actions}` : ""} +
`; +} + +function subscriptionRow(s: PushSubscriptionRow): string { + let host = s.endpoint; + try { + host = new URL(s.endpoint).host; + } catch {} + const classes = Object.entries(s.classes ?? {}) + .map(([k, v]) => `${esc(k)}: ${v ? "on" : "off"}`) + .join(", "); + const quiet = + s.quiet?.enabled === false + ? "quiet hours off" + : `quiet hours ${s.quiet?.start ?? "?"}–${s.quiet?.end ?? "?"} ${s.quiet?.tz ?? ""}`; + return `
${esc(host)} subscribed ${fmtDate(s.created_at)} · classes ${esc(classes || "—")} · ${esc(quiet)}${s.gone_count ? ` · gone ×${s.gone_count}` : ""} +
${esc(s.user_agent ?? "")} +
`; +} + +export function renderAlerts(view: AlertsPageView, provenance: Provenance, vapidPublicKey: string): string { + if (!view.available) { + return layout( + "Alerts", + `

Alerts

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.

`, + provenance, + "/alerts", + ); + } + const open = view.incidents.filter((i) => i.status !== "closed"); + const closed = view.incidents.filter((i) => i.status === "closed"); + const events = view.events + .map( + (e) => + `${fmtDate(e.at)}${esc(e.kind)}${esc(e.title ?? e.incident_id)}${esc(e.source ?? "")}${e.incident_key ? ` · ${esc(e.incident_key)}` : ""}`, + ) + .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… + +


+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.

+ + + + +
+
+

Subscriptions (${view.subscriptions.length})

+${view.subscriptions.length ? view.subscriptions.map(subscriptionRow).join("") : `

No push subscriptions yet — enable push above.

`} +

Open incidents (${open.length})

+${open.length ? open.map(incidentCard).join("") : `

No open incidents. Silence is golden.

`} +${closed.length ? `

Closed (recent)

${closed.map(incidentCard).join("")}` : ""} +

Ledger — recent transitions

+
${events}
Recent alert-ledger transitions
atkindincidentsource · key
`; + 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.
+


+

Subscriptions (${view.subscriptions.length})

+${view.subscriptions.length ? view.subscriptions.map(subscriptionRow).join("") : `

No push subscriptions yet — enable push above.

`}`; + const script = ``; + return layout("Notification preferences", body, provenance, "/alerts/preferences", script); +} + +// --- Notifications page (#3319, notification measurement) ------------------- + +export interface NotificationsPageView { + available: boolean; + rollup: NotificationRollup | null; +} + +function pct(ratio: number | null): string { + return ratio === null ? "—" : `${Math.round(ratio * 100)}%`; +} + +export function renderNotifications(view: NotificationsPageView, provenance: Provenance): string { + if (!view.available || !view.rollup) { + return layout( + "Notifications", + `

Notifications

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.

`, + provenance, + "/notifications", + ); + } + const rollup = view.rollup; + const proposals = rollup.classes.filter((c) => c.proposal); + const rows = rollup.classes + .map((c) => { + const cells = c.weeks.map((w) => `${w.sent} sent · ${w.acted} acted (${pct(w.ratio)})`).join(""); + return `${esc(c.class)}${cells}${c.sent} sent · ${c.acted} acted (${pct(c.ratio)})`; + }) + .join(""); + const weekHeads = rollup.classes[0] + ? rollup.classes[0].weeks.map((w) => `week of ${esc(fmtDate(w.start))}`).join("") + : ""; + const proposalHtml = proposals.length + ? `

Default-off proposals

${proposals + .map( + (c) => + `
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 + ? `
${weekHeads}${rows}
Sent vs acted-on by class and rolling week
classrolling 4 weeks
` + : `

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 + ? `

Data freshness: ${digest.freshness + .map((f) => `${esc(f.facet)}=${esc(f.state)}${f.ageMs !== null ? ` (${esc(ageTextDigest(f.ageMs))})` : ""}`) + .join(" · ")}

` + : `

Data freshness: not measured by this source — treat every section as unverified.

`; + const sections = digest.sections + .map((s) => { + const items = s.items.length + ? `${s.truncated ? `

… capped at ${DIGEST_SECTION_LIMIT} items

` : ""}` + : `

${s.stale ? "(unavailable — see the stale note)" : "(nothing)"}

`; + return `

${esc(s.title)}${s.stale ? ` — STALE: ${esc(s.staleNote ?? "source degraded")}` : ""}

${items}`; + }) + .join("\n"); + const archiveLinks = archives.length + ? `

Archive

` + : `

Archive

No digests archived yet — the generator (scripts/generate-digest.ts) writes one per day.

`; + const body = `

PM ${esc(digest.kind)} digest — ${esc(digest.date)}

+

Generated ${esc(digest.generatedAt)} from the canonical projection · window ${digest.windowHours}h from ${esc(digest.windowStart)} · machine twin: ${esc(`/api/digest.json?date=${digest.date}&kind=${digest.kind}`)}

+${freshness} +${sections} +${archiveLinks}`; + return layout( + `Digest ${digest.date}`, + body, + provenance, + "/digest", + "", + detail ? freshnessChips(detail, ["items", "quota"]) : "", + ); +} + +function ageTextDigest(ageMs: number): string { + const mins = Math.max(0, Math.round(ageMs / 60000)); + if (mins < 60) return `${mins}m old`; + const hours = Math.floor(mins / 60); + if (hours < 48) return `${hours}h ${mins % 60}m old`; + return `${Math.floor(hours / 24)}d ${hours % 24}h old`; +} diff --git a/pm-stack/aggregator/src/render-attention.ts b/pm-stack/aggregator/src/render-attention.ts new file mode 100644 index 0000000000..5173f8af5e --- /dev/null +++ b/pm-stack/aggregator/src/render-attention.ts @@ -0,0 +1,827 @@ +// render.ts split (#13051): attention (needs-you) view and the needs-Drew census. +// render.ts re-exports every public name from here; callers keep importing "./render.ts". + +import { type AttentionView, sessionChildren, sessionRoots } from "./derive.ts"; +import type { DashAction } from "./actions.ts"; +import { cardState, type CardState } from "./card-state.ts"; +import { DELEGATION_DEFAULT_OBJECT_REF, NEEDS_ORDER_OBJECT_REF, type NeedsOrder } from "./tier-items.ts"; +import type { CommentKindCounts } from "./comments.ts"; +import { needsDrewWait, type NeedsDrewCensus, type NeedsDrewItem } from "./needs-drew.ts"; +import { feedAgeText } from "./feed.ts"; +import type { DashComment, Provenance, ProvenanceDetail, RefKey, SourceCoverage, TierItem } from "./model.ts"; +import type { ItemBrief } from "./brief.ts"; +import type { AuthorIdentity } from "./registry.ts"; +import type { DecisionSetSummary } from "./decisions.ts"; + +import { + esc, + fmtDate, + DASH_AFTER_JS, + COMMENT_SCRIPT, + FRAG_WATCHDOG_SCRIPT, + ACTION_SCRIPT, + freshnessChips, + layout, + sessionObjectRef, + tierItemObjectRef, + type CommentFormOpts, + relTime, + cardDomId, + authorSelectHtml, + aformHtml, + actboxHtml, + delegationDefaultHtml, + coverageHtml, + briefPanelsForRefs, +} from "./render-core.ts"; +import { sessionCard, tierItemCard } from "./render-quota.ts"; + +export interface AttentionAct { + actionsByObject?: Map; + identities?: AuthorIdentity[]; + commentsByObject?: Map; + commentOpts?: CommentFormOpts; + /** #1456: the effective Needs-you card order + its pending state. */ + needsOrder?: NeedsOrder; + needsOrderPending?: boolean; +} + +interface StripEntry { + objectRef: string; + title?: string; + cs: CardState; +} + +/** One suppressed card in a strip (#1443/#1450): what happened, when it + * lifts, and the way back — Unsnooze for a snooze (a superseding + * snooze at "now"), Restore for a dismiss / mark-done (a restore + * action superseding the suppressor). */ +function stripCardHtml(entry: StripEntry, identities: AuthorIdentity[] | undefined): string { + const sup = entry.cs.suppressed!; + const refLink = `${entry.title ? esc(entry.title) : `${esc(entry.objectRef)}`}`; + if (sup.kind === "snoozed") { + const a = sup.action; + const stateLine = + a.state === "new" + ? `⏳ sent · pending — snooze until ${esc(fmtDate(sup.until))}` + : `applied by ${esc(a.appliedByRun ?? "a fleet run")} — snoozed until ${esc(fmtDate(sup.until))}`; + const unsnooze = + identities !== undefined + ? actboxHtml( + { identities }, + aformHtml({ + kind: "triage", + verb: "snooze", + objectRef: entry.objectRef, + supersedes: a.id, + inner: ``, + }), + ) + : ""; + return `
💤 ${refLink} snoozed until ${esc(fmtDate(sup.until))}
${stateLine}${a.resultNote ? ` — ${esc(a.resultNote)}` : ""}${unsnooze}
`; + } + const a = sup.action; + const label = sup.kind === "done" ? "✓ marked done by you" : "dismissed by you"; + const stateLine = + a.state === "new" + ? "⏳ sent · pending" + : a.state === "applied" + ? `applied by ${esc(a.appliedByRun ?? "a fleet run")}` + : a.state; + const restore = + identities !== undefined + ? actboxHtml( + { identities }, + aformHtml({ + kind: "triage", + verb: "restore", + objectRef: entry.objectRef, + supersedes: a.id, + inner: `Records a restore that supersedes the ${sup.kind === "done" ? "mark-done" : "dismiss"} — the card returns with its history intact.`, + }), + ) + : ""; + return `
${refLink} ${label}
${stateLine}${a.payload.reason ? ` — reason: ${esc(a.payload.reason)}` : ""}${a.resultNote ? ` · ${esc(a.resultNote)}` : ""} · ${esc(relTime(a.createdAt))}${restore}
`; +} + +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 `
Bulk triage${authorSelectHtml(act.identities)}0 selected
`; +} + +/** + * 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 = `

All decision sets

`; + const footer = `

Live from the decision-set store at page load.

`; + if (summaries === null) { + return `

Questions

Unavailable — the decision-set store could not be read, so open questions cannot be reported here.

${allSetsLink}${footer}
`; + } + const open = summaries.filter((s) => s.openQuestions > 0).sort((a, b) => b.createdAt.localeCompare(a.createdAt)); + if (!open.length) { + return `

Questions

No open questions right now — the stack is clear.

${allSetsLink}${footer}
`; + } + const totalOpen = open.reduce((n, s) => n + s.openQuestions, 0); + const rows = open + .map((s) => { + const stamp = Number.isFinite(Date.parse(s.createdAt)) + ? QUESTIONS_STAMP.format(new Date(s.createdAt)) + : s.createdAt; + return `
${esc(s.title)}
${s.openQuestions} open question${s.openQuestions === 1 ? "" : "s"} · ${s.items} item${s.items === 1 ? "" : "s"} · ${s.questions} question${s.questions === 1 ? "" : "s"} · Raised ${esc(stamp)}
`; + }) + .join(""); + return `

Questions

${open.length} open set${open.length === 1 ? "" : "s"} · ${totalOpen} open question${totalOpen === 1 ? "" : "s"}

${rows}${allSetsLink}${footer}
`; +} + +export function renderAttention( + view: AttentionView, + coverage: SourceCoverage[], + provenance: Provenance, + counts?: Map, + detail?: ProvenanceDetail, + act?: AttentionAct, + briefs?: Map, + census?: NeedsDrewCensus | null, + questionsHtml = "", +): string { + const sections = attentionSections(view, coverage, counts, act, briefs, census); + return layout( + "Needs you", + `

Needs you

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.

`; + } + const failed = census.sources.filter((x) => !x.ok || x.truncated || x.incomplete); + const failureNote = failed.length + ? `` + : ""; + // 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 => + `
  • ${esc(i.ref)} ${i.kind === "pr" ? "(PR) " : ""}${esc(i.title)} — ${i.needsLabels + .map((l) => `${esc(l)}`) + .join(" ")} — ${note} (updated ${esc(i.updatedAt)})
  • `; + 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}.

    `; + const reviewRows = review.length + ? `
      ${review.map((i) => line(i, reasonOf(i))).join("")}
    ` + : `

    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.

      ${parked + .map((i) => line(i, reasonOf(i))) + .join("")}
    ` + : `

    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" + ? `` + : `` + : ts.state === "stale" + ? `` + : ""; + 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 = ``; + // #1290/#1291: the standing delegation-default toggle — a dashboard + // preference, so it renders whenever the action surface is up; its + // state comes from the preference records in the store. + const delegationDefault = act?.identities + ? delegationDefaultHtml(act.actionsByObject?.get(DELEGATION_DEFAULT_OBJECT_REF), { + identities: act.identities, + }) + : ""; + const header = `${tierBanner}${chips} +${coverageHtml(coverage)} +${delegationDefault}`; + const drewCards = + drewCardsList.map((c) => c.html).join("") || + (ts.present + ? `

    Nothing in the user queue right now.

    ` + : `

    Unknown — the tier source is missing, so this queue cannot be reported.

    `); + const orchCards = + orchCardsList.join("") || + (ts.present + ? `

    The fleet's queue is empty.

    ` + : `

    Unknown — the tier source is missing, so this queue cannot be reported.

    `); + const snoozedStrip = snoozedList.length + ? `

    Snoozed by you (${snoozedList.length})

    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.

    ${orchCards}${needsDrewCensusHtml(census)}`; + const sessionCards = roots.length + ? roots.map((e) => sessionCard(e, children, 0, counts, sessionAct)).join("") + : `

    No current sessions.

    `; + const sessions = `

    All sessions (${roots.length})

    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 + ? `
    ${item.links.map((l) => `${esc(l.ref)}`).join(" ")}
    ` + : ""; + return `
    orchestrator · in flight ${esc(item.title)}${cmt}
    ${status}${repo}${goal}${blocked}${refs}${briefs}
    `; + } + const src = item.source === "github" ? `gh-only ` : ""; + // #1154: a card whose linked issue sits in the Project pool + // carries the status-request control for that pool item. + let statusCtl = ""; + if (act?.identities && act.poolByRef) { + const pooled = item.links.map((l) => act.poolByRef!.get(l.ref)).find((p) => p !== undefined); + if (pooled) { + const objectRef = ghObjectRef(pooled.ref); + statusCtl = `${actionBadgesHtml(act.actionsByObject?.get(objectRef))}${statusRequestHtml(objectRef, pooled.ref, pooled.status ?? null, { identities: act.identities })}`; + } + } + const kaneo = item.kaneoUrl ? ` Kaneo ↗` : ""; + // #1198: the board column is Kaneo's status; when the linked + // Project pool item's Status disagrees canonically, show BOTH + // instead of silently picking the column. + let statusClash = ""; + if (act?.poolByRef) { + const pooled = item.links.map((l) => act.poolByRef!.get(l.ref)).find((p) => p !== undefined); + if (pooled?.status) { + const boardCanonical = canonicalStatusFor("kaneo", item.status); + const projectCanonical = canonicalStatusFor("project", pooled.status); + if (boardCanonical && projectCanonical && boardCanonical !== projectCanonical) { + statusClash = ` ⚠ board: ${esc(item.status)} · project: ${esc(pooled.status)}`; + } + } + } + return `
    ${src}${esc(item.title)}${cmt}
    ${repo}${kaneo}${statusClash}${stripHtml(items, item.links)}${statusCtl}${briefs}
    `; + }) + .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 `

    ${heading} ${overCapBadges}

    ${cards}
    `; + }) + .join(""); + return `
    ${bodies}
    `; +} + +/** The board page (#1444): full server render. */ +export function renderBoard( + board: BoardItem[], + items: Map, + provenance: Provenance, + counts?: Map, + detail?: ProvenanceDetail, + act?: { + actionsByObject?: Map; + poolByRef?: Map; + identities?: AuthorIdentity[]; + briefs?: Map; + }, + renderOpts?: { showAllDone?: boolean }, +): string { + return layout( + "Cross-repo WIP board", + `

    Cross-repo WIP board

    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.

    ${renderBoardBody(board, items, counts, act, renderOpts)}`, + provenance, + "/board", + act?.identities ? ACTION_SCRIPT : "", + detail ? freshnessChips(detail, ["board", "items", "orchestration"]) : "", + ); +} + +/** The Datastar shell for / (#1444): heading + intro paint at once; + * the board itself streams in from /frag/board. */ +export function renderBoardShell(provenance: Provenance, detail?: ProvenanceDetail, viewQuery = ""): string { + const fragBoard = viewQuery ? `/frag/board?${viewQuery}` : "/frag/board"; + return layout( + "Cross-repo WIP board", + `

    Cross-repo WIP board

    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) => `
    ${esc(formatForecastSummary(c))}
    `).join(""); + return `
    ${lines}
    `; +} + +function roadmapDrilldown( + drill: RoadmapDrill, + row: RoadmapRow, + forecasts?: Map, + spend?: SpendCardsView | null, +): string { + const parts: string[] = []; + if (!drill.epic) { + parts.push(`

    No epic yet — no Project epic matches this roadmap row.

    `); + } else { + const epic = drill.epic; + parts.push( + `

    Epic: ${esc(epic.title)} ${esc(epic.ref)} · ${esc(epic.state)}

    `, + ); + if (drill.children.length === 0) { + parts.push(`

    No child issues in the Project pool for this epic yet.

    `); + } else { + const done = drill.children.filter(isEpicChildDone).length; + const total = drill.children.length; + const pct = Math.round((done / total) * 100); + parts.push( + `

    Progress: ${done}/${total} child issues done

    ${pct}%
    `, + ); + parts.push( + `
      ${drill.children + .map( + (c) => + `
    • ${esc(c.title)} ${esc(c.state)} ${esc(c.ref)}
    • `, + ) + .join("")}
    `, + ); + } + } + if (drill.epic) { + const fc = forecastSummaryHtml(forecasts?.get(drill.epic.ref)); + if (fc) parts.push(fc); + } + if (drill.epic) { + const card = spend?.byScope.get(drill.epic.ref); + if (card) parts.push(spendCardHtml(card)); + } + if (row.notes.trim()) parts.push(`

    ${esc(row.notes)}

    `); + return `
    Epic & issues${parts.join("")}
    `; +} + +function roadmapCard( + row: RoadmapRow, + items: Map, + counts?: Map, + drill?: RoadmapDrill, + annotations?: Map, + briefs?: Map, + forecasts?: Map, + spend?: SpendCardsView | null, + epicRollups?: Map, + showRowNotes = false, +): string { + const refs = allRefs([row]); + const refBadges = refs + .map((r) => items.get(r)) + .filter((x): x is GhItem => Boolean(x)) + .map(itemBadge) + .join(" "); + const cmt = counts ? commentBadge(row.subject, counts) : ""; + const grist = row.gristUrl ? ` Grist ↗` : ""; + const repoFile = row.fileUrl ? ` Repo file ↗` : ""; + const expansion = drill ? roadmapDrilldown(drill, row, forecasts, spend) : ""; + // The program timeline has no drill map; keep its Notes visible without + // duplicating the same text when a card already has a drilldown. + const rowNotes = showRowNotes && !drill && row.notes.trim() ? `

    ${esc(row.notes)}

    ` : ""; + const epicRollup = epicRollups?.get(row.subject); + const rollupHtml = epicRollup ? epicRollupHtml(epicRollup) : ""; + const notes = annotations?.get(row.subject) ?? []; + const annotationHtml = notes.length + ? `
    ${notes.map(roadmapAnnotationHtml).join("")}
    ` + : ""; + const briefPanels = briefPanelsForRefs(refs, briefs); + const horizonWarning = row.horizonError + ? ` Invalid Horizon` + : ""; + // #1198: the row's status is Grist's; when the linked GitHub item's + // derived lifecycle status (or its Project Status) disagrees + // canonically, show BOTH instead of silently picking Grist's. + let statusClash = ""; + const ghLinked = refs.map((r) => items.get(r)).find((x) => x !== undefined); + if (ghLinked) { + const gristCanonical = canonicalStatusFor("grist", row.status); + const derived = ghItemDerivedStatus(ghLinked); + if (gristCanonical && derived && derived !== gristCanonical) { + statusClash = ` ⚠ grist: ${esc(row.status)} · derived: ${esc(derived)}`; + } else if (gristCanonical && ghLinked.projectStatus) { + const projectCanonical = canonicalStatusFor("project", ghLinked.projectStatus); + if (projectCanonical && projectCanonical !== gristCanonical) { + statusClash = ` ⚠ grist: ${esc(row.status)} · project: ${esc(ghLinked.projectStatus)}`; + } + } + } + return `
    ${esc(row.title)}${cmt}
    ${esc(row.status)} ${esc(row.area)} · ${esc(row.horizon)}${horizonWarning}${statusClash}${refBadges}${grist}${repoFile}${rollupHtml}${annotationHtml}${rowNotes}${expansion}${briefPanels}
    `; +} + +function roadmapAnnotationHtml(annotation: RoadmapAnnotation): string { + return `
    ${esc(annotation.date)} ${esc(annotation.kind)} ${authorBadge(annotation.author)}
    ${esc(annotation.body)}
    `; +} + +export function timelineTable( + tl: ReturnType, + items: Map, + counts?: Map, + drill?: Map, + annotations?: Map, + briefs?: Map, + forecasts?: Map, + spend?: SpendCardsView | null, + options?: { epicRollups?: Map; showRowNotes?: boolean }, +): string { + const head = `Theme${tl.lanes.map((l) => `${esc(l.label)}`).join("")}`; + const body = tl.themes + .map((theme) => { + const themeRows = [...(tl.cells.get(theme)?.values() ?? [])].flat(); + const done = themeRows.filter((row) => row.status.trim().toLowerCase() === "done").length; + const cells = tl.lanes + .map((lane) => { + const rs = tl.cells.get(theme)?.get(lane.key) ?? []; + return `${rs.map((r) => roadmapCard(r, items, counts, drill?.get(r.subject), annotations, briefs, forecasts, spend, options?.epicRollups, options?.showRowNotes)).join("")}`; + }) + .join(""); + return `${esc(theme)} (${done}/${themeRows.length} done)${cells}`; + }) + .join(""); + return `
    ${head}${body}
    Roadmap timeline by theme
    `; +} + +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).
    ` + : reconciliation && reconciliation.drift > 0 + ? `
    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).
    ` + : ""; + const chips = `${GRAINS.map( + ([g, label]) => + `${label}`, + ).join("")} Priorities`; + const invalidHorizons = rows.filter((row) => row.horizonError); + const horizonFlag = invalidHorizons.length + ? `
    ${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.
    ` + : ""; + let body: string; + if (prioritiesView) { + const ordered = [...rows].sort((a, b) => { + const rank = (row: RoadmapRow) => { + const match = /#(\d+)$/.exec(row.priority ?? ""); + return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER; + }; + return rank(a) - rank(b) || a.title.localeCompare(b.title); + }); + body = ordered.length + ? ordered + .map((row) => { + const priority = row.priority + ? `Priority ${esc(row.priority)}` + : 'No priority link'; + const after = row.afterRefs?.length + ? `After: ${row.afterRefs.map((ref) => `${esc(ref)}`).join(", ")}` + : 'No predecessor recorded'; + const release = row.releaseRef + ? `Release ${esc(row.releaseRef)}` + : 'No release linked'; + return `
    ${esc(row.title)}
    ${priority} ${release}
    ${after}
    ${esc(row.area)} · ${esc(row.horizon)} · ${esc(row.status)}
    `; + }) + .join("") + : '

    No priority rows in the current roadmap source.

    '; + } else if (grain === "quarter") { + body = timelineTable(buildTimeline(rows), items, counts, drill, annotations, briefs, forecasts, spend); + } else if (grain === "month") { + body = timelineTable(monthTimeline(rows), items, counts, drill, annotations, briefs, forecasts, spend); + } else { + const dg = roadmapDayGrain(rows, grain); + const byTheme = new Map(); + for (const row of rows) { + const theme = row.area || "Unthemed"; + byTheme.set(theme, [...(byTheme.get(theme) ?? []), row]); + } + body = byTheme.size + ? [...byTheme.entries()] + .map(([theme, themeRows]) => { + const done = themeRows.filter((row) => row.status.trim().toLowerCase() === "done").length; + const cards = (laneRows: RoadmapRow[]) => + laneRows + .map((row) => + roadmapCard(row, items, counts, drill?.get(row.subject), annotations, briefs, forecasts, spend), + ) + .join(""); + const lanes = dg.lanes + .map((lane) => { + const laneRows = lane.rows.filter((row) => (row.area || "Unthemed") === theme); + return laneRows.length ? `

    ${esc(lane.label)}

    ${cards(laneRows)}` : ""; + }) + .join(""); + const outsideRows = dg.outsideRows.filter((row) => (row.area || "Unthemed") === theme); + const coarseRows = dg.coarse.filter((row) => (row.area || "Unthemed") === theme); + const outside = outsideRows.length + ? `

    Outside this window (${outsideRows.length})

    ${cards(outsideRows)}` + : ""; + const coarse = coarseRows.length + ? `

    Undated or coarse horizons (${coarseRows.length})

    ${cards(coarseRows)}` + : ""; + return `

    ${esc(theme)} (${done}/${themeRows.length} done)

    ${lanes}${outside}${coarse}
    `; + }) + .join("") + : '

    No roadmap rows.

    '; + } + const releaseCards = releases + .filter((release) => release.kind === "release") + .map((release) => { + const counts = release.counts; + const carried = release.carriedOverEpics.length + ? `

    Carried-over epics: ${release.carriedOverEpics.map((ref) => `${esc(ref)}`).join(", ")}

    ` + : '

    No carried-over epics.

    '; + return `

    ${esc(release.milestone.title)}

    Date: ${esc(release.releaseDate ?? "date not set")}

    Issues: ${counts.issues.closed}/${counts.issues.total} closed · Designs: ${counts.designs.closed}/${counts.designs.total} closed · Epics: ${counts.epics.closed}/${counts.epics.total} closed

    ${carried}

    ${esc(release.descriptionLine)}

    `; + }) + .join(""); + const releasesHtml = `

    Releases

    ${releaseCards || '

    No release close-out snapshots are available.

    '}

    Releases JSON

    `; + return layout( + "Roadmap", + `

    Roadmap

    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 `

    Epic rollup — ${children} · Status mix: ${statusMix} · Blocked: ${rollup.blocked}

    `; +} + +export function eventTableHtml(events: readonly AuditEvent[]): string { + const rows = events + .map((event) => { + const source = event.source.link + ? `${esc(event.source.identity)}` + : esc(event.source.identity); + const delay = Date.parse(event.ingestedAt) - Date.parse(event.at); + const ingested = + Number.isFinite(delay) && delay > 0 ? `(+${Math.round(delay / 1000)}s ingest)` : ""; + return `${esc(event.at)} ${ingested}${esc(event.actor)} (${esc(event.attribution.confidence)})${esc(event.kind)}${esc(event.ref)}${esc(event.summary)}${source}`; + }) + .join("\n"); + return `
    ${rows || ''}
    Shared activity events
    WhenActorKindRefSummarySource
    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) + ? `` + : ""; +} + +export function renderItem( + title: string, + subject: string, + links: BoardItem["links"], + items: Map, + comments: Comment[], + provenance: Provenance, + extras?: ItemExtras, +): string { + const strip = executionStrip(links, items); + const all = [...strip.implementing, ...strip.review, ...strip.merged, ...strip.queued, ...strip.closed]; + const refRows = all + .map( + (i) => + `${itemBadge(i)}${esc(i.title)}${esc(i.labels.join(", "))}${fmtDate(i.updatedAt)}`, + ) + .join(""); + const stream = commentStream(links, comments); + const commentRows = stream + .map( + (c) => + `${fmtDate(c.createdAt)}${esc(c.kind)}${esc(c.author)}${esc(c.body)}${c.path ? ` (${esc(c.path)}${c.line ? `:${c.line}` : ""})` : ""}`, + ) + .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) + ? `no comments loaded — ${FIXTURE_COMMENTS_CAUSE}` + : 'no comments'; + const dashSection = extras + ? `

    Dashboard comments

    ${ + extras.dashComments.length + ? extras.dashComments.map((c) => dashCommentHtml(c, true)).join("") + : `

    No dashboard comments yet — notes are read when this is picked up; messages are triaged by the orchestrator.

    ` + }${commentFormHtml(extras.formRef, extras.formOpts)}` + : ""; + const roadmapAnnotationSection = + extras?.roadmapAnnotations !== undefined + ? `

    Roadmap annotations

    ${extras.roadmapAnnotations.length ? extras.roadmapAnnotations.map(roadmapAnnotationHtml).join("") : '

    No roadmap annotations yet.

    '}${roadmapAnnotationFormHtml(extras.formRef, extras.formOpts.identities)}
    ` + : ""; + const sessionSection = + extras && extras.sessions.length + ? `

    Sessions that worked this

    ${extras.sessions.map((r) => sessionRecordLine(r)).join("")}
    ` + : ""; + const statusSection = + extras?.statusRequest && extras.formOpts + ? `

    Request status change

    ${actionBadgesHtml(extras.actions)}${statusRequestHtml(extras.statusRequest.objectRef, extras.statusRequest.targetRef, extras.statusRequest.currentStatus, { identities: extras.formOpts.identities })}` + : ""; + const svcLinks = extras?.serviceLinks?.length + ? `

    Live services: ${extras.serviceLinks.map((s) => `${esc(s.label)} ↗`).join(" · ")}

    ` + : ""; + const epicRollup = extras?.epicRollup ? epicRollupHtml(extras.epicRollup) : ""; + const dispatchSection = extras?.dispatchStates?.length + ? `

    ready-for-agent dispatch

      ${extras.dispatchStates + .map( + (entry) => + `
    • ${esc(entry.ref)}: ${esc(entry.state)} · ${esc(entry.provenance.source)} checked ${esc(entry.provenance.observedAt)}
    • `, + ) + .join("")}
    ` + : ""; + const activitySection = extras?.activity + ? `

    Activity stream

    View these events in the global river

    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.

    ${gapsHtml(extras.activity.gaps)}

    Activity source coverage

    ${activityCoverageHtml(extras.activity.coverage)}
    ` + : ""; + return layout( + title, + `

    ${esc(title)}

    subject: ${esc(subject)}

    ${extras?.genealogySentence ? `

    ${esc(extras.genealogySentence)}

    ` : ""}${epicRollup}${svcLinks}${dispatchSection}${stripHtml(items, links)} +${ + extras?.briefs + ? briefPanelsForRefs( + links.map((link) => link.ref), + extras.briefs, + ) + : "" +} +

    ${linkedHeader}

    ${refRows || ''}
    Linked issues and pull requests
    RefTitleLabelsUpdated
    none resolved
    +

    Activity stream comments

    ${commentsBanner}
    ${commentRows || emptyCommentRow}
    Comments
    WhenKindAuthorBody
    + ${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 per manifest section — but EVERY page + * present, primary and dropdown-tier alike: this is where demoted + * pages live. + */ +export function pageDropdown(active: string): string { + let selectedMarked = false; + const groups = groupedPages() + .map(({ group, pages }) => { + const options = pages + .map((p) => { + const selected = p.route === active && !selectedMarked; + if (selected) selectedMarked = true; + return ``; + }) + .join(""); + return `${options}`; + }) + .join(""); + return ``; +} + +export function themeToggle(): string { + // Datastar-first theme toggle (Phase C): the vendored Datastar v1 binds + // data-on: (colon form) for handlers — the dash form does not bind + // clicks (verified live against the vendored bundle). A $pmTheme signal seeded from + // the the inline bootstrap set (stored choice or the + // dark default); the effect is the single writer of data-theme + + // localStorage, and the click handler only flips the signal. + return ``; +} + +function globalSearch(): string { + return ``; +} + +export function layout( + title: string, + body: string, + provenance: Provenance, + active: string, + extra = "", + chipsHtml = "", +): string { + // Nav + the page dropdown both render from the manifest (#906 §1): + // registering a page in src/pages.ts is the only step that puts it + // in either. Both use the same grouped model (#1215): the bar groups + // its links by section (#1135) so pages wrap onto a second row at + // phone width instead of scrolling sideways, the dropdown mirrors + // the sections as s, and both list every page. + const links = navLinks(active); + const dropdown = pageDropdown(active); + return ` + +${esc(title)} · aggregator +
    ${chipsHtml}${body} +
    source detailboard: ${esc(provenance.board)} · roadmap: ${esc(provenance.roadmap)} · items: ${esc(provenance.items)} · comments: ${esc(provenance.comments)} · quota: ${esc(provenance.quota)} · usage: ${esc(provenance.usage)} · attention: ${esc(provenance.attention)} · orchestration: ${esc(provenance.orchestration)} · dns: ${esc(provenance.dns)} · registry: ${esc(provenance.registry)} · aa: ${esc(provenance.aa)}
    ${KEY_HINT} · tailnet: ${TAILNET_URL.replace("http://", "")}
    +
    ${extra}${paletteHtml()}${KEYBOARD_SCRIPT}`; +} + +/** Global search over board/roadmap subjects, linked refs, and the slice-2 sources (#1212): registry sessions, the DNS register, services, and tier items. */ +export function renderSearch( + query: string, + results: SearchResult[], + items: Map, + provenance: Provenance, + detail?: ProvenanceDetail, +): string { + const cards = results + .map((result) => { + const badges = result.refs + .map((ref) => { + const item = items.get(ref); + // Codex P1 on PR #7331 (defense in depth): a non-GitHub ref + // (tracked-goal id, orch: key) must never reach refUrl, which + // throws on it — render it as a plain-text badge instead. + return item + ? itemBadge(item) + : isValidRef(ref) + ? `${esc(ref)} · unresolved` + : `${esc(ref)} · unresolved`; + }) + .join(" "); + return `
    ${esc(result.title)}
    ${result.kind} · ${esc(result.summary)}${badges ? `
    ${badges}
    ` : ""}
    `; + }) + .join(""); + const body = `

    Search

    Search board items, roadmap rows, registry sessions, DNS domains, services, and tier items by subject, title, or linked issue/PR ref. Every result links to its own detail view. Linked GitHub badges show their current projected state and whether the result is fixture-only.

    ${query ? `

    ${results.length} result${results.length === 1 ? "" : "s"} for “${esc(query)}”

    ${cards || '

    No matching work found.

    '}` : '

    Enter a title or issue/PR reference to search.

    '}`; + // #1212 slice 2: the search page carries the same freshness facets + // as the home page of each result kind present (board/roadmap/items + // for work, registry for sessions, dns for the register, quota and + // usage for services, orchestration/attention/registry for tiers). + const chipKeys = new Set(["board", "roadmap", "items"]); + for (const result of results) { + if (result.kind === "registry") chipKeys.add("registry"); + if (result.kind === "dns") chipKeys.add("dns"); + if (result.kind === "service") { + chipKeys.add("quota"); + chipKeys.add("usage"); + } + if (result.kind === "tier") { + chipKeys.add("orchestration"); + chipKeys.add("attention"); + chipKeys.add("registry"); + } + } + return layout("Search", body, provenance, "/search", "", detail ? freshnessChips(detail, [...chipKeys]) : ""); +} + +// --- Dashboard comments (#906 §2) ------------------------------------------ + +/** Object refs: the keys dashboard comment threads hang on. */ +export const sessionObjectRef = (id: string): string => `session:${id}`; +export const ghObjectRef = (ref: RefKey): string => `gh:${ref}`; +export function tierItemObjectRef(item: TierItem): string { + // Watchdog items (#1148) all carry the implementation issue as their + // display ref, but each watchdog: is an independent object: + // keying them all by the shared gh: ref would give every watchdog + // card the same DOM id, actions, dismissal state, and comment + // thread, so dismissing one input's card would suppress them all + // (Codex P1 on PR #2431). Watchdog cards key by their unique id; + // the gh: ref still renders as the card's issue link. + if (item.source === "watchdog") return `orch:${item.id}`; + return item.ref ? ghObjectRef(item.ref) : `orch:${item.id}`; +} + +/** A 💬 link to an object's comment thread, with its comment count. */ +export function commentBadge(objectRef: string, counts?: Map): string { + // #1210: a detailed count distinguishes notes from actionable + // comments (awaiting triage / to post / failed) in the badge itself; + // a plain number count keeps the original rendering. + const v = counts?.get(objectRef) as number | CommentKindCounts | undefined; + const n = typeof v === "number" ? v : (v?.total ?? 0); + const actionable = typeof v === "object" && v !== null ? v.actionable : 0; + const title = + typeof v === "object" && v !== null + ? `Dashboard comments on this item: ${v.total} total — ${v.notes} notes, ${v.messagesNew} messages awaiting triage, ${v.githubPending} GitHub comments to post, ${v.githubFailed} failed to post` + : "Dashboard comments on this item"; + const queued = actionable ? ` · ${actionable} queued` : ""; + return ` 💬${n ? ` ${n}` : ""}${queued}`; +} + +export function authorBadge(a: DashAuthor, linkedIdentity?: { source: string; id: string }): string { + const cls = a.kind === "drew" ? "drew" : a.kind === "muse" ? "Muse" : "agent"; + const link = a.sessionId + ? ` session` + : ""; + const linked = linkedIdentity + ? ` linked identity` + : ""; + return `${esc(a.label)}${link}${linked}`; +} + +export function dashCommentHtml(c: DashComment, showObject = false): string { + const verificationChip = + c.provenance === "verified" + ? `verified identity` + : `asserted-legacy — author is a claim`; + const kindChip = + c.kind === "message" + ? `✉ message to Muse ${c.triageState === "triaged" ? "triaged by the orchestrator" : "awaiting triage"}` + : c.kind === "github" + ? `GitHub comment ${ + c.githubState === "posted" + ? `posted${c.githubUrl ? ` — view` : ""}` + : c.githubState === "failed" + ? `posting failed ${relTime(c.githubFailedAt ?? c.createdAt)} — no automatic retry exists; a fleet poster must post it by hand${c.githubError ? ` — last error: ${esc(c.githubError)}` : ""}` + : `pending — will post to ${esc(c.githubRef ?? "")}` + }` + : `note`; + const obj = showObject ? ` on ${esc(c.objectRef)}` : ""; + return `
    ${authorBadge(c.author, c.linkedIdentity)} ${verificationChip} ${kindChip}${obj}
    ${esc(c.body)}
    ${fmtDate(c.createdAt)}
    `; +} + +export interface CommentFormOpts { + /** Refs the "post as GitHub comment" kind may target (explicit select). */ + githubRefs?: RefKey[]; + /** Author identities for the picker (standing + registry sessions). */ + identities: AuthorIdentity[]; +} + +/** + * The author picker's server-rendered options (#1179): the standing + * identities only. Session identities (one per registry session -- + * ~700 and growing) used to be inlined into every card's picker, + * which made list pages quadratic: /program shipped 351 copies of a + * ~123 KB option list (44 MB of HTML), /board 94 copies (12.9 MB). + * The full list now loads on demand from /api/author-identities the + * first time any picker on the page is touched and is applied to + * every picker at once (see DASH_AFTER_JS). Pickers keep working + * without that fetch -- standing identities are the common case. + */ +export function authorOptionsHtml(identities: AuthorIdentity[]): string { + return identities + .filter((i) => !i.sessionId) + .map( + (i) => + ``, + ) + .join(""); +} + +export function commentFormHtml(objectRef: string, opts: CommentFormOpts): string { + const ghRefs = opts.githubRefs ?? []; + const authorOptions = authorOptionsHtml(opts.identities); + const ghTarget = ghRefs.length + ? `` + : ""; + const ghKind = ghRefs.length + ? `` + : ""; + return `
    + + + +
    + + +${ghKind}
    +${ghTarget} + +
    `; +} + +/** A full thread + form for one object ref (discuss page, item page). */ +export function commentThreadHtml( + objectRef: string, + comments: DashComment[], + opts: CommentFormOpts, + heading = "Dashboard comments", +): string { + const list = comments.length + ? comments.map((c) => dashCommentHtml(c)).join("") + : `

    No dashboard comments yet.

    `; + return `

    ${esc(heading)}

    ${list}${commentFormHtml(objectRef, opts)}`; +} + +// --- Dashboard actions (#1152/#1154/#1156) -------------------------------- +// Forms post DashActions to the actions store (src/actions.ts); the +// fleet consumers apply them and report back. Nothing here writes +// anywhere else — a control renders the REQUEST and the store's state +// (pending / applied / rejected), never a pretend-completed change. + +/** "12m ago" style relative stamp for action badges. */ +export function relTime(iso: string, now = Date.now()): string { + const ms = now - Date.parse(iso); + if (Number.isNaN(ms)) return iso; + if (ms < 60_000) return "just now"; + const m = Math.floor(ms / 60_000); + if (m < 60) return `${m}m ago`; + const h = Math.floor(m / 60); + if (h < 24) return `${h}h ago`; + return `${Math.floor(h / 24)}d ago`; +} + +const VERB_BADGE_LABELS: Record = { + acknowledge: "acknowledge", + snooze: "snooze", + escalate: "escalate", + "de-escalate": "de-escalate", + answer: "answer", + delegate: "delegate", + dismiss: "dismiss", + "mark-done": "already done", + restore: "restore", + "set-needs-order": "card order", + "approve-proposal": "approve proposal", + "reject-proposal": "reject proposal", + "request-status": "status change", + "set-delegation-default": "standing default", + poke: "poke", + stop: "stop", +}; + +function pendingBadgeLabel(a: DashAction): string { + if (a.verb === "request-status") return `status → ${a.payload.status ?? "?"} requested`; + if (a.verb === "snooze") return `snooze until ${a.payload.until ? fmtDate(a.payload.until) : "?"} requested`; + if (a.verb === "delegate") return `delegate (${a.payload.mode ?? "?"}) requested`; + return `${VERB_BADGE_LABELS[a.verb] ?? a.verb} requested`; +} + +/** + * The visible state of an object's actions: every still-pending action + * as a ⏳ badge, plus the latest applied/rejected outcome per verb + * family (snooze / status / acknowledge / tier / delegation) so the + * user can SEE that an action landed — or that it was rejected, with + * the consumer's note. + */ +export function actionBadgesHtml(actions: DashAction[] | undefined, now = Date.now()): string { + if (!actions?.length) return ""; + const badges: string[] = []; + for (const a of actions) { + if (a.state === "new") { + badges.push( + `⏳ ${esc(pendingBadgeLabel(a))} · ${esc(relTime(a.createdAt, now))}`, + ); + } + } + const snooze = latestInFamily(actions, "snooze"); + if (snooze?.state === "applied" && snooze.payload.until && Date.parse(snooze.payload.until) > now) { + badges.push( + `💤 snoozed until ${esc(fmtDate(snooze.payload.until))}`, + ); + } + const status = latestInFamily(actions, "status"); + if (status?.state === "applied") { + badges.push( + `✓ status → ${esc(status.payload.status ?? "")} applied · ${esc(relTime(status.appliedAt ?? status.createdAt, now))}`, + ); + } else if (status?.state === "rejected") { + badges.push( + `✗ status → ${esc(status.payload.status ?? "")} rejected${status.resultNote ? ` — ${esc(status.resultNote)}` : ""}`, + ); + } + const ack = latestInFamily(actions, "ack"); + if (ack?.state === "applied") { + badges.push( + `✓ acknowledged · ${esc(relTime(ack.appliedAt ?? ack.createdAt, now))}`, + ); + } + const tier = latestInFamily(actions, "tier"); + if (tier?.state === "applied") { + badges.push( + `✓ moved to ${tier.payload.tier === "needs-drew" ? "Needs User" : "Needs Orchestrator"} · ${esc(relTime(tier.appliedAt ?? tier.createdAt, now))}`, + ); + } else if (tier?.state === "rejected") { + badges.push( + `✗ ${esc(VERB_BADGE_LABELS[tier.verb] ?? tier.verb)} rejected${tier.resultNote ? ` — ${esc(tier.resultNote)}` : ""}`, + ); + } + const delegation = latestInFamily(actions, "delegation"); + if (delegation?.state === "applied") { + badges.push( + `✓ delegated (${esc(delegation.payload.mode ?? "")}) · ${esc(relTime(delegation.appliedAt ?? delegation.createdAt, now))}`, + ); + } else if (delegation?.state === "rejected") { + badges.push( + `✗ delegate rejected${delegation.resultNote ? ` — ${esc(delegation.resultNote)}` : ""}`, + ); + } + return badges.length ? ` ${badges.join(" ")}` : ""; +} + +export interface ActionFormOpts { + /** Author identities for the picker (standing + registry sessions). */ + identities: AuthorIdentity[]; + /** When set, every control renders disabled with this reason shown. */ + disabledReason?: string; +} + +/** Stable DOM id for one card, from its object ref (#1444 fragments + * patch sections; #1443's in-place feedback finds cards by ref). */ +export function cardDomId(objectRef: string): string { + return `card-${objectRef.replace(/[^a-zA-Z0-9]+/g, "-")}`; +} + +/** The card's action history (#1445): every recorded action with its + * state — the audit trail the store keeps, readable on the card. */ +export function actionHistoryHtml(actions: DashAction[] | undefined): string { + if (!actions?.length) return `

    No actions recorded on this card yet.

    `; + return [...actions] + .reverse() + .map((a) => { + const bits = [ + `${esc(VERB_BADGE_LABELS[a.verb] ?? a.verb)}`, + a.state === "new" + ? "⏳ pending" + : a.state === "applied" + ? `✓ applied${a.appliedByRun ? ` by ${esc(a.appliedByRun)}` : ""}` + : a.state === "rejected" + ? "✗ rejected" + : "superseded", + esc(relTime(a.createdAt)), + a.payload.reason ? `— ${esc(a.payload.reason)}` : "", + a.payload.until ? `until ${esc(fmtDate(a.payload.until))}` : "", + a.resultNote ? `· ${esc(a.resultNote)}` : "", + ].filter(Boolean); + return `
    ${bits.join(" ")}
    `; + }) + .join(""); +} + +/** + * The per-card comment box (#1446): the card's existing dashboard + * comments with their queued/posted state, plus a compact form. The + * form posts kind "message" (the orchestrator's queue input); the + * "also post publicly" checkbox adds a kind "github" comment when + * the card carries a gh: ref — posted later by the orchestrator, + * never by the aggregator (no GitHub credentials here). + */ +export function cardCommentHtml( + objectRef: string, + ghRef: RefKey | undefined, + comments: DashComment[] | undefined, + opts: CommentFormOpts, +): string { + const list = comments?.length + ? comments.map((c) => dashCommentHtml(c)).join("") + : `

    No comments on this card yet.

    `; + const authorOptions = authorOptionsHtml(opts.identities); + const ghBox = ghRef + ? `` + : `No GitHub issue on this card — the comment stays internal.`; + return `
    💬 Comments for the orchestrator${comments?.length ? ` (${comments.length})` : ""}${list}
    + + + +
    ${ghBox}
    +
    `; +} + +/** One-tap dismissal reasons (#1449): the common resolutions. */ +export const DISMISS_REASONS = ["Already handled", "No longer relevant", "Duplicate", "Won't do"] as const; +/** One-tap de-escalation reasons (#1449): Drew's "send why" chips. */ +export const DEESCALATE_REASONS = [ + "Orchestrator should have handled this", + "Passing to orchestrator this time", + "Need more info", + "Need recommendations", +] as const; + +/** + * The quick-action bar (#1449): one-tap resolutions with the reason + * attached, writing the existing action vocabulary. Chips disable + * while their verb is pending, so a resolution can't be double-sent. + */ +export function quickBarHtml(objectRef: string, tier: "needs-drew" | "needs-orchestrator", cs: CardState): string { + const chip = ( + verb: DashAction["verb"], + label: string, + hidden: string, + opts: { primary?: boolean; disabled?: boolean; sentLabel?: string } = {}, + ): string => + aformHtml({ + kind: "triage", + verb, + objectRef, + inner: `${hidden}`, + }).replace('class="aform"', 'class="aform qform"'); + const donePending = pendingVerb(cs, "mark-done"); + const dismissPending = pendingVerb(cs, "dismiss"); + const movePending = pendingVerb(cs, "de-escalate") ?? pendingVerb(cs, "escalate"); + const parts: string[] = [ + chip("mark-done", "Already done", "", { + primary: true, + disabled: !!donePending, + sentLabel: "✓ Already done · sent", + }), + ]; + for (const reason of DISMISS_REASONS) { + parts.push( + chip("dismiss", `Dismiss: ${reason}`, ``, { + disabled: !!dismissPending, + sentLabel: "Dismiss · sent", + }), + ); + } + if (tier === "needs-drew") { + for (const reason of DEESCALATE_REASONS) { + parts.push( + chip( + "de-escalate", + reason, + ``, + { disabled: !!movePending, sentLabel: "Sent to orchestrator" }, + ), + ); + } + } + const note = donePending || dismissPending || movePending ? ` ⏳ sent · pending` : ""; + return `
    Quick actions — one tap, reason attached${note}${parts.join("")}
    `; +} + +export function authorSelectHtml(identities: AuthorIdentity[]): string { + return `
    `; +} + +interface AFormSpec { + kind: DashAction["kind"]; + verb: DashAction["verb"]; + objectRef: string; + targetRef?: RefKey; + sessionId?: string; + sessionSource?: string; + supersedes?: string; + /** Inner controls (inputs/buttons), already escaped HTML. */ + inner: string; +} + +export function aformHtml(spec: AFormSpec): string { + const data = [ + `data-kind="${esc(spec.kind)}"`, + `data-verb="${esc(spec.verb)}"`, + `data-object="${esc(spec.objectRef)}"`, + `data-token="${esc(newClientToken())}"`, + spec.targetRef ? `data-target-ref="${esc(spec.targetRef)}"` : "", + spec.sessionId ? `data-session-id="${esc(spec.sessionId)}"` : "", + spec.sessionSource ? `data-session-source="${esc(spec.sessionSource)}"` : "", + spec.supersedes ? `data-supersedes="${esc(spec.supersedes)}"` : "", + ] + .filter(Boolean) + .join(" "); + return `
    ${spec.inner}
    `; +} + +/** Wrap a card's action forms: one author picker + the disabled gate. */ +export function actboxHtml(opts: ActionFormOpts, forms: string): string { + const inner = `${authorSelectHtml(opts.identities)}${forms}`; + return opts.disabledReason + ? `

    ⚠ Actions unavailable — ${esc(opts.disabledReason)}

    ${inner}
    ` + : `
    ${inner}
    `; +} + +function snoozeFieldsHtml(): 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 ``; +} + +/** + * The #1152 triage control set for one tier item: acknowledge (a + * non-resolving "seen" record), snooze (presets + custom), and the + * tier move toward the OTHER tier (de-escalate on Needs User cards, + * escalate on Needs Orchestrator cards), each with an optional reason. + * The answer control lives with the item's own surface (session cards + * carry the session answer; #1291 adds the tier answer row). + */ +export function triageActionsHtml( + objectRef: string, + tier: "needs-drew" | "needs-orchestrator", + opts: ActionFormOpts, + extraForms = "", + cs: CardState = cardState(undefined), +): string { + // #1443: a control whose verb is already pending (or, for + // acknowledge, already in effect) renders disabled — repeat clicks + // cannot pile up duplicate pending actions, and the card SAYS so. + const ackPending = pendingVerb(cs, "acknowledge"); + const snoozePending = pendingVerb(cs, "snooze"); + const moveVerb = tier === "needs-drew" ? "de-escalate" : "escalate"; + const movePending = pendingVerb(cs, moveVerb); + const move = + tier === "needs-drew" + ? aformHtml({ + kind: "triage", + verb: "de-escalate", + objectRef, + inner: ``, + }) + : aformHtml({ + kind: "triage", + verb: "escalate", + objectRef, + inner: ``, + }); + const ackInner = ackPending + ? `Recorded — the fleet applies it on its next pass.` + : cs.acked + ? `You have seen this — it stays until a resolving action or a new signal.` + : `Records that you have seen this — it stays until a resolving action or a new signal.`; + const forms = [ + quickBarHtml(objectRef, tier, cs), + aformHtml({ + kind: "triage", + verb: "acknowledge", + objectRef, + inner: ackInner, + }), + aformHtml({ + kind: "triage", + verb: "snooze", + objectRef, + inner: `${snoozeFieldsHtml()}`, + }), + move, + ].join(""); + return actboxHtml(opts, forms + extraForms); +} + +// --- Needs-user action layer (#1291) --------------------------------------- +// Everything in this block renders ONLY what the published item and +// the actions store actually say — why-class, options, survey, +// delegation state, proposal, inability. No decorative states: a +// control exists exactly when its verb can be posted and consumed. + +const WHY_USER_LABELS: Record = { + decision: "Decision", + "missing-info": "Missing Info", + approval: "Approval", + access: "Access", + policy: "Policy", +}; + +const DELEGATION_MODE_LABELS: Record = { + user: "With You", + "first-pass": "First Pass", + auto: "Auto", +}; + +export function whyUserBadge(item: TierItem): string { + if (!item.whyUser) return ""; + return ` ${esc(WHY_USER_LABELS[item.whyUser])}`; +} + +function questionFieldHtml(q: TierItemQuestion, answeredValue?: string | string[], answerAction?: DashAction): string { + const name = `answers:${q.id}`; + const answered = answeredValue !== undefined; + const disabled = answered ? " disabled" : ""; + let field: string; + if (q.type === "single" || q.type === "yesno") { + const opts = q.options ?? [ + { id: "yes", label: "Yes" }, + { id: "no", label: "No" }, + ]; + field = `${opts + .map( + (o) => + ``, + ) + .join("")}`; + } else if (q.type === "multi") { + const chosen = Array.isArray(answeredValue) ? answeredValue : answeredValue ? [answeredValue] : []; + field = `${(q.options ?? []) + .map( + (o) => + ``, + ) + .join("")}`; + } else { + field = ``; + } + // #1451: answered state rides the card — a partial submit records + // what it covered and the still-open required questions say so. + const state = answered + ? ` ✓ answered: ${esc(Array.isArray(answeredValue) ? answeredValue.join(", ") : (answeredValue ?? ""))}${answerAction ? ` · ${answerAction.state === "new" ? "pending" : "applied"} · action ${esc(answerAction.id)}` : ""}` + : q.required + ? ` still needed` + : ""; + return `
    ${esc(q.prompt)}${q.required ? "" : ` (optional)`}${state}
    ${field}
    Needed: ${esc(q.covers)}
    `; +} + +/** The latest applied reject-proposal on an item, when one exists — + * its reason rides the next proposal's box (#1293). */ +function lastRejection(actions: DashAction[] | undefined): DashAction | undefined { + return (actions ?? []).filter((a) => a.verb === "reject-proposal" && a.state === "applied").at(-1); +} + +/** + * The needs-user body block for one card: summary, the what-happens- + * if-this-sits line, the delegation status line, and the proposal / + * inability boxes (#1291/#1293). Pure content — the forms live in + * needsUserFormsHtml, inside the card's actbox. + */ +export function needsUserBodyHtml(item: TierItem, actions: DashAction[] | undefined, now = Date.now()): string { + const parts: string[] = []; + if (item.summary) parts.push(`
    ${esc(item.summary)}`); + if (item.ifIgnored) + parts.push(`
    If nothing happens: ${esc(item.ifIgnored)}`); + const d = item.delegation; + if (d) { + const rejected = lastRejection(actions); + const statusBits = [ + `Delegation: ${esc(DELEGATION_MODE_LABELS[d.mode])}`, + d.status === "idle" + ? "not started" + : d.status === "working" + ? "the orchestrator is working it" + : d.status === "proposal-ready" + ? "proposal ready for your review" + : d.status === "unable" + ? "returned — the orchestrator could not resolve it" + : "done", + d.runId ? `run ${esc(d.runId)}` : "", + `updated ${esc(relTime(d.updatedAt, now))}`, + ].filter(Boolean); + parts.push(`
    ${statusBits.join(" · ")}`); + if (rejected && d.mode === "first-pass" && d.status !== "proposal-ready") + parts.push( + `
    Previous proposal rejected: ${esc(rejected.payload.reason ?? "")} — a new first pass must differ materially or say why it cannot.`, + ); + if (d.status === "proposal-ready" && d.proposal) { + if (proposalExpired(d, now)) { + parts.push( + `
    Proposal expired — drafted ${esc(fmtDate(d.proposal.at))} by run ${esc(d.runId ?? "unknown")}; it is no longer actionable. Delegate a fresh first pass below.
    ${esc(d.proposal.summary)}
    `, + ); + } else { + parts.push( + `
    First-pass proposal${rejected ? ` — second first pass; previous rejected: ${esc(rejected.payload.reason ?? "")}` : ""}
    ${esc(d.proposal.summary)}${ + d.proposal.detail ? `
    ${esc(d.proposal.detail)}` : "" + }${ + d.proposal.proposedChanges?.length + ? `
    Proposed changes:
      ${d.proposal.proposedChanges.map((c) => `
    • ${esc(c)}
    • `).join("")}
    ` + : "" + }Drafted ${esc(fmtDate(d.proposal.at))} — nothing is applied unless you approve; approval takes effect on the next orchestration pass.
    `, + ); + } + } + if (d.status === "unable" && d.unable) { + parts.push( + `
    The orchestrator could not resolve this — ${esc(d.unable.reason)}
    Tried:
      ${d.unable.whatItTried.map((t) => `
    • ${esc(t)}
    • `).join("")}
    Needs: ${esc(d.unable.whatItNeeds)}
    Declared ${esc(fmtDate(d.unable.at))} by run ${esc(d.runId ?? "unknown")}.
    `, + ); + } + } + // #1293: a pending approve/reject whose proposal has since changed + // renders as no longer applicable, not as a live request. + const pendingProposalAction = (actions ?? []).some( + (a) => a.state === "new" && (a.verb === "approve-proposal" || a.verb === "reject-proposal"), + ); + if (pendingProposalAction) { + const live = proposalIdentity(item); + const stillLive = (actions ?? []).some( + (a) => + a.state === "new" && + (a.verb === "approve-proposal" || a.verb === "reject-proposal") && + live !== null && + a.payload.proposalRunId === live.runId && + a.payload.proposalUpdatedAt === live.updatedAt, + ); + if (!stillLive) + parts.push( + `
    ⏳ A pending proposal action is no longer applicable — the proposal changed since it was recorded; the pass will reject it with that note.`, + ); + } + return parts.join(""); +} + +/** + * The needs-user forms for one card (they join the card's actbox): + * the item's own options as answer buttons, the survey as one answer + * form, a free-text answer when the item offers neither, delegation + * mode controls, proposal approve/reject, and dismiss (#1291). + */ +export function needsUserFormsHtml( + item: TierItem, + objectRef: string, + now = Date.now(), + cs: CardState = cardState(undefined), +): string { + const forms: string[] = []; + // Older option actions predate the canonical question pointer. Resolve + // them from the currently published item so already-answered cards + // cannot reopen the same question after this deploy. + const answered = new Map(cs.answered); + const answerActionsByQuestion = new Map(cs.answerActionsByQuestion); + for (const [optionId, action] of cs.answeredOptionActionsById) { + const questionId = questionIdForOption(item, optionId); + if (questionId && !answered.has(questionId)) { + answered.set(questionId, optionId); + answerActionsByQuestion.set(questionId, action); + } + } + for (const opt of item.options ?? []) { + const questionId = questionIdForOption(item, opt.id); + const questionValue = questionId ? answered.get(questionId) : undefined; + const answerAction = questionId ? answerActionsByQuestion.get(questionId) : cs.answeredOptionAction; + const locked = questionId ? questionValue !== undefined : cs.answeredOptionActionsById.size > 0; + const picked = cs.answeredOptionId === opt.id || (questionId !== undefined && questionValue === opt.id); + forms.push( + aformHtml({ + kind: "triage", + verb: "answer", + objectRef, + inner: `${locked && answerAction ? `Answer action ${esc(answerAction.id)}` : ""}${ + opt.description ? `${esc(opt.description)}` : "" + }${opt.effect ? `Effect: ${esc(opt.effect)}` : ""}`, + }), + ); + } + if (item.questions?.length) { + const remaining = item.questions.filter((q) => q.required && !answered.has(q.id)); + const allDone = remaining.length === 0 && item.questions.some((q) => answered.has(q.id)); + const hasUnanswered = item.questions.some((q) => !answered.has(q.id)); + forms.push( + aformHtml({ + kind: "triage", + verb: "answer", + objectRef, + inner: `${item.questions.map((q) => questionFieldHtml(q, answered.get(q.id), answerActionsByQuestion.get(q.id))).join("")}${ + allDone + ? "All required questions are answered — the answers are recorded and pending with the orchestrator." + : `Answer any subset and submit (#1451): answered questions are recorded, and the card keeps showing what remains${remaining.length ? ` — still needed: ${esc(remaining.map((q) => q.id).join(", "))}` : ""}.` + }`, + }), + ); + } + if (!item.options?.length && !item.questions?.length) { + forms.push( + aformHtml({ + kind: "triage", + verb: "answer", + objectRef, + inner: ``, + }), + ); + } + const d = item.delegation; + if (d) { + const autoBlocked = item.whyUser === "access" || item.whyUser === "policy"; + const expired = proposalExpired(d, now); + const modeButton = (mode: DelegationMode, label: string) => { + if (mode === "auto" && autoBlocked) + return `${esc(WHY_USER_LABELS[item.whyUser!])} items can never be auto-delegated — they stay with you.`; + const current = d.mode === mode && !(expired && mode === "first-pass"); + return aformHtml({ + kind: "triage", + verb: "delegate", + objectRef, + inner: ``, + }); + }; + forms.push( + modeButton( + "first-pass", + expired && d.mode === "first-pass" ? "Delegate: First Pass (fresh draft)" : "Delegate: First Pass", + ), + modeButton("auto", "Delegate: Auto"), + modeButton("user", "Bring Back to Me"), + ); + if (d.status === "proposal-ready" && d.proposal && !expired && d.runId) { + const identity = + `` + + ``; + forms.push( + aformHtml({ + kind: "triage", + verb: "approve-proposal", + objectRef, + inner: `${identity}The pass applies it on its next run and reports the application.`, + }), + aformHtml({ + kind: "triage", + verb: "reject-proposal", + objectRef, + inner: `${identity}`, + }), + ); + } + } + forms.push( + aformHtml({ + kind: "triage", + verb: "dismiss", + objectRef, + inner: `Dismissed items stay out of the queue unless a new material fact appears — then they resurface with the fact cited.`, + }), + ); + // A pending delegation action supersedes the stamped mode display: + // the badges already say so; nothing extra to render here. + return forms.join(""); +} + +/** The standing delegation-default toggle (#1290/#1291): the current + * effective value from the preference records, with the change form. */ +export function delegationDefaultHtml(records: DashAction[] | undefined, opts: ActionFormOpts): string { + const eff = effectiveStandingAuto(records ?? []); + const state = eff.standingAuto + ? `On — Decision, Missing Info, and Approval items delegate to Auto by default` + : `Off — items stay with you unless you delegate them per item`; + const pending = eff.pending + ? ` ⏳ change pending — applies on the next orchestration pass` + : ""; + const form = aformHtml({ + kind: "preference", + verb: "set-delegation-default", + objectRef: DELEGATION_DEFAULT_OBJECT_REF, + inner: `Access and Policy items never auto, whatever this says. Per-item delegation always overrides the default. Initial record: the user's decision, 2026-10-27.`, + }); + return `
    Standing delegation default — ${state}.${pending}${actboxHtml(opts, form)}
    `; +} + +/** The Project Status values a status request may target (#910 field). + * #1198: this set IS the canonical status taxonomy's set — one + * definition (status-taxonomy.ts), adopted here, never a second copy. */ +export const PROJECT_STATUS_VALUES = CANONICAL_STATUSES; + +/** The #1154 control: request a Project Status change (never a direct write). */ +export function statusRequestHtml( + objectRef: string, + targetRef: RefKey, + currentStatus: string | null, + opts: ActionFormOpts, +): string { + const options = PROJECT_STATUS_VALUES.map( + (s) => ``, + ).join(""); + const form = aformHtml({ + kind: "status-request", + verb: "request-status", + objectRef, + targetRef, + inner: `A request, not a write — the orchestration pass (the Project's single writer) applies it on its next run.`, + }); + return actboxHtml(opts, form); +} + +/** Which session verbs a source can support, and why not when it can't. */ +export function sessionVerbSupport(source: string): { verb: "poke" | "answer" | "stop"; reason?: string }[] { + if (source === "opencode-sandbox" || source === "opencode-laptop") { + return [{ verb: "poke" }, { verb: "answer" }, { verb: "stop" }]; + } + if (source === "claude-code") { + const reason = "No live control channel for Muse sessions — launch records only"; + return [ + { verb: "poke", reason }, + { verb: "answer", reason }, + { verb: "stop", reason }, + ]; + } + return []; +} + +/** The #1156 control set for one live session (merged registry identity). */ +export function sessionActionsHtml(sessionId: string, source: string, opts: ActionFormOpts): string { + const support = sessionVerbSupport(source); + if (!support.length) return ""; + const objectRef = sessionObjectRef(sessionId); + const forms = support + .map(({ verb, reason }) => { + if (reason) { + return `
    ${esc(reason)}.
    `; + } + if (verb === "poke") { + return aformHtml({ + kind: "session", + verb, + objectRef, + sessionId, + sessionSource: source, + inner: `Nudges the session via its owning server.`, + }); + } + if (verb === "answer") { + return aformHtml({ + kind: "session", + verb, + objectRef, + sessionId, + sessionSource: source, + inner: ``, + }); + } + return aformHtml({ + kind: "session", + verb, + objectRef, + sessionId, + sessionSource: source, + inner: `Two-step: tick Confirm stop, then Stop — the owning job terminates the run.`, + }); + }) + .join(""); + return actboxHtml(opts, forms); +} + +/** Terminal registry statuses — a record in one of these is history, not live. */ +const TERMINAL_SESSION_STATUSES = new Set([ + "completed", + "complete", + "done", + "failed", + "error", + "stopped", + "terminated", + "succeeded", + "cancelled", +]); + +/** A registry record counts as live inside the attention currency window (2 h). */ +export function sessionRecordIsLive(r: SessionRecord, now = Date.now()): boolean { + if (TERMINAL_SESSION_STATUSES.has(r.status.toLowerCase())) return false; + if (!r.lastSeenAt) return false; + return now - Date.parse(r.lastSeenAt) < 2 * 60 * 60 * 1000; +} + +export function coverageHtml(coverage: SourceCoverage[]): string { + const rows = coverage + .map( + (c) => + `
  • ${c.wired ? "✓" : "⚠"} ${esc(c.label)} — ${c.wired ? "wired" : "not wired"} · ${esc(c.detail)}
  • `, + ) + .join(""); + return `
    Session coverage
      ${rows}
    `; +} + +export function itemBadge(item: GhItem): string { + // #1141: fixture-resolved state is invented fallback data — render it + // hollow (dashed, transparent) and named "unverified" so it can never + // be mistaken for a live badge on board/roadmap/item/program pages. + const unverified = item.resolution === "fixture"; + const cls = item.state === "merged" ? "merged" : item.state === "open" ? "open" : "closed"; + const kind = item.kind === "pr" ? (item.state === "merged" ? "PR merged" : "PR") : "issue"; + const draft = item.draft ? " · draft" : ""; + const marker = unverified ? " · unverified" : ""; + const title = unverified ? `${item.title} (unverified — fixture state, not live GitHub data)` : item.title; + return `${kind} ${esc(item.ref)}${draft}${marker}`; +} + +export function stripHtml(items: Map, links: BoardItem["links"]): string { + const strip = executionStrip(links, items); + const buckets: [string, string, GhItem[]][] = [ + ["implementing", "implementing", strip.implementing], + ["review", "review", strip.review], + ["merged", "merged", strip.merged], + ["open", "queued", strip.queued], + ["closed", "closed", strip.closed], + ]; + const parts: string[] = []; + for (const [cls, label, list] of buckets) { + if (list.length === 0) continue; + parts.push(`${label}: ${list.length}` + list.map(itemBadge).join(" ")); + } + if (strip.unknown.length) { + parts.push(`unresolved: ${strip.unknown.map(esc).join(", ")}`); + } + return `
    ${parts.join(" ")}
    `; +} + +export function briefPanelsForRefs(refs: RefKey[], briefs?: Map): string { + return [...new Set(refs)] + .map((ref) => briefs?.get(ref)) + .filter((brief): brief is ItemBrief => Boolean(brief)) + .map(briefPanelHtml) + .join(""); +} + +export function briefPanelHtml(brief: ItemBrief): string { + const ev = (e: { text: string; url: string }) => `${esc(e.text)}`; + const activity = brief.lastActivity.evidence + ? `${esc(brief.lastActivity.text)} Evidence: ${ev(brief.lastActivity.evidence)}.` + : esc(brief.lastActivity.text); + const clash = brief.disagreement + ? `
    ⚠ ${esc(brief.disagreement.text)} Evidence: ${ev(brief.disagreement.evidence)}.` + : ""; + return `
    Derived brief (derived from the projection — not authored)
    State: ${esc(brief.state.text)} Evidence: ${ev(brief.state.evidence)}.
    Blocker: ${esc(brief.blocker.text)} Evidence: ${ev(brief.blocker.evidence)}.
    ${activity}
    Next: ${esc(brief.nextAction.text)} Evidence: ${ev(brief.nextAction.evidence)}.${clash}
    `; +} diff --git a/pm-stack/aggregator/src/render-dns.ts b/pm-stack/aggregator/src/render-dns.ts new file mode 100644 index 0000000000..56bff65642 --- /dev/null +++ b/pm-stack/aggregator/src/render-dns.ts @@ -0,0 +1,101 @@ +// render.ts split (#13051): DNS register view. +// render.ts re-exports every public name from here; callers keep importing "./render.ts". + +import { summarizeDns } from "./dns.ts"; +import type { DnsEntry, DnsSection, Provenance, ProvenanceDetail } from "./model.ts"; +import { dnsAnchor } from "./search-view.ts"; + +import { esc, fmtDate, freshnessChips, layout } from "./render-core.ts"; + +// --- DNS register page (#906 §1, data from #902) ----------------------------- + +function dnsTable(entries: DnsEntry[], renewingSoon: Set, nextRenewal?: DnsEntry | null): string { + const rows = entries + .map( + (e) => + `${esc(e.domain)}${esc(e.renewal)}${e.priceUsd != null ? `$${e.priceUsd.toFixed(2)}` : "—"}${esc(e.autoRenew)}${esc(e.plan)}${esc(e.review)}`, + ) + .join(""); + return `
    ${rows || ''}
    Domain register
    DomainNext renewalPrice (list)Auto-renewPlan / statusReview?
    none
    `; +} + +const DNS_FILTER_SCRIPT = ``; + +export function renderDns(section: DnsSection | null, provenance: Provenance, detail?: ProvenanceDetail): string { + const chips = detail ? freshnessChips(detail, ["dns"]) : ""; + if (!section) { + return layout( + "DNS register", + `

    DNS / domain register

    `, + provenance, + "/dns", + "", + chips, + ); + } + const s = summarizeDns(section); + const next = s.nextRenewal; + const soonTotal = Math.round(s.renewingSoon.reduce((sum, e) => sum + (e.priceUsd ?? 0), 0) * 100) / 100; + const renewingSoon = new Set(s.renewingSoon); + const filters = [ + ["all", "All", section.entries.length], + ["active", "Active", s.active.length], + ["earmarked", "Earmarked", s.earmarked.length], + ["unused", "Unused", s.unused.length], + ["renewing-soon", "Renewing soon", s.renewingSoon.length], + ] as const; + const filterChips = filters + .map( + ([filter, label, count], index) => + ``, + ) + .join(""); + const body = `

    DNS / domain register

    +

    ${section.entries.length} domains · $${section.totalAnnualListUsd.toFixed(2)}/yr at list renewal prices · register parsed ${fmtDate(section.generatedAt)} (${esc(section.source)}). The register is maintained by the #902 pipeline — this page renders it, never edits it. Machine-first: /api/dns.json.

    +
    +
    Next renewal
    ${ + next + ? `${esc(next.renewal)}${next.priceUsd != null ? ` · $${next.priceUsd.toFixed(2)}` : ""}
    See its row in the renewal-sorted register.` + : "—" + }
    +
    Renewing in 45 days
    ${s.renewingSoon.length} domain${s.renewingSoon.length === 1 ? "" : "s"} · $${soonTotal.toFixed(2)} at list price
    +
    Auto-renew
    ${s.autoRenew.on} ON · ${s.autoRenew.off} OFF · ${s.autoRenew.unknown} unknown
    +
    Portfolio shape
    ${s.active.length} in use · ${s.earmarked.length} unused but earmarked · ${s.unused.length} completely unused
    +
    +

    Domain register (${section.entries.length})

    +
    ${filterChips}
    +${dnsTable(section.entries, renewingSoon, next)}`; + return layout("DNS register", body, provenance, "/dns", DNS_FILTER_SCRIPT, chips); +} diff --git a/pm-stack/aggregator/src/render-program.ts b/pm-stack/aggregator/src/render-program.ts new file mode 100644 index 0000000000..9e4f4c7fe9 --- /dev/null +++ b/pm-stack/aggregator/src/render-program.ts @@ -0,0 +1,1235 @@ +// render.ts split (#13051): projects and program views, epic graph and phase panels. +// render.ts re-exports every public name from here; callers keep importing "./render.ts". + +import { renderDesignBoards, type BoardSnapshot } from "./design-boards.ts"; +import { timeline as buildTimeline } from "./derive.ts"; +import type { CoverageSnapshotFile } from "./coverage.ts"; +import 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 { cardState } from "./card-state.ts"; +import { serviceHomeLinks } from "./service-links.ts"; +import { + type GhItem, + type OrchestrationSection, + type ProjectAudit, + type ProjectPoolItem, + type Provenance, + type ProvenanceDetail, + type RefKey, + isValidRef, + refUrl, +} from "./model.ts"; +import type { ProgramData, ProgramEntry, ProgramLive, TrackedIssue } from "./program.ts"; +import type { ProjectDetail, ProjectSummary } from "./project-config.ts"; +import { derivedProjectState, projectDisagreement, PROJECT_URL } from "./projects.ts"; +import { + PHASE12_ISSUE_URL, + joinPhase12Steps, + parsePhase12Steps, + phase12IsStale, + type Phase12Snapshot, + type Phase12StepState, +} from "./phase12.ts"; +import { + PHASE_TRACKER_REPO, + PHASE_TRACKER_UMBRELLA, + derivePhase12Progress, + derivePhaseValidation, +} from "./phase-tracker.ts"; +import { deriveMappedProgress, type PhaseMappingSnapshot } from "./phase-mapping.ts"; +import { + BUILD_HEALTH_REPO, + buildHealthIsStale, + projectLane, + projectNightlyTrend, + type BuildHealthSnapshot, +} from "./build-health.ts"; +import type { QueueSnapshot } from "./queue.ts"; +import { + F12_DESIGN_ISSUE_URL, + parseF12Designs, + parseF12Items, + projectF12Readiness, + type F12PrRef, +} from "./f12-readiness.ts"; +import { canonicalStatusFor } from "./status-taxonomy.ts"; +import { buildItemBrief, type ItemBrief } from "./brief.ts"; +import { buildEpicRollups, uniqueProjectItemsByRef, type EpicRollup } from "./epics.ts"; +import { spendCardHtml, unattributedSpendHtml, type SpendCardsView } from "./spend-cards.ts"; +import { effortWeight, handsLine, summarizeWeights, weightedLine } from "./weights.ts"; +import { blockedSummary, depthLayout, hasGraphEdges } from "./graph.ts"; +import { EPIC_GRAPH_DEFAULT_CAP, epicGraph, epicSelector } from "./epic-graph.ts"; +import type { AuthorIdentity } from "./registry.ts"; + +import { + esc, + fmtDate, + ACTION_SCRIPT, + freshnessChips, + layout, + sessionObjectRef, + ghObjectRef, + tierItemObjectRef, + actionBadgesHtml, + actionHistoryHtml, + triageActionsHtml, + needsUserBodyHtml, + needsUserFormsHtml, + statusRequestHtml, + sessionVerbSupport, + sessionActionsHtml, + itemBadge, + briefPanelHtml, +} from "./render-core.ts"; +import { forecastSummaryHtml, timelineTable, epicRollupHtml } from "./render-board.ts"; +import { coverageSectionHtml, statusTaxonomyHtml } from "./render-views.ts"; + +export function projectsBodyHtml( + pool: ProjectPoolItem[], + opts: { + area?: string | null; + /** Pool facet filters (#1208): Project Status / Kind single-select values, or the "(no status)" / "(no kind)" unset buckets. */ + status?: string | null; + kind?: string | null; + /** Project #4 audit snapshot (#1208): reconciles the rendered pool count against the board total (draft/unlinked caveat). */ + audit?: ProjectAudit | null; + orchestration?: OrchestrationSection | null; + detail?: ProvenanceDetail; + actionsByObject?: Map; + identities?: AuthorIdentity[]; + coverage?: CoverageSnapshotFile | null; + /** Where the area chips point: /projects standalone, /program once merged (#1497). */ + basePath?: string; + /** Prebuilt briefs (#1279), e.g. with comment activity folded in. + * Absent: briefs are built here from the pool + orchestration only. */ + briefs?: Map; + /** Shared forecast contracts by item ref (#3984): the same objects + * /api/forecasts.json serves, rendered as one-line summaries. */ + forecasts?: Map; + /** Spend beside progress (#4824): the #4823 rollup store's + * reader view. Absent/null: cards render exactly as before. */ + spend?: SpendCardsView | null; + } = {}, +): string { + const base = opts.basePath ?? "/projects"; + const areas = [...new Set(pool.map((p) => p.area).filter((a): a is string => Boolean(a)))].sort(); + // #1143: Area-unset items get an explicit "(unset)" bucket, mirroring + // the /program index banner — without it they are silently mixed into + // "all" with no count and no way to view them as the gap they are. + const UNSET_AREA = "(unset)"; + const unsetCount = pool.filter((p) => !p.area).length; + const area = + opts.area === UNSET_AREA && unsetCount > 0 ? UNSET_AREA : opts.area && areas.includes(opts.area) ? opts.area : null; + const shownByArea = + area === UNSET_AREA ? pool.filter((p) => !p.area) : area ? pool.filter((p) => p.area === area) : pool; + // #1208: Status and Kind are pool fields too — facet-filter them like + // Area (the saved-view dimensions in views.ts carry the same pair, so + // a view and the chips agree). "(no status)" / "(no kind)" are the + // explicit unset buckets, mirroring the Area "(unset)" bucket (#1143). + const UNSET_STATUS = "(no status)"; + const UNSET_KIND = "(no kind)"; + const statuses = [...new Set(pool.map((p) => p.status).filter((s): s is string => Boolean(s)))].sort(); + const kinds = [...new Set(pool.map((p) => p.kind).filter((s): s is string => Boolean(s)))].sort(); + const statusSel = + opts.status === UNSET_STATUS ? UNSET_STATUS : opts.status && statuses.includes(opts.status) ? opts.status : null; + const kindSel = opts.kind === UNSET_KIND ? UNSET_KIND : opts.kind && kinds.includes(opts.kind) ? opts.kind : null; + const shown = shownByArea + .filter((p) => (statusSel === UNSET_STATUS ? !p.status : statusSel ? p.status === statusSel : true)) + .filter((p) => (kindSel === UNSET_KIND ? !p.kind : kindSel ? p.kind === kindSel : true)); + /** Facet link builder: change one facet, keep the others. */ + const facetHref = (patch: { area?: string | null; status?: string | null; kind?: string | null }): string => { + const q = new URLSearchParams(); + const a = patch.area !== undefined ? patch.area : area; + const s = patch.status !== undefined ? patch.status : statusSel; + const k = patch.kind !== undefined ? patch.kind : kindSel; + if (a) q.set("area", a); + if (s) q.set("status", s); + if (k) q.set("kind", k); + const qs = q.toString(); + return qs ? `${base}?${qs}` : base; + }; + const chips = [ + `all (${pool.length})`, + ...areas.map( + (a) => + `${esc(a)} (${pool.filter((p) => p.area === a).length})`, + ), + ...(unsetCount > 0 + ? [ + `${UNSET_AREA} (${unsetCount})`, + ] + : []), + ].join(""); + if (!pool.length) { + return `${coverageSectionHtml(opts.coverage)}${opts.spend?.unattributed ? unattributedSpendHtml(opts.spend.unattributed) : ""}

    Live services: ${serviceHomeLinks() + .map((s) => `${esc(s.label)} ↗`) + .join(" · ")}

    `; + } + const areaWeights = areas + .map((a) => { + const items = pool.filter((p) => p.area === a); + const w = summarizeWeights(uniqueProjectItemsByRef(items)); + return `
    ${esc(a)} — ${esc(weightedLine(w))}
    ${esc(handsLine(w))}
    `; + }) + .join(""); + const shownWeights = summarizeWeights(uniqueProjectItemsByRef(shown)); + const epicRollups = buildEpicRollups(pool); + const cards = shown + .map((p) => { + const derived = derivedProjectState(p, opts.orchestration); + const clash = projectDisagreement(p, opts.orchestration); + const clashBadge = clash + ? ` ⚠ project: ${esc(clash.project)} · derived: ${esc(clash.derived)}` + : ""; + const statusBadge = p.status + ? `${esc(p.status)}` + : `no status`; + const linksLine = `${esc(p.repo)}#${p.number} · Project item · Project #4${p.updatedAt ? ` · updated ${fmtDate(p.updatedAt)}` : ""}`; + // #5082: only active work (canonical Project status + // In Progress / In Review) and epics + // render as a full card — status-request control, derived + // brief, rollups. An epic's rollup / forecast / spend ARE its + // substance at any status (#3984, #4824) and epics are few + // (40 of 1,422). Every other item renders compact: title, + // badges, links — the shape the per-project pages already + // use. The pool only ever + // grows — 725 of 1,422 items were Done at the 2026-11-13 + // measurement — and at ~2.8 KB per full card (actbox ~1.2 KB + + // brief ~0.9 KB of it) the page reached 4.08 MB and grew with + // every filed item. A compact row keeps the item's identity, + // status, badges and links; the dropped blocks are the ones + // whose content is formulaic for a queued/finished item (the + // brief's "Next: No action" for Done items) or an action that + // belongs to active work. When the derived state disagrees the + // ⚠ clash badge still shows on the compact row, so no signal + // is lost. Counts, chips and weights use the whole pool either + // way; the area filter and saved views filter rows the same. + // Action-result badges (a pending / applied status request) + // also stay on compact rows — only the form and brief drop. + const canonical = canonicalStatusFor("project", p.status); + const active = canonical === "In Progress" || canonical === "In Review" || p.kind === "Epic"; + const objectRef = ghObjectRef(p.ref); + const actionBadges = actionBadgesHtml(opts.actionsByObject?.get(objectRef)); + if (!active) { + const metaCompact = [ + p.area ? `${esc(p.area)}` : "", + p.horizon ? `${esc(p.horizon)}` : "", + p.kind ? `${esc(p.kind)}` : "", + `issue ${esc(p.state)}`, + ].join(" "); + const compactLinks = `${esc(p.repo)}#${p.number} · Project item${p.updatedAt ? ` · updated ${fmtDate(p.updatedAt)}` : ""}`; + return `
    ${esc(p.title)}${clashBadge}
    ${statusBadge} ${metaCompact}
    ${compactLinks}${actionBadges}
    `; + } + const meta = [ + p.area ? `${esc(p.area)}` : "", + p.horizon ? `${esc(p.horizon)}` : "", + p.kind ? `${esc(p.kind)}` : "", + `issue ${esc(p.state)}`, + `derived: ${esc(derived)}`, + ].join(" "); + // #1154: the status-request control + the store's visible state. + const statusCtl = opts.identities + ? `${actionBadges}${statusRequestHtml(objectRef, p.ref, p.status ?? null, { identities: opts.identities })}` + : ""; + const rollup = p.kind === "Epic" ? epicRollups.get(p.ref) : undefined; + const epicRollup = rollup ? epicRollupHtml(rollup) : ""; + const spendCard = opts.spend?.byScope.get(p.ref); + const spendHtml = spendCard ? spendCardHtml(spendCard) : ""; + const brief = opts.briefs?.get(p.ref) ?? buildItemBrief(p, { pool, orchestration: opts.orchestration }); + const forecastHtml = forecastSummaryHtml(opts.forecasts?.get(p.ref)); + return `
    ${esc(p.title)}${clashBadge}
    ${statusBadge} ${meta}
    ${linksLine}${epicRollup}${spendHtml}${forecastHtml}${statusCtl}${briefPanelHtml(brief)}
    `; + }) + .join(""); + const body = `

    ${pool.length} items from the org Project Developing Today (#4), read live by the fleet-feed collector (GraphQL, read-only) and carried in the feed. This pool is the resolution source for board/roadmap GitHub items. Where the Project Status and the derived state disagree, the card shows ⚠ with both values. Machine-first: /api/projects.json.

    +
    ${chips}
    +
    Status: ${[ + `any`, + ...statuses.map( + (s) => + `${esc(s)} (${pool.filter((p) => p.status === s).length})`, + ), + ...(pool.some((p) => !p.status) + ? [ + `${UNSET_STATUS} (${pool.filter((p) => !p.status).length})`, + ] + : []), + ].join("")}
    +
    Kind: ${[ + `any`, + ...kinds.map( + (k) => + `${esc(k)} (${pool.filter((p) => p.kind === k).length})`, + ), + ...(pool.some((p) => !p.kind) + ? [ + `${UNSET_KIND} (${pool.filter((p) => !p.kind).length})`, + ] + : []), + ].join("")}
    +${opts.audit && (opts.audit.poolTotalItems ?? opts.audit.totalItems) > pool.length ? `` : ""} +${shown.length !== pool.length ? `

    Filters show ${shown.length} of ${pool.length} pool items.

    ` : ""} +${unsetCount > 0 ? `` : ""} +${coverageSectionHtml(opts.coverage)} +${statusTaxonomyHtml()} +

    Weighted progress (effort xs=1 · s=4 · m=12 · l=40, #1108): ${esc(weightedLine(shownWeights))}
    ${esc(handsLine(shownWeights))}

    +${area ? "" : `

    Per-Area weighted progress

    ${areaWeights}`} +

    Live services: ${serviceHomeLinks() + .map((s) => `${esc(s.label)} ↗`) + .join(" · ")}

    +${cards || '

    No items in this area.

    '}${opts.spend?.unattributed ? unattributedSpendHtml(opts.spend.unattributed) : ""}`; + return body; +} + +export function renderProjects( + pool: ProjectPoolItem[], + provenance: Provenance, + opts: { + area?: string | null; + /** Pool facet filters (#1208): Project Status / Kind single-select values, or the "(no status)" / "(no kind)" unset buckets. */ + status?: string | null; + kind?: string | null; + /** Project #4 audit snapshot (#1208): reconciles the rendered pool count against the board total (draft/unlinked caveat). */ + audit?: ProjectAudit | null; + designBoards?: BoardSnapshot[]; + orchestration?: OrchestrationSection | null; + detail?: ProvenanceDetail; + actionsByObject?: Map; + identities?: AuthorIdentity[]; + coverage?: CoverageSnapshotFile | null; + basePath?: string; + briefs?: Map; + forecasts?: Map; + spend?: SpendCardsView | null; + } = {}, +): string { + return layout( + "Projects", + `

    Projects — GitHub Project pool

    +${renderDesignBoards(opts.designBoards ?? [])} +${projectsBodyHtml(pool, opts)}`, + provenance, + "/projects", + opts.identities ? ACTION_SCRIPT : "", + opts.detail ? freshnessChips(opts.detail, ["items"]) : "", + ); +} + +// --- Program status page (#1046: the dashboard documents itself) ------------ +// Editorial sections come from src/program.ts (the PROGRAM object — the +// one file to edit when the program changes); the live-status section is +// derived from the Source at request time by buildProgramLive, so its +// claims cannot drift from the tracked issues / Project pool / +// orchestrator they describe. Unresolvable refs render as "unresolved". + +function programEntryHtml(e: ProgramEntry, items: Map): string { + const refs = (e.refs ?? []) + .map((r) => { + const item = items.get(r); + return item + ? itemBadge(item) + : `unresolved ${esc(r)}`; + }) + .join(" "); + const links = (e.links ?? []).map((l) => `${esc(l.label)}`).join(" · "); + const meta = [refs, links].filter(Boolean).join(" "); + return `
    ${esc(e.title)}
    ${esc(e.detail)}${meta ? `
    ${meta}` : ""}
    `; +} + +function programEntries(entries: ProgramEntry[], items: Map): string { + return entries.map((e) => programEntryHtml(e, items)).join(""); +} + +function countList(list: { name: string; count: number }[]): string { + return list.length ? list.map((c) => `${esc(c.name)}: ${c.count}`).join(" · ") : 'none'; +} + +function trackedTable(tracked: TrackedIssue[]): string { + const rows = tracked + .map(({ ref, item }) => + item + ? `${itemBadge(item)}${esc(item.title)}${esc(item.state)}${fmtDate(item.updatedAt)}` + : `unresolved${esc(ref)}unresolved — the current source cannot resolve this ref—`, + ) + .join(""); + return `
    ${rows}
    Tracked issues
    Tracked issueTitleStateUpdated
    `; +} + +function poolSummaryHtml(live: ProgramLive): string { + return live.pool.total + ? `
    ${live.pool.total} items in the org Project pool
    By status — ${countList(live.pool.byStatus)}
    By area — ${countList(live.pool.byArea)}
    ` + : ``; +} + +function orchestrationHtml(live: ProgramLive): string { + return live.orchestration + ? `
    Orchestrator — latest run ${esc(live.orchestration.runId)}, published ${fmtDate(live.orchestration.generatedAt)}.
    The tiers and goal measurements it publishes are on Needs you and Today.
    ` + : `
    Orchestrator — no orchestration section in the current feed yet (not measured). The Today view derives and labels itself until one lands.
    `; +} + +function projectCard(s: ProjectSummary): string { + const poolLine = + s.poolArea === null + ? `No dedicated Project Area yet.` + : `${s.poolTotal} pool items (${esc(s.poolArea)})${s.poolTotal ? `
    Weighted — ${esc(weightedLine(s.weights))}
    ${esc(handsLine(s.weights))}
    By status — ${countList(s.poolByStatus)}` : ""}`; + const roadmapLine = + s.roadmapArea === null + ? `No Grist roadmap area yet.` + : `${s.roadmapRows} roadmap row${s.roadmapRows === 1 ? "" : "s"} (${esc(s.roadmapArea)})`; + const homeLine = s.homeDoc + ? `
    Home doc: ${esc(s.homeDoc.path)}` + : ""; + return `
    ${esc(s.title)}
    ${poolLine}
    ${roadmapLine}${homeLine}
    Project page →
    `; +} + +/** /program as the projects index (#1121): one card per configured + * project from the registry, the whole-pool + orchestrator live blocks + * from #1046, and the unset-Area count as a visible gap. The full + * pm-dashboard document moved to /program/pm-dashboard — every link + * that pointed at /program still lands here. */ +export function renderProgram( + data: ProgramData, + items: Map, + provenance: Provenance, + detail?: ProvenanceDetail, + poolSection?: { + pool: ProjectPoolItem[]; + area?: string | null; + status?: string | null; + kind?: string | null; + audit?: ProjectAudit | null; + designBoards?: BoardSnapshot[]; + coverage?: CoverageSnapshotFile | null; + orchestration?: OrchestrationSection | null; + actionsByObject?: Map; + identities?: AuthorIdentity[]; + /** Prebuilt briefs (#1279), e.g. with comment activity folded in. */ + briefs?: Map; + forecasts?: Map; + /** The #4829 flow twin the #4830 charts render on this page. */ + flowAnalytics?: FlowAnalytics; + /** Spend beside progress (#4824) for the pool section. */ + spend?: SpendCardsView | null; + } | null, +): string { + const poolSectionHtml = poolSection + ? `

    Projects pool

    +

    The Projects page, merged into Program status by the #1497 curation — the raw org Project pool with its Project-vs-derived disagreements. /projects redirects to this section; the machine twin /api/projects.json is unchanged.

    +${projectsBodyHtml(poolSection.pool, { area: poolSection.area, status: poolSection.status, kind: poolSection.kind, audit: poolSection.audit, orchestration: poolSection.orchestration, actionsByObject: poolSection.actionsByObject, identities: poolSection.identities, coverage: poolSection.coverage, basePath: "/program", briefs: poolSection.briefs, forecasts: poolSection.forecasts, spend: poolSection.spend })}` + : ""; + const { program, live } = data; + const projects = data.projects ?? []; + const unset = live.pool.byArea.find((c) => c.name === "(unset)")?.count ?? 0; + const cards = projects.map(projectCard).join(""); + const unsetHtml = + live.pool.total && unset + ? `` + : ""; + const body = `

    Program status — projects

    +

    Every project the fleet runs, documented the same way: a description, its live Project-pool and roadmap sections, its tracked issues resolved live, and its roadmap — all driven by the project registry in src/project-config.ts. Pick a project for its full page.

    +

    Source of truth: the design record in developing-today/code · the org Project Developing Today (#4) · Machine-first: /api/program.json.

    +

    What runs where — every stack service, its port and bind, and its live health: Health & topology →

    +

    Projects

    +
    ${cards || '

    No projects configured.

    '}
    +${unsetHtml} +${renderDesignBoards(poolSection?.designBoards ?? [])} +

    Live status

    +

    Derived at request time from the Project pool and the latest orchestration section — not written by hand.

    +${poolSummaryHtml(live)} +${orchestrationHtml(live)} +

    The PM dashboard's own record

    +

    This dashboard's architecture, what's built, what's next, and its long-term roadmap live on its project page: PM dashboard →. Its tracked issues, resolved live:

    +${trackedTable(live.tracked)}${poolSectionHtml}${poolSection?.flowAnalytics ? flowChartsHtml(poolSection.flowAnalytics) : ""}`; + return layout( + "Program status", + body, + provenance, + "/program", + poolSection?.identities ? ACTION_SCRIPT : "", + detail ? freshnessChips(detail, ["orchestration", "items", "roadmap"]) : "", + ); +} + +// --- Per-project page (#1121, registry in src/project-config.ts) ------------- + +const POOL_ITEM_CAP = 24; + +/** Render a graph ref as a link only when it satisfies the shared ref rule. */ +function poolRefLink(ref: RefKey): string { + const label = esc(ref); + return isValidRef(ref) ? `${label}` : label; +} + +/** The #2400 graph section of a project page: blocked weight + longest + * blocked chain and the depth-graph SVG, from the part-1 edge contract + * (#2399). Graceful absence is explicit: a pool with no effort labels + * and no edges says "not yet sized/graphed" (never a fake 0%); a sized + * pool without edges says "not yet graphed" only. */ +function poolGraphHtml(items: ProjectPoolItem[], allW: ReturnType): string { + const edges = hasGraphEdges(items); + if (!edges && allW.totalWeight === 0) { + return ``; + } + if (!edges) { + return `

    Not yet graphed: pool items carry no parent / blocked-by edges yet, so blocked weight and the depth graph appear once the collector sees edges. Weighted progress above is from effort labels alone.

    `; + } + const blocked = blockedSummary(items); + const chainHtml = + blocked.longestChain.length >= 2 + ? ` · longest blocked chain: ${blocked.longestChain.map(poolRefLink).join(" → ")} (${blocked.longestChain.length - 1} link${blocked.longestChain.length === 2 ? "" : "s"})` + : ""; + const blockedHtml = blocked.blockedCount + ? `

    Blocked weight: ${blocked.blockedWeight} across ${blocked.blockedCount} open item${blocked.blockedCount === 1 ? "" : "s"} waiting on an unresolved blocker${blocked.blockedUnsizedCount ? ` (${blocked.blockedUnsizedCount} of them unsized — counted, never zero-weighted)` : ""}${chainHtml}.

    ` + : `

    Blocked weight: 0 — no open item is waiting on an unresolved blocker.

    `; + + const layout = depthLayout(items); + const pos = new Map(layout.nodes.map((n) => [n.ref, n])); + const X = (depth: number) => 16 + depth * 180; + const Y = (row: number) => 16 + row * 26; + const width = X(layout.maxDepth) + 340; + const height = Y(layout.nodes.length - 1) + 16; + const edgeLines = layout.edges + .map((e) => { + const a = pos.get(e.from)!; + const b = pos.get(e.to)!; + return ``; + }) + .join(""); + const nodeShapes = layout.nodes + .map((n) => { + const label = `#${n.number} ${n.title.length > 34 ? `${n.title.slice(0, 33)}…` : n.title}`; + const dash = n.mode === "hybrid" ? ` stroke-dasharray="3 2"` : ""; + const strokeW = n.mode === "physical" ? 3 : 1.5; + const shape = n.epic + ? `` + : ``; + return `${shape}${esc(label)}`; + }) + .join(""); + const truncated = layout.truncated + ? `

    Depth graph shows ${layout.nodes.length} of ${items.length} items (cap) — the full set is in the cards below.

    ` + : ""; + const svg = layout.nodes.length + ? `${edgeLines}${nodeShapes}

    Depth = sub-issue nesting from the Project pool. Squares are epics; amber = open, grey = closed. Border: thick solid = mode/physical, dashed = mode/hybrid, thin = online or no mode.

    ${truncated}` + : ""; + return `

    Blocked + depth graph

    ${blockedHtml}${svg}`; +} + +/** The #3973 per-epic dependency graph section of a project page + * (design doc/2026-11-01T21-05-00Z_design_aggregator_dependency_graph_1257.md): + * an epic selector with item/blocked counts, then per epic a summary + + * ranked blocked list beside the graph SVG and a vertical, + * keyboard-readable dependency list. The list is the primary surface + * on narrow screens (the flex column stacks it full-width; the SVG + * may scroll horizontally as a secondary detail). Dependency edges + * are dashed amber, hierarchy edges solid grey, and every node's + * state is written as text — color is never the only signal. Empty + * or unavailable graph data says so; it is never an empty success. */ +/** Section anchor for one epic's graph, derived from the canonical ref + * (owner/repo#number), never the bare issue number: two repositories + * can hold epics with the same number, and bare-number ids collide. */ +function epicGraphAnchor(ref: RefKey): string { + return `epic-graph-${ref.replace(/[^a-zA-Z0-9]+/g, "-")}`; +} + +interface EpicGraphActionContext { + orchestration?: OrchestrationSection | null; + actionsByObject?: Map; + identities?: AuthorIdentity[]; + orchestrationState?: string; +} + +function epicGraphSectionHtml( + items: ProjectPoolItem[], + selectorItems: ProjectPoolItem[] = items, + actionContext?: EpicGraphActionContext, +): string { + // Selector entries and rendered sections are scoped to the project's + // own pool (selectorItems = detail.poolItems): on a normal project + // request the caller passes the entire org pool as `items` for + // membership and blocker resolution, and rendering every eligible + // epic from every Area would bury this project's section in unrelated + // projects (Codex round-2 on #3973). Resolution inside each section + // still runs against the full `items` pool. + // The selector rollups are computed from the full `items` pool too, + // then filtered to this project's epic refs (Codex round-3 on + // #3973): computing them from the scoped pool made a member whose + // blocker lives in another Area count as blocked in the selector + // while its section — resolving against the full pool — correctly + // reported it unblocked. + const projectEpicRefs = new Set(selectorItems.filter((i) => i.kind === "Epic").map((i) => i.ref)); + const selector = epicSelector(items).filter((e) => projectEpicRefs.has(e.ref)); + if (!selector.length) { + return `

    Per-epic dependency graph

    `; + } + const selectorHtml = ``; + const sections = selector.map((entry) => epicGraphOneHtml(items, entry, actionContext)).join(""); + return `

    Per-epic dependency graph

    ${selectorHtml}${sections}`; +} + +function graphNodeActionsHtml(nodeRef: RefKey, context?: EpicGraphActionContext): string { + const section = context?.orchestration; + const drewItem = section?.tiers.needsDrew.find((item) => item.ref === nodeRef); + const orchestratorItem = section?.tiers.needsOrchestrator.find((item) => item.ref === nodeRef); + const item = drewItem ?? orchestratorItem; + if (!item) { + return `

    No inline action: this item is not in the currently published Needs User or Needs Orchestrator tier.

    `; + } + + const tier = drewItem ? "needs-drew" : "needs-orchestrator"; + const objectRef = tierItemObjectRef(item); + const actions = context?.actionsByObject?.get(objectRef); + const state = cardState(actions); + const disabledReason = + item.source === "watchdog" || context?.orchestrationState === "live" + ? undefined + : `the tier source is ${context?.orchestrationState ?? "unavailable"}, so this item cannot be confirmed against the orchestrator's current published queues`; + const controls = context?.identities + ? triageActionsHtml( + objectRef, + tier, + { identities: context.identities, ...(disabledReason ? { disabledReason } : {}) }, + tier === "needs-drew" ? needsUserFormsHtml(item, objectRef, Date.now(), state) : "", + state, + ) + : `

    Inline actions unavailable: no dashboard author identity is configured.

    `; + const needsUserBody = tier === "needs-drew" ? needsUserBodyHtml(item, actions) : ""; + const history = `${actionBadgesHtml(actions)}
    Action history${actionHistoryHtml(actions)}
    `; + + let sessionControls = ""; + if (item.sessionId) { + const sessionSource = item.source === "claude" ? "claude-code" : item.source; + const support = sessionVerbSupport(sessionSource); + if (!context?.identities) { + sessionControls = `

    Session action unavailable: no dashboard author identity is configured.

    `; + } else if (support.some((entry) => !entry.reason)) { + const sessionRef = sessionObjectRef(item.sessionId); + const sessionActions = context?.actionsByObject?.get(sessionRef); + sessionControls = `${actionBadgesHtml(sessionActions)}${sessionActionsHtml(item.sessionId, sessionSource, { identities: context.identities })}
    Session action history${actionHistoryHtml(sessionActions)}
    `; + } else { + const reason = + support.find((entry) => entry.reason)?.reason ?? + "this published item has no supported live session control channel"; + sessionControls = `

    Session action unavailable: ${esc(reason)}.

    `; + } + } + + return `
    ${tier === "needs-drew" ? "Needs User" : "Needs Orchestrator"}${needsUserBody}${history}${controls}${sessionControls}
    `; +} + +function epicGraphOneHtml( + items: ProjectPoolItem[], + entry: ReturnType[number], + actionContext?: EpicGraphActionContext, +): string { + const g = epicGraph(items, entry.ref); + const heading = `

    ${esc(entry.title)} (${esc(entry.ref)})

    `; + if (g.status === "unavailable" || !g.epic) { + return `
    ${heading}
    `; + } + const poolByRef = new Map(items.map((p) => [p.ref, p])); + const unresolvedOf = (ref: RefKey): boolean => { + const held = poolByRef.get(ref); + return held === undefined || held.state === "open"; + }; + const summary = `

    ${g.memberCount} item${g.memberCount === 1 ? "" : "s"} in this epic · ${g.blockedCount} blocked on an unresolved blocker · ${g.externalCount} one-hop reference${g.externalCount === 1 ? "" : "s"} outside this pool (unresolved — status unknown, never counted as resolved).

    `; + const cycleGroupsHtml = g.cycleGroups.length + ? `
    ${g.cycleGroups + .map((group) => { + const members = group.members + .map((ref) => { + const member = poolByRef.get(ref); + return `
  • ${poolRefLink(ref)}${member?.title ? ` — ${esc(member.title)}` : ""}
  • `; + }) + .join(""); + const explanation = + group.kind === "dependency" + ? "The dependency data is contradictory. Resolving one member alone does not clear this cycle; correct the cycle edges." + : "The parent links are cyclic. These members are one hierarchy warning group, not independent roots; correct the parent edges."; + return ``; + }) + .join("")}
    ` + : ""; + const edgeDiagnosticsHtml = g.edgeDiagnostics.length + ? `` + : ""; + const truncatedHtml = g.truncated + ? `

    Truncated: this graph shows ${g.nodes.length} of ${g.totalNodes} nodes (cap ${EPIC_GRAPH_DEFAULT_CAP}). The counts above cover the full set; a capped graph is not complete.

    ` + : ""; + + // Ranked summary: open member items by how many distinct open epic items + // are in the transitive blockedBy ancestry of their blockers (the full + // transitive downstream ranking is #3974). Never derived from the + // capped node list: a member the cap hid is still waiting. + const ranked = g.rankedBlocked; + const rankedHtml = ranked.length + ? `
      ${ranked + .map((r) => { + const blockerItems = r.blockers.map((b) => poolRefLink(b)); + const contributingItems = + r.contributingItems.length > 0 + ? `
      Contributing downstream epics: ${r.contributingItems.map((ci) => poolRefLink(ci)).join(", ")}` + : ""; + return `
    • ${esc(r.ref)} — waiting on ${r.downstreamCount} distinct downstream open epic item${r.downstreamCount === 1 ? "" : "s"} via ${r.blockers.length} unresolved blocker${r.blockers.length === 1 ? "" : "s"}: ${blockerItems.join(", ")}${contributingItems}
    • `; + }) + .join("")}
    ` + : g.blockedCount > 0 + ? `

    ${g.blockedCount} open item${g.blockedCount === 1 ? " is" : "s are"} waiting on an unresolved blocker, but none can be ranked here — members of a dependency cycle are excluded from the unblock ranking until the cycle is broken.

    ` + : `

    No open item in this epic is waiting on an unresolved blocker.

    `; + + const rankedBlockersHtml = g.rankedBlockers.length + ? `
      ${g.rankedBlockers + .map((blocker) => { + const stateText = + blocker.state === null ? "outside this pool; status unknown — unresolved" : "open unresolved blocker"; + const downstream = blocker.downstreamItems + .map((item) => { + const weightText = item.effortWeight === null ? "unsized" : `effort weight ${item.effortWeight}`; + const additionalBlockers = item.additionalBlockers.length + ? `additional unresolved blockers: ${item.additionalBlockers.map((ref) => `${esc(ref)}`).join(", ")}` + : "no additional unresolved blockers"; + return `
    1. ${esc(item.ref)} (${weightText}) — ${additionalBlockers}
    2. `; + }) + .join(""); + return `
    3. ${esc(blocker.ref)} (${stateText}) — ${blocker.downstreamCount} distinct open downstream item${blocker.downstreamCount === 1 ? "" : "s"}; known effort weight ${blocker.knownEffortWeight}; ${blocker.unsizedCount} unsized contributor${blocker.unsizedCount === 1 ? "" : "s"}:
        ${downstream}
    4. `; + }) + .join("")}
    ` + : `

    No unresolved blocker has open downstream work in this epic.

    `; + + // SVG: hierarchy edges solid grey, dependency edges dashed amber — + // distinct by dash and color, and named in the legend text. + const pos = new Map(g.nodes.map((n) => [n.ref, n])); + const X = (depth: number) => 16 + depth * 180; + const Y = (row: number) => 16 + row * 26; + const width = X(g.maxDepth) + 340; + const height = g.nodes.length ? Y(g.nodes.length - 1) + 16 : 32; + // Dependency edges carry an arrowhead marker pointing at the blocker + // (the `to` node): hierarchy depth alone does not show which sibling + // blocks which (Codex round-2 on #3973). The marker id is per-epic -- + // several epic sections share one page, and duplicate ids would make + // every edge reference the first section's marker. + const depMarkerId = `dep-arrow-${epicGraphAnchor(g.epic.ref)}`; + const depDefs = g.edges.some((e) => e.type === "dependency") + ? `` + : ""; + const edgeLines = g.edges + .map((e) => { + const a = pos.get(e.from)!; + const b = pos.get(e.to)!; + return e.type === "dependency" + ? `` + : ``; + }) + .join(""); + const nodeShapes = g.nodes + .map((n) => { + const label = n.title + ? `#${n.number} ${n.title.length > 34 ? `${n.title.slice(0, 33)}…` : n.title}` + : `${n.ref} (outside this pool)`; + const x = X(n.depth); + const y = Y(n.row); + const shape = n.unresolved + ? `` + : n.epic + ? `` + : ``; + const nodeLabel = `${esc(label)}`; + return `${shape}${isValidRef(n.ref) ? `${nodeLabel}` : nodeLabel}`; + }) + .join(""); + const svg = g.edges.length + ? `
    ${depDefs}${edgeLines}${nodeShapes}

    Solid grey lines are sub-issue hierarchy (parent → child); dashed amber lines are dependency edges, with an arrowhead pointing at the blocker (item → blocker). Squares are epics; diamonds are references outside this pool whose status is unknown. Every node's state is also written as text in the list — color is never the only signal.

    ` + : `

    Not yet graphed: this epic's items carry no parent / blocked-by edges yet, so there is no graph to draw. The items are listed below.

    `; + + const listHtml = `
      ${g.nodes + .map((n) => { + const stateText = n.unresolved + ? "not in this pool / status unknown — unresolved" + : `issue ${esc(n.state ?? "unknown")}`; + const blockedBy = n.blockers.length + ? `blocked by: ${n.blockers.map((b) => `${poolRefLink(b)}${unresolvedOf(b) ? " (unresolved)" : " (resolved)"}`).join(", ")}` + : "blocked by: none observed"; + const blocks = n.dependents.length + ? `blocks: ${n.dependents.map(poolRefLink).join(", ")}` + : "blocks: none observed"; + const name = n.title ? `${esc(n.title)}` : "(outside this pool — no title in this feed)"; + const nodeRef = isValidRef(n.ref) ? `${esc(n.ref)}` : esc(n.ref); + const actions = isValidRef(n.ref) ? graphNodeActionsHtml(n.ref, actionContext) : ""; + return `
    • ${nodeRef} ${name} — ${stateText}; ${blockedBy}; ${blocks}${actions}
    • `; + }) + .join("")}
    `; + + return `
    ${heading}${summary}${cycleGroupsHtml}${edgeDiagnosticsHtml}${truncatedHtml}
    ${svg}
    Primary ranking — blockers by downstream open work

    Each open epic item is counted once per blocker across its transitive blockedBy ancestry. This measures downstream reach, not a promise that every item is immediately unblocked. Current additional unresolved blockers are listed per item; unsized contributors count separately from known effort weight. The longest dependency chain remains a separate diagnostic.

    ${rankedBlockersHtml}
    Open items by their worst blocker's downstream reach
    ${rankedHtml}
    All items — dependency list
    ${listHtml}
    `; +} + +/** The Path to Phase 12 panel (#9922): #1235's ordered steps, parsed + * from its body snapshot and joined to live GitHub item state and to + * queue state from the fleet-queue collector (#9920). A stale or + * missing body snapshot renders the warning INSTEAD of the steps — a + * silently old step list is the defect #1239's rules name. A stale + * queue snapshot still renders, but behind its own warning: the step + * list is the panel's spine, the task states are the perishable part. */ +export function phase12PanelHtml( + snapshot: Phase12Snapshot | null, + items: Map, + queue: QueueSnapshot | null = null, +): string { + const head = `

    Path to Phase 12 — live from #1235

    `; + if (!snapshot) { + return `${head}`; + } + const queueSegment = + queue === null + ? "queue state unavailable in the current source" + : !queue.available + ? "queue read failed — per-step task state withheld" + : `queue state from the fleet-queue collector, fetched ${esc(new Date(queue.fetchedAt).toISOString())}`; + const sourceLine = `

    Source: developing-today/code#1235 body, fetched ${esc(snapshot.fetchedAt)} · issue updated ${esc(snapshot.issueUpdatedAt)} · per-step state is live GitHub state; ${queueSegment}.

    `; + if (phase12IsStale(snapshot)) { + return `${head}${sourceLine}`; + } + const steps = joinPhase12Steps(parsePhase12Steps(snapshot.body), items, queue); + if (!steps.length) { + return `${head}${sourceLine}`; + } + const queueStale = + queue !== null && queue.available && queue.stale + ? `` + : ""; + const queueBadge = (s: Phase12StepState): string => { + if (queue === null || !queue.available) return ""; + const [task, ...earlier] = s.queueTasks; + if (!task) return ` no queue task`; + const cls = + task.status === "claimed" + ? "implementing" + : task.status === "done" || task.status === "completed" + ? "merged" + : task.status === "blocked" || task.status === "dep_blocked" + ? "closed" + : ""; + const bits = [`task ${task.id}`]; + if (task.lane) bits.push(`lane ${task.lane}`); + if (task.progressStage) bits.push(task.progressStage); + const more = earlier.length + ? ` (+${earlier.length} earlier task${earlier.length === 1 ? "" : "s"})` + : ""; + return ` queue: ${esc(task.status)} ${esc(bits.join(" · "))}${more}`; + }; + const rows = steps + .map((s) => { + const stateBadge = + s.liveState === null + ? `not resolved in the current source` + : `issue ${esc(s.liveState)}`; + const box = s.checked ? "☑" : "☐"; + const done = s.doneNote ? `
    ${esc(s.doneNote)}` : ""; + return `
    ${box} ${esc(s.label)} — #${s.issueNumber} ${esc(s.liveTitle ?? s.title)}
    ${stateBadge}${queueBadge(s)}${done}
    `; + }) + .join(""); + return `${head}${sourceLine}${queueStale}${rows}`; +} + +/** The Phase tracker panel (#9923): per-phase validation state for + * Phases 0-13, derived live from the items source (the four #796 + * validation audits, #1075-#1078, already in the id project's tracked + * refs). No hand-maintained values: a reopened audit or a new open + * follow-up changes the panel without an edit. Phase 12 also shows + * F-item progress counted from #1235's ordered step list, and Phases + * 11 and 13 count the F-item mapping table in planning/roadmaps/id.md + * (the source of record, #9923 step 3) when the source carries it; + * Phases 0-10 have no F-item numbering in their plans, so they state + * that gap instead of showing a fabricated percentage. */ +export function phaseTrackerPanelHtml( + items: Map, + phase12: Phase12Snapshot | null = null, + phaseMapping: PhaseMappingSnapshot | null = null, +): string { + const umbrellaUrl = `https://github.com/${PHASE_TRACKER_REPO}/issues/${PHASE_TRACKER_UMBRELLA}`; + const head = `

    Phase tracker — validation by phase, live from #${PHASE_TRACKER_UMBRELLA}

    `; + const progress = derivePhase12Progress(phase12, items); + const mappedProgress = phaseMapping ? deriveMappedProgress(phaseMapping.entries, items) : null; + const sourceLine = `

    Source: the validation audits #1075–#1078 under umbrella #${PHASE_TRACKER_UMBRELLA}, resolved from the same live GitHub items as the tracked-issues table above (the page provenance stamp applies). Phase 12 progress counts the ordered steps in #1235 against live issue state${phase12 ? ` (body fetched ${esc(phase12.fetchedAt)})` : ""}; ${phaseMapping ? `Phases 11 and 13 progress counts the F-item mapping table in planning/roadmaps/id.md (read ${esc(phaseMapping.fetchedAt)}) against live item state; ` : ""}Phases 0–10 have no F-item numbering in their plans, so no percentage is shown for them — the gap is stated rather than a number invented.

    `; + const rows = derivePhaseValidation(items) + .map((r) => { + const badge = + r.state === "validated" + ? `validated — audit closed` + : r.state === "validation-open" + ? `validation open — audit open` + : r.state === "unresolved" + ? `audit not resolved in the current source` + : `no validation audit`; + const audit = + r.auditIssue === null + ? `—` + : `#${r.auditIssue}${r.auditTitle ? ` ${esc(r.auditTitle)}` : ""}`; + const followUps = r.openFollowUps.length + ? r.openFollowUps.map((f) => `#${f.issueNumber}`).join(" ") + : `—`; + const mapped = mappedProgress?.get(r.phase); + const progressCell = + r.phase === 12 + ? progress + ? `${progress.done}/${progress.total} steps done (${progress.percent}%)
    ${progress.open} open${progress.unresolved ? ` · ${progress.unresolved} not resolved in the current source` : ""} — from #1235` + : `withheld — #1235 feed unavailable or stale` + : mapped + ? `${mapped.done}/${mapped.total} items done (${mapped.percent}%)
    ${mapped.open} open${mapped.unresolved ? ` · ${mapped.unresolved} not resolved in the current source` : ""} — from the F-item mapping in planning/roadmaps/id.md` + : r.phase <= 10 + ? `not derived — this phase's plan has no F-item numbering` + : `not derived — F-item mapping unavailable in the current source`; + return `Phase ${r.phase}${badge}${audit}${followUps}${progressCell}`; + }) + .join(""); + return `${head}${sourceLine}
    ${rows}
    Validation state per id-program phase, derived from live audit issue state
    PhaseValidationAuditOpen follow-upsProgress
    `; +} + +/** The Build health panel (#9924): current CI lane states + the id + * E2E nightly trend, projected from the Actions-API snapshot. A stale + * or missing snapshot renders the warning INSTEAD of lane states — + * silently old CI state is the defect #1239's rules name. A lane whose + * read failed renders unavailable; a failing nightly run keeps its + * link, which is the point of the trend. */ +export function buildHealthPanelHtml(snapshot: BuildHealthSnapshot | null): string { + const head = `

    Build health — live from the GitHub Actions API

    `; + if (!snapshot) { + return `${head}`; + } + const sourceLine = `

    Source: GitHub Actions API for ${esc(BUILD_HEALTH_REPO)}, fetched ${esc(snapshot.fetchedAt)}.

    `; + if (buildHealthIsStale(snapshot)) { + return `${head}${sourceLine}`; + } + const runBadge = (status: string, conclusion: string | null): string => { + if (status !== "completed") return `${esc(status)}`; + if (conclusion === "success") return `success`; + if (conclusion === "failure") return `failure`; + return `${esc(conclusion ?? "completed")}`; + }; + const laneCards = snapshot.lanes + .map((laneRuns) => { + if (laneRuns.error) { + return `
    ${esc(laneRuns.lane.label)}
    unavailable
    Actions read failed: ${esc(laneRuns.error)}
    `; + } + const proj = projectLane(laneRuns); + if (!proj.latest) { + return `
    ${esc(laneRuns.lane.label)}
    no runs reported
    `; + } + const history = proj.history + .map( + (r) => + `${r.conclusion === "success" ? "✓" : r.conclusion === "failure" ? "✗" : "·"}`, + ) + .join(" "); + return `
    ${esc(laneRuns.lane.label)}
    ${runBadge(proj.latest.status, proj.latest.conclusion)} latest: ${esc(proj.latest.createdAt)} (${esc(proj.latest.event)})${history ? `
    recent completed: ${history}` : ""}
    `; + }) + .join(""); + let nightlyHtml: string; + if (snapshot.nightly.error) { + nightlyHtml = `
    ${esc(snapshot.nightly.lane.label)} — nightly trend
    unavailable
    Actions read failed: ${esc(snapshot.nightly.error)}
    `; + } else { + const trend = projectNightlyTrend(snapshot.nightly); + nightlyHtml = trend.length + ? `
    ${esc(snapshot.nightly.lane.label)} — nightly trend (oldest → newest)
    ${trend + .map( + (r) => + `${r.conclusion === "success" ? "✓" : r.conclusion === "failure" ? "✗" : "·"} ${esc(r.createdAt.slice(0, 10))}`, + ) + .join(" · ")}
    ` + : `
    ${esc(snapshot.nightly.lane.label)} — nightly trend
    no completed runs reported
    `; + } + return `${head}${sourceLine}${laneCards}${nightlyHtml}`; +} + +/** The Phase 12 readiness panel (#9926): F12.1–F12.18 with design + * state (from #534's checklist), live issue state, and PR state + * (timeline cross-references). The F-item list is parsed from + * #1235's body — never hand-typed here. A stale snapshot withholds + * the rows behind the warning; missing sub-feeds render their + * column as unavailable instead of inventing a state. */ +export function f12ReadinessPanelHtml( + phase12: Phase12Snapshot | null, + design: Phase12Snapshot | null, + prRefs: Map | null, + items: Map, +): string { + const head = `

    Phase 12 readiness — F12.1–F12.18, live

    `; + if (!phase12) { + return `${head}`; + } + const sourceLine = `

    Sources: F-item list + order from developing-today/code#1235 (fetched ${esc(phase12.fetchedAt)}); design state from #534${design ? ` (fetched ${esc(design.fetchedAt)})` : " (feed unavailable — design column withheld)"}; issue state is live GitHub state; PR state from issue-timeline cross-references${prRefs ? "" : " (timeline read unavailable — PR column withheld)"}.

    `; + if (phase12IsStale(phase12) || (design !== null && phase12IsStale(design))) { + return `${head}${sourceLine}`; + } + const fItems = parseF12Items(phase12.body); + if (!fItems.length) { + return `${head}${sourceLine}`; + } + const designs = design ? parseF12Designs(design.body) : new Map(); + const rows = projectF12Readiness(fItems, designs, items, prRefs ?? new Map()) + .map((r) => { + const issueBadge = + r.issueState === null + ? `issue not resolved in the current source` + : `issue ${esc(r.issueState)}`; + const designBadge = !design + ? `design feed unavailable` + : r.design === null + ? `no design entry in #534` + : r.design.done + ? `design ${esc(r.design.designId)} done` + : `design ${esc(r.design.designId)} pending`; + const prBadge = !prRefs + ? `PR read unavailable` + : r.prs.length + ? r.prs + .map( + (p) => + `PR #${p.number} ${esc(p.state)}`, + ) + .join(" ") + : `no cross-referenced PR`; + return `
    ${esc(r.f)} — #${r.issueNumber} ${esc(r.title ?? "")}
    ${designBadge} ${issueBadge} ${prBadge}
    `; + }) + .join(""); + return `${head}${sourceLine}${rows}`; +} + +export function queuePanelHtml(snapshot: QueueSnapshot | null): string { + const head = `

    Queue & fleet \u2014 live from the fleet queue broker

    `; + if (!snapshot) { + return `${head}`; + } + const fetchedIso = new Date(snapshot.fetchedAt).toISOString(); + const sourceLine = `

    Source: queue-broker /health + /list (read-only), fetched ${esc(fetchedIso)}.

    `; + if (!snapshot.available || snapshot.stale) { + const why = snapshot.errors.length ? ` Last read error: ${esc(snapshot.errors[0])}.` : ""; + return `${head}${sourceLine}`; + } + const age = (ms: number | null): string => { + if (ms === null) return "\u2014"; + const mins = Math.floor(ms / 60_000); + if (mins < 60) return `${mins}m`; + const hours = Math.floor(mins / 60); + if (hours < 48) return `${hours}h ${mins % 60}m`; + return `${Math.floor(hours / 24)}d ${hours % 24}h`; + }; + const streamRows = snapshot.queues + .map( + (q) => + `${esc(q.queue)}${q.queued}${q.claimed}${q.parked}${q.blocked}${q.done}${esc(age(q.oldestQueuedAgeMs))}${q.terminalEvents24h} / ${q.terminalEvents7d}`, + ) + .join(""); + const streams = `${streamRows}
    Queue streams
    Queue streamQueuedClaimedParkedBlockedDoneOldest queuedTerminal 24h / 7d
    `; + const idItems = snapshot.tasks.filter( + (task) => + task.repo === "developing-today/code" && + task.issue !== null && + (task.status === "claimed" || task.status === "parked"), + ); + const itemRows = idItems + .slice(0, 50) + .map((task) => { + const who = [task.worker, task.lane].filter(Boolean).join(" / ") || "\u2014"; + const stage = task.progressStage ? esc(task.progressStage) : "\u2014"; + return `${task.id}#${task.issue} ${esc(task.title)}${esc(task.status)}${esc(who)}${stage}`; + }) + .join(""); + const items = idItems.length + ? `

    Claimed & parked id items (${idItems.length})

    ${itemRows}
    Claimed & parked id items
    TaskIssueStatusWorker / laneStage
    ` + : `

    Claimed & parked id items

    None in the current snapshot.

    `; + return `${head}${sourceLine}${streams}${items}`; +} + +export function renderProgramProject( + detail: ProjectDetail, + items: Map, + provenance: Provenance, + provDetail?: ProvenanceDetail, + epicPool: ProjectPoolItem[] = detail.poolItems, + phase12?: Phase12Snapshot | null, + buildHealth?: BuildHealthSnapshot | null, + f12?: { design: Phase12Snapshot | null; prRefs: Map | null } | null, + queueSnap?: QueueSnapshot | null, + phaseMapping?: PhaseMappingSnapshot | null, + graphActions?: EpicGraphActionContext, +): string { + const { config } = detail; + const linkBits: string[] = []; + if (config.homeDoc) { + linkBits.push( + `Home doc: ${esc(config.homeDoc.path)} (${esc(config.homeDoc.repo)})`, + ); + } else { + linkBits.push(`No home doc configured for this project yet.`); + } + if (detail.doc?.latestStatus) { + const status = detail.doc.latestStatus; + linkBits.push( + `Latest status: ${esc(status.title ?? status.dir)} (${esc(status.timestamp)} \u2014 newest doc/ status record, derived at request time)`, + ); + } else if (detail.doc) { + linkBits.push( + `No status record under doc/ for this project yet \u2014 checked the code checkout at ${esc(detail.doc.fetchedAt)}.`, + ); + } else if (config.statusReport) { + linkBits.push(`Status report: ${esc(config.statusReport.label)}`); + } else { + linkBits.push(`No status report yet for this project.`); + } + if (detail.doc?.description) { + linkBits.push( + `Description derived from ${esc(detail.doc.roadmapPath)} (read at request time)`, + ); + } else if (detail.doc) { + linkBits.push( + `No prose description found in ${esc(detail.doc.roadmapPath)} \u2014 the registry intro is shown instead.`, + ); + } + for (const l of config.dashboardLinks ?? []) { + linkBits.push( + `${esc(l.label)}${l.note ? ` (${esc(l.note)})` : ""}`, + ); + } + linkBits.push(`JSON twin`); + + const archHtml = config.architecture?.length + ? `

    What this is — architecture

    ${programEntries(config.architecture, items)}` + : ""; + + let poolHtml: string; + if (config.poolArea === null) { + poolHtml = ``; + } else if (!detail.poolItems.length) { + poolHtml = ``; + } else { + const shown = detail.poolItems.slice(0, POOL_ITEM_CAP); + const cards = shown + .map((p) => { + const statusBadge = p.status + ? `${esc(p.status)}` + : `no status`; + const meta = [ + p.horizon ? `${esc(p.horizon)}` : "", + p.kind ? `${esc(p.kind)}` : "", + `issue ${esc(p.state)}`, + ].join(" "); + return `
    ${esc(p.title)}
    ${statusBadge} ${meta}
    ${esc(p.repo)}#${p.number} · Project item${p.updatedAt ? ` · updated ${fmtDate(p.updatedAt)}` : ""}
    `; + }) + .join(""); + const more = + detail.poolItems.length > POOL_ITEM_CAP + ? `

    Showing ${POOL_ITEM_CAP} of ${detail.poolItems.length} — the full set is on /projects.

    ` + : ""; + const allW = summarizeWeights(detail.poolItems); + const epics = detail.poolItems.filter((p) => p.kind === "Epic"); + const epicW = summarizeWeights(epics); + const epicRollups = buildEpicRollups(epicPool); + const epicRows = epics + .map((p) => { + const w = effortWeight(p.labels); + const epicRollup = epicRollups.get(p.ref); + const rollup = epicRollup ? epicRollupHtml(epicRollup) : ""; + return `
    ${esc(p.title)}
    weight: ${w === null ? "unsized" : w} · issue ${esc(p.state)}${p.status ? ` · status: ${esc(p.status)}` : ""} · ${esc(p.repo)}#${p.number}${rollup}
    `; + }) + .join(""); + const epicHtml = epics.length + ? `

    Epics — weighted progress

    ${esc(weightedLine(epicW))}

    ${epicRows}` + : ""; + poolHtml = `

    ${esc(weightedLine(allW))}
    ${esc(handsLine(allW))}
    ${detail.poolItems.length} items with Area ${esc(config.poolArea)} — by status: ${countList(detail.poolByStatus)}. Full pool view: /projects?area=${esc(config.poolArea)}.

    ${epicHtml}${poolGraphHtml(detail.poolItems, allW)}${epicGraphSectionHtml(epicPool, detail.poolItems, graphActions)}${cards}${more}`; + } + + let roadmapHtml: string; + if (config.roadmapArea === null) { + roadmapHtml = ``; + } else if (!detail.roadmapRows.length) { + roadmapHtml = ``; + } else { + const rollups = buildEpicRollups(epicPool); + const rowRollups = new Map(); + for (const row of detail.roadmapRows) { + const epic = row.links + .map((link) => epicPool.find((item) => item.ref === link.ref && item.kind === "Epic")) + .find(Boolean); + const rollup = epic ? rollups.get(epic.ref) : undefined; + if (rollup) rowRollups.set(row.subject, rollup); + } + roadmapHtml = `

    ${detail.roadmapRows.length} row${detail.roadmapRows.length === 1 ? "" : "s"} with area ${esc(config.roadmapArea)} in Grist's Program roadmap. Timeline lanes and drill-downs use the shared roadmap renderer; epic rollups are per matched row.

    ${timelineTable(buildTimeline(detail.roadmapRows), items, undefined, undefined, undefined, undefined, undefined, undefined, { epicRollups: rowRollups, showRowNotes: true })}`; + } + + const repoCardsHtml = detail.repoCards.length + ? `

    Per-repo cards

    +

    One card per working repo. Open-issue counts are a dated GitHub-search snapshot (date on each card), never a live claim; the pool items and roadmap rows are split live from the same sections above, by repo.

    ${detail.repoCards + .map(({ card, poolItems, roadmapRows, tracked }) => { + const refs = tracked + .map( + ({ ref, item }) => + `${esc(ref)}${item ? ` ${esc(item.state)}` : ""}`, + ) + .join(" "); + return `
    ${esc(card.repo)}
    ${esc(card.role)}
    Open issues (GitHub search, ${esc(card.openIssuesAsOf)}): ${card.openIssues} · fleet pool items in this repo: ${poolItems.length} · roadmap rows: ${roadmapRows.length}${refs ? `
    ${refs}` : ""}
    `; + }) + .join("")}` + : ""; + + const sweepHealthHtml = config.sweepHealth?.length + ? `

    Sweep health — published fleet state

    +

    Built only from already-published fleet data — the orchestration section this aggregator serves and the fleet's tracked issues. No new data pipeline feeds this section.

    ${programEntries(config.sweepHealth, items)}` + : ""; + + const phaseTrackerHtml = + config.id === "id" ? phaseTrackerPanelHtml(items, phase12 ?? null, phaseMapping ?? null) : ""; + const phase12Html = + config.id === "id" && phase12 !== undefined ? phase12PanelHtml(phase12, items, queueSnap ?? null) : ""; + const buildHealthHtml = config.id === "id" && buildHealth !== undefined ? buildHealthPanelHtml(buildHealth) : ""; + const f12Html = + config.id === "id" && f12 !== undefined + ? f12ReadinessPanelHtml(phase12 ?? null, f12?.design ?? null, f12?.prRefs ?? null, items) + : ""; + const queueHtml = config.id === "id" && queueSnap !== undefined ? queuePanelHtml(queueSnap) : ""; + + const ed = config.editorial; + const editorialHtml = ed + ? `${ed.done.length ? `

    What's built

    ${programEntries(ed.done, items)}` : ""}${ed.next.length ? `

    What's next

    ${programEntries(ed.next, items)}` : ""}${ed.longTerm.length ? `

    Long-term roadmap

    ${programEntries(ed.longTerm, items)}` : ""}${ed.gaps.length ? `

    Known gaps

    ${programEntries(ed.gaps, items)}` : ""}` + : ""; + + const body = `

    ${esc(config.title)}

    +

    ${esc(detail.doc?.description ?? config.intro)}

    +

    ${linkBits.join(" · ")}

    +

    ← all projects

    +${archHtml} +

    Live status — tracked issues

    +

    Resolved at request time from the same Source as every other view. A ref the current source cannot resolve says so — never an invented state.

    +${trackedTable(detail.tracked)} +

    Project pool — live

    +${poolHtml} +

    Roadmap — live

    +${roadmapHtml} +${repoCardsHtml} +${sweepHealthHtml} +${phaseTrackerHtml}${phase12Html}${buildHealthHtml}${f12Html}${queueHtml}${editorialHtml}`; + return layout( + config.title, + body, + provenance, + "/program", + graphActions?.identities ? ACTION_SCRIPT : "", + provDetail ? freshnessChips(provDetail, ["orchestration", "items", "roadmap"]) : "", + ); +} diff --git a/pm-stack/aggregator/src/render-quota.ts b/pm-stack/aggregator/src/render-quota.ts new file mode 100644 index 0000000000..53e610f56b --- /dev/null +++ b/pm-stack/aggregator/src/render-quota.ts @@ -0,0 +1,720 @@ +// render.ts split (#13051): quota view, usage/billing cards, service detail and history charts. +// render.ts re-exports every public name from here; callers keep importing "./render.ts". + +import { analyticsSectionHtml } from "./quota-analytics-view.ts"; +import { freshness, projectPace, resetMarkers, sourceOf, STATE_LABELS, windowPercent } from "./derive.ts"; +import type { DashAction } from "./actions.ts"; +import { cardState } from "./card-state.ts"; +import type { CommentKindCounts } from "./comments.ts"; +import { providerDisplayNames } from "./provider-display.ts"; +import { + type ChargeRow, + type DashComment, + type PaygLine, + type Provenance, + type ProvenanceDetail, + type QuotaView, + type SaasService, + type SnapshotRecord, + type TieredEntry, + type TierItem, + type UsageMetric, + type UsageView, + SAAS_GROUP_LABELS, + SESSION_SOURCE_LABELS, + countedEstimate, + isValidRef, + refUrl, +} from "./model.ts"; +import type { AuthorIdentity } from "./registry.ts"; + +import { + esc, + fmtDate, + fmtCentral, + freshnessChips, + layout, + sessionObjectRef, + tierItemObjectRef, + commentBadge, + type CommentFormOpts, + actionBadgesHtml, + cardDomId, + actionHistoryHtml, + cardCommentHtml, + triageActionsHtml, + whyUserBadge, + needsUserBodyHtml, + needsUserFormsHtml, + sessionActionsHtml, +} from "./render-core.ts"; + +// --- Quota view (#851) + Usage & billing hub (design 2026-10-25) ----------- + +const SOURCE_CLASS_LABELS: Record = { + api: "API read", + console: "console read", + manual: "manual read", + estimate: "estimate", + invoice: "invoice", +}; + +export function fmtMetricValue(v: number | null, unit: string): string { + if (v == null) return "not measured"; + if (unit === "usd") return `$${v.toFixed(2)}`; + if (unit === "cny") return `¥${v.toFixed(2)}`; + if (unit === "gb") return `${v} GB`; + if (unit === "pct") return `${v}%`; + return v.toLocaleString(); +} + +/** The freshness stamp every hub card carries (§1.1): measured-at + source + age. */ +export function freshnessStamp(measuredAt: string | null, sourceClass: string, cadenceDays: number): string { + const f = freshness(measuredAt, cadenceDays); + const cls = SOURCE_CLASS_LABELS[sourceClass] ?? sourceClass; + if (!measuredAt) + return `no dated read ${esc(cls)} · ${esc("never measured")}`; + const age = f.ageDays == null ? "" : f.ageDays === 0 ? " · today" : ` · ${f.ageDays}d ago`; + const stale = f.stale ? ` stale — as of ${esc(measuredAt.slice(0, 10))}` : ""; + return `measured ${esc(measuredAt.slice(0, 10))}${age} · ${esc(cls)}${stale}`; +} + +function metricRow(m: UsageMetric): string { + const pct = m.percent; + const meter = + pct != null + ? ` ${pct.toFixed(0)}% · ` + : ""; + const limit = m.limit == null ? "" : ` / ${fmtMetricValue(m.limit, m.unit)}`; + return `
    ${esc(m.label)}: ${meter}${fmtMetricValue(m.used, m.unit)}${limit}${m.note ? ` — ${esc(m.note)}` : ""}
    `; +} + +function attentionStripHtml(usage: UsageView): string { + if (!usage.attention.length) { + return `
    Needs attention — no quota or credential alerts. (Bubble rules: any metric over 80% of its limit, or projected unbilled PAYG over $5.)
    `; + } + const rows = usage.attention + .map( + (f) => + `
    ${esc(f.label)} — ${esc(f.detail)} details
    `, + ) + .join(""); + return `

    Needs attention

    ${rows}`; +} + +/** + * The DeepSeek PAYG reserve's balance, from the snapshot store (#1052): + * the newest unit "cny" record. Shown in ¥ with its own measured-at — + * the yuan figure as read, never converted to dollars. + */ +function paygBalanceHtml(usage: UsageView): string { + const recs = (usage.history["deepseek"] ?? []).filter((r) => r.unit === "cny" && typeof r.value === "number"); + if (!recs.length) return ""; + const last = recs[recs.length - 1]; + return `
    DeepSeek PAYG reserve balance: ¥${(last.value as number).toFixed(2)}
    reserve only — never a routine route · measured ${esc(last.ts.slice(0, 10))} · ${esc(last.observedBy)}
    `; +} + +function paygCardHtml(usage: UsageView): string { + const balance = paygBalanceHtml(usage); + const balanceBlock = balance ? `
    ${balance}
    ` : ""; + if (!usage.payg.length) { + return `
    PAYG dollars
    pay-as-you-go agent spend
    No metered spill recorded in local records.
    ${balanceBlock}
    `; + } + const lines = usage.payg + .map((l: PaygLine) => { + const figures = + l.settledUsd != null + ? `$${l.settledUsd.toFixed(2)} ${l.settledSource === "invoice" ? "invoiced" : "settled"}${ + l.estimate + ? ` · estimates $${l.estimate.low.toFixed(2)}–$${l.estimate.high.toFixed(2)}` + : l.accruedUsd != null + ? ` · $${l.accruedUsd.toFixed(2)} accrued` + : "" + }${l.settledVarianceUsd != null ? ` · variance ${l.settledVarianceUsd < 0 ? "-$" : "+$"}${Math.abs(l.settledVarianceUsd).toFixed(2)}` : ""} · $${(l.unbilledUsd ?? 0).toFixed(2)} unbilled` + : l.accruedUsd != null + ? `$${l.accruedUsd.toFixed(2)} accrued${l.collectedUsd != null ? ` · $${l.collectedUsd.toFixed(2)} collected` : ""} · $${(l.unbilledUsd ?? 0).toFixed(2)} unbilled` + : l.estimate + ? `counted $${countedEstimate(l.estimate).toFixed(2)} as used (1.2 × high) · estimate $${l.estimate.low.toFixed(2)}–$${l.estimate.high.toFixed(2)} ${esc(l.estimate.period)}` + : "not estimable from local records"; + const stale = l.staleEstimate + ? ` stale estimate — unreconciled >1 invoice cycle` + : ""; + return `
    ${esc(l.label)}${stale}: ${figures}
    ${esc(l.note)}
    ${freshnessStamp(l.measuredAt, l.sourceClass, 7)}
    `; + }) + .join(""); + const total = usage.payg.reduce((sum, l) => sum + (l.unbilledUsd ?? 0), 0); + return `
    PAYG dollars
    metered spill, counted per Decision 004 — estimates at 1.2 × high
    $${total.toFixed(2)} projected unbilled
    ${lines}${balanceBlock}
    `; +} + +function serviceCardHtml(svc: SaasService, history: SnapshotRecord[]): string { + const f = freshness(svc.measuredAt, svc.cadenceDays); + const highlights = svc.metrics.filter((m) => m.highlight); + const metrics = highlights.length + ? highlights.map(metricRow).join("") + : `
    ${esc(svc.usageNote ?? "No highlight metrics recorded.")}
    `; + const billed = svc.billedUsd != null ? `
    billed this period: $${svc.billedUsd.toFixed(2)}
    ` : ""; + const payg = svc.paygEstimate + ? `
    PAYG estimate: counted $${countedEstimate(svc.paygEstimate).toFixed(2)} (${esc(svc.paygEstimate.period)}; range $${svc.paygEstimate.low.toFixed(2)}–$${svc.paygEstimate.high.toFixed(2)} in detail)
    ` + : svc.paygNote + ? `
    PAYG: ${esc(svc.paygNote)}
    ` + : ""; + const conflict = svc.conflicts.length + ? ` conflict` + : ""; + const pace = paceLineHtml(svc.id, history); + const extractionGap = + svc.extractionHealth?.status === "gap" + ? ` extraction gap` + : ""; + return `
    ${esc(svc.name)}${svc.status !== "active" ? ` ${esc(svc.status)}` : ""}${conflict}${extractionGap}
    ${esc(svc.plan)}
    ${freshnessStamp(svc.measuredAt, svc.sourceClass, svc.cadenceDays)}${svc.nextDate ? `
    next: ${esc(svc.nextDate)}` : ""}
    ${metrics}${billed}${payg}${pace}
    `; +} + +function uninstrumentedServicesHtml(services: UsageView["uninstrumentedServices"]): string { + if (!services.length) return ""; + const rows = services + .map( + (svc) => + `${esc(svc.name)}${esc(svc.whatFor)}${esc(svc.status)}${esc(svc.checkedAt ?? "no check date recorded")}${esc(svc.overageBehavior)}${esc(svc.guardrailNotes)}`, + ) + .join(""); + return `

    Tracker services without instrumented quotas

    ${services.length} evaluated services — expand for tracker states and guardrails
    ${rows}
    Services in free-services-to-check.md
    ServiceWhat forTracker stateCheckedOverage behaviorGuardrail notes
    `; +} + +/** A one-line pace projection on a card, when the history supports one (§1.5). */ +function paceLineHtml(serviceId: string, history: SnapshotRecord[]): string { + const metricIds = [...new Set(history.filter((r) => r.unit === "pct").map((r) => r.metricId))]; + for (const metricId of metricIds) { + const pace = projectPace(history, metricId); + if (pace?.projectedExhaustionAt) { + return `
    pace (${esc(metricId)}): +${pace.slopePerDay} pts/day → projected to exhaust ${esc(pace.projectedExhaustionAt.slice(0, 10))}${pace.projectedPercentAtReset != null ? ` · ${pace.projectedPercentAtReset}% at reset` : ""}
    `; + } + } + return ""; +} + +function chargesStripHtml(usage: UsageView): string { + if (!usage.charges.length) { + return `

    Charges this period

    ${esc(usage.chargesNote ?? "No charge evidence in the local records yet — rows appear as Plaid/Gmail receipt evidence is recorded.")}
    `; + } + const rows = usage.charges + .map( + (c: ChargeRow) => + `${esc(c.at)}${esc(c.label)}$${c.amountUsd.toFixed(2)}${esc(c.method)}${esc(c.source)}`, + ) + .join(""); + const total = usage.charges.reduce((sum, c) => sum + c.amountUsd, 0); + return `

    Charges this period

    Evidence, not accounting — charges observed on cards/receipts in the local records (full balances stay in the finance tooling). Total observed: $${total.toFixed(2)}.

    ${rows}
    Charges this period
    DateChargeAmountMethodEvidence
    `; +} + +/** Lazy-refresh strip (#1171): a visible "refreshing" marker while a + * gatherer run is in flight, plus the manual refresh-now control. Both + * use the same trigger path; neither blocks the page on provider calls. */ +function quotaRefreshHtml(refresh?: import("./quota-refresh.ts").RefreshStatus, generatedAt?: string | null): string { + if (!refresh) return ""; + const marker = refresh.refreshing + ? `refreshing — the quota gatherer is running; reload for updated data` + : refresh.stale + ? `quota data is older than five minutes` + : ""; + // Manual refresh (#6125): the button POSTs the manual trigger route + // (POST /api/quota/refresh -> quotaRefresher.manual -> the deployed + // quota-gatherer.service, whose read is the single `opencode quota` + // source), then polls /api/quota.json until quota-current.json's + // generatedAt advances. Success is never faked: an advanced file whose + // gatherer reported failure, a failed request, or a poll window with + // no advance all surface as a failure message. The form remains the + // no-JS path (POST /quota/refresh, same manual trigger, 303 back). + return `
    ${marker || 'quota data is fresh'}
    +`; +} + +export function renderQuota( + view: QuotaView, + provenance: Provenance, + usage?: UsageView, + detail?: ProvenanceDetail, + /** Lazy-refresh state (#1171): renders the "refreshing" marker and the + * manual refresh-now control. Absent means no request was made. */ + refresh?: import("./quota-refresh.ts").RefreshStatus, + /** Analytics & projection model (2026-11-13): built by the server + * from the route ledger + snapshot store; absent/null renders no + * section (older callers and tests are unaffected). */ + analytics?: import("./analytics-store.ts").QuotaAnalytics | null, +): string { + // "-direct" display rule (#6125): judged over every provider name/id + // this surface renders — pool providers, pool ids, burn rows, the + // model-choice pool lists, and credential-lifecycle provider names. + // Display only; ids and keys below stay exactly as the view carries + // them. + const displayNames = providerDisplayNames([ + ...view.pools.map((p) => p.provider), + ...view.pools.map((p) => p.id), + ...(view.burn ?? []).map((b) => b.provider), + ...(view.burn ?? []).map((b) => b.pool), + ...(view.choices ? [...view.choices.hasHeadroom, ...view.choices.burnBeforeReset, ...view.choices.doNotStart] : []), + ...(view.credentialLifecycle ?? []).map((c) => c.providerName), + ]); + const display = (name: string) => displayNames.get(name) ?? name; + const credentialLifecycle = view.credentialLifecycle?.length + ? `

    Credential lifecycle

    ${view.credentialLifecycle + .map((credential) => { + const expiry = credential.expiresAt ? ` · expires ${fmtCentral(credential.expiresAt)}` : " · expiry unknown"; + const reason = credential.reason ? ` · ${esc(credential.reason)}` : ""; + const action = credential.userAction + ? ` · user action: ${esc(credential.userAction.title)}` + : ""; + return `
    ${esc(display(credential.providerName))} · ${esc(credential.label)} ${esc(credential.state)}${expiry}${reason}${action}
    `; + }) + .join("")}
    ` + : ""; + // #6671: provider-auth keeper problems render as their own card — + // a dying provider session (or a keeper that stopped reporting) + // must be visible on the board, not only in a state file. All-ok + // keepers render nothing here (no alert, no noise). + const providerAuthProblems = (view.providerAuth ?? []).filter((a) => a.reporting !== "ok"); + const providerAuthSection = providerAuthProblems.length + ? `

    Provider auth

    ${providerAuthProblems + .map((a) => { + const detail = + a.reporting === "attention" + ? `${esc(a.alert ?? a.status ?? "attention")}${a.alertSince ? ` · since ${fmtCentral(a.alertSince)}` : ""}${a.sessionExpiresAt ? ` · session expires ${fmtCentral(a.sessionExpiresAt)}` : ""}${a.lastGoodAt ? ` · last good ${fmtCentral(a.lastGoodAt)}` : ""}` + : a.reporting === "stale" + ? `keeper not reporting · last check ${fmtCentral(a.checkedAt)}` + : a.reporting === "invalid" + ? "keeper not reporting · state file invalid" + : "keeper not reporting · no state file"; + return `
    ${esc(a.provider)} ${esc(a.reporting)} ${detail}
    `; + }) + .join("")}
    ` + : ""; + const pools = view.pools + .map((p) => { + const windows = p.windows + .map((w) => { + const pct = windowPercent(w); + const used = w.unit === "usd" ? `$${w.used.toFixed(2)}` : w.used.toLocaleString(); + const limit = w.limit == null ? "∞" : w.unit === "usd" ? `$${w.limit.toFixed(2)}` : w.limit.toLocaleString(); + return `
    ${esc(w.name)}: ${pct.toFixed(0)}% · ${used}/${limit} ${esc(w.unit)} · resets ${fmtCentral(w.resetsAt)}
    `; + }) + .join(""); + const sessions = (p.activeSessions ?? []) + .map( + (s) => + `
    burning: ${esc(s.session)} (${esc(s.model)}) ${s.tokens.toLocaleString()} tok
    `, + ) + .join(""); + const credRows = (p.credentials ?? []) + .map((c) => { + const wins = c.windows.map((w) => `${esc(w.name)} ${windowPercent(w).toFixed(0)}%`).join(" \u00b7 "); + const state = + c.freshness.state === "ok" + ? "" + : ` \u00b7 ${esc(c.freshness.state)}${c.freshness.error ? ` \u00b7 ${esc(c.freshness.error)}` : ""}`; + return `
    credential ${esc(c.label)}: ${wins || esc(c.freshness.state)}${state}
    `; + }) + .join(""); + const fresh = p.freshness + ? `
    gatherer · ${esc(p.freshness.state)} · measured ${fmtCentral(p.freshness.measuredAt)} · ${esc(p.freshness.source)}${p.freshness.error ? ` · ${esc(p.freshness.error)}` : ""}
    ` + : ""; + const extractionGap = + p.extractionHealth?.status === "gap" + ? ` extraction gap` + : ""; + + return `
    ${esc(display(p.provider))}
    ${esc(p.plan)}
    ${esc(p.state)}${p.wallLiftsAt ? ` · lifts ${fmtCentral(p.wallLiftsAt)}` : ""}${extractionGap}${p.burnTokensPerMin ? ` ${p.burnTokensPerMin} tok/min` : ""}
    ${windows}${credRows}${sessions}${fresh}${p.note ? `
    ${esc(p.note)}
    ` : ""}
    `; + }) + .join(""); + const burn = view.burn + .map( + (b) => + `${esc(display(b.provider))}${esc(display(b.pool))}${fmtCentral(b.from)}${fmtCentral(b.to)}${b.tokens.toLocaleString()}`, + ) + .join(""); + const choices = (list: string[]) => (list.length ? list.map((id) => esc(display(id))).join(", ") : "—"); + const burnAndChoices = `

    Burn between resets

    ${burn || ''}
    Burn between resets
    ProviderPoolFromToTokens
    none
    +

    Model choice

    + + +
    Model choice rules
    RulePools
    Headroom for a new session${choices(view.choices.hasHeadroom)}
    Burn-it-before-reset (unused headroom)${choices(view.choices.burnBeforeReset)}
    Do not start a second session${choices(view.choices.doNotStart)}
    `; + if (!usage) { + return layout( + "Quota + throughput", + `

    Quota + throughput

    All pooled quotas, resets, and burn rates — all times Central (America/Chicago). Machine-first: the same data is at /api/quota.json.

    +${credentialLifecycle} +${providerAuthSection} +${quotaRefreshHtml(refresh, view.gatherer?.generatedAt ?? null)} +${view.gatherer ? `

    Gatherer tick: ${view.gatherer.tickAt ? fmtCentral(view.gatherer.tickAt) : "unknown"} · ${view.gatherer.ok ? "ok" : "failed"}${view.gatherer.tickAt && Date.now() - Date.parse(view.gatherer.tickAt) > 20 * 60_000 ? " · stale" : ""}${view.gatherer.durationMs != null ? ` · ${esc(view.gatherer.durationMs)} ms` : ""}${view.gatherer.error ? ` · ${esc(view.gatherer.error)}` : ""}

    ` : ""} +

    Pools

    ${pools} +${analytics ? analyticsSectionHtml(analytics, display) : ""} +${burnAndChoices}`, + provenance, + "/quota", + ); + } + const groupOrder: (keyof typeof SAAS_GROUP_LABELS)[] = [ + "database", + "object-storage", + "compute", + "dev-platform", + "domains", + "account-tooling", + ]; + const groups = groupOrder + .map((g) => { + const svcs = usage.services.filter((s) => s.group === g); + const cards = svcs.map((s) => serviceCardHtml(s, usage.history[s.id] ?? [])).join(""); + const domainsCard = + g === "domains" + ? usage.domains + ? `
    Domains
    Porkbun register — summary only; the full register lives on the DNS page
    renewal exposure: $${usage.domains.totalAnnualUsd.toFixed(2)}/yr across ${usage.domains.domainCount} domains
    next renewal: ${esc(usage.domains.nextRenewal ?? "—")}
    ` + : `
    Domains: the register has not reached the feed yet — see /dns.
    ` + : ""; + const subs = + g === "account-tooling" && usage.subscriptions.length + ? `
    Subscriptions (flat)
    renewal-only rows — no usage meter
    ${usage.subscriptions + .map( + (s) => + `
    ${esc(s.name)}: ${esc(s.plan)}${s.renewsAt ? ` · renews ${esc(s.renewsAt)}` : " · renewal date unknown"}
    `, + ) + .join("")}
    ` + : ""; + if (!cards && !domainsCard && !subs) return ""; + return `

    ${esc(SAAS_GROUP_LABELS[g])}

    ${cards}${domainsCard}${subs}
    `; + }) + .join(""); + return layout( + "Usage & billing", + `

    Usage & billing

    Token quotas, PAYG dollars, and SaaS usage vs limits — from dated local records; every card carries its measured-at stamp, and stale cards dim — all times Central (America/Chicago). Machine-first: /api/quota.json.

    +${attentionStripHtml(usage)} +${credentialLifecycle} +${providerAuthSection} +${quotaRefreshHtml(refresh, view.gatherer?.generatedAt ?? null)} +${view.gatherer ? `

    Gatherer tick: ${view.gatherer.tickAt ? fmtCentral(view.gatherer.tickAt) : "unknown"} · ${view.gatherer.ok ? "ok" : "failed"}${view.gatherer.tickAt && Date.now() - Date.parse(view.gatherer.tickAt) > 20 * 60_000 ? " · stale" : ""}${view.gatherer.durationMs != null ? ` · ${esc(view.gatherer.durationMs)} ms` : ""}${view.gatherer.error ? ` · ${esc(view.gatherer.error)}` : ""}

    ` : ""} +

    Token quotas

    ${pools} +${analytics ? analyticsSectionHtml(analytics, display) : ""} +${paygCardHtml(usage)} +

    SaaS & services

    ${groups || '

    No services extracted yet.

    '}${uninstrumentedServicesHtml(usage.uninstrumentedServices ?? [])} +${chargesStripHtml(usage)} +

    Sources

    Research records behind the cards on this page that carry provenance — all in ~/workspace/ai-subscriptions/:
    · evidence baseline: evidence-and-interpretation-baseline-2026-10-20.md (dated official pricing wording + interpretation notes)
    · master tracker: the tracker behind quota-view.md Part (b) — each card with a tracker row cites its Summary (b) row and service section
    · candidate evaluations: free-services-to-check.md
    Per-service provenance (tracker row or its absence, baseline, quota-view section) is on each service's detail page.
    +${burnAndChoices}`, + provenance, + "/quota", + "", + detail ? freshnessChips(detail, ["quota", "usage"]) : "", + ); +} + +// --- Service detail view (hub v1.1, §1.5) ------------------------------------- + +/** An inline SVG history chart for one metric, with reset markers (§4). */ +export function historyChartHtml(records: SnapshotRecord[], metricId: string): string { + const recs = records + .filter((r) => r.metricId === metricId && typeof r.value === "number") + .sort((a, b) => a.ts.localeCompare(b.ts)) as (SnapshotRecord & { value: number })[]; + if (!recs.length) return ""; + const W = 640; + const H = 130; + const PAD = 28; + const t0 = Date.parse(recs[0].ts); + const t1 = Math.max(Date.parse(recs[recs.length - 1].ts), t0 + 1); + const vmax = Math.max(...recs.map((r) => r.value), ...(recs.map((r) => r.limit ?? 0) as number[]), 1) * 1.1; + const x = (ts: string) => PAD + ((Date.parse(ts) - t0) / (t1 - t0)) * (W - PAD - 8); + const y = (v: number) => H - 18 - (v / vmax) * (H - 34); + const markers = resetMarkers(records, metricId) + .filter((m) => Date.parse(m.ts) >= t0 && Date.parse(m.ts) <= t1) + .map( + (m) => + `reset ${esc(m.resetsAt.slice(0, 10))}`, + ) + .join(""); + const limitLine = recs.find((r) => r.limit != null) + ? `` + : ""; + const points = recs + .map( + (r) => + `${esc(r.ts.slice(0, 10))}: ${r.value} ${esc(r.unit)} (${esc(r.source)})`, + ) + .join(""); + const line = recs.map((r, i) => `${i === 0 ? "M" : "L"}${x(r.ts).toFixed(1)},${y(r.value).toFixed(1)}`).join(" "); + const first = recs[0]; + const last = recs[recs.length - 1]; + return `
    ${esc(metricId)} · ${recs.length} snapshot${recs.length === 1 ? "" : "s"} · ${esc(first.ts.slice(0, 10))} → ${esc(last.ts.slice(0, 10))} · dashed amber = window reset, red = limit
    ${markers}${limitLine}${points}
    `; +} + +function snapshotFreshnessStamp(history: SnapshotRecord[], cadenceDays: number, now: Date): string { + const latest = history.reduce( + (current, record) => (!current || Date.parse(record.ts) > Date.parse(current.ts) ? record : current), + null, + ); + if (!latest) { + return '

    No snapshot writer has landed a record for this service yet. The feed-ingest tick is the normal landing path; the §4 backfill is a one-shot recovery, not normal history startup.

    '; + } + const measuredAt = latest.ts.slice(0, 10); + const f = freshness(measuredAt, cadenceDays, now); + const age = f.ageDays == null ? " · age unknown" : f.ageDays === 0 ? " · today" : ` · ${f.ageDays}d ago`; + const state = f.stale ? 'stale' : 'within cadence'; + return `

    Latest stored snapshot: ${age} · ${cadenceDays}-day expected cadence · ${state}

    `; +} + +export function renderServiceDetail( + svc: SaasService, + history: SnapshotRecord[], + provenance: Provenance, + detail?: ProvenanceDetail, + now = new Date(), +): string { + const f = freshness(svc.measuredAt, svc.cadenceDays); + const metricRows = svc.metrics.length + ? svc.metrics + .map( + (m) => + `${esc(m.label)}${m.highlight ? ' highlight' : ""}${fmtMetricValue(m.used, m.unit)}${m.limit == null ? "—" : fmtMetricValue(m.limit, m.unit)}${m.percent != null ? `${m.percent.toFixed(0)}%` : "—"}${esc(m.note ?? "")}`, + ) + .join("") + : 'No metrics recorded for this service yet.'; + const payg = svc.paygEstimate + ? `

    PAYG estimate

    low $${svc.paygEstimate.low.toFixed(2)} / high $${svc.paygEstimate.high.toFixed(2)} ${esc(svc.paygEstimate.period)} — counted as used: $${countedEstimate(svc.paygEstimate).toFixed(2)} (1.2 × high, Decision 004).${svc.paygEstimate.note ? `
    ${esc(svc.paygEstimate.note)}` : ""}
    ` + : svc.paygNote + ? `

    PAYG estimate

    ${esc(svc.paygNote)} — no number is invented where the records carry no volume.
    ` + : ""; + const metricIds = [...new Set(history.map((r) => r.metricId))]; + const charts = metricIds + .map((id) => historyChartHtml(history, id)) + .filter(Boolean) + .join(""); + const paces = metricIds + .map((id) => ({ id, pace: projectPace(history, id) })) + .filter((p) => p.pace) + .map( + (p) => + `
    ${esc(p.id)}: +${p.pace!.slopePerDay} pts/day over ${p.pace!.points} reads${p.pace!.projectedExhaustionAt ? ` → projected to exhaust ${esc(p.pace!.projectedExhaustionAt.slice(0, 10))}` : ""}${p.pace!.projectedPercentAtReset != null ? ` · projected ${p.pace!.projectedPercentAtReset}% at reset` : ""}
    `, + ) + .join(""); + const reads = svc.reads.length + ? svc.reads.map((r) => `
    ${esc(r.at)}
    ${esc(r.text)}
    `).join("") + : '

    No dated reads recorded.

    '; + const conflicts = svc.conflicts.length + ? `

    Conflicts (shown, not resolved)

    ${svc.conflicts.map((c) => `
    ${esc(c)}
    `).join("")}` + : ""; + const body = `

    ← Usage & billing

    +

    ${esc(svc.name)}

    +
    ${esc(svc.plan)} ${esc(svc.status)}
    ${freshnessStamp(svc.measuredAt, svc.sourceClass, svc.cadenceDays)}
    source: ${esc(svc.sourceNote)}${svc.nextDate ? ` · next: ${esc(svc.nextDate)}` : ""}${svc.billedUsd != null ? ` · billed this period: $${svc.billedUsd.toFixed(2)}` : ""}${svc.usageNote ? `
    ${esc(svc.usageNote)}` : ""}
    +

    Sources

    ${svc.sources ? `
    quota-view section: ${esc(svc.sources.quotaViewSection)} in quota-view.md Part (b)
    tracker row: ${svc.sources.trackerRow ? `Summary (b) — ${esc(svc.sources.trackerRow)}` : (svc.status === "candidate" || svc.status === "no-account") ? "none — no Summary (b) row; candidate / not held (§1.4)" : "none — no Summary (b) row"}
    evidence baseline: ${esc(svc.sources.baselineDoc)}
    ` : `
    source: ${esc(svc.sourceNote)}
    `}
    +

    All metrics

    ${metricRows}
    All metrics
    MetricUsedLimit%Note
    +${payg} +

    Snapshot history

    ${snapshotFreshnessStamp(history, svc.cadenceDays, now)}${charts || ""} +${paces ? `

    Pace projections

    ${paces}
    ` : ""} +${conflicts} +

    Dated source reads

    ${reads} +

    Machine-first: /api/quota/service.json?id=${esc(svc.id)}

    `; + return layout( + `${svc.name} · usage`, + body, + provenance, + "/quota", + "", + detail ? freshnessChips(detail, ["quota", "usage"]) : "", + ); +} + +// --- Attention view (#852, tiered in slice 2) ------------------------------- + +export function sessionCard( + e: TieredEntry, + children: Map, + depth = 0, + counts?: Map, + act?: { + actionsByObject?: Map; + identities?: AuthorIdentity[]; + commentsByObject?: Map; + commentOpts?: CommentFormOpts; + }, +): string { + const src = SESSION_SOURCE_LABELS[sourceOf(e)]; + const sub = + e.parentId && depth === 0 + ? ` sub-session${e.agent ? ` · ${esc(e.agent)}` : ""} ↳ ${esc(e.parentId)}` + : e.agent + ? ` ${esc(e.agent)}` + : ""; + const tierBadge = + e.tier === "needs-drew" + ? `Needs User` + : e.tier === "needs-orchestrator" + ? `Needs Orchestrator` + : ""; + const evidence = e.supervisionNote ? `${e.evidence} Keeper: ${e.supervisionNote}` : e.evidence; + const reason = e.drewReason ? `
    Why you: ${esc(e.drewReason)}
    ` : ""; + const orch = e.orchestratorNote ? `
    ${esc(e.orchestratorNote)}
    ` : ""; + const kids = children.get(e.sessionId) ?? []; + const kidsHtml = kids.length + ? `
    ${kids.length} sub-session${kids.length === 1 ? "" : "s"}${kids.map((k) => sessionCard(k, children, depth + 1, counts, act)).join("")}
    ` + : ""; + const cmt = counts ? commentBadge(sessionObjectRef(e.sessionId), counts) : ""; + // #1156 + #1152: session actions (poke/answer/stop by source support) + // and, for tiered entries, the triage set — session-derived items + // stay actionable even when the tier source is down (the session + // feed is live), so no disabledReason ever applies here. + const objectRef = sessionObjectRef(e.sessionId); + const own = act?.actionsByObject?.get(objectRef); + const badges = actionBadgesHtml(own); + const cs = cardState(own); + let controls = ""; + if (act?.identities) { + const sessionBox = sessionActionsHtml(e.sessionId, sourceOf(e), { identities: act.identities }); + const triageBox = + e.tier === "needs-drew" || e.tier === "needs-orchestrator" + ? triageActionsHtml(objectRef, e.tier, { identities: act.identities }, "", cs) + : ""; + controls = `${sessionBox}${triageBox}`; + } + // #1445/#1446: inline detail (state + full action history) and the + // per-card comment box ride the session card too. + const detail = `
    Details & history
    Session
    ${esc(e.sessionId)}
    State
    ${esc(STATE_LABELS[e.state] ?? e.state)}
    Last activity
    ${esc(fmtDate(e.lastActivityAt))}
    Ref
    ${esc(objectRef)}
    ${actionHistoryHtml(own)}
    `; + const commentBox = + act?.identities && act.commentOpts + ? cardCommentHtml(objectRef, undefined, act.commentsByObject?.get(objectRef), act.commentOpts) + : ""; + return `
    ${esc(e.title ?? e.sessionId)} ${esc(src)} ${esc(STATE_LABELS[e.state])}${tierBadge}${cs.acked ? ` Acknowledged` : ""}${sub}${cmt}${badges}
    ${esc(e.sessionId)} · ${esc(e.directory ?? "—")}${e.branch ? ` · ${esc(e.branch)}` : ""} · ${esc(e.model ?? "—")}${e.provider ? ` / ${esc(e.provider)}` : ""} · last activity ${fmtDate(e.lastActivityAt)} · ${esc(e.messageCount ?? "—")} msgs${e.outcome ? ` · outcome: ${esc(e.outcome)}` : ""}
    ${esc(evidence)}${reason}${orch}${controls}${detail}${commentBox}${kidsHtml}
    `; +} + +/** A #899 tier item that is not a live session — a decision, task, or gap. */ +export function tierItemCard( + item: TierItem, + whyLabel: string, + counts?: Map, + act?: { + actions?: DashAction[]; + identities?: AuthorIdentity[]; + disabledReason?: string; + comments?: DashComment[]; + commentOpts?: CommentFormOpts; + }, +): string { + const blocked = item.blockedBy?.length + ? `
    Blocked by: ${item.blockedBy + .map((d) => esc(`${d.task} (${d.status}${d.workerLabel ? `, ${d.workerLabel}` : ""})`)) + .join("; ")}` + : ""; + const question = item.question ? `
    “${esc(item.question)}”` : ""; + const action = item.recommendedAction + ? `
    Recommended: ${esc(item.recommendedAction)}` + : ""; + // A tier item's ref is only sometimes a GitHub ref: tracked-goal items + // carry their goal id (e.g. "goal_…"), and refUrl throws on those — one + // such item 500ed the whole Needs-you render (phase-b inventory, + // 2026-11-05). Non-GitHub refs render as plain code, never a link. + const refLink = item.ref + ? isValidRef(item.ref) + ? `${esc(item.ref)}` + : `${esc(item.ref)}` + : ""; + const ref = item.ref ? `
    ${refLink}` : ""; + const cmt = counts ? commentBadge(tierItemObjectRef(item), counts) : ""; + const badges = actionBadgesHtml(act?.actions); + // #1291: on Needs User cards, the item's own contract renders — the + // why-class badge in the header, the summary / if-ignored / + // delegation / proposal / inability block in the body, and the + // options / survey / delegation / dismiss forms in the actbox. + const isUserTier = whyLabel === "Why you"; + const objectRef = tierItemObjectRef(item); + const cs = cardState(act?.actions); + const extBody = isUserTier ? needsUserBodyHtml(item, act?.actions) : ""; + const extForms = isUserTier ? needsUserFormsHtml(item, objectRef, Date.now(), cs) : ""; + // #1152: the triage control set. Section-derived items disable with + // the reason when the tier source is absent/invalid (#1139 state) — + // the item may not exist in the publisher's current view. + const controls = act?.identities + ? triageActionsHtml( + objectRef, + isUserTier ? "needs-drew" : "needs-orchestrator", + { + identities: act.identities, + ...(act.disabledReason ? { disabledReason: act.disabledReason } : {}), + }, + extForms, + cs, + ) + : ""; + // #1445: the title itself links to the GitHub issue when the card + // carries a gh: ref, and every card expands inline to its full + // detail — source, state, since/lastSeenAt, horizon, blockedBy, + // the question payload, and the recorded action history. + const titleHtml = + item.ref && isValidRef(item.ref) ? `${esc(item.title)}` : esc(item.title); + const questionPayload = item.questions?.length + ? `
    Questions
    ${item.questions + .map( + (q) => + `${esc(q.prompt)} (covers: ${esc(q.covers)}${q.required ? "" : "; optional"})`, + ) + .join("
    ")}
    ` + : item.question + ? `
    Question
    “${esc(item.question)}”
    ` + : ""; + const detail = `
    Details & history
    Source
    ${esc(item.source)} · ${esc(item.kind)}${item.state ? ` · state ${esc(item.state)}` : ""}
    Since
    ${esc(fmtDate(item.since))}
    Last seen
    ${esc(fmtDate(item.lastSeenAt))}
    ${item.horizon ? `
    Horizon
    ${esc(item.horizon)}
    ` : ""}
    Ref
    ${esc(objectRef)}${item.ref ? ` · ${refLink}` : ""}
    ${item.blockedBy?.length ? `
    Blocked by
    ${item.blockedBy.map((d) => esc(`${d.task} (${d.status}${d.workerLabel ? `, ${d.workerLabel}` : ""})`)).join("; ")}
    ` : ""}${questionPayload}
    ${actionHistoryHtml(act?.actions)}
    `; + const commentBox = + act?.identities && act.commentOpts ? cardCommentHtml(objectRef, item.ref, act.comments, act.commentOpts) : ""; + return `
    ${esc(item.source)} ${esc(item.kind)}${isUserTier ? whyUserBadge(item) : ""}${cs.acked ? ` Acknowledged` : ""} ${titleHtml}${cmt}${badges}

    ${esc(whyLabel)}: ${esc(item.reason)}${question}${blocked}${action}${extBody}${ref}${controls}${detail}${commentBox}
    `; +} diff --git a/pm-stack/aggregator/src/render-today.ts b/pm-stack/aggregator/src/render-today.ts new file mode 100644 index 0000000000..88955c23a0 --- /dev/null +++ b/pm-stack/aggregator/src/render-today.ts @@ -0,0 +1,558 @@ +// render.ts split (#13051): today, queue and overview views. +// render.ts re-exports every public name from here; callers keep importing "./render.ts". + +import { type AttentionView, type TodayObjective, type TodayView, buildQuotaActions, windowPercent } from "./derive.ts"; +import type { DashAction } from "./actions.ts"; +import { cardState } from "./card-state.ts"; +import { AA_PLAN_FACTS } from "./aa.ts"; +import { FEED_STALE_MS, ageMsText, feedAgeText } from "./feed.ts"; +import { providerDisplayNames } from "./provider-display.ts"; +import { + reconciledInProgress, + type InProgressSignal, + type QueueView, + type QueueRow, + type ReconciledInProgressItem, +} from "./queue-view.ts"; +import type { HealthView } from "./health.ts"; +import { + type BoardItem, + type GhItem, + type OrchestrationSection, + type ProjectPoolItem, + type Provenance, + type ProvenanceDetail, + type QuotaState, + type QuotaView, + type RefKey, + type SourceCoverage, + isValidRef, + refUrl, +} from "./model.ts"; + +import { + esc, + fmtDate, + FRAG_WATCHDOG_SCRIPT, + freshnessChips, + layout, + sessionObjectRef, + tierItemObjectRef, + coverageHtml, +} from "./render-core.ts"; + +// --- Today view (slice 2, #898 §4) ------------------------------------------- + +function todayHealthStrip(health: HealthView | null, quota: QuotaView, quotaUnavailable: boolean): string { + const compactAge = (ageMs: number) => ageMsText(ageMs).replace(/ old$/, ""); + const stackServices = + health?.services.filter( + (service) => service.def.probe !== "feed" && service.def.probe !== "section" && service.def.probe !== "off", + ) ?? []; + const stackUp = stackServices.filter((service) => service.ok === true).length; + const stackDown = stackServices.filter((service) => service.ok === false); + const stackUnknown = stackServices.filter((service) => service.ok === null); + const stackText = + !health || health.mode !== "live" || stackServices.length === 0 + ? "stack unknown" + : `stack ${stackUp}/${stackServices.length} up${stackDown.length ? ` · ${stackDown.map((service) => service.def.name).join(", ")} down` : ""}${stackUnknown.length ? ` · unknown: ${stackUnknown.map((service) => service.def.name).join(", ")}` : ""}`; + const stackState = + !health || health.mode !== "live" || stackServices.length === 0 + ? "unknown" + : stackDown.length + ? "warn" + : stackUnknown.length + ? "unknown" + : "ok"; + + const feedAge = health?.feed.ageMs; + const feedDown = health?.services.some((service) => service.def.id === "fleet-feed" && service.ok === false) ?? false; + const feedState = + feedDown || (feedAge !== null && feedAge !== undefined && feedAge > 15 * 60_000) + ? "warn" + : feedAge === null || feedAge === undefined + ? "unknown" + : "ok"; + const feedText = feedAge === null || feedAge === undefined ? "feed unknown" : `feed ${compactAge(feedAge)}`; + + const orchestration = health?.jobs.orchestration; + const orchestrationState = + !orchestration || orchestration.state === "unknown" + ? "unknown" + : orchestration.state === "live" && orchestration.ageMs !== undefined + ? "ok" + : "warn"; + const orchestrationText = + !orchestration || orchestration.state === "unknown" + ? "orchestrator unknown" + : orchestration.state === "live" + ? orchestration.ageMs === undefined + ? "orchestrator age unknown" + : `orchestrator ${compactAge(orchestration.ageMs)}` + : `orchestrator ${orchestration.state}`; + + const heartbeatOnly = quota.gatherer?.source === "standalone-heartbeat"; + const poolErrors = quota.pools.filter((pool) => pool.state === "error" || pool.freshness?.state === "error"); + const providerErrors = quota.gatherer?.providers.filter((provider) => provider.state === "error") ?? []; + // A standalone tick is not a replacement quota measurement. Preserve base + // pool failures and include heartbeat failures, deduplicating known services. + const quotaErrors = heartbeatOnly + ? new Set([...poolErrors.map((pool) => pool.id), ...providerErrors.map((provider) => provider.serviceId)]).size + : quota.gatherer + ? providerErrors.length + : poolErrors.length; + const quotaUnknown = + quotaUnavailable || ((!quota.gatherer || heartbeatOnly) && quota.pools.length === 0 && quotaErrors === 0); + const quotaState = quotaUnknown ? "unknown" : quotaErrors ? "warn" : quota.gatherer?.ok === false ? "unknown" : "ok"; + const quotaText = quotaUnknown + ? "quota unknown" + : quotaErrors + ? `quota errors ${quotaErrors}` + : quota.gatherer?.ok === false + ? "quota reads unknown" + : "quota reads OK"; + + const items = [ + { text: stackText, state: stackState, href: "/health", title: "Stack service health" }, + { text: feedText, state: feedState, href: "/health", title: "Fleet feed freshness" }, + { text: orchestrationText, state: orchestrationState, href: "/health", title: "Orchestration freshness" }, + { text: quotaText, state: quotaState, href: "/quota", title: "Quota read status" }, + ]; + return `
    ${items.map((item) => `${esc(item.text)}`).join("")}
    `; +} + +/** The today page's body alone (#1444 fragment payload). */ +export function renderTodayBody( + today: TodayView, + attention: AttentionView, + quota: QuotaView, + coverage: SourceCoverage[], + health: HealthView | null = null, + quotaUnavailable = false, + queue?: QueueView, + queueStale = false, + questionsHtml = "", +): string { + const walled = quota.pools.filter((p) => p.state === "walled"); + const quotaActions = buildQuotaActions(quota, AA_PLAN_FACTS); + // "-direct" display rule (#6125), judged over this view's pool set. + const poolDisplayNames = providerDisplayNames(quota.pools.map((p) => p.provider)); + const displayPoolProvider = (name: string) => poolDisplayNames.get(name) ?? name; + const alerts: string[] = []; + const drewTotal = attention.drew.length + attention.drewExtra.length; + if (drewTotal) { + alerts.push( + ``, + ); + } + // #1174: the same eligible quota actions as /quota's strip and + // /attention's orchestrator tier, derived once above — never a + // second list. Walled pools without a typed action still banner. + for (const a of quotaActions) { + alerts.push( + ``, + ); + } + for (const p of walled.filter((p) => !quotaActions.some((a) => a.poolId === p.id))) { + alerts.push( + ``, + ); + } + const wipViolations = (today.wipLanes ?? []).flatMap((lane) => [ + ...(lane.overCap ? [`${lane.lane} ${lane.count}/${lane.cap}`] : []), + ...lane.projects + .filter((scope) => scope.overCap) + .map((scope) => `project ${scope.key} · ${lane.lane} ${scope.count}/${scope.cap}`), + ...lane.epics + .filter((scope) => scope.overCap) + .map((scope) => `epic ${scope.key} · ${lane.lane} ${scope.count}/${scope.cap}`), + ]); + if (wipViolations.length) { + alerts.push( + ``, + ); + } + // #1139: the derived view's banner names the section's TRUE state — + // absent, invalid, and stale are different failures, and "has not + // published yet" is only honest for one of them. + const diag = today.sectionDiagnosis; + const staleBanner = + today.fromOrchestrator && diag?.state === "stale" + ? `` + : ""; + const provenanceLine = today.fromOrchestrator + ? `

    From the orchestration job's goal measurements (section written ${fmtDate(today.generatedAt)}). Machine-first: /api/today.json · /api/orchestration.json.

    ${staleBanner}` + : diag?.state === "invalid" + ? `` + : diag?.state === "stale" + ? `` + : ``; + const actions = today.actions?.length + ? `

    Pushed back into motion

    ${today.actions.map((a) => `
    ${esc(a.kind)} ${esc(a.target)}
    ${esc(a.summary)}
    ${esc(fmtDate(a.at))}
    `).join("")}` + : ""; + const quotaObjectives: TodayObjective[] = quotaActions.map((a) => ({ + title: a.title, + detail: a.detail, + chip: "quota · action", + })); + const allObjectives = [...today.objectives, ...quotaObjectives]; + // #6174: an objective ref comes from publisher lined-up data and is + // only sometimes a GitHub ref — tracked-goal items carry their goal id, + // and refUrl throws on those, which 500ed the whole /today render (the + // Today-page sibling of the #6149 Needs-you fix). Mirror tierItemCard: + // GitHub refs link, everything else renders as plain code. + const objectives = allObjectives.length + ? allObjectives + .map( + (o, i) => + `
    ${i + 1}
    ${esc(o.title)} ${esc(o.chip)}${o.detail ? `
    ${esc(o.detail)}` : ""}${o.statusNote ? `
    ${esc(o.statusNote)}` : ""}${o.ref ? `
    ${isValidRef(o.ref) ? `${esc(o.ref)}` : `${esc(o.ref)}`}` : ""}
    `, + ) + .join("") + : `

    No objectives lined up for today.

    `; + const momentum = today.momentum.length + ? today.momentum + .map((m) => { + // Defensive: a TodayView built outside derive.ts may still + // carry a non-array `accomplished` (e.g. a bare string) — + // coerce instead of crashing the whole /today render. + const rawAccomplished: unknown = m.accomplished; + const accomplished = ( + Array.isArray(rawAccomplished) ? rawAccomplished : rawAccomplished ? [rawAccomplished] : [] + ).map((a) => String(a)); + const done = accomplished.length + ? `
    Recently accomplished:
      ${accomplished.map((a) => `
    • ${esc(a)}
    • `).join("")}
    ` + : ""; + const blocked = m.blockedBy ? `
    Blocked by: ${esc(m.blockedBy)}` : ""; + const detail = m.detail ? `
    ${esc(m.detail)}` : ""; + return `
    ${esc(m.project)} ${esc(m.state)}${done}${blocked}${detail}
    `; + }) + .join("") + : `

    No projects to measure yet.

    `; + const nextUp = queue + ? `

    Next up ${Math.min(queue.nextUp.length, 5)}${queueStale ? ' stale inputs' : ""}

    The next queued work, in the published horizon order.

    ${queueRows(queue.nextUp.slice(0, 5), "Nothing is queued for the next pick.")}
    ` + : ""; + return `${todayHealthStrip(health, quota, quotaUnavailable)}${provenanceLine}${alerts.join("")} +

    Top objectives

    ${objectives} +

    Project momentum

    ${momentum} +${nextUp}${questionsHtml}${actions}${coverageHtml(coverage)}`; +} + +/** The today page (#1444): full server render. */ +export function renderToday( + today: TodayView, + attention: AttentionView, + quota: QuotaView, + coverage: SourceCoverage[], + provenance: Provenance, + detail?: ProvenanceDetail, + health: HealthView | null = null, + quotaUnavailable = false, + queue?: QueueView, + queueStale = false, + questionsHtml = "", +): string { + return layout( + "Today", + `

    Today

    ${renderTodayBody(today, attention, quota, coverage, health, quotaUnavailable, queue, queueStale, questionsHtml)}`, + provenance, + "/today", + "", + detail ? freshnessChips(detail, ["orchestration", "quota", "attention"]) : "", + ); +} + +/** The Datastar shell for /today (#1444). */ +export function renderTodayShell( + provenance: Provenance, + detail: ProvenanceDetail | undefined, + health: HealthView | null, + quota: QuotaView, + quotaUnavailable = false, + questionsHtml = "", +): string { + return layout( + "Today", + `

    Today

    ${todayHealthStrip(health, quota, quotaUnavailable)}
    Loading today…
    ${questionsHtml}`, + provenance, + "/today", + FRAG_WATCHDOG_SCRIPT, + detail ? freshnessChips(detail, ["orchestration", "quota", "attention"]) : "", + ); +} + +// --- Queue visibility (#1160) ----------------------------------------------- + +function queueRows(rows: QueueRow[], empty: string): string { + if (!rows.length) return `

    ${esc(empty)}

    `; + return `
    ${rows + .map((item) => { + const area = item.area ? `${item.area} · ${item.repo}` : item.repo; + const blocked = item.status.toLowerCase().includes("block"); + const age = + item.ageDays === undefined + ? blocked + ? "block age unknown" + : "age unknown" + : blocked + ? `block state last updated ${item.ageDays}d ago` + : item.ageDays === 0 + ? "updated today" + : `${item.ageDays}d since update`; + const blockers = item.blockedBy?.length + ? `
    Blocked by: ${item.blockedBy.map(esc).join("; ")}` + : ""; + const worker = item.worker ? `
    Worker: ${esc(item.worker)}` : ""; + const epic = item.epic + ? item.epic.url + ? `
    Epic: ${esc(item.epic.title)}` + : `
    Epic: ${esc(item.epic.title)}` + : ""; + const why = item.why ? `
    ${esc(item.why)}` : ""; + const signals = item.signals?.length + ? `
    ${item.signals + .map( + (signal) => + `${signal === "project-status" ? "Project Status" : signal === "active-session" ? "Active session" : "Open PR"}`, + ) + .join(" ")}` + : ""; + const clash = item.disagreement + ? ` ⚠ project: ${esc(item.disagreement.project)} · derived: ${esc(item.disagreement.derived)}` + : ""; + const horizon = item.horizon ? ` · ${esc(item.horizon)}` : ""; + const title = item.url ? `${esc(item.title)}` : esc(item.title); + return `
    ${esc(area)} ${esc(item.status)}${horizon}
    ${title}${item.ref ? `
    ${esc(item.ref)}` : ""}
    ${esc(age)} · ${esc(item.source)}${signals}${clash}${epic}${why}${blockers}${worker}
    `; + }) + .join("")}
    `; +} + +/** The queue page body is also the Datastar fragment and JSON's source view. */ +export function renderQueueBody(view: QueueView): string { + return `

    Cross-project work, reconciled from the existing board, Project pool, and orchestration inputs. Counts are the rows shown; machine-first: /api/queue.json. Updated ${esc(fmtDate(view.generatedAt))}.

    +

    In progress ${view.inProgress.length}

    ${queueRows(view.inProgress, "Nothing is in progress.")} +

    Blocked ${view.blocked.length}

    ${queueRows(view.blocked, "Nothing is blocked.")} +

    Done recently ${view.doneRecently.length}

    Completed or merged in the last 7 days; retired bookkeeping cards are excluded.

    ${queueRows(view.doneRecently, "Nothing completed in the last 7 days.")} +

    Next up ${view.nextUp.length}

    Queued work ordered by the published horizon ladder.

    ${queueRows(view.nextUp, "Nothing is queued for the next pick.")}`; +} + +export function renderQueue(view: QueueView, provenance: Provenance, detail?: ProvenanceDetail): string { + return layout( + "Queue", + `

    Queue visibility

    ${renderQueueBody(view)}`, + provenance, + "/queue", + "", + detail ? freshnessChips(detail, ["board", "orchestration", "items"]) : "", + ); +} + +export function renderQueueShell(provenance: Provenance, detail?: ProvenanceDetail): string { + return layout( + "Queue", + `

    Queue visibility

    Loading queue…
    `, + provenance, + "/queue", + FRAG_WATCHDOG_SCRIPT, + detail ? freshnessChips(detail, ["board", "orchestration", "items"]) : "", + ); +} + +// --- Overview / front door (#1134) ------------------------------------------- +// "/" is the stack front door: one glance at what needs Drew, what is +// moving, what is broken, and where the quotas sit. Every number here +// is derived from the same source views the dedicated pages render +// (attention, the Project pool, quota, health, the board) — the +// overview owns no data of its own, so its counts cannot drift from +// their source pages. deriveOverview is pure, so the HTML page and +// /api/overview.json serve the identical summary. + +export interface OverviewData { + attention: AttentionView; + pool: ProjectPoolItem[]; + quota: QuotaView; + health: HealthView; + board: BoardItem[]; + /** Resolved board refs, used to distinguish open linked PRs. */ + items?: Map; + /** The same line-up source used by /projects for disagreement badges. */ + orchestration?: OrchestrationSection | null; + /** Dashboard actions by object ref, so the needs-you summary applies + * the same render-time suppression as /attention (Codex review on + * PR 2424). Absent in tests and fixture renders: nothing suppressed. */ + actionsByObject?: Map; +} + +export type OverviewInProgressSignal = InProgressSignal; + +export type OverviewInProgressItem = ReconciledInProgressItem; + +export interface OverviewSummary { + /** count is null when the tier source is not present: the queue is + * unknown, never a confident zero (Codex review on PR 2424). */ + needsYou: { count: number | null; tierState: string; top: { title: string; detail?: string }[] }; + projects: { repo: string; total: number; inProgress: number; inReview: number; done: number }[]; + quota: { provider: string; plan: string; state: QuotaState; worstPercent: number | null }[]; + health: { degraded: boolean; up: number; down: number; total: number; feedAgeMs: number | null }; + recentDone: { title: string; repo: string }[]; + inProgress: OverviewInProgressItem[]; +} + +export function deriveOverview(data: OverviewData): OverviewSummary { + // The needs-you summary must agree with /attention on the same data: + // suppressed entries (snoozed / dismissed / marked done — pending + // counts, exactly as on the attention page) leave the count and the + // top list, and when the tier source is not present the count is + // unknown rather than an authoritative number over a partial queue. + const now = Date.now(); + const suppressed = (objectRef: string): boolean => + cardState(data.actionsByObject?.get(objectRef), now).suppressed !== null; + const drewVisible = data.attention.drew.filter((e) => !suppressed(sessionObjectRef(e.sessionId))); + const drewExtraVisible = data.attention.drewExtra.filter((item) => !suppressed(tierItemObjectRef(item))); + const tierPresent = data.attention.tierSource.present; + const top: { title: string; detail?: string }[] = tierPresent + ? [ + ...drewExtraVisible.map((t) => ({ title: t.title, detail: t.reason })), + ...drewVisible.map((e) => ({ title: e.title ?? e.sessionId, detail: e.drewReason })), + ].slice(0, 5) + : []; + const byRepo = new Map(); + for (const item of data.pool) { + const row = byRepo.get(item.repo) ?? { repo: item.repo, total: 0, inProgress: 0, inReview: 0, done: 0 }; + row.total += 1; + if (item.status === "In Progress") row.inProgress += 1; + else if (item.status === "In Review") row.inReview += 1; + else if (item.status === "Done") row.done += 1; + byRepo.set(item.repo, row); + } + // "-direct" display rule (#6125), judged over this view's pool set. + const quotaDisplayNames = providerDisplayNames(data.quota.pools.map((pool) => pool.provider)); + const quota = data.quota.pools.map((pool) => { + // #1134 review (Codex P2): derive from used/limit with the shared + // helper — a window that carries `used` and `limit` but no explicit + // `percent` must not silently drop out of the tightest-window figure. + const percents = pool.windows.map((w) => windowPercent(w)); + return { + provider: quotaDisplayNames.get(pool.provider) ?? pool.provider, + plan: pool.plan, + state: pool.state, + worstPercent: percents.length ? Math.max(...percents) : null, + }; + }); + const services = data.health.services; + const byRecency = (a: BoardItem, b: BoardItem) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""); + return { + needsYou: { + count: tierPresent ? drewVisible.length + drewExtraVisible.length : null, + tierState: data.attention.tierSource.state, + top, + }, + projects: [...byRepo.values()].sort((a, b) => b.total - a.total || a.repo.localeCompare(b.repo)), + quota, + health: { + degraded: data.health.degraded, + up: services.filter((svc) => svc.ok === true).length, + down: services.filter((svc) => svc.ok === false).length, + total: services.length, + feedAgeMs: data.health.feed.ageMs, + }, + recentDone: data.board + .filter((b) => b.status === "done") + .sort(byRecency) + .slice(0, 5) + .map((b) => ({ title: b.title, repo: b.repo })), + inProgress: reconciledInProgress(data), + }; +} + +export function renderOverviewBody(summary: OverviewSummary): string { + // #1134 review (Codex P2): the stale note is about the tier source, not + // about the count, so an empty last published queue must still say it. + const staleNote = `

    Tier source stale — this is its last published state and may have moved since.

    `; + const needs = + summary.needsYou.count === null + ? `` + : summary.needsYou.count + ? `${summary.needsYou.tierState === "stale" ? staleNote : ""}` + : `

    Nothing needs you right now.

    ${summary.needsYou.tierState === "stale" ? staleNote : ""}`; + const topItems = summary.needsYou.top.length + ? `
      ${summary.needsYou.top.map((t) => `
    • ${esc(t.title)}${t.detail ? ` — ${esc(t.detail)}` : ""}
    • `).join("")}
    ` + : ""; + const projectCards = summary.projects.length + ? summary.projects + .map( + (proj) => + `
    ${esc(proj.repo)} ${proj.total} tracked
    ${proj.inProgress} in progress · ${proj.inReview} in review · ${proj.done} done — projects
    `, + ) + .join("") + : `

    No Project pool items collected yet.

    `; + const quotaStrip = summary.quota.length + ? summary.quota + .map((pool) => { + const pct = pool.worstPercent !== null ? ` · ${Math.round(pool.worstPercent)}% of tightest window` : ""; + return `
    ${esc(pool.provider)} ${esc(pool.plan)} ${esc(pool.state)}${pct}
    `; + }) + .join("") + : `

    No quota pools measured yet.

    `; + const healthStrip = `
    ${summary.health.up} of ${summary.health.total} services up${summary.health.down ? ` · ${summary.health.down} down` : ""}${summary.health.degraded ? ` · degraded` : ""}${summary.health.feedAgeMs !== null ? ` · feed ${esc(ageMsText(summary.health.feedAgeMs))} old` : ""} — health
    `; + // #1116 item (5): when the feed itself has crossed the staleness + // threshold the dashboard must say so visibly — a "feed X old" suffix + // is not an actionable warning. The data-signal hook is what the + // age-feed drill greps for as its rendered-page evidence. + const feedAgeMs = summary.health.feedAgeMs; + const feedStaleBanner = + feedAgeMs !== null && feedAgeMs >= FEED_STALE_MS + ? `` + : ""; + const itemList = (items: { title: string; repo: string }[], empty: string) => + items.length + ? `
      ${items.map((i) => `
    • ${esc(i.title)}${i.repo ? ` ${esc(i.repo)}` : ""}
    • `).join("")}
    ` + : `

    ${empty}

    `; + const inProgressItems = summary.inProgress.length + ? `
      ${summary.inProgress + .map((item) => { + const signals = item.signals + .map( + (signal) => + `${signal === "project-status" ? "Project Status" : signal === "active-session" ? "Active session" : "Open PR"}`, + ) + .join(" "); + const clash = item.disagreement + ? ` ⚠ project: ${esc(item.disagreement.project)} · derived: ${esc(item.disagreement.derived)}` + : ""; + return `
    • ${esc(item.title)} ${esc(item.repo)} ${signals}${clash}
    • `; + }) + .join("")}
    ` + : `

    Nothing in progress from the Project, active-session, or open-PR signals.

    `; + return `

    One glance at the whole stack: what needs you, what is moving, what is broken, and where the quotas sit. Every number is the same one its source page shows. Machine-first: /api/overview.json.

    +

    Needs you (${summary.needsYou.count ?? "unknown"})

    ${needs}${topItems} +

    Projects

    ${projectCards} +

    Quota

    ${quotaStrip} +

    Health

    ${feedStaleBanner}${healthStrip} +

    In progress

    ${inProgressItems} +

    Recently done

    ${itemList(summary.recentDone, "Nothing done on the board yet.")} +

    In progress reconciles Project Status, active sessions lined up, and open PRs; recently done is the board's lane — the full curated cross-repo board is a drill-down from here: Board →

    `; +} + +/** The overview page (#1134): full server render. */ +export function renderOverview(data: OverviewData, provenance: Provenance, detail?: ProvenanceDetail): string { + return layout( + "Overview", + `

    Overview

    ${renderOverviewBody(deriveOverview(data))}`, + provenance, + "/", + "", + detail ? freshnessChips(detail, ["board", "quota", "attention"]) : "", + ); +} + +/** The Datastar shell for / (#1134, on the #1444 pattern). */ +export function renderOverviewShell(provenance: Provenance, detail?: ProvenanceDetail): string { + return layout( + "Overview", + `

    Overview

    Loading the overview…
    `, + provenance, + "/", + FRAG_WATCHDOG_SCRIPT, + detail ? freshnessChips(detail, ["board", "quota", "attention"]) : "", + ); +} diff --git a/pm-stack/aggregator/src/render-views.ts b/pm-stack/aggregator/src/render-views.ts new file mode 100644 index 0000000000..41f19f1ae5 --- /dev/null +++ b/pm-stack/aggregator/src/render-views.ts @@ -0,0 +1,493 @@ +// render.ts split (#13051): sessions, conflicts, pages, health, discuss and comments-queue views. +// render.ts re-exports every public name from here; callers keep importing "./render.ts". + +import { diffCoverage, staleIssueState, type CoverageSnapshotFile } from "./coverage.ts"; +import { registryQueryString, type RegistryView } from "./registry-view.ts"; +import type { DashAction } from "./actions.ts"; +import { commentKindCounts, queuedComments } from "./comments.ts"; +import { ageMsText } from "./feed.ts"; +import type { HealthView, PageHealth } from "./health.ts"; +import type { DashComment, Provenance, ProvenanceDetail, SessionRecord } from "./model.ts"; +import { PAGES } from "./pages.ts"; +import { CANONICAL_STATUSES, STATUS_SOURCE_LABELS, STATUS_TAXONOMY } from "./status-taxonomy.ts"; +import type { ConflictEntry, ConflictInbox } from "./conflicts.ts"; +import type { AuthorIdentity } from "./registry.ts"; + +import { + esc, + fmtDate, + COMMENT_SCRIPT, + ACTION_SCRIPT, + freshnessChips, + layout, + sessionObjectRef, + dashCommentHtml, + type CommentFormOpts, + commentThreadHtml, +} from "./render-core.ts"; +import { + FIXTURE_COMMENTS_CAUSE, + commentsFixtureSourced, + fixtureCommentsBannerHtml, + sessionRecordLine, +} from "./render-board.ts"; + +// --- Sessions / identity registry page (#906 §3) ------------------------------ + +const REGISTRY_SOURCE_ORDER = ["opencode-laptop", "opencode-sandbox", "jules", "claude-code", "cron"]; + +export function renderSessions( + records: SessionRecord[], + provenance: Provenance, + detail?: ProvenanceDetail, + act?: { actionsByObject?: Map; identities?: AuthorIdentity[] }, + view?: RegistryView, +): string { + const bySource = new Map(); + for (const r of records) bySource.set(r.source, [...(bySource.get(r.source) ?? []), r]); + const totalTokens = records.reduce((sum, r) => sum + (r.tokensTotal ?? 0), 0); + const groups = [...bySource.entries()] + .sort((a, b) => REGISTRY_SOURCE_ORDER.indexOf(a[0]) - REGISTRY_SOURCE_ORDER.indexOf(b[0])) + .map( + ([source, list]) => + `

    ${esc(source)} (${list.length})

    ${list + .map((r) => + sessionRecordLine(r, { + actions: act?.actionsByObject?.get(sessionObjectRef(r.id)), + identities: act?.identities, + }), + ) + .join("")}`, + ) + .join(""); + // #1209: when the server hands us a RegistryView, the page is one + // windowed/filtered/paginated slice of the store — say so, with the + // hidden counts, a search/filter form, and pagination links. Without + // a view (older callers/tests) the page renders what it was given. + let viewHtml = ""; + if (view) { + const q = view.query; + const windowLabel = q.windowDays === null ? "all history" : `last ${q.windowDays} days`; + const filterBits = [ + q.q ? `search "${esc(q.q)}"` : "", + q.agent ? `agent "${esc(q.agent)}"` : "", + q.task ? `task "${esc(q.task)}"` : "", + ].filter(Boolean); + const hiddenBits = [ + view.hiddenByWindow > 0 ? `${view.hiddenByWindow} hidden by the ${windowLabel} window` : "", + view.hiddenByPagination > 0 ? `${view.hiddenByPagination} more on other pages` : "", + ].filter(Boolean); + const toggle = + q.windowDays === null + ? `last 7 days` + : `all history`; + const prev = + q.offset > 0 + ? `← prev` + : ""; + const next = + view.remainingAfterPage > 0 + ? `next →` + : ""; + viewHtml = `
    ${view.matched} of ${view.totalAll} sessions · window: ${esc(windowLabel)}${filterBits.length ? ` · ${filterBits.join(" · ")}` : ""}${hiddenBits.length ? `
    ${hiddenBits.join(" · ")}` : ""}${view.pinnedIncluded ? `
    A deep-linked session outside this view is pinned at the top of the list.` : ""}
    ${toggle}${prev ? ` · ${prev}` : ""}${next ? ` · ${next}` : ""} +
    `; + } + const body = `

    Sessions — identity registry

    +${viewHtml}

    Every agent/session the fleet can see, with its stable id, the agent identity it ran as, its parent session, and its token total where the source reports one. Task links are loose (from the session's PR, title, or launch record) and improve over time. ${records.length} records shown · ${totalTokens.toLocaleString()} tokens recorded on this page. Machine-first: /api/registry.json.

    +

    Coverage honesty: OpenCode sessions register from their servers; Muse sessions only when a launch record was appended at spawn (scripts/record-claude-launch.ts) — a Muse session that never wrote one is invisible here, and the coverage note on Needs you says which sources are wired.

    +${groups || '

    No sessions recorded yet.

    '}`; + return layout( + "Sessions", + body, + provenance, + "/sessions", + act?.identities ? ACTION_SCRIPT : "", + detail ? freshnessChips(detail, ["registry"]) : "", + ); +} + +// --- All pages (the manifest as a page) --------------------------------------- + +// --- Source-conflict inbox (#1282, slice 1) ----------------------------------- + +/** + * /conflicts — the read-only source-conflict inbox. Every disagreement the + * facets already report, in one queue, grouped by conflict class, each entry + * naming the item, both sources, both values and how long the pair has been + * on record. It resolves nothing: slice 1 projects only, so this page is the + * same list /api/conflicts.json serves, rendered. + */ +export function renderConflicts(inbox: ConflictInbox, provenance: Provenance, detail?: ProvenanceDetail): string { + const chips = detail ? freshnessChips(detail, ["items", "usage"]) : ""; + const ageCell = (entry: ConflictEntry): string => { + if (entry.ageDays === null) return `undated`; + const days = `${entry.ageDays} day${entry.ageDays === 1 ? "" : "s"}`; + const floor = entry.ageBasis === "project-item-updated-at" ? " (floor)" : ""; + return `at least ${days}${floor}
    ${esc(fmtDate(entry.observedAt ?? ""))}${entry.ageBasis === "undated" ? "" : ` · ${esc(entry.ageBasis)}`}`; + }; + const itemCell = (entry: ConflictEntry): string => { + const label = esc(entry.item.title); + if (!entry.item.url) return `${label}`; + return `${label}${entry.item.ref ? `
    ${esc(entry.item.ref)}` : ""}`; + }; + const groups = inbox.byClass + .map((cls) => { + const entries = inbox.entries.filter((e) => e.classId === cls.classId); + if (!entries.length) return ""; + const rows = entries + .map( + (e) => + `${itemCell(e)}${esc(e.sources.a)}
    vs
    ${esc(e.sources.b)}${esc(e.values.a)}
    vs
    ${esc(e.values.b)}${ageCell(e)}${e.href ? `records →` : "—"}`, + ) + .join(""); + return `

    ${esc(cls.label)} (${entries.length})

    +
    ${rows}
    ${esc(cls.label)} — item, sources, both values, age
    ItemSourcesBoth valuesDisagreeing forRecords
    `; + }) + .join(""); + const oldest = + inbox.oldestAgeDays === null ? "—" : `at least ${inbox.oldestAgeDays} day${inbox.oldestAgeDays === 1 ? "" : "s"}`; + const body = `

    Source conflicts

    +

    Every live disagreement the facets already report, in one queue: ${inbox.total} entr${inbox.total === 1 ? "y" : "ies"} across ${inbox.byClass.filter((c) => c.count > 0).length} class${inbox.byClass.filter((c) => c.count > 0).length === 1 ? "" : "es"} · oldest ${oldest} · assembled ${esc(fmtDate(inbox.generatedAt))}. Machine-first: /api/conflicts.json. This page projects; it does not resolve — trust rulings are slice 2 of #1282, so nothing here changes what a render shows.

    +
    +
    Conflicts
    ${inbox.total} live
    +${inbox.byClass.map((c) => `
    ${esc(c.label)}
    ${c.count} live
    `).join("")} +
    Oldest disagreement
    ${oldest}
    +
    +

    Age is a floor, not an exact birthday: it is measured from the newest timestamp the source carries for the pair (a Project item's updatedAt, a service's measuredAt), so the values have disagreed for at least that long — an item edited yesterday for another reason can carry a much older clash.

    +${inbox.total ? groups : ``}`; + return layout("Source conflicts", body, provenance, "/conflicts", "", chips); +} + +export function renderPages(provenance: Provenance, history: PageHealth[] = []): string { + const byRoute = new Map(history.map((p) => [p.route, p])); + const rows = PAGES.map((p) => { + const h = byRoute.get(p.route); + const last = + !h || h.lastRenderedAt === null + ? 'not rendered since this process started' + : `${esc(ageMsText(h.ageMs ?? 0))} · ${h.ok ? "ok" : 'last render failed'}`; + const tier = p.nav === "primary" ? "Primary nav" : "Dropdown-only"; + return `${esc(p.title)}${esc(p.route)}${p.api ? `${esc(p.api)}` : '—'}${tier}${last}${esc(p.blurb)}`; + }).join(""); + return layout( + "All pages", + `

    All pages

    Every registered page, from the manifest in src/pages.ts — the nav bar renders the primary tier, the page dropdown lists them all (#1497). Last-rendered + status come live from the render registry (#1147), the same one Health reports — a page this process has not rendered yet says so, never a fake time. Adding a page is one manifest entry + a render function + a route (recipe in the README).

    ${rows}
    All registered pages
    PageRouteJSON twinNav tierLast renderedWhat it is
    `, + provenance, + "/pages", + ); +} + +// --- Health & topology (#1147 page, #1137 table) --------------------------- + +/** + * The /health page: one view assembled by src/health.ts from live + * probes (cached 60 s), the feed, the section diagnosis, and this + * process's render registry — the same view /api/health serves, so + * the page and the API cannot disagree. States are named per row; a + * failed probe, a stale feed, and an unrendered page all say so. + */ +export function renderHealth(view: HealthView, provenance: Provenance): string { + const nowMs = Date.parse(view.generatedAt); + const probedAge = (iso?: string): string => + iso ? ` · probed ${ageMsText(Math.max(0, nowMs - Date.parse(iso)))}` : ""; + const serviceRows = view.services + .map((s) => { + const port = s.def.port !== null ? String(s.def.port) : "—"; + const upWhen = s.def.upWhen ? `
    up = ${esc(s.def.upWhen)}` : ""; + const notes = s.def.notes ? `
    ${esc(s.def.notes)}` : ""; + return `${esc(s.def.name)}${upWhen}${notes}${port}${esc(s.def.bind)}${esc(s.def.runsAs)}${esc(s.state)} — ${esc(s.detail)}${probedAge(s.probedAt)}${esc(s.def.consumers)}${esc(s.def.breaksIfDown)}`; + }) + .join(""); + const sectionRows = view.feed.sections.length + ? view.feed.sections + .map((s) => { + let status: string; + if (s.status === "unknown") status = s.present ? "present" : 'absent'; + else if (s.status === "error") status = 'error'; + else if (s.status === "skipped") status = 'skipped'; + else status = s.present ? "present · ok" : "empty · ok"; + return `${esc(s.key)}${status}${s.ageMs !== undefined ? esc(ageMsText(s.ageMs)) : "—"}${s.behindBy === null ? "unknown" : s.behindBy}${s.lastSyncAt ? esc(s.lastSyncAt) : "—"}${s.lagNote ? esc(s.lagNote) : ""}${s.note ? esc(s.note) : ""}`; + }) + .join("") + : `No readable fleet feed — sections cannot be reported.`; + const gathererRows = view.quotaGatherer?.providers.length + ? view.quotaGatherer.providers + .map( + (p) => + `${esc(p.providerId)}${p.credentialLabel ? ` · ${esc(p.credentialLabel)}` : ""}${esc(p.serviceId)}${esc(p.state)}unknown${p.lastSyncAt ? esc(p.lastSyncAt) : "—"}${esc(p.lagNote)}`, + ) + .join("") + : `No quota-gatherer provider rows are available.`; + const orch = view.jobs.orchestration; + const orchLine = orch.generatedAt + ? `last run ${esc(orch.runId ?? "unknown")} · ${esc(ageMsText(orch.ageMs ?? 0))} · state ${esc(orch.state)}${orch.failedChecks ? ` · failed checks: ${esc(orch.failedChecks.join(", "))}` : ""} · next expected ~${esc(orch.nextExpectedAt ?? "")} (hourly cadence — an expectation, not a promise)` + : `no run on record · state ${esc(orch.state)}${orch.failedChecks ? ` · failed checks: ${esc(orch.failedChecks.join(", "))}` : ""}`; + const coll = view.jobs.collector; + const drift = view.feed.checkout; + const driftLine = + drift.state === "behind" + ? ` · collector checkout behind origin/main by ${drift.behindBy ?? "?"} commit(s) — the collector is running old code` + : drift.state === "in-sync" + ? ` · collector checkout in sync with origin/main` + : ` · collector checkout drift unknown: ${esc(drift.reason ?? "no reason given")}`; + const collLine = coll.generatedAt + ? `feed generated ${esc(ageMsText(coll.ageMs ?? 0))} · file written ${coll.fileMtime ? esc(coll.fileMtime) : "unknown"}${driftLine}` + : "no readable fleet feed"; + const pageRows = view.pages + .map((p) => { + const last = + p.lastRenderedAt === null + ? `not rendered since this process started (boot ${esc(view.bootAt)})` + : `${esc(ageMsText(p.ageMs ?? 0))} · ${p.ok ? "ok" : 'last render failed'}`; + return `${esc(p.title)}${esc(p.route)}${last}`; + }) + .join(""); + // #1203: the ready-for-agent facet — the harness's real dispatch-layer + // state, not just whether its UI answers 200. "down" means the GraphQL + // read failed (detail names the error) or a backend is not READY; the + // repositories table still shows what the harness reports when it can + // be read at all. + const rfa = view.rfa; + const rfaState = + rfa.state === "up" + ? 'up' + : rfa.state === "fixtures" + ? 'fixtures' + : 'down'; + const rfaRepoRows = rfa.repositories.length + ? rfa.repositories + .map( + (r) => + `${esc(r.projectPath)}${r.paused ? "paused" : "running"}${esc(r.mergePolicy ?? "—")}${r.workItems}`, + ) + .join("") + : `No harness repositories reported — the harness could not be read, or none are registered.`; + const rfaBackendLine = rfa.backends.length + ? `Backends: ${rfa.backends.map((b) => `${esc(b.id)} ${esc(b.kind)}${b.reason ? ` — ${esc(b.reason)}` : ""}`).join(" · ")}` + : "Backends: none reported."; + const rfaSection = `

    ready-for-agent harness

    +
    ${rfaState} — ${esc(rfa.detail)}
    ${rfaBackendLine}
    +
    ${rfaRepoRows}
    ready-for-agent repositories — settings and dispatch work items
    RepositoryPausedMerge policyWork items
    `; + // #3976: push health — the freshness journal + reconciler state, + // rendered beside (never merged into) the per-source freshness + // story: the push state describes the delivery machinery, each + // source row describes that source's own data age and lag. + const push = view.push; + const pushSection = push + ? `

    Push health \u2014 event-driven freshness (#3976)

    +
    push: ${esc(push.state)}
    +
    ${esc(push.state)} \u2014 ${esc(push.detail)}
    last event ${push.lastEventAt ? esc(ageMsText(Math.max(0, nowMs - Date.parse(push.lastEventAt)))) : "none recorded"} \u00b7 last successful reconcile ${push.lastSuccessfulReconcileAt ? esc(ageMsText(Math.max(0, nowMs - Date.parse(push.lastSuccessfulReconcileAt)))) : "never in this process"} \u00b7 journal cursor ${push.cursor ?? "unknown"} \u00b7 gaps: ${push.gaps.open} open \u00b7 ${push.gaps.repairedTotal} repaired by reconciliation \u00b7 ${push.gaps.resetsTotal} journal reset(s)${push.gaps.lastResetAt ? ` (last ${esc(push.gaps.lastResetAt)})` : ""}
    +
    ${push.sources.map((s) => ``).join("")}
    Push sources \u2014 freshness is per source; a quiet source is silent, not an outage
    SourceStateLast eventAgeLagNotices
    ${esc(s.source)}${esc(s.state)}${s.missingNotice ? ' \u00b7 notice missing \u2014 gap open' : ""}${s.lastEventAt ? esc(s.lastEventAt) : "\u2014"}${s.ageMs !== null ? esc(ageMsText(s.ageMs)) : "\u2014"}${s.lagMs !== null ? esc(ageMsText(s.lagMs)) : "\u2014"}${s.notices}
    ` + : `

    Push health \u2014 event-driven freshness (#3976)

    \n

    Push health is not assembled in this mode \u2014 no state is invented for it.

    `; + const sloRows = (view.slo ?? []) + .map((s) => { + const current = !s.sourced + ? `unknown / no signal source` + : s.currentValue !== null + ? esc(ageMsText(s.currentValue)) + : s.latestBad === null + ? `\u2014` + : s.latestBad + ? "down" + : "up"; + const remaining = s.budgetRemainingPercent === null ? "\u2014" : `${s.budgetRemainingPercent.toFixed(1)}%`; + const burn = s.burnRate1h === null ? "\u2014" : s.burnRate1h.toFixed(2); + return `${esc(s.label)}${esc(s.target)}${current}${remaining}${burn}${esc(s.state)}`; + }) + .join(""); + const sloSection = view.slo + ? `

    SLO error budgets (#9988)

    +

    Each minute the health view is sampled into an append-only journal. Budgets are computed over each facet's rolling window; a facet with no signal source is shown as unknown, never as good.

    +
    ${sloRows}
    SLO error budgets \u2014 remaining budget and 1-hour burn rate per facet
    FacetTargetCurrentBudget remaining1h burnState
    ` + : ""; + const cov = view.itemsCoverage; + const coverageLine = + cov && cov.total > 0 + ? `${cov.resolvedLive} of ${cov.total} board items resolved from live data (project pool / projector) · ${cov.fixture} resolved from fixtures (rendered hollow + "unverified") · coverage ratio ${cov.ratio !== null ? cov.ratio.toFixed(2) : "—"} — measured on the health prime's board resolution pass, the same pass that sets the items facet provenance (#1141).` + : `not measured yet — coverage is computed on the health prime's board resolution pass (#1267); a pass that resolved no tagged items reports nothing rather than inventing a ratio.`; + const facets = view.facets + ? freshnessChips(view.facets, [ + "board", + "roadmap", + "items", + "comments", + "quota", + "usage", + "attention", + "orchestration", + "dns", + "registry", + "aa", + ]) + : `

    This source does not report structured source facets.

    `; + const degraded = view.degraded + ? `
    Something below is degraded — each row names its own state; nothing on this page is smoothed over.
    ` + : ""; + const modeNote = + view.mode === "fixtures" + ? `` + : ""; + const body = `

    Health

    +

    Every stack service probed live (results cached 60 s), every feed section aged, the last job runs, and this dashboard's own render history — assembled from the same view /api/health serves, at ${esc(view.generatedAt)}.

    +${degraded}${modeNote} +

    Services & topology

    +

    What runs where: the component, its port and bind as actually deployed, what consumes it, and what breaks without it. State is probed, never assumed.

    +
    ${serviceRows}
    Services, ports, and topology
    ServicePortBindRuns asStateConsumed byIf it is down
    +${rfaSection} +${pushSection} +${sloSection} +

    Feed sections

    +
    ${sectionRows}
    Feed sections — presence, age, lag, and last sync
    SectionPresentAgeBehind byLast syncLag noteNote
    +

    Quota gatherer sources

    +
    ${gathererRows}
    Quota-gatherer provider freshness and lag
    ProviderServiceStateBehind byLast syncLag note
    +

    Jobs

    +
    Orchestration pass
    ${orchLine}
    +
    Fleet-feed collector
    ${collLine}
    +

    Item resolution coverage

    +
    ${coverageLine}
    +

    Source conflicts

    +
    ${ + view.conflicts + ? `${view.conflicts.total} live source conflict${view.conflicts.total === 1 ? "" : "s"}${view.conflicts.byClass + .filter((c) => c.count > 0) + .map((c) => ` · ${esc(c.label)}: ${c.count}`) + .join( + "", + )}${view.conflicts.oldestAgeDays === null ? "" : ` · oldest at least ${view.conflicts.oldestAgeDays} day${view.conflicts.oldestAgeDays === 1 ? "" : "s"}`} (#1282 slice 1 — a growing count means the sources keep disagreeing and nobody has ruled on the class)` + : `not assembled for this health view` + }
    +

    Dashboard comments

    +
    ${view.comments.pendingMessages} message${view.comments.pendingMessages === 1 ? "" : "s"} awaiting triage · ${view.comments.pendingGithub} GitHub comment${view.comments.pendingGithub === 1 ? "" : "s"} awaiting posting · ${view.comments.total} comment${view.comments.total === 1 ? "" : "s"} in the store (#1145 — a pending count that does not drain means work arrives faster than it is cleared, or the triage/poster loop has stopped; check the loop's last run before acting)
    +

    Source facets

    +${facets} +

    Pages

    +

    Render history of this process — a page nobody has opened since boot is labelled unrendered, not green.

    +
    ${pageRows}
    Pages — last rendered
    PageRouteLast rendered
    `; + return layout("Health", body, provenance, "/health"); +} + +// --- Discuss page (one object's dashboard comments) ----------------------------- + +export function renderDiscuss( + objectRef: string, + title: string, + comments: DashComment[], + opts: CommentFormOpts, + provenance: Provenance, +): string { + const back = + objectRef.startsWith("gh:") || objectRef.startsWith("kaneo:") || objectRef.startsWith("grist:") + ? `

    ← the item page

    ` + : objectRef.startsWith("session:") + ? `

    ← the session registry · Needs you

    ` + : `

    ← Needs you

    `; + // #1500: the same fixture banner + honest empty wording as the item + // page, keyed off the comments provenance this page already receives. + const discussFixtureBanner = fixtureCommentsBannerHtml(provenance); + const discussEmptyWording = + commentsFixtureSourced(provenance) && comments.length === 0 + ? `

    no comments loaded — ${FIXTURE_COMMENTS_CAUSE}

    ` + : ""; + const body = `

    ${esc(title)}

    object: ${esc(objectRef)}

    ${back}${discussFixtureBanner}${discussEmptyWording} +

    Two kinds, visibly distinct: a note is read when this is next picked up and triggers nothing; a message to Muse is triaged by the orchestrator on its next pass and may create work.${ + opts.githubRefs?.length + ? ` This item is GitHub-backed, so a comment can also be posted as a GitHub comment on an explicit target.` + : "" + }

    +${commentThreadHtml(objectRef, comments, opts)}`; + return layout(title, body, provenance, "", COMMENT_SCRIPT); +} + +// --- Comments queue page (#1210) ------------------------------------------ + +/** The queue view: every comment still waiting on a loop — messages + * awaiting triage and GitHub comments pending/failed to post — with + * kind/state counts. Terminal comments (triaged/posted) and notes + * are not queued and never render here. */ +export function renderCommentsQueue(comments: DashComment[], provenance: Provenance): string { + const queued = queuedComments(comments); + const k = commentKindCounts(comments); + const summary = `${queued.length} queued — ${k.messagesNew} messages awaiting triage · ${k.githubPending} GitHub comments to post · ${k.githubFailed} failed to post (of ${k.total} comments total: ${k.notes} notes, ${k.messages} messages, ${k.github} GitHub)`; + const list = queued.length + ? queued + .map( + (c) => + `${dashCommentHtml(c, true)}\n

    open the thread

    `, + ) + .join("\n") + : `

    Nothing is queued — every message is triaged and every GitHub comment is posted.

    `; + const body = `

    Comments queue

    +

    Every dashboard comment still waiting on a loop (#1210), oldest first. A note is never queued: it is read when its item is next picked up. Machine-first: /api/comments/queue.json.

    +

    ${summary}

    +${list}`; + return layout("Comments queue", body, provenance, "/comments"); +} + +// --- Projects page (#910 stage 5: the live GitHub Project pool) ------------ +// New function only (parallel agents own the other render functions). +// Renders the feed's Project pool; where the Project Status and the +// derived state (see src/projects.ts derivedProjectState) disagree, +// BOTH are shown — neither side is silently preferred. + +/** #1220: the coverage panel — Project #4 pool vs backlog reality per + * repo (open issues and gate labels from the feed, pool size and unset + * Status/Area from the pool), with the week-over-week delta against the + * stored baseline in parentheses when a baseline exists. */ +export function coverageSectionHtml(coverage: CoverageSnapshotFile | null | undefined): string { + if (!coverage) return ""; + const { current, baseline } = coverage; + const delta = diffCoverage(current, baseline); + const cell = ( + repo: string, + v: number | null, + key: "openIssues" | "gateNow" | "gateNext" | "poolItems" | "poolUnsetStatus" | "poolUnsetArea", + ): string => { + if (v === null) return "—"; + const d = delta.get(repo)?.[key]; + return d === undefined || d === null || d === 0 + ? `${v}` + : `${v} (${d > 0 ? "+" : ""}${d})`; + }; + const rows = current.repos + .map((r) => { + const state = staleIssueState(r); + const status = + state === "error" + ? `Collection error${r.staleIssuesError ? `: ${esc(r.staleIssuesError)}` : ""}` + : state === "stale" + ? "STALE — collection is over 7 days old" + : state === "unavailable" + ? "Unavailable — collection failed or not collected" + : "Current"; + const collectedAt = r.staleIssuesCollectedAt + ? `` + : "—"; + return `${esc(r.repo)}${cell(r.repo, r.openIssues, "openIssues")}${cell(r.repo, r.gateNow, "gateNow")}${cell(r.repo, r.gateNext, "gateNext")}${cell(r.repo, r.poolItems, "poolItems")}${cell(r.repo, r.poolUnsetStatus, "poolUnsetStatus")}${cell(r.repo, r.poolUnsetArea, "poolUnsetArea")}${r.staleOpenIssues === null ? "—" : r.staleOpenIssues}${collectedAt}${status}`; + }) + .join(""); + const note = baseline + ? `Week-over-week delta vs the ${esc(fmtDate(baseline.generatedAt))} snapshot in parentheses. Snapshot stored ${esc(fmtDate(current.generatedAt))}; it rotates into the baseline after a week.` + : `First snapshot stored ${esc(fmtDate(current.generatedAt))} — the week-over-week delta appears after the next weekly rotation.`; + return `

    Coverage — pool vs backlog (#1220)

    +
    ${rows}
    Coverage — pool vs backlog by repository
    RepoOpen issuesnow gatenext gatePool itemsUnset StatusUnset AreaOpen issues untouched >90 daysStale count collected at (UTC)Stale count status
    +

    ${note} Open issues and gate labels come from the collector's Search API census in the fleet feed; pool counts from Project #4 (— = that source was unavailable for the repo, never a real zero). The stale count includes open issues only, is captured at the per-repository timestamp, and is marked stale after seven days; missing/error data is not presented as zero. The same report is in /api/projects.json as \`coverage\`.

    `; +} + +/** The Projects pool body (cards, chips, coverage) without the page + * shell — rendered standalone by renderProjects and, since the #1497 + * merge, as the pool section of /program. */ +/** The per-item brief panel (#1279): visibly labelled as derived, every + * line carrying its evidence link. The identical brief object ships in + * the JSON twin (/api/projects.json `briefs`). */ +/** The canonical status taxonomy (#1198 acceptance 1): the mapping + * table from status-taxonomy.ts, rendered where the pool renders — + * /projects standalone and the pool section of /program. */ +export function statusTaxonomyHtml(): string { + const rows = STATUS_TAXONOMY.map( + (row) => + `${esc(STATUS_SOURCE_LABELS[row.source])}${esc(row.raw)}${esc(row.canonical)}`, + ).join(""); + return `

    Canonical status taxonomy (#1198)

    +

    One canonical status set — ${CANONICAL_STATUSES.map(esc).join(" · ")} — and every source's vocabulary mapped into it. An item's canonical status is the same on every page for the same inputs; a source value with no row here is unmapped and surfaces as a ⚠ disagreement rather than being guessed. The ⚠ badges on Board, Roadmap, Today, and this pool all compare through this table.

    +
    ${rows}
    Per-source status mapping to the canonical set
    SourceSource statusCanonical status
    `; +} diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 4f87f012b7..6720f8f153 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -1,8515 +1,118 @@ -import { renderDesignBoards, type BoardSnapshot } from "./design-boards.ts"; // Pure HTML rendering. Every view function takes already-assembled data and // returns a full HTML string — nothing here does I/O, which keeps the smoke // tests cheap (render from fixtures and assert on output). -import { analyticsSectionHtml } from "./quota-analytics-view.ts"; -import { - type AttentionView, - type RoadmapGrain, - type TodayObjective, - type TodayView, - allRefs, - buildQuotaActions, - commentStream, - executionStrip, - freshness, - monthTimeline, - projectPace, - resetMarkers, - roadmapDayGrain, - sessionChildren, - sessionRoots, - sourceOf, - STATE_LABELS, - timeline as buildTimeline, - windowPercent, -} from "./derive.ts"; -import type { RoadmapReconciliation } from "./roadmap-reconcile.ts"; -import type { RoadmapAnnotation } from "./roadmap-annotations.ts"; -import type { ReleaseSnapshot } from "./releases.ts"; -import { diffCoverage, staleIssueState, type CoverageSnapshotFile } from "./coverage.ts"; -import { DIGEST_SECTION_LIMIT, type Digest, type DigestKind } from "./digest.ts"; -import { registryQueryString, type RegistryView } from "./registry-view.ts"; -import { formatForecastSummary, type ForecastContract } from "./forecast-contract.ts"; -import type { FlowAnalytics } from "./flow-analytics.ts"; -import { flowChartsHtml } from "./flow-charts.ts"; -import { latestInFamily, newClientToken, type DashAction } from "./actions.ts"; -import { applyBoardDonePolicy, DONE_STRIP_RENDER_LIMIT, selectVisibleDoneCards } from "./board-policy.ts"; -import { summarizeWipLanes } from "./wip-limits.ts"; -import { cardState, pendingVerb, type CardState } from "./card-state.ts"; -import { - DELEGATION_DEFAULT_OBJECT_REF, - NEEDS_ORDER_OBJECT_REF, - effectiveStandingAuto, - proposalExpired, - proposalIdentity, - questionIdForOption, - type NeedsOrder, -} from "./tier-items.ts"; -import { commentKindCounts, githubCommentUrl, queuedComments, type CommentKindCounts } from "./comments.ts"; -import { serviceHomeLinks, type ItemServiceLink } from "./service-links.ts"; -import { activityCoverageHtml, gapsHtml, type ActivityCoverage, type GapRecord } from "./activity.ts"; -import type { AuditEvent } from "./events.ts"; -import { AA_PLAN_FACTS, aaCaiPoints, aaPoints, summarizeAa } from "./aa.ts"; -import { - applyInequalityFilters, - bandIndex, - computeRecommendations, - logEdges, - normName, - paretoSet, - pctRank, - projectTask, - scoreEdges, -} from "./assets/aa-explorer-computations.js"; -import { summarizeDns } from "./dns.ts"; -import { needsDrewWait, type NeedsDrewCensus, type NeedsDrewItem } from "./needs-drew.ts"; -import type { Incident, IncidentEvent, PushSubscriptionRow } from "./alerts.ts"; -import type { NotificationRollup } from "./notifications.ts"; -import { NOTIFICATION_CLASS_DEFAULTS, NOTIFICATION_CLASSES } from "./notifications.ts"; -import { FEED_STALE_MS, ageMsText, feedAgeText } from "./feed.ts"; -import { providerDisplayNames } from "./provider-display.ts"; -import { - reconciledInProgress, - type InProgressSignal, - type QueueView, - type QueueRow, - type ReconciledInProgressItem, -} from "./queue-view.ts"; -import type { HealthView, PageHealth } from "./health.ts"; -import { - type AaCaiRow, - type AaConfig, - type AaFeedSection, - type AaRanking, - type AaSection, - type AaTestRun, - type BoardItem, - type ChargeRow, - type Comment, - type DashAuthor, - type DashComment, - type DelegationMode, - type DnsEntry, - type DnsSection, - type GhItem, - type OrchestrationSection, - type PaygLine, - type ProjectAudit, - type ProjectPoolItem, - type Provenance, - type ProvenanceDetail, - type QuotaState, - type QuotaView, - type RefKey, - type RoadmapRow, - type SaasService, - type SessionRecord, - type SnapshotRecord, - type SourceCoverage, - type TieredEntry, - type TierItem, - type TierItemQuestion, - type UsageMetric, - type UsageView, - type WhyUserClass, - SAAS_GROUP_LABELS, - SESSION_SOURCE_LABELS, - countedEstimate, - refsInText, - isValidRef, - refUrl, -} from "./model.ts"; -import { PAGES, groupedPages, primaryGroupedPages, manifestRouteFor, pageByRoute } from "./pages.ts"; -import { KEY_HINT, KEYBOARD_SCRIPT, paletteHtml } from "./keyboard.ts"; -import type { ProgramData, ProgramEntry, ProgramLive, TrackedIssue } from "./program.ts"; -import type { ProjectDetail, ProjectSummary } from "./project-config.ts"; -import { derivedProjectState, projectDisagreement, PROJECT_URL } from "./projects.ts"; -import { - PHASE12_ISSUE_URL, - joinPhase12Steps, - parsePhase12Steps, - phase12IsStale, - type Phase12Snapshot, - type Phase12StepState, -} from "./phase12.ts"; -import { - PHASE_TRACKER_REPO, - PHASE_TRACKER_UMBRELLA, - derivePhase12Progress, - derivePhaseValidation, -} from "./phase-tracker.ts"; -import { deriveMappedProgress, type PhaseMappingSnapshot } from "./phase-mapping.ts"; -import { - BUILD_HEALTH_REPO, - buildHealthIsStale, - projectLane, - projectNightlyTrend, - type BuildHealthSnapshot, -} from "./build-health.ts"; -import type { QueueSnapshot } from "./queue.ts"; -import { - F12_DESIGN_ISSUE_URL, - parseF12Designs, - parseF12Items, - projectF12Readiness, - type F12PrRef, -} from "./f12-readiness.ts"; -import { - CANONICAL_STATUSES, - STATUS_SOURCE_LABELS, - STATUS_TAXONOMY, - canonicalStatusFor, - ghItemDerivedStatus, -} from "./status-taxonomy.ts"; -import type { ConflictEntry, ConflictInbox } from "./conflicts.ts"; -import { buildItemBrief, type ItemBrief } from "./brief.ts"; -import { buildEpicRollups, isEpicChildDone, uniqueProjectItemsByRef, type EpicRollup } from "./epics.ts"; -import { spendCardHtml, unattributedSpendHtml, type SpendCardsView } from "./spend-cards.ts"; -import { effortWeight, handsLine, summarizeWeights, weightedLine } from "./weights.ts"; -import { blockedSummary, depthLayout, hasGraphEdges } from "./graph.ts"; -import { EPIC_GRAPH_DEFAULT_CAP, epicGraph, epicSelector } from "./epic-graph.ts"; -import { type AuthorIdentity } from "./registry.ts"; -import type { SearchResult } from "./search-view.ts"; -import type { DecisionSetSummary } from "./decisions.ts"; -import { dnsAnchor } 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. - */ -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). - */ -const COMMENT_SCRIPT = ``; - -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 = ``; - -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 per manifest section — but EVERY page - * present, primary and dropdown-tier alike: this is where demoted - * pages live. - */ -export function pageDropdown(active: string): string { - let selectedMarked = false; - const groups = groupedPages() - .map(({ group, pages }) => { - const options = pages - .map((p) => { - const selected = p.route === active && !selectedMarked; - if (selected) selectedMarked = true; - return ``; - }) - .join(""); - return `${options}`; - }) - .join(""); - return ``; -} - -export function themeToggle(): string { - // Datastar-first theme toggle (Phase C): the vendored Datastar v1 binds - // data-on: (colon form) for handlers — the dash form does not bind - // clicks (verified live against the vendored bundle). A $pmTheme signal seeded from - // the the inline bootstrap set (stored choice or the - // dark default); the effect is the single writer of data-theme + - // localStorage, and the click handler only flips the signal. - return ``; -} - -function globalSearch(): string { - return ``; -} - -function layout( - title: string, - body: string, - provenance: Provenance, - active: string, - extra = "", - chipsHtml = "", -): string { - // Nav + the page dropdown both render from the manifest (#906 §1): - // registering a page in src/pages.ts is the only step that puts it - // in either. Both use the same grouped model (#1215): the bar groups - // its links by section (#1135) so pages wrap onto a second row at - // phone width instead of scrolling sideways, the dropdown mirrors - // the sections as s, and both list every page. - const links = navLinks(active); - const dropdown = pageDropdown(active); - return ` - -${esc(title)} · aggregator -
    ${chipsHtml}${body} -
    source detailboard: ${esc(provenance.board)} · roadmap: ${esc(provenance.roadmap)} · items: ${esc(provenance.items)} · comments: ${esc(provenance.comments)} · quota: ${esc(provenance.quota)} · usage: ${esc(provenance.usage)} · attention: ${esc(provenance.attention)} · orchestration: ${esc(provenance.orchestration)} · dns: ${esc(provenance.dns)} · registry: ${esc(provenance.registry)} · aa: ${esc(provenance.aa)}
    ${KEY_HINT} · tailnet: ${TAILNET_URL.replace("http://", "")}
    -
    ${extra}${paletteHtml()}${KEYBOARD_SCRIPT}`; -} - -/** Global search over board/roadmap subjects, linked refs, and the slice-2 sources (#1212): registry sessions, the DNS register, services, and tier items. */ -export function renderSearch( - query: string, - results: SearchResult[], - items: Map, - provenance: Provenance, - detail?: ProvenanceDetail, -): string { - const cards = results - .map((result) => { - const badges = result.refs - .map((ref) => { - const item = items.get(ref); - // Codex P1 on PR #7331 (defense in depth): a non-GitHub ref - // (tracked-goal id, orch: key) must never reach refUrl, which - // throws on it — render it as a plain-text badge instead. - return item - ? itemBadge(item) - : isValidRef(ref) - ? `${esc(ref)} · unresolved` - : `${esc(ref)} · unresolved`; - }) - .join(" "); - return `
    ${esc(result.title)}
    ${result.kind} · ${esc(result.summary)}${badges ? `
    ${badges}
    ` : ""}
    `; - }) - .join(""); - const body = `

    Search

    Search board items, roadmap rows, registry sessions, DNS domains, services, and tier items by subject, title, or linked issue/PR ref. Every result links to its own detail view. Linked GitHub badges show their current projected state and whether the result is fixture-only.

    ${query ? `

    ${results.length} result${results.length === 1 ? "" : "s"} for “${esc(query)}”

    ${cards || '

    No matching work found.

    '}` : '

    Enter a title or issue/PR reference to search.

    '}`; - // #1212 slice 2: the search page carries the same freshness facets - // as the home page of each result kind present (board/roadmap/items - // for work, registry for sessions, dns for the register, quota and - // usage for services, orchestration/attention/registry for tiers). - const chipKeys = new Set(["board", "roadmap", "items"]); - for (const result of results) { - if (result.kind === "registry") chipKeys.add("registry"); - if (result.kind === "dns") chipKeys.add("dns"); - if (result.kind === "service") { - chipKeys.add("quota"); - chipKeys.add("usage"); - } - if (result.kind === "tier") { - chipKeys.add("orchestration"); - chipKeys.add("attention"); - chipKeys.add("registry"); - } - } - return layout("Search", body, provenance, "/search", "", detail ? freshnessChips(detail, [...chipKeys]) : ""); -} - -// --- Dashboard comments (#906 §2) ------------------------------------------ - -/** Object refs: the keys dashboard comment threads hang on. */ -export const sessionObjectRef = (id: string): string => `session:${id}`; -export const ghObjectRef = (ref: RefKey): string => `gh:${ref}`; -export function tierItemObjectRef(item: TierItem): string { - // Watchdog items (#1148) all carry the implementation issue as their - // display ref, but each watchdog: is an independent object: - // keying them all by the shared gh: ref would give every watchdog - // card the same DOM id, actions, dismissal state, and comment - // thread, so dismissing one input's card would suppress them all - // (Codex P1 on PR #2431). Watchdog cards key by their unique id; - // the gh: ref still renders as the card's issue link. - if (item.source === "watchdog") return `orch:${item.id}`; - return item.ref ? ghObjectRef(item.ref) : `orch:${item.id}`; -} - -/** A 💬 link to an object's comment thread, with its comment count. */ -export function commentBadge(objectRef: string, counts?: Map): string { - // #1210: a detailed count distinguishes notes from actionable - // comments (awaiting triage / to post / failed) in the badge itself; - // a plain number count keeps the original rendering. - const v = counts?.get(objectRef) as number | CommentKindCounts | undefined; - const n = typeof v === "number" ? v : (v?.total ?? 0); - const actionable = typeof v === "object" && v !== null ? v.actionable : 0; - const title = - typeof v === "object" && v !== null - ? `Dashboard comments on this item: ${v.total} total — ${v.notes} notes, ${v.messagesNew} messages awaiting triage, ${v.githubPending} GitHub comments to post, ${v.githubFailed} failed to post` - : "Dashboard comments on this item"; - const queued = actionable ? ` · ${actionable} queued` : ""; - return ` 💬${n ? ` ${n}` : ""}${queued}`; -} - -export function authorBadge(a: DashAuthor, linkedIdentity?: { source: string; id: string }): string { - const cls = a.kind === "drew" ? "drew" : a.kind === "muse" ? "Muse" : "agent"; - const link = a.sessionId - ? ` session` - : ""; - const linked = linkedIdentity - ? ` linked identity` - : ""; - return `${esc(a.label)}${link}${linked}`; -} - -export function dashCommentHtml(c: DashComment, showObject = false): string { - const verificationChip = - c.provenance === "verified" - ? `verified identity` - : `asserted-legacy — author is a claim`; - const kindChip = - c.kind === "message" - ? `✉ message to Muse ${c.triageState === "triaged" ? "triaged by the orchestrator" : "awaiting triage"}` - : c.kind === "github" - ? `GitHub comment ${ - c.githubState === "posted" - ? `posted${c.githubUrl ? ` — view` : ""}` - : c.githubState === "failed" - ? `posting failed ${relTime(c.githubFailedAt ?? c.createdAt)} — no automatic retry exists; a fleet poster must post it by hand${c.githubError ? ` — last error: ${esc(c.githubError)}` : ""}` - : `pending — will post to ${esc(c.githubRef ?? "")}` - }` - : `note`; - const obj = showObject ? ` on ${esc(c.objectRef)}` : ""; - return `
    ${authorBadge(c.author, c.linkedIdentity)} ${verificationChip} ${kindChip}${obj}
    ${esc(c.body)}
    ${fmtDate(c.createdAt)}
    `; -} - -export interface CommentFormOpts { - /** Refs the "post as GitHub comment" kind may target (explicit select). */ - githubRefs?: RefKey[]; - /** Author identities for the picker (standing + registry sessions). */ - identities: AuthorIdentity[]; -} - -/** - * The author picker's server-rendered options (#1179): the standing - * identities only. Session identities (one per registry session -- - * ~700 and growing) used to be inlined into every card's picker, - * which made list pages quadratic: /program shipped 351 copies of a - * ~123 KB option list (44 MB of HTML), /board 94 copies (12.9 MB). - * The full list now loads on demand from /api/author-identities the - * first time any picker on the page is touched and is applied to - * every picker at once (see DASH_AFTER_JS). Pickers keep working - * without that fetch -- standing identities are the common case. - */ -export function authorOptionsHtml(identities: AuthorIdentity[]): string { - return identities - .filter((i) => !i.sessionId) - .map( - (i) => - ``, - ) - .join(""); -} - -export function commentFormHtml(objectRef: string, opts: CommentFormOpts): string { - const ghRefs = opts.githubRefs ?? []; - const authorOptions = authorOptionsHtml(opts.identities); - const ghTarget = ghRefs.length - ? `` - : ""; - const ghKind = ghRefs.length - ? `` - : ""; - return `
    - - - -
    - - -${ghKind}
    -${ghTarget} - -
    `; -} - -/** A full thread + form for one object ref (discuss page, item page). */ -export function commentThreadHtml( - objectRef: string, - comments: DashComment[], - opts: CommentFormOpts, - heading = "Dashboard comments", -): string { - const list = comments.length - ? comments.map((c) => dashCommentHtml(c)).join("") - : `

    No dashboard comments yet.

    `; - return `

    ${esc(heading)}

    ${list}${commentFormHtml(objectRef, opts)}`; -} - -// --- Dashboard actions (#1152/#1154/#1156) -------------------------------- -// Forms post DashActions to the actions store (src/actions.ts); the -// fleet consumers apply them and report back. Nothing here writes -// anywhere else — a control renders the REQUEST and the store's state -// (pending / applied / rejected), never a pretend-completed change. - -/** "12m ago" style relative stamp for action badges. */ -export function relTime(iso: string, now = Date.now()): string { - const ms = now - Date.parse(iso); - if (Number.isNaN(ms)) return iso; - if (ms < 60_000) return "just now"; - const m = Math.floor(ms / 60_000); - if (m < 60) return `${m}m ago`; - const h = Math.floor(m / 60); - if (h < 24) return `${h}h ago`; - return `${Math.floor(h / 24)}d ago`; -} - -const VERB_BADGE_LABELS: Record = { - acknowledge: "acknowledge", - snooze: "snooze", - escalate: "escalate", - "de-escalate": "de-escalate", - answer: "answer", - delegate: "delegate", - dismiss: "dismiss", - "mark-done": "already done", - restore: "restore", - "set-needs-order": "card order", - "approve-proposal": "approve proposal", - "reject-proposal": "reject proposal", - "request-status": "status change", - "set-delegation-default": "standing default", - poke: "poke", - stop: "stop", -}; - -function pendingBadgeLabel(a: DashAction): string { - if (a.verb === "request-status") return `status → ${a.payload.status ?? "?"} requested`; - if (a.verb === "snooze") return `snooze until ${a.payload.until ? fmtDate(a.payload.until) : "?"} requested`; - if (a.verb === "delegate") return `delegate (${a.payload.mode ?? "?"}) requested`; - return `${VERB_BADGE_LABELS[a.verb] ?? a.verb} requested`; -} - -/** - * The visible state of an object's actions: every still-pending action - * as a ⏳ badge, plus the latest applied/rejected outcome per verb - * family (snooze / status / acknowledge / tier / delegation) so the - * user can SEE that an action landed — or that it was rejected, with - * the consumer's note. - */ -export function actionBadgesHtml(actions: DashAction[] | undefined, now = Date.now()): string { - if (!actions?.length) return ""; - const badges: string[] = []; - for (const a of actions) { - if (a.state === "new") { - badges.push( - `⏳ ${esc(pendingBadgeLabel(a))} · ${esc(relTime(a.createdAt, now))}`, - ); - } - } - const snooze = latestInFamily(actions, "snooze"); - if (snooze?.state === "applied" && snooze.payload.until && Date.parse(snooze.payload.until) > now) { - badges.push( - `💤 snoozed until ${esc(fmtDate(snooze.payload.until))}`, - ); - } - const status = latestInFamily(actions, "status"); - if (status?.state === "applied") { - badges.push( - `✓ status → ${esc(status.payload.status ?? "")} applied · ${esc(relTime(status.appliedAt ?? status.createdAt, now))}`, - ); - } else if (status?.state === "rejected") { - badges.push( - `✗ status → ${esc(status.payload.status ?? "")} rejected${status.resultNote ? ` — ${esc(status.resultNote)}` : ""}`, - ); - } - const ack = latestInFamily(actions, "ack"); - if (ack?.state === "applied") { - badges.push( - `✓ acknowledged · ${esc(relTime(ack.appliedAt ?? ack.createdAt, now))}`, - ); - } - const tier = latestInFamily(actions, "tier"); - if (tier?.state === "applied") { - badges.push( - `✓ moved to ${tier.payload.tier === "needs-drew" ? "Needs User" : "Needs Orchestrator"} · ${esc(relTime(tier.appliedAt ?? tier.createdAt, now))}`, - ); - } else if (tier?.state === "rejected") { - badges.push( - `✗ ${esc(VERB_BADGE_LABELS[tier.verb] ?? tier.verb)} rejected${tier.resultNote ? ` — ${esc(tier.resultNote)}` : ""}`, - ); - } - const delegation = latestInFamily(actions, "delegation"); - if (delegation?.state === "applied") { - badges.push( - `✓ delegated (${esc(delegation.payload.mode ?? "")}) · ${esc(relTime(delegation.appliedAt ?? delegation.createdAt, now))}`, - ); - } else if (delegation?.state === "rejected") { - badges.push( - `✗ delegate rejected${delegation.resultNote ? ` — ${esc(delegation.resultNote)}` : ""}`, - ); - } - return badges.length ? ` ${badges.join(" ")}` : ""; -} - -export interface ActionFormOpts { - /** Author identities for the picker (standing + registry sessions). */ - identities: AuthorIdentity[]; - /** When set, every control renders disabled with this reason shown. */ - disabledReason?: string; -} - -/** Stable DOM id for one card, from its object ref (#1444 fragments - * patch sections; #1443's in-place feedback finds cards by ref). */ -export function cardDomId(objectRef: string): string { - return `card-${objectRef.replace(/[^a-zA-Z0-9]+/g, "-")}`; -} - -/** The card's action history (#1445): every recorded action with its - * state — the audit trail the store keeps, readable on the card. */ -export function actionHistoryHtml(actions: DashAction[] | undefined): string { - if (!actions?.length) return `

    No actions recorded on this card yet.

    `; - return [...actions] - .reverse() - .map((a) => { - const bits = [ - `${esc(VERB_BADGE_LABELS[a.verb] ?? a.verb)}`, - a.state === "new" - ? "⏳ pending" - : a.state === "applied" - ? `✓ applied${a.appliedByRun ? ` by ${esc(a.appliedByRun)}` : ""}` - : a.state === "rejected" - ? "✗ rejected" - : "superseded", - esc(relTime(a.createdAt)), - a.payload.reason ? `— ${esc(a.payload.reason)}` : "", - a.payload.until ? `until ${esc(fmtDate(a.payload.until))}` : "", - a.resultNote ? `· ${esc(a.resultNote)}` : "", - ].filter(Boolean); - return `
    ${bits.join(" ")}
    `; - }) - .join(""); -} - -/** - * The per-card comment box (#1446): the card's existing dashboard - * comments with their queued/posted state, plus a compact form. The - * form posts kind "message" (the orchestrator's queue input); the - * "also post publicly" checkbox adds a kind "github" comment when - * the card carries a gh: ref — posted later by the orchestrator, - * never by the aggregator (no GitHub credentials here). - */ -export function cardCommentHtml( - objectRef: string, - ghRef: RefKey | undefined, - comments: DashComment[] | undefined, - opts: CommentFormOpts, -): string { - const list = comments?.length - ? comments.map((c) => dashCommentHtml(c)).join("") - : `

    No comments on this card yet.

    `; - const authorOptions = authorOptionsHtml(opts.identities); - const ghBox = ghRef - ? `` - : `No GitHub issue on this card — the comment stays internal.`; - return `
    💬 Comments for the orchestrator${comments?.length ? ` (${comments.length})` : ""}${list}
    - - - -
    ${ghBox}
    -
    `; -} - -/** One-tap dismissal reasons (#1449): the common resolutions. */ -export const DISMISS_REASONS = ["Already handled", "No longer relevant", "Duplicate", "Won't do"] as const; -/** One-tap de-escalation reasons (#1449): Drew's "send why" chips. */ -export const DEESCALATE_REASONS = [ - "Orchestrator should have handled this", - "Passing to orchestrator this time", - "Need more info", - "Need recommendations", -] as const; - -/** - * The quick-action bar (#1449): one-tap resolutions with the reason - * attached, writing the existing action vocabulary. Chips disable - * while their verb is pending, so a resolution can't be double-sent. - */ -export function quickBarHtml(objectRef: string, tier: "needs-drew" | "needs-orchestrator", cs: CardState): string { - const chip = ( - verb: DashAction["verb"], - label: string, - hidden: string, - opts: { primary?: boolean; disabled?: boolean; sentLabel?: string } = {}, - ): string => - aformHtml({ - kind: "triage", - verb, - objectRef, - inner: `${hidden}`, - }).replace('class="aform"', 'class="aform qform"'); - const donePending = pendingVerb(cs, "mark-done"); - const dismissPending = pendingVerb(cs, "dismiss"); - const movePending = pendingVerb(cs, "de-escalate") ?? pendingVerb(cs, "escalate"); - const parts: string[] = [ - chip("mark-done", "Already done", "", { - primary: true, - disabled: !!donePending, - sentLabel: "✓ Already done · sent", - }), - ]; - for (const reason of DISMISS_REASONS) { - parts.push( - chip("dismiss", `Dismiss: ${reason}`, ``, { - disabled: !!dismissPending, - sentLabel: "Dismiss · sent", - }), - ); - } - if (tier === "needs-drew") { - for (const reason of DEESCALATE_REASONS) { - parts.push( - chip( - "de-escalate", - reason, - ``, - { disabled: !!movePending, sentLabel: "Sent to orchestrator" }, - ), - ); - } - } - const note = donePending || dismissPending || movePending ? ` ⏳ sent · pending` : ""; - return `
    Quick actions — one tap, reason attached${note}${parts.join("")}
    `; -} - -function authorSelectHtml(identities: AuthorIdentity[]): string { - return `
    `; -} - -interface AFormSpec { - kind: DashAction["kind"]; - verb: DashAction["verb"]; - objectRef: string; - targetRef?: RefKey; - sessionId?: string; - sessionSource?: string; - supersedes?: string; - /** Inner controls (inputs/buttons), already escaped HTML. */ - inner: string; -} - -function aformHtml(spec: AFormSpec): string { - const data = [ - `data-kind="${esc(spec.kind)}"`, - `data-verb="${esc(spec.verb)}"`, - `data-object="${esc(spec.objectRef)}"`, - `data-token="${esc(newClientToken())}"`, - spec.targetRef ? `data-target-ref="${esc(spec.targetRef)}"` : "", - spec.sessionId ? `data-session-id="${esc(spec.sessionId)}"` : "", - spec.sessionSource ? `data-session-source="${esc(spec.sessionSource)}"` : "", - spec.supersedes ? `data-supersedes="${esc(spec.supersedes)}"` : "", - ] - .filter(Boolean) - .join(" "); - return `
    ${spec.inner}
    `; -} - -/** Wrap a card's action forms: one author picker + the disabled gate. */ -function actboxHtml(opts: ActionFormOpts, forms: string): string { - const inner = `${authorSelectHtml(opts.identities)}${forms}`; - return opts.disabledReason - ? `

    ⚠ Actions unavailable — ${esc(opts.disabledReason)}

    ${inner}
    ` - : `
    ${inner}
    `; -} - -function snoozeFieldsHtml(): 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 ``; -} - -/** - * The #1152 triage control set for one tier item: acknowledge (a - * non-resolving "seen" record), snooze (presets + custom), and the - * tier move toward the OTHER tier (de-escalate on Needs User cards, - * escalate on Needs Orchestrator cards), each with an optional reason. - * The answer control lives with the item's own surface (session cards - * carry the session answer; #1291 adds the tier answer row). - */ -export function triageActionsHtml( - objectRef: string, - tier: "needs-drew" | "needs-orchestrator", - opts: ActionFormOpts, - extraForms = "", - cs: CardState = cardState(undefined), -): string { - // #1443: a control whose verb is already pending (or, for - // acknowledge, already in effect) renders disabled — repeat clicks - // cannot pile up duplicate pending actions, and the card SAYS so. - const ackPending = pendingVerb(cs, "acknowledge"); - const snoozePending = pendingVerb(cs, "snooze"); - const moveVerb = tier === "needs-drew" ? "de-escalate" : "escalate"; - const movePending = pendingVerb(cs, moveVerb); - const move = - tier === "needs-drew" - ? aformHtml({ - kind: "triage", - verb: "de-escalate", - objectRef, - inner: ``, - }) - : aformHtml({ - kind: "triage", - verb: "escalate", - objectRef, - inner: ``, - }); - const ackInner = ackPending - ? `Recorded — the fleet applies it on its next pass.` - : cs.acked - ? `You have seen this — it stays until a resolving action or a new signal.` - : `Records that you have seen this — it stays until a resolving action or a new signal.`; - const forms = [ - quickBarHtml(objectRef, tier, cs), - aformHtml({ - kind: "triage", - verb: "acknowledge", - objectRef, - inner: ackInner, - }), - aformHtml({ - kind: "triage", - verb: "snooze", - objectRef, - inner: `${snoozeFieldsHtml()}`, - }), - move, - ].join(""); - return actboxHtml(opts, forms + extraForms); -} - -// --- Needs-user action layer (#1291) --------------------------------------- -// Everything in this block renders ONLY what the published item and -// the actions store actually say — why-class, options, survey, -// delegation state, proposal, inability. No decorative states: a -// control exists exactly when its verb can be posted and consumed. - -const WHY_USER_LABELS: Record = { - decision: "Decision", - "missing-info": "Missing Info", - approval: "Approval", - access: "Access", - policy: "Policy", -}; - -const DELEGATION_MODE_LABELS: Record = { - user: "With You", - "first-pass": "First Pass", - auto: "Auto", -}; - -export function whyUserBadge(item: TierItem): string { - if (!item.whyUser) return ""; - return ` ${esc(WHY_USER_LABELS[item.whyUser])}`; -} - -function questionFieldHtml(q: TierItemQuestion, answeredValue?: string | string[], answerAction?: DashAction): string { - const name = `answers:${q.id}`; - const answered = answeredValue !== undefined; - const disabled = answered ? " disabled" : ""; - let field: string; - if (q.type === "single" || q.type === "yesno") { - const opts = q.options ?? [ - { id: "yes", label: "Yes" }, - { id: "no", label: "No" }, - ]; - field = `${opts - .map( - (o) => - ``, - ) - .join("")}`; - } else if (q.type === "multi") { - const chosen = Array.isArray(answeredValue) ? answeredValue : answeredValue ? [answeredValue] : []; - field = `${(q.options ?? []) - .map( - (o) => - ``, - ) - .join("")}`; - } else { - field = ``; - } - // #1451: answered state rides the card — a partial submit records - // what it covered and the still-open required questions say so. - const state = answered - ? ` ✓ answered: ${esc(Array.isArray(answeredValue) ? answeredValue.join(", ") : (answeredValue ?? ""))}${answerAction ? ` · ${answerAction.state === "new" ? "pending" : "applied"} · action ${esc(answerAction.id)}` : ""}` - : q.required - ? ` still needed` - : ""; - return `
    ${esc(q.prompt)}${q.required ? "" : ` (optional)`}${state}
    ${field}
    Needed: ${esc(q.covers)}
    `; -} - -/** The latest applied reject-proposal on an item, when one exists — - * its reason rides the next proposal's box (#1293). */ -function lastRejection(actions: DashAction[] | undefined): DashAction | undefined { - return (actions ?? []).filter((a) => a.verb === "reject-proposal" && a.state === "applied").at(-1); -} - -/** - * The needs-user body block for one card: summary, the what-happens- - * if-this-sits line, the delegation status line, and the proposal / - * inability boxes (#1291/#1293). Pure content — the forms live in - * needsUserFormsHtml, inside the card's actbox. - */ -export function needsUserBodyHtml(item: TierItem, actions: DashAction[] | undefined, now = Date.now()): string { - const parts: string[] = []; - if (item.summary) parts.push(`
    ${esc(item.summary)}`); - if (item.ifIgnored) - parts.push(`
    If nothing happens: ${esc(item.ifIgnored)}`); - const d = item.delegation; - if (d) { - const rejected = lastRejection(actions); - const statusBits = [ - `Delegation: ${esc(DELEGATION_MODE_LABELS[d.mode])}`, - d.status === "idle" - ? "not started" - : d.status === "working" - ? "the orchestrator is working it" - : d.status === "proposal-ready" - ? "proposal ready for your review" - : d.status === "unable" - ? "returned — the orchestrator could not resolve it" - : "done", - d.runId ? `run ${esc(d.runId)}` : "", - `updated ${esc(relTime(d.updatedAt, now))}`, - ].filter(Boolean); - parts.push(`
    ${statusBits.join(" · ")}`); - if (rejected && d.mode === "first-pass" && d.status !== "proposal-ready") - parts.push( - `
    Previous proposal rejected: ${esc(rejected.payload.reason ?? "")} — a new first pass must differ materially or say why it cannot.`, - ); - if (d.status === "proposal-ready" && d.proposal) { - if (proposalExpired(d, now)) { - parts.push( - `
    Proposal expired — drafted ${esc(fmtDate(d.proposal.at))} by run ${esc(d.runId ?? "unknown")}; it is no longer actionable. Delegate a fresh first pass below.
    ${esc(d.proposal.summary)}
    `, - ); - } else { - parts.push( - `
    First-pass proposal${rejected ? ` — second first pass; previous rejected: ${esc(rejected.payload.reason ?? "")}` : ""}
    ${esc(d.proposal.summary)}${ - d.proposal.detail ? `
    ${esc(d.proposal.detail)}` : "" - }${ - d.proposal.proposedChanges?.length - ? `
    Proposed changes:
      ${d.proposal.proposedChanges.map((c) => `
    • ${esc(c)}
    • `).join("")}
    ` - : "" - }Drafted ${esc(fmtDate(d.proposal.at))} — nothing is applied unless you approve; approval takes effect on the next orchestration pass.
    `, - ); - } - } - if (d.status === "unable" && d.unable) { - parts.push( - `
    The orchestrator could not resolve this — ${esc(d.unable.reason)}
    Tried:
      ${d.unable.whatItTried.map((t) => `
    • ${esc(t)}
    • `).join("")}
    Needs: ${esc(d.unable.whatItNeeds)}
    Declared ${esc(fmtDate(d.unable.at))} by run ${esc(d.runId ?? "unknown")}.
    `, - ); - } - } - // #1293: a pending approve/reject whose proposal has since changed - // renders as no longer applicable, not as a live request. - const pendingProposalAction = (actions ?? []).some( - (a) => a.state === "new" && (a.verb === "approve-proposal" || a.verb === "reject-proposal"), - ); - if (pendingProposalAction) { - const live = proposalIdentity(item); - const stillLive = (actions ?? []).some( - (a) => - a.state === "new" && - (a.verb === "approve-proposal" || a.verb === "reject-proposal") && - live !== null && - a.payload.proposalRunId === live.runId && - a.payload.proposalUpdatedAt === live.updatedAt, - ); - if (!stillLive) - parts.push( - `
    ⏳ A pending proposal action is no longer applicable — the proposal changed since it was recorded; the pass will reject it with that note.`, - ); - } - return parts.join(""); -} - -/** - * The needs-user forms for one card (they join the card's actbox): - * the item's own options as answer buttons, the survey as one answer - * form, a free-text answer when the item offers neither, delegation - * mode controls, proposal approve/reject, and dismiss (#1291). - */ -export function needsUserFormsHtml( - item: TierItem, - objectRef: string, - now = Date.now(), - cs: CardState = cardState(undefined), -): string { - const forms: string[] = []; - // Older option actions predate the canonical question pointer. Resolve - // them from the currently published item so already-answered cards - // cannot reopen the same question after this deploy. - const answered = new Map(cs.answered); - const answerActionsByQuestion = new Map(cs.answerActionsByQuestion); - for (const [optionId, action] of cs.answeredOptionActionsById) { - const questionId = questionIdForOption(item, optionId); - if (questionId && !answered.has(questionId)) { - answered.set(questionId, optionId); - answerActionsByQuestion.set(questionId, action); - } - } - for (const opt of item.options ?? []) { - const questionId = questionIdForOption(item, opt.id); - const questionValue = questionId ? answered.get(questionId) : undefined; - const answerAction = questionId ? answerActionsByQuestion.get(questionId) : cs.answeredOptionAction; - const locked = questionId ? questionValue !== undefined : cs.answeredOptionActionsById.size > 0; - const picked = cs.answeredOptionId === opt.id || (questionId !== undefined && questionValue === opt.id); - forms.push( - aformHtml({ - kind: "triage", - verb: "answer", - objectRef, - inner: `${locked && answerAction ? `Answer action ${esc(answerAction.id)}` : ""}${ - opt.description ? `${esc(opt.description)}` : "" - }${opt.effect ? `Effect: ${esc(opt.effect)}` : ""}`, - }), - ); - } - if (item.questions?.length) { - const remaining = item.questions.filter((q) => q.required && !answered.has(q.id)); - const allDone = remaining.length === 0 && item.questions.some((q) => answered.has(q.id)); - const hasUnanswered = item.questions.some((q) => !answered.has(q.id)); - forms.push( - aformHtml({ - kind: "triage", - verb: "answer", - objectRef, - inner: `${item.questions.map((q) => questionFieldHtml(q, answered.get(q.id), answerActionsByQuestion.get(q.id))).join("")}${ - allDone - ? "All required questions are answered — the answers are recorded and pending with the orchestrator." - : `Answer any subset and submit (#1451): answered questions are recorded, and the card keeps showing what remains${remaining.length ? ` — still needed: ${esc(remaining.map((q) => q.id).join(", "))}` : ""}.` - }`, - }), - ); - } - if (!item.options?.length && !item.questions?.length) { - forms.push( - aformHtml({ - kind: "triage", - verb: "answer", - objectRef, - inner: ``, - }), - ); - } - const d = item.delegation; - if (d) { - const autoBlocked = item.whyUser === "access" || item.whyUser === "policy"; - const expired = proposalExpired(d, now); - const modeButton = (mode: DelegationMode, label: string) => { - if (mode === "auto" && autoBlocked) - return `${esc(WHY_USER_LABELS[item.whyUser!])} items can never be auto-delegated — they stay with you.`; - const current = d.mode === mode && !(expired && mode === "first-pass"); - return aformHtml({ - kind: "triage", - verb: "delegate", - objectRef, - inner: ``, - }); - }; - forms.push( - modeButton( - "first-pass", - expired && d.mode === "first-pass" ? "Delegate: First Pass (fresh draft)" : "Delegate: First Pass", - ), - modeButton("auto", "Delegate: Auto"), - modeButton("user", "Bring Back to Me"), - ); - if (d.status === "proposal-ready" && d.proposal && !expired && d.runId) { - const identity = - `` + - ``; - forms.push( - aformHtml({ - kind: "triage", - verb: "approve-proposal", - objectRef, - inner: `${identity}The pass applies it on its next run and reports the application.`, - }), - aformHtml({ - kind: "triage", - verb: "reject-proposal", - objectRef, - inner: `${identity}`, - }), - ); - } - } - forms.push( - aformHtml({ - kind: "triage", - verb: "dismiss", - objectRef, - inner: `Dismissed items stay out of the queue unless a new material fact appears — then they resurface with the fact cited.`, - }), - ); - // A pending delegation action supersedes the stamped mode display: - // the badges already say so; nothing extra to render here. - return forms.join(""); -} - -/** The standing delegation-default toggle (#1290/#1291): the current - * effective value from the preference records, with the change form. */ -export function delegationDefaultHtml(records: DashAction[] | undefined, opts: ActionFormOpts): string { - const eff = effectiveStandingAuto(records ?? []); - const state = eff.standingAuto - ? `On — Decision, Missing Info, and Approval items delegate to Auto by default` - : `Off — items stay with you unless you delegate them per item`; - const pending = eff.pending - ? ` ⏳ change pending — applies on the next orchestration pass` - : ""; - const form = aformHtml({ - kind: "preference", - verb: "set-delegation-default", - objectRef: DELEGATION_DEFAULT_OBJECT_REF, - inner: `Access and Policy items never auto, whatever this says. Per-item delegation always overrides the default. Initial record: the user's decision, 2026-10-27.`, - }); - return `
    Standing delegation default — ${state}.${pending}${actboxHtml(opts, form)}
    `; -} - -/** The Project Status values a status request may target (#910 field). - * #1198: this set IS the canonical status taxonomy's set — one - * definition (status-taxonomy.ts), adopted here, never a second copy. */ -export const PROJECT_STATUS_VALUES = CANONICAL_STATUSES; - -/** The #1154 control: request a Project Status change (never a direct write). */ -export function statusRequestHtml( - objectRef: string, - targetRef: RefKey, - currentStatus: string | null, - opts: ActionFormOpts, -): string { - const options = PROJECT_STATUS_VALUES.map( - (s) => ``, - ).join(""); - const form = aformHtml({ - kind: "status-request", - verb: "request-status", - objectRef, - targetRef, - inner: `A request, not a write — the orchestration pass (the Project's single writer) applies it on its next run.`, - }); - return actboxHtml(opts, form); -} - -/** Which session verbs a source can support, and why not when it can't. */ -export function sessionVerbSupport(source: string): { verb: "poke" | "answer" | "stop"; reason?: string }[] { - if (source === "opencode-sandbox" || source === "opencode-laptop") { - return [{ verb: "poke" }, { verb: "answer" }, { verb: "stop" }]; - } - if (source === "claude-code") { - const reason = "No live control channel for Muse sessions — launch records only"; - return [ - { verb: "poke", reason }, - { verb: "answer", reason }, - { verb: "stop", reason }, - ]; - } - return []; -} - -/** The #1156 control set for one live session (merged registry identity). */ -export function sessionActionsHtml(sessionId: string, source: string, opts: ActionFormOpts): string { - const support = sessionVerbSupport(source); - if (!support.length) return ""; - const objectRef = sessionObjectRef(sessionId); - const forms = support - .map(({ verb, reason }) => { - if (reason) { - return `
    ${esc(reason)}.
    `; - } - if (verb === "poke") { - return aformHtml({ - kind: "session", - verb, - objectRef, - sessionId, - sessionSource: source, - inner: `Nudges the session via its owning server.`, - }); - } - if (verb === "answer") { - return aformHtml({ - kind: "session", - verb, - objectRef, - sessionId, - sessionSource: source, - inner: ``, - }); - } - return aformHtml({ - kind: "session", - verb, - objectRef, - sessionId, - sessionSource: source, - inner: `Two-step: tick Confirm stop, then Stop — the owning job terminates the run.`, - }); - }) - .join(""); - return actboxHtml(opts, forms); -} - -/** Terminal registry statuses — a record in one of these is history, not live. */ -const TERMINAL_SESSION_STATUSES = new Set([ - "completed", - "complete", - "done", - "failed", - "error", - "stopped", - "terminated", - "succeeded", - "cancelled", -]); - -/** A registry record counts as live inside the attention currency window (2 h). */ -export function sessionRecordIsLive(r: SessionRecord, now = Date.now()): boolean { - if (TERMINAL_SESSION_STATUSES.has(r.status.toLowerCase())) return false; - if (!r.lastSeenAt) return false; - return now - Date.parse(r.lastSeenAt) < 2 * 60 * 60 * 1000; -} - -export function coverageHtml(coverage: SourceCoverage[]): string { - const rows = coverage - .map( - (c) => - `
  • ${c.wired ? "✓" : "⚠"} ${esc(c.label)} — ${c.wired ? "wired" : "not wired"} · ${esc(c.detail)}
  • `, - ) - .join(""); - return `
    Session coverage
      ${rows}
    `; -} - -function itemBadge(item: GhItem): string { - // #1141: fixture-resolved state is invented fallback data — render it - // hollow (dashed, transparent) and named "unverified" so it can never - // be mistaken for a live badge on board/roadmap/item/program pages. - const unverified = item.resolution === "fixture"; - const cls = item.state === "merged" ? "merged" : item.state === "open" ? "open" : "closed"; - const kind = item.kind === "pr" ? (item.state === "merged" ? "PR merged" : "PR") : "issue"; - const draft = item.draft ? " · draft" : ""; - const marker = unverified ? " · unverified" : ""; - const title = unverified ? `${item.title} (unverified — fixture state, not live GitHub data)` : item.title; - return `${kind} ${esc(item.ref)}${draft}${marker}`; -} - -function stripHtml(items: Map, links: BoardItem["links"]): string { - const strip = executionStrip(links, items); - const buckets: [string, string, GhItem[]][] = [ - ["implementing", "implementing", strip.implementing], - ["review", "review", strip.review], - ["merged", "merged", strip.merged], - ["open", "queued", strip.queued], - ["closed", "closed", strip.closed], - ]; - const parts: string[] = []; - for (const [cls, label, list] of buckets) { - if (list.length === 0) continue; - parts.push(`${label}: ${list.length}` + list.map(itemBadge).join(" ")); - } - if (strip.unknown.length) { - parts.push(`unresolved: ${strip.unknown.map(esc).join(", ")}`); - } - return `
    ${parts.join(" ")}
    `; -} - -function briefPanelsForRefs(refs: RefKey[], briefs?: Map): string { - return [...new Set(refs)] - .map((ref) => briefs?.get(ref)) - .filter((brief): brief is ItemBrief => Boolean(brief)) - .map(briefPanelHtml) - .join(""); -} - -// --- 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 - ? `
    ${item.links.map((l) => `${esc(l.ref)}`).join(" ")}
    ` - : ""; - return `
    orchestrator · in flight ${esc(item.title)}${cmt}
    ${status}${repo}${goal}${blocked}${refs}${briefs}
    `; - } - const src = item.source === "github" ? `gh-only ` : ""; - // #1154: a card whose linked issue sits in the Project pool - // carries the status-request control for that pool item. - let statusCtl = ""; - if (act?.identities && act.poolByRef) { - const pooled = item.links.map((l) => act.poolByRef!.get(l.ref)).find((p) => p !== undefined); - if (pooled) { - const objectRef = ghObjectRef(pooled.ref); - statusCtl = `${actionBadgesHtml(act.actionsByObject?.get(objectRef))}${statusRequestHtml(objectRef, pooled.ref, pooled.status ?? null, { identities: act.identities })}`; - } - } - const kaneo = item.kaneoUrl ? ` Kaneo ↗` : ""; - // #1198: the board column is Kaneo's status; when the linked - // Project pool item's Status disagrees canonically, show BOTH - // instead of silently picking the column. - let statusClash = ""; - if (act?.poolByRef) { - const pooled = item.links.map((l) => act.poolByRef!.get(l.ref)).find((p) => p !== undefined); - if (pooled?.status) { - const boardCanonical = canonicalStatusFor("kaneo", item.status); - const projectCanonical = canonicalStatusFor("project", pooled.status); - if (boardCanonical && projectCanonical && boardCanonical !== projectCanonical) { - statusClash = ` ⚠ board: ${esc(item.status)} · project: ${esc(pooled.status)}`; - } - } - } - return `
    ${src}${esc(item.title)}${cmt}
    ${repo}${kaneo}${statusClash}${stripHtml(items, item.links)}${statusCtl}${briefs}
    `; - }) - .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 `

    ${heading} ${overCapBadges}

    ${cards}
    `; - }) - .join(""); - return `
    ${bodies}
    `; -} - -/** The board page (#1444): full server render. */ -export function renderBoard( - board: BoardItem[], - items: Map, - provenance: Provenance, - counts?: Map, - detail?: ProvenanceDetail, - act?: { - actionsByObject?: Map; - poolByRef?: Map; - identities?: AuthorIdentity[]; - briefs?: Map; - }, - renderOpts?: { showAllDone?: boolean }, -): string { - return layout( - "Cross-repo WIP board", - `

    Cross-repo WIP board

    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.

    ${renderBoardBody(board, items, counts, act, renderOpts)}`, - provenance, - "/board", - act?.identities ? ACTION_SCRIPT : "", - detail ? freshnessChips(detail, ["board", "items", "orchestration"]) : "", - ); -} - -/** The Datastar shell for / (#1444): heading + intro paint at once; - * the board itself streams in from /frag/board. */ -export function renderBoardShell(provenance: Provenance, detail?: ProvenanceDetail, viewQuery = ""): string { - const fragBoard = viewQuery ? `/frag/board?${viewQuery}` : "/frag/board"; - return layout( - "Cross-repo WIP board", - `

    Cross-repo WIP board

    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) => `
    ${esc(formatForecastSummary(c))}
    `).join(""); - return `
    ${lines}
    `; -} - -function roadmapDrilldown( - drill: RoadmapDrill, - row: RoadmapRow, - forecasts?: Map, - spend?: SpendCardsView | null, -): string { - const parts: string[] = []; - if (!drill.epic) { - parts.push(`

    No epic yet — no Project epic matches this roadmap row.

    `); - } else { - const epic = drill.epic; - parts.push( - `

    Epic: ${esc(epic.title)} ${esc(epic.ref)} · ${esc(epic.state)}

    `, - ); - if (drill.children.length === 0) { - parts.push(`

    No child issues in the Project pool for this epic yet.

    `); - } else { - const done = drill.children.filter(isEpicChildDone).length; - const total = drill.children.length; - const pct = Math.round((done / total) * 100); - parts.push( - `

    Progress: ${done}/${total} child issues done

    ${pct}%
    `, - ); - parts.push( - `
      ${drill.children - .map( - (c) => - `
    • ${esc(c.title)} ${esc(c.state)} ${esc(c.ref)}
    • `, - ) - .join("")}
    `, - ); - } - } - if (drill.epic) { - const fc = forecastSummaryHtml(forecasts?.get(drill.epic.ref)); - if (fc) parts.push(fc); - } - if (drill.epic) { - const card = spend?.byScope.get(drill.epic.ref); - if (card) parts.push(spendCardHtml(card)); - } - if (row.notes.trim()) parts.push(`

    ${esc(row.notes)}

    `); - return `
    Epic & issues${parts.join("")}
    `; -} - -function roadmapCard( - row: RoadmapRow, - items: Map, - counts?: Map, - drill?: RoadmapDrill, - annotations?: Map, - briefs?: Map, - forecasts?: Map, - spend?: SpendCardsView | null, - epicRollups?: Map, - showRowNotes = false, -): string { - const refs = allRefs([row]); - const refBadges = refs - .map((r) => items.get(r)) - .filter((x): x is GhItem => Boolean(x)) - .map(itemBadge) - .join(" "); - const cmt = counts ? commentBadge(row.subject, counts) : ""; - const grist = row.gristUrl ? ` Grist ↗` : ""; - const repoFile = row.fileUrl ? ` Repo file ↗` : ""; - const expansion = drill ? roadmapDrilldown(drill, row, forecasts, spend) : ""; - // The program timeline has no drill map; keep its Notes visible without - // duplicating the same text when a card already has a drilldown. - const rowNotes = showRowNotes && !drill && row.notes.trim() ? `

    ${esc(row.notes)}

    ` : ""; - const epicRollup = epicRollups?.get(row.subject); - const rollupHtml = epicRollup ? epicRollupHtml(epicRollup) : ""; - const notes = annotations?.get(row.subject) ?? []; - const annotationHtml = notes.length - ? `
    ${notes.map(roadmapAnnotationHtml).join("")}
    ` - : ""; - const briefPanels = briefPanelsForRefs(refs, briefs); - const horizonWarning = row.horizonError - ? ` Invalid Horizon` - : ""; - // #1198: the row's status is Grist's; when the linked GitHub item's - // derived lifecycle status (or its Project Status) disagrees - // canonically, show BOTH instead of silently picking Grist's. - let statusClash = ""; - const ghLinked = refs.map((r) => items.get(r)).find((x) => x !== undefined); - if (ghLinked) { - const gristCanonical = canonicalStatusFor("grist", row.status); - const derived = ghItemDerivedStatus(ghLinked); - if (gristCanonical && derived && derived !== gristCanonical) { - statusClash = ` ⚠ grist: ${esc(row.status)} · derived: ${esc(derived)}`; - } else if (gristCanonical && ghLinked.projectStatus) { - const projectCanonical = canonicalStatusFor("project", ghLinked.projectStatus); - if (projectCanonical && projectCanonical !== gristCanonical) { - statusClash = ` ⚠ grist: ${esc(row.status)} · project: ${esc(ghLinked.projectStatus)}`; - } - } - } - return `
    ${esc(row.title)}${cmt}
    ${esc(row.status)} ${esc(row.area)} · ${esc(row.horizon)}${horizonWarning}${statusClash}${refBadges}${grist}${repoFile}${rollupHtml}${annotationHtml}${rowNotes}${expansion}${briefPanels}
    `; -} - -function roadmapAnnotationHtml(annotation: RoadmapAnnotation): string { - return `
    ${esc(annotation.date)} ${esc(annotation.kind)} ${authorBadge(annotation.author)}
    ${esc(annotation.body)}
    `; -} - -function timelineTable( - tl: ReturnType, - items: Map, - counts?: Map, - drill?: Map, - annotations?: Map, - briefs?: Map, - forecasts?: Map, - spend?: SpendCardsView | null, - options?: { epicRollups?: Map; showRowNotes?: boolean }, -): string { - const head = `Theme${tl.lanes.map((l) => `${esc(l.label)}`).join("")}`; - const body = tl.themes - .map((theme) => { - const themeRows = [...(tl.cells.get(theme)?.values() ?? [])].flat(); - const done = themeRows.filter((row) => row.status.trim().toLowerCase() === "done").length; - const cells = tl.lanes - .map((lane) => { - const rs = tl.cells.get(theme)?.get(lane.key) ?? []; - return `${rs.map((r) => roadmapCard(r, items, counts, drill?.get(r.subject), annotations, briefs, forecasts, spend, options?.epicRollups, options?.showRowNotes)).join("")}`; - }) - .join(""); - return `${esc(theme)} (${done}/${themeRows.length} done)${cells}`; - }) - .join(""); - return `
    ${head}${body}
    Roadmap timeline by theme
    `; -} - -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).
    ` - : reconciliation && reconciliation.drift > 0 - ? `
    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).
    ` - : ""; - const chips = `${GRAINS.map( - ([g, label]) => - `${label}`, - ).join("")} Priorities`; - const invalidHorizons = rows.filter((row) => row.horizonError); - const horizonFlag = invalidHorizons.length - ? `
    ${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.
    ` - : ""; - let body: string; - if (prioritiesView) { - const ordered = [...rows].sort((a, b) => { - const rank = (row: RoadmapRow) => { - const match = /#(\d+)$/.exec(row.priority ?? ""); - return match ? Number(match[1]) : Number.MAX_SAFE_INTEGER; - }; - return rank(a) - rank(b) || a.title.localeCompare(b.title); - }); - body = ordered.length - ? ordered - .map((row) => { - const priority = row.priority - ? `Priority ${esc(row.priority)}` - : 'No priority link'; - const after = row.afterRefs?.length - ? `After: ${row.afterRefs.map((ref) => `${esc(ref)}`).join(", ")}` - : 'No predecessor recorded'; - const release = row.releaseRef - ? `Release ${esc(row.releaseRef)}` - : 'No release linked'; - return `
    ${esc(row.title)}
    ${priority} ${release}
    ${after}
    ${esc(row.area)} · ${esc(row.horizon)} · ${esc(row.status)}
    `; - }) - .join("") - : '

    No priority rows in the current roadmap source.

    '; - } else if (grain === "quarter") { - body = timelineTable(buildTimeline(rows), items, counts, drill, annotations, briefs, forecasts, spend); - } else if (grain === "month") { - body = timelineTable(monthTimeline(rows), items, counts, drill, annotations, briefs, forecasts, spend); - } else { - const dg = roadmapDayGrain(rows, grain); - const byTheme = new Map(); - for (const row of rows) { - const theme = row.area || "Unthemed"; - byTheme.set(theme, [...(byTheme.get(theme) ?? []), row]); - } - body = byTheme.size - ? [...byTheme.entries()] - .map(([theme, themeRows]) => { - const done = themeRows.filter((row) => row.status.trim().toLowerCase() === "done").length; - const cards = (laneRows: RoadmapRow[]) => - laneRows - .map((row) => - roadmapCard(row, items, counts, drill?.get(row.subject), annotations, briefs, forecasts, spend), - ) - .join(""); - const lanes = dg.lanes - .map((lane) => { - const laneRows = lane.rows.filter((row) => (row.area || "Unthemed") === theme); - return laneRows.length ? `

    ${esc(lane.label)}

    ${cards(laneRows)}` : ""; - }) - .join(""); - const outsideRows = dg.outsideRows.filter((row) => (row.area || "Unthemed") === theme); - const coarseRows = dg.coarse.filter((row) => (row.area || "Unthemed") === theme); - const outside = outsideRows.length - ? `

    Outside this window (${outsideRows.length})

    ${cards(outsideRows)}` - : ""; - const coarse = coarseRows.length - ? `

    Undated or coarse horizons (${coarseRows.length})

    ${cards(coarseRows)}` - : ""; - return `

    ${esc(theme)} (${done}/${themeRows.length} done)

    ${lanes}${outside}${coarse}
    `; - }) - .join("") - : '

    No roadmap rows.

    '; - } - const releaseCards = releases - .filter((release) => release.kind === "release") - .map((release) => { - const counts = release.counts; - const carried = release.carriedOverEpics.length - ? `

    Carried-over epics: ${release.carriedOverEpics.map((ref) => `${esc(ref)}`).join(", ")}

    ` - : '

    No carried-over epics.

    '; - return `

    ${esc(release.milestone.title)}

    Date: ${esc(release.releaseDate ?? "date not set")}

    Issues: ${counts.issues.closed}/${counts.issues.total} closed · Designs: ${counts.designs.closed}/${counts.designs.total} closed · Epics: ${counts.epics.closed}/${counts.epics.total} closed

    ${carried}

    ${esc(release.descriptionLine)}

    `; - }) - .join(""); - const releasesHtml = `

    Releases

    ${releaseCards || '

    No release close-out snapshots are available.

    '}

    Releases JSON

    `; - return layout( - "Roadmap", - `

    Roadmap

    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 `
    - - - - -
    `; -} - -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 `

    Epic rollup — ${children} · Status mix: ${statusMix} · Blocked: ${rollup.blocked}

    `; -} - -export function eventTableHtml(events: readonly AuditEvent[]): string { - const rows = events - .map((event) => { - const source = event.source.link - ? `${esc(event.source.identity)}` - : esc(event.source.identity); - const delay = Date.parse(event.ingestedAt) - Date.parse(event.at); - const ingested = - Number.isFinite(delay) && delay > 0 ? `(+${Math.round(delay / 1000)}s ingest)` : ""; - return `${esc(event.at)} ${ingested}${esc(event.actor)} (${esc(event.attribution.confidence)})${esc(event.kind)}${esc(event.ref)}${esc(event.summary)}${source}`; - }) - .join("\n"); - return `
    ${rows || ''}
    Shared activity events
    WhenActorKindRefSummarySource
    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) - ? `` - : ""; -} - -export function renderItem( - title: string, - subject: string, - links: BoardItem["links"], - items: Map, - comments: Comment[], - provenance: Provenance, - extras?: ItemExtras, -): string { - const strip = executionStrip(links, items); - const all = [...strip.implementing, ...strip.review, ...strip.merged, ...strip.queued, ...strip.closed]; - const refRows = all - .map( - (i) => - `${itemBadge(i)}${esc(i.title)}${esc(i.labels.join(", "))}${fmtDate(i.updatedAt)}`, - ) - .join(""); - const stream = commentStream(links, comments); - const commentRows = stream - .map( - (c) => - `${fmtDate(c.createdAt)}${esc(c.kind)}${esc(c.author)}${esc(c.body)}${c.path ? ` (${esc(c.path)}${c.line ? `:${c.line}` : ""})` : ""}`, - ) - .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) - ? `no comments loaded — ${FIXTURE_COMMENTS_CAUSE}` - : 'no comments'; - const dashSection = extras - ? `

    Dashboard comments

    ${ - extras.dashComments.length - ? extras.dashComments.map((c) => dashCommentHtml(c, true)).join("") - : `

    No dashboard comments yet — notes are read when this is picked up; messages are triaged by the orchestrator.

    ` - }${commentFormHtml(extras.formRef, extras.formOpts)}` - : ""; - const roadmapAnnotationSection = - extras?.roadmapAnnotations !== undefined - ? `

    Roadmap annotations

    ${extras.roadmapAnnotations.length ? extras.roadmapAnnotations.map(roadmapAnnotationHtml).join("") : '

    No roadmap annotations yet.

    '}${roadmapAnnotationFormHtml(extras.formRef, extras.formOpts.identities)}
    ` - : ""; - const sessionSection = - extras && extras.sessions.length - ? `

    Sessions that worked this

    ${extras.sessions.map((r) => sessionRecordLine(r)).join("")}
    ` - : ""; - const statusSection = - extras?.statusRequest && extras.formOpts - ? `

    Request status change

    ${actionBadgesHtml(extras.actions)}${statusRequestHtml(extras.statusRequest.objectRef, extras.statusRequest.targetRef, extras.statusRequest.currentStatus, { identities: extras.formOpts.identities })}` - : ""; - const svcLinks = extras?.serviceLinks?.length - ? `

    Live services: ${extras.serviceLinks.map((s) => `${esc(s.label)} ↗`).join(" · ")}

    ` - : ""; - const epicRollup = extras?.epicRollup ? epicRollupHtml(extras.epicRollup) : ""; - const dispatchSection = extras?.dispatchStates?.length - ? `

    ready-for-agent dispatch

      ${extras.dispatchStates - .map( - (entry) => - `
    • ${esc(entry.ref)}: ${esc(entry.state)} · ${esc(entry.provenance.source)} checked ${esc(entry.provenance.observedAt)}
    • `, - ) - .join("")}
    ` - : ""; - const activitySection = extras?.activity - ? `

    Activity stream

    View these events in the global river

    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.

    ${gapsHtml(extras.activity.gaps)}

    Activity source coverage

    ${activityCoverageHtml(extras.activity.coverage)}
    ` - : ""; - return layout( - title, - `

    ${esc(title)}

    subject: ${esc(subject)}

    ${extras?.genealogySentence ? `

    ${esc(extras.genealogySentence)}

    ` : ""}${epicRollup}${svcLinks}${dispatchSection}${stripHtml(items, links)} -${ - extras?.briefs - ? briefPanelsForRefs( - links.map((link) => link.ref), - extras.briefs, - ) - : "" -} -

    ${linkedHeader}

    ${refRows || ''}
    Linked issues and pull requests
    RefTitleLabelsUpdated
    none resolved
    -

    Activity stream comments

    ${commentsBanner}
    ${commentRows || emptyCommentRow}
    Comments
    WhenKindAuthorBody
    - ${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}
    `; -} - -// --- Quota view (#851) + Usage & billing hub (design 2026-10-25) ----------- - -const SOURCE_CLASS_LABELS: Record = { - api: "API read", - console: "console read", - manual: "manual read", - estimate: "estimate", - invoice: "invoice", -}; - -export function fmtMetricValue(v: number | null, unit: string): string { - if (v == null) return "not measured"; - if (unit === "usd") return `$${v.toFixed(2)}`; - if (unit === "cny") return `¥${v.toFixed(2)}`; - if (unit === "gb") return `${v} GB`; - if (unit === "pct") return `${v}%`; - return v.toLocaleString(); -} - -/** The freshness stamp every hub card carries (§1.1): measured-at + source + age. */ -export function freshnessStamp(measuredAt: string | null, sourceClass: string, cadenceDays: number): string { - const f = freshness(measuredAt, cadenceDays); - const cls = SOURCE_CLASS_LABELS[sourceClass] ?? sourceClass; - if (!measuredAt) - return `no dated read ${esc(cls)} · ${esc("never measured")}`; - const age = f.ageDays == null ? "" : f.ageDays === 0 ? " · today" : ` · ${f.ageDays}d ago`; - const stale = f.stale ? ` stale — as of ${esc(measuredAt.slice(0, 10))}` : ""; - return `measured ${esc(measuredAt.slice(0, 10))}${age} · ${esc(cls)}${stale}`; -} - -function metricRow(m: UsageMetric): string { - const pct = m.percent; - const meter = - pct != null - ? ` ${pct.toFixed(0)}% · ` - : ""; - const limit = m.limit == null ? "" : ` / ${fmtMetricValue(m.limit, m.unit)}`; - return `
    ${esc(m.label)}: ${meter}${fmtMetricValue(m.used, m.unit)}${limit}${m.note ? ` — ${esc(m.note)}` : ""}
    `; -} - -function attentionStripHtml(usage: UsageView): string { - if (!usage.attention.length) { - return `
    Needs attention — no quota or credential alerts. (Bubble rules: any metric over 80% of its limit, or projected unbilled PAYG over $5.)
    `; - } - const rows = usage.attention - .map( - (f) => - `
    ${esc(f.label)} — ${esc(f.detail)} details
    `, - ) - .join(""); - return `

    Needs attention

    ${rows}`; -} - -/** - * The DeepSeek PAYG reserve's balance, from the snapshot store (#1052): - * the newest unit "cny" record. Shown in ¥ with its own measured-at — - * the yuan figure as read, never converted to dollars. - */ -function paygBalanceHtml(usage: UsageView): string { - const recs = (usage.history["deepseek"] ?? []).filter((r) => r.unit === "cny" && typeof r.value === "number"); - if (!recs.length) return ""; - const last = recs[recs.length - 1]; - return `
    DeepSeek PAYG reserve balance: ¥${(last.value as number).toFixed(2)}
    reserve only — never a routine route · measured ${esc(last.ts.slice(0, 10))} · ${esc(last.observedBy)}
    `; -} - -function paygCardHtml(usage: UsageView): string { - const balance = paygBalanceHtml(usage); - const balanceBlock = balance ? `
    ${balance}
    ` : ""; - if (!usage.payg.length) { - return `
    PAYG dollars
    pay-as-you-go agent spend
    No metered spill recorded in local records.
    ${balanceBlock}
    `; - } - const lines = usage.payg - .map((l: PaygLine) => { - const figures = - l.settledUsd != null - ? `$${l.settledUsd.toFixed(2)} ${l.settledSource === "invoice" ? "invoiced" : "settled"}${ - l.estimate - ? ` · estimates $${l.estimate.low.toFixed(2)}–$${l.estimate.high.toFixed(2)}` - : l.accruedUsd != null - ? ` · $${l.accruedUsd.toFixed(2)} accrued` - : "" - }${l.settledVarianceUsd != null ? ` · variance ${l.settledVarianceUsd < 0 ? "-$" : "+$"}${Math.abs(l.settledVarianceUsd).toFixed(2)}` : ""} · $${(l.unbilledUsd ?? 0).toFixed(2)} unbilled` - : l.accruedUsd != null - ? `$${l.accruedUsd.toFixed(2)} accrued${l.collectedUsd != null ? ` · $${l.collectedUsd.toFixed(2)} collected` : ""} · $${(l.unbilledUsd ?? 0).toFixed(2)} unbilled` - : l.estimate - ? `counted $${countedEstimate(l.estimate).toFixed(2)} as used (1.2 × high) · estimate $${l.estimate.low.toFixed(2)}–$${l.estimate.high.toFixed(2)} ${esc(l.estimate.period)}` - : "not estimable from local records"; - const stale = l.staleEstimate - ? ` stale estimate — unreconciled >1 invoice cycle` - : ""; - return `
    ${esc(l.label)}${stale}: ${figures}
    ${esc(l.note)}
    ${freshnessStamp(l.measuredAt, l.sourceClass, 7)}
    `; - }) - .join(""); - const total = usage.payg.reduce((sum, l) => sum + (l.unbilledUsd ?? 0), 0); - return `
    PAYG dollars
    metered spill, counted per Decision 004 — estimates at 1.2 × high
    $${total.toFixed(2)} projected unbilled
    ${lines}${balanceBlock}
    `; -} - -function serviceCardHtml(svc: SaasService, history: SnapshotRecord[]): string { - const f = freshness(svc.measuredAt, svc.cadenceDays); - const highlights = svc.metrics.filter((m) => m.highlight); - const metrics = highlights.length - ? highlights.map(metricRow).join("") - : `
    ${esc(svc.usageNote ?? "No highlight metrics recorded.")}
    `; - const billed = svc.billedUsd != null ? `
    billed this period: $${svc.billedUsd.toFixed(2)}
    ` : ""; - const payg = svc.paygEstimate - ? `
    PAYG estimate: counted $${countedEstimate(svc.paygEstimate).toFixed(2)} (${esc(svc.paygEstimate.period)}; range $${svc.paygEstimate.low.toFixed(2)}–$${svc.paygEstimate.high.toFixed(2)} in detail)
    ` - : svc.paygNote - ? `
    PAYG: ${esc(svc.paygNote)}
    ` - : ""; - const conflict = svc.conflicts.length - ? ` conflict` - : ""; - const pace = paceLineHtml(svc.id, history); - const extractionGap = - svc.extractionHealth?.status === "gap" - ? ` extraction gap` - : ""; - return `
    ${esc(svc.name)}${svc.status !== "active" ? ` ${esc(svc.status)}` : ""}${conflict}${extractionGap}
    ${esc(svc.plan)}
    ${freshnessStamp(svc.measuredAt, svc.sourceClass, svc.cadenceDays)}${svc.nextDate ? `
    next: ${esc(svc.nextDate)}` : ""}
    ${metrics}${billed}${payg}${pace}
    `; -} - -function uninstrumentedServicesHtml(services: UsageView["uninstrumentedServices"]): string { - if (!services.length) return ""; - const rows = services - .map( - (svc) => - `${esc(svc.name)}${esc(svc.whatFor)}${esc(svc.status)}${esc(svc.checkedAt ?? "no check date recorded")}${esc(svc.overageBehavior)}${esc(svc.guardrailNotes)}`, - ) - .join(""); - return `

    Tracker services without instrumented quotas

    ${services.length} evaluated services — expand for tracker states and guardrails
    ${rows}
    Services in free-services-to-check.md
    ServiceWhat forTracker stateCheckedOverage behaviorGuardrail notes
    `; -} - -/** A one-line pace projection on a card, when the history supports one (§1.5). */ -function paceLineHtml(serviceId: string, history: SnapshotRecord[]): string { - const metricIds = [...new Set(history.filter((r) => r.unit === "pct").map((r) => r.metricId))]; - for (const metricId of metricIds) { - const pace = projectPace(history, metricId); - if (pace?.projectedExhaustionAt) { - return `
    pace (${esc(metricId)}): +${pace.slopePerDay} pts/day → projected to exhaust ${esc(pace.projectedExhaustionAt.slice(0, 10))}${pace.projectedPercentAtReset != null ? ` · ${pace.projectedPercentAtReset}% at reset` : ""}
    `; - } - } - return ""; -} - -function chargesStripHtml(usage: UsageView): string { - if (!usage.charges.length) { - return `

    Charges this period

    ${esc(usage.chargesNote ?? "No charge evidence in the local records yet — rows appear as Plaid/Gmail receipt evidence is recorded.")}
    `; - } - const rows = usage.charges - .map( - (c: ChargeRow) => - `${esc(c.at)}${esc(c.label)}$${c.amountUsd.toFixed(2)}${esc(c.method)}${esc(c.source)}`, - ) - .join(""); - const total = usage.charges.reduce((sum, c) => sum + c.amountUsd, 0); - return `

    Charges this period

    Evidence, not accounting — charges observed on cards/receipts in the local records (full balances stay in the finance tooling). Total observed: $${total.toFixed(2)}.

    ${rows}
    Charges this period
    DateChargeAmountMethodEvidence
    `; -} - -/** Lazy-refresh strip (#1171): a visible "refreshing" marker while a - * gatherer run is in flight, plus the manual refresh-now control. Both - * use the same trigger path; neither blocks the page on provider calls. */ -function quotaRefreshHtml(refresh?: import("./quota-refresh.ts").RefreshStatus, generatedAt?: string | null): string { - if (!refresh) return ""; - const marker = refresh.refreshing - ? `refreshing — the quota gatherer is running; reload for updated data` - : refresh.stale - ? `quota data is older than five minutes` - : ""; - // Manual refresh (#6125): the button POSTs the manual trigger route - // (POST /api/quota/refresh -> quotaRefresher.manual -> the deployed - // quota-gatherer.service, whose read is the single `opencode quota` - // source), then polls /api/quota.json until quota-current.json's - // generatedAt advances. Success is never faked: an advanced file whose - // gatherer reported failure, a failed request, or a poll window with - // no advance all surface as a failure message. The form remains the - // no-JS path (POST /quota/refresh, same manual trigger, 303 back). - return `
    ${marker || 'quota data is fresh'}
    -`; -} - -export function renderQuota( - view: QuotaView, - provenance: Provenance, - usage?: UsageView, - detail?: ProvenanceDetail, - /** Lazy-refresh state (#1171): renders the "refreshing" marker and the - * manual refresh-now control. Absent means no request was made. */ - refresh?: import("./quota-refresh.ts").RefreshStatus, - /** Analytics & projection model (2026-11-13): built by the server - * from the route ledger + snapshot store; absent/null renders no - * section (older callers and tests are unaffected). */ - analytics?: import("./analytics-store.ts").QuotaAnalytics | null, -): string { - // "-direct" display rule (#6125): judged over every provider name/id - // this surface renders — pool providers, pool ids, burn rows, the - // model-choice pool lists, and credential-lifecycle provider names. - // Display only; ids and keys below stay exactly as the view carries - // them. - const displayNames = providerDisplayNames([ - ...view.pools.map((p) => p.provider), - ...view.pools.map((p) => p.id), - ...(view.burn ?? []).map((b) => b.provider), - ...(view.burn ?? []).map((b) => b.pool), - ...(view.choices ? [...view.choices.hasHeadroom, ...view.choices.burnBeforeReset, ...view.choices.doNotStart] : []), - ...(view.credentialLifecycle ?? []).map((c) => c.providerName), - ]); - const display = (name: string) => displayNames.get(name) ?? name; - const credentialLifecycle = view.credentialLifecycle?.length - ? `

    Credential lifecycle

    ${view.credentialLifecycle - .map((credential) => { - const expiry = credential.expiresAt ? ` · expires ${fmtCentral(credential.expiresAt)}` : " · expiry unknown"; - const reason = credential.reason ? ` · ${esc(credential.reason)}` : ""; - const action = credential.userAction - ? ` · user action: ${esc(credential.userAction.title)}` - : ""; - return `
    ${esc(display(credential.providerName))} · ${esc(credential.label)} ${esc(credential.state)}${expiry}${reason}${action}
    `; - }) - .join("")}
    ` - : ""; - // #6671: provider-auth keeper problems render as their own card — - // a dying provider session (or a keeper that stopped reporting) - // must be visible on the board, not only in a state file. All-ok - // keepers render nothing here (no alert, no noise). - const providerAuthProblems = (view.providerAuth ?? []).filter((a) => a.reporting !== "ok"); - const providerAuthSection = providerAuthProblems.length - ? `

    Provider auth

    ${providerAuthProblems - .map((a) => { - const detail = - a.reporting === "attention" - ? `${esc(a.alert ?? a.status ?? "attention")}${a.alertSince ? ` · since ${fmtCentral(a.alertSince)}` : ""}${a.sessionExpiresAt ? ` · session expires ${fmtCentral(a.sessionExpiresAt)}` : ""}${a.lastGoodAt ? ` · last good ${fmtCentral(a.lastGoodAt)}` : ""}` - : a.reporting === "stale" - ? `keeper not reporting · last check ${fmtCentral(a.checkedAt)}` - : a.reporting === "invalid" - ? "keeper not reporting · state file invalid" - : "keeper not reporting · no state file"; - return `
    ${esc(a.provider)} ${esc(a.reporting)} ${detail}
    `; - }) - .join("")}
    ` - : ""; - const pools = view.pools - .map((p) => { - const windows = p.windows - .map((w) => { - const pct = windowPercent(w); - const used = w.unit === "usd" ? `$${w.used.toFixed(2)}` : w.used.toLocaleString(); - const limit = w.limit == null ? "∞" : w.unit === "usd" ? `$${w.limit.toFixed(2)}` : w.limit.toLocaleString(); - return `
    ${esc(w.name)}: ${pct.toFixed(0)}% · ${used}/${limit} ${esc(w.unit)} · resets ${fmtCentral(w.resetsAt)}
    `; - }) - .join(""); - const sessions = (p.activeSessions ?? []) - .map( - (s) => - `
    burning: ${esc(s.session)} (${esc(s.model)}) ${s.tokens.toLocaleString()} tok
    `, - ) - .join(""); - const credRows = (p.credentials ?? []) - .map((c) => { - const wins = c.windows.map((w) => `${esc(w.name)} ${windowPercent(w).toFixed(0)}%`).join(" \u00b7 "); - const state = - c.freshness.state === "ok" - ? "" - : ` \u00b7 ${esc(c.freshness.state)}${c.freshness.error ? ` \u00b7 ${esc(c.freshness.error)}` : ""}`; - return `
    credential ${esc(c.label)}: ${wins || esc(c.freshness.state)}${state}
    `; - }) - .join(""); - const fresh = p.freshness - ? `
    gatherer · ${esc(p.freshness.state)} · measured ${fmtCentral(p.freshness.measuredAt)} · ${esc(p.freshness.source)}${p.freshness.error ? ` · ${esc(p.freshness.error)}` : ""}
    ` - : ""; - const extractionGap = - p.extractionHealth?.status === "gap" - ? ` extraction gap` - : ""; - - return `
    ${esc(display(p.provider))}
    ${esc(p.plan)}
    ${esc(p.state)}${p.wallLiftsAt ? ` · lifts ${fmtCentral(p.wallLiftsAt)}` : ""}${extractionGap}${p.burnTokensPerMin ? ` ${p.burnTokensPerMin} tok/min` : ""}
    ${windows}${credRows}${sessions}${fresh}${p.note ? `
    ${esc(p.note)}
    ` : ""}
    `; - }) - .join(""); - const burn = view.burn - .map( - (b) => - `${esc(display(b.provider))}${esc(display(b.pool))}${fmtCentral(b.from)}${fmtCentral(b.to)}${b.tokens.toLocaleString()}`, - ) - .join(""); - const choices = (list: string[]) => (list.length ? list.map((id) => esc(display(id))).join(", ") : "—"); - const burnAndChoices = `

    Burn between resets

    ${burn || ''}
    Burn between resets
    ProviderPoolFromToTokens
    none
    -

    Model choice

    - - -
    Model choice rules
    RulePools
    Headroom for a new session${choices(view.choices.hasHeadroom)}
    Burn-it-before-reset (unused headroom)${choices(view.choices.burnBeforeReset)}
    Do not start a second session${choices(view.choices.doNotStart)}
    `; - if (!usage) { - return layout( - "Quota + throughput", - `

    Quota + throughput

    All pooled quotas, resets, and burn rates — all times Central (America/Chicago). Machine-first: the same data is at /api/quota.json.

    -${credentialLifecycle} -${providerAuthSection} -${quotaRefreshHtml(refresh, view.gatherer?.generatedAt ?? null)} -${view.gatherer ? `

    Gatherer tick: ${view.gatherer.tickAt ? fmtCentral(view.gatherer.tickAt) : "unknown"} · ${view.gatherer.ok ? "ok" : "failed"}${view.gatherer.tickAt && Date.now() - Date.parse(view.gatherer.tickAt) > 20 * 60_000 ? " · stale" : ""}${view.gatherer.durationMs != null ? ` · ${esc(view.gatherer.durationMs)} ms` : ""}${view.gatherer.error ? ` · ${esc(view.gatherer.error)}` : ""}

    ` : ""} -

    Pools

    ${pools} -${analytics ? analyticsSectionHtml(analytics, display) : ""} -${burnAndChoices}`, - provenance, - "/quota", - ); - } - const groupOrder: (keyof typeof SAAS_GROUP_LABELS)[] = [ - "database", - "object-storage", - "compute", - "dev-platform", - "domains", - "account-tooling", - ]; - const groups = groupOrder - .map((g) => { - const svcs = usage.services.filter((s) => s.group === g); - const cards = svcs.map((s) => serviceCardHtml(s, usage.history[s.id] ?? [])).join(""); - const domainsCard = - g === "domains" - ? usage.domains - ? `
    Domains
    Porkbun register — summary only; the full register lives on the DNS page
    renewal exposure: $${usage.domains.totalAnnualUsd.toFixed(2)}/yr across ${usage.domains.domainCount} domains
    next renewal: ${esc(usage.domains.nextRenewal ?? "—")}
    ` - : `
    Domains: the register has not reached the feed yet — see /dns.
    ` - : ""; - const subs = - g === "account-tooling" && usage.subscriptions.length - ? `
    Subscriptions (flat)
    renewal-only rows — no usage meter
    ${usage.subscriptions - .map( - (s) => - `
    ${esc(s.name)}: ${esc(s.plan)}${s.renewsAt ? ` · renews ${esc(s.renewsAt)}` : " · renewal date unknown"}
    `, - ) - .join("")}
    ` - : ""; - if (!cards && !domainsCard && !subs) return ""; - return `

    ${esc(SAAS_GROUP_LABELS[g])}

    ${cards}${domainsCard}${subs}
    `; - }) - .join(""); - return layout( - "Usage & billing", - `

    Usage & billing

    Token quotas, PAYG dollars, and SaaS usage vs limits — from dated local records; every card carries its measured-at stamp, and stale cards dim — all times Central (America/Chicago). Machine-first: /api/quota.json.

    -${attentionStripHtml(usage)} -${credentialLifecycle} -${providerAuthSection} -${quotaRefreshHtml(refresh, view.gatherer?.generatedAt ?? null)} -${view.gatherer ? `

    Gatherer tick: ${view.gatherer.tickAt ? fmtCentral(view.gatherer.tickAt) : "unknown"} · ${view.gatherer.ok ? "ok" : "failed"}${view.gatherer.tickAt && Date.now() - Date.parse(view.gatherer.tickAt) > 20 * 60_000 ? " · stale" : ""}${view.gatherer.durationMs != null ? ` · ${esc(view.gatherer.durationMs)} ms` : ""}${view.gatherer.error ? ` · ${esc(view.gatherer.error)}` : ""}

    ` : ""} -

    Token quotas

    ${pools} -${analytics ? analyticsSectionHtml(analytics, display) : ""} -${paygCardHtml(usage)} -

    SaaS & services

    ${groups || '

    No services extracted yet.

    '}${uninstrumentedServicesHtml(usage.uninstrumentedServices ?? [])} -${chargesStripHtml(usage)} -

    Sources

    Research records behind the cards on this page that carry provenance — all in ~/workspace/ai-subscriptions/:
    · evidence baseline: evidence-and-interpretation-baseline-2026-10-20.md (dated official pricing wording + interpretation notes)
    · master tracker: the tracker behind quota-view.md Part (b) — each card with a tracker row cites its Summary (b) row and service section
    · candidate evaluations: free-services-to-check.md
    Per-service provenance (tracker row or its absence, baseline, quota-view section) is on each service's detail page.
    -${burnAndChoices}`, - provenance, - "/quota", - "", - detail ? freshnessChips(detail, ["quota", "usage"]) : "", - ); -} - -// --- Service detail view (hub v1.1, §1.5) ------------------------------------- - -/** An inline SVG history chart for one metric, with reset markers (§4). */ -export function historyChartHtml(records: SnapshotRecord[], metricId: string): string { - const recs = records - .filter((r) => r.metricId === metricId && typeof r.value === "number") - .sort((a, b) => a.ts.localeCompare(b.ts)) as (SnapshotRecord & { value: number })[]; - if (!recs.length) return ""; - const W = 640; - const H = 130; - const PAD = 28; - const t0 = Date.parse(recs[0].ts); - const t1 = Math.max(Date.parse(recs[recs.length - 1].ts), t0 + 1); - const vmax = Math.max(...recs.map((r) => r.value), ...(recs.map((r) => r.limit ?? 0) as number[]), 1) * 1.1; - const x = (ts: string) => PAD + ((Date.parse(ts) - t0) / (t1 - t0)) * (W - PAD - 8); - const y = (v: number) => H - 18 - (v / vmax) * (H - 34); - const markers = resetMarkers(records, metricId) - .filter((m) => Date.parse(m.ts) >= t0 && Date.parse(m.ts) <= t1) - .map( - (m) => - `reset ${esc(m.resetsAt.slice(0, 10))}`, - ) - .join(""); - const limitLine = recs.find((r) => r.limit != null) - ? `` - : ""; - const points = recs - .map( - (r) => - `${esc(r.ts.slice(0, 10))}: ${r.value} ${esc(r.unit)} (${esc(r.source)})`, - ) - .join(""); - const line = recs.map((r, i) => `${i === 0 ? "M" : "L"}${x(r.ts).toFixed(1)},${y(r.value).toFixed(1)}`).join(" "); - const first = recs[0]; - const last = recs[recs.length - 1]; - return `
    ${esc(metricId)} · ${recs.length} snapshot${recs.length === 1 ? "" : "s"} · ${esc(first.ts.slice(0, 10))} → ${esc(last.ts.slice(0, 10))} · dashed amber = window reset, red = limit
    ${markers}${limitLine}${points}
    `; -} - -function snapshotFreshnessStamp(history: SnapshotRecord[], cadenceDays: number, now: Date): string { - const latest = history.reduce( - (current, record) => (!current || Date.parse(record.ts) > Date.parse(current.ts) ? record : current), - null, - ); - if (!latest) { - return '

    No snapshot writer has landed a record for this service yet. The feed-ingest tick is the normal landing path; the §4 backfill is a one-shot recovery, not normal history startup.

    '; - } - const measuredAt = latest.ts.slice(0, 10); - const f = freshness(measuredAt, cadenceDays, now); - const age = f.ageDays == null ? " · age unknown" : f.ageDays === 0 ? " · today" : ` · ${f.ageDays}d ago`; - const state = f.stale ? 'stale' : 'within cadence'; - return `

    Latest stored snapshot: ${age} · ${cadenceDays}-day expected cadence · ${state}

    `; -} - -export function renderServiceDetail( - svc: SaasService, - history: SnapshotRecord[], - provenance: Provenance, - detail?: ProvenanceDetail, - now = new Date(), -): string { - const f = freshness(svc.measuredAt, svc.cadenceDays); - const metricRows = svc.metrics.length - ? svc.metrics - .map( - (m) => - `${esc(m.label)}${m.highlight ? ' highlight' : ""}${fmtMetricValue(m.used, m.unit)}${m.limit == null ? "—" : fmtMetricValue(m.limit, m.unit)}${m.percent != null ? `${m.percent.toFixed(0)}%` : "—"}${esc(m.note ?? "")}`, - ) - .join("") - : 'No metrics recorded for this service yet.'; - const payg = svc.paygEstimate - ? `

    PAYG estimate

    low $${svc.paygEstimate.low.toFixed(2)} / high $${svc.paygEstimate.high.toFixed(2)} ${esc(svc.paygEstimate.period)} — counted as used: $${countedEstimate(svc.paygEstimate).toFixed(2)} (1.2 × high, Decision 004).${svc.paygEstimate.note ? `
    ${esc(svc.paygEstimate.note)}` : ""}
    ` - : svc.paygNote - ? `

    PAYG estimate

    ${esc(svc.paygNote)} — no number is invented where the records carry no volume.
    ` - : ""; - const metricIds = [...new Set(history.map((r) => r.metricId))]; - const charts = metricIds - .map((id) => historyChartHtml(history, id)) - .filter(Boolean) - .join(""); - const paces = metricIds - .map((id) => ({ id, pace: projectPace(history, id) })) - .filter((p) => p.pace) - .map( - (p) => - `
    ${esc(p.id)}: +${p.pace!.slopePerDay} pts/day over ${p.pace!.points} reads${p.pace!.projectedExhaustionAt ? ` → projected to exhaust ${esc(p.pace!.projectedExhaustionAt.slice(0, 10))}` : ""}${p.pace!.projectedPercentAtReset != null ? ` · projected ${p.pace!.projectedPercentAtReset}% at reset` : ""}
    `, - ) - .join(""); - const reads = svc.reads.length - ? svc.reads.map((r) => `
    ${esc(r.at)}
    ${esc(r.text)}
    `).join("") - : '

    No dated reads recorded.

    '; - const conflicts = svc.conflicts.length - ? `

    Conflicts (shown, not resolved)

    ${svc.conflicts.map((c) => `
    ${esc(c)}
    `).join("")}` - : ""; - const body = `

    ← Usage & billing

    -

    ${esc(svc.name)}

    -
    ${esc(svc.plan)} ${esc(svc.status)}
    ${freshnessStamp(svc.measuredAt, svc.sourceClass, svc.cadenceDays)}
    source: ${esc(svc.sourceNote)}${svc.nextDate ? ` · next: ${esc(svc.nextDate)}` : ""}${svc.billedUsd != null ? ` · billed this period: $${svc.billedUsd.toFixed(2)}` : ""}${svc.usageNote ? `
    ${esc(svc.usageNote)}` : ""}
    -

    Sources

    ${svc.sources ? `
    quota-view section: ${esc(svc.sources.quotaViewSection)} in quota-view.md Part (b)
    tracker row: ${svc.sources.trackerRow ? `Summary (b) — ${esc(svc.sources.trackerRow)}` : (svc.status === "candidate" || svc.status === "no-account") ? "none — no Summary (b) row; candidate / not held (§1.4)" : "none — no Summary (b) row"}
    evidence baseline: ${esc(svc.sources.baselineDoc)}
    ` : `
    source: ${esc(svc.sourceNote)}
    `}
    -

    All metrics

    ${metricRows}
    All metrics
    MetricUsedLimit%Note
    -${payg} -

    Snapshot history

    ${snapshotFreshnessStamp(history, svc.cadenceDays, now)}${charts || ""} -${paces ? `

    Pace projections

    ${paces}
    ` : ""} -${conflicts} -

    Dated source reads

    ${reads} -

    Machine-first: /api/quota/service.json?id=${esc(svc.id)}

    `; - return layout( - `${svc.name} · usage`, - body, - provenance, - "/quota", - "", - detail ? freshnessChips(detail, ["quota", "usage"]) : "", - ); -} - -// --- Attention view (#852, tiered in slice 2) ------------------------------- - -function sessionCard( - e: TieredEntry, - children: Map, - depth = 0, - counts?: Map, - act?: { - actionsByObject?: Map; - identities?: AuthorIdentity[]; - commentsByObject?: Map; - commentOpts?: CommentFormOpts; - }, -): string { - const src = SESSION_SOURCE_LABELS[sourceOf(e)]; - const sub = - e.parentId && depth === 0 - ? ` sub-session${e.agent ? ` · ${esc(e.agent)}` : ""} ↳ ${esc(e.parentId)}` - : e.agent - ? ` ${esc(e.agent)}` - : ""; - const tierBadge = - e.tier === "needs-drew" - ? `Needs User` - : e.tier === "needs-orchestrator" - ? `Needs Orchestrator` - : ""; - const evidence = e.supervisionNote ? `${e.evidence} Keeper: ${e.supervisionNote}` : e.evidence; - const reason = e.drewReason ? `
    Why you: ${esc(e.drewReason)}
    ` : ""; - const orch = e.orchestratorNote ? `
    ${esc(e.orchestratorNote)}
    ` : ""; - const kids = children.get(e.sessionId) ?? []; - const kidsHtml = kids.length - ? `
    ${kids.length} sub-session${kids.length === 1 ? "" : "s"}${kids.map((k) => sessionCard(k, children, depth + 1, counts, act)).join("")}
    ` - : ""; - const cmt = counts ? commentBadge(sessionObjectRef(e.sessionId), counts) : ""; - // #1156 + #1152: session actions (poke/answer/stop by source support) - // and, for tiered entries, the triage set — session-derived items - // stay actionable even when the tier source is down (the session - // feed is live), so no disabledReason ever applies here. - const objectRef = sessionObjectRef(e.sessionId); - const own = act?.actionsByObject?.get(objectRef); - const badges = actionBadgesHtml(own); - const cs = cardState(own); - let controls = ""; - if (act?.identities) { - const sessionBox = sessionActionsHtml(e.sessionId, sourceOf(e), { identities: act.identities }); - const triageBox = - e.tier === "needs-drew" || e.tier === "needs-orchestrator" - ? triageActionsHtml(objectRef, e.tier, { identities: act.identities }, "", cs) - : ""; - controls = `${sessionBox}${triageBox}`; - } - // #1445/#1446: inline detail (state + full action history) and the - // per-card comment box ride the session card too. - const detail = `
    Details & history
    Session
    ${esc(e.sessionId)}
    State
    ${esc(STATE_LABELS[e.state] ?? e.state)}
    Last activity
    ${esc(fmtDate(e.lastActivityAt))}
    Ref
    ${esc(objectRef)}
    ${actionHistoryHtml(own)}
    `; - const commentBox = - act?.identities && act.commentOpts - ? cardCommentHtml(objectRef, undefined, act.commentsByObject?.get(objectRef), act.commentOpts) - : ""; - return `
    ${esc(e.title ?? e.sessionId)} ${esc(src)} ${esc(STATE_LABELS[e.state])}${tierBadge}${cs.acked ? ` Acknowledged` : ""}${sub}${cmt}${badges}
    ${esc(e.sessionId)} · ${esc(e.directory ?? "—")}${e.branch ? ` · ${esc(e.branch)}` : ""} · ${esc(e.model ?? "—")}${e.provider ? ` / ${esc(e.provider)}` : ""} · last activity ${fmtDate(e.lastActivityAt)} · ${esc(e.messageCount ?? "—")} msgs${e.outcome ? ` · outcome: ${esc(e.outcome)}` : ""}
    ${esc(evidence)}${reason}${orch}${controls}${detail}${commentBox}${kidsHtml}
    `; -} - -/** A #899 tier item that is not a live session — a decision, task, or gap. */ -function tierItemCard( - item: TierItem, - whyLabel: string, - counts?: Map, - act?: { - actions?: DashAction[]; - identities?: AuthorIdentity[]; - disabledReason?: string; - comments?: DashComment[]; - commentOpts?: CommentFormOpts; - }, -): string { - const blocked = item.blockedBy?.length - ? `
    Blocked by: ${item.blockedBy - .map((d) => esc(`${d.task} (${d.status}${d.workerLabel ? `, ${d.workerLabel}` : ""})`)) - .join("; ")}` - : ""; - const question = item.question ? `
    “${esc(item.question)}”` : ""; - const action = item.recommendedAction - ? `
    Recommended: ${esc(item.recommendedAction)}` - : ""; - // A tier item's ref is only sometimes a GitHub ref: tracked-goal items - // carry their goal id (e.g. "goal_…"), and refUrl throws on those — one - // such item 500ed the whole Needs-you render (phase-b inventory, - // 2026-11-05). Non-GitHub refs render as plain code, never a link. - const refLink = item.ref - ? isValidRef(item.ref) - ? `${esc(item.ref)}` - : `${esc(item.ref)}` - : ""; - const ref = item.ref ? `
    ${refLink}` : ""; - const cmt = counts ? commentBadge(tierItemObjectRef(item), counts) : ""; - const badges = actionBadgesHtml(act?.actions); - // #1291: on Needs User cards, the item's own contract renders — the - // why-class badge in the header, the summary / if-ignored / - // delegation / proposal / inability block in the body, and the - // options / survey / delegation / dismiss forms in the actbox. - const isUserTier = whyLabel === "Why you"; - const objectRef = tierItemObjectRef(item); - const cs = cardState(act?.actions); - const extBody = isUserTier ? needsUserBodyHtml(item, act?.actions) : ""; - const extForms = isUserTier ? needsUserFormsHtml(item, objectRef, Date.now(), cs) : ""; - // #1152: the triage control set. Section-derived items disable with - // the reason when the tier source is absent/invalid (#1139 state) — - // the item may not exist in the publisher's current view. - const controls = act?.identities - ? triageActionsHtml( - objectRef, - isUserTier ? "needs-drew" : "needs-orchestrator", - { - identities: act.identities, - ...(act.disabledReason ? { disabledReason: act.disabledReason } : {}), - }, - extForms, - cs, - ) - : ""; - // #1445: the title itself links to the GitHub issue when the card - // carries a gh: ref, and every card expands inline to its full - // detail — source, state, since/lastSeenAt, horizon, blockedBy, - // the question payload, and the recorded action history. - const titleHtml = - item.ref && isValidRef(item.ref) ? `${esc(item.title)}` : esc(item.title); - const questionPayload = item.questions?.length - ? `
    Questions
    ${item.questions - .map( - (q) => - `${esc(q.prompt)} (covers: ${esc(q.covers)}${q.required ? "" : "; optional"})`, - ) - .join("
    ")}
    ` - : item.question - ? `
    Question
    “${esc(item.question)}”
    ` - : ""; - const detail = `
    Details & history
    Source
    ${esc(item.source)} · ${esc(item.kind)}${item.state ? ` · state ${esc(item.state)}` : ""}
    Since
    ${esc(fmtDate(item.since))}
    Last seen
    ${esc(fmtDate(item.lastSeenAt))}
    ${item.horizon ? `
    Horizon
    ${esc(item.horizon)}
    ` : ""}
    Ref
    ${esc(objectRef)}${item.ref ? ` · ${refLink}` : ""}
    ${item.blockedBy?.length ? `
    Blocked by
    ${item.blockedBy.map((d) => esc(`${d.task} (${d.status}${d.workerLabel ? `, ${d.workerLabel}` : ""})`)).join("; ")}
    ` : ""}${questionPayload}
    ${actionHistoryHtml(act?.actions)}
    `; - const commentBox = - act?.identities && act.commentOpts ? cardCommentHtml(objectRef, item.ref, act.comments, act.commentOpts) : ""; - return `
    ${esc(item.source)} ${esc(item.kind)}${isUserTier ? whyUserBadge(item) : ""}${cs.acked ? ` Acknowledged` : ""} ${titleHtml}${cmt}${badges}

    ${esc(whyLabel)}: ${esc(item.reason)}${question}${blocked}${action}${extBody}${ref}${controls}${detail}${commentBox}
    `; -} - -export interface AttentionAct { - actionsByObject?: Map; - identities?: AuthorIdentity[]; - commentsByObject?: Map; - commentOpts?: CommentFormOpts; - /** #1456: the effective Needs-you card order + its pending state. */ - needsOrder?: NeedsOrder; - needsOrderPending?: boolean; -} - -interface StripEntry { - objectRef: string; - title?: string; - cs: CardState; -} - -/** One suppressed card in a strip (#1443/#1450): what happened, when it - * lifts, and the way back — Unsnooze for a snooze (a superseding - * snooze at "now"), Restore for a dismiss / mark-done (a restore - * action superseding the suppressor). */ -function stripCardHtml(entry: StripEntry, identities: AuthorIdentity[] | undefined): string { - const sup = entry.cs.suppressed!; - const refLink = `${entry.title ? esc(entry.title) : `${esc(entry.objectRef)}`}`; - if (sup.kind === "snoozed") { - const a = sup.action; - const stateLine = - a.state === "new" - ? `⏳ sent · pending — snooze until ${esc(fmtDate(sup.until))}` - : `applied by ${esc(a.appliedByRun ?? "a fleet run")} — snoozed until ${esc(fmtDate(sup.until))}`; - const unsnooze = - identities !== undefined - ? actboxHtml( - { identities }, - aformHtml({ - kind: "triage", - verb: "snooze", - objectRef: entry.objectRef, - supersedes: a.id, - inner: ``, - }), - ) - : ""; - return `
    💤 ${refLink} snoozed until ${esc(fmtDate(sup.until))}
    ${stateLine}${a.resultNote ? ` — ${esc(a.resultNote)}` : ""}${unsnooze}
    `; - } - const a = sup.action; - const label = sup.kind === "done" ? "✓ marked done by you" : "dismissed by you"; - const stateLine = - a.state === "new" - ? "⏳ sent · pending" - : a.state === "applied" - ? `applied by ${esc(a.appliedByRun ?? "a fleet run")}` - : a.state; - const restore = - identities !== undefined - ? actboxHtml( - { identities }, - aformHtml({ - kind: "triage", - verb: "restore", - objectRef: entry.objectRef, - supersedes: a.id, - inner: `Records a restore that supersedes the ${sup.kind === "done" ? "mark-done" : "dismiss"} — the card returns with its history intact.`, - }), - ) - : ""; - return `
    ${refLink} ${label}
    ${stateLine}${a.payload.reason ? ` — reason: ${esc(a.payload.reason)}` : ""}${a.resultNote ? ` · ${esc(a.resultNote)}` : ""} · ${esc(relTime(a.createdAt))}${restore}
    `; -} - -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 `
    Bulk triage${authorSelectHtml(act.identities)}0 selected
    `; -} - -/** - * 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 = `

    All decision sets

    `; - const footer = `

    Live from the decision-set store at page load.

    `; - if (summaries === null) { - return `

    Questions

    Unavailable — the decision-set store could not be read, so open questions cannot be reported here.

    ${allSetsLink}${footer}
    `; - } - const open = summaries.filter((s) => s.openQuestions > 0).sort((a, b) => b.createdAt.localeCompare(a.createdAt)); - if (!open.length) { - return `

    Questions

    No open questions right now — the stack is clear.

    ${allSetsLink}${footer}
    `; - } - const totalOpen = open.reduce((n, s) => n + s.openQuestions, 0); - const rows = open - .map((s) => { - const stamp = Number.isFinite(Date.parse(s.createdAt)) - ? QUESTIONS_STAMP.format(new Date(s.createdAt)) - : s.createdAt; - return `
    ${esc(s.title)}
    ${s.openQuestions} open question${s.openQuestions === 1 ? "" : "s"} · ${s.items} item${s.items === 1 ? "" : "s"} · ${s.questions} question${s.questions === 1 ? "" : "s"} · Raised ${esc(stamp)}
    `; - }) - .join(""); - return `

    Questions

    ${open.length} open set${open.length === 1 ? "" : "s"} · ${totalOpen} open question${totalOpen === 1 ? "" : "s"}

    ${rows}${allSetsLink}${footer}
    `; -} - -export function renderAttention( - view: AttentionView, - coverage: SourceCoverage[], - provenance: Provenance, - counts?: Map, - detail?: ProvenanceDetail, - act?: AttentionAct, - briefs?: Map, - census?: NeedsDrewCensus | null, - questionsHtml = "", -): string { - const sections = attentionSections(view, coverage, counts, act, briefs, census); - return layout( - "Needs you", - `

    Needs you

    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.

    `; - } - const failed = census.sources.filter((x) => !x.ok || x.truncated || x.incomplete); - const failureNote = failed.length - ? `` - : ""; - // 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 => - `
  • ${esc(i.ref)} ${i.kind === "pr" ? "(PR) " : ""}${esc(i.title)} — ${i.needsLabels - .map((l) => `${esc(l)}`) - .join(" ")} — ${note} (updated ${esc(i.updatedAt)})
  • `; - 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}.

    `; - const reviewRows = review.length - ? `
      ${review.map((i) => line(i, reasonOf(i))).join("")}
    ` - : `

    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.

      ${parked - .map((i) => line(i, reasonOf(i))) - .join("")}
    ` - : `

    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" - ? `` - : `` - : ts.state === "stale" - ? `` - : ""; - 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 = ``; - // #1290/#1291: the standing delegation-default toggle — a dashboard - // preference, so it renders whenever the action surface is up; its - // state comes from the preference records in the store. - const delegationDefault = act?.identities - ? delegationDefaultHtml(act.actionsByObject?.get(DELEGATION_DEFAULT_OBJECT_REF), { - identities: act.identities, - }) - : ""; - const header = `${tierBanner}${chips} -${coverageHtml(coverage)} -${delegationDefault}`; - const drewCards = - drewCardsList.map((c) => c.html).join("") || - (ts.present - ? `

    Nothing in the user queue right now.

    ` - : `

    Unknown — the tier source is missing, so this queue cannot be reported.

    `); - const orchCards = - orchCardsList.join("") || - (ts.present - ? `

    The fleet's queue is empty.

    ` - : `

    Unknown — the tier source is missing, so this queue cannot be reported.

    `); - const snoozedStrip = snoozedList.length - ? `

    Snoozed by you (${snoozedList.length})

    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.

    ${orchCards}${needsDrewCensusHtml(census)}`; - const sessionCards = roots.length - ? roots.map((e) => sessionCard(e, children, 0, counts, sessionAct)).join("") - : `

    No current sessions.

    `; - const sessions = `

    All sessions (${roots.length})

    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"]) : "", - ); -} - -// --- Today view (slice 2, #898 §4) ------------------------------------------- - -function todayHealthStrip(health: HealthView | null, quota: QuotaView, quotaUnavailable: boolean): string { - const compactAge = (ageMs: number) => ageMsText(ageMs).replace(/ old$/, ""); - const stackServices = - health?.services.filter( - (service) => service.def.probe !== "feed" && service.def.probe !== "section" && service.def.probe !== "off", - ) ?? []; - const stackUp = stackServices.filter((service) => service.ok === true).length; - const stackDown = stackServices.filter((service) => service.ok === false); - const stackUnknown = stackServices.filter((service) => service.ok === null); - const stackText = - !health || health.mode !== "live" || stackServices.length === 0 - ? "stack unknown" - : `stack ${stackUp}/${stackServices.length} up${stackDown.length ? ` · ${stackDown.map((service) => service.def.name).join(", ")} down` : ""}${stackUnknown.length ? ` · unknown: ${stackUnknown.map((service) => service.def.name).join(", ")}` : ""}`; - const stackState = - !health || health.mode !== "live" || stackServices.length === 0 - ? "unknown" - : stackDown.length - ? "warn" - : stackUnknown.length - ? "unknown" - : "ok"; - - const feedAge = health?.feed.ageMs; - const feedDown = health?.services.some((service) => service.def.id === "fleet-feed" && service.ok === false) ?? false; - const feedState = - feedDown || (feedAge !== null && feedAge !== undefined && feedAge > 15 * 60_000) - ? "warn" - : feedAge === null || feedAge === undefined - ? "unknown" - : "ok"; - const feedText = feedAge === null || feedAge === undefined ? "feed unknown" : `feed ${compactAge(feedAge)}`; - - const orchestration = health?.jobs.orchestration; - const orchestrationState = - !orchestration || orchestration.state === "unknown" - ? "unknown" - : orchestration.state === "live" && orchestration.ageMs !== undefined - ? "ok" - : "warn"; - const orchestrationText = - !orchestration || orchestration.state === "unknown" - ? "orchestrator unknown" - : orchestration.state === "live" - ? orchestration.ageMs === undefined - ? "orchestrator age unknown" - : `orchestrator ${compactAge(orchestration.ageMs)}` - : `orchestrator ${orchestration.state}`; - - const heartbeatOnly = quota.gatherer?.source === "standalone-heartbeat"; - const poolErrors = quota.pools.filter((pool) => pool.state === "error" || pool.freshness?.state === "error"); - const providerErrors = quota.gatherer?.providers.filter((provider) => provider.state === "error") ?? []; - // A standalone tick is not a replacement quota measurement. Preserve base - // pool failures and include heartbeat failures, deduplicating known services. - const quotaErrors = heartbeatOnly - ? new Set([...poolErrors.map((pool) => pool.id), ...providerErrors.map((provider) => provider.serviceId)]).size - : quota.gatherer - ? providerErrors.length - : poolErrors.length; - const quotaUnknown = - quotaUnavailable || ((!quota.gatherer || heartbeatOnly) && quota.pools.length === 0 && quotaErrors === 0); - const quotaState = quotaUnknown ? "unknown" : quotaErrors ? "warn" : quota.gatherer?.ok === false ? "unknown" : "ok"; - const quotaText = quotaUnknown - ? "quota unknown" - : quotaErrors - ? `quota errors ${quotaErrors}` - : quota.gatherer?.ok === false - ? "quota reads unknown" - : "quota reads OK"; - - const items = [ - { text: stackText, state: stackState, href: "/health", title: "Stack service health" }, - { text: feedText, state: feedState, href: "/health", title: "Fleet feed freshness" }, - { text: orchestrationText, state: orchestrationState, href: "/health", title: "Orchestration freshness" }, - { text: quotaText, state: quotaState, href: "/quota", title: "Quota read status" }, - ]; - return `
    ${items.map((item) => `${esc(item.text)}`).join("")}
    `; -} - -/** The today page's body alone (#1444 fragment payload). */ -export function renderTodayBody( - today: TodayView, - attention: AttentionView, - quota: QuotaView, - coverage: SourceCoverage[], - health: HealthView | null = null, - quotaUnavailable = false, - queue?: QueueView, - queueStale = false, - questionsHtml = "", -): string { - const walled = quota.pools.filter((p) => p.state === "walled"); - const quotaActions = buildQuotaActions(quota, AA_PLAN_FACTS); - // "-direct" display rule (#6125), judged over this view's pool set. - const poolDisplayNames = providerDisplayNames(quota.pools.map((p) => p.provider)); - const displayPoolProvider = (name: string) => poolDisplayNames.get(name) ?? name; - const alerts: string[] = []; - const drewTotal = attention.drew.length + attention.drewExtra.length; - if (drewTotal) { - alerts.push( - ``, - ); - } - // #1174: the same eligible quota actions as /quota's strip and - // /attention's orchestrator tier, derived once above — never a - // second list. Walled pools without a typed action still banner. - for (const a of quotaActions) { - alerts.push( - ``, - ); - } - for (const p of walled.filter((p) => !quotaActions.some((a) => a.poolId === p.id))) { - alerts.push( - ``, - ); - } - const wipViolations = (today.wipLanes ?? []).flatMap((lane) => [ - ...(lane.overCap ? [`${lane.lane} ${lane.count}/${lane.cap}`] : []), - ...lane.projects - .filter((scope) => scope.overCap) - .map((scope) => `project ${scope.key} · ${lane.lane} ${scope.count}/${scope.cap}`), - ...lane.epics - .filter((scope) => scope.overCap) - .map((scope) => `epic ${scope.key} · ${lane.lane} ${scope.count}/${scope.cap}`), - ]); - if (wipViolations.length) { - alerts.push( - ``, - ); - } - // #1139: the derived view's banner names the section's TRUE state — - // absent, invalid, and stale are different failures, and "has not - // published yet" is only honest for one of them. - const diag = today.sectionDiagnosis; - const staleBanner = - today.fromOrchestrator && diag?.state === "stale" - ? `` - : ""; - const provenanceLine = today.fromOrchestrator - ? `

    From the orchestration job's goal measurements (section written ${fmtDate(today.generatedAt)}). Machine-first: /api/today.json · /api/orchestration.json.

    ${staleBanner}` - : diag?.state === "invalid" - ? `` - : diag?.state === "stale" - ? `` - : ``; - const actions = today.actions?.length - ? `

    Pushed back into motion

    ${today.actions.map((a) => `
    ${esc(a.kind)} ${esc(a.target)}
    ${esc(a.summary)}
    ${esc(fmtDate(a.at))}
    `).join("")}` - : ""; - const quotaObjectives: TodayObjective[] = quotaActions.map((a) => ({ - title: a.title, - detail: a.detail, - chip: "quota · action", - })); - const allObjectives = [...today.objectives, ...quotaObjectives]; - // #6174: an objective ref comes from publisher lined-up data and is - // only sometimes a GitHub ref — tracked-goal items carry their goal id, - // and refUrl throws on those, which 500ed the whole /today render (the - // Today-page sibling of the #6149 Needs-you fix). Mirror tierItemCard: - // GitHub refs link, everything else renders as plain code. - const objectives = allObjectives.length - ? allObjectives - .map( - (o, i) => - `
    ${i + 1}
    ${esc(o.title)} ${esc(o.chip)}${o.detail ? `
    ${esc(o.detail)}` : ""}${o.statusNote ? `
    ${esc(o.statusNote)}` : ""}${o.ref ? `
    ${isValidRef(o.ref) ? `${esc(o.ref)}` : `${esc(o.ref)}`}` : ""}
    `, - ) - .join("") - : `

    No objectives lined up for today.

    `; - const momentum = today.momentum.length - ? today.momentum - .map((m) => { - // Defensive: a TodayView built outside derive.ts may still - // carry a non-array `accomplished` (e.g. a bare string) — - // coerce instead of crashing the whole /today render. - const rawAccomplished: unknown = m.accomplished; - const accomplished = ( - Array.isArray(rawAccomplished) ? rawAccomplished : rawAccomplished ? [rawAccomplished] : [] - ).map((a) => String(a)); - const done = accomplished.length - ? `
    Recently accomplished:
      ${accomplished.map((a) => `
    • ${esc(a)}
    • `).join("")}
    ` - : ""; - const blocked = m.blockedBy ? `
    Blocked by: ${esc(m.blockedBy)}` : ""; - const detail = m.detail ? `
    ${esc(m.detail)}` : ""; - return `
    ${esc(m.project)} ${esc(m.state)}${done}${blocked}${detail}
    `; - }) - .join("") - : `

    No projects to measure yet.

    `; - const nextUp = queue - ? `

    Next up ${Math.min(queue.nextUp.length, 5)}${queueStale ? ' stale inputs' : ""}

    The next queued work, in the published horizon order.

    ${queueRows(queue.nextUp.slice(0, 5), "Nothing is queued for the next pick.")}
    ` - : ""; - return `${todayHealthStrip(health, quota, quotaUnavailable)}${provenanceLine}${alerts.join("")} -

    Top objectives

    ${objectives} -

    Project momentum

    ${momentum} -${nextUp}${questionsHtml}${actions}${coverageHtml(coverage)}`; -} - -/** The today page (#1444): full server render. */ -export function renderToday( - today: TodayView, - attention: AttentionView, - quota: QuotaView, - coverage: SourceCoverage[], - provenance: Provenance, - detail?: ProvenanceDetail, - health: HealthView | null = null, - quotaUnavailable = false, - queue?: QueueView, - queueStale = false, - questionsHtml = "", -): string { - return layout( - "Today", - `

    Today

    ${renderTodayBody(today, attention, quota, coverage, health, quotaUnavailable, queue, queueStale, questionsHtml)}`, - provenance, - "/today", - "", - detail ? freshnessChips(detail, ["orchestration", "quota", "attention"]) : "", - ); -} - -/** The Datastar shell for /today (#1444). */ -export function renderTodayShell( - provenance: Provenance, - detail: ProvenanceDetail | undefined, - health: HealthView | null, - quota: QuotaView, - quotaUnavailable = false, - questionsHtml = "", -): string { - return layout( - "Today", - `

    Today

    ${todayHealthStrip(health, quota, quotaUnavailable)}
    Loading today…
    ${questionsHtml}`, - provenance, - "/today", - FRAG_WATCHDOG_SCRIPT, - detail ? freshnessChips(detail, ["orchestration", "quota", "attention"]) : "", - ); -} - -// --- Queue visibility (#1160) ----------------------------------------------- - -function queueRows(rows: QueueRow[], empty: string): string { - if (!rows.length) return `

    ${esc(empty)}

    `; - return `
    ${rows - .map((item) => { - const area = item.area ? `${item.area} · ${item.repo}` : item.repo; - const blocked = item.status.toLowerCase().includes("block"); - const age = - item.ageDays === undefined - ? blocked - ? "block age unknown" - : "age unknown" - : blocked - ? `block state last updated ${item.ageDays}d ago` - : item.ageDays === 0 - ? "updated today" - : `${item.ageDays}d since update`; - const blockers = item.blockedBy?.length - ? `
    Blocked by: ${item.blockedBy.map(esc).join("; ")}` - : ""; - const worker = item.worker ? `
    Worker: ${esc(item.worker)}` : ""; - const epic = item.epic - ? item.epic.url - ? `
    Epic: ${esc(item.epic.title)}` - : `
    Epic: ${esc(item.epic.title)}` - : ""; - const why = item.why ? `
    ${esc(item.why)}` : ""; - const signals = item.signals?.length - ? `
    ${item.signals - .map( - (signal) => - `${signal === "project-status" ? "Project Status" : signal === "active-session" ? "Active session" : "Open PR"}`, - ) - .join(" ")}` - : ""; - const clash = item.disagreement - ? ` ⚠ project: ${esc(item.disagreement.project)} · derived: ${esc(item.disagreement.derived)}` - : ""; - const horizon = item.horizon ? ` · ${esc(item.horizon)}` : ""; - const title = item.url ? `${esc(item.title)}` : esc(item.title); - return `
    ${esc(area)} ${esc(item.status)}${horizon}
    ${title}${item.ref ? `
    ${esc(item.ref)}` : ""}
    ${esc(age)} · ${esc(item.source)}${signals}${clash}${epic}${why}${blockers}${worker}
    `; - }) - .join("")}
    `; -} - -/** The queue page body is also the Datastar fragment and JSON's source view. */ -export function renderQueueBody(view: QueueView): string { - return `

    Cross-project work, reconciled from the existing board, Project pool, and orchestration inputs. Counts are the rows shown; machine-first: /api/queue.json. Updated ${esc(fmtDate(view.generatedAt))}.

    -

    In progress ${view.inProgress.length}

    ${queueRows(view.inProgress, "Nothing is in progress.")} -

    Blocked ${view.blocked.length}

    ${queueRows(view.blocked, "Nothing is blocked.")} -

    Done recently ${view.doneRecently.length}

    Completed or merged in the last 7 days; retired bookkeeping cards are excluded.

    ${queueRows(view.doneRecently, "Nothing completed in the last 7 days.")} -

    Next up ${view.nextUp.length}

    Queued work ordered by the published horizon ladder.

    ${queueRows(view.nextUp, "Nothing is queued for the next pick.")}`; -} - -export function renderQueue(view: QueueView, provenance: Provenance, detail?: ProvenanceDetail): string { - return layout( - "Queue", - `

    Queue visibility

    ${renderQueueBody(view)}`, - provenance, - "/queue", - "", - detail ? freshnessChips(detail, ["board", "orchestration", "items"]) : "", - ); -} - -export function renderQueueShell(provenance: Provenance, detail?: ProvenanceDetail): string { - return layout( - "Queue", - `

    Queue visibility

    Loading queue…
    `, - provenance, - "/queue", - FRAG_WATCHDOG_SCRIPT, - detail ? freshnessChips(detail, ["board", "orchestration", "items"]) : "", - ); -} - -// --- Overview / front door (#1134) ------------------------------------------- -// "/" is the stack front door: one glance at what needs Drew, what is -// moving, what is broken, and where the quotas sit. Every number here -// is derived from the same source views the dedicated pages render -// (attention, the Project pool, quota, health, the board) — the -// overview owns no data of its own, so its counts cannot drift from -// their source pages. deriveOverview is pure, so the HTML page and -// /api/overview.json serve the identical summary. - -export interface OverviewData { - attention: AttentionView; - pool: ProjectPoolItem[]; - quota: QuotaView; - health: HealthView; - board: BoardItem[]; - /** Resolved board refs, used to distinguish open linked PRs. */ - items?: Map; - /** The same line-up source used by /projects for disagreement badges. */ - orchestration?: OrchestrationSection | null; - /** Dashboard actions by object ref, so the needs-you summary applies - * the same render-time suppression as /attention (Codex review on - * PR 2424). Absent in tests and fixture renders: nothing suppressed. */ - actionsByObject?: Map; -} - -export type OverviewInProgressSignal = InProgressSignal; - -export type OverviewInProgressItem = ReconciledInProgressItem; - -export interface OverviewSummary { - /** count is null when the tier source is not present: the queue is - * unknown, never a confident zero (Codex review on PR 2424). */ - needsYou: { count: number | null; tierState: string; top: { title: string; detail?: string }[] }; - projects: { repo: string; total: number; inProgress: number; inReview: number; done: number }[]; - quota: { provider: string; plan: string; state: QuotaState; worstPercent: number | null }[]; - health: { degraded: boolean; up: number; down: number; total: number; feedAgeMs: number | null }; - recentDone: { title: string; repo: string }[]; - inProgress: OverviewInProgressItem[]; -} - -export function deriveOverview(data: OverviewData): OverviewSummary { - // The needs-you summary must agree with /attention on the same data: - // suppressed entries (snoozed / dismissed / marked done — pending - // counts, exactly as on the attention page) leave the count and the - // top list, and when the tier source is not present the count is - // unknown rather than an authoritative number over a partial queue. - const now = Date.now(); - const suppressed = (objectRef: string): boolean => - cardState(data.actionsByObject?.get(objectRef), now).suppressed !== null; - const drewVisible = data.attention.drew.filter((e) => !suppressed(sessionObjectRef(e.sessionId))); - const drewExtraVisible = data.attention.drewExtra.filter((item) => !suppressed(tierItemObjectRef(item))); - const tierPresent = data.attention.tierSource.present; - const top: { title: string; detail?: string }[] = tierPresent - ? [ - ...drewExtraVisible.map((t) => ({ title: t.title, detail: t.reason })), - ...drewVisible.map((e) => ({ title: e.title ?? e.sessionId, detail: e.drewReason })), - ].slice(0, 5) - : []; - const byRepo = new Map(); - for (const item of data.pool) { - const row = byRepo.get(item.repo) ?? { repo: item.repo, total: 0, inProgress: 0, inReview: 0, done: 0 }; - row.total += 1; - if (item.status === "In Progress") row.inProgress += 1; - else if (item.status === "In Review") row.inReview += 1; - else if (item.status === "Done") row.done += 1; - byRepo.set(item.repo, row); - } - // "-direct" display rule (#6125), judged over this view's pool set. - const quotaDisplayNames = providerDisplayNames(data.quota.pools.map((pool) => pool.provider)); - const quota = data.quota.pools.map((pool) => { - // #1134 review (Codex P2): derive from used/limit with the shared - // helper — a window that carries `used` and `limit` but no explicit - // `percent` must not silently drop out of the tightest-window figure. - const percents = pool.windows.map((w) => windowPercent(w)); - return { - provider: quotaDisplayNames.get(pool.provider) ?? pool.provider, - plan: pool.plan, - state: pool.state, - worstPercent: percents.length ? Math.max(...percents) : null, - }; - }); - const services = data.health.services; - const byRecency = (a: BoardItem, b: BoardItem) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""); - return { - needsYou: { - count: tierPresent ? drewVisible.length + drewExtraVisible.length : null, - tierState: data.attention.tierSource.state, - top, - }, - projects: [...byRepo.values()].sort((a, b) => b.total - a.total || a.repo.localeCompare(b.repo)), - quota, - health: { - degraded: data.health.degraded, - up: services.filter((svc) => svc.ok === true).length, - down: services.filter((svc) => svc.ok === false).length, - total: services.length, - feedAgeMs: data.health.feed.ageMs, - }, - recentDone: data.board - .filter((b) => b.status === "done") - .sort(byRecency) - .slice(0, 5) - .map((b) => ({ title: b.title, repo: b.repo })), - inProgress: reconciledInProgress(data), - }; -} - -export function renderOverviewBody(summary: OverviewSummary): string { - // #1134 review (Codex P2): the stale note is about the tier source, not - // about the count, so an empty last published queue must still say it. - const staleNote = `

    Tier source stale — this is its last published state and may have moved since.

    `; - const needs = - summary.needsYou.count === null - ? `` - : summary.needsYou.count - ? `${summary.needsYou.tierState === "stale" ? staleNote : ""}` - : `

    Nothing needs you right now.

    ${summary.needsYou.tierState === "stale" ? staleNote : ""}`; - const topItems = summary.needsYou.top.length - ? `
      ${summary.needsYou.top.map((t) => `
    • ${esc(t.title)}${t.detail ? ` — ${esc(t.detail)}` : ""}
    • `).join("")}
    ` - : ""; - const projectCards = summary.projects.length - ? summary.projects - .map( - (proj) => - `
    ${esc(proj.repo)} ${proj.total} tracked
    ${proj.inProgress} in progress · ${proj.inReview} in review · ${proj.done} done — projects
    `, - ) - .join("") - : `

    No Project pool items collected yet.

    `; - const quotaStrip = summary.quota.length - ? summary.quota - .map((pool) => { - const pct = pool.worstPercent !== null ? ` · ${Math.round(pool.worstPercent)}% of tightest window` : ""; - return `
    ${esc(pool.provider)} ${esc(pool.plan)} ${esc(pool.state)}${pct}
    `; - }) - .join("") - : `

    No quota pools measured yet.

    `; - const healthStrip = `
    ${summary.health.up} of ${summary.health.total} services up${summary.health.down ? ` · ${summary.health.down} down` : ""}${summary.health.degraded ? ` · degraded` : ""}${summary.health.feedAgeMs !== null ? ` · feed ${esc(ageMsText(summary.health.feedAgeMs))} old` : ""} — health
    `; - // #1116 item (5): when the feed itself has crossed the staleness - // threshold the dashboard must say so visibly — a "feed X old" suffix - // is not an actionable warning. The data-signal hook is what the - // age-feed drill greps for as its rendered-page evidence. - const feedAgeMs = summary.health.feedAgeMs; - const feedStaleBanner = - feedAgeMs !== null && feedAgeMs >= FEED_STALE_MS - ? `` - : ""; - const itemList = (items: { title: string; repo: string }[], empty: string) => - items.length - ? `
      ${items.map((i) => `
    • ${esc(i.title)}${i.repo ? ` ${esc(i.repo)}` : ""}
    • `).join("")}
    ` - : `

    ${empty}

    `; - const inProgressItems = summary.inProgress.length - ? `
      ${summary.inProgress - .map((item) => { - const signals = item.signals - .map( - (signal) => - `${signal === "project-status" ? "Project Status" : signal === "active-session" ? "Active session" : "Open PR"}`, - ) - .join(" "); - const clash = item.disagreement - ? ` ⚠ project: ${esc(item.disagreement.project)} · derived: ${esc(item.disagreement.derived)}` - : ""; - return `
    • ${esc(item.title)} ${esc(item.repo)} ${signals}${clash}
    • `; - }) - .join("")}
    ` - : `

    Nothing in progress from the Project, active-session, or open-PR signals.

    `; - return `

    One glance at the whole stack: what needs you, what is moving, what is broken, and where the quotas sit. Every number is the same one its source page shows. Machine-first: /api/overview.json.

    -

    Needs you (${summary.needsYou.count ?? "unknown"})

    ${needs}${topItems} -

    Projects

    ${projectCards} -

    Quota

    ${quotaStrip} -

    Health

    ${feedStaleBanner}${healthStrip} -

    In progress

    ${inProgressItems} -

    Recently done

    ${itemList(summary.recentDone, "Nothing done on the board yet.")} -

    In progress reconciles Project Status, active sessions lined up, and open PRs; recently done is the board's lane — the full curated cross-repo board is a drill-down from here: Board →

    `; -} - -/** The overview page (#1134): full server render. */ -export function renderOverview(data: OverviewData, provenance: Provenance, detail?: ProvenanceDetail): string { - return layout( - "Overview", - `

    Overview

    ${renderOverviewBody(deriveOverview(data))}`, - provenance, - "/", - "", - detail ? freshnessChips(detail, ["board", "quota", "attention"]) : "", - ); -} - -/** The Datastar shell for / (#1134, on the #1444 pattern). */ -export function renderOverviewShell(provenance: Provenance, detail?: ProvenanceDetail): string { - return layout( - "Overview", - `

    Overview

    Loading the overview…
    `, - provenance, - "/", - FRAG_WATCHDOG_SCRIPT, - detail ? freshnessChips(detail, ["board", "quota", "attention"]) : "", - ); -} - -// --- DNS register page (#906 §1, data from #902) ----------------------------- - -function dnsTable(entries: DnsEntry[], renewingSoon: Set, nextRenewal?: DnsEntry | null): string { - const rows = entries - .map( - (e) => - `${esc(e.domain)}${esc(e.renewal)}${e.priceUsd != null ? `$${e.priceUsd.toFixed(2)}` : "—"}${esc(e.autoRenew)}${esc(e.plan)}${esc(e.review)}`, - ) - .join(""); - return `
    ${rows || ''}
    Domain register
    DomainNext renewalPrice (list)Auto-renewPlan / statusReview?
    none
    `; -} - -const DNS_FILTER_SCRIPT = ``; - -export function renderDns(section: DnsSection | null, provenance: Provenance, detail?: ProvenanceDetail): string { - const chips = detail ? freshnessChips(detail, ["dns"]) : ""; - if (!section) { - return layout( - "DNS register", - `

    DNS / domain register

    `, - provenance, - "/dns", - "", - chips, - ); - } - const s = summarizeDns(section); - const next = s.nextRenewal; - const soonTotal = Math.round(s.renewingSoon.reduce((sum, e) => sum + (e.priceUsd ?? 0), 0) * 100) / 100; - const renewingSoon = new Set(s.renewingSoon); - const filters = [ - ["all", "All", section.entries.length], - ["active", "Active", s.active.length], - ["earmarked", "Earmarked", s.earmarked.length], - ["unused", "Unused", s.unused.length], - ["renewing-soon", "Renewing soon", s.renewingSoon.length], - ] as const; - const filterChips = filters - .map( - ([filter, label, count], index) => - ``, - ) - .join(""); - const body = `

    DNS / domain register

    -

    ${section.entries.length} domains · $${section.totalAnnualListUsd.toFixed(2)}/yr at list renewal prices · register parsed ${fmtDate(section.generatedAt)} (${esc(section.source)}). The register is maintained by the #902 pipeline — this page renders it, never edits it. Machine-first: /api/dns.json.

    -
    -
    Next renewal
    ${ - next - ? `${esc(next.renewal)}${next.priceUsd != null ? ` · $${next.priceUsd.toFixed(2)}` : ""}
    See its row in the renewal-sorted register.` - : "—" - }
    -
    Renewing in 45 days
    ${s.renewingSoon.length} domain${s.renewingSoon.length === 1 ? "" : "s"} · $${soonTotal.toFixed(2)} at list price
    -
    Auto-renew
    ${s.autoRenew.on} ON · ${s.autoRenew.off} OFF · ${s.autoRenew.unknown} unknown
    -
    Portfolio shape
    ${s.active.length} in use · ${s.earmarked.length} unused but earmarked · ${s.unused.length} completely unused
    -
    -

    Domain register (${section.entries.length})

    -
    ${filterChips}
    -${dnsTable(section.entries, renewingSoon, next)}`; - return layout("DNS register", body, provenance, "/dns", DNS_FILTER_SCRIPT, chips); -} - -// --- AA cost explorer page (ainventory import data via the fleet feed) ----- - -/** - * The Cost Explorer's client side: tabs, the shared filter bar, the - * three frontier charts, and both tables, all rendered from the - * #xpl-data JSON the server embeds (aaPoints + catalog, computed in - * src/aa.ts). Dependency-free inline script, like COMMENT_SCRIPT. - * Written without template literals on purpose — it lives inside one. - */ -const AA_EXPLORER_SCRIPT = ``; - -function fmtCost(v: number | null): string { - return v == null ? "—" : `$${Number(v.toFixed(4))}`; -} - -function fmtSec(v: number | null): string { - if (v == null) return "—"; - if (v < 60) return `${Number(v.toFixed(1))}s`; - return `${Math.floor(v / 60)}m ${Math.round(v % 60)}s`; -} - -function fmtTimed(v: number | null): string { - return v == null ? 'not measured' : fmtSec(v); -} - -/** "openai|gpt-6-luna|max|reasoning|fallback-na" -> "gpt-6-luna · max". */ -function variantLabel(modelVariantKey: string): string { - const parts = modelVariantKey.split("|"); - return parts.length >= 3 ? `${parts[1]} · ${parts[2]}` : modelVariantKey; -} - -function aaTimingsTable(testRuns: AaTestRun[]): string { - const rows = testRuns - .map( - (r) => - `${esc(variantLabel(r.modelVariantKey))}
    ${esc(r.snapshotDate ?? "no snapshot date")}${r.intelligence ?? "—"}${fmtCost(r.costPerTaskUsd)}${fmtTimed(r.ttftSeconds)}${fmtTimed(r.firstAnswerSeconds)}${fmtTimed(r.e2e500Seconds)}${fmtTimed(r.timePerTaskSeconds)}${r.outputSpeedTps ?? "—"}`, - ) - .join(""); - return `
    ${rows || ''}
    Model configurations — intelligence and cost
    ConfigurationIntelligence$/taskTTFTFirst answerE2E (500 tok)Time / taskSpeed (t/s)
    none
    `; -} - -function aaConfigsTable(configs: AaConfig[]): string { - const rows = configs - .map( - (c) => - `${esc(c.modelName)}${esc(c.effort ?? "—")}${c.intelligence ?? "—"}${fmtCost(c.costPerTaskUsd)}${c.speedTps ?? "—"}`, - ) - .join(""); - return `
    ${rows || ''}
    Models — effort, intelligence, cost, and speed
    ModelEffort (AA label)Intelligence$/taskSpeed (t/s)
    none
    `; -} - -function aaCaiTable(rowsIn: AaCaiRow[]): string { - const pct = (v: number | null): string => (v == null ? "—" : `${Number((v * 100).toFixed(1))}%`); - const rows = rowsIn - .map( - (r) => - `${esc(r.family)}
    ${esc(r.creator)}${r.snapshotDate ? ` · ${esc(r.snapshotDate)}` : ""}${esc(r.effort ?? "—")}${esc(r.harness ?? "—")}${esc(r.version ?? "—")}${r.score ?? "—"}${pct(r.deepSwe)}${pct(r.terminalBench)}${pct(r.sweAtlas)}${fmtCost(r.cost)}${fmtTimed(r.wallSec)}${r.tokensPerTask != null ? Math.round(r.tokensPerTask).toLocaleString("en-US") : "—"}`, - ) - .join(""); - return `

    Coding Agent Index observations

    -

    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.

    -
    ${rows || ''}
    Model benchmark scores
    ModelEffortHarnessVersionCAI scoreDeepSWE v1.1Terminal-Bench 4.0SWE-Atlas-QnA$/taskAgent wall time / taskTokens / task
    none
    `; -} - -function aaNameList(names: string[]): string { - return names.length - ? `
    ${names.map((n) => `${esc(n)}`).join("")}
    ` - : '

    none

    '; -} - -/** JSON for a `; - return layout("Cost Explorer", body, provenance, "/aa", AA_EXPLORER_SCRIPT, aaFreshnessChips(detail, section)); -} - -// --- Sessions / identity registry page (#906 §3) ------------------------------ - -const REGISTRY_SOURCE_ORDER = ["opencode-laptop", "opencode-sandbox", "jules", "claude-code", "cron"]; - -export function renderSessions( - records: SessionRecord[], - provenance: Provenance, - detail?: ProvenanceDetail, - act?: { actionsByObject?: Map; identities?: AuthorIdentity[] }, - view?: RegistryView, -): string { - const bySource = new Map(); - for (const r of records) bySource.set(r.source, [...(bySource.get(r.source) ?? []), r]); - const totalTokens = records.reduce((sum, r) => sum + (r.tokensTotal ?? 0), 0); - const groups = [...bySource.entries()] - .sort((a, b) => REGISTRY_SOURCE_ORDER.indexOf(a[0]) - REGISTRY_SOURCE_ORDER.indexOf(b[0])) - .map( - ([source, list]) => - `

    ${esc(source)} (${list.length})

    ${list - .map((r) => - sessionRecordLine(r, { - actions: act?.actionsByObject?.get(sessionObjectRef(r.id)), - identities: act?.identities, - }), - ) - .join("")}`, - ) - .join(""); - // #1209: when the server hands us a RegistryView, the page is one - // windowed/filtered/paginated slice of the store — say so, with the - // hidden counts, a search/filter form, and pagination links. Without - // a view (older callers/tests) the page renders what it was given. - let viewHtml = ""; - if (view) { - const q = view.query; - const windowLabel = q.windowDays === null ? "all history" : `last ${q.windowDays} days`; - const filterBits = [ - q.q ? `search "${esc(q.q)}"` : "", - q.agent ? `agent "${esc(q.agent)}"` : "", - q.task ? `task "${esc(q.task)}"` : "", - ].filter(Boolean); - const hiddenBits = [ - view.hiddenByWindow > 0 ? `${view.hiddenByWindow} hidden by the ${windowLabel} window` : "", - view.hiddenByPagination > 0 ? `${view.hiddenByPagination} more on other pages` : "", - ].filter(Boolean); - const toggle = - q.windowDays === null - ? `last 7 days` - : `all history`; - const prev = - q.offset > 0 - ? `← prev` - : ""; - const next = - view.remainingAfterPage > 0 - ? `next →` - : ""; - viewHtml = `
    ${view.matched} of ${view.totalAll} sessions · window: ${esc(windowLabel)}${filterBits.length ? ` · ${filterBits.join(" · ")}` : ""}${hiddenBits.length ? `
    ${hiddenBits.join(" · ")}` : ""}${view.pinnedIncluded ? `
    A deep-linked session outside this view is pinned at the top of the list.` : ""}
    ${toggle}${prev ? ` · ${prev}` : ""}${next ? ` · ${next}` : ""} -
    `; - } - const body = `

    Sessions — identity registry

    -${viewHtml}

    Every agent/session the fleet can see, with its stable id, the agent identity it ran as, its parent session, and its token total where the source reports one. Task links are loose (from the session's PR, title, or launch record) and improve over time. ${records.length} records shown · ${totalTokens.toLocaleString()} tokens recorded on this page. Machine-first: /api/registry.json.

    -

    Coverage honesty: OpenCode sessions register from their servers; Muse sessions only when a launch record was appended at spawn (scripts/record-claude-launch.ts) — a Muse session that never wrote one is invisible here, and the coverage note on Needs you says which sources are wired.

    -${groups || '

    No sessions recorded yet.

    '}`; - return layout( - "Sessions", - body, - provenance, - "/sessions", - act?.identities ? ACTION_SCRIPT : "", - detail ? freshnessChips(detail, ["registry"]) : "", - ); -} - -// --- All pages (the manifest as a page) --------------------------------------- - -// --- Source-conflict inbox (#1282, slice 1) ----------------------------------- - -/** - * /conflicts — the read-only source-conflict inbox. Every disagreement the - * facets already report, in one queue, grouped by conflict class, each entry - * naming the item, both sources, both values and how long the pair has been - * on record. It resolves nothing: slice 1 projects only, so this page is the - * same list /api/conflicts.json serves, rendered. - */ -export function renderConflicts(inbox: ConflictInbox, provenance: Provenance, detail?: ProvenanceDetail): string { - const chips = detail ? freshnessChips(detail, ["items", "usage"]) : ""; - const ageCell = (entry: ConflictEntry): string => { - if (entry.ageDays === null) return `undated`; - const days = `${entry.ageDays} day${entry.ageDays === 1 ? "" : "s"}`; - const floor = entry.ageBasis === "project-item-updated-at" ? " (floor)" : ""; - return `at least ${days}${floor}
    ${esc(fmtDate(entry.observedAt ?? ""))}${entry.ageBasis === "undated" ? "" : ` · ${esc(entry.ageBasis)}`}`; - }; - const itemCell = (entry: ConflictEntry): string => { - const label = esc(entry.item.title); - if (!entry.item.url) return `${label}`; - return `${label}${entry.item.ref ? `
    ${esc(entry.item.ref)}` : ""}`; - }; - const groups = inbox.byClass - .map((cls) => { - const entries = inbox.entries.filter((e) => e.classId === cls.classId); - if (!entries.length) return ""; - const rows = entries - .map( - (e) => - `${itemCell(e)}${esc(e.sources.a)}
    vs
    ${esc(e.sources.b)}${esc(e.values.a)}
    vs
    ${esc(e.values.b)}${ageCell(e)}${e.href ? `records →` : "—"}`, - ) - .join(""); - return `

    ${esc(cls.label)} (${entries.length})

    -
    ${rows}
    ${esc(cls.label)} — item, sources, both values, age
    ItemSourcesBoth valuesDisagreeing forRecords
    `; - }) - .join(""); - const oldest = - inbox.oldestAgeDays === null ? "—" : `at least ${inbox.oldestAgeDays} day${inbox.oldestAgeDays === 1 ? "" : "s"}`; - const body = `

    Source conflicts

    -

    Every live disagreement the facets already report, in one queue: ${inbox.total} entr${inbox.total === 1 ? "y" : "ies"} across ${inbox.byClass.filter((c) => c.count > 0).length} class${inbox.byClass.filter((c) => c.count > 0).length === 1 ? "" : "es"} · oldest ${oldest} · assembled ${esc(fmtDate(inbox.generatedAt))}. Machine-first: /api/conflicts.json. This page projects; it does not resolve — trust rulings are slice 2 of #1282, so nothing here changes what a render shows.

    -
    -
    Conflicts
    ${inbox.total} live
    -${inbox.byClass.map((c) => `
    ${esc(c.label)}
    ${c.count} live
    `).join("")} -
    Oldest disagreement
    ${oldest}
    -
    -

    Age is a floor, not an exact birthday: it is measured from the newest timestamp the source carries for the pair (a Project item's updatedAt, a service's measuredAt), so the values have disagreed for at least that long — an item edited yesterday for another reason can carry a much older clash.

    -${inbox.total ? groups : ``}`; - return layout("Source conflicts", body, provenance, "/conflicts", "", chips); -} - -export function renderPages(provenance: Provenance, history: PageHealth[] = []): string { - const byRoute = new Map(history.map((p) => [p.route, p])); - const rows = PAGES.map((p) => { - const h = byRoute.get(p.route); - const last = - !h || h.lastRenderedAt === null - ? 'not rendered since this process started' - : `${esc(ageMsText(h.ageMs ?? 0))} · ${h.ok ? "ok" : 'last render failed'}`; - const tier = p.nav === "primary" ? "Primary nav" : "Dropdown-only"; - return `${esc(p.title)}${esc(p.route)}${p.api ? `${esc(p.api)}` : '—'}${tier}${last}${esc(p.blurb)}`; - }).join(""); - return layout( - "All pages", - `

    All pages

    Every registered page, from the manifest in src/pages.ts — the nav bar renders the primary tier, the page dropdown lists them all (#1497). Last-rendered + status come live from the render registry (#1147), the same one Health reports — a page this process has not rendered yet says so, never a fake time. Adding a page is one manifest entry + a render function + a route (recipe in the README).

    ${rows}
    All registered pages
    PageRouteJSON twinNav tierLast renderedWhat it is
    `, - provenance, - "/pages", - ); -} - -// --- Health & topology (#1147 page, #1137 table) --------------------------- - -/** - * The /health page: one view assembled by src/health.ts from live - * probes (cached 60 s), the feed, the section diagnosis, and this - * process's render registry — the same view /api/health serves, so - * the page and the API cannot disagree. States are named per row; a - * failed probe, a stale feed, and an unrendered page all say so. - */ -export function renderHealth(view: HealthView, provenance: Provenance): string { - const nowMs = Date.parse(view.generatedAt); - const probedAge = (iso?: string): string => - iso ? ` · probed ${ageMsText(Math.max(0, nowMs - Date.parse(iso)))}` : ""; - const serviceRows = view.services - .map((s) => { - const port = s.def.port !== null ? String(s.def.port) : "—"; - const upWhen = s.def.upWhen ? `
    up = ${esc(s.def.upWhen)}` : ""; - const notes = s.def.notes ? `
    ${esc(s.def.notes)}` : ""; - return `${esc(s.def.name)}${upWhen}${notes}${port}${esc(s.def.bind)}${esc(s.def.runsAs)}${esc(s.state)} — ${esc(s.detail)}${probedAge(s.probedAt)}${esc(s.def.consumers)}${esc(s.def.breaksIfDown)}`; - }) - .join(""); - const sectionRows = view.feed.sections.length - ? view.feed.sections - .map((s) => { - let status: string; - if (s.status === "unknown") status = s.present ? "present" : 'absent'; - else if (s.status === "error") status = 'error'; - else if (s.status === "skipped") status = 'skipped'; - else status = s.present ? "present · ok" : "empty · ok"; - return `${esc(s.key)}${status}${s.ageMs !== undefined ? esc(ageMsText(s.ageMs)) : "—"}${s.behindBy === null ? "unknown" : s.behindBy}${s.lastSyncAt ? esc(s.lastSyncAt) : "—"}${s.lagNote ? esc(s.lagNote) : ""}${s.note ? esc(s.note) : ""}`; - }) - .join("") - : `No readable fleet feed — sections cannot be reported.`; - const gathererRows = view.quotaGatherer?.providers.length - ? view.quotaGatherer.providers - .map( - (p) => - `${esc(p.providerId)}${p.credentialLabel ? ` · ${esc(p.credentialLabel)}` : ""}${esc(p.serviceId)}${esc(p.state)}unknown${p.lastSyncAt ? esc(p.lastSyncAt) : "—"}${esc(p.lagNote)}`, - ) - .join("") - : `No quota-gatherer provider rows are available.`; - const orch = view.jobs.orchestration; - const orchLine = orch.generatedAt - ? `last run ${esc(orch.runId ?? "unknown")} · ${esc(ageMsText(orch.ageMs ?? 0))} · state ${esc(orch.state)}${orch.failedChecks ? ` · failed checks: ${esc(orch.failedChecks.join(", "))}` : ""} · next expected ~${esc(orch.nextExpectedAt ?? "")} (hourly cadence — an expectation, not a promise)` - : `no run on record · state ${esc(orch.state)}${orch.failedChecks ? ` · failed checks: ${esc(orch.failedChecks.join(", "))}` : ""}`; - const coll = view.jobs.collector; - const drift = view.feed.checkout; - const driftLine = - drift.state === "behind" - ? ` · collector checkout behind origin/main by ${drift.behindBy ?? "?"} commit(s) — the collector is running old code` - : drift.state === "in-sync" - ? ` · collector checkout in sync with origin/main` - : ` · collector checkout drift unknown: ${esc(drift.reason ?? "no reason given")}`; - const collLine = coll.generatedAt - ? `feed generated ${esc(ageMsText(coll.ageMs ?? 0))} · file written ${coll.fileMtime ? esc(coll.fileMtime) : "unknown"}${driftLine}` - : "no readable fleet feed"; - const pageRows = view.pages - .map((p) => { - const last = - p.lastRenderedAt === null - ? `not rendered since this process started (boot ${esc(view.bootAt)})` - : `${esc(ageMsText(p.ageMs ?? 0))} · ${p.ok ? "ok" : 'last render failed'}`; - return `${esc(p.title)}${esc(p.route)}${last}`; - }) - .join(""); - // #1203: the ready-for-agent facet — the harness's real dispatch-layer - // state, not just whether its UI answers 200. "down" means the GraphQL - // read failed (detail names the error) or a backend is not READY; the - // repositories table still shows what the harness reports when it can - // be read at all. - const rfa = view.rfa; - const rfaState = - rfa.state === "up" - ? 'up' - : rfa.state === "fixtures" - ? 'fixtures' - : 'down'; - const rfaRepoRows = rfa.repositories.length - ? rfa.repositories - .map( - (r) => - `${esc(r.projectPath)}${r.paused ? "paused" : "running"}${esc(r.mergePolicy ?? "—")}${r.workItems}`, - ) - .join("") - : `No harness repositories reported — the harness could not be read, or none are registered.`; - const rfaBackendLine = rfa.backends.length - ? `Backends: ${rfa.backends.map((b) => `${esc(b.id)} ${esc(b.kind)}${b.reason ? ` — ${esc(b.reason)}` : ""}`).join(" · ")}` - : "Backends: none reported."; - const rfaSection = `

    ready-for-agent harness

    -
    ${rfaState} — ${esc(rfa.detail)}
    ${rfaBackendLine}
    -
    ${rfaRepoRows}
    ready-for-agent repositories — settings and dispatch work items
    RepositoryPausedMerge policyWork items
    `; - // #3976: push health — the freshness journal + reconciler state, - // rendered beside (never merged into) the per-source freshness - // story: the push state describes the delivery machinery, each - // source row describes that source's own data age and lag. - const push = view.push; - const pushSection = push - ? `

    Push health \u2014 event-driven freshness (#3976)

    -
    push: ${esc(push.state)}
    -
    ${esc(push.state)} \u2014 ${esc(push.detail)}
    last event ${push.lastEventAt ? esc(ageMsText(Math.max(0, nowMs - Date.parse(push.lastEventAt)))) : "none recorded"} \u00b7 last successful reconcile ${push.lastSuccessfulReconcileAt ? esc(ageMsText(Math.max(0, nowMs - Date.parse(push.lastSuccessfulReconcileAt)))) : "never in this process"} \u00b7 journal cursor ${push.cursor ?? "unknown"} \u00b7 gaps: ${push.gaps.open} open \u00b7 ${push.gaps.repairedTotal} repaired by reconciliation \u00b7 ${push.gaps.resetsTotal} journal reset(s)${push.gaps.lastResetAt ? ` (last ${esc(push.gaps.lastResetAt)})` : ""}
    -
    ${push.sources.map((s) => ``).join("")}
    Push sources \u2014 freshness is per source; a quiet source is silent, not an outage
    SourceStateLast eventAgeLagNotices
    ${esc(s.source)}${esc(s.state)}${s.missingNotice ? ' \u00b7 notice missing \u2014 gap open' : ""}${s.lastEventAt ? esc(s.lastEventAt) : "\u2014"}${s.ageMs !== null ? esc(ageMsText(s.ageMs)) : "\u2014"}${s.lagMs !== null ? esc(ageMsText(s.lagMs)) : "\u2014"}${s.notices}
    ` - : `

    Push health \u2014 event-driven freshness (#3976)

    \n

    Push health is not assembled in this mode \u2014 no state is invented for it.

    `; - const sloRows = (view.slo ?? []) - .map((s) => { - const current = !s.sourced - ? `unknown / no signal source` - : s.currentValue !== null - ? esc(ageMsText(s.currentValue)) - : s.latestBad === null - ? `\u2014` - : s.latestBad - ? "down" - : "up"; - const remaining = s.budgetRemainingPercent === null ? "\u2014" : `${s.budgetRemainingPercent.toFixed(1)}%`; - const burn = s.burnRate1h === null ? "\u2014" : s.burnRate1h.toFixed(2); - return `${esc(s.label)}${esc(s.target)}${current}${remaining}${burn}${esc(s.state)}`; - }) - .join(""); - const sloSection = view.slo - ? `

    SLO error budgets (#9988)

    -

    Each minute the health view is sampled into an append-only journal. Budgets are computed over each facet's rolling window; a facet with no signal source is shown as unknown, never as good.

    -
    ${sloRows}
    SLO error budgets \u2014 remaining budget and 1-hour burn rate per facet
    FacetTargetCurrentBudget remaining1h burnState
    ` - : ""; - const cov = view.itemsCoverage; - const coverageLine = - cov && cov.total > 0 - ? `${cov.resolvedLive} of ${cov.total} board items resolved from live data (project pool / projector) · ${cov.fixture} resolved from fixtures (rendered hollow + "unverified") · coverage ratio ${cov.ratio !== null ? cov.ratio.toFixed(2) : "—"} — measured on the health prime's board resolution pass, the same pass that sets the items facet provenance (#1141).` - : `not measured yet — coverage is computed on the health prime's board resolution pass (#1267); a pass that resolved no tagged items reports nothing rather than inventing a ratio.`; - const facets = view.facets - ? freshnessChips(view.facets, [ - "board", - "roadmap", - "items", - "comments", - "quota", - "usage", - "attention", - "orchestration", - "dns", - "registry", - "aa", - ]) - : `

    This source does not report structured source facets.

    `; - const degraded = view.degraded - ? `
    Something below is degraded — each row names its own state; nothing on this page is smoothed over.
    ` - : ""; - const modeNote = - view.mode === "fixtures" - ? `` - : ""; - const body = `

    Health

    -

    Every stack service probed live (results cached 60 s), every feed section aged, the last job runs, and this dashboard's own render history — assembled from the same view /api/health serves, at ${esc(view.generatedAt)}.

    -${degraded}${modeNote} -

    Services & topology

    -

    What runs where: the component, its port and bind as actually deployed, what consumes it, and what breaks without it. State is probed, never assumed.

    -
    ${serviceRows}
    Services, ports, and topology
    ServicePortBindRuns asStateConsumed byIf it is down
    -${rfaSection} -${pushSection} -${sloSection} -

    Feed sections

    -
    ${sectionRows}
    Feed sections — presence, age, lag, and last sync
    SectionPresentAgeBehind byLast syncLag noteNote
    -

    Quota gatherer sources

    -
    ${gathererRows}
    Quota-gatherer provider freshness and lag
    ProviderServiceStateBehind byLast syncLag note
    -

    Jobs

    -
    Orchestration pass
    ${orchLine}
    -
    Fleet-feed collector
    ${collLine}
    -

    Item resolution coverage

    -
    ${coverageLine}
    -

    Source conflicts

    -
    ${ - view.conflicts - ? `${view.conflicts.total} live source conflict${view.conflicts.total === 1 ? "" : "s"}${view.conflicts.byClass - .filter((c) => c.count > 0) - .map((c) => ` · ${esc(c.label)}: ${c.count}`) - .join( - "", - )}${view.conflicts.oldestAgeDays === null ? "" : ` · oldest at least ${view.conflicts.oldestAgeDays} day${view.conflicts.oldestAgeDays === 1 ? "" : "s"}`} (#1282 slice 1 — a growing count means the sources keep disagreeing and nobody has ruled on the class)` - : `not assembled for this health view` - }
    -

    Dashboard comments

    -
    ${view.comments.pendingMessages} message${view.comments.pendingMessages === 1 ? "" : "s"} awaiting triage · ${view.comments.pendingGithub} GitHub comment${view.comments.pendingGithub === 1 ? "" : "s"} awaiting posting · ${view.comments.total} comment${view.comments.total === 1 ? "" : "s"} in the store (#1145 — a pending count that does not drain means work arrives faster than it is cleared, or the triage/poster loop has stopped; check the loop's last run before acting)
    -

    Source facets

    -${facets} -

    Pages

    -

    Render history of this process — a page nobody has opened since boot is labelled unrendered, not green.

    -
    ${pageRows}
    Pages — last rendered
    PageRouteLast rendered
    `; - return layout("Health", body, provenance, "/health"); -} - -// --- Discuss page (one object's dashboard comments) ----------------------------- - -export function renderDiscuss( - objectRef: string, - title: string, - comments: DashComment[], - opts: CommentFormOpts, - provenance: Provenance, -): string { - const back = - objectRef.startsWith("gh:") || objectRef.startsWith("kaneo:") || objectRef.startsWith("grist:") - ? `

    ← the item page

    ` - : objectRef.startsWith("session:") - ? `

    ← the session registry · Needs you

    ` - : `

    ← Needs you

    `; - // #1500: the same fixture banner + honest empty wording as the item - // page, keyed off the comments provenance this page already receives. - const discussFixtureBanner = fixtureCommentsBannerHtml(provenance); - const discussEmptyWording = - commentsFixtureSourced(provenance) && comments.length === 0 - ? `

    no comments loaded — ${FIXTURE_COMMENTS_CAUSE}

    ` - : ""; - const body = `

    ${esc(title)}

    object: ${esc(objectRef)}

    ${back}${discussFixtureBanner}${discussEmptyWording} -

    Two kinds, visibly distinct: a note is read when this is next picked up and triggers nothing; a message to Muse is triaged by the orchestrator on its next pass and may create work.${ - opts.githubRefs?.length - ? ` This item is GitHub-backed, so a comment can also be posted as a GitHub comment on an explicit target.` - : "" - }

    -${commentThreadHtml(objectRef, comments, opts)}`; - return layout(title, body, provenance, "", COMMENT_SCRIPT); -} - -// --- Comments queue page (#1210) ------------------------------------------ - -/** The queue view: every comment still waiting on a loop — messages - * awaiting triage and GitHub comments pending/failed to post — with - * kind/state counts. Terminal comments (triaged/posted) and notes - * are not queued and never render here. */ -export function renderCommentsQueue(comments: DashComment[], provenance: Provenance): string { - const queued = queuedComments(comments); - const k = commentKindCounts(comments); - const summary = `${queued.length} queued — ${k.messagesNew} messages awaiting triage · ${k.githubPending} GitHub comments to post · ${k.githubFailed} failed to post (of ${k.total} comments total: ${k.notes} notes, ${k.messages} messages, ${k.github} GitHub)`; - const list = queued.length - ? queued - .map( - (c) => - `${dashCommentHtml(c, true)}\n

    open the thread

    `, - ) - .join("\n") - : `

    Nothing is queued — every message is triaged and every GitHub comment is posted.

    `; - const body = `

    Comments queue

    -

    Every dashboard comment still waiting on a loop (#1210), oldest first. A note is never queued: it is read when its item is next picked up. Machine-first: /api/comments/queue.json.

    -

    ${summary}

    -${list}`; - return layout("Comments queue", body, provenance, "/comments"); -} - -// --- Projects page (#910 stage 5: the live GitHub Project pool) ------------ -// New function only (parallel agents own the other render functions). -// Renders the feed's Project pool; where the Project Status and the -// derived state (see src/projects.ts derivedProjectState) disagree, -// BOTH are shown — neither side is silently preferred. - -/** #1220: the coverage panel — Project #4 pool vs backlog reality per - * repo (open issues and gate labels from the feed, pool size and unset - * Status/Area from the pool), with the week-over-week delta against the - * stored baseline in parentheses when a baseline exists. */ -function coverageSectionHtml(coverage: CoverageSnapshotFile | null | undefined): string { - if (!coverage) return ""; - const { current, baseline } = coverage; - const delta = diffCoverage(current, baseline); - const cell = ( - repo: string, - v: number | null, - key: "openIssues" | "gateNow" | "gateNext" | "poolItems" | "poolUnsetStatus" | "poolUnsetArea", - ): string => { - if (v === null) return "—"; - const d = delta.get(repo)?.[key]; - return d === undefined || d === null || d === 0 - ? `${v}` - : `${v} (${d > 0 ? "+" : ""}${d})`; - }; - const rows = current.repos - .map((r) => { - const state = staleIssueState(r); - const status = - state === "error" - ? `Collection error${r.staleIssuesError ? `: ${esc(r.staleIssuesError)}` : ""}` - : state === "stale" - ? "STALE — collection is over 7 days old" - : state === "unavailable" - ? "Unavailable — collection failed or not collected" - : "Current"; - const collectedAt = r.staleIssuesCollectedAt - ? `` - : "—"; - return `${esc(r.repo)}${cell(r.repo, r.openIssues, "openIssues")}${cell(r.repo, r.gateNow, "gateNow")}${cell(r.repo, r.gateNext, "gateNext")}${cell(r.repo, r.poolItems, "poolItems")}${cell(r.repo, r.poolUnsetStatus, "poolUnsetStatus")}${cell(r.repo, r.poolUnsetArea, "poolUnsetArea")}${r.staleOpenIssues === null ? "—" : r.staleOpenIssues}${collectedAt}${status}`; - }) - .join(""); - const note = baseline - ? `Week-over-week delta vs the ${esc(fmtDate(baseline.generatedAt))} snapshot in parentheses. Snapshot stored ${esc(fmtDate(current.generatedAt))}; it rotates into the baseline after a week.` - : `First snapshot stored ${esc(fmtDate(current.generatedAt))} — the week-over-week delta appears after the next weekly rotation.`; - return `

    Coverage — pool vs backlog (#1220)

    -
    ${rows}
    Coverage — pool vs backlog by repository
    RepoOpen issuesnow gatenext gatePool itemsUnset StatusUnset AreaOpen issues untouched >90 daysStale count collected at (UTC)Stale count status
    -

    ${note} Open issues and gate labels come from the collector's Search API census in the fleet feed; pool counts from Project #4 (— = that source was unavailable for the repo, never a real zero). The stale count includes open issues only, is captured at the per-repository timestamp, and is marked stale after seven days; missing/error data is not presented as zero. The same report is in /api/projects.json as \`coverage\`.

    `; -} - -/** The Projects pool body (cards, chips, coverage) without the page - * shell — rendered standalone by renderProjects and, since the #1497 - * merge, as the pool section of /program. */ -/** The per-item brief panel (#1279): visibly labelled as derived, every - * line carrying its evidence link. The identical brief object ships in - * the JSON twin (/api/projects.json `briefs`). */ -export function briefPanelHtml(brief: ItemBrief): string { - const ev = (e: { text: string; url: string }) => `${esc(e.text)}`; - const activity = brief.lastActivity.evidence - ? `${esc(brief.lastActivity.text)} Evidence: ${ev(brief.lastActivity.evidence)}.` - : esc(brief.lastActivity.text); - const clash = brief.disagreement - ? `
    ⚠ ${esc(brief.disagreement.text)} Evidence: ${ev(brief.disagreement.evidence)}.` - : ""; - return `
    Derived brief (derived from the projection — not authored)
    State: ${esc(brief.state.text)} Evidence: ${ev(brief.state.evidence)}.
    Blocker: ${esc(brief.blocker.text)} Evidence: ${ev(brief.blocker.evidence)}.
    ${activity}
    Next: ${esc(brief.nextAction.text)} Evidence: ${ev(brief.nextAction.evidence)}.${clash}
    `; -} - -/** The canonical status taxonomy (#1198 acceptance 1): the mapping - * table from status-taxonomy.ts, rendered where the pool renders — - * /projects standalone and the pool section of /program. */ -export function statusTaxonomyHtml(): string { - const rows = STATUS_TAXONOMY.map( - (row) => - `${esc(STATUS_SOURCE_LABELS[row.source])}${esc(row.raw)}${esc(row.canonical)}`, - ).join(""); - return `

    Canonical status taxonomy (#1198)

    -

    One canonical status set — ${CANONICAL_STATUSES.map(esc).join(" · ")} — and every source's vocabulary mapped into it. An item's canonical status is the same on every page for the same inputs; a source value with no row here is unmapped and surfaces as a ⚠ disagreement rather than being guessed. The ⚠ badges on Board, Roadmap, Today, and this pool all compare through this table.

    -
    ${rows}
    Per-source status mapping to the canonical set
    SourceSource statusCanonical status
    `; -} - -export function projectsBodyHtml( - pool: ProjectPoolItem[], - opts: { - area?: string | null; - /** Pool facet filters (#1208): Project Status / Kind single-select values, or the "(no status)" / "(no kind)" unset buckets. */ - status?: string | null; - kind?: string | null; - /** Project #4 audit snapshot (#1208): reconciles the rendered pool count against the board total (draft/unlinked caveat). */ - audit?: ProjectAudit | null; - orchestration?: OrchestrationSection | null; - detail?: ProvenanceDetail; - actionsByObject?: Map; - identities?: AuthorIdentity[]; - coverage?: CoverageSnapshotFile | null; - /** Where the area chips point: /projects standalone, /program once merged (#1497). */ - basePath?: string; - /** Prebuilt briefs (#1279), e.g. with comment activity folded in. - * Absent: briefs are built here from the pool + orchestration only. */ - briefs?: Map; - /** Shared forecast contracts by item ref (#3984): the same objects - * /api/forecasts.json serves, rendered as one-line summaries. */ - forecasts?: Map; - /** Spend beside progress (#4824): the #4823 rollup store's - * reader view. Absent/null: cards render exactly as before. */ - spend?: SpendCardsView | null; - } = {}, -): string { - const base = opts.basePath ?? "/projects"; - const areas = [...new Set(pool.map((p) => p.area).filter((a): a is string => Boolean(a)))].sort(); - // #1143: Area-unset items get an explicit "(unset)" bucket, mirroring - // the /program index banner — without it they are silently mixed into - // "all" with no count and no way to view them as the gap they are. - const UNSET_AREA = "(unset)"; - const unsetCount = pool.filter((p) => !p.area).length; - const area = - opts.area === UNSET_AREA && unsetCount > 0 ? UNSET_AREA : opts.area && areas.includes(opts.area) ? opts.area : null; - const shownByArea = - area === UNSET_AREA ? pool.filter((p) => !p.area) : area ? pool.filter((p) => p.area === area) : pool; - // #1208: Status and Kind are pool fields too — facet-filter them like - // Area (the saved-view dimensions in views.ts carry the same pair, so - // a view and the chips agree). "(no status)" / "(no kind)" are the - // explicit unset buckets, mirroring the Area "(unset)" bucket (#1143). - const UNSET_STATUS = "(no status)"; - const UNSET_KIND = "(no kind)"; - const statuses = [...new Set(pool.map((p) => p.status).filter((s): s is string => Boolean(s)))].sort(); - const kinds = [...new Set(pool.map((p) => p.kind).filter((s): s is string => Boolean(s)))].sort(); - const statusSel = - opts.status === UNSET_STATUS ? UNSET_STATUS : opts.status && statuses.includes(opts.status) ? opts.status : null; - const kindSel = opts.kind === UNSET_KIND ? UNSET_KIND : opts.kind && kinds.includes(opts.kind) ? opts.kind : null; - const shown = shownByArea - .filter((p) => (statusSel === UNSET_STATUS ? !p.status : statusSel ? p.status === statusSel : true)) - .filter((p) => (kindSel === UNSET_KIND ? !p.kind : kindSel ? p.kind === kindSel : true)); - /** Facet link builder: change one facet, keep the others. */ - const facetHref = (patch: { area?: string | null; status?: string | null; kind?: string | null }): string => { - const q = new URLSearchParams(); - const a = patch.area !== undefined ? patch.area : area; - const s = patch.status !== undefined ? patch.status : statusSel; - const k = patch.kind !== undefined ? patch.kind : kindSel; - if (a) q.set("area", a); - if (s) q.set("status", s); - if (k) q.set("kind", k); - const qs = q.toString(); - return qs ? `${base}?${qs}` : base; - }; - const chips = [ - `all (${pool.length})`, - ...areas.map( - (a) => - `${esc(a)} (${pool.filter((p) => p.area === a).length})`, - ), - ...(unsetCount > 0 - ? [ - `${UNSET_AREA} (${unsetCount})`, - ] - : []), - ].join(""); - if (!pool.length) { - return `${coverageSectionHtml(opts.coverage)}${opts.spend?.unattributed ? unattributedSpendHtml(opts.spend.unattributed) : ""}

    Live services: ${serviceHomeLinks() - .map((s) => `${esc(s.label)} ↗`) - .join(" · ")}

    `; - } - const areaWeights = areas - .map((a) => { - const items = pool.filter((p) => p.area === a); - const w = summarizeWeights(uniqueProjectItemsByRef(items)); - return `
    ${esc(a)} — ${esc(weightedLine(w))}
    ${esc(handsLine(w))}
    `; - }) - .join(""); - const shownWeights = summarizeWeights(uniqueProjectItemsByRef(shown)); - const epicRollups = buildEpicRollups(pool); - const cards = shown - .map((p) => { - const derived = derivedProjectState(p, opts.orchestration); - const clash = projectDisagreement(p, opts.orchestration); - const clashBadge = clash - ? ` ⚠ project: ${esc(clash.project)} · derived: ${esc(clash.derived)}` - : ""; - const statusBadge = p.status - ? `${esc(p.status)}` - : `no status`; - const linksLine = `${esc(p.repo)}#${p.number} · Project item · Project #4${p.updatedAt ? ` · updated ${fmtDate(p.updatedAt)}` : ""}`; - // #5082: only active work (canonical Project status - // In Progress / In Review) and epics - // render as a full card — status-request control, derived - // brief, rollups. An epic's rollup / forecast / spend ARE its - // substance at any status (#3984, #4824) and epics are few - // (40 of 1,422). Every other item renders compact: title, - // badges, links — the shape the per-project pages already - // use. The pool only ever - // grows — 725 of 1,422 items were Done at the 2026-11-13 - // measurement — and at ~2.8 KB per full card (actbox ~1.2 KB + - // brief ~0.9 KB of it) the page reached 4.08 MB and grew with - // every filed item. A compact row keeps the item's identity, - // status, badges and links; the dropped blocks are the ones - // whose content is formulaic for a queued/finished item (the - // brief's "Next: No action" for Done items) or an action that - // belongs to active work. When the derived state disagrees the - // ⚠ clash badge still shows on the compact row, so no signal - // is lost. Counts, chips and weights use the whole pool either - // way; the area filter and saved views filter rows the same. - // Action-result badges (a pending / applied status request) - // also stay on compact rows — only the form and brief drop. - const canonical = canonicalStatusFor("project", p.status); - const active = canonical === "In Progress" || canonical === "In Review" || p.kind === "Epic"; - const objectRef = ghObjectRef(p.ref); - const actionBadges = actionBadgesHtml(opts.actionsByObject?.get(objectRef)); - if (!active) { - const metaCompact = [ - p.area ? `${esc(p.area)}` : "", - p.horizon ? `${esc(p.horizon)}` : "", - p.kind ? `${esc(p.kind)}` : "", - `issue ${esc(p.state)}`, - ].join(" "); - const compactLinks = `${esc(p.repo)}#${p.number} · Project item${p.updatedAt ? ` · updated ${fmtDate(p.updatedAt)}` : ""}`; - return `
    ${esc(p.title)}${clashBadge}
    ${statusBadge} ${metaCompact}
    ${compactLinks}${actionBadges}
    `; - } - const meta = [ - p.area ? `${esc(p.area)}` : "", - p.horizon ? `${esc(p.horizon)}` : "", - p.kind ? `${esc(p.kind)}` : "", - `issue ${esc(p.state)}`, - `derived: ${esc(derived)}`, - ].join(" "); - // #1154: the status-request control + the store's visible state. - const statusCtl = opts.identities - ? `${actionBadges}${statusRequestHtml(objectRef, p.ref, p.status ?? null, { identities: opts.identities })}` - : ""; - const rollup = p.kind === "Epic" ? epicRollups.get(p.ref) : undefined; - const epicRollup = rollup ? epicRollupHtml(rollup) : ""; - const spendCard = opts.spend?.byScope.get(p.ref); - const spendHtml = spendCard ? spendCardHtml(spendCard) : ""; - const brief = opts.briefs?.get(p.ref) ?? buildItemBrief(p, { pool, orchestration: opts.orchestration }); - const forecastHtml = forecastSummaryHtml(opts.forecasts?.get(p.ref)); - return `
    ${esc(p.title)}${clashBadge}
    ${statusBadge} ${meta}
    ${linksLine}${epicRollup}${spendHtml}${forecastHtml}${statusCtl}${briefPanelHtml(brief)}
    `; - }) - .join(""); - const body = `

    ${pool.length} items from the org Project Developing Today (#4), read live by the fleet-feed collector (GraphQL, read-only) and carried in the feed. This pool is the resolution source for board/roadmap GitHub items. Where the Project Status and the derived state disagree, the card shows ⚠ with both values. Machine-first: /api/projects.json.

    -
    ${chips}
    -
    Status: ${[ - `any`, - ...statuses.map( - (s) => - `${esc(s)} (${pool.filter((p) => p.status === s).length})`, - ), - ...(pool.some((p) => !p.status) - ? [ - `${UNSET_STATUS} (${pool.filter((p) => !p.status).length})`, - ] - : []), - ].join("")}
    -
    Kind: ${[ - `any`, - ...kinds.map( - (k) => - `${esc(k)} (${pool.filter((p) => p.kind === k).length})`, - ), - ...(pool.some((p) => !p.kind) - ? [ - `${UNSET_KIND} (${pool.filter((p) => !p.kind).length})`, - ] - : []), - ].join("")}
    -${opts.audit && (opts.audit.poolTotalItems ?? opts.audit.totalItems) > pool.length ? `` : ""} -${shown.length !== pool.length ? `

    Filters show ${shown.length} of ${pool.length} pool items.

    ` : ""} -${unsetCount > 0 ? `` : ""} -${coverageSectionHtml(opts.coverage)} -${statusTaxonomyHtml()} -

    Weighted progress (effort xs=1 · s=4 · m=12 · l=40, #1108): ${esc(weightedLine(shownWeights))}
    ${esc(handsLine(shownWeights))}

    -${area ? "" : `

    Per-Area weighted progress

    ${areaWeights}`} -

    Live services: ${serviceHomeLinks() - .map((s) => `${esc(s.label)} ↗`) - .join(" · ")}

    -${cards || '

    No items in this area.

    '}${opts.spend?.unattributed ? unattributedSpendHtml(opts.spend.unattributed) : ""}`; - return body; -} - -export function renderProjects( - pool: ProjectPoolItem[], - provenance: Provenance, - opts: { - area?: string | null; - /** Pool facet filters (#1208): Project Status / Kind single-select values, or the "(no status)" / "(no kind)" unset buckets. */ - status?: string | null; - kind?: string | null; - /** Project #4 audit snapshot (#1208): reconciles the rendered pool count against the board total (draft/unlinked caveat). */ - audit?: ProjectAudit | null; - designBoards?: BoardSnapshot[]; - orchestration?: OrchestrationSection | null; - detail?: ProvenanceDetail; - actionsByObject?: Map; - identities?: AuthorIdentity[]; - coverage?: CoverageSnapshotFile | null; - basePath?: string; - briefs?: Map; - forecasts?: Map; - spend?: SpendCardsView | null; - } = {}, -): string { - return layout( - "Projects", - `

    Projects — GitHub Project pool

    -${renderDesignBoards(opts.designBoards ?? [])} -${projectsBodyHtml(pool, opts)}`, - provenance, - "/projects", - opts.identities ? ACTION_SCRIPT : "", - opts.detail ? freshnessChips(opts.detail, ["items"]) : "", - ); -} - -// --- Program status page (#1046: the dashboard documents itself) ------------ -// Editorial sections come from src/program.ts (the PROGRAM object — the -// one file to edit when the program changes); the live-status section is -// derived from the Source at request time by buildProgramLive, so its -// claims cannot drift from the tracked issues / Project pool / -// orchestrator they describe. Unresolvable refs render as "unresolved". - -function programEntryHtml(e: ProgramEntry, items: Map): string { - const refs = (e.refs ?? []) - .map((r) => { - const item = items.get(r); - return item - ? itemBadge(item) - : `unresolved ${esc(r)}`; - }) - .join(" "); - const links = (e.links ?? []).map((l) => `${esc(l.label)}`).join(" · "); - const meta = [refs, links].filter(Boolean).join(" "); - return `
    ${esc(e.title)}
    ${esc(e.detail)}${meta ? `
    ${meta}` : ""}
    `; -} - -function programEntries(entries: ProgramEntry[], items: Map): string { - return entries.map((e) => programEntryHtml(e, items)).join(""); -} - -function countList(list: { name: string; count: number }[]): string { - return list.length ? list.map((c) => `${esc(c.name)}: ${c.count}`).join(" · ") : 'none'; -} - -function trackedTable(tracked: TrackedIssue[]): string { - const rows = tracked - .map(({ ref, item }) => - item - ? `${itemBadge(item)}${esc(item.title)}${esc(item.state)}${fmtDate(item.updatedAt)}` - : `unresolved${esc(ref)}unresolved — the current source cannot resolve this ref—`, - ) - .join(""); - return `
    ${rows}
    Tracked issues
    Tracked issueTitleStateUpdated
    `; -} - -function poolSummaryHtml(live: ProgramLive): string { - return live.pool.total - ? `
    ${live.pool.total} items in the org Project pool
    By status — ${countList(live.pool.byStatus)}
    By area — ${countList(live.pool.byArea)}
    ` - : ``; -} - -function orchestrationHtml(live: ProgramLive): string { - return live.orchestration - ? `
    Orchestrator — latest run ${esc(live.orchestration.runId)}, published ${fmtDate(live.orchestration.generatedAt)}.
    The tiers and goal measurements it publishes are on Needs you and Today.
    ` - : `
    Orchestrator — no orchestration section in the current feed yet (not measured). The Today view derives and labels itself until one lands.
    `; -} - -function projectCard(s: ProjectSummary): string { - const poolLine = - s.poolArea === null - ? `No dedicated Project Area yet.` - : `${s.poolTotal} pool items (${esc(s.poolArea)})${s.poolTotal ? `
    Weighted — ${esc(weightedLine(s.weights))}
    ${esc(handsLine(s.weights))}
    By status — ${countList(s.poolByStatus)}` : ""}`; - const roadmapLine = - s.roadmapArea === null - ? `No Grist roadmap area yet.` - : `${s.roadmapRows} roadmap row${s.roadmapRows === 1 ? "" : "s"} (${esc(s.roadmapArea)})`; - const homeLine = s.homeDoc - ? `
    Home doc: ${esc(s.homeDoc.path)}` - : ""; - return `
    ${esc(s.title)}
    ${poolLine}
    ${roadmapLine}${homeLine}
    Project page →
    `; -} - -/** /program as the projects index (#1121): one card per configured - * project from the registry, the whole-pool + orchestrator live blocks - * from #1046, and the unset-Area count as a visible gap. The full - * pm-dashboard document moved to /program/pm-dashboard — every link - * that pointed at /program still lands here. */ -export function renderProgram( - data: ProgramData, - items: Map, - provenance: Provenance, - detail?: ProvenanceDetail, - poolSection?: { - pool: ProjectPoolItem[]; - area?: string | null; - status?: string | null; - kind?: string | null; - audit?: ProjectAudit | null; - designBoards?: BoardSnapshot[]; - coverage?: CoverageSnapshotFile | null; - orchestration?: OrchestrationSection | null; - actionsByObject?: Map; - identities?: AuthorIdentity[]; - /** Prebuilt briefs (#1279), e.g. with comment activity folded in. */ - briefs?: Map; - forecasts?: Map; - /** The #4829 flow twin the #4830 charts render on this page. */ - flowAnalytics?: FlowAnalytics; - /** Spend beside progress (#4824) for the pool section. */ - spend?: SpendCardsView | null; - } | null, -): string { - const poolSectionHtml = poolSection - ? `

    Projects pool

    -

    The Projects page, merged into Program status by the #1497 curation — the raw org Project pool with its Project-vs-derived disagreements. /projects redirects to this section; the machine twin /api/projects.json is unchanged.

    -${projectsBodyHtml(poolSection.pool, { area: poolSection.area, status: poolSection.status, kind: poolSection.kind, audit: poolSection.audit, orchestration: poolSection.orchestration, actionsByObject: poolSection.actionsByObject, identities: poolSection.identities, coverage: poolSection.coverage, basePath: "/program", briefs: poolSection.briefs, forecasts: poolSection.forecasts, spend: poolSection.spend })}` - : ""; - const { program, live } = data; - const projects = data.projects ?? []; - const unset = live.pool.byArea.find((c) => c.name === "(unset)")?.count ?? 0; - const cards = projects.map(projectCard).join(""); - const unsetHtml = - live.pool.total && unset - ? `` - : ""; - const body = `

    Program status — projects

    -

    Every project the fleet runs, documented the same way: a description, its live Project-pool and roadmap sections, its tracked issues resolved live, and its roadmap — all driven by the project registry in src/project-config.ts. Pick a project for its full page.

    -

    Source of truth: the design record in developing-today/code · the org Project Developing Today (#4) · Machine-first: /api/program.json.

    -

    What runs where — every stack service, its port and bind, and its live health: Health & topology →

    -

    Projects

    -
    ${cards || '

    No projects configured.

    '}
    -${unsetHtml} -${renderDesignBoards(poolSection?.designBoards ?? [])} -

    Live status

    -

    Derived at request time from the Project pool and the latest orchestration section — not written by hand.

    -${poolSummaryHtml(live)} -${orchestrationHtml(live)} -

    The PM dashboard's own record

    -

    This dashboard's architecture, what's built, what's next, and its long-term roadmap live on its project page: PM dashboard →. Its tracked issues, resolved live:

    -${trackedTable(live.tracked)}${poolSectionHtml}${poolSection?.flowAnalytics ? flowChartsHtml(poolSection.flowAnalytics) : ""}`; - return layout( - "Program status", - body, - provenance, - "/program", - poolSection?.identities ? ACTION_SCRIPT : "", - detail ? freshnessChips(detail, ["orchestration", "items", "roadmap"]) : "", - ); -} - -// --- Per-project page (#1121, registry in src/project-config.ts) ------------- - -const POOL_ITEM_CAP = 24; - -/** Render a graph ref as a link only when it satisfies the shared ref rule. */ -function poolRefLink(ref: RefKey): string { - const label = esc(ref); - return isValidRef(ref) ? `${label}` : label; -} - -/** The #2400 graph section of a project page: blocked weight + longest - * blocked chain and the depth-graph SVG, from the part-1 edge contract - * (#2399). Graceful absence is explicit: a pool with no effort labels - * and no edges says "not yet sized/graphed" (never a fake 0%); a sized - * pool without edges says "not yet graphed" only. */ -function poolGraphHtml(items: ProjectPoolItem[], allW: ReturnType): string { - const edges = hasGraphEdges(items); - if (!edges && allW.totalWeight === 0) { - return ``; - } - if (!edges) { - return `

    Not yet graphed: pool items carry no parent / blocked-by edges yet, so blocked weight and the depth graph appear once the collector sees edges. Weighted progress above is from effort labels alone.

    `; - } - const blocked = blockedSummary(items); - const chainHtml = - blocked.longestChain.length >= 2 - ? ` · longest blocked chain: ${blocked.longestChain.map(poolRefLink).join(" → ")} (${blocked.longestChain.length - 1} link${blocked.longestChain.length === 2 ? "" : "s"})` - : ""; - const blockedHtml = blocked.blockedCount - ? `

    Blocked weight: ${blocked.blockedWeight} across ${blocked.blockedCount} open item${blocked.blockedCount === 1 ? "" : "s"} waiting on an unresolved blocker${blocked.blockedUnsizedCount ? ` (${blocked.blockedUnsizedCount} of them unsized — counted, never zero-weighted)` : ""}${chainHtml}.

    ` - : `

    Blocked weight: 0 — no open item is waiting on an unresolved blocker.

    `; - - const layout = depthLayout(items); - const pos = new Map(layout.nodes.map((n) => [n.ref, n])); - const X = (depth: number) => 16 + depth * 180; - const Y = (row: number) => 16 + row * 26; - const width = X(layout.maxDepth) + 340; - const height = Y(layout.nodes.length - 1) + 16; - const edgeLines = layout.edges - .map((e) => { - const a = pos.get(e.from)!; - const b = pos.get(e.to)!; - return ``; - }) - .join(""); - const nodeShapes = layout.nodes - .map((n) => { - const label = `#${n.number} ${n.title.length > 34 ? `${n.title.slice(0, 33)}…` : n.title}`; - const dash = n.mode === "hybrid" ? ` stroke-dasharray="3 2"` : ""; - const strokeW = n.mode === "physical" ? 3 : 1.5; - const shape = n.epic - ? `` - : ``; - return `${shape}${esc(label)}`; - }) - .join(""); - const truncated = layout.truncated - ? `

    Depth graph shows ${layout.nodes.length} of ${items.length} items (cap) — the full set is in the cards below.

    ` - : ""; - const svg = layout.nodes.length - ? `${edgeLines}${nodeShapes}

    Depth = sub-issue nesting from the Project pool. Squares are epics; amber = open, grey = closed. Border: thick solid = mode/physical, dashed = mode/hybrid, thin = online or no mode.

    ${truncated}` - : ""; - return `

    Blocked + depth graph

    ${blockedHtml}${svg}`; -} - -/** The #3973 per-epic dependency graph section of a project page - * (design doc/2026-11-01T21-05-00Z_design_aggregator_dependency_graph_1257.md): - * an epic selector with item/blocked counts, then per epic a summary + - * ranked blocked list beside the graph SVG and a vertical, - * keyboard-readable dependency list. The list is the primary surface - * on narrow screens (the flex column stacks it full-width; the SVG - * may scroll horizontally as a secondary detail). Dependency edges - * are dashed amber, hierarchy edges solid grey, and every node's - * state is written as text — color is never the only signal. Empty - * or unavailable graph data says so; it is never an empty success. */ -/** Section anchor for one epic's graph, derived from the canonical ref - * (owner/repo#number), never the bare issue number: two repositories - * can hold epics with the same number, and bare-number ids collide. */ -function epicGraphAnchor(ref: RefKey): string { - return `epic-graph-${ref.replace(/[^a-zA-Z0-9]+/g, "-")}`; -} - -interface EpicGraphActionContext { - orchestration?: OrchestrationSection | null; - actionsByObject?: Map; - identities?: AuthorIdentity[]; - orchestrationState?: string; -} - -function epicGraphSectionHtml( - items: ProjectPoolItem[], - selectorItems: ProjectPoolItem[] = items, - actionContext?: EpicGraphActionContext, -): string { - // Selector entries and rendered sections are scoped to the project's - // own pool (selectorItems = detail.poolItems): on a normal project - // request the caller passes the entire org pool as `items` for - // membership and blocker resolution, and rendering every eligible - // epic from every Area would bury this project's section in unrelated - // projects (Codex round-2 on #3973). Resolution inside each section - // still runs against the full `items` pool. - // The selector rollups are computed from the full `items` pool too, - // then filtered to this project's epic refs (Codex round-3 on - // #3973): computing them from the scoped pool made a member whose - // blocker lives in another Area count as blocked in the selector - // while its section — resolving against the full pool — correctly - // reported it unblocked. - const projectEpicRefs = new Set(selectorItems.filter((i) => i.kind === "Epic").map((i) => i.ref)); - const selector = epicSelector(items).filter((e) => projectEpicRefs.has(e.ref)); - if (!selector.length) { - return `

    Per-epic dependency graph

    `; - } - const selectorHtml = ``; - const sections = selector.map((entry) => epicGraphOneHtml(items, entry, actionContext)).join(""); - return `

    Per-epic dependency graph

    ${selectorHtml}${sections}`; -} - -function graphNodeActionsHtml(nodeRef: RefKey, context?: EpicGraphActionContext): string { - const section = context?.orchestration; - const drewItem = section?.tiers.needsDrew.find((item) => item.ref === nodeRef); - const orchestratorItem = section?.tiers.needsOrchestrator.find((item) => item.ref === nodeRef); - const item = drewItem ?? orchestratorItem; - if (!item) { - return `

    No inline action: this item is not in the currently published Needs User or Needs Orchestrator tier.

    `; - } - - const tier = drewItem ? "needs-drew" : "needs-orchestrator"; - const objectRef = tierItemObjectRef(item); - const actions = context?.actionsByObject?.get(objectRef); - const state = cardState(actions); - const disabledReason = - item.source === "watchdog" || context?.orchestrationState === "live" - ? undefined - : `the tier source is ${context?.orchestrationState ?? "unavailable"}, so this item cannot be confirmed against the orchestrator's current published queues`; - const controls = context?.identities - ? triageActionsHtml( - objectRef, - tier, - { identities: context.identities, ...(disabledReason ? { disabledReason } : {}) }, - tier === "needs-drew" ? needsUserFormsHtml(item, objectRef, Date.now(), state) : "", - state, - ) - : `

    Inline actions unavailable: no dashboard author identity is configured.

    `; - const needsUserBody = tier === "needs-drew" ? needsUserBodyHtml(item, actions) : ""; - const history = `${actionBadgesHtml(actions)}
    Action history${actionHistoryHtml(actions)}
    `; - - let sessionControls = ""; - if (item.sessionId) { - const sessionSource = item.source === "claude" ? "claude-code" : item.source; - const support = sessionVerbSupport(sessionSource); - if (!context?.identities) { - sessionControls = `

    Session action unavailable: no dashboard author identity is configured.

    `; - } else if (support.some((entry) => !entry.reason)) { - const sessionRef = sessionObjectRef(item.sessionId); - const sessionActions = context?.actionsByObject?.get(sessionRef); - sessionControls = `${actionBadgesHtml(sessionActions)}${sessionActionsHtml(item.sessionId, sessionSource, { identities: context.identities })}
    Session action history${actionHistoryHtml(sessionActions)}
    `; - } else { - const reason = - support.find((entry) => entry.reason)?.reason ?? - "this published item has no supported live session control channel"; - sessionControls = `

    Session action unavailable: ${esc(reason)}.

    `; - } - } - - return `
    ${tier === "needs-drew" ? "Needs User" : "Needs Orchestrator"}${needsUserBody}${history}${controls}${sessionControls}
    `; -} - -function epicGraphOneHtml( - items: ProjectPoolItem[], - entry: ReturnType[number], - actionContext?: EpicGraphActionContext, -): string { - const g = epicGraph(items, entry.ref); - const heading = `

    ${esc(entry.title)} (${esc(entry.ref)})

    `; - if (g.status === "unavailable" || !g.epic) { - return `
    ${heading}
    `; - } - const poolByRef = new Map(items.map((p) => [p.ref, p])); - const unresolvedOf = (ref: RefKey): boolean => { - const held = poolByRef.get(ref); - return held === undefined || held.state === "open"; - }; - const summary = `

    ${g.memberCount} item${g.memberCount === 1 ? "" : "s"} in this epic · ${g.blockedCount} blocked on an unresolved blocker · ${g.externalCount} one-hop reference${g.externalCount === 1 ? "" : "s"} outside this pool (unresolved — status unknown, never counted as resolved).

    `; - const cycleGroupsHtml = g.cycleGroups.length - ? `
    ${g.cycleGroups - .map((group) => { - const members = group.members - .map((ref) => { - const member = poolByRef.get(ref); - return `
  • ${poolRefLink(ref)}${member?.title ? ` — ${esc(member.title)}` : ""}
  • `; - }) - .join(""); - const explanation = - group.kind === "dependency" - ? "The dependency data is contradictory. Resolving one member alone does not clear this cycle; correct the cycle edges." - : "The parent links are cyclic. These members are one hierarchy warning group, not independent roots; correct the parent edges."; - return ``; - }) - .join("")}
    ` - : ""; - const edgeDiagnosticsHtml = g.edgeDiagnostics.length - ? `` - : ""; - const truncatedHtml = g.truncated - ? `

    Truncated: this graph shows ${g.nodes.length} of ${g.totalNodes} nodes (cap ${EPIC_GRAPH_DEFAULT_CAP}). The counts above cover the full set; a capped graph is not complete.

    ` - : ""; - - // Ranked summary: open member items by how many distinct open epic items - // are in the transitive blockedBy ancestry of their blockers (the full - // transitive downstream ranking is #3974). Never derived from the - // capped node list: a member the cap hid is still waiting. - const ranked = g.rankedBlocked; - const rankedHtml = ranked.length - ? `
      ${ranked - .map((r) => { - const blockerItems = r.blockers.map((b) => poolRefLink(b)); - const contributingItems = - r.contributingItems.length > 0 - ? `
      Contributing downstream epics: ${r.contributingItems.map((ci) => poolRefLink(ci)).join(", ")}` - : ""; - return `
    • ${esc(r.ref)} — waiting on ${r.downstreamCount} distinct downstream open epic item${r.downstreamCount === 1 ? "" : "s"} via ${r.blockers.length} unresolved blocker${r.blockers.length === 1 ? "" : "s"}: ${blockerItems.join(", ")}${contributingItems}
    • `; - }) - .join("")}
    ` - : g.blockedCount > 0 - ? `

    ${g.blockedCount} open item${g.blockedCount === 1 ? " is" : "s are"} waiting on an unresolved blocker, but none can be ranked here — members of a dependency cycle are excluded from the unblock ranking until the cycle is broken.

    ` - : `

    No open item in this epic is waiting on an unresolved blocker.

    `; - - const rankedBlockersHtml = g.rankedBlockers.length - ? `
      ${g.rankedBlockers - .map((blocker) => { - const stateText = - blocker.state === null ? "outside this pool; status unknown — unresolved" : "open unresolved blocker"; - const downstream = blocker.downstreamItems - .map((item) => { - const weightText = item.effortWeight === null ? "unsized" : `effort weight ${item.effortWeight}`; - const additionalBlockers = item.additionalBlockers.length - ? `additional unresolved blockers: ${item.additionalBlockers.map((ref) => `${esc(ref)}`).join(", ")}` - : "no additional unresolved blockers"; - return `
    1. ${esc(item.ref)} (${weightText}) — ${additionalBlockers}
    2. `; - }) - .join(""); - return `
    3. ${esc(blocker.ref)} (${stateText}) — ${blocker.downstreamCount} distinct open downstream item${blocker.downstreamCount === 1 ? "" : "s"}; known effort weight ${blocker.knownEffortWeight}; ${blocker.unsizedCount} unsized contributor${blocker.unsizedCount === 1 ? "" : "s"}:
        ${downstream}
    4. `; - }) - .join("")}
    ` - : `

    No unresolved blocker has open downstream work in this epic.

    `; - - // SVG: hierarchy edges solid grey, dependency edges dashed amber — - // distinct by dash and color, and named in the legend text. - const pos = new Map(g.nodes.map((n) => [n.ref, n])); - const X = (depth: number) => 16 + depth * 180; - const Y = (row: number) => 16 + row * 26; - const width = X(g.maxDepth) + 340; - const height = g.nodes.length ? Y(g.nodes.length - 1) + 16 : 32; - // Dependency edges carry an arrowhead marker pointing at the blocker - // (the `to` node): hierarchy depth alone does not show which sibling - // blocks which (Codex round-2 on #3973). The marker id is per-epic -- - // several epic sections share one page, and duplicate ids would make - // every edge reference the first section's marker. - const depMarkerId = `dep-arrow-${epicGraphAnchor(g.epic.ref)}`; - const depDefs = g.edges.some((e) => e.type === "dependency") - ? `` - : ""; - const edgeLines = g.edges - .map((e) => { - const a = pos.get(e.from)!; - const b = pos.get(e.to)!; - return e.type === "dependency" - ? `` - : ``; - }) - .join(""); - const nodeShapes = g.nodes - .map((n) => { - const label = n.title - ? `#${n.number} ${n.title.length > 34 ? `${n.title.slice(0, 33)}…` : n.title}` - : `${n.ref} (outside this pool)`; - const x = X(n.depth); - const y = Y(n.row); - const shape = n.unresolved - ? `` - : n.epic - ? `` - : ``; - const nodeLabel = `${esc(label)}`; - return `${shape}${isValidRef(n.ref) ? `${nodeLabel}` : nodeLabel}`; - }) - .join(""); - const svg = g.edges.length - ? `
    ${depDefs}${edgeLines}${nodeShapes}

    Solid grey lines are sub-issue hierarchy (parent → child); dashed amber lines are dependency edges, with an arrowhead pointing at the blocker (item → blocker). Squares are epics; diamonds are references outside this pool whose status is unknown. Every node's state is also written as text in the list — color is never the only signal.

    ` - : `

    Not yet graphed: this epic's items carry no parent / blocked-by edges yet, so there is no graph to draw. The items are listed below.

    `; - - const listHtml = `
      ${g.nodes - .map((n) => { - const stateText = n.unresolved - ? "not in this pool / status unknown — unresolved" - : `issue ${esc(n.state ?? "unknown")}`; - const blockedBy = n.blockers.length - ? `blocked by: ${n.blockers.map((b) => `${poolRefLink(b)}${unresolvedOf(b) ? " (unresolved)" : " (resolved)"}`).join(", ")}` - : "blocked by: none observed"; - const blocks = n.dependents.length - ? `blocks: ${n.dependents.map(poolRefLink).join(", ")}` - : "blocks: none observed"; - const name = n.title ? `${esc(n.title)}` : "(outside this pool — no title in this feed)"; - const nodeRef = isValidRef(n.ref) ? `${esc(n.ref)}` : esc(n.ref); - const actions = isValidRef(n.ref) ? graphNodeActionsHtml(n.ref, actionContext) : ""; - return `
    • ${nodeRef} ${name} — ${stateText}; ${blockedBy}; ${blocks}${actions}
    • `; - }) - .join("")}
    `; - - return `
    ${heading}${summary}${cycleGroupsHtml}${edgeDiagnosticsHtml}${truncatedHtml}
    ${svg}
    Primary ranking — blockers by downstream open work

    Each open epic item is counted once per blocker across its transitive blockedBy ancestry. This measures downstream reach, not a promise that every item is immediately unblocked. Current additional unresolved blockers are listed per item; unsized contributors count separately from known effort weight. The longest dependency chain remains a separate diagnostic.

    ${rankedBlockersHtml}
    Open items by their worst blocker's downstream reach
    ${rankedHtml}
    All items — dependency list
    ${listHtml}
    `; -} - -/** The Path to Phase 12 panel (#9922): #1235's ordered steps, parsed - * from its body snapshot and joined to live GitHub item state and to - * queue state from the fleet-queue collector (#9920). A stale or - * missing body snapshot renders the warning INSTEAD of the steps — a - * silently old step list is the defect #1239's rules name. A stale - * queue snapshot still renders, but behind its own warning: the step - * list is the panel's spine, the task states are the perishable part. */ -export function phase12PanelHtml( - snapshot: Phase12Snapshot | null, - items: Map, - queue: QueueSnapshot | null = null, -): string { - const head = `

    Path to Phase 12 — live from #1235

    `; - if (!snapshot) { - return `${head}`; - } - const queueSegment = - queue === null - ? "queue state unavailable in the current source" - : !queue.available - ? "queue read failed — per-step task state withheld" - : `queue state from the fleet-queue collector, fetched ${esc(new Date(queue.fetchedAt).toISOString())}`; - const sourceLine = `

    Source: developing-today/code#1235 body, fetched ${esc(snapshot.fetchedAt)} · issue updated ${esc(snapshot.issueUpdatedAt)} · per-step state is live GitHub state; ${queueSegment}.

    `; - if (phase12IsStale(snapshot)) { - return `${head}${sourceLine}`; - } - const steps = joinPhase12Steps(parsePhase12Steps(snapshot.body), items, queue); - if (!steps.length) { - return `${head}${sourceLine}`; - } - const queueStale = - queue !== null && queue.available && queue.stale - ? `` - : ""; - const queueBadge = (s: Phase12StepState): string => { - if (queue === null || !queue.available) return ""; - const [task, ...earlier] = s.queueTasks; - if (!task) return ` no queue task`; - const cls = - task.status === "claimed" - ? "implementing" - : task.status === "done" || task.status === "completed" - ? "merged" - : task.status === "blocked" || task.status === "dep_blocked" - ? "closed" - : ""; - const bits = [`task ${task.id}`]; - if (task.lane) bits.push(`lane ${task.lane}`); - if (task.progressStage) bits.push(task.progressStage); - const more = earlier.length - ? ` (+${earlier.length} earlier task${earlier.length === 1 ? "" : "s"})` - : ""; - return ` queue: ${esc(task.status)} ${esc(bits.join(" · "))}${more}`; - }; - const rows = steps - .map((s) => { - const stateBadge = - s.liveState === null - ? `not resolved in the current source` - : `issue ${esc(s.liveState)}`; - const box = s.checked ? "☑" : "☐"; - const done = s.doneNote ? `
    ${esc(s.doneNote)}` : ""; - return `
    ${box} ${esc(s.label)} — #${s.issueNumber} ${esc(s.liveTitle ?? s.title)}
    ${stateBadge}${queueBadge(s)}${done}
    `; - }) - .join(""); - return `${head}${sourceLine}${queueStale}${rows}`; -} - -/** The Phase tracker panel (#9923): per-phase validation state for - * Phases 0-13, derived live from the items source (the four #796 - * validation audits, #1075-#1078, already in the id project's tracked - * refs). No hand-maintained values: a reopened audit or a new open - * follow-up changes the panel without an edit. Phase 12 also shows - * F-item progress counted from #1235's ordered step list, and Phases - * 11 and 13 count the F-item mapping table in planning/roadmaps/id.md - * (the source of record, #9923 step 3) when the source carries it; - * Phases 0-10 have no F-item numbering in their plans, so they state - * that gap instead of showing a fabricated percentage. */ -export function phaseTrackerPanelHtml( - items: Map, - phase12: Phase12Snapshot | null = null, - phaseMapping: PhaseMappingSnapshot | null = null, -): string { - const umbrellaUrl = `https://github.com/${PHASE_TRACKER_REPO}/issues/${PHASE_TRACKER_UMBRELLA}`; - const head = `

    Phase tracker — validation by phase, live from #${PHASE_TRACKER_UMBRELLA}

    `; - const progress = derivePhase12Progress(phase12, items); - const mappedProgress = phaseMapping ? deriveMappedProgress(phaseMapping.entries, items) : null; - const sourceLine = `

    Source: the validation audits #1075–#1078 under umbrella #${PHASE_TRACKER_UMBRELLA}, resolved from the same live GitHub items as the tracked-issues table above (the page provenance stamp applies). Phase 12 progress counts the ordered steps in #1235 against live issue state${phase12 ? ` (body fetched ${esc(phase12.fetchedAt)})` : ""}; ${phaseMapping ? `Phases 11 and 13 progress counts the F-item mapping table in planning/roadmaps/id.md (read ${esc(phaseMapping.fetchedAt)}) against live item state; ` : ""}Phases 0–10 have no F-item numbering in their plans, so no percentage is shown for them — the gap is stated rather than a number invented.

    `; - const rows = derivePhaseValidation(items) - .map((r) => { - const badge = - r.state === "validated" - ? `validated — audit closed` - : r.state === "validation-open" - ? `validation open — audit open` - : r.state === "unresolved" - ? `audit not resolved in the current source` - : `no validation audit`; - const audit = - r.auditIssue === null - ? `—` - : `#${r.auditIssue}${r.auditTitle ? ` ${esc(r.auditTitle)}` : ""}`; - const followUps = r.openFollowUps.length - ? r.openFollowUps.map((f) => `#${f.issueNumber}`).join(" ") - : `—`; - const mapped = mappedProgress?.get(r.phase); - const progressCell = - r.phase === 12 - ? progress - ? `${progress.done}/${progress.total} steps done (${progress.percent}%)
    ${progress.open} open${progress.unresolved ? ` · ${progress.unresolved} not resolved in the current source` : ""} — from #1235` - : `withheld — #1235 feed unavailable or stale` - : mapped - ? `${mapped.done}/${mapped.total} items done (${mapped.percent}%)
    ${mapped.open} open${mapped.unresolved ? ` · ${mapped.unresolved} not resolved in the current source` : ""} — from the F-item mapping in planning/roadmaps/id.md` - : r.phase <= 10 - ? `not derived — this phase's plan has no F-item numbering` - : `not derived — F-item mapping unavailable in the current source`; - return `Phase ${r.phase}${badge}${audit}${followUps}${progressCell}`; - }) - .join(""); - return `${head}${sourceLine}
    ${rows}
    Validation state per id-program phase, derived from live audit issue state
    PhaseValidationAuditOpen follow-upsProgress
    `; -} - -/** The Build health panel (#9924): current CI lane states + the id - * E2E nightly trend, projected from the Actions-API snapshot. A stale - * or missing snapshot renders the warning INSTEAD of lane states — - * silently old CI state is the defect #1239's rules name. A lane whose - * read failed renders unavailable; a failing nightly run keeps its - * link, which is the point of the trend. */ -export function buildHealthPanelHtml(snapshot: BuildHealthSnapshot | null): string { - const head = `

    Build health — live from the GitHub Actions API

    `; - if (!snapshot) { - return `${head}`; - } - const sourceLine = `

    Source: GitHub Actions API for ${esc(BUILD_HEALTH_REPO)}, fetched ${esc(snapshot.fetchedAt)}.

    `; - if (buildHealthIsStale(snapshot)) { - return `${head}${sourceLine}`; - } - const runBadge = (status: string, conclusion: string | null): string => { - if (status !== "completed") return `${esc(status)}`; - if (conclusion === "success") return `success`; - if (conclusion === "failure") return `failure`; - return `${esc(conclusion ?? "completed")}`; - }; - const laneCards = snapshot.lanes - .map((laneRuns) => { - if (laneRuns.error) { - return `
    ${esc(laneRuns.lane.label)}
    unavailable
    Actions read failed: ${esc(laneRuns.error)}
    `; - } - const proj = projectLane(laneRuns); - if (!proj.latest) { - return `
    ${esc(laneRuns.lane.label)}
    no runs reported
    `; - } - const history = proj.history - .map( - (r) => - `${r.conclusion === "success" ? "✓" : r.conclusion === "failure" ? "✗" : "·"}`, - ) - .join(" "); - return `
    ${esc(laneRuns.lane.label)}
    ${runBadge(proj.latest.status, proj.latest.conclusion)} latest: ${esc(proj.latest.createdAt)} (${esc(proj.latest.event)})${history ? `
    recent completed: ${history}` : ""}
    `; - }) - .join(""); - let nightlyHtml: string; - if (snapshot.nightly.error) { - nightlyHtml = `
    ${esc(snapshot.nightly.lane.label)} — nightly trend
    unavailable
    Actions read failed: ${esc(snapshot.nightly.error)}
    `; - } else { - const trend = projectNightlyTrend(snapshot.nightly); - nightlyHtml = trend.length - ? `
    ${esc(snapshot.nightly.lane.label)} — nightly trend (oldest → newest)
    ${trend - .map( - (r) => - `${r.conclusion === "success" ? "✓" : r.conclusion === "failure" ? "✗" : "·"} ${esc(r.createdAt.slice(0, 10))}`, - ) - .join(" · ")}
    ` - : `
    ${esc(snapshot.nightly.lane.label)} — nightly trend
    no completed runs reported
    `; - } - return `${head}${sourceLine}${laneCards}${nightlyHtml}`; -} - -/** The Phase 12 readiness panel (#9926): F12.1–F12.18 with design - * state (from #534's checklist), live issue state, and PR state - * (timeline cross-references). The F-item list is parsed from - * #1235's body — never hand-typed here. A stale snapshot withholds - * the rows behind the warning; missing sub-feeds render their - * column as unavailable instead of inventing a state. */ -export function f12ReadinessPanelHtml( - phase12: Phase12Snapshot | null, - design: Phase12Snapshot | null, - prRefs: Map | null, - items: Map, -): string { - const head = `

    Phase 12 readiness — F12.1–F12.18, live

    `; - if (!phase12) { - return `${head}`; - } - const sourceLine = `

    Sources: F-item list + order from developing-today/code#1235 (fetched ${esc(phase12.fetchedAt)}); design state from #534${design ? ` (fetched ${esc(design.fetchedAt)})` : " (feed unavailable — design column withheld)"}; issue state is live GitHub state; PR state from issue-timeline cross-references${prRefs ? "" : " (timeline read unavailable — PR column withheld)"}.

    `; - if (phase12IsStale(phase12) || (design !== null && phase12IsStale(design))) { - return `${head}${sourceLine}`; - } - const fItems = parseF12Items(phase12.body); - if (!fItems.length) { - return `${head}${sourceLine}`; - } - const designs = design ? parseF12Designs(design.body) : new Map(); - const rows = projectF12Readiness(fItems, designs, items, prRefs ?? new Map()) - .map((r) => { - const issueBadge = - r.issueState === null - ? `issue not resolved in the current source` - : `issue ${esc(r.issueState)}`; - const designBadge = !design - ? `design feed unavailable` - : r.design === null - ? `no design entry in #534` - : r.design.done - ? `design ${esc(r.design.designId)} done` - : `design ${esc(r.design.designId)} pending`; - const prBadge = !prRefs - ? `PR read unavailable` - : r.prs.length - ? r.prs - .map( - (p) => - `PR #${p.number} ${esc(p.state)}`, - ) - .join(" ") - : `no cross-referenced PR`; - return `
    ${esc(r.f)} — #${r.issueNumber} ${esc(r.title ?? "")}
    ${designBadge} ${issueBadge} ${prBadge}
    `; - }) - .join(""); - return `${head}${sourceLine}${rows}`; -} - -export function queuePanelHtml(snapshot: QueueSnapshot | null): string { - const head = `

    Queue & fleet \u2014 live from the fleet queue broker

    `; - if (!snapshot) { - return `${head}`; - } - const fetchedIso = new Date(snapshot.fetchedAt).toISOString(); - const sourceLine = `

    Source: queue-broker /health + /list (read-only), fetched ${esc(fetchedIso)}.

    `; - if (!snapshot.available || snapshot.stale) { - const why = snapshot.errors.length ? ` Last read error: ${esc(snapshot.errors[0])}.` : ""; - return `${head}${sourceLine}`; - } - const age = (ms: number | null): string => { - if (ms === null) return "\u2014"; - const mins = Math.floor(ms / 60_000); - if (mins < 60) return `${mins}m`; - const hours = Math.floor(mins / 60); - if (hours < 48) return `${hours}h ${mins % 60}m`; - return `${Math.floor(hours / 24)}d ${hours % 24}h`; - }; - const streamRows = snapshot.queues - .map( - (q) => - `${esc(q.queue)}${q.queued}${q.claimed}${q.parked}${q.blocked}${q.done}${esc(age(q.oldestQueuedAgeMs))}${q.terminalEvents24h} / ${q.terminalEvents7d}`, - ) - .join(""); - const streams = `${streamRows}
    Queue streams
    Queue streamQueuedClaimedParkedBlockedDoneOldest queuedTerminal 24h / 7d
    `; - const idItems = snapshot.tasks.filter( - (task) => - task.repo === "developing-today/code" && - task.issue !== null && - (task.status === "claimed" || task.status === "parked"), - ); - const itemRows = idItems - .slice(0, 50) - .map((task) => { - const who = [task.worker, task.lane].filter(Boolean).join(" / ") || "\u2014"; - const stage = task.progressStage ? esc(task.progressStage) : "\u2014"; - return `${task.id}#${task.issue} ${esc(task.title)}${esc(task.status)}${esc(who)}${stage}`; - }) - .join(""); - const items = idItems.length - ? `

    Claimed & parked id items (${idItems.length})

    ${itemRows}
    Claimed & parked id items
    TaskIssueStatusWorker / laneStage
    ` - : `

    Claimed & parked id items

    None in the current snapshot.

    `; - return `${head}${sourceLine}${streams}${items}`; -} - -export function renderProgramProject( - detail: ProjectDetail, - items: Map, - provenance: Provenance, - provDetail?: ProvenanceDetail, - epicPool: ProjectPoolItem[] = detail.poolItems, - phase12?: Phase12Snapshot | null, - buildHealth?: BuildHealthSnapshot | null, - f12?: { design: Phase12Snapshot | null; prRefs: Map | null } | null, - queueSnap?: QueueSnapshot | null, - phaseMapping?: PhaseMappingSnapshot | null, - graphActions?: EpicGraphActionContext, -): string { - const { config } = detail; - const linkBits: string[] = []; - if (config.homeDoc) { - linkBits.push( - `Home doc: ${esc(config.homeDoc.path)} (${esc(config.homeDoc.repo)})`, - ); - } else { - linkBits.push(`No home doc configured for this project yet.`); - } - if (detail.doc?.latestStatus) { - const status = detail.doc.latestStatus; - linkBits.push( - `Latest status: ${esc(status.title ?? status.dir)} (${esc(status.timestamp)} \u2014 newest doc/ status record, derived at request time)`, - ); - } else if (detail.doc) { - linkBits.push( - `No status record under doc/ for this project yet \u2014 checked the code checkout at ${esc(detail.doc.fetchedAt)}.`, - ); - } else if (config.statusReport) { - linkBits.push(`Status report: ${esc(config.statusReport.label)}`); - } else { - linkBits.push(`No status report yet for this project.`); - } - if (detail.doc?.description) { - linkBits.push( - `Description derived from ${esc(detail.doc.roadmapPath)} (read at request time)`, - ); - } else if (detail.doc) { - linkBits.push( - `No prose description found in ${esc(detail.doc.roadmapPath)} \u2014 the registry intro is shown instead.`, - ); - } - for (const l of config.dashboardLinks ?? []) { - linkBits.push( - `${esc(l.label)}${l.note ? ` (${esc(l.note)})` : ""}`, - ); - } - linkBits.push(`JSON twin`); - - const archHtml = config.architecture?.length - ? `

    What this is — architecture

    ${programEntries(config.architecture, items)}` - : ""; - - let poolHtml: string; - if (config.poolArea === null) { - poolHtml = ``; - } else if (!detail.poolItems.length) { - poolHtml = ``; - } else { - const shown = detail.poolItems.slice(0, POOL_ITEM_CAP); - const cards = shown - .map((p) => { - const statusBadge = p.status - ? `${esc(p.status)}` - : `no status`; - const meta = [ - p.horizon ? `${esc(p.horizon)}` : "", - p.kind ? `${esc(p.kind)}` : "", - `issue ${esc(p.state)}`, - ].join(" "); - return `
    ${esc(p.title)}
    ${statusBadge} ${meta}
    ${esc(p.repo)}#${p.number} · Project item${p.updatedAt ? ` · updated ${fmtDate(p.updatedAt)}` : ""}
    `; - }) - .join(""); - const more = - detail.poolItems.length > POOL_ITEM_CAP - ? `

    Showing ${POOL_ITEM_CAP} of ${detail.poolItems.length} — the full set is on /projects.

    ` - : ""; - const allW = summarizeWeights(detail.poolItems); - const epics = detail.poolItems.filter((p) => p.kind === "Epic"); - const epicW = summarizeWeights(epics); - const epicRollups = buildEpicRollups(epicPool); - const epicRows = epics - .map((p) => { - const w = effortWeight(p.labels); - const epicRollup = epicRollups.get(p.ref); - const rollup = epicRollup ? epicRollupHtml(epicRollup) : ""; - return `
    ${esc(p.title)}
    weight: ${w === null ? "unsized" : w} · issue ${esc(p.state)}${p.status ? ` · status: ${esc(p.status)}` : ""} · ${esc(p.repo)}#${p.number}${rollup}
    `; - }) - .join(""); - const epicHtml = epics.length - ? `

    Epics — weighted progress

    ${esc(weightedLine(epicW))}

    ${epicRows}` - : ""; - poolHtml = `

    ${esc(weightedLine(allW))}
    ${esc(handsLine(allW))}
    ${detail.poolItems.length} items with Area ${esc(config.poolArea)} — by status: ${countList(detail.poolByStatus)}. Full pool view: /projects?area=${esc(config.poolArea)}.

    ${epicHtml}${poolGraphHtml(detail.poolItems, allW)}${epicGraphSectionHtml(epicPool, detail.poolItems, graphActions)}${cards}${more}`; - } - - let roadmapHtml: string; - if (config.roadmapArea === null) { - roadmapHtml = ``; - } else if (!detail.roadmapRows.length) { - roadmapHtml = ``; - } else { - const rollups = buildEpicRollups(epicPool); - const rowRollups = new Map(); - for (const row of detail.roadmapRows) { - const epic = row.links - .map((link) => epicPool.find((item) => item.ref === link.ref && item.kind === "Epic")) - .find(Boolean); - const rollup = epic ? rollups.get(epic.ref) : undefined; - if (rollup) rowRollups.set(row.subject, rollup); - } - roadmapHtml = `

    ${detail.roadmapRows.length} row${detail.roadmapRows.length === 1 ? "" : "s"} with area ${esc(config.roadmapArea)} in Grist's Program roadmap. Timeline lanes and drill-downs use the shared roadmap renderer; epic rollups are per matched row.

    ${timelineTable(buildTimeline(detail.roadmapRows), items, undefined, undefined, undefined, undefined, undefined, undefined, { epicRollups: rowRollups, showRowNotes: true })}`; - } - - const repoCardsHtml = detail.repoCards.length - ? `

    Per-repo cards

    -

    One card per working repo. Open-issue counts are a dated GitHub-search snapshot (date on each card), never a live claim; the pool items and roadmap rows are split live from the same sections above, by repo.

    ${detail.repoCards - .map(({ card, poolItems, roadmapRows, tracked }) => { - const refs = tracked - .map( - ({ ref, item }) => - `${esc(ref)}${item ? ` ${esc(item.state)}` : ""}`, - ) - .join(" "); - return `
    ${esc(card.repo)}
    ${esc(card.role)}
    Open issues (GitHub search, ${esc(card.openIssuesAsOf)}): ${card.openIssues} · fleet pool items in this repo: ${poolItems.length} · roadmap rows: ${roadmapRows.length}${refs ? `
    ${refs}` : ""}
    `; - }) - .join("")}` - : ""; - - const sweepHealthHtml = config.sweepHealth?.length - ? `

    Sweep health — published fleet state

    -

    Built only from already-published fleet data — the orchestration section this aggregator serves and the fleet's tracked issues. No new data pipeline feeds this section.

    ${programEntries(config.sweepHealth, items)}` - : ""; - - const phaseTrackerHtml = - config.id === "id" ? phaseTrackerPanelHtml(items, phase12 ?? null, phaseMapping ?? null) : ""; - const phase12Html = - config.id === "id" && phase12 !== undefined ? phase12PanelHtml(phase12, items, queueSnap ?? null) : ""; - const buildHealthHtml = config.id === "id" && buildHealth !== undefined ? buildHealthPanelHtml(buildHealth) : ""; - const f12Html = - config.id === "id" && f12 !== undefined - ? f12ReadinessPanelHtml(phase12 ?? null, f12?.design ?? null, f12?.prRefs ?? null, items) - : ""; - const queueHtml = config.id === "id" && queueSnap !== undefined ? queuePanelHtml(queueSnap) : ""; - - const ed = config.editorial; - const editorialHtml = ed - ? `${ed.done.length ? `

    What's built

    ${programEntries(ed.done, items)}` : ""}${ed.next.length ? `

    What's next

    ${programEntries(ed.next, items)}` : ""}${ed.longTerm.length ? `

    Long-term roadmap

    ${programEntries(ed.longTerm, items)}` : ""}${ed.gaps.length ? `

    Known gaps

    ${programEntries(ed.gaps, items)}` : ""}` - : ""; - - const body = `

    ${esc(config.title)}

    -

    ${esc(detail.doc?.description ?? config.intro)}

    -

    ${linkBits.join(" · ")}

    -

    ← all projects

    -${archHtml} -

    Live status — tracked issues

    -

    Resolved at request time from the same Source as every other view. A ref the current source cannot resolve says so — never an invented state.

    -${trackedTable(detail.tracked)} -

    Project pool — live

    -${poolHtml} -

    Roadmap — live

    -${roadmapHtml} -${repoCardsHtml} -${sweepHealthHtml} -${phaseTrackerHtml}${phase12Html}${buildHealthHtml}${f12Html}${queueHtml}${editorialHtml}`; - return layout( - config.title, - body, - provenance, - "/program", - graphActions?.identities ? ACTION_SCRIPT : "", - provDetail ? freshnessChips(provDetail, ["orchestration", "items", "roadmap"]) : "", - ); -} - -// --- Alerts page (#3676, the alert throat) --------------------------------- - -export interface AlertsPageView { - available: boolean; - incidents: Incident[]; - events: IncidentEvent[]; - subscriptions: PushSubscriptionRow[]; - ackWindowMin: number; -} - -function incidentCard(i: Incident): string { - const sev = i.severity === "critical" ? "closed" : i.severity === "warning" ? "implementing" : "open"; - const times = [ - `first seen ${fmtDate(i.first_seen_at)}`, - i.occurrences > 1 ? `${i.occurrences} occurrences, last ${fmtDate(i.last_seen_at)}` : null, - i.delivered_at - ? `pushed ${fmtDate(i.delivered_at)}` - : i.severity === "critical" && i.status === "open" - ? "not yet pushed" - : null, - i.escalated_at ? `escalated ${fmtDate(i.escalated_at)}` : null, - i.acked_at ? `acked ${fmtDate(i.acked_at)}` : null, - i.closed_at ? `closed ${fmtDate(i.closed_at)}` : null, - ] - .filter(Boolean) - .join(" · "); - const actions = - i.status === "open" - ? ` ` - : i.status === "acked" - ? `` - : ""; - return `
    -${esc(i.title)} ${esc(i.severity)} ${esc(i.status)} -${i.body ? `
    ${esc(i.body)}` : ""} -
    source ${esc(i.source)} · key ${esc(i.incident_key)} · ${esc(times)} -${actions ? `
    ${actions}` : ""} -
    `; -} - -function subscriptionRow(s: PushSubscriptionRow): string { - let host = s.endpoint; - try { - host = new URL(s.endpoint).host; - } catch {} - const classes = Object.entries(s.classes ?? {}) - .map(([k, v]) => `${esc(k)}: ${v ? "on" : "off"}`) - .join(", "); - const quiet = - s.quiet?.enabled === false - ? "quiet hours off" - : `quiet hours ${s.quiet?.start ?? "?"}–${s.quiet?.end ?? "?"} ${s.quiet?.tz ?? ""}`; - return `
    ${esc(host)} subscribed ${fmtDate(s.created_at)} · classes ${esc(classes || "—")} · ${esc(quiet)}${s.gone_count ? ` · gone ×${s.gone_count}` : ""} -
    ${esc(s.user_agent ?? "")} -
    `; -} - -export function renderAlerts(view: AlertsPageView, provenance: Provenance, vapidPublicKey: string): string { - if (!view.available) { - return layout( - "Alerts", - `

    Alerts

    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.

    `, - provenance, - "/alerts", - ); - } - const open = view.incidents.filter((i) => i.status !== "closed"); - const closed = view.incidents.filter((i) => i.status === "closed"); - const events = view.events - .map( - (e) => - `${fmtDate(e.at)}${esc(e.kind)}${esc(e.title ?? e.incident_id)}${esc(e.source ?? "")}${e.incident_key ? ` · ${esc(e.incident_key)}` : ""}`, - ) - .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… - -


    -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.

    - - - - -
    -
    -

    Subscriptions (${view.subscriptions.length})

    -${view.subscriptions.length ? view.subscriptions.map(subscriptionRow).join("") : `

    No push subscriptions yet — enable push above.

    `} -

    Open incidents (${open.length})

    -${open.length ? open.map(incidentCard).join("") : `

    No open incidents. Silence is golden.

    `} -${closed.length ? `

    Closed (recent)

    ${closed.map(incidentCard).join("")}` : ""} -

    Ledger — recent transitions

    -
    ${events}
    Recent alert-ledger transitions
    atkindincidentsource · key
    `; - 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.
    -


    -

    Subscriptions (${view.subscriptions.length})

    -${view.subscriptions.length ? view.subscriptions.map(subscriptionRow).join("") : `

    No push subscriptions yet — enable push above.

    `}`; - const script = ``; - return layout("Notification preferences", body, provenance, "/alerts/preferences", script); -} - -// --- Notifications page (#3319, notification measurement) ------------------- - -export interface NotificationsPageView { - available: boolean; - rollup: NotificationRollup | null; -} - -function pct(ratio: number | null): string { - return ratio === null ? "—" : `${Math.round(ratio * 100)}%`; -} - -export function renderNotifications(view: NotificationsPageView, provenance: Provenance): string { - if (!view.available || !view.rollup) { - return layout( - "Notifications", - `

    Notifications

    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.

    `, - provenance, - "/notifications", - ); - } - const rollup = view.rollup; - const proposals = rollup.classes.filter((c) => c.proposal); - const rows = rollup.classes - .map((c) => { - const cells = c.weeks.map((w) => `${w.sent} sent · ${w.acted} acted (${pct(w.ratio)})`).join(""); - return `${esc(c.class)}${cells}${c.sent} sent · ${c.acted} acted (${pct(c.ratio)})`; - }) - .join(""); - const weekHeads = rollup.classes[0] - ? rollup.classes[0].weeks.map((w) => `week of ${esc(fmtDate(w.start))}`).join("") - : ""; - const proposalHtml = proposals.length - ? `

    Default-off proposals

    ${proposals - .map( - (c) => - `
    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 - ? `
    ${weekHeads}${rows}
    Sent vs acted-on by class and rolling week
    classrolling 4 weeks
    ` - : `

    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 - ? `

    Data freshness: ${digest.freshness - .map((f) => `${esc(f.facet)}=${esc(f.state)}${f.ageMs !== null ? ` (${esc(ageTextDigest(f.ageMs))})` : ""}`) - .join(" · ")}

    ` - : `

    Data freshness: not measured by this source — treat every section as unverified.

    `; - const sections = digest.sections - .map((s) => { - const items = s.items.length - ? `
      ${s.items - .map( - (i) => - `
    • ${esc(i.title)} ${esc(i.ref)} — ${esc(i.note)}
    • `, - ) - .join("")}
    ${s.truncated ? `

    … capped at ${DIGEST_SECTION_LIMIT} items

    ` : ""}` - : `

    ${s.stale ? "(unavailable — see the stale note)" : "(nothing)"}

    `; - return `

    ${esc(s.title)}${s.stale ? ` — STALE: ${esc(s.staleNote ?? "source degraded")}` : ""}

    ${items}`; - }) - .join("\n"); - const archiveLinks = archives.length - ? `

    Archive

      ${archives - .map((a) => `
    • ${esc(a.date)} ${esc(a.kind)}
    • `) - .join("")}
    ` - : `

    Archive

    No digests archived yet — the generator (scripts/generate-digest.ts) writes one per day.

    `; - const body = `

    PM ${esc(digest.kind)} digest — ${esc(digest.date)}

    -

    Generated ${esc(digest.generatedAt)} from the canonical projection · window ${digest.windowHours}h from ${esc(digest.windowStart)} · machine twin: ${esc(`/api/digest.json?date=${digest.date}&kind=${digest.kind}`)}

    -${freshness} -${sections} -${archiveLinks}`; - return layout( - `Digest ${digest.date}`, - body, - provenance, - "/digest", - "", - detail ? freshnessChips(detail, ["items", "quota"]) : "", - ); -} - -function ageTextDigest(ageMs: number): string { - const mins = Math.max(0, Math.round(ageMs / 60000)); - if (mins < 60) return `${mins}m old`; - const hours = Math.floor(mins / 60); - if (hours < 48) return `${hours}h ${mins % 60}m old`; - return `${Math.floor(hours / 24)}d ${hours % 24}h old`; -} +// +// Split by view into the render-*.ts modules (#13051); this file is the +// barrel — every public name is re-exported here so existing callers keep +// importing the same names from "./render.ts". + +export { + esc, + fmtDate, + fmtCentral, + TAILNET_URL, + FRAG_WATCHDOG_MS, + FRAG_WATCHDOG_SCRIPT, + freshnessChips, + navLinks, + pageDropdown, + themeToggle, + renderSearch, + sessionObjectRef, + ghObjectRef, + tierItemObjectRef, + commentBadge, + authorBadge, + dashCommentHtml, + authorOptionsHtml, + commentFormHtml, + commentThreadHtml, + relTime, + actionBadgesHtml, + cardDomId, + actionHistoryHtml, + cardCommentHtml, + DISMISS_REASONS, + DEESCALATE_REASONS, + quickBarHtml, + triageActionsHtml, + whyUserBadge, + needsUserBodyHtml, + needsUserFormsHtml, + delegationDefaultHtml, + PROJECT_STATUS_VALUES, + statusRequestHtml, + sessionVerbSupport, + sessionActionsHtml, + sessionRecordIsLive, + coverageHtml, + briefPanelHtml, +} from "./render-core.ts"; +export type { CommentFormOpts, ActionFormOpts } from "./render-core.ts"; +export { + renderBoardBody, + renderBoard, + renderBoardShell, + buildRoadmapDrill, + forecastSummaryHtml, + renderRoadmap, + eventTableHtml, + FIXTURE_COMMENTS_CAUSE, + commentsFixtureSourced, + fixtureCommentsBannerHtml, + renderItem, + sessionRecordLine, +} from "./render-board.ts"; +export type { RoadmapDrill, ItemExtras } from "./render-board.ts"; +export { fmtMetricValue, freshnessStamp, renderQuota, historyChartHtml, renderServiceDetail } from "./render-quota.ts"; +export { + questionsSectionHtml, + renderAttention, + needsDrewCensusHtml, + attentionSections, + attentionFragment, + renderAttentionShell, +} from "./render-attention.ts"; +export type { AttentionAct } from "./render-attention.ts"; +export { + renderTodayBody, + renderToday, + renderTodayShell, + renderQueueBody, + renderQueue, + renderQueueShell, + deriveOverview, + renderOverviewBody, + renderOverview, + renderOverviewShell, +} from "./render-today.ts"; +export type { + OverviewData, + OverviewInProgressSignal, + OverviewInProgressItem, + OverviewSummary, +} from "./render-today.ts"; +export { renderDns } from "./render-dns.ts"; +export { renderAa } from "./render-aa.ts"; +export { + renderSessions, + renderConflicts, + renderPages, + renderHealth, + renderDiscuss, + renderCommentsQueue, + statusTaxonomyHtml, +} from "./render-views.ts"; +export { + projectsBodyHtml, + renderProjects, + renderProgram, + phase12PanelHtml, + phaseTrackerPanelHtml, + buildHealthPanelHtml, + f12ReadinessPanelHtml, + queuePanelHtml, + renderProgramProject, +} from "./render-program.ts"; +export { renderAlerts, renderNotificationPreferences, renderNotifications, renderDigest } from "./render-alerts.ts"; +export type { AlertsPageView, NotificationPreferencesView, NotificationsPageView } from "./render-alerts.ts"; diff --git a/pm-stack/aggregator/test/a11y-1215.test.ts b/pm-stack/aggregator/test/a11y-1215.test.ts index b447a2ec70..8a71676dae 100644 --- a/pm-stack/aggregator/test/a11y-1215.test.ts +++ b/pm-stack/aggregator/test/a11y-1215.test.ts @@ -3,17 +3,23 @@ // navigation model for the bar and the Pages dropdown, and captions / // scoped headers on every aggregator table. import { describe, expect, test } from "bun:test"; -import { readFileSync } from "node:fs"; +import { readFileSync, readdirSync } from "node:fs"; import { join } from "node:path"; import { PAGES } from "../src/pages.ts"; import { navLinks, pageDropdown, renderAa } from "../src/render.ts"; import { FIXTURE_AA } from "../src/sources/fixtures.ts"; import { addConsoleShortcut } from "../src/console-gate.ts"; +// The render layer is split across render.ts + render-*.ts (#13051); scan +// the whole module set — the same code the single render.ts used to hold. const renderSource = readFileSync(join(import.meta.dir, "..", "src", "ui.css"), "utf8") + "\n" + - readFileSync(join(import.meta.dir, "..", "src", "render.ts"), "utf8"); + readdirSync(join(import.meta.dir, "..", "src")) + .filter((f) => f.startsWith("render") && f.endsWith(".ts")) + .sort() + .map((f) => readFileSync(join(import.meta.dir, "..", "src", f), "utf8")) + .join("\n"); describe("light theme (#1215)", () => { const light = renderSource.slice( diff --git a/pm-stack/aggregator/test/freshness-fallback-3976.test.ts b/pm-stack/aggregator/test/freshness-fallback-3976.test.ts index 905258fea1..84c0571c96 100644 --- a/pm-stack/aggregator/test/freshness-fallback-3976.test.ts +++ b/pm-stack/aggregator/test/freshness-fallback-3976.test.ts @@ -95,10 +95,19 @@ describe("#3976 SSE-down fallback policy", () => { // The vendored Datastar v1 binds data-on: (colon form); // the dash form resolves to an unregistered plugin and never // fires, leaving every dashrefresh dispatch inert (Codex review - // round 2 on PR #9193; see themeToggle() in render.ts). Oracle: + // round 2 on PR #9193; see themeToggle() in render-core.ts). Oracle: // every fragment container source carries the colon form and no // source carries the dash form. - for (const rel of ["render.ts", "server.ts", "freshness-delivery.ts"]) { + // render.ts's fragment shells live in render-board.ts, + // render-attention.ts and render-today.ts since the #13051 split; + // together they are the render-layer entries in this oracle. + for (const rel of [ + "render-board.ts", + "render-attention.ts", + "render-today.ts", + "server.ts", + "freshness-delivery.ts", + ]) { const src = await readFile(join(import.meta.dir, "..", "src", rel), "utf8"); expect(src).toContain("data-on:dashrefresh__window"); expect(src).not.toContain("data-on-dashrefresh__window"); @@ -106,7 +115,7 @@ describe("#3976 SSE-down fallback policy", () => { }); test("the layout ships the freshness client and the server serves it", async () => { - const render = await readFile(join(import.meta.dir, "..", "src", "render.ts"), "utf8"); + const render = await readFile(join(import.meta.dir, "..", "src", "render-core.ts"), "utf8"); const server = await readFile(join(import.meta.dir, "..", "src", "server.ts"), "utf8"); expect(render).toContain("/assets/freshness-client.js"); expect(server).toContain('path === "/assets/freshness-client.js"'); diff --git a/pm-stack/aggregator/test/mobile-targets.test.ts b/pm-stack/aggregator/test/mobile-targets.test.ts index b4b4e5a45e..6c1e2f770d 100644 --- a/pm-stack/aggregator/test/mobile-targets.test.ts +++ b/pm-stack/aggregator/test/mobile-targets.test.ts @@ -1,12 +1,21 @@ import { describe, expect, test } from "bun:test"; -import { readFileSync } from "node:fs"; +import { readFileSync, readdirSync } from "node:fs"; import { join } from "node:path"; // #1180 mobile audit (390x844): control-class tap targets carry a 40px // floor in the stylesheet. Static assertions, same style as nav.test.ts — // the rendered measurements live on issue #1180. const SRC = join(import.meta.dir, "..", "src"); -const renderSource = readFileSync(join(SRC, "ui.css"), "utf8") + "\n" + readFileSync(join(SRC, "render.ts"), "utf8"); +// The render layer is split across render.ts + render-*.ts (#13051); scan +// the whole module set — the same code the single render.ts used to hold. +const renderSource = + readFileSync(join(SRC, "ui.css"), "utf8") + + "\n" + + readdirSync(SRC) + .filter((f) => f.startsWith("render") && f.endsWith(".ts")) + .sort() + .map((f) => readFileSync(join(SRC, f), "utf8")) + .join("\n"); function cssRule(selector: string): string { const start = renderSource.indexOf(`\n${selector} {`); diff --git a/pm-stack/aggregator/test/nav.test.ts b/pm-stack/aggregator/test/nav.test.ts index 9b35d0ecef..28c0df66be 100644 --- a/pm-stack/aggregator/test/nav.test.ts +++ b/pm-stack/aggregator/test/nav.test.ts @@ -3,7 +3,7 @@ // serves is reachable from the manifest — the bar, the dropdown, the // /pages list, or a parent page's sub-route. import { describe, expect, test } from "bun:test"; -import { readFileSync } from "node:fs"; +import { readFileSync, readdirSync } from "node:fs"; import { join } from "node:path"; import { PAGE_GROUPS, @@ -19,7 +19,16 @@ import { addConsoleShortcut } from "../src/console-gate.ts"; const SRC = join(import.meta.dir, "..", "src"); const serverSource = readFileSync(join(SRC, "server.ts"), "utf8"); -const renderSource = readFileSync(join(SRC, "ui.css"), "utf8") + "\n" + readFileSync(join(SRC, "render.ts"), "utf8"); +// The render layer is split across render.ts + render-*.ts (#13051); scan +// the whole module set — the same code the single render.ts used to hold. +const renderSource = + readFileSync(join(SRC, "ui.css"), "utf8") + + "\n" + + readdirSync(SRC) + .filter((f) => f.startsWith("render") && f.endsWith(".ts")) + .sort() + .map((f) => readFileSync(join(SRC, f), "utf8")) + .join("\n"); /** The CSS rule body for a selector in the stylesheet string. */ function cssRule(selector: string): string { diff --git a/pm-stack/aggregator/test/setups-store-2851.test.ts b/pm-stack/aggregator/test/setups-store-2851.test.ts index f493fbd338..885da9522b 100644 --- a/pm-stack/aggregator/test/setups-store-2851.test.ts +++ b/pm-stack/aggregator/test/setups-store-2851.test.ts @@ -4,13 +4,18 @@ // saved — and importing a "__proto__" entry mutated the live store's // prototype while dropping the entry. The fix makes loadSetups() // return a null-prototype store. These tests extract the REAL -// loadSetups/storeSetups from src/render.ts and drive the save/import +// loadSetups/storeSetups from the render module set (src/render-aa.ts +// since the #13051 split) and drive the save/import // handler cores verbatim against a stub localStorage. import { describe, expect, test } from "bun:test"; -import { readFileSync } from "node:fs"; +import { readFileSync, readdirSync } from "node:fs"; import { join } from "node:path"; -const renderSource = readFileSync(join(import.meta.dir, "..", "src", "render.ts"), "utf8"); +const renderSource = readdirSync(join(import.meta.dir, "..", "src")) + .filter((f) => f.startsWith("render") && f.endsWith(".ts")) + .sort() + .map((f) => readFileSync(join(import.meta.dir, "..", "src", f), "utf8")) + .join("\n"); const storeFns = renderSource.slice( renderSource.indexOf("function loadSetups()"), renderSource.indexOf("function refreshSetupList"), diff --git a/pm-stack/aggregator/test/ui-overhaul.test.ts b/pm-stack/aggregator/test/ui-overhaul.test.ts index 20c2b5b984..3566b620c9 100644 --- a/pm-stack/aggregator/test/ui-overhaul.test.ts +++ b/pm-stack/aggregator/test/ui-overhaul.test.ts @@ -5,12 +5,18 @@ // idle timeout, and the fragment contract (ids + patch re-GET hooks) // is untouched. import { describe, expect, test } from "bun:test"; -import { existsSync, readFileSync } from "node:fs"; +import { existsSync, readFileSync, readdirSync } from "node:fs"; import { join } from "node:path"; import { renderSearch } from "../src/render.ts"; const SRC = join(import.meta.dir, "..", "src"); -const renderSource = readFileSync(join(SRC, "render.ts"), "utf8"); +// The render layer is split across render.ts + render-*.ts (#13051); scan +// the whole module set — the same code the single render.ts used to hold. +const renderSource = readdirSync(SRC) + .filter((f) => f.startsWith("render") && f.endsWith(".ts")) + .sort() + .map((f) => readFileSync(join(SRC, f), "utf8")) + .join("\n"); const serverSource = readFileSync(join(SRC, "server.ts"), "utf8"); const uiCss = readFileSync(join(SRC, "ui.css"), "utf8");