From fc571cff35f67a1da8b430d47f3e13d195f47a5c Mon Sep 17 00:00:00 2001 From: Muse Sweep Date: Tue, 27 Oct 2026 06:22:19 +0000 Subject: [PATCH] =?UTF-8?q?feat(aggregator):=20honesty=20+=20freshness=20?= =?UTF-8?q?=E2=80=94=20no=20silent=20zeros,=20primed=20health,=20per-sourc?= =?UTF-8?q?e=20chips=20(#1139,=20#1267,=20#1138)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #1139 — the orchestration section is diagnosed on every read (diagnoseOrchestrationSection: live/stale>90m/absent/invalid with the failing check named) and Source.diagnostics() carries it to the surfaces. /attention banners an absent/invalid/stale tier source at the point of display, renders tier counts as 'unknown' (never a confident 0) when the source is missing, stamps tier headings with the section run id + age when present, and suppresses the false-reassurance empty copy. /today's derived banner names the section's true state (invalid names the failed checks); a stale section behind the served view warns. This banner is #1148's aggregator-side dead-man's switch. #1267 — /api/health primes every provenance facet (60s-cached, failure-tolerant) before answering, so its report no longer depends on request order; the response also carries the structured sections diagnosis. Regression test boots a live-source server and asserts on the FIRST response it ever serves. The live items() facet also reports pool-backed truthfully on an empty-refs prime call. #1138 — per-source freshness chips (source · state · age; counts always with their noun) on the pages that use each source, from Source.provenanceDetail(); the footer provenance line moves into a collapsed 'source detail' disclosure. The registry facet now counts the MERGED store total (the number /sessions renders) instead of the per-read incoming batch, ending the 221-vs-61 disagreement. Role-based wording (Drew, 2026-10-27): all user-visible 'Needs Drew' copy becomes 'Needs user' (headings, chips, session badge, /today alert, page blurb, program editorial, README) — the NEEDS USER queue is an intake the orchestrator works first; only items it cannot resolve escalate to the user. Internal field names, JSON keys, and the orchestration contract (needsDrew etc.) are unchanged — contract naming is #1290's decision. Tests: 181 pass (baseline 167), tsc clean, biome 2.3.2 + prettier. --- pm-stack/aggregator/README.md | 35 ++- pm-stack/aggregator/src/derive.ts | 57 ++++- pm-stack/aggregator/src/feed.ts | 53 ++++- pm-stack/aggregator/src/model.ts | 18 ++ pm-stack/aggregator/src/pages.ts | 2 +- pm-stack/aggregator/src/program.ts | 2 +- pm-stack/aggregator/src/project-config.ts | 2 +- pm-stack/aggregator/src/render.ts | 207 +++++++++++++++--- pm-stack/aggregator/src/server.ts | 84 +++++-- pm-stack/aggregator/src/source.ts | 16 ++ pm-stack/aggregator/src/sources/fixtures.ts | 20 ++ pm-stack/aggregator/src/sources/live.ts | 97 +++++++- pm-stack/aggregator/test/boot.test.ts | 6 +- .../aggregator/test/health-priming.test.ts | 97 ++++++++ .../aggregator/test/orchestration.test.ts | 108 +++++++++ pm-stack/aggregator/test/render.test.ts | 69 +++++- pm-stack/aggregator/test/slice2.test.ts | 65 +++++- 17 files changed, 878 insertions(+), 60 deletions(-) create mode 100644 pm-stack/aggregator/test/health-priming.test.ts diff --git a/pm-stack/aggregator/README.md b/pm-stack/aggregator/README.md index afa4888f5d..f50f617d71 100644 --- a/pm-stack/aggregator/README.md +++ b/pm-stack/aggregator/README.md @@ -18,7 +18,7 @@ Design record (source of truth): | 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 DREW** (default; only items that genuinely require Drew, 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` | +| `/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=` | @@ -40,7 +40,7 @@ that is plumbing, not links). ### Needs-you tiers + session clarity (slice 2, #898) - **Tiering** (`buildAttention` in `src/derive.ts`): every classified - session lands in NEEDS DREW (with an explainable `drewReason`), + session lands in NEEDS USER (with an explainable `drewReason`), NEEDS ORCHESTRATOR (with the fleet's next step), or in-motion. Drew rules, in order: the orchestration job's own classification (#899 — its tiers win for anything they name, reason verbatim) → a keeper @@ -138,7 +138,7 @@ Two kinds, visually distinct everywhere they render: pass polls `GET /api/comments.json?kind=message&state=new` (and `?kind=github&state=new` for pending GitHub posts), triages each into its normal flow — update the item, queue work, escalate to Drew via -the usual NEEDS DREW path; github-kind ones get posted and reported — +the usual NEEDS USER path; github-kind ones get posted and reported — then marks them consumed with `POST /api/comments/triage { ids }`. Notes are never polled; they are read from `/api/comments.json?object=` when an item is picked up. Item @@ -362,6 +362,35 @@ projector-ized live per-source feeds. in `pm-stack/kaneo-projects.json` (Session H): `code`, `opencode`, `openchamber` under `developing-today/`, `nix` under `dezren39/`. +## Honesty + freshness (#1139, #1267, #1138) + +- **No silent zeros (#1139).** The orchestration section is + diagnosed on every read — live / stale (>90 min) / absent / + invalid (with the failing check named) — via + `diagnoseOrchestrationSection` in `src/feed.ts` and + `Source.diagnostics()`. `/attention` banners an absent, invalid, or + stale tier source at the point of display and renders the tier + counts as "unknown" rather than a confident 0 when the source is + missing; `/today`'s derived-view banner names the section's true + state. The stale/absent banner is also the aggregator-side + dead-man's switch for #1148: if the orchestration job dies, the + surfaces Drew reads say so. Visible tier wording is role-based — + NEEDS USER, not NEEDS DREW (Drew's 2026-10-27 direction; internal + field names and the orchestration contract are unchanged). The + NEEDS USER queue is an intake the orchestrator works first; only + items it cannot resolve escalate to the user. +- **Health primes (#1267).** Provenance strings populate lazily, one + facet per method call, so `/api/health` exercises every facet + (60 s-cached) before answering — its report no longer depends on + which pages were visited since boot. The response also carries the + structured `sections` diagnosis beside the provenance strings. +- **Freshness chips (#1138).** Pages render per-source chips + (source · state · age, counts always with their noun) for exactly + the sources they use, from `Source.provenanceDetail()`; the full + provenance line moves to a collapsed "source detail" disclosure in + the footer. The registry chip counts the merged store total — the + same number the /sessions header renders. + ## Design notes — the two new views (#851, #852) Both were added as **design issues** (2026-10-25) and are implemented diff --git a/pm-stack/aggregator/src/derive.ts b/pm-stack/aggregator/src/derive.ts index 6ff10f1c8b..b4d9a764f2 100644 --- a/pm-stack/aggregator/src/derive.ts +++ b/pm-stack/aggregator/src/derive.ts @@ -1,5 +1,6 @@ // Pure derivations from the read model: the execution strip, the roadmap // timeline lanes, and the unified comment stream. No I/O here. +import type { SectionDiagnosis } from "./feed.ts"; import type { Comment, GhItem, Link, RefKey, RoadmapRow } from "./model.ts"; export interface ExecutionStrip { @@ -335,6 +336,22 @@ export function tierEntry(e: AttentionEntry, match?: SectionMatch | null): Tiere return { ...e, tier: "needs-orchestrator", orchestratorNote: ORCHESTRATOR_NOTES[e.state] }; } +/** + * Where the tiers came from, honestly (#1139): when the orchestration + * section is absent, invalid, or stale, the tier counts are not the + * orchestrator's published queues and the page must say so at the + * point of display instead of rendering a confident zero. `present` + * means a valid section was served (stale counts as present — its + * numbers render, badged old). + */ +export interface TierSourceInfo { + present: boolean; + state: SectionDiagnosis["state"]; + runId?: string; + generatedAt?: string; + failedChecks?: string[]; +} + export interface AttentionView { drew: TieredEntry[]; orchestrator: TieredEntry[]; @@ -345,6 +362,8 @@ export interface AttentionView { all: TieredEntry[]; /** Finished/stale entries dropped before display. */ expiredCount: number; + /** The tier source's diagnosis (#1139); drives the banner + counts. */ + tierSource: TierSourceInfo; } /** Classify, expire, and tier a raw session feed in one pass. */ @@ -352,7 +371,25 @@ export function buildAttention( feed: SessionFeedEntry[], section?: OrchestrationSection | null, now = Date.now(), + diagnosis?: SectionDiagnosis, ): AttentionView { + // The tier source's state (#1139): the caller's diagnosis when it + // has one (the live source tracks it in Source.diagnostics()); else + // derive the coarse form from the section itself — a served section + // is present, a missing one is absent. "invalid" can only come from + // a real diagnosis, since an invalid section never reaches here as + // a section. + const tierSource: TierSourceInfo = diagnosis + ? { + present: diagnosis.state === "live" || diagnosis.state === "stale", + state: diagnosis.state, + runId: diagnosis.runId, + generatedAt: diagnosis.generatedAt, + failedChecks: diagnosis.failedChecks, + } + : section + ? { present: true, state: "live", runId: section.runId, generatedAt: section.generatedAt } + : { present: false, state: "absent" }; const { current, expired } = partitionFresh(feed, now); const bySession = new Map(); if (section) { @@ -392,6 +429,7 @@ export function buildAttention( orchestratorExtra: extras(section?.tiers.needsOrchestrator), all, expiredCount: expired.length, + tierSource, }; } @@ -580,6 +618,12 @@ export interface TodayView { generatedAt?: string; /** What the orchestrator pushed back into motion (section path only). */ actions?: { at: string; kind: string; target: string; summary: string }[]; + /** + * The orchestration section's diagnosis (#1139): the derived view's + * banner names the true state (absent vs invalid vs stale) instead + * of always claiming the job "has not published yet". + */ + sectionDiagnosis?: SectionDiagnosis; } const PRIORITY_ORDER: Record = { urgent: 0, high: 1, normal: 2, medium: 2, low: 3 }; @@ -648,8 +692,17 @@ export function deriveToday( items: Map, section: OrchestrationSection | null, now = new Date(), + diagnosis?: SectionDiagnosis, ): TodayView { - if (section) return todayFromSection(section); + if (section) { + const view = todayFromSection(section); + view.sectionDiagnosis = diagnosis ?? { + state: "live", + runId: section.runId, + generatedAt: section.generatedAt, + }; + return view; + } // Derived until #899 lands: today's dated roadmap rows first, then the // board's in-progress work by priority, then what's in review. @@ -707,7 +760,7 @@ export function deriveToday( detail: inProgress ? undefined : "nothing in progress on the board", }); } - return { fromOrchestrator: false, objectives, momentum }; + return { fromOrchestrator: false, objectives, momentum, sectionDiagnosis: diagnosis ?? { state: "absent" } }; } // --------------------------------------------------------------------------- diff --git a/pm-stack/aggregator/src/feed.ts b/pm-stack/aggregator/src/feed.ts index 2ff73c1d4c..e10a7c727e 100644 --- a/pm-stack/aggregator/src/feed.ts +++ b/pm-stack/aggregator/src/feed.ts @@ -138,6 +138,44 @@ export function isOrchestrationSection(v: unknown): v is OrchestrationSection { return orchestrationSectionProblem(v) === null; } +/** + * A section older than this at the hourly cadence is stale (#1139, + * #1148's threshold): still served, but every surface that renders its + * numbers must say the data is old instead of presenting it as current. + */ +export const ORCHESTRATION_STALE_MS = 90 * 60_000; + +/** + * The diagnosis behind the honesty surfaces (#1139/#1140): a section + * the aggregator holds is in exactly one of these states. "invalid" + * names the failing checks (from orchestrationSectionProblem — the + * gate itself, so the diagnosis can never drift from the validation) + * and is never collapsed into "absent": a publisher whose section is + * being rejected has a bug to fix, not a run that never happened. + */ +export interface SectionDiagnosis { + state: "live" | "absent" | "invalid" | "stale"; + generatedAt?: string; + runId?: string; + ageMs?: number; + /** Names of the failing structural checks; never values. */ + failedChecks?: string[]; +} + +export function diagnoseOrchestrationSection(v: unknown, now = Date.now()): SectionDiagnosis { + if (v === null || v === undefined) return { state: "absent" }; + const problem = orchestrationSectionProblem(v); + if (problem !== null) return { state: "invalid", failedChecks: [problem] }; + const s = v as OrchestrationSection; + const ageMs = Math.max(0, now - Date.parse(s.generatedAt)); + return { + state: ageMs > ORCHESTRATION_STALE_MS ? "stale" : "live", + generatedAt: s.generatedAt, + runId: s.runId, + ageMs, + }; +} + /** * A valid section with its provenance in the canonical object form: * a legacy plain-string provenance becomes `{ sources: [it] }`. @@ -174,11 +212,16 @@ export async function loadFeed(path: string): Promise { } } +/** "3m old", "2h old", "fresh" — for an age in milliseconds. */ +export function ageMsText(ageMs: number): string { + const ms = Math.max(0, ageMs); + if (ms < 90_000) return "fresh"; + if (ms < 3_600_000) return `${Math.round(ms / 60_000)}m old`; + if (ms < 86_400_000) return `${(ms / 3_600_000).toFixed(1)}h old`; + return `${Math.round(ms / 86_400_000)}d old`; +} + /** "3m old", "2h old", "fresh" — for provenance strings. */ export function feedAgeText(generatedAt: string, now = Date.now()): string { - const ageMs = Math.max(0, now - Date.parse(generatedAt)); - if (ageMs < 90_000) return "fresh"; - if (ageMs < 3_600_000) return `${Math.round(ageMs / 60_000)}m old`; - if (ageMs < 86_400_000) return `${(ageMs / 3_600_000).toFixed(1)}h old`; - return `${Math.round(ageMs / 86_400_000)}d old`; + return ageMsText(now - Date.parse(generatedAt)); } diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index 0d21495dca..1a7d6ca4de 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -170,6 +170,24 @@ export interface Provenance { aa: string; } +/** + * One facet's freshness, structured (#1138): the human string above, + * plus the machine state the freshness chips render. `count` always + * ships with its noun (`countLabel`) so a chip can never show a bare + * number that contradicts a page header counting the same thing. + */ +export interface ProvenanceFacet { + /** The provenance string, unchanged — also the chip's tooltip. */ + text: string; + state: "live" | "fixtures" | "stale" | "absent" | "invalid"; + ageMs?: number; + count?: number; + countLabel?: string; +} + +/** Per-facet freshness detail, keyed exactly like Provenance. */ +export type ProvenanceDetail = Record; + // --------------------------------------------------------------------------- // Quota + throughput view (#851). Machine-first: the same shapes the API // returns are what the GUI renders. No code from the CCC reference design diff --git a/pm-stack/aggregator/src/pages.ts b/pm-stack/aggregator/src/pages.ts index 2bb5b2a3f2..8c743455f1 100644 --- a/pm-stack/aggregator/src/pages.ts +++ b/pm-stack/aggregator/src/pages.ts @@ -34,7 +34,7 @@ export const PAGES: PageDef[] = [ title: "Needs you", route: "/attention", api: "/api/attention.json", - blurb: "NEEDS DREW vs NEEDS ORCHESTRATOR, and every live session.", + blurb: "NEEDS USER vs NEEDS ORCHESTRATOR, and every live session.", }, { id: "board", title: "Board", route: "/", api: "/api/board.json", blurb: "The curated cross-repo WIP board." }, { diff --git a/pm-stack/aggregator/src/program.ts b/pm-stack/aggregator/src/program.ts index e00c3d5c3d..749fa33658 100644 --- a/pm-stack/aggregator/src/program.ts +++ b/pm-stack/aggregator/src/program.ts @@ -121,7 +121,7 @@ export const PROGRAM: ProgramDoc = { { title: "Slice 2 — mobile, tiers, horizons, Today", detail: - "Mobile-first views; NEEDS DREW vs NEEDS ORCHESTRATOR with a why-you reason and staleness expiry; roadmap horizons quarter/month/week/3-day/today; the /today view rendering the orchestrator's goal measurements; session source labels (OpenCode sandbox/laptop, Jules).", + "Mobile-first views; NEEDS USER vs NEEDS ORCHESTRATOR with a why-you reason and staleness expiry; roadmap horizons quarter/month/week/3-day/today; the /today view rendering the orchestrator's goal measurements; session source labels (OpenCode sandbox/laptop, Jules).", refs: [issue(898)], links: [prLink(901)], }, diff --git a/pm-stack/aggregator/src/project-config.ts b/pm-stack/aggregator/src/project-config.ts index 8454d98530..1809f9e449 100644 --- a/pm-stack/aggregator/src/project-config.ts +++ b/pm-stack/aggregator/src/project-config.ts @@ -488,7 +488,7 @@ export const PROJECT_CONFIGS: ProjectConfig[] = [ { title: "Plaid / Citi still not linked", detail: - "Plaid blocks Muse's browser, so linking Citi (Costco, Diamond, Double Cash) needs Drew's own browser session. Several vendor meters are also console-only, so some /quota numbers are dated manual reads rather than live meters.", + "Plaid blocks Muse's browser, so linking Citi (Costco, Diamond, Double Cash) needs the user's own browser session. Several vendor meters are also console-only, so some /quota numbers are dated manual reads rather than live meters.", }, ], }, diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 328a621ba2..2490a27451 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -23,6 +23,7 @@ import { import { githubCommentUrl } from "./comments.ts"; import { summarizeAa } from "./aa.ts"; import { summarizeDns } from "./dns.ts"; +import { ageMsText, feedAgeText } from "./feed.ts"; import { type AaConfig, type AaFeedSection, @@ -41,6 +42,7 @@ import { type PaygLine, type ProjectPoolItem, type Provenance, + type ProvenanceDetail, type QuotaView, type RefKey, type RoadmapRow, @@ -125,6 +127,13 @@ meter { width: 140px; height: 14px; } .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 10px 0; } .chips a { border: 1px solid #30363d; border-radius: 999px; padding: 5px 12px; text-decoration: none; color: #e6edf3; background: #161b22; } .chips a.active { border-color: #1f6feb; background: #1f6feb33; color: #58a6ff; } +.fchip { border: 1px solid #30363d; border-radius: 999px; padding: 5px 12px; color: #e6edf3; background: #161b22; font-size: 12.5px; } +.fchip.live { border-color: #2ea04388; } +.fchip.stale { border-color: #d29922; color: #e3b341; } +.fchip.invalid { border-color: #f85149; color: #f85149; } +.fchip.absent { border-color: #d29922; color: #e3b341; } +.srcdetail { margin: 6px 0; } +.srcdetail summary { cursor: pointer; } .reason { border-left: 3px solid #f85149; padding: 6px 10px; margin: 8px 0 2px; background: #f851490d; } .orch-note { border-left: 3px solid #1f6feb; padding: 6px 10px; margin: 8px 0 2px; background: #1f6feb0d; } .cov { border: 1px solid #30363d; border-radius: 8px; padding: 8px 12px; margin: 12px 0; background: #0d1117; } @@ -209,7 +218,49 @@ document.addEventListener("change", (ev) => { }); `; -function layout(title: string, body: string, provenance: Provenance, active: string, extra = ""): string { +/** 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}
`; +} + +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. @@ -224,8 +275,8 @@ function layout(title: string, body: string, provenance: Provenance, active: str return ` ${esc(title)} · aggregator -
${body} -
board: ${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)}
tailnet: ${TAILNET_URL.replace("http://", "")}
+
${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)}
tailnet: ${TAILNET_URL.replace("http://", "")}
${extra}`; } @@ -356,6 +407,7 @@ export function renderBoard( items: Map, provenance: Provenance, counts?: Map, + detail?: ProvenanceDetail, ): string { const cols = new Map(); for (const item of board) { @@ -405,6 +457,8 @@ export function renderBoard( `

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.

${bodies}
`, provenance, "/", + "", + detail ? freshnessChips(detail, ["board", "items", "orchestration"]) : "", ); } @@ -455,6 +509,7 @@ export function renderRoadmap( provenance: Provenance, grain: RoadmapGrain = "quarter", counts?: Map, + detail?: ProvenanceDetail, ): string { const chips = GRAINS.map( ([g, label]) => `${label}`, @@ -486,6 +541,8 @@ export function renderRoadmap( `

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.

${chips}
${body}`, provenance, "/roadmap", + "", + detail ? freshnessChips(detail, ["roadmap", "items"]) : "", ); } @@ -679,7 +736,12 @@ function chargesStripHtml(usage: UsageView): string { 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}
DateChargeAmountMethodEvidence
`; } -export function renderQuota(view: QuotaView, provenance: Provenance, usage?: UsageView): string { +export function renderQuota( + view: QuotaView, + provenance: Provenance, + usage?: UsageView, + detail?: ProvenanceDetail, +): string { const pools = view.pools .map((p) => { const windows = p.windows @@ -763,6 +825,8 @@ ${chargesStripHtml(usage)} ${burnAndChoices}`, provenance, "/quota", + "", + detail ? freshnessChips(detail, ["quota", "usage"]) : "", ); } @@ -804,7 +868,12 @@ export function historyChartHtml(records: SnapshotRecord[], metricId: string): s 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}
`; } -export function renderServiceDetail(svc: SaasService, history: SnapshotRecord[], provenance: Provenance): string { +export function renderServiceDetail( + svc: SaasService, + history: SnapshotRecord[], + provenance: Provenance, + detail?: ProvenanceDetail, +): string { const f = freshness(svc.measuredAt, svc.cadenceDays); const metricRows = svc.metrics.length ? svc.metrics @@ -848,7 +917,14 @@ ${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"); + return layout( + `${svc.name} · usage`, + body, + provenance, + "/quota", + "", + detail ? freshnessChips(detail, ["quota", "usage"]) : "", + ); } // --- Attention view (#852, tiered in slice 2) ------------------------------- @@ -868,7 +944,7 @@ function sessionCard( : ""; const tierBadge = e.tier === "needs-drew" - ? `needs Drew` + ? `needs user` : e.tier === "needs-orchestrator" ? `needs orchestrator` : ""; @@ -904,36 +980,66 @@ export function renderAttention( coverage: SourceCoverage[], provenance: Provenance, counts?: Map, + detail?: ProvenanceDetail, ): string { const children = sessionChildren(view.all); const roots = sessionRoots(view.all); const drewTotal = view.drew.length + view.drewExtra.length; const orchTotal = view.orchestrator.length + view.orchestratorExtra.length; - const chips = ``; + // #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) : "")}` + : ""; + const drewCount = ts.present ? String(drewTotal) : "unknown"; + const orchCount = ts.present ? String(orchTotal) : "unknown"; + const chips = ``; const drewCards = [ ...view.drew.map((e) => sessionCard(e, children, 0, counts)), ...view.drewExtra.map((i) => tierItemCard(i, "Why you", counts)), - ].join("") || `

Nothing needs you right now.

`; + ].join("") || + (ts.present + ? `

Nothing in the user queue right now.

` + : `

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

`); const orchCards = [ ...view.orchestrator.map((e) => sessionCard(e, children, 0, counts)), ...view.orchestratorExtra.map((i) => tierItemCard(i, "Why the fleet", counts)), - ].join("") || `

The fleet's queue is empty.

`; + ].join("") || + (ts.present + ? `

The fleet's queue is empty.

` + : `

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

`); const sessionCards = roots.length ? roots.map((e) => sessionCard(e, children, 0, counts)).join("") : `

No current sessions.

`; return layout( "Needs you", - `

Needs you

Only what genuinely requires Drew lands in NEEDS DREW — each with its reason. Everything else the fleet can work is the orchestrator's 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.

-${chips} + `

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 Drew (${drewTotal})

${drewCards} -

Needs orchestrator (${orchTotal})

The orchestration job (#899) reviews this queue and pushes work back into motion; it escalates here only what truly needs Drew.

${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, "/attention", + "", + detail ? freshnessChips(detail, ["orchestration", "attention", "registry"]) : "", ); } @@ -945,13 +1051,14 @@ export function renderToday( quota: QuotaView, coverage: SourceCoverage[], provenance: Provenance, + detail?: ProvenanceDetail, ): string { const walled = quota.pools.filter((p) => p.state === "walled"); const alerts: string[] = []; const drewTotal = attention.drew.length + attention.drewExtra.length; if (drewTotal) { alerts.push( - ``, + ``, ); } if (walled.length) { @@ -959,9 +1066,21 @@ export function renderToday( ``, ); } + // #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.

` - : ``; + ? `

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("")}` : ""; @@ -1000,6 +1119,8 @@ export function renderToday( ${actions}${coverageHtml(coverage)}`, provenance, "/today", + "", + detail ? freshnessChips(detail, ["orchestration", "quota", "attention"]) : "", ); } @@ -1015,13 +1136,16 @@ function dnsTable(entries: DnsEntry[]): string { return `
${rows || ''}
DomainNext renewalPrice (list)Auto-renewPlan / statusReview?
none
`; } -export function renderDns(section: DnsSection | null, provenance: Provenance): string { +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); @@ -1043,7 +1167,7 @@ export function renderDns(section: DnsSection | null, provenance: Provenance): s

Unused but earmarked (${s.earmarked.length})

No public-facing use, but the name or plan ties them to a project family (earmark as recorded in the register).

${dnsTable(s.earmarked)}

Completely unused (${s.unused.length})

Nothing but registrar defaults — each still auto-renews until someone decides otherwise.

${dnsTable(s.unused)}
Full register (${section.entries.length})${dnsTable(section.entries)}
`; - return layout("DNS register", body, provenance, "/dns"); + return layout("DNS register", body, provenance, "/dns", "", chips); } // --- AA cost explorer page (ainventory workbook data via the fleet feed) ----- @@ -1168,7 +1292,7 @@ ${coverageHtml}`; const REGISTRY_SOURCE_ORDER = ["opencode-laptop", "opencode-sandbox", "jules", "claude-code", "cron"]; -export function renderSessions(records: SessionRecord[], provenance: Provenance): string { +export function renderSessions(records: SessionRecord[], provenance: Provenance, detail?: ProvenanceDetail): 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); @@ -1182,7 +1306,7 @@ export function renderSessions(records: SessionRecord[], provenance: Provenance)

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 · ${totalTokens.toLocaleString()} tokens recorded. Machine-first: /api/registry.json.

Coverage honesty: OpenCode sessions register from their servers; Jules from the keeper's state; 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"); + return layout("Sessions", body, provenance, "/sessions", "", detail ? freshnessChips(detail, ["registry"]) : ""); } // --- All pages (the manifest as a page) --------------------------------------- @@ -1234,7 +1358,11 @@ ${commentThreadHtml(objectRef, comments, opts)}`; export function renderProjects( pool: ProjectPoolItem[], provenance: Provenance, - opts: { area?: string | null; orchestration?: OrchestrationSection | null } = {}, + opts: { + area?: string | null; + orchestration?: OrchestrationSection | null; + detail?: ProvenanceDetail; + } = {}, ): string { const areas = [...new Set(pool.map((p) => p.area).filter((a): a is string => Boolean(a)))].sort(); const area = opts.area && areas.includes(opts.area) ? opts.area : null; @@ -1278,7 +1406,14 @@ export function renderProjects(

${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}
${cards || '

No items in this area.

'}`; - return layout("Projects", body, provenance, "/projects"); + return layout( + "Projects", + body, + provenance, + "/projects", + "", + opts.detail ? freshnessChips(opts.detail, ["items"]) : "", + ); } // --- Program status page (#1046: the dashboard documents itself) ------------ @@ -1353,7 +1488,12 @@ function projectCard(s: ProjectSummary): string { * 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): string { +export function renderProgram( + data: ProgramData, + items: Map, + provenance: Provenance, + detail?: ProvenanceDetail, +): string { const { program, live } = data; const projects = data.projects ?? []; const unset = live.pool.byArea.find((c) => c.name === "(unset)")?.count ?? 0; @@ -1375,7 +1515,14 @@ ${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)}`; - return layout("Program status", body, provenance, "/program"); + return layout( + "Program status", + body, + provenance, + "/program", + "", + detail ? freshnessChips(detail, ["orchestration", "items", "roadmap"]) : "", + ); } // --- Per-project page (#1121, registry in src/project-config.ts) ------------- @@ -1386,6 +1533,7 @@ export function renderProgramProject( detail: ProjectDetail, items: Map, provenance: Provenance, + provDetail?: ProvenanceDetail, ): string { const { config } = detail; const linkBits: string[] = []; @@ -1472,5 +1620,12 @@ ${poolHtml}

Roadmap — live

${roadmapHtml} ${editorialHtml}`; - return layout(config.title, body, provenance, "/program"); + return layout( + config.title, + body, + provenance, + "/program", + "", + provDetail ? freshnessChips(provDetail, ["orchestration", "items", "roadmap"]) : "", + ); } diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 34534a551b..5fba59dc0b 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -48,6 +48,48 @@ const source = pickSource(); const cfg = loadConfig(); const commentsStore = new CommentsStore(cfg.commentsFile); +/** + * #1267: the live source populates its provenance strings lazily, one + * facet per method call — so a consumer that reads provenance() + * without exercising the facets (exactly what /api/health did) + * reports "fixtures" for facets that are really live, and its answer + * depends on which pages were visited since boot. Health therefore + * exercises every facet method before reading provenance. Priming is + * cached for 60 s (the #1147 probe-cache cadence): facet reads are + * mostly cache- or file-backed, and a watchdog polling health must + * not fan out to every upstream on every hit. Facet failures never + * fail health — a failed facet keeps its honest fallback string, + * which is precisely what health exists to report. + */ +let lastPrimedAt = 0; +let priming: Promise | null = null; +async function ensureProvenancePrimed(): Promise { + if (Date.now() - lastPrimedAt < 60_000) return; + priming ??= (async () => { + try { + const { items } = await boardContext(); + const refs = [...items.keys()]; + await Promise.allSettled([ + source.roadmap(), + source.comments(refs), + source.quota(), + source.usage(), + source.attention(), + source.orchestration(), + source.dns(), + source.aa(), + source.registry(), + source.projects(), + ]); + } catch { + /* facets that failed keep their fallback strings — health reports those */ + } + lastPrimedAt = Date.now(); + priming = null; + })(); + await priming; +} + /** Author identities for the comment form: standing + registry sessions. */ async function commentFormOpts(githubRefs: RefKey[] = []): Promise { const records = await source.registry().catch(() => []); @@ -119,7 +161,10 @@ async function roadmapContext() { async function attentionContext() { const [feed, summary, coverage] = await Promise.all([source.attention(), source.orchestration(), source.coverage()]); - return { view: buildAttention(feed, summary), coverage }; + // Read the diagnosis AFTER orchestration() has run: the live source + // recomputes it on every orchestration read (#1139). + const diagnosis = source.diagnostics?.().orchestration; + return { view: buildAttention(feed, summary, Date.now(), diagnosis), coverage }; } async function todayContext() { @@ -130,7 +175,8 @@ async function todayContext() { source.quota(), source.orchestration(), ]); - return { today: deriveToday(board, rows, items, summary), view, coverage, quota }; + const diagnosis = source.diagnostics?.().orchestration; + return { today: deriveToday(board, rows, items, summary, new Date(), diagnosis), view, coverage, quota }; } const GRAINS = new Set(["quarter", "month", "week", "3d", "today"]); @@ -139,6 +185,7 @@ async function handler(req: Request): Promise { const url = new URL(req.url); const path = url.pathname; const prov = () => source.provenance(); + const provDetail = () => source.provenanceDetail?.(); // --- Dashboard comment writes (#906 §2) -------------------------------- if (req.method === "POST" && path === "/api/comments") { @@ -193,31 +240,31 @@ async function handler(req: Request): Promise { if (path === "/" || path === "/board") { const { board, items } = await boardContext(); - return html(renderBoard(board, items, prov(), await commentsStore.counts())); + return html(renderBoard(board, items, prov(), await commentsStore.counts(), provDetail())); } if (path === "/today") { const { today, view, coverage, quota } = await todayContext(); - return html(renderToday(today, view, quota, coverage, prov())); + return html(renderToday(today, view, quota, coverage, prov(), provDetail())); } if (path === "/roadmap") { const { rows, items } = await roadmapContext(); const g = url.searchParams.get("h") ?? "quarter"; const grain: RoadmapGrain = GRAINS.has(g) ? (g as RoadmapGrain) : "quarter"; - return html(renderRoadmap(rows, items, prov(), grain, await commentsStore.counts())); + return html(renderRoadmap(rows, items, prov(), grain, await commentsStore.counts(), provDetail())); } if (path === "/quota") { const [quota, usage] = await Promise.all([source.quota(), source.usage()]); - return html(renderQuota(quota, prov(), usage)); + return html(renderQuota(quota, prov(), usage, provDetail())); } const serviceMatch = /^\/quota\/service\/([\w-]+)$/.exec(path); if (serviceMatch) { const usage = await source.usage(); const svc = usage.services.find((s) => s.id === serviceMatch[1]); - if (svc) return html(renderServiceDetail(svc, usage.history[svc.id] ?? [], prov())); + if (svc) return html(renderServiceDetail(svc, usage.history[svc.id] ?? [], prov(), provDetail())); return html( `

Not found

no SaaS service with id ${serviceMatch[1]} — back to Usage & billing

`, ); @@ -225,11 +272,11 @@ async function handler(req: Request): Promise { if (path === "/attention") { const { view, coverage } = await attentionContext(); - return html(renderAttention(view, coverage, prov(), await commentsStore.counts())); + return html(renderAttention(view, coverage, prov(), await commentsStore.counts(), provDetail())); } if (path === "/dns") { - return html(renderDns(await source.dns(), prov())); + return html(renderDns(await source.dns(), prov(), provDetail())); } if (path === "/api/dns.json") { const section = await source.dns(); @@ -245,7 +292,7 @@ async function handler(req: Request): Promise { } if (path === "/sessions") { - return html(renderSessions(await source.registry(), prov())); + return html(renderSessions(await source.registry(), prov(), provDetail())); } if (path === "/api/registry.json") { const records = await source.registry(); @@ -257,7 +304,9 @@ async function handler(req: Request): Promise { source.projects().catch(() => []), source.orchestration().catch(() => null), ]); - return html(renderProjects(pool, prov(), { area: url.searchParams.get("area"), orchestration })); + return html( + renderProjects(pool, prov(), { area: url.searchParams.get("area"), orchestration, detail: provDetail() }), + ); } if (path === "/api/projects.json") { const pool = await source.projects().catch(() => []); @@ -281,7 +330,7 @@ async function handler(req: Request): Promise { projects: buildProjectSummaries(PROJECT_CONFIGS, pool, rows), }; if (path === "/api/program.json") return json(data); - return html(renderProgram(data, items, prov())); + return html(renderProgram(data, items, prov(), provDetail())); } const programProjectMatch = /^\/program\/([\w-]+)$/.exec(path); @@ -298,7 +347,7 @@ async function handler(req: Request): Promise { source.projects().catch(() => []), source.roadmap().catch(() => []), ]); - return html(renderProgramProject(buildProjectDetail(config, items, pool, rows), items, prov())); + return html(renderProgramProject(buildProjectDetail(config, items, pool, rows), items, prov(), provDetail())); } if (path === "/api/program-project.json") { const id = url.searchParams.get("id") ?? ""; @@ -381,7 +430,14 @@ async function handler(req: Request): Promise { return json(section ?? { status: "absent", reason: "no orchestration run has published yet" }); } if (path === "/api/health") { - return json({ status: "ok", source: prov() }); + // #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(); + const body: Record = { status: "ok", source: prov() }; + const diag = source.diagnostics?.(); + if (diag) body.sections = diag; + return json(body); } const itemMatch = /^\/item\/(.+)$/.exec(path); diff --git a/pm-stack/aggregator/src/source.ts b/pm-stack/aggregator/src/source.ts index 757135db46..4e8a0af197 100644 --- a/pm-stack/aggregator/src/source.ts +++ b/pm-stack/aggregator/src/source.ts @@ -1,6 +1,7 @@ // The one interface every data source implements. The views never know // whether they are looking at fixtures or live readers — swapping one for // the other is a config change (PM_AGG_SOURCE), not a code change. +import type { SectionDiagnosis } from "./feed.ts"; import type { AaFeedSection, BoardItem, @@ -10,6 +11,7 @@ import type { OrchestrationSection, ProjectPoolItem, Provenance, + ProvenanceDetail, QuotaView, RefKey, UsageView, @@ -50,4 +52,18 @@ export interface Source { /** Which session sources are wired, for the coverage note (slice 2). */ coverage(): Promise; provenance(): Provenance; + /** + * Structured per-section diagnosis (#1139/#1140): the honesty + * surfaces read the orchestration section's state from here instead + * of inferring it from a null section — absent, invalid, and stale + * are different failures with different remedies. Optional so test + * doubles and older sources keep working; absent = unmeasured. + */ + diagnostics?(): { orchestration: SectionDiagnosis }; + /** + * Structured per-facet freshness for the chips (#1138). Optional for + * the same reason as diagnostics(); when a source does not provide + * it, pages render without chips rather than with invented states. + */ + provenanceDetail?(): ProvenanceDetail; } diff --git a/pm-stack/aggregator/src/sources/fixtures.ts b/pm-stack/aggregator/src/sources/fixtures.ts index 49aa90d75c..29469ab4b4 100644 --- a/pm-stack/aggregator/src/sources/fixtures.ts +++ b/pm-stack/aggregator/src/sources/fixtures.ts @@ -1246,5 +1246,25 @@ export function fixtureSource(): Source { }, ], provenance: () => provenance, + // Fixtures carry no orchestration section (see orchestration() + // above), so the honest diagnosis is absent — the honesty + // surfaces banner it exactly like a live source with no run yet. + diagnostics: () => ({ orchestration: { state: "absent" as const } }), + provenanceDetail: () => { + const facet = (text: string) => ({ text, state: "fixtures" as const }); + return { + board: facet(provenance.board), + roadmap: facet(provenance.roadmap), + items: facet(provenance.items), + comments: facet(provenance.comments), + quota: facet(provenance.quota), + usage: facet(provenance.usage), + attention: facet(provenance.attention), + orchestration: facet(provenance.orchestration), + dns: facet(provenance.dns), + registry: facet(provenance.registry), + aa: facet(provenance.aa), + }; + }, }; } diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index ba3cf6f442..4a0937b086 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -9,11 +9,13 @@ import type { Config } from "../config.ts"; import { isAaSection } from "../aa.ts"; import { isDnsSection } from "../dns.ts"; import { + diagnoseOrchestrationSection, feedAgeText, normalizeOrchestrationSection, orchestrationSectionProblem, loadFeed, type FleetFeed, + type SectionDiagnosis, } from "../feed.ts"; import { isSessionRecord, mergeRecords, recordFromSessionEntry } from "../registry.ts"; import { buildAttentionFlags } from "../derive.ts"; @@ -33,6 +35,8 @@ import { type OrchestrationSection, type ProjectPoolItem, type Provenance, + type ProvenanceDetail, + type ProvenanceFacet, type QuotaView, type RefKey, type RoadmapRow, @@ -467,6 +471,13 @@ export function inFlightBoardItems(section: OrchestrationSection, existing: Boar // --- Composition ---------------------------------------------------------- +/** + * The fleet's own staleness line for the feed itself (#1148's + * watchdog threshold): a feed-backed facet older than this renders + * its freshness chip as stale, however live its last read was. + */ +const FEED_STALE_MS = 15 * 60_000; + export function liveSource(cfg: Config): Source { const fix = fixtureSource(); const provenance: Provenance = { @@ -483,6 +494,16 @@ export function liveSource(cfg: Config): Source { aa: "fixtures", }; + // #1139/#1140: the last orchestration diagnosis, recomputed on every + // orchestration() read from the raw feed value — the honesty + // surfaces (Source.diagnostics) read it from here, never from a + // null section, so absent/invalid/stale stay distinguishable. + let lastOrchestrationDiagnosis: SectionDiagnosis = { state: "absent" }; + // #1138: the merged registry total from the last registry() read — + // the freshness chip counts THIS (the same number /sessions renders + // in its header), never the per-read incoming batch. + let lastRegistryMergedCount: number | null = null; + async function kaneoCookieHeader(): Promise { if (!cfg.kaneo.email || !cfg.kaneo.password) throw new Error("no kaneo credentials"); const res = await fetch(`${cfg.kaneo.baseUrl}/api/auth/sign-in/email`, { @@ -667,6 +688,12 @@ export function liveSource(cfg: Config): Source { : ""); } else if (projectorServed) { provenance.items = "live (projector)"; + } else if (pool.length > 0 && feed) { + // No refs were resolved this call (e.g. the /api/health + // provenance prime, #1267): the facet is pool-backed all the + // same — say so rather than leaving the fixture default + // standing for a facet nobody happened to exercise yet. + provenance.items = `live (project pool · fleet feed · ${feedAgeText(feed.generatedAt)})`; } return out; }, @@ -807,7 +834,10 @@ export function liveSource(cfg: Config): Source { // the normalized contract shape, #1110), invalid (a section is // present but failed validation: name the failed check, never // claim the job "has not published"), absent (no section key). + // #1139 adds the fourth — stale — tracked as a diagnosis on the + // source so the attention/today surfaces can banner it. const feed = await getFeed(); + lastOrchestrationDiagnosis = diagnoseOrchestrationSection(feed?.orchestration ?? null); if (feed?.orchestration) { const section = normalizeOrchestrationSection(feed.orchestration); if (section) { @@ -876,11 +906,20 @@ export function liveSource(cfg: Config): Source { /* laptop part fails soft, like attention */ } if (incoming.length > 0) { - provenance.registry = `live (${incoming.length} records merged · feed ${feed ? feedAgeText(feed.generatedAt) : "absent"})`; - return mergeIntoRegistry(incoming); + const merged = await mergeIntoRegistry(incoming); + lastRegistryMergedCount = merged.length; + // #1138: the headline number is the MERGED total — the same + // count the /sessions header renders — with the latest feed's + // contribution labelled as what it is. (This string used to + // headline the incoming batch, so one page carried two counts + // for "records" with nothing explaining the difference.) + provenance.registry = `live (${merged.length} session records · ${incoming.length} from the latest feed · feed ${feed ? feedAgeText(feed.generatedAt) : "absent"})`; + return merged; } + const store = await loadRegistryStore(); + lastRegistryMergedCount = store.length; provenance.registry = "store only (no live registry source reachable)"; - return loadRegistryStore(); + return store; }, async coverage(): Promise { const feed = lastFeed ?? (await getFeed()); @@ -930,6 +969,58 @@ export function liveSource(cfg: Config): Source { return out; }, provenance: () => provenance, + diagnostics: () => ({ orchestration: lastOrchestrationDiagnosis }), + provenanceDetail: (): ProvenanceDetail => { + // #1138: facet state derives from the facet's own string (the + // strings are the contract every facet already maintains), + // plus two facts strings can't carry: the orchestration + // diagnosis (stale/invalid precision) and the feed's age (a + // "live" string over a dead feed is stale, #1148's threshold). + const feedAgeMs = lastFeed ? Math.max(0, Date.now() - Date.parse(lastFeed.generatedAt)) : undefined; + const facet = (key: keyof Provenance): ProvenanceFacet => { + const text = provenance[key]; + let state: ProvenanceFacet["state"]; + if (text.startsWith("live")) state = "live"; + else if (text.startsWith("invalid")) state = "invalid"; + else if (text.startsWith("none yet") || text.startsWith("not collected yet")) state = "absent"; + else if (text.startsWith("store only")) state = "live"; + else state = "fixtures"; + const feedBacked = text.includes("fleet feed"); + if (state === "live" && feedBacked && feedAgeMs !== undefined && feedAgeMs > FEED_STALE_MS) { + state = "stale"; + } + const out: ProvenanceFacet = { text, state }; + if (key === "orchestration") { + if (lastOrchestrationDiagnosis.state === "stale" && state === "live") out.state = "stale"; + if (lastOrchestrationDiagnosis.state === "invalid") out.state = "invalid"; + if (lastOrchestrationDiagnosis.ageMs !== undefined) out.ageMs = lastOrchestrationDiagnosis.ageMs; + } else if (feedBacked && feedAgeMs !== undefined) { + out.ageMs = feedAgeMs; + } + if (key === "registry" && lastRegistryMergedCount !== null) { + out.count = lastRegistryMergedCount; + out.countLabel = "session records"; + if (feedAgeMs !== undefined) { + out.ageMs = feedAgeMs; + if (out.state === "live" && feedAgeMs > FEED_STALE_MS) out.state = "stale"; + } + } + return out; + }; + return { + board: facet("board"), + roadmap: facet("roadmap"), + items: facet("items"), + comments: facet("comments"), + quota: facet("quota"), + usage: facet("usage"), + attention: facet("attention"), + orchestration: facet("orchestration"), + dns: facet("dns"), + registry: facet("registry"), + aa: facet("aa"), + }; + }, }; } diff --git a/pm-stack/aggregator/test/boot.test.ts b/pm-stack/aggregator/test/boot.test.ts index e72ab622e9..c16cf518cd 100644 --- a/pm-stack/aggregator/test/boot.test.ts +++ b/pm-stack/aggregator/test/boot.test.ts @@ -63,7 +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 Drew")).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("Session coverage")).toBe(true); expect(attention.includes("amd-6.raptor-pumpkinseed.ts.net")).toBe(true); }); diff --git a/pm-stack/aggregator/test/health-priming.test.ts b/pm-stack/aggregator/test/health-priming.test.ts new file mode 100644 index 0000000000..8146b5d5b7 --- /dev/null +++ b/pm-stack/aggregator/test/health-priming.test.ts @@ -0,0 +1,97 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import { spawn, type Subprocess } from "bun"; +import { mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +// #1267: /api/health must not lie by request order. The live source +// populates provenance strings lazily — historically, a fresh process +// whose FIRST request was /api/health reported "fixtures" for facets +// that were really live, because no page visit had exercised them yet. +// This test boots a live-source server against a controlled feed and +// asserts on the FIRST response the process ever serves. + +interface HealthBody { + status: string; + source: Record; + sections?: { orchestration: { state: string; runId?: string } }; +} + +let proc: Subprocess | undefined; +let firstHealth: HealthBody | undefined; + +beforeAll(async () => { + const dir = await mkdtemp(join(tmpdir(), "pm-health-")); + const now = new Date().toISOString(); + const feed = { + version: 1, + generatedAt: now, + quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, + attention: [], + orchestration: { + version: 1, + generatedAt: now, + runId: "orch-health-test", + provenance: { sources: ["health priming test"], runId: "orch-health-test" }, + tiers: { needsDrew: [], needsOrchestrator: [] }, + dependencies: [], + goals: [], + actions: [], + }, + registry: [{ id: "ses-health-1", source: "opencode-sandbox", label: "Health probe session" }], + }; + const feedFile = join(dir, "fleet-feed.json"); + await writeFile(feedFile, JSON.stringify(feed)); + const port = 5100 + Math.floor(Math.random() * 800); + proc = spawn({ + cmd: ["bun", "run", "src/server.ts"], + cwd: join(import.meta.dir, ".."), + env: { + ...Bun.env, + PM_AGG_PORT: String(port), + PM_AGG_SOURCE: "live", + PM_AGG_FEED_FILE: feedFile, + PM_AGG_REGISTRY_FILE: join(dir, "registry.json"), + PM_AGG_COMMENTS_FILE: join(dir, "comments.json"), + PM_AGG_SNAPSHOTS_DIR: join(dir, "snapshots"), + PM_AGG_OPENCHAMBER_STATE: join(dir, "no-state.json"), + PM_AGG_QUOTA_VIEW: join(dir, "no-quota-view.md"), + PM_AGG_QUOTA_REGISTRY: join(dir, "no-quota-registry.md"), + PM_PROJECTOR_URL: "off", + KANEO_ADMIN_EMAIL: "", + KANEO_ADMIN_PASSWORD: "", + GRIST_API_KEY: "", + }, + stdout: "pipe", + stderr: "inherit", + }); + // Poll until the server answers; the first successful body IS the + // assertion target — nothing else touches this process beforehand. + const deadline = Date.now() + 20_000; + while (Date.now() < deadline && !firstHealth) { + try { + const res = await fetch(`http://127.0.0.1:${port}/api/health`); + if (res.ok) firstHealth = (await res.json()) as HealthBody; + } catch { + /* not up yet */ + } + if (!firstHealth) await Bun.sleep(150); + } + expect(firstHealth).toBeDefined(); +}); + +afterAll(() => { + proc?.kill(); +}); + +describe("/api/health provenance priming (#1267)", () => { + test("the first-ever response reports the live facets truthfully", () => { + expect(firstHealth?.status).toBe("ok"); + expect(firstHealth?.source.quota).toContain("live (fleet feed"); + expect(firstHealth?.source.orchestration).toContain("live (orchestration section orch-health-test"); + expect(firstHealth?.source.registry).toContain("1 session records"); + expect(firstHealth?.source.registry).not.toBe("fixtures"); + expect(firstHealth?.sections?.orchestration.state).toBe("live"); + expect(firstHealth?.sections?.orchestration.runId).toBe("orch-health-test"); + }); +}); diff --git a/pm-stack/aggregator/test/orchestration.test.ts b/pm-stack/aggregator/test/orchestration.test.ts index 8a0981ac0c..5a024baa75 100644 --- a/pm-stack/aggregator/test/orchestration.test.ts +++ b/pm-stack/aggregator/test/orchestration.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import { loadConfig } from "../src/config.ts"; import { todayFromSection } from "../src/derive.ts"; import { + diagnoseOrchestrationSection, isFleetFeed, isOrchestrationSection, normalizeOrchestrationSection, @@ -273,3 +274,110 @@ describe("live source orchestration states (#1140)", () => { expect(src.provenance().orchestration).toContain("live (orchestration section orch-2026-10-27T03:14:56Z"); }); }); + +describe("orchestration diagnosis (#1139)", () => { + test("absent: null and missing values diagnose as absent", () => { + expect(diagnoseOrchestrationSection(null).state).toBe("absent"); + expect(diagnoseOrchestrationSection(undefined).state).toBe("absent"); + }); + + test("invalid: a present-but-malformed section names the failing check", () => { + const bad = { ...SECTION, tiers: { needsOrchestrator: [] } }; + const d = diagnoseOrchestrationSection(bad, Date.parse("2026-10-25T18:00:00.000Z")); + expect(d.state).toBe("invalid"); + expect(d.failedChecks).toContain("tiers.needsDrew"); + }); + + test("live: a fresh valid section diagnoses live with run id and age", () => { + const d = diagnoseOrchestrationSection(SECTION, Date.parse("2026-10-25T17:50:00.000Z")); + expect(d.state).toBe("live"); + expect(d.runId).toBe("orch-2026-10-25T17:20:00.000Z"); + expect(d.ageMs).toBe(30 * 60_000); + }); + + test("stale: a valid section older than the 90m threshold diagnoses stale", () => { + const d = diagnoseOrchestrationSection(SECTION, Date.parse("2026-10-25T19:00:00.000Z")); + expect(d.state).toBe("stale"); + expect(d.ageMs).toBe(100 * 60_000); + }); +}); + +describe("live source diagnostics + provenance detail (#1139/#1138)", () => { + async function sourceWithFeed(over: Record): Promise> { + const dir = await mkdtemp(join(tmpdir(), "pm-diag-")); + const feedFile = join(dir, "fleet-feed.json"); + const now = new Date().toISOString(); + await writeFile( + feedFile, + JSON.stringify({ + version: 1, + generatedAt: now, + quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, + attention: [], + ...over, + }), + ); + const cfg = loadConfig({ + ...Bun.env, + PM_AGG_SOURCE: "live", + PM_AGG_FEED_FILE: feedFile, + PM_AGG_REGISTRY_FILE: join(dir, "registry.json"), + PM_AGG_COMMENTS_FILE: join(dir, "comments.json"), + PM_AGG_SNAPSHOTS_DIR: join(dir, "snapshots"), + PM_AGG_OPENCHAMBER_STATE: join(dir, "no-state.json"), + PM_PROJECTOR_URL: "off", + KANEO_ADMIN_EMAIL: "", + KANEO_ADMIN_PASSWORD: "", + GRIST_API_KEY: "", + }); + return liveSource(cfg); + } + + const liveSection = () => ({ + ...SECTION, + generatedAt: new Date().toISOString(), + runId: "orch-diag-live", + provenance: { sources: ["test"], runId: "orch-diag-live" }, + }); + + test("diagnostics reflects the section the source actually holds", async () => { + const ok = await sourceWithFeed({ orchestration: liveSection() }); + await ok.orchestration(); + expect(ok.diagnostics?.().orchestration.state).toBe("live"); + expect(ok.diagnostics?.().orchestration.runId).toBe("orch-diag-live"); + expect(ok.provenanceDetail?.().orchestration.state).toBe("live"); + + const missing = await sourceWithFeed({}); + await missing.orchestration(); + expect(missing.diagnostics?.().orchestration.state).toBe("absent"); + + const invalidSrc = await sourceWithFeed({ + orchestration: { + version: 1, + generatedAt: new Date().toISOString(), + runId: "x", + tiers: { needsDrew: [], needsOrchestrator: [] }, + }, + }); + await invalidSrc.orchestration(); + const d = invalidSrc.diagnostics?.().orchestration; + expect(d?.state).toBe("invalid"); + expect(d?.failedChecks).toContain("provenance"); + expect(invalidSrc.provenanceDetail?.().orchestration.state).toBe("invalid"); + }); + + test("registry facet counts the MERGED total, with its noun (#1138)", async () => { + const src = await sourceWithFeed({ + orchestration: liveSection(), + registry: [{ id: "ses-diag-1", source: "opencode-sandbox", label: "Diag session" }], + }); + const records = await src.registry(); + expect(records.length).toBe(1); + expect(src.provenance().registry).toContain("1 session records"); + expect(src.provenance().registry).toContain("1 from the latest feed"); + const facet = src.provenanceDetail?.().registry; + expect(facet?.count).toBe(1); + expect(facet?.countLabel).toBe("session records"); + expect(facet?.state).toBe("live"); + }); +}); diff --git a/pm-stack/aggregator/test/render.test.ts b/pm-stack/aggregator/test/render.test.ts index edaa919bab..f6485203e1 100644 --- a/pm-stack/aggregator/test/render.test.ts +++ b/pm-stack/aggregator/test/render.test.ts @@ -3,6 +3,7 @@ import { attentionSorted, buildAttention, classifyAttention, + deriveToday, executionStrip, laneFor, timeline, @@ -15,6 +16,7 @@ import { refUrl, type BoardItem, type GhItem, + type ProvenanceDetail, type RefKey, type RoadmapRow, type SessionFeedEntry, @@ -26,7 +28,15 @@ import { FIXTURE_ROADMAP, fixtureSource, } from "../src/sources/fixtures.ts"; -import { renderAttention, renderBoard, renderItem, renderQuota, renderRoadmap } from "../src/render.ts"; +import { + renderAttention, + renderBoard, + renderItem, + renderQuota, + renderRoadmap, + renderSessions, + renderToday, +} from "../src/render.ts"; const items = new Map(FIXTURE_ITEMS.map((i) => [i.ref, i])); @@ -212,9 +222,64 @@ 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 Drew"); + 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("waiting for an answer"); expect(html).toContain("Waiting on:"); }); }); + +describe("freshness chips (#1138)", () => { + const detail: ProvenanceDetail = { + board: { text: "fixtures", state: "fixtures" }, + roadmap: { text: "fixtures", state: "fixtures" }, + items: { text: "fixtures", state: "fixtures" }, + comments: { text: "fixtures", state: "fixtures" }, + quota: { text: "live (fleet feed)", state: "live", ageMs: 120_000 }, + usage: { text: "fixtures", state: "fixtures" }, + attention: { text: "live (laptop live)", state: "live" }, + orchestration: { text: "live (orchestration section orch-x)", state: "live", ageMs: 600_000 }, + dns: { text: "fixtures", state: "fixtures" }, + registry: { + text: "live (221 session records · 61 from the latest feed)", + state: "live", + ageMs: 180_000, + count: 221, + countLabel: "session records", + }, + aa: { text: "fixtures", state: "fixtures" }, + }; + + test("sessions chip carries the merged count with its noun; footer detail is collapsed", async () => { + const src = fixtureSource(); + const html = renderSessions(await src.registry(), src.provenance(), detail); + expect(html).toContain('class="fchip live"'); + expect(html).toContain("registry · live · 221 session records"); + // The ten-string provenance line survives, inside
. + expect(html).toContain(" { + const src = fixtureSource(); + const today = deriveToday(FIXTURE_BOARD, FIXTURE_ROADMAP, items, null); + const attention = buildAttention(await src.attention(), null); + const html = renderToday(today, attention, await src.quota(), await src.coverage(), src.provenance(), detail); + expect(html).toContain("orchestration · live"); + expect(html).toContain("quota · live"); + expect(html).not.toContain("dns · fixtures"); + expect(html).not.toContain("registry · live"); + }); + + test("no detail, no chips — older callers render as before", async () => { + const src = fixtureSource(); + const html = renderSessions(await src.registry(), src.provenance()); + expect(html).not.toContain('class="fchip'); + }); +}); diff --git a/pm-stack/aggregator/test/slice2.test.ts b/pm-stack/aggregator/test/slice2.test.ts index 95b8d9de82..af06b3b996 100644 --- a/pm-stack/aggregator/test/slice2.test.ts +++ b/pm-stack/aggregator/test/slice2.test.ts @@ -380,7 +380,12 @@ 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 Drew"); + 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("Tier source missing"); + expect(html).toContain("orch-test"); expect(html).toContain("Why you:"); expect(html).toContain("Only Drew can pick which repo installs"); expect(html).toContain("OpenCode · laptop"); @@ -392,3 +397,61 @@ describe("attention render (slice 2)", () => { expect(html).not.toContain("one-shot probe"); // the expired fixture entry }); }); + +describe("attention honesty (#1139)", () => { + test("absent section: banner renders, counts are unknown, never a confident zero", async () => { + const src = fixtureSource(); + const view = buildAttention(await src.attention(), null); + expect(view.tierSource.present).toBe(false); + expect(view.tierSource.state).toBe("absent"); + 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)"); + // The false-reassurance empty copy is suppressed in this state. + expect(html).not.toContain("Nothing in the user queue right now."); + }); + + test("invalid section: the banner names the failed check", async () => { + const src = fixtureSource(); + const view = buildAttention(await src.attention(), null, Date.now(), { + state: "invalid", + failedChecks: ["provenance"], + }); + expect(view.tierSource.present).toBe(false); + 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)"); + }); + + test("stale section: counts render, badged with a stale banner and the run stamp", async () => { + const src = fixtureSource(); + const view = buildAttention(await src.attention(), SECTION, Date.now(), { + state: "stale", + runId: SECTION.runId, + generatedAt: SECTION.generatedAt, + }); + 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).toContain("orch-test"); + }); + + test("today's derived banner names an invalid section instead of 'not published'", async () => { + const src = fixtureSource(); + const items = new Map(FIXTURE_ITEMS.map((i) => [i.ref, i])); + const today = deriveToday(FIXTURE_BOARD, FIXTURE_ROADMAP, items, null, new Date(), { + state: "invalid", + failedChecks: ["tiers.needsDrew"], + }); + const attention = buildAttention(await src.attention(), null); + const html = renderToday(today, attention, await src.quota(), await src.coverage(), src.provenance()); + expect(html).toContain("failed validation"); + expect(html).toContain("tiers.needsDrew"); + expect(html).not.toContain("has not published a goal-measurement section yet"); + }); +});