From 430c928c3c690c3e2e23e4b1454bfed031774a93 Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Tue, 27 Oct 2026 07:04:24 +0000 Subject: [PATCH] feat(aggregator): /health page + services topology (#1147, #1137) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - src/topology.ts: ServiceDef registry for every stack component (port, bind as actually deployed, runs-as, consumers, breaks-if- down); probe targets come from config where config has them. - src/health.ts: health assembly shared by /health and /api/health (they cannot disagree): HTTP probes with an injectable fetcher, 1.5s timeout, 60s result cache; projector off-by-config is never probed and never red; Kaneo Postgres inferred from Kaneo's probe, honestly 'unknown' when Kaneo is down; orchestration state is the #1140 section diagnosis verbatim; feed section ages; job lines (orchestration last run + hourly next-expected, collector feed time + file mtime); pages from an in-process render registry — unrendered pages say so, never fake-green. Fixtures mode probes nothing and reports 'fixtures' for every service. - server.ts: /health route; /api/health extended in place (services/ feed/pages/jobs/degraded added; status/source/sections stable); render recording against manifest routes. - config.ts: PM_AGG_PAD_URL / PM_AGG_RFA_URL probe targets. - Copy (Drew, 2026-10-27): tier titles are Title Case — 'Needs User' / 'Needs Orchestrator' in headings, chips, and badges (was 'Needs user'); sentence-internal prose unchanged. Tests updated to match. - README views table gains /health; layout list updated. --- pm-stack/aggregator/README.md | 36 ++- pm-stack/aggregator/src/config.ts | 15 ++ pm-stack/aggregator/src/health.ts | 341 ++++++++++++++++++++++++ pm-stack/aggregator/src/pages.ts | 8 + pm-stack/aggregator/src/render.ts | 105 +++++++- pm-stack/aggregator/src/server.ts | 79 +++++- pm-stack/aggregator/src/topology.ts | 168 ++++++++++++ pm-stack/aggregator/test/boot.test.ts | 4 +- pm-stack/aggregator/test/health.test.ts | 284 ++++++++++++++++++++ pm-stack/aggregator/test/render.test.ts | 8 +- pm-stack/aggregator/test/slice2.test.ts | 14 +- 11 files changed, 1028 insertions(+), 34 deletions(-) create mode 100644 pm-stack/aggregator/src/health.ts create mode 100644 pm-stack/aggregator/src/topology.ts create mode 100644 pm-stack/aggregator/test/health.test.ts diff --git a/pm-stack/aggregator/README.md b/pm-stack/aggregator/README.md index f50f617d71..7b536d2039 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -15,20 +15,21 @@ Design record (source of truth): ## The views -| Route | View | Machine-first JSON | -| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -| `/today` | **Today** (slice 2, #898) — the day's top objectives, prioritized, plus per-project momentum (moving / stalled / blocked-by-what, recent accomplishments). From the orchestration job's goal measurements (#899) when a section exists; derived from board + roadmap + item activity, and labelled as derived, until then. | `/api/today.json` | -| `/attention` | **Needs you** (#852, tiered in slice 2) — **NEEDS USER** (default; the intake queue the orchestrator works first — only items it cannot resolve escalate here, each with its reason), **NEEDS ORCHESTRATOR** (the fleet's own queue), then every current session with source labels and plain-language states. Finished runs and stale items expire out. | `/api/attention.json`, `/api/coverage.json` | -| `/` | **Cross-repo WIP board** — the curated in-flight set across all four repos, with an execution strip per card (implementing → review → merged → queued). | `/api/board.json` | -| `/roadmap` | **Roadmap** — Grist's `Program roadmap` table as a timeline; `?h=` switches the horizon: `quarter` (default), `month`, `week`, `3d`, `today` — one data model at every grain. | `/api/roadmap.json` | -| `/quota` | **Usage & billing** (hub, design 2026-10-25; pools from #851) — needs-attention strip (bubble rules: >80% of a limit, >$5 projected unbilled PAYG), token-quota pools + PAYG dollars card, SaaS service cards grouped by kind with highlight metrics, charges evidence strip. Per-service detail: `/quota/service/`. | `/api/quota.json` (extended: `saas`/`payg`/`charges`/…), `/api/quota/service.json?id=` | -| `/dns` | **DNS / domain register** (slice 3, #906; data owned by #902) — the register rendered next-renewal-first: renewing-soon spend, then in-use / unused-but-earmarked / completely-unused views and the full table. | `/api/dns.json` | -| `/sessions` | **Sessions** (slice 3, #906) — the identity registry: every known session with its stable id, agent identity, parent, task refs, and token total, grouped by source. | `/api/registry.json` | -| `/program` | **Program status — projects index** (#1046, generalized #1121) — one card per configured project (title, live Project-pool counts by status for its Area, Grist roadmap row count, home-doc link), the whole-pool summary, orchestration freshness, and the pool's unset-Area count as a visible gap. Driven by the project registry in `src/project-config.ts`. | `/api/program.json` (incl. per-project summaries) | -| `/program/` | **Project page** (#1121) — one per registry entry (pm-dashboard, lab-cluster, id, repo-fleet, mcpx, cloud-program): intro + home-doc/dashboard links, live tracked-issue states, its Area's pool items grouped by status, its roadmap area's rows, and editorial done/next/long-term/gaps where configured. Null Area/roadmap/home-doc render as honest gap notes, never empty sections. The full PM-dashboard document (#1046) lives at `/program/pm-dashboard`. | `/api/program-project.json?id=` | -| `/pages` | **All pages** — the page manifest rendered: every registered page, its route, and its JSON twin. | — (the manifest is `src/pages.ts`) | -| `/discuss/` | **Comment thread** for one object ref (a `gh:` ref, an `orch:` tier item, a `session:` id, a board item, a roadmap subject) — dashboard comments + the post form. | `/api/comments.json?object=` | -| `/item/` | Drill-down for one board card or roadmap row: linked refs + a unified comment stream, plus its dashboard comments and the sessions that worked it. | — | +| Route | View | Machine-first JSON | +| ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | +| `/today` | **Today** (slice 2, #898) — the day's top objectives, prioritized, plus per-project momentum (moving / stalled / blocked-by-what, recent accomplishments). From the orchestration job's goal measurements (#899) when a section exists; derived from board + roadmap + item activity, and labelled as derived, until then. | `/api/today.json` | +| `/attention` | **Needs you** (#852, tiered in slice 2) — **NEEDS USER** (default; the intake queue the orchestrator works first — only items it cannot resolve escalate here, each with its reason), **NEEDS ORCHESTRATOR** (the fleet's own queue), then every current session with source labels and plain-language states. Finished runs and stale items expire out. | `/api/attention.json`, `/api/coverage.json` | +| `/` | **Cross-repo WIP board** — the curated in-flight set across all four repos, with an execution strip per card (implementing → review → merged → queued). | `/api/board.json` | +| `/roadmap` | **Roadmap** — Grist's `Program roadmap` table as a timeline; `?h=` switches the horizon: `quarter` (default), `month`, `week`, `3d`, `today` — one data model at every grain. | `/api/roadmap.json` | +| `/quota` | **Usage & billing** (hub, design 2026-10-25; pools from #851) — needs-attention strip (bubble rules: >80% of a limit, >$5 projected unbilled PAYG), token-quota pools + PAYG dollars card, SaaS service cards grouped by kind with highlight metrics, charges evidence strip. Per-service detail: `/quota/service/`. | `/api/quota.json` (extended: `saas`/`payg`/`charges`/…), `/api/quota/service.json?id=` | +| `/dns` | **DNS / domain register** (slice 3, #906; data owned by #902) — the register rendered next-renewal-first: renewing-soon spend, then in-use / unused-but-earmarked / completely-unused views and the full table. | `/api/dns.json` | +| `/sessions` | **Sessions** (slice 3, #906) — the identity registry: every known session with its stable id, agent identity, parent, task refs, and token total, grouped by source. | `/api/registry.json` | +| `/program` | **Program status — projects index** (#1046, generalized #1121) — one card per configured project (title, live Project-pool counts by status for its Area, Grist roadmap row count, home-doc link), the whole-pool summary, orchestration freshness, and the pool's unset-Area count as a visible gap. Driven by the project registry in `src/project-config.ts`. | `/api/program.json` (incl. per-project summaries) | +| `/program/` | **Project page** (#1121) — one per registry entry (pm-dashboard, lab-cluster, id, repo-fleet, mcpx, cloud-program): intro + home-doc/dashboard links, live tracked-issue states, its Area's pool items grouped by status, its roadmap area's rows, and editorial done/next/long-term/gaps where configured. Null Area/roadmap/home-doc render as honest gap notes, never empty sections. The full PM-dashboard document (#1046) lives at `/program/pm-dashboard`. | `/api/program-project.json?id=` | +| `/health` | **Health & topology** (#1147 + #1137) — every stack service probed live (60 s probe cache): the aggregator, Kaneo, its Postgres, ready-for-agent, Pad, Grist, the fleet-feed collector, the orchestration pass, and the projector (off by config, stated not implied); the services & ports topology table (port, bind, runs-as, consumers, what breaks); feed section ages; last job runs; per-source facets; and this dashboard's own per-page render history (in-process registry — an unrendered page says so, never fake-green). | `/api/health` (extended in place: `services` / `feed` / `pages` / `jobs` beside the original `status` / `source` / `sections`) | +| `/pages` | **All pages** — the page manifest rendered: every registered page, its route, and its JSON twin. | — (the manifest is `src/pages.ts`) | +| `/discuss/` | **Comment thread** for one object ref (a `gh:` ref, an `orch:` tier item, a `session:` id, a board item, a roadmap subject) — dashboard comments + the post form. | `/api/comments.json?object=` | +| `/item/` | Drill-down for one board card or roadmap row: linked refs + a unified comment stream, plus its dashboard comments and the sessions that worked it. | — | All views are mobile-first (single-column stacking, scrollable tables, touch-sized switchers) — verify at phone width, not by resizing a desktop @@ -430,6 +431,10 @@ src/ project + validation + the per-project live builders the index, project pages, and JSON twins read (#1120) derive.ts execution strip, timeline lanes, quota/attention rules + topology.ts the services & ports registry: what runs where, bound + how, consumed by whom (#1137) + health.ts /health assembly: cached service probes, feed ages, + job runs, the render registry (#1147) render.ts pure HTML rendering of every view server.ts Bun HTTP server (pages, JSON twins, comment writes) config.ts env config @@ -465,4 +470,7 @@ test/ page manifest, slice-3 renders + HTTP flows program.test.ts /program manifest entry, live-data builder (empty/absent/null inputs), render smoke (#1046) + health.test.ts health assembly vs fake fetchers (up/down/timeout/ + cache/degraded), fixtures story, /health boot + (#1137, #1147) ``` diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index 2a1b905707..c47c9bb1c6 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -42,6 +42,15 @@ export interface Config { projector: { baseUrl: string | null; }; + /** Probe targets for the /health page (#1147): the stack services the + * aggregator does not otherwise read. Kaneo/Grist/projector targets + * already live in their own sections above. */ + pad: { + baseUrl: string; + }; + readyForAgent: { + baseUrl: string; + }; } export function loadConfig(env: Record = process.env): Config { @@ -92,5 +101,11 @@ export function loadConfig(env: Record = process.env ? null : s(env.PM_PROJECTOR_URL, "http://127.0.0.1:7801"), }, + pad: { + baseUrl: s(env.PM_AGG_PAD_URL, "http://127.0.0.1:7777"), + }, + readyForAgent: { + baseUrl: s(env.PM_AGG_RFA_URL, "http://127.0.0.1:6056"), + }, }; } diff --git a/pm-stack/aggregator/src/health.ts b/pm-stack/aggregator/src/health.ts new file mode 100644 index 0000000000..1c9b885c04 --- /dev/null +++ b/pm-stack/aggregator/src/health.ts @@ -0,0 +1,341 @@ +// Health assembly for /health + /api/health (#1147): per-service +// probe state, per-section feed ages, job runs, and this process's +// own page-render history — assembled from the same readers the rest +// of the dashboard trusts, so the page and the API can never disagree. +// +// Honesty rules (the #1110/#1139 lessons, applied to health itself): +// - Probes are real HTTP reads of the loopback targets in +// src/topology.ts (from config where config has them), cached 60 s +// so a human refreshing — or a watchdog polling — never fans out to +// five services per hit. A failed probe renders as a failed probe, +// with its error and its age; nothing here invents a state. +// - The projector (off by config) is never probed and never red. +// - Page health is an in-process render registry (server.ts records +// each successful page render), never self-HTTP: a route nobody has +// opened is labelled "not rendered since boot", not fake-green. +// - In fixtures mode there are no live probes to make: every service +// reports "fixtures", which is also the degraded-state test fixture. +import type { Config } from "./config.ts"; +import { ageMsText, type FleetFeed, type SectionDiagnosis } from "./feed.ts"; +import type { ProvenanceDetail } from "./model.ts"; +import { PAGES } from "./pages.ts"; +import { buildServices, type ServiceDef } from "./topology.ts"; + +/** Same staleness threshold live.ts applies to feed-backed facets. */ +const FEED_STALE_MS = 15 * 60_000; +/** Orchestration cadence: hourly; next run is an expectation, not a promise. */ +const ORCHESTRATION_CADENCE_MS = 3_600_000; + +export const PROBE_CACHE_MS = 60_000; +export const PROBE_TIMEOUT_MS = 1_500; + +/** The minimal fetch shape probes need — injectable for tests. */ +export type ProbeFetch = ( + url: string, + init: { signal: AbortSignal; redirect: "manual" }, +) => Promise<{ status: number }>; + +const defaultProbeFetch: ProbeFetch = async (url, init) => { + const res = await fetch(url, init); + return { status: res.status }; +}; + +export interface ProbeOutcome { + state: ServiceState; + ok: boolean | null; + detail: string; + statusCode?: number; + /** When the probe actually ran (a cached outcome keeps its own time). */ + probedAtMs?: number; +} + +export type ServiceState = "up" | "down" | "stale" | "absent" | "invalid" | "unknown" | "off" | "self" | "fixtures"; + +export interface ProbeCache { + entries: Map; +} + +export function createProbeCache(): ProbeCache { + return { entries: new Map() }; +} + +const sharedProbeCache = createProbeCache(); + +async function probeHttp(def: ServiceDef, fetcher: ProbeFetch, cache: ProbeCache, now: number): Promise { + const hit = cache.entries.get(def.id); + if (hit && now - hit.at < PROBE_CACHE_MS) return hit.outcome; + const url = `${def.loopbackUrl}${def.healthPath ?? "/"}`; + let outcome: ProbeOutcome; + try { + const res = await fetcher(url, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS), redirect: "manual" }); + const expected = def.expectStatuses ?? [200]; + outcome = expected.includes(res.status) + ? { state: "up", ok: true, detail: `HTTP ${res.status}`, statusCode: res.status, probedAtMs: now } + : { + state: "down", + ok: false, + detail: `HTTP ${res.status} — expected ${expected.join(" or ")}`, + statusCode: res.status, + probedAtMs: now, + }; + } catch (err) { + const name = err instanceof Error ? err.name : ""; + const detail = + name === "TimeoutError" || name === "AbortError" + ? `probe timed out after ${PROBE_TIMEOUT_MS / 1000}s` + : `probe failed: ${err instanceof Error ? err.message : String(err)}`; + outcome = { state: "down", ok: false, detail, probedAtMs: now }; + } + cache.entries.set(def.id, { at: now, outcome }); + return outcome; +} + +export interface ServiceHealth { + def: ServiceDef; + state: ServiceState; + ok: boolean | null; + detail: string; + statusCode?: number; + probedAt?: string; +} + +export interface FeedSectionHealth { + key: string; + present: boolean; + /** The timestamp the age is measured from (the section's own when it has one). */ + generatedAt?: string; + ageMs?: number; + note?: string; +} + +export interface PageHealth { + route: string; + title: string; + lastRenderedAt: string | null; + ok: boolean | null; + ageMs: number | null; +} + +export interface HealthView { + /** The aggregator process itself is up if it assembled this view. */ + status: "ok"; + mode: "live" | "fixtures"; + generatedAt: string; + bootAt: string; + degraded: boolean; + services: ServiceHealth[]; + feed: { + generatedAt: string | null; + fileMtime: string | null; + ageMs: number | null; + sections: FeedSectionHealth[]; + }; + jobs: { + orchestration: { + state: SectionDiagnosis["state"] | "unknown"; + runId?: string; + generatedAt?: string; + ageMs?: number; + nextExpectedAt?: string; + failedChecks?: string[]; + }; + collector: { generatedAt: string | null; fileMtime: string | null; ageMs: number | null }; + }; + pages: PageHealth[]; + facets: ProvenanceDetail | null; +} + +// --- Render registry ------------------------------------------------------- +// server.ts records every successful page render here. Module scope +// ≈ process scope: BOOT_AT is when this process started serving. + +const BOOT_AT = Date.now(); +const renderLog = new Map(); + +export function recordRender(route: string, ok: boolean, at = Date.now()): void { + renderLog.set(route, { at, ok }); +} + +export function renderRegistrySize(): number { + return renderLog.size; +} + +function pageHealth(now: number): PageHealth[] { + return PAGES.map((p) => { + const mark = renderLog.get(p.route); + if (!mark) return { route: p.route, title: p.title, lastRenderedAt: null, ok: null, ageMs: null }; + return { + route: p.route, + title: p.title, + lastRenderedAt: new Date(mark.at).toISOString(), + ok: mark.ok, + ageMs: Math.max(0, now - mark.at), + }; + }); +} + +// --- Feed sections --------------------------------------------------------- + +function feedSections(feed: FleetFeed | null, now: number): FeedSectionHealth[] { + if (!feed) return []; + const from = (generatedAt: string | undefined, present: boolean, note?: string): Partial => { + const ts = generatedAt ?? feed.generatedAt; + return { present, generatedAt: ts, ageMs: Math.max(0, now - Date.parse(ts)), ...(note ? { note } : {}) }; + }; + const aa = feed.aa; + const aaNote = + aa && "status" in aa && aa.status === "absent" + ? `absent form: ${"reason" in aa ? String(aa.reason) : "no reason given"}` + : undefined; + return [ + { key: "quota", ...from(undefined, true) }, + { key: "attention", ...from(undefined, true) }, + { key: "orchestration", ...from(feed.orchestration?.generatedAt, feed.orchestration !== undefined) }, + { key: "dns", ...from(feed.dns?.generatedAt, feed.dns !== undefined) }, + { key: "registry", ...from(undefined, feed.registry !== undefined) }, + { key: "projects", ...from(undefined, feed.projects !== undefined) }, + { key: "saas", ...from(undefined, feed.saas !== undefined) }, + { key: "payg", ...from(undefined, feed.payg !== undefined) }, + { key: "charges", ...from(undefined, feed.charges !== undefined) }, + { key: "subscriptions", ...from(undefined, feed.subscriptions !== undefined) }, + { key: "snapshots", ...from(undefined, feed.snapshots !== undefined) }, + { key: "aa", ...from(aa?.generatedAt, aa !== undefined, aaNote) }, + ] as FeedSectionHealth[]; +} + +// --- Assembly --------------------------------------------------------------- + +export interface HealthInputs { + mode: "live" | "fixtures"; + cfg: Config; + feed: FleetFeed | null; + feedFileMtimeMs: number | null; + diagnosis?: SectionDiagnosis; + detail?: ProvenanceDetail; +} + +export interface HealthDeps { + fetcher?: ProbeFetch; + cache?: ProbeCache; + now?: number; +} + +export async function buildHealth(inputs: HealthInputs, deps: HealthDeps = {}): Promise { + const now = deps.now ?? Date.now(); + const fetcher = deps.fetcher ?? defaultProbeFetch; + const cache = deps.cache ?? sharedProbeCache; + const { cfg, feed } = inputs; + const feedAgeMs = feed ? Math.max(0, now - Date.parse(feed.generatedAt)) : null; + const diagnosis = inputs.diagnosis; + + const services: ServiceHealth[] = []; + const outcomes = new Map(); + for (const def of buildServices(cfg)) { + let outcome: ProbeOutcome; + if (inputs.mode === "fixtures") { + outcome = { state: "fixtures", ok: null, detail: "fixtures mode — no live probes are made" }; + } else if (def.probe === "off") { + outcome = { state: "off", ok: null, detail: "off by config — never probed, not an error" }; + } else if (def.probe === "self") { + outcome = { state: "self", ok: true, detail: "this process — it assembled this view" }; + } else if (def.probe === "http") { + outcome = await probeHttp(def, fetcher, cache, now); + } else if (def.probe === "feed") { + outcome = + feed === null + ? { state: "down", ok: false, detail: "no readable fleet feed" } + : feedAgeMs !== null && feedAgeMs > FEED_STALE_MS + ? { state: "stale", ok: false, detail: `feed ${ageMsText(feedAgeMs)} — past the 15m freshness threshold` } + : { state: "up", ok: true, detail: `feed ${feedAgeMs !== null ? ageMsText(feedAgeMs) : ""}`.trim() }; + } else if (def.probe === "section") { + if (!diagnosis) { + outcome = { state: "unknown", ok: null, detail: "this source reports no section diagnosis" }; + } else if (diagnosis.state === "live") { + outcome = { + state: "up", + ok: true, + detail: + `section ${diagnosis.runId ?? ""} · ${diagnosis.ageMs !== undefined ? ageMsText(diagnosis.ageMs) : ""}`.trim(), + }; + } else if (diagnosis.state === "stale") { + outcome = { + state: "stale", + ok: false, + detail: `section ${diagnosis.runId ?? ""} is ${diagnosis.ageMs !== undefined ? ageMsText(diagnosis.ageMs) : "old"} — past the 90m stale threshold`, + }; + } else if (diagnosis.state === "invalid") { + outcome = { + state: "invalid", + ok: false, + detail: `section present but rejected — failed checks: ${(diagnosis.failedChecks ?? []).join(", ") || "unknown"}`, + }; + } else { + outcome = { + state: "absent", + ok: false, + detail: "no orchestration section in the feed the aggregator received", + }; + } + } else { + // probe === "inferred": follows the named service's outcome. + const parent = def.inferredFrom ? outcomes.get(def.inferredFrom) : undefined; + outcome = + parent === undefined + ? { state: "unknown", ok: null, detail: "the service this is inferred from has no probe outcome" } + : parent.state === "up" + ? { state: "up", ok: true, detail: `inferred from ${def.inferredFrom} — container-internal, no host probe` } + : { + state: "unknown", + ok: null, + detail: `cannot infer — ${def.inferredFrom} is ${parent.state}, which proves nothing about this service`, + }; + } + outcomes.set(def.id, outcome); + services.push({ + def, + state: outcome.state, + ok: outcome.ok, + detail: outcome.detail, + ...(outcome.statusCode !== undefined ? { statusCode: outcome.statusCode } : {}), + ...(outcome.probedAtMs !== undefined ? { probedAt: new Date(outcome.probedAtMs).toISOString() } : {}), + }); + } + + const degraded = + inputs.mode === "live" && + (services.some((s) => s.ok === false) || (feedAgeMs !== null && feedAgeMs > FEED_STALE_MS)); + + return { + status: "ok", + mode: inputs.mode, + generatedAt: new Date(now).toISOString(), + bootAt: new Date(BOOT_AT).toISOString(), + degraded, + services, + feed: { + generatedAt: feed?.generatedAt ?? null, + fileMtime: inputs.feedFileMtimeMs !== null ? new Date(inputs.feedFileMtimeMs).toISOString() : null, + ageMs: feedAgeMs, + sections: feedSections(feed, now), + }, + jobs: { + orchestration: { + state: diagnosis?.state ?? "unknown", + ...(diagnosis?.runId ? { runId: diagnosis.runId } : {}), + ...(diagnosis?.generatedAt ? { generatedAt: diagnosis.generatedAt } : {}), + ...(diagnosis?.ageMs !== undefined ? { ageMs: diagnosis.ageMs } : {}), + ...(diagnosis?.generatedAt + ? { nextExpectedAt: new Date(Date.parse(diagnosis.generatedAt) + ORCHESTRATION_CADENCE_MS).toISOString() } + : {}), + ...(diagnosis?.failedChecks ? { failedChecks: diagnosis.failedChecks } : {}), + }, + collector: { + generatedAt: feed?.generatedAt ?? null, + fileMtime: inputs.feedFileMtimeMs !== null ? new Date(inputs.feedFileMtimeMs).toISOString() : null, + ageMs: feedAgeMs, + }, + }, + pages: pageHealth(now), + facets: inputs.detail ?? null, + }; +} diff --git a/pm-stack/aggregator/src/pages.ts b/pm-stack/aggregator/src/pages.ts index 8c743455f1..90d92a5452 100644 --- a/pm-stack/aggregator/src/pages.ts +++ b/pm-stack/aggregator/src/pages.ts @@ -88,6 +88,14 @@ export const PAGES: PageDef[] = [ blurb: "The projects hub: every project's status, roadmap, and tracked work, one page per project under /program/ — fed from the project registry, the tracked issues, and the Project pool.", }, + { + id: "health", + title: "Health", + route: "/health", + api: "/api/health", + blurb: + "Service & page health (#1147): live probes for every stack service, feed section ages, last job runs, this dashboard's render history — and the services & ports topology (#1137).", + }, { id: "pages", title: "All pages", diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 2490a27451..3bb6e90c9b 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -24,6 +24,7 @@ import { githubCommentUrl } from "./comments.ts"; import { summarizeAa } from "./aa.ts"; import { summarizeDns } from "./dns.ts"; import { ageMsText, feedAgeText } from "./feed.ts"; +import type { HealthView } from "./health.ts"; import { type AaConfig, type AaFeedSection, @@ -132,6 +133,12 @@ meter { width: 140px; height: 14px; } .fchip.stale { border-color: #d29922; color: #e3b341; } .fchip.invalid { border-color: #f85149; color: #f85149; } .fchip.absent { border-color: #d29922; color: #e3b341; } +.dot { display: inline-block; width: 9px; height: 9px; border-radius: 50%; margin-right: 6px; background: #8b949e; vertical-align: baseline; } +.dot.up, .dot.self { background: #3fb950; } +.dot.down, .dot.invalid { background: #f85149; } +.dot.stale, .dot.absent { background: #d29922; } +.dot.off, .dot.unknown { background: #8b949e; } +.dot.fixtures { background: #bc8cff; } .srcdetail { margin: 6px 0; } .srcdetail summary { cursor: pointer; } .reason { border-left: 3px solid #f85149; padding: 6px 10px; margin: 8px 0 2px; background: #f851490d; } @@ -944,9 +951,9 @@ function sessionCard( : ""; const tierBadge = e.tier === "needs-drew" - ? `needs user` + ? `Needs User` : e.tier === "needs-orchestrator" - ? `needs orchestrator` + ? `Needs Orchestrator` : ""; const evidence = e.supervisionNote ? `${e.evidence} Keeper: ${e.supervisionNote}` : e.evidence; const reason = e.drewReason ? `
Why you: ${esc(e.drewReason)}
` : ""; @@ -1007,7 +1014,7 @@ export function renderAttention( : ""; const drewCount = ts.present ? String(drewTotal) : "unknown"; const orchCount = ts.present ? String(orchTotal) : "unknown"; - const chips = ``; + const chips = ``; const drewCards = [ ...view.drew.map((e) => sessionCard(e, children, 0, counts)), @@ -1032,8 +1039,8 @@ export function renderAttention( `

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.

${tierBanner}${chips} ${coverageHtml(coverage)} -

Needs user (${drewCount})${sectionStamp}

${drewCards} -

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

Needs User (${drewCount})${sectionStamp}

${drewCards} +

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}

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.

` : ""}`, provenance, @@ -1324,6 +1331,93 @@ export function renderPages(provenance: Provenance): string { ); } +// --- 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) => + `${esc(s.key)}${s.present ? "present" : 'absent'}${s.ageMs !== undefined ? esc(ageMsText(s.ageMs)) : "—"}${s.note ? esc(s.note) : ""}`, + ) + .join("") + : `No readable fleet feed — sections cannot be reported.`; + 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 collLine = coll.generatedAt + ? `feed generated ${esc(ageMsText(coll.ageMs ?? 0))} · file written ${coll.fileMtime ? esc(coll.fileMtime) : "unknown"}` + : "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(""); + 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; the projector is off by config and says so.

+
${serviceRows}
ServicePortBindRuns asStateConsumed byIf it is down
+

Feed sections

+
${sectionRows}
SectionPresentAgeNote
+

Jobs

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

Source facets

+${facets} +

Pages

+

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

+
${pageRows}
PageRouteLast rendered
`; + return layout("Health", body, provenance, "/health"); +} + // --- Discuss page (one object's dashboard comments) ----------------------------- export function renderDiscuss( @@ -1505,6 +1599,7 @@ export function renderProgram( 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} diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 5fba59dc0b..93f7d66fb0 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -3,8 +3,12 @@ // adds the app's first writes — dashboard comments (POST /api/comments // and its triage/github-result companions); everything underneath // (GitHub, Kaneo, Grist) stays read-only from here. +import { stat } from "node:fs/promises"; import { CommentsStore, validateNewComment } from "./comments.ts"; import { loadConfig } from "./config.ts"; +import { loadFeed } from "./feed.ts"; +import { buildHealth, recordRender, type HealthView } from "./health.ts"; +import { PAGES } from "./pages.ts"; import { allRefs, buildAttention, deriveToday, projectPace, type RoadmapGrain } from "./derive.ts"; import type { DashComment, RefKey } from "./model.ts"; import { buildProgramData, programRefs } from "./program.ts"; @@ -23,6 +27,7 @@ import { renderBoard, renderDiscuss, renderDns, + renderHealth, renderItem, renderPages, renderProgram, @@ -90,6 +95,32 @@ async function ensureProvenancePrimed(): Promise { await priming; } +/** + * The one health assembly behind both /health and /api/health + * (#1147): primed provenance first (so facet truth never depends on + * request order, #1267), then the feed snapshot the section ages and + * job lines are measured from, then buildHealth's probes (cached + * 60 s inside health.ts). Page and API read this same view, so they + * cannot disagree. + */ +async function healthContext(): Promise { + await ensureProvenancePrimed(); + const [feed, feedFileMtimeMs] = await Promise.all([ + loadFeed(cfg.feedFile).catch(() => null), + stat(cfg.feedFile) + .then((s) => s.mtimeMs) + .catch(() => null), + ]); + return buildHealth({ + mode: cfg.source, + cfg, + feed, + feedFileMtimeMs, + diagnosis: source.diagnostics?.().orchestration, + detail: source.provenanceDetail?.(), + }); +} + /** Author identities for the comment form: standing + registry sessions. */ async function commentFormOpts(githubRefs: RefKey[] = []): Promise { const records = await source.registry().catch(() => []); @@ -361,6 +392,11 @@ async function handler(req: Request): Promise { return json(buildProjectDetail(config, items, pool, rows)); } + if (path === "/health") { + const view = await healthContext(); + return html(renderHealth(view, prov())); + } + if (path === "/pages") { return html(renderPages(prov())); } @@ -433,10 +469,24 @@ async function handler(req: Request): Promise { // #1267: prime first — health's answer must not depend on // request order. `sections` carries the structured diagnosis // (#1140) beside the provenance strings for machine consumers. - await ensureProvenancePrimed(); + // #1147 extends the shape in place (services/feed/pages/jobs + // added from the same assembly /health renders; the existing + // status/source/sections keys are unchanged). + const view = await healthContext(); const body: Record = { status: "ok", source: prov() }; const diag = source.diagnostics?.(); if (diag) body.sections = diag; + body.services = view.services.map((s) => ({ + id: s.def.id, + state: s.state, + ok: s.ok, + detail: s.detail, + ...(s.probedAt ? { probedAt: s.probedAt } : {}), + })); + body.feed = { generatedAt: view.feed.generatedAt, fileMtime: view.feed.fileMtime }; + body.pages = view.pages.map((p) => ({ route: p.route, lastRenderedAt: p.lastRenderedAt, ok: p.ok })); + body.jobs = view.jobs; + body.degraded = view.degraded; return json(body); } @@ -475,6 +525,31 @@ async function handler(req: Request): Promise { return json({ error: "not found", path }, 404); } +/** + * #1147's render registry: every successful HTML page render is + * recorded against its manifest route (subroutes count toward their + * parent page), so /health can report each page's real last-render + * time — measured from actual traffic, never self-probed. + */ +function manifestRouteFor(path: string): string | null { + const exact = PAGES.find((p) => p.route === path); + if (exact) return exact.route; + if (path.startsWith("/program/")) return "/program"; + if (path.startsWith("/quota/service/")) return "/quota"; + return null; +} + +async function fetchHandler(req: Request): Promise { + const res = await handler(req); + if (req.method === "GET") { + const route = manifestRouteFor(new URL(req.url).pathname); + if (route && (res.headers.get("content-type") ?? "").includes("text/html")) { + recordRender(route, res.status < 400); + } + } + return res; +} + // One server per bind address (PM_AGG_HOSTS). Deployment on the // laptop binds loopback + the tailnet address, like Pad/Grist — no // public route (Drew, 2026-10-25: public only behind a password). @@ -482,7 +557,7 @@ const servers = cfg.hosts.map((hostname) => Bun.serve({ hostname, port: cfg.port, - fetch: handler, + fetch: fetchHandler, }), ); diff --git a/pm-stack/aggregator/src/topology.ts b/pm-stack/aggregator/src/topology.ts new file mode 100644 index 0000000000..a7736e828a --- /dev/null +++ b/pm-stack/aggregator/src/topology.ts @@ -0,0 +1,168 @@ +// The PM stack's services & ports topology (#1137): what runs where, +// bound how, consumed by whom. This is the registry the /health page +// renders (with live probe state from src/health.ts) — one home for +// the table, linked from /program, never duplicated. +// +// Identity facts (port, bind, runs-as, purpose) are static text: they +// change only when the stack is redeployed, and the implementing PR +// re-verified every row against laptop ground truth (ss -tln, +// systemctl --user, docker ps) on 2026-10-27. Anything that can rot — +// reachability, ages, section state — is NEVER encoded here; it comes +// from probes, the feed, and the section diagnosis at render time. +// Probe targets come from config where config has them (Kaneo, Grist, +// projector) so an env override moves the probe with the reader. +import type { Config } from "./config.ts"; + +/** How a service's current state is established (#1147). */ +export type ProbeKind = + /** HTTP probe of loopbackUrl + healthPath against expectStatuses. */ + | "http" + /** This very process — serving the page is the proof. */ + | "self" + /** No listener to probe: the fleet feed file's freshness is the pulse. */ + | "feed" + /** State is the orchestration section diagnosis, verbatim. */ + | "section" + /** Inferred from another service's probe (named in `inferredFrom`). */ + | "inferred" + /** Off by config: never probed, never an error. */ + | "off"; + +export interface ServiceDef { + id: string; + name: string; + /** Listener port, or null when the component has none. */ + port: number | null; + /** The bind as actually deployed — stated plainly, never softened. */ + bind: string; + /** systemd unit / container / scheduler that runs it. */ + runsAs: string; + probe: ProbeKind; + /** Probe target for probe:"http" (from config where config has it). */ + loopbackUrl?: string; + healthPath?: string; + /** HTTP statuses that prove life for this service. */ + expectStatuses?: number[]; + /** Human form of expectStatuses, rendered in the table. */ + upWhen?: string; + /** For probe:"inferred" — the service id whose probe this follows. */ + inferredFrom?: string; + /** Who reads it. */ + consumers: string; + /** What degrades when it is down. */ + breaksIfDown: string; + notes?: string; +} + +export function buildServices(cfg: Config): ServiceDef[] { + return [ + { + id: "aggregator", + name: "Aggregator (this dashboard)", + port: cfg.port, + bind: "loopback + tailnet", + runsAs: "pm-aggregator.service (bun)", + probe: "self", + consumers: "the user — the single URL for the whole stack", + breaksIfDown: "the dashboard itself; every view is gone", + }, + { + id: "kaneo", + name: "Kaneo", + port: 5173, + bind: "loopback only · public via Cloudflare tunnel (kaneo.security.cab, pm-tunnel.service)", + runsAs: "container pm-stack-kaneo-1", + probe: "http", + loopbackUrl: cfg.kaneo.baseUrl, + healthPath: "/api/health", + expectStatuses: [200], + upWhen: "HTTP 200 on /api/health", + consumers: "the aggregator's board (its curated WIP set)", + breaksIfDown: "the board loses its live source and falls back to fixtures", + }, + { + id: "kaneo-postgres", + name: "Kaneo Postgres", + port: 5432, + bind: "container-internal only (no host listener)", + runsAs: "container pm-stack-postgres-1", + probe: "inferred", + inferredFrom: "kaneo", + consumers: "Kaneo only", + breaksIfDown: "Kaneo is down with it — its state is inferred from Kaneo's probe", + }, + { + id: "ready-for-agent", + name: "ready-for-agent", + port: 6056, + bind: "0.0.0.0 — every interface, incl. LAN (bind scope tracked in #1181)", + runsAs: "ready-for-agent.service", + probe: "http", + loopbackUrl: cfg.readyForAgent.baseUrl, + healthPath: "/", + expectStatuses: [200], + upWhen: "HTTP 200", + consumers: "GitHub issues across the fleet (label-driven dispatch)", + breaksIfDown: "queued issue dispatch stops; issues wait for the next runner", + }, + { + id: "pad", + name: "Pad", + port: 7777, + bind: "loopback + tailnet", + runsAs: "container pad-pad-1", + probe: "http", + loopbackUrl: cfg.pad.baseUrl, + healthPath: "/", + expectStatuses: [200], + upWhen: "HTTP 200", + consumers: "the user and agents — shared plans and docs", + breaksIfDown: "shared planning docs are unreachable", + }, + { + id: "grist", + name: "Grist", + port: 8484, + bind: "loopback + tailnet", + runsAs: "container grist-grist-1", + probe: "http", + loopbackUrl: cfg.grist.baseUrl, + healthPath: "/", + expectStatuses: [200, 302], + upWhen: "HTTP 200 or 302 (Grist answers 302 on /)", + consumers: 'the aggregator\'s roadmap (its "Program roadmap" doc) and the collector', + breaksIfDown: "the roadmap loses its live source and falls back to the feed/fixtures", + }, + { + id: "fleet-feed", + name: "Fleet-feed collector", + port: null, + bind: "— (no listener)", + runsAs: "sandbox systemd timer (fleet-feed-collector, ~5 min cadence)", + probe: "feed", + consumers: "the aggregator — most live facets read the feed it pushes", + breaksIfDown: "feed-backed facets go stale, then fall back to fixtures", + }, + { + id: "orchestration", + name: "Orchestration pass", + port: null, + bind: "— (no listener)", + runsAs: "hourly cron (orchestration-pass)", + probe: "section", + consumers: "the aggregator's Today / Needs User / board in-flight lane", + breaksIfDown: "tiers fall back to derived views; the honesty banners name it", + }, + { + id: "projector", + name: "Projector", + port: 7801, + bind: "— (not running)", + runsAs: "off by config (PM_PROJECTOR_URL=off)", + probe: "off", + consumers: "the aggregator's comment/registry projection (disabled while off)", + breaksIfDown: "nothing — while off, the comment projection runs on fixtures by design", + notes: "Off is a configuration state, not a failure.", + }, + ]; +} diff --git a/pm-stack/aggregator/test/boot.test.ts b/pm-stack/aggregator/test/boot.test.ts index c16cf518cd..7859727a20 100644 --- a/pm-stack/aggregator/test/boot.test.ts +++ b/pm-stack/aggregator/test/boot.test.ts @@ -63,11 +63,11 @@ describe("server boots from fixtures", () => { const attention = await (await fetch(`http://127.0.0.1:${port}/attention`)).text(); expect(quota.includes("Usage & billing")).toBe(true); // the hub retitle (design 2026-10-25 §1.1) expect(attention.includes("Needs you")).toBe(true); - expect(attention.includes("Needs user")).toBe(true); + expect(attention.includes("Needs User")).toBe(true); // Fixtures carry no orchestration section, so the tier honesty // banner renders and the tier counts are "unknown", never 0 (#1139). expect(attention.includes("Tier source missing")).toBe(true); - expect(attention.includes("Needs user (unknown)")).toBe(true); + expect(attention.includes("Needs User (unknown)")).toBe(true); expect(attention.includes("Session coverage")).toBe(true); expect(attention.includes("amd-6.raptor-pumpkinseed.ts.net")).toBe(true); }); diff --git a/pm-stack/aggregator/test/health.test.ts b/pm-stack/aggregator/test/health.test.ts new file mode 100644 index 0000000000..1e68776741 --- /dev/null +++ b/pm-stack/aggregator/test/health.test.ts @@ -0,0 +1,284 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { spawn, type Subprocess } from "bun"; +import { loadConfig } from "../src/config.ts"; +import type { FleetFeed, SectionDiagnosis } from "../src/feed.ts"; +import { buildHealth, createProbeCache, recordRender, type HealthInputs, type ProbeFetch } from "../src/health.ts"; + +// #1147/#1137: health assembly — service probes (injectable fetcher, +// 60 s cache), feed section ages, job runs, the render registry, and +// the fixtures-mode story. The degraded states are proven here with +// fake fetchers; no service is ever killed on the laptop for a test. + +const NOW = Date.parse("2026-10-27T06:00:00Z"); +const cfg = loadConfig({}); + +function feedAt(ageMs: number): FleetFeed { + const generatedAt = new Date(NOW - ageMs).toISOString(); + return { + version: 1, + generatedAt, + quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, + attention: [], + orchestration: { + version: 1, + generatedAt, + runId: "orch-health-unit", + provenance: { sources: ["unit test"] }, + tiers: { needsDrew: [], needsOrchestrator: [] }, + dependencies: [], + goals: [], + actions: [], + }, + dns: { generatedAt, source: "unit", totalAnnualListUsd: 0, entries: [] }, + registry: [], + projects: [], + } as unknown as FleetFeed; +} + +const LIVE_DIAGNOSIS: SectionDiagnosis = { + state: "live", + runId: "orch-health-unit", + generatedAt: new Date(NOW - 60_000).toISOString(), + ageMs: 60_000, +}; + +function inputs(over: Partial = {}): HealthInputs { + return { + mode: "live", + cfg, + feed: feedAt(5 * 60_000), + feedFileMtimeMs: NOW - 4 * 60_000, + diagnosis: LIVE_DIAGNOSIS, + ...over, + }; +} + +/** A fetcher that answers per-URL and records every call. */ +function fakeFetcher(handler: (url: string) => { status: number } | Error) { + const calls: string[] = []; + const fetcher: ProbeFetch = async (url) => { + calls.push(url); + const out = handler(url); + if (out instanceof Error) throw out; + return out; + }; + return { fetcher, calls }; +} + +const allUp = () => ({ status: 200 }); + +function service(view: Awaited>, id: string) { + const s = view.services.find((x) => x.def.id === id); + if (!s) throw new Error(`no service ${id}`); + return s; +} + +describe("buildHealth probes", () => { + test("all services up: 200s and Grist's 302 prove life; projector never probed", async () => { + const { fetcher, calls } = fakeFetcher((url) => + url.startsWith("http://127.0.0.1:8484") ? { status: 302 } : allUp(), + ); + const view = await buildHealth(inputs(), { fetcher, cache: createProbeCache(), now: NOW }); + expect(service(view, "kaneo").state).toBe("up"); + expect(service(view, "grist").state).toBe("up"); + expect(service(view, "grist").statusCode).toBe(302); + expect(service(view, "ready-for-agent").state).toBe("up"); + expect(service(view, "pad").state).toBe("up"); + expect(service(view, "aggregator").state).toBe("self"); + expect(service(view, "kaneo-postgres").state).toBe("up"); + expect(service(view, "fleet-feed").state).toBe("up"); + expect(service(view, "orchestration").state).toBe("up"); + const projector = service(view, "projector"); + expect(projector.state).toBe("off"); + expect(projector.ok).toBeNull(); + expect(calls.some((u) => u.includes("7801"))).toBe(false); + expect(view.degraded).toBe(false); + }); + + test("a throwing probe renders down with its error; the inferred service says unknown, not down", async () => { + const { fetcher } = fakeFetcher((url) => + url.startsWith("http://127.0.0.1:5173") ? new Error("connect ECONNREFUSED") : allUp(), + ); + const view = await buildHealth(inputs(), { fetcher, cache: createProbeCache(), now: NOW }); + const kaneo = service(view, "kaneo"); + expect(kaneo.state).toBe("down"); + expect(kaneo.ok).toBe(false); + expect(kaneo.detail).toContain("ECONNREFUSED"); + const pg = service(view, "kaneo-postgres"); + expect(pg.state).toBe("unknown"); + expect(pg.ok).toBeNull(); + expect(view.degraded).toBe(true); + }); + + test("a timeout renders down as a timeout; an unexpected status renders down with the status", async () => { + const timeout = new Error("timed out"); + timeout.name = "TimeoutError"; + const { fetcher } = fakeFetcher((url) => { + if (url.startsWith("http://127.0.0.1:6056")) return timeout; + if (url.startsWith("http://127.0.0.1:7777")) return { status: 503 }; + return allUp(); + }); + const view = await buildHealth(inputs(), { fetcher, cache: createProbeCache(), now: NOW }); + expect(service(view, "ready-for-agent").detail).toContain("timed out"); + const pad = service(view, "pad"); + expect(pad.state).toBe("down"); + expect(pad.detail).toContain("HTTP 503"); + }); + + test("the 60 s probe cache suppresses a second probe, then expires", async () => { + const { fetcher, calls } = fakeFetcher(allUp); + const cache = createProbeCache(); + await buildHealth(inputs(), { fetcher, cache, now: NOW }); + const firstCount = calls.length; + expect(firstCount).toBeGreaterThan(0); + await buildHealth(inputs(), { fetcher, cache, now: NOW + 30_000 }); + expect(calls.length).toBe(firstCount); + await buildHealth(inputs(), { fetcher, cache, now: NOW + 61_000 }); + expect(calls.length).toBe(firstCount * 2); + }); + + test("absent orchestration section is a named state, not a silent zero", async () => { + const { fetcher } = fakeFetcher(allUp); + const view = await buildHealth(inputs({ diagnosis: { state: "absent" } }), { + fetcher, + cache: createProbeCache(), + now: NOW, + }); + const orch = service(view, "orchestration"); + expect(orch.state).toBe("absent"); + expect(orch.ok).toBe(false); + expect(view.jobs.orchestration.state).toBe("absent"); + expect(view.degraded).toBe(true); + }); + + test("invalid section names its failed checks; stale feed marks the collector stale", async () => { + const { fetcher } = fakeFetcher(allUp); + const view = await buildHealth( + inputs({ + feed: feedAt(20 * 60_000), + diagnosis: { state: "invalid", failedChecks: ["provenance"] }, + }), + { fetcher, cache: createProbeCache(), now: NOW }, + ); + const orch = service(view, "orchestration"); + expect(orch.state).toBe("invalid"); + expect(orch.detail).toContain("provenance"); + expect(service(view, "fleet-feed").state).toBe("stale"); + expect(view.degraded).toBe(true); + const orchSection = view.feed.sections.find((s) => s.key === "orchestration"); + expect(orchSection?.present).toBe(true); + expect(orchSection?.ageMs).toBe(20 * 60_000); + const saas = view.feed.sections.find((s) => s.key === "saas"); + expect(saas?.present).toBe(false); + }); + + test("fixtures mode never probes and reports fixtures for every service", async () => { + const { fetcher, calls } = fakeFetcher(allUp); + const view = await buildHealth( + inputs({ mode: "fixtures", feed: null, feedFileMtimeMs: null, diagnosis: undefined }), + { + fetcher, + cache: createProbeCache(), + now: NOW, + }, + ); + expect(calls.length).toBe(0); + expect(view.services.every((s) => s.state === "fixtures")).toBe(true); + expect(view.degraded).toBe(false); + }); + + test("pages come from the render registry — rendered vs never rendered", async () => { + recordRender("/today", true, NOW - 120_000); + const { fetcher } = fakeFetcher(allUp); + const view = await buildHealth(inputs(), { fetcher, cache: createProbeCache(), now: NOW }); + const today = view.pages.find((p) => p.route === "/today"); + expect(today?.lastRenderedAt).toBe(new Date(NOW - 120_000).toISOString()); + expect(today?.ok).toBe(true); + const health = view.pages.find((p) => p.route === "/health"); + expect(health?.title).toBe("Health"); + const unrendered = view.pages.find((p) => p.route === "/pages"); + // /pages may or may not have been recorded by another test in this + // process; assert only the shape contract for unrendered entries. + if (unrendered && unrendered.lastRenderedAt === null) { + expect(unrendered.ok).toBeNull(); + expect(unrendered.ageMs).toBeNull(); + } + }); +}); + +// --- Boot: the fixture server serves /health and the extended twin --------- + +let proc: Subprocess | null = null; +let port = 0; + +beforeAll(async () => { + port = 6100 + Math.floor(Math.random() * 800); + proc = spawn({ + cmd: ["bun", "run", "src/server.ts"], + cwd: import.meta.dir + "/..", + env: { ...Bun.env, PM_AGG_PORT: String(port), PM_AGG_SOURCE: "fixtures" }, + stdout: "pipe", + stderr: "inherit", + }); + const deadline = Date.now() + 8000; + let ready = false; + while (Date.now() < deadline) { + try { + const res = await fetch(`http://127.0.0.1:${port}/api/health`); + if (res.ok) { + ready = true; + break; + } + } catch { + /* not up yet */ + } + await Bun.sleep(120); + } + expect(ready).toBe(true); +}); + +afterAll(() => { + proc?.kill(); +}); + +describe("health page + extended /api/health (fixtures boot)", () => { + test("/health renders the topology table with honest fixture states", async () => { + const res = await fetch(`http://127.0.0.1:${port}/health`); + expect(res.status).toBe(200); + const html = await res.text(); + expect(html).toContain("Services & topology"); + expect(html).toContain("ready-for-agent"); + expect(html).toContain("Kaneo Postgres"); + expect(html).toContain("off by config"); + expect(html).toContain("fixtures"); + expect(html).toContain("not rendered since this process started"); + }); + + test("/api/health keeps its old keys and gains services/feed/pages/jobs", async () => { + const res = await fetch(`http://127.0.0.1:${port}/api/health`); + expect(res.status).toBe(200); + const body = (await res.json()) as { + status: string; + source: { board: string }; + services: { id: string; state: string }[]; + feed: { generatedAt: unknown }; + pages: { route: string; lastRenderedAt: unknown }[]; + jobs: { orchestration: { state: string } }; + }; + expect(body.status).toBe("ok"); + expect(body.source.board).toBe("fixtures"); + expect(Array.isArray(body.services)).toBe(true); + expect(body.services.find((s) => s.id === "projector")?.state).toBe("fixtures"); + expect("generatedAt" in body.feed).toBe(true); + expect(body.pages.some((p) => p.route === "/health")).toBe(true); + expect(body.jobs.orchestration.state).toBeDefined(); + }); + + test("/pages lists the health page from the manifest", async () => { + const res = await fetch(`http://127.0.0.1:${port}/pages`); + expect(res.status).toBe(200); + const html = await res.text(); + expect(html).toContain('href="/health"'); + expect(html).toContain("/api/health"); + }); +}); diff --git a/pm-stack/aggregator/test/render.test.ts b/pm-stack/aggregator/test/render.test.ts index f6485203e1..409f4408b9 100644 --- a/pm-stack/aggregator/test/render.test.ts +++ b/pm-stack/aggregator/test/render.test.ts @@ -222,13 +222,13 @@ describe("render smoke (fixtures)", () => { const view = buildAttention(await src.attention(), await src.orchestration()); const html = renderAttention(view, await src.coverage(), src.provenance()); expect(html).toContain("Needs you"); - expect(html).toContain("Needs user"); - expect(html).toContain("Needs orchestrator"); + expect(html).toContain("Needs User"); + expect(html).toContain("Needs Orchestrator"); // No orchestration section in fixtures: the honesty banner shows // and the tier heading reports "unknown", not a number (#1139). expect(html).toContain("Tier source missing"); - expect(html).toContain("Needs user (unknown)"); - expect(html).not.toContain("Needs user (0)"); + expect(html).toContain("Needs User (unknown)"); + expect(html).not.toContain("Needs User (0)"); expect(html).toContain("waiting for an answer"); expect(html).toContain("Waiting on:"); }); diff --git a/pm-stack/aggregator/test/slice2.test.ts b/pm-stack/aggregator/test/slice2.test.ts index af06b3b996..64b77b19e7 100644 --- a/pm-stack/aggregator/test/slice2.test.ts +++ b/pm-stack/aggregator/test/slice2.test.ts @@ -380,10 +380,10 @@ describe("attention render (slice 2)", () => { const src = fixtureSource(); const view = buildAttention(await src.attention(), SECTION); const html = renderAttention(view, await src.coverage(), src.provenance()); - expect(html).toContain("Needs user"); + expect(html).toContain("Needs User"); // Section present: counts render as numbers and the tier header // carries the section's run id — no honesty banner (#1139). - expect(html).not.toContain("Needs user (unknown)"); + expect(html).not.toContain("Needs User (unknown)"); expect(html).not.toContain("Tier source missing"); expect(html).toContain("orch-test"); expect(html).toContain("Why you:"); @@ -407,9 +407,9 @@ describe("attention honesty (#1139)", () => { const html = renderAttention(view, await src.coverage(), src.provenance()); expect(html).toContain("Tier source missing"); expect(html).toContain("the orchestrator's published queues are NOT reflected"); - expect(html).toContain("Needs user (unknown)"); - expect(html).toContain("Needs orchestrator (unknown)"); - expect(html).not.toContain("Needs user (0)"); + expect(html).toContain("Needs User (unknown)"); + expect(html).toContain("Needs Orchestrator (unknown)"); + expect(html).not.toContain("Needs User (0)"); // The false-reassurance empty copy is suppressed in this state. expect(html).not.toContain("Nothing in the user queue right now."); }); @@ -424,7 +424,7 @@ describe("attention honesty (#1139)", () => { const html = renderAttention(view, await src.coverage(), src.provenance()); expect(html).toContain("Tier source invalid"); expect(html).toContain("provenance"); - expect(html).toContain("Needs user (unknown)"); + expect(html).toContain("Needs User (unknown)"); }); test("stale section: counts render, badged with a stale banner and the run stamp", async () => { @@ -437,7 +437,7 @@ describe("attention honesty (#1139)", () => { expect(view.tierSource.present).toBe(true); const html = renderAttention(view, await src.coverage(), src.provenance()); expect(html).toContain("Tier source stale"); - expect(html).not.toContain("Needs user (unknown)"); + expect(html).not.toContain("Needs User (unknown)"); expect(html).toContain("orch-test"); });