From 9d0c136ba246ca4df4282c78be58bdd9ba14d0a1 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Mon, 9 Nov 2026 08:58:55 -0600 Subject: [PATCH] aggregator(forecast): expose and render one forecast contract on Roadmap and Projects (#3984) --- pm-stack/aggregator/src/config.ts | 8 + pm-stack/aggregator/src/forecast-contract.ts | 388 ++++++++++++++++++ pm-stack/aggregator/src/render.ts | 39 +- pm-stack/aggregator/src/server.ts | 91 ++++ .../test/forecast-contract-3984.test.ts | 312 ++++++++++++++ 5 files changed, 830 insertions(+), 8 deletions(-) create mode 100644 pm-stack/aggregator/src/forecast-contract.ts create mode 100644 pm-stack/aggregator/test/forecast-contract-3984.test.ts diff --git a/pm-stack/aggregator/src/config.ts b/pm-stack/aggregator/src/config.ts index 35bc82e6d0..7db00ccdec 100644 --- a/pm-stack/aggregator/src/config.ts +++ b/pm-stack/aggregator/src/config.ts @@ -61,6 +61,10 @@ export interface Config { digestsDir: string; /** Append-only notification state/send/suppression log (#3317). */ notificationsFile: string; + /** Versioned item-history JSONL (#3981) the forecast contract + * (#3984) derives from: one cutoff per line, read via + * ItemHistoryStore. */ + itemHistoryFile: string; /** The stewardship quota view; the hub's live fallback source when the * fleet feed carries no saas/payg sections yet (hub §2.3). */ quotaViewFile: string; @@ -185,6 +189,10 @@ export function loadConfig(env: Record = process.env join(homedir(), "workspace/goals/keep-the-four-repos-healthy/hidden_files/provider-quota-registry.md"), ), quotaCurrentFile: s(env.PM_AGG_QUOTA_CURRENT_FILE, join(process.cwd(), "quota-current.json")), + itemHistoryFile: s( + env.PM_AGG_ITEM_HISTORY_FILE, + join(homedir(), ".local", "state", "pm-aggregator", "item-history.jsonl"), + ), coverageSnapshotFile: s(env.PM_AGG_COVERAGE_SNAPSHOT_FILE, join(process.cwd(), "coverage-snapshot.json")), openchamberStateFile: s( env.PM_AGG_OPENCHAMBER_STATE, diff --git a/pm-stack/aggregator/src/forecast-contract.ts b/pm-stack/aggregator/src/forecast-contract.ts new file mode 100644 index 0000000000..a96dace22a --- /dev/null +++ b/pm-stack/aggregator/src/forecast-contract.ts @@ -0,0 +1,388 @@ +// Shared forecast contract for #3984 (design: +// doc/2026-11-01T21-07-00Z_design_pm-stack_forecasting.md §4, parent +// #1256). Roadmap and Projects render THE SAME machine-readable +// forecast objects this module builds, and GET /api/forecasts.json +// serves them verbatim — page wording and API wording cannot drift. +// +// The three forecast types of the design stay separate objects so +// missing data in one plane can never make another look more certain: +// +// - epic_completion: wraps deriveEpicEta (#3982, src/forecast.ts). +// - quota_exhaustion: a per-pool wall interval from a measured burn +// rate. The per-pool rate-history model is #3983, still open; until +// a caller can supply a rate measured in the pool's own units, the +// honest result is the first-class "quota_rate_unavailable" state — +// never an invented date and never "safe". +// - stall_risk: wraps deriveStallRisk (#3982 §3). The score is a +// versioned rule score, not a probability; the contract exposes the +// contributing signals and the evidence coverage, and a stall score +// alone never escalates to Needs-you. +// +// Honesty rules (§4): p50/p80 are nullable; "no measurable pace", +// "not enough history", and "quota rate unavailable" are first-class +// states; missing values are never rendered as zero; every object +// names its scope, asOf, model version, input window/coverage, and +// structured reasons/limitations. + +import { + deriveEpicEta, + deriveStallRisk, + type BorrowedBaseline, + type EpicEta, + type EtaStatus, + type ForecastConfidence, + type StallRisk, +} from "./forecast.ts"; +import type { ItemHistoryCutoff } from "./item-history.ts"; +import type { RefKey } from "./model.ts"; + +export const FORECAST_CONTRACT_VERSION = "forecast-contract/v1"; +export const QUOTA_FORECAST_MODEL_VERSION = "quota-wall/v1"; + +/** A rate observation older than this is stale source, not a rate. + * Mirrors QUOTA_CURRENT_FRESH_MS (src/quota-current.ts). */ +export const QUOTA_RATE_FRESH_MS = 20 * 60_000; + +export interface ForecastReason { + code: string; + text: string; +} + +interface ForecastContractBase { + contractVersion: typeof FORECAST_CONTRACT_VERSION; + subjectRef: RefKey; + /** The actual pool/subject scope the numbers describe, stated in + * words — a Project #4 pool scope is a curated subset, never + * silently a repo-wide backlog (§4 / design "Current inputs"). */ + scope: string; + asOf: string; + modelVersion: string; + /** Evidence grade, not a probability (design §1). */ + confidence: ForecastConfidence; + reasons: ForecastReason[]; + limitations: ForecastReason[]; +} + +export interface EpicCompletionForecast extends ForecastContractBase { + type: "epic_completion"; + status: EtaStatus; + inputWindow: EpicEta["inputWindow"]; + inputCoverage: EpicEta["inputCoverage"]; + remainingUnits: number; + completedUnits: number; + /** ISO dates, or null when no defensible date exists. */ + p50: string | null; + p80: string | null; + baselineSource: string; + remainingEffort: EpicEta["remainingEffort"]; +} + +export type QuotaForecastStatus = "forecast" | "quota_rate_unavailable" | "no_recent_burn"; + +export interface QuotaExhaustionForecast extends ForecastContractBase { + type: "quota_exhaustion"; + status: QuotaForecastStatus; + poolId: string; + provider: string | null; + unit: string; + remainingAmount: number | null; + limitAmount: number | null; + nextReset: string | null; + inputWindow: { from: string | null; to: string }; + inputCoverage: { rateKnown: boolean; missing: string[] }; + /** Exhaustion interval from the observed rate; null unless a fresh + * measured rate, a remaining amount, and a reset are all known. */ + exhaustion: { + estimatedAt: string; + earliest: string; + latest: string; + beforeReset: boolean; + } | null; +} + +export interface StallRiskForecast extends ForecastContractBase { + type: "stall_risk"; + /** Versioned rule score 0–100. NOT a probability/percentage. */ + score: number; + threshold: number; + atRisk: boolean; + /** Always false: score alone never escalates (§3). */ + escalatesToNeedsYou: false; + /** Fraction of the four stall signals a source actually supplied. */ + evidenceCoverage: number; + signals: StallRisk["signals"]; +} + +export type ForecastContract = EpicCompletionForecast | QuotaExhaustionForecast | StallRiskForecast; + +const limitation = (text: string): ForecastReason => ({ code: "model_limitation", text }); + +export interface EpicForecastOptions { + scope?: string; + /** GitHub-vs-Project status disagreement for the subject, in words, + * when the caller knows one — surfaced on the contract, never + * resolved silently (§4). */ + statusDisagreement?: string | null; +} + +/** Map a derived epic ETA (#3982) onto the shared contract (§4). */ +export function epicForecastContract(eta: EpicEta, opts: EpicForecastOptions = {}): EpicCompletionForecast { + const reasons: ForecastReason[] = []; + if (eta.status === "borrowed_baseline") { + reasons.push({ + code: "borrowed_baseline", + text: `local evidence is below the numeric-forecast floor; the rate is borrowed from ${eta.baselineSource}`, + }); + } else if (eta.status === "not_enough_history") { + reasons.push({ + code: "not_enough_history", + text: "not enough complete observed history for a defensible date; no date is published", + }); + } else if (eta.status === "no_measurable_pace") { + reasons.push({ + code: "no_measurable_pace", + text: "the observed completion pace in scope is zero; no date is published", + }); + } + if (opts.statusDisagreement) { + reasons.push({ code: "status_disagreement", text: opts.statusDisagreement }); + } + return { + contractVersion: FORECAST_CONTRACT_VERSION, + type: "epic_completion", + subjectRef: eta.subjectRef, + scope: opts.scope ?? `direct native children of ${eta.subjectRef} in the item-history pool`, + asOf: eta.asOf, + modelVersion: eta.modelVersion, + confidence: eta.confidence, + reasons, + limitations: eta.limitations.map(limitation), + status: eta.status, + inputWindow: eta.inputWindow, + inputCoverage: eta.inputCoverage, + remainingUnits: eta.remainingUnits, + completedUnits: eta.completedUnits, + p50: eta.p50, + p80: eta.p80, + baselineSource: eta.baselineSource, + remainingEffort: eta.remainingEffort, + }; +} + +export interface QuotaForecastInput { + poolId: string; + provider?: string | null; + subjectRef?: RefKey; + scope?: string; + asOf: string; + unit: string; + remainingAmount?: number | null; + limitAmount?: number | null; + nextReset?: string | null; + /** Burn measured in the pool's own units. Omit (or pass null) when + * no source measures the rate in these units — the result is then + * "quota_rate_unavailable", by design (§2). */ + rate?: { + amountPerHour: number; + observedAt: string; + /** Observed low/high rate band, when a rate history supplies one + * (#3933/#3983). Without it the interval collapses to the point + * estimate and says so in limitations. */ + intervalPerHour?: { low: number; high: number }; + } | null; + /** Max acceptable rate age; defaults to QUOTA_RATE_FRESH_MS. */ + maxRateAgeMs?: number; +} + +/** Build the quota-wall contract for one pool (§2 + §4). */ +export function quotaForecastContract(input: QuotaForecastInput): QuotaExhaustionForecast { + const reasons: ForecastReason[] = []; + const limitations: ForecastReason[] = []; + const missing: string[] = []; + const remaining = input.remainingAmount ?? null; + const limit = input.limitAmount ?? null; + const nextReset = input.nextReset ?? null; + if (remaining === null) missing.push("remaining amount"); + if (limit === null) missing.push("limit"); + if (nextReset === null) missing.push("next reset"); + const rate = input.rate ?? null; + if (rate === null) missing.push("measured burn rate"); + + let status: QuotaForecastStatus = "quota_rate_unavailable"; + let exhaustion: QuotaExhaustionForecast["exhaustion"] = null; + if (rate !== null) { + const ageMs = Date.parse(input.asOf) - Date.parse(rate.observedAt); + if (Number.isNaN(ageMs) || ageMs < 0 || ageMs > (input.maxRateAgeMs ?? QUOTA_RATE_FRESH_MS)) { + reasons.push({ + code: "stale_source", + text: `burn rate observed at ${rate.observedAt} is stale at ${input.asOf}; a stale rate publishes no date`, + }); + missing.push("fresh burn rate"); + } else if (!(rate.amountPerHour > 0)) { + status = "no_recent_burn"; + reasons.push({ + code: "no_recent_burn", + text: "measured burn rate is zero; absence of burn is not evidence the pool is safe", + }); + } else if (remaining !== null && nextReset !== null) { + const at = (hours: number) => new Date(Date.parse(input.asOf) + hours * 3_600_000).toISOString(); + const estimatedAt = at(remaining / rate.amountPerHour); + let earliest = estimatedAt; + let latest = estimatedAt; + const band = rate.intervalPerHour; + if (band && band.low > 0 && band.high >= band.low) { + earliest = at(remaining / band.high); + latest = at(remaining / band.low); + } else { + limitations.push({ + code: "single_linear_rate", + text: "single linear rate: the interval collapses to the point estimate until a measured rate history (#3933/#3983) supplies a band; no statistical confidence is implied", + }); + } + exhaustion = { estimatedAt, earliest, latest, beforeReset: estimatedAt <= nextReset }; + status = "forecast"; + reasons.push({ + code: exhaustion.beforeReset ? "wall_before_reset" : "wall_after_reset", + text: exhaustion.beforeReset + ? "the measured rate exhausts the remaining amount before the next reset" + : "the measured rate does not exhaust the remaining amount before the next reset", + }); + } + } + if (status === "quota_rate_unavailable") { + for (const m of [...new Set(missing)]) { + reasons.push({ code: `missing_${m.replace(/[^a-z]+/g, "_")}`, text: `${m} unavailable for pool ${input.poolId}` }); + } + if (!reasons.some((r) => r.code === "stale_source")) { + reasons.push({ + code: "quota_rate_unavailable", + text: "quota rate unavailable: no exhaustion date is published and the pool is not shown as safe", + }); + } + } + return { + contractVersion: FORECAST_CONTRACT_VERSION, + type: "quota_exhaustion", + subjectRef: input.subjectRef ?? `quota:${input.poolId}`, + scope: input.scope ?? `quota pool ${input.poolId}`, + asOf: input.asOf, + modelVersion: QUOTA_FORECAST_MODEL_VERSION, + confidence: status === "forecast" ? "low" : "unavailable", + reasons, + limitations, + status, + poolId: input.poolId, + provider: input.provider ?? null, + unit: input.unit, + remainingAmount: remaining, + limitAmount: limit, + nextReset, + inputWindow: { from: rate?.observedAt ?? null, to: input.asOf }, + inputCoverage: { rateKnown: rate !== null && status !== "quota_rate_unavailable", missing: [...new Set(missing)] }, + exhaustion, + }; +} + +export interface StallForecastOptions { + scope?: string; +} + +/** Map a derived stall-risk score (#3982 §3) onto the shared contract. */ +export function stallForecastContract(risk: StallRisk, opts: StallForecastOptions = {}): StallRiskForecast { + const reasons: ForecastReason[] = risk.signals + .filter((s) => s.known && s.contribution > 0) + .map((s) => ({ code: s.code, text: s.detail })); + const limitations: ForecastReason[] = risk.signals + .filter((s) => !s.known) + .map((s) => ({ code: "signal_unknown", text: `${s.code}: no source supplied this signal; it contributed nothing` })); + return { + contractVersion: FORECAST_CONTRACT_VERSION, + type: "stall_risk", + subjectRef: risk.ref, + scope: opts.scope ?? `item ${risk.ref}`, + asOf: risk.asOf, + modelVersion: risk.modelVersion, + confidence: risk.evidenceCoverage >= 1 ? "medium" : risk.evidenceCoverage > 0 ? "low" : "unavailable", + reasons, + limitations, + score: risk.score, + threshold: risk.threshold, + atRisk: risk.atRisk, + escalatesToNeedsYou: false, + evidenceCoverage: risk.evidenceCoverage, + signals: risk.signals, + }; +} + +export interface SubjectForecastOptions extends EpicForecastOptions { + /** Meaningful-activity proxy for the stall plane: the item's + * updatedAt, when the caller has it. */ + updatedAt?: string | null; + borrowedBaseline?: BorrowedBaseline; +} + +/** The epic-completion + stall-risk contracts for one subject, from + * the stored item history. Both planes share the same cutoffs; each + * keeps its own honesty state. */ +export function subjectForecastContracts( + cutoffs: ItemHistoryCutoff[], + subjectRef: RefKey, + opts: SubjectForecastOptions = {}, +): ForecastContract[] { + const eta = deriveEpicEta({ subjectRef, cutoffs, borrowedBaseline: opts.borrowedBaseline }); + const stall = deriveStallRisk({ ref: subjectRef, cutoffs, updatedAt: opts.updatedAt ?? null }); + return [epicForecastContract(eta, opts), stallForecastContract(stall, opts)]; +} + +// --- Shared one-line rendering (§4 presentation) -------------------------- + +function fmtDay(iso: string): string { + const d = new Date(iso); + return Number.isNaN(d.getTime()) + ? iso + : d.toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" }); +} + +function fmtRange(from: string, to: string): string { + return from === to ? fmtDay(from) : `${fmtDay(from)} – ${fmtDay(to)}`; +} + +/** One line, always carrying its evidence beside the estimate: a + * range (or a named no-date state), the confidence grade, and the + * input summary. Never a bare date, never a missing value as zero. */ +export function formatForecastSummary(contract: ForecastContract): string { + if (contract.type === "epic_completion") { + const total = contract.completedUnits + contract.remainingUnits; + const evidence = + `${contract.completedUnits} of ${total} completed children, ${contract.inputWindow.completeWeeks} complete observed weeks; ` + + `baseline: ${contract.baselineSource}`; + if (contract.p50 && contract.p80) { + return `${fmtRange(contract.p50, contract.p80)} · ${contract.confidence} confidence · ${evidence}`; + } + if (contract.status === "no_measurable_pace") return `No measurable pace · ${evidence}`; + if (contract.status === "not_enough_history") return `Not enough history · ${evidence}`; + return `No forecast date · ${contract.confidence} confidence · ${evidence}`; + } + if (contract.type === "quota_exhaustion") { + if (contract.status === "forecast" && contract.exhaustion) { + const reset = contract.nextReset ? `, resets ${fmtDay(contract.nextReset)}` : ""; + return ( + `Quota wall ${fmtRange(contract.exhaustion.earliest, contract.exhaustion.latest)} · low confidence · ` + + `${contract.remainingAmount} of ${contract.limitAmount} ${contract.unit} remaining${reset}; ` + + `${contract.exhaustion.beforeReset ? "exhausts before reset" : "does not exhaust before reset"}` + ); + } + if (contract.status === "no_recent_burn") { + return `No recent burn measured · pool ${contract.poolId} · not evidence the pool is safe`; + } + return `Quota rate unavailable · pool ${contract.poolId} · no exhaustion date published`; + } + const signals = contract.reasons.length + ? contract.reasons.map((r) => r.text).join("; ") + : "no contributing signals"; + const known = contract.signals.filter((sig) => sig.known).length; + return ( + `Stall risk ${contract.score} (threshold ${contract.threshold}) · ${contract.atRisk ? "at risk" : "below threshold"} · ` + + `${signals} · evidence from ${known} of ${contract.signals.length} signals` + ); +} diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 4f825a079d..dabbe78da3 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -25,6 +25,7 @@ import type { RoadmapAnnotation } from "./roadmap-annotations.ts"; import { diffCoverage, staleIssueState, type CoverageSnapshotFile } from "./coverage.ts"; import { DIGEST_SECTION_LIMIT, type Digest, type DigestKind } from "./digest.ts"; import { registryQueryString, type RegistryView } from "./registry-view.ts"; +import { formatForecastSummary, type ForecastContract } from "./forecast-contract.ts"; import { latestInFamily, newClientToken, type DashAction } from "./actions.ts"; import { applyBoardDonePolicy, DONE_STRIP_RENDER_LIMIT } from "./board-policy.ts"; import { summarizeWipLanes } from "./wip-limits.ts"; @@ -1655,7 +1656,15 @@ export function buildRoadmapDrill( ); } -function roadmapDrilldown(drill: RoadmapDrill, row: RoadmapRow): string { +/** The shared forecast contract (§4, #3984) as page lines: the same + * one-line summaries the API serves, never a bare date. */ +export function forecastSummaryHtml(contracts: ForecastContract[] | undefined): string { + if (!contracts?.length) return ""; + const lines = contracts.map((c) => `
${esc(formatForecastSummary(c))}
`).join(""); + return `
${lines}
`; +} + +function roadmapDrilldown(drill: RoadmapDrill, row: RoadmapRow, forecasts?: Map): string { const parts: string[] = []; if (!drill.epic) { parts.push(`

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

`); @@ -1683,6 +1692,10 @@ function roadmapDrilldown(drill: RoadmapDrill, row: RoadmapRow): string { ); } } + if (drill.epic) { + const fc = forecastSummaryHtml(forecasts?.get(drill.epic.ref)); + if (fc) parts.push(fc); + } if (row.notes.trim()) parts.push(`

${esc(row.notes)}

`); return `
Epic & issues${parts.join("")}
`; } @@ -1694,6 +1707,7 @@ function roadmapCard( drill?: RoadmapDrill, annotations?: Map, briefs?: Map, + forecasts?: Map, ): string { const refs = allRefs([row]); const refBadges = refs @@ -1703,7 +1717,7 @@ function roadmapCard( .join(" "); const cmt = counts ? commentBadge(row.subject, counts) : ""; const grist = row.gristUrl ? ` Grist ↗` : ""; - const expansion = drill ? roadmapDrilldown(drill, row) : ""; + const expansion = drill ? roadmapDrilldown(drill, row, forecasts) : ""; const notes = annotations?.get(row.subject) ?? []; const annotationHtml = notes.length ? `
${notes.map(roadmapAnnotationHtml).join("")}
` @@ -1726,6 +1740,7 @@ function timelineTable( drill?: Map, annotations?: Map, briefs?: Map, + forecasts?: Map, ): string { const head = `Theme${tl.lanes.map((l) => `${esc(l.label)}`).join("")}`; const body = tl.themes @@ -1735,7 +1750,7 @@ function timelineTable( const cells = tl.lanes .map((lane) => { const rs = tl.cells.get(theme)?.get(lane.key) ?? []; - return `${rs.map((r) => roadmapCard(r, items, counts, drill?.get(r.subject), annotations, briefs)).join("")}`; + return `${rs.map((r) => roadmapCard(r, items, counts, drill?.get(r.subject), annotations, briefs, forecasts)).join("")}`; }) .join(""); return `${esc(theme)} (${done}/${themeRows.length} done)${cells}`; @@ -1756,6 +1771,7 @@ export function renderRoadmap( annotations?: Map, viewQuery = "", briefs?: Map, + forecasts?: Map, ): string { // #1144: when the Grist rows and the Project's Kind=Epic pool items // disagree, say so on the page itself — drift the reader can see, @@ -1776,9 +1792,9 @@ export function renderRoadmap( : ""; let body: string; if (grain === "quarter") { - body = timelineTable(buildTimeline(rows), items, counts, drill, annotations, briefs); + body = timelineTable(buildTimeline(rows), items, counts, drill, annotations, briefs, forecasts); } else if (grain === "month") { - body = timelineTable(monthTimeline(rows), items, counts, drill, annotations, briefs); + body = timelineTable(monthTimeline(rows), items, counts, drill, annotations, briefs, forecasts); } else { const dg = roadmapDayGrain(rows, grain); const byTheme = new Map(); @@ -1791,7 +1807,7 @@ export function renderRoadmap( .map(([theme, themeRows]) => { const done = themeRows.filter((row) => row.status.trim().toLowerCase() === "done").length; const cards = (laneRows: RoadmapRow[]) => - laneRows.map((row) => roadmapCard(row, items, counts, drill?.get(row.subject), annotations, briefs)).join(""); + laneRows.map((row) => roadmapCard(row, items, counts, drill?.get(row.subject), annotations, briefs, forecasts)).join(""); const lanes = dg.lanes .map((lane) => { const laneRows = lane.rows.filter((row) => (row.area || "Unthemed") === theme); @@ -6355,6 +6371,9 @@ export function projectsBodyHtml( /** Prebuilt briefs (#1279), e.g. with comment activity folded in. * Absent: briefs are built here from the pool + orchestration only. */ briefs?: Map; + /** Shared forecast contracts by item ref (#3984): the same objects + * /api/forecasts.json serves, rendered as one-line summaries. */ + forecasts?: Map; } = {}, ): string { const base = opts.basePath ?? "/projects"; @@ -6418,7 +6437,8 @@ export function projectsBodyHtml( const rollup = p.kind === "Epic" ? epicRollups.get(p.ref) : undefined; const epicRollup = rollup ? epicRollupHtml(rollup) : ""; const brief = opts.briefs?.get(p.ref) ?? buildItemBrief(p, { pool, orchestration: opts.orchestration }); - return `
${esc(p.title)}${clashBadge}
${statusBadge} ${meta}
${esc(p.repo)}#${p.number} · Project item · Project #4${p.updatedAt ? ` · updated ${fmtDate(p.updatedAt)}` : ""}${epicRollup}${statusCtl}${briefPanelHtml(brief)}
`; + const forecastHtml = forecastSummaryHtml(opts.forecasts?.get(p.ref)); + return `
${esc(p.title)}${clashBadge}
${statusBadge} ${meta}
${esc(p.repo)}#${p.number} · Project item · Project #4${p.updatedAt ? ` · updated ${fmtDate(p.updatedAt)}` : ""}${epicRollup}${forecastHtml}${statusCtl}${briefPanelHtml(brief)}
`; }) .join(""); const body = `

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

@@ -6445,6 +6465,8 @@ export function renderProjects( identities?: AuthorIdentity[]; coverage?: CoverageSnapshotFile | null; basePath?: string; + briefs?: Map; + forecasts?: Map; } = {}, ): string { return layout( @@ -6544,12 +6566,13 @@ export function renderProgram( identities?: AuthorIdentity[]; /** Prebuilt briefs (#1279), e.g. with comment activity folded in. */ briefs?: Map; + forecasts?: Map; } | null, ): string { const poolSectionHtml = poolSection ? `

Projects pool

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

-${projectsBodyHtml(poolSection.pool, { area: poolSection.area, orchestration: poolSection.orchestration, actionsByObject: poolSection.actionsByObject, identities: poolSection.identities, coverage: poolSection.coverage, basePath: "/program", briefs: poolSection.briefs })}` +${projectsBodyHtml(poolSection.pool, { area: poolSection.area, orchestration: poolSection.orchestration, actionsByObject: poolSection.actionsByObject, identities: poolSection.identities, coverage: poolSection.coverage, basePath: "/program", briefs: poolSection.briefs, forecasts: poolSection.forecasts })}` : ""; const { program, live } = data; const projects = data.projects ?? []; diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index eec67cf6d3..6265ea9643 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -139,11 +139,19 @@ import { buildQueueView, queueInputsStale } from "./queue-view.ts"; import { dashboardResponseWithinDeadline } from "./assembly-deadline.ts"; import { dispatchStateFor, fetchRfaState, RFA_NOT_PICKED_UP } from "./sources/ready-for-agent.ts"; import { TodayCache, TODAY_CACHE_TTL_MS } from "./today-cache.ts"; +import { ItemHistoryStore } from "./item-history.ts"; +import { + FORECAST_CONTRACT_VERSION, + quotaForecastContract, + subjectForecastContracts, + type ForecastContract, +} from "./forecast-contract.ts"; const cfg = loadConfig(); const commentsStore = new CommentsStore(cfg.commentsFile); const roadmapAnnotationsStore = new RoadmapAnnotationsStore(cfg.roadmapAnnotationsFile); const coverageStore = new CoverageSnapshotStore(cfg.coverageSnapshotFile); +const itemHistoryStore = new ItemHistoryStore(cfg.itemHistoryFile); async function readyAgentDispatchStates(items: Map) { const targets = [...items.values()].filter((item) => @@ -516,6 +524,72 @@ async function boardContext() { return { board, items }; } +/** All shared forecast contracts (#3984): epic-completion + stall-risk + * per epic subject from the stored item history (#3981), and one + * quota-exhaustion contract per quota pool. The rate for a pool is + * only usable when the gatherer measured a token burn for a token + * window with ok freshness — anything else stays the contract's + * first-class quota_rate_unavailable state, never an invented date. */ +async function allForecastContracts( + pool: ProjectPoolItem[], +): Promise<{ byRef: Map; contracts: ForecastContract[] }> { + const byRef = new Map(); + const contracts: ForecastContract[] = []; + const add = (c: ForecastContract) => { + contracts.push(c); + byRef.set(c.subjectRef, [...(byRef.get(c.subjectRef) ?? []), c]); + }; + const cutoffs = await itemHistoryStore.readAll().catch(() => []); + if (cutoffs.length) { + const poolByRef = new Map(pool.map((it) => [it.ref, it])); + const subjects = new Set(); + for (const cutoff of cutoffs) { + for (const item of cutoff.items) { + if (item.parentRef) subjects.add(item.parentRef); + } + } + for (const subjectRef of subjects) { + const poolItem = poolByRef.get(subjectRef); + const statusDisagreement = + poolItem && poolItem.status && ((poolItem.state === "closed" && poolItem.status !== "Done") || (poolItem.state === "open" && poolItem.status === "Done")) + ? `GitHub state ${poolItem.state} disagrees with Project Status ${poolItem.status}; both are shown, neither is preferred` + : null; + for (const c of subjectForecastContracts(cutoffs, subjectRef, { + updatedAt: poolItem?.updatedAt ?? null, + statusDisagreement, + scope: `direct native children of ${subjectRef} in the Project #4 pool item history (curated pool scope, not a repo-wide backlog)`, + })) { + add(c); + } + } + } + const quota = await source.quota().catch(() => emptyQuotaView()); + const asOf = new Date().toISOString(); + for (const qpool of quota.pools) { + const window = qpool.windows + .filter((w) => w.limit !== null && w.limit > 0) + .sort((a, b) => (b.percent ?? 0) - (a.percent ?? 0))[0]; + const rate = + window && window.unit === "tokens" && qpool.burnTokensPerMin != null && qpool.freshness?.state === "ok" + ? { amountPerHour: qpool.burnTokensPerMin * 60, observedAt: qpool.freshness.measuredAt } + : null; + add( + quotaForecastContract({ + poolId: qpool.id, + provider: qpool.provider, + asOf, + unit: window?.unit ?? "tokens", + remainingAmount: window ? window.limit! - window.used : null, + limitAmount: window?.limit ?? null, + nextReset: window?.resetsAt ?? null, + rate, + scope: `quota pool ${qpool.id} (${qpool.provider}/${qpool.plan})`, + }), + ); + } + return { byRef, contracts }; +} + async function roadmapContext() { const rows = await source.roadmap().catch(() => []); const refs = allRefs(rows); @@ -1502,6 +1576,7 @@ async function handler(req: Request): Promise { orchestration, orchestrationStatus, }); + const forecasts = (await allForecastContracts(pool)).byRef; const g = url.searchParams.get("h") ?? "quarter"; const grain: RoadmapGrain = GRAINS.has(g) ? (g as RoadmapGrain) : "quarter"; const resolved = await resolveView(url); @@ -1532,6 +1607,7 @@ async function handler(req: Request): Promise { await annotationsFor(rows), viewQuery, briefs, + forecasts, ), ); } @@ -1568,10 +1644,24 @@ async function handler(req: Request): Promise { await annotationsFor(keptRows), viewQuery, briefs, + forecasts, ), ); } + if (path === "/api/forecasts.json") { + // #3984: the shared forecast contract — the identical objects the + // Roadmap and Projects pages render as one-line summaries. + const pool = await source.projects().catch(() => []); + const { contracts } = await allForecastContracts(pool); + const subject = url.searchParams.get("subject"); + return json({ + contractVersion: FORECAST_CONTRACT_VERSION, + generatedAt: new Date().toISOString(), + contracts: subject ? contracts.filter((c) => c.subjectRef === subject) : contracts, + }); + } + if (path === "/quota") { const [quota, usage] = await Promise.all([ source.quota().catch(() => emptyQuotaView()), @@ -1816,6 +1906,7 @@ async function handler(req: Request): Promise { actionsByObject, identities: formOpts.identities, briefs, + forecasts: (await allForecastContracts(viewPool)).byRef, }), ); } diff --git a/pm-stack/aggregator/test/forecast-contract-3984.test.ts b/pm-stack/aggregator/test/forecast-contract-3984.test.ts new file mode 100644 index 0000000000..075a481d69 --- /dev/null +++ b/pm-stack/aggregator/test/forecast-contract-3984.test.ts @@ -0,0 +1,312 @@ +import { describe, expect, test } from "bun:test"; +import { + FORECAST_CONTRACT_VERSION, + epicForecastContract, + formatForecastSummary, + quotaForecastContract, + stallForecastContract, + subjectForecastContracts, + type ForecastContract, +} from "../src/forecast-contract.ts"; +import { deriveEpicEta, type StallRisk } from "../src/forecast.ts"; +import type { ItemHistoryCutoff, ItemHistoryItem } from "../src/item-history.ts"; +import type { ProjectPoolItem, RoadmapRow } from "../src/model.ts"; +import { buildRoadmapDrill, projectsBodyHtml, renderRoadmap } from "../src/render.ts"; +import { reconcileRoadmap } from "../src/roadmap-reconcile.ts"; + +// #3984: one forecast contract, consumed by the API and rendered by +// Roadmap and Projects. ORACLE: the §4 field list and honesty states +// of doc/2026-11-01T21-07-00Z_design_pm-stack_forecasting.md — every +// contract carries scope/subject, asOf, model version, input +// window/coverage, remaining units, nullable P50/P80, confidence, +// baseline source, and structured reasons/limitations; the three +// forecast types are epic completion, quota exhaustion, stall risk. + +const REPO = "developing-today/code"; +const EPIC = `${REPO}#100`; +const W = [ + "2026-09-07T00:00:00Z", + "2026-09-14T00:00:00Z", + "2026-09-21T00:00:00Z", + "2026-09-28T00:00:00Z", + "2026-10-05T00:00:00Z", + "2026-10-12T00:00:00Z", + "2026-10-19T00:00:00Z", + "2026-10-26T00:00:00Z", + "2026-11-02T00:00:00Z", +]; + +function item(number: number, partial: Partial = {}): ItemHistoryItem { + return { + ref: `${REPO}#${number}`, + repo: REPO, + number, + kind: "issue", + state: "open", + status: null, + effort: null, + parentRef: EPIC, + blockedBy: [], + ...partial, + }; +} + +function cutoff(at: string, items: ItemHistoryItem[], complete = true): ItemHistoryCutoff { + return { + schemaVersion: 1, + cutoffAt: at, + coverage: { source: "projects-pool", fetchedAt: at, complete, unavailable: !complete }, + items, + }; +} + +function history(total: number, closesAtWeek: (number | null)[], weeks = W): ItemHistoryCutoff[] { + return weeks.map((at, week) => + cutoff( + at, + Array.from({ length: total }, (_, i) => + item(i + 1, { state: closesAtWeek[i] !== null && closesAtWeek[i]! <= week ? "closed" : "open" }), + ), + ), + ); +} + +const epicOf = (cutoffs: ItemHistoryCutoff[], opts?: Parameters[2]) => + subjectForecastContracts(cutoffs, EPIC, opts).find((c) => c.type === "epic_completion")!; + +describe("epic completion contract (#3984 §4)", () => { + test("high confidence: stable pace, >=12 completions over 8 weeks publishes a range with its evidence", () => { + // 16 children close, 2 per week across all 8 transitions; 4 remain. + const closes = Array.from({ length: 20 }, (_, i) => (i < 16 ? Math.floor(i / 2) + 1 : null)); + const c = epicOf(history(20, closes)); + expect(c.contractVersion).toBe(FORECAST_CONTRACT_VERSION); + expect(c.subjectRef).toBe(EPIC); + expect(c.scope).toContain(EPIC); + expect(c.status).toBe("forecast"); + expect(c.confidence).toBe("high"); + expect(c.p50).not.toBeNull(); + expect(c.p80).not.toBeNull(); + expect(c.p50! <= c.p80!).toBe(true); + expect(c.remainingUnits).toBe(4); + expect(c.completedUnits).toBe(16); + expect(c.baselineSource).toBe(EPIC); + const line = formatForecastSummary(c); + expect(line).toContain("high confidence"); + expect(line).toContain("16 of 20 completed children"); + // Never a bare date: the range always travels with its evidence. + expect(line).not.toMatch(/^[A-Z][a-z]{2} \d{1,2}$/); + expect(line.split("·").length).toBeGreaterThanOrEqual(3); + }); + + test("low confidence: borrowed baseline is named, never silent", () => { + const closes = Array.from({ length: 6 }, (_, i) => (i === 0 ? 2 : null)); + const c = epicOf(history(6, closes, W.slice(0, 5)), { + borrowedBaseline: { scopeRef: "portfolio baseline", weeklyCompletions: [1, 1, 1, 1] }, + }); + expect(c.status).toBe("borrowed_baseline"); + expect(c.confidence).toBe("low"); + expect(c.baselineSource).toBe("portfolio baseline"); + expect(c.p50).not.toBeNull(); + expect(c.reasons.map((r) => r.code)).toContain("borrowed_baseline"); + expect(formatForecastSummary(c)).toContain("portfolio baseline"); + }); + + test("missing baseline: below the floor with no comparable scope publishes no date", () => { + const c = epicOf(history(4, [null, null, null, null], W.slice(0, 2))); + expect(c.status).toBe("not_enough_history"); + expect(c.p50).toBeNull(); + expect(c.p80).toBeNull(); + expect(c.limitations.map((l) => l.text).join(" ")).toContain("no comparable borrowed baseline"); + expect(formatForecastSummary(c)).toContain("Not enough history"); + }); + + test("no measurable pace: a full zero-completion window is a state, not a date or a zero", () => { + const c = epicOf(history(5, [null, null, null, null, null], W.slice(0, 5))); + expect(c.status).toBe("no_measurable_pace"); + expect(c.p50).toBeNull(); + expect(formatForecastSummary(c)).toContain("No measurable pace"); + }); + + test("status disagreement stays visible on the contract", () => { + const eta = deriveEpicEta({ subjectRef: EPIC, cutoffs: history(4, [null, null, null, null], W.slice(0, 2)) }); + const c = epicForecastContract(eta, { statusDisagreement: "GitHub state open disagrees with Project Status Done" }); + expect(c.reasons.map((r) => r.code)).toContain("status_disagreement"); + }); +}); + +describe("quota exhaustion contract (#3984 §2/§4)", () => { + const base = { + poolId: "pool-a", + provider: "example", + asOf: "2026-11-09T12:00:00Z", + unit: "tokens", + remainingAmount: 500, + limitAmount: 1000, + nextReset: "2026-11-10T12:00:00Z", + }; + + test("fresh measured rate publishes an exhaustion interval and its relation to reset", () => { + const c = quotaForecastContract({ ...base, rate: { amountPerHour: 100, observedAt: "2026-11-09T11:55:00Z" } }); + expect(c.type).toBe("quota_exhaustion"); + expect(c.status).toBe("forecast"); + expect(c.exhaustion?.estimatedAt).toBe("2026-11-09T17:00:00.000Z"); + expect(c.exhaustion?.beforeReset).toBe(true); + expect(c.limitations.map((l) => l.code)).toContain("single_linear_rate"); + expect(formatForecastSummary(c)).toContain("Quota wall"); + }); + + test("an observed rate band widens the interval honestly", () => { + const c = quotaForecastContract({ + ...base, + rate: { amountPerHour: 100, observedAt: "2026-11-09T11:55:00Z", intervalPerHour: { low: 50, high: 200 } }, + }); + expect(c.exhaustion?.earliest).toBe("2026-11-09T14:30:00.000Z"); + expect(c.exhaustion?.latest).toBe("2026-11-09T22:00:00.000Z"); + expect(c.limitations.map((l) => l.code)).not.toContain("single_linear_rate"); + }); + + test("quota rate unavailable is first-class: no rate in pool units, no date, never safe", () => { + const c = quotaForecastContract({ ...base, rate: null }); + expect(c.status).toBe("quota_rate_unavailable"); + expect(c.confidence).toBe("unavailable"); + expect(c.exhaustion).toBeNull(); + expect(c.inputCoverage.missing).toContain("measured burn rate"); + const line = formatForecastSummary(c); + expect(line).toContain("Quota rate unavailable"); + expect(line).not.toContain("safe"); + }); + + test("stale source: an old rate observation publishes no date", () => { + const c = quotaForecastContract({ ...base, rate: { amountPerHour: 100, observedAt: "2026-11-09T09:00:00Z" } }); + expect(c.status).toBe("quota_rate_unavailable"); + expect(c.exhaustion).toBeNull(); + expect(c.reasons.map((r) => r.code)).toContain("stale_source"); + }); + + test("zero burn is no_recent_burn, explicitly not evidence of safety", () => { + const c = quotaForecastContract({ ...base, rate: { amountPerHour: 0, observedAt: "2026-11-09T11:55:00Z" } }); + expect(c.status).toBe("no_recent_burn"); + expect(c.exhaustion).toBeNull(); + expect(formatForecastSummary(c)).toContain("not evidence the pool is safe"); + }); + + test("missing limit/reset: the missing fields are named as structured reasons", () => { + const c = quotaForecastContract({ ...base, limitAmount: null, nextReset: null, rate: null }); + expect(c.remainingAmount).toBe(500); + expect(c.limitAmount).toBeNull(); + expect(c.inputCoverage.missing).toContain("limit"); + expect(c.inputCoverage.missing).toContain("next reset"); + }); +}); + +describe("stall risk contract (#3984 §3/§4)", () => { + test("score, threshold, contributing signals, and unknown signals are all exposed", () => { + const risk: StallRisk = { + ref: EPIC, + asOf: "2026-11-02T00:00:00Z", + modelVersion: "stall-risk/v1", + score: 50, + threshold: 60, + atRisk: false, + escalatesToNeedsYou: false, + evidenceCoverage: 0.5, + signals: [ + { code: "blocked_edge_age", contribution: 30, known: true, observedAt: "2026-10-26T00:00:00Z", detail: "blocked edge unresolved for at least 7 days (lower bound)" }, + { code: "no_meaningful_activity", contribution: 20, known: true, observedAt: "2026-11-02T00:00:00Z", detail: "no meaningful activity for at least 7 days (updatedAt proxy)" }, + { code: "queue_heartbeat", contribution: 0, known: false, observedAt: null, detail: "no queue source" }, + { code: "queue_requeues", contribution: 0, known: false, observedAt: null, detail: "no queue source" }, + ], + }; + const c = stallForecastContract(risk); + expect(c.type).toBe("stall_risk"); + expect(c.score).toBe(50); + expect(c.escalatesToNeedsYou).toBe(false); + expect(c.reasons.map((r) => r.code)).toEqual(["blocked_edge_age", "no_meaningful_activity"]); + expect(c.limitations.map((l) => l.code)).toEqual(["signal_unknown", "signal_unknown"]); + const line = formatForecastSummary(c); + expect(line).toContain("Stall risk 50 (threshold 60)"); + expect(line).not.toContain("%"); + }); + + test("subject contracts bundle the epic and stall planes for the same subject", () => { + const contracts = subjectForecastContracts(history(5, [null, null, null, null, null], W.slice(0, 5)), EPIC); + expect(contracts.map((c) => c.type).sort()).toEqual(["epic_completion", "stall_risk"]); + for (const c of contracts as ForecastContract[]) { + expect(c.contractVersion).toBe(FORECAST_CONTRACT_VERSION); + expect(c.scope.length).toBeGreaterThan(0); + expect(Array.isArray(c.reasons)).toBe(true); + expect(Array.isArray(c.limitations)).toBe(true); + } + }); +}); + +// --- Rendering: Roadmap and Projects consume the same contract ----------- + +const poolItem = ( + ref: string, + title: string, + opts: { kind?: string | null; state?: ProjectPoolItem["state"]; epicRef?: string } = {}, +): ProjectPoolItem => ({ + id: `PVTI_${ref}`, + url: "https://github.com/orgs/developing-today/projects/4", + projectUrl: "https://github.com/orgs/developing-today/projects/4", + ref: ref as ProjectPoolItem["ref"], + repo: ref.split("#")[0], + number: Number(ref.split("#")[1]), + issueUrl: `https://github.com/${ref.replace("#", "/issues/")}`, + title, + state: opts.state ?? "open", + contentKind: "issue", + status: "Todo", + area: "id", + horizon: "Quarter", + kind: opts.kind === undefined ? "Task" : opts.kind, + ...(opts.epicRef ? { epicRef: opts.epicRef as ProjectPoolItem["epicRef"] } : {}), +}); + +describe("rendering consumes the shared contract (#3984)", () => { + const closes = Array.from({ length: 20 }, (_, i) => (i < 16 ? Math.floor(i / 2) + 1 : null)); + const contracts = subjectForecastContracts(history(20, closes), EPIC); + const byRef = new Map([[EPIC, contracts] as const]); + + test("Projects pool card renders the forecast line for its epic", () => { + const pool = [poolItem(EPIC, "Identity epic", { kind: "Epic" })]; + const html = projectsBodyHtml(pool, { forecasts: byRef }); + expect(html).toContain("high confidence"); + expect(html).toContain("16 of 20 completed children"); + expect(html).toContain("Stall risk"); + }); + + test("Roadmap drill-down renders the same forecast line for the matched epic", () => { + const row: RoadmapRow = { + id: 1, + subject: "grist:doc/roadmap/1", + title: "Identity", + area: "id", + status: "In Progress", + horizon: "Quarter", + source: "grist", + notes: "", + links: [{ ref: EPIC as RoadmapRow["links"][number]["ref"], relation: "tracks" as const }], + }; + const pool = [ + poolItem(EPIC, "Identity epic", { kind: "Epic" }), + poolItem(`${REPO}#101`, "Child one", { state: "closed", epicRef: EPIC }), + ]; + const rec = reconcileRoadmap([row], pool); + const drill = buildRoadmapDrill([row], rec, pool); + const prov = { + board: "x", roadmap: "x", items: "x", comments: "x", quota: "x", usage: "x", + attention: "x", orchestration: "x", dns: "x", registry: "x", aa: "x", + } as Parameters[2]; + const html = renderRoadmap([row], new Map(), prov, "quarter", undefined, undefined, rec, drill, undefined, "", undefined, byRef); + expect(html).toContain("high confidence"); + expect(html).toContain("16 of 20 completed children"); + }); + + test("no forecasts supplied: pages render exactly as before (no forecast block)", () => { + const pool = [poolItem(EPIC, "Identity epic", { kind: "Epic" })]; + const html = projectsBodyHtml(pool, {}); + expect(html).not.toContain("forecast-line"); + }); +});