diff --git a/pm-stack/aggregator/src/forecast.ts b/pm-stack/aggregator/src/forecast.ts new file mode 100644 index 0000000000..6a4717247c --- /dev/null +++ b/pm-stack/aggregator/src/forecast.ts @@ -0,0 +1,607 @@ +// Pure forecast derivations for epic ETA bands and item stall risk +// (#3982, slice 2 of the forecasting design, +// doc/2026-11-01T21-07-00Z_design_pm-stack_forecasting.md §1, §3, §4). +// +// Everything here is a pure function over the versioned item-history +// cutoffs captured by #3981 (src/item-history.ts): no fetching, no +// store, no second history. The honesty rules of the design are the +// contract of this module: +// +// - The throughput unit is one direct native child ISSUE closure. +// Merged PRs are context, never units, so an issue and its PR can +// never double-count; a reopened child is not currently complete. +// - Only complete observed weekly buckets take part, and zero- +// completion weeks count: they are real observations, not gaps. +// Incomplete/unavailable cutoffs are excluded, never read as zero. +// - A numeric ETA requires at least 3 completed units and 4 complete +// observed weeks in scope. Below that, the result is either a +// clearly named borrowed baseline (low confidence) or +// "not_enough_history" with NO dates — never an invented date. +// - Effort stays explicit: remaining work is reported per effort +// label, unsized work is counted as unsized, and `l` (an open-ended +// floor in weights.ts) is flagged open-ended. No size is inferred. +// - Stall risk is a versioned, explainable 0-100 rule score with +// reason codes and timestamps. Blocker age is a first-observed +// LOWER BOUND (item-history.ts), labelled as such. Signals a source +// does not supply stay unknown: they contribute nothing and reduce +// evidence coverage. Score >= 60 is informational "at risk" only — +// by design (§3) it never creates a Needs-you escalation by itself. + +import type { ItemHistoryCutoff } from "./item-history.ts"; +import { blockerFirstObserved, weeklyTransitions } from "./item-history.ts"; +import type { RefKey } from "./model.ts"; + +export const FORECAST_MODEL_VERSION = "forecast/v1"; +export const STALL_MODEL_VERSION = "stall-risk/v1"; + +/** At/above this score an item is surfaced as "at risk" (§3). */ +export const STALL_AT_RISK_THRESHOLD = 60; + +const DAY_MS = 86_400_000; + +/** True when instant `a` is at or before instant `b`, compared as + * instants, not strings: the same instant can be written with or + * without fractional seconds or with a timezone offset, and string + * order disagrees with instant order across such representations + * (e.g. "2026-11-02T00:00:00Z" sorts AFTER "2026-11-02T00:00:00.000Z" + * as a string but is the same instant). Unparseable values fall back + * to string order so behaviour stays deterministic. */ +function atOrBefore(a: string, b: string): boolean { + const x = Date.parse(a); + const y = Date.parse(b); + return Number.isNaN(x) || Number.isNaN(y) ? a <= b : x <= y; +} + +/** Instant order for cutoff sorting, string order as tie-break. */ +function instantOrder(a: string, b: string): number { + const x = Date.parse(a); + const y = Date.parse(b); + if (Number.isNaN(x) || Number.isNaN(y) || x === y) return a.localeCompare(b); + return x - y; +} + +function completeCutoffs(cutoffs: ItemHistoryCutoff[]): ItemHistoryCutoff[] { + return [...cutoffs] + .filter((c) => c.coverage.complete && !c.coverage.unavailable) + .sort((a, b) => instantOrder(a.cutoffAt, b.cutoffAt)); +} + +function addDays(iso: string, days: number): string { + return new Date(Date.parse(iso) + days * DAY_MS).toISOString(); +} + +/** ETA date for a remaining-unit count at a weekly pace, or null when + * the horizon is not representable as a Date (an absurdly small pace + * would otherwise make toISOString throw a RangeError). */ +function etaDate(asOf: string, remainingUnits: number, pacePerWeek: number): string | null { + const weeks = Math.ceil(remainingUnits / pacePerWeek); + const ms = Date.parse(asOf) + weeks * 7 * DAY_MS; + if (!Number.isFinite(ms) || Math.abs(ms) > 8.64e15) return null; + return addDays(asOf, weeks * 7); +} + +function median(xs: number[]): number { + const s = [...xs].sort((a, b) => a - b); + const mid = Math.floor(s.length / 2); + return s.length % 2 === 1 ? s[mid]! : (s[mid - 1]! + s[mid]!) / 2; +} + +/** Lower quartile — the conservative (slower) pace behind the P80. */ +function lowerQuartile(xs: number[]): number { + const s = [...xs].sort((a, b) => a - b); + return s[Math.floor((s.length - 1) / 4)]!; +} + +export type ForecastConfidence = "high" | "medium" | "low" | "unavailable"; + +export type EtaStatus = "forecast" | "borrowed_baseline" | "not_enough_history" | "no_measurable_pace"; + +export interface BorrowedBaseline { + /** The comparable scope the rate is borrowed from, named verbatim + * in the result (e.g. a project or portfolio ref). Never silent. */ + scopeRef: string; + /** Completions per complete observed week in that scope. */ + weeklyCompletions: number[]; +} + +export interface EpicEtaInput { + /** The epic/project subject the ETA describes. */ + subjectRef: RefKey; + /** The full stored history (any order; incomplete cutoffs are + * filtered out here). */ + cutoffs: ItemHistoryCutoff[]; + /** Direct native children of the subject. When omitted, children + * are derived from the latest complete cutoff: issue items whose + * parentRef is the subject (epicRef is ancestor membership and + * would also match grandchildren, so it is not used). */ + childRefs?: RefKey[]; + /** Optional comparable-scope rate for the low-evidence case. */ + borrowedBaseline?: BorrowedBaseline; + /** Forecast instant; defaults to the latest complete cutoff. */ + asOf?: string; +} + +export interface EpicEta { + subjectRef: RefKey; + asOf: string; + modelVersion: string; + status: EtaStatus; + /** Scope actually used for the rate: the subject, or the named + * borrowed baseline's scope. */ + baselineSource: string; + inputWindow: { + primaryWeeks: number; + comparisonWeeks: number; + completeWeeks: number; + from: string | null; + to: string | null; + }; + inputCoverage: { + completeWeeks: number; + totalCutoffs: number; + unavailableCutoffs: number; + }; + remainingUnits: number; + completedUnits: number; + sample: { + completionsPrimary: number; + completionsComparison: number; + }; + /** Remaining work by effort label; `unsized` counts children with + * no effort label and `openEnded` counts the open-ended floor + * sizes (`l`, `xl`) — explicit, never folded into the unit count. */ + remainingEffort: { + byEffort: Record; + unsized: number; + openEnded: number; + }; + /** ISO dates, or null when no defensible date exists. */ + p50: string | null; + p80: string | null; + confidence: ForecastConfidence; + limitations: string[]; +} + +/** + * Derive the ETA band for one epic/project subject over the item + * history. Deterministic: the same cutoffs always produce the same + * result, and every number in it names its window and sample. + */ +export function deriveEpicEta(input: EpicEtaInput): EpicEta { + // Rolling-origin honesty (design \u00a75): a forecast "as of" an instant + // uses only cutoffs observed at or before that instant \u2014 later + // cutoffs are future outcomes and must not leak into scope, + // transitions, or coverage. + const scopedCutoffs = input.asOf + ? input.cutoffs.filter((c) => atOrBefore(c.cutoffAt, input.asOf!)) + : input.cutoffs; + const complete = completeCutoffs(scopedCutoffs); + const latest = complete[complete.length - 1]; + const asOf = input.asOf ?? latest?.cutoffAt ?? new Date(0).toISOString(); + const limitations: string[] = []; + + const base = { + subjectRef: input.subjectRef, + asOf, + modelVersion: FORECAST_MODEL_VERSION, + inputWindow: { + primaryWeeks: 0, + comparisonWeeks: 0, + completeWeeks: complete.length, + from: complete[0]?.cutoffAt ?? null, + to: latest?.cutoffAt ?? null, + }, + inputCoverage: { + completeWeeks: complete.length, + totalCutoffs: scopedCutoffs.length, + unavailableCutoffs: scopedCutoffs.filter((c) => c.coverage.unavailable).length, + }, + }; + + if (!latest) { + return { + ...base, + status: "not_enough_history", + baselineSource: input.subjectRef, + remainingUnits: 0, + completedUnits: 0, + sample: { completionsPrimary: 0, completionsComparison: 0 }, + remainingEffort: { byEffort: {}, unsized: 0, openEnded: 0 }, + p50: null, + p80: null, + confidence: "unavailable", + limitations: ["no complete observed cutoffs in the item history"], + }; + } + + // Scope: direct native child issues at the latest complete cutoff. + // Direct means parentRef === subject: epicRef is ANCESTOR membership + // (projects.ts walks the whole parent chain), so counting epicRef + // would count grandchildren as independent units. + const childRefs = + input.childRefs ?? + latest.items + .filter((i) => i.kind !== "pr" && i.parentRef === input.subjectRef) + .map((i) => i.ref); + const childSet = new Set(childRefs); + const children = latest.items.filter((i) => childSet.has(i.ref) && i.kind !== "pr"); + // Explicitly requested children absent from the latest complete + // cutoff are unknown, not complete: a complete cutoff establishes + // coverage of the fetched pool, not the presence of every requested + // ref. They surface as a scope limitation below and block the + // nothing-left branch. + const missingRefs = + input.childRefs === undefined ? [] : childRefs.filter((ref) => !children.some((i) => i.ref === ref)); + const completedUnits = children.filter((i) => i.state !== "open").length; + // A reopened child is open at the latest cutoff: it is remaining + // work, not a completion, whatever earlier weeks observed. + const remaining = children.filter((i) => i.state === "open"); + const remainingUnits = remaining.length; + + const byEffort: Record = {}; + let unsized = 0; + let openEnded = 0; + for (const item of remaining) { + if (item.effort === null) unsized++; + else { + byEffort[item.effort] = (byEffort[item.effort] ?? 0) + 1; + if (item.effort === "l" || item.effort === "xl") openEnded++; + } + } + if (missingRefs.length > 0) { + limitations.push( + `${missingRefs.length} explicitly requested child(ren) absent from the latest complete cutoff; state unknown: ${missingRefs.join(", ")}`, + ); + } + if (unsized > 0) limitations.push(`${unsized} remaining unit(s) are unsized; no size was inferred`); + if (openEnded > 0) { + limitations.push(`${openEnded} remaining unit(s) carry an open-ended effort floor (l/xl)`); + } + + // Throughput series restricted to this scope's children. Weeks are + // the complete observed buckets from item-history (zero weeks + // included by construction). + const weeks = weeklyTransitions(scopedCutoffs) + .map((w) => ({ + cutoffAt: w.cutoffAt, + completed: w.completedRefs.filter((r) => childSet.has(r)).length, + })) + .filter((w) => complete.some((c) => c.cutoffAt === w.cutoffAt)); + const primary = weeks.slice(-4).map((w) => w.completed); + const comparison = weeks.slice(-8).map((w) => w.completed); + const completionsPrimary = primary.reduce((a, b) => a + b, 0); + const completionsComparison = comparison.reduce((a, b) => a + b, 0); + + const result: EpicEta = { + ...base, + status: "forecast", + baselineSource: input.subjectRef, + inputWindow: { + ...base.inputWindow, + primaryWeeks: primary.length, + comparisonWeeks: comparison.length, + }, + remainingUnits, + completedUnits, + sample: { completionsPrimary, completionsComparison }, + remainingEffort: { byEffort, unsized, openEnded }, + p50: null, + p80: null, + confidence: "unavailable", + limitations, + }; + + if (remainingUnits === 0 && missingRefs.length > 0) { + // Every observed child is complete, but requested children are + // unobserved: the subject cannot be declared complete while their + // state is unknown, and no completion date is defensible. + result.status = "not_enough_history"; + limitations.push( + "explicitly requested child(ren) are unobserved; the subject is not declared complete while their state is unknown", + ); + return result; + } + + if (remainingUnits === 0 && completedUnits > 0) { + // Nothing left: the ETA is the as-of instant itself. + result.p50 = asOf; + result.p80 = asOf; + result.confidence = completionsComparison >= 3 && comparison.length >= 4 ? "medium" : "low"; + return result; + } + + const enoughLocal = completionsPrimary >= 3 && primary.length >= 4; + if (!enoughLocal && primary.length >= 4 && completionsPrimary === 0) { + // A full primary window with zero completions is a measured + // pace — of zero. That is "no measurable pace" (§1), not a + // missing sample: no date, and a borrowed rate would hide it. + result.status = "no_measurable_pace"; + limitations.push("zero completions across the 4 complete primary weeks; no date is returned"); + return result; + } + let paceSeries: number[]; + if (enoughLocal) { + paceSeries = primary; + } else if (input.borrowedBaseline && input.borrowedBaseline.weeklyCompletions.length >= 4) { + paceSeries = input.borrowedBaseline.weeklyCompletions.slice(-4); + result.status = "borrowed_baseline"; + result.baselineSource = input.borrowedBaseline.scopeRef; + result.confidence = "low"; + limitations.push( + `local evidence is below the numeric-forecast floor (3 completions / 4 complete weeks); rate borrowed from ${input.borrowedBaseline.scopeRef}`, + ); + } else { + result.status = "not_enough_history"; + limitations.push( + "fewer than 3 completions or 4 complete weeks in scope and no comparable borrowed baseline: no ETA date is defensible", + ); + return result; + } + + const paceP50 = median(paceSeries); + if (paceP50 <= 0) { + result.status = "no_measurable_pace"; + limitations.push("observed weekly pace is zero in the primary window; no date is returned"); + return result; + } + const paceP80 = lowerQuartile(paceSeries); + // Whole weeks, rounded up: a partial week is not a completion date. + result.p50 = etaDate(asOf, remainingUnits, paceP50); + if (result.p50 === null) { + limitations.push("P50 horizon exceeds the representable date range; no P50 date is returned"); + } + if (paceP80 <= 0) { + // An unmeasurable conservative pace is stated, not converted into + // a finite denominator: a zero lower-quartile pace (a single + // observed zero-completion week can produce one) makes any P80 + // date indefensible \u2014 an EPSILON pace overflows the Date range + // and throws. + result.p80 = null; + limitations.push( + "conservative (lower-quartile) weekly pace is zero in the pace window; no P80 date is defensible", + ); + } else { + result.p80 = etaDate(asOf, remainingUnits, paceP80); + if (result.p80 === null) { + limitations.push("P80 horizon exceeds the representable date range; no P80 date is returned"); + } + } + + if (result.status === "forecast") { + const comparisonRate = comparison.length > 0 ? completionsComparison / comparison.length : 0; + const primaryRate = completionsPrimary / primary.length; + const stable = + comparisonRate > 0 && Math.abs(primaryRate - comparisonRate) / comparisonRate <= 0.25; + result.confidence = + completionsComparison >= 12 && comparison.length >= 8 && stable ? "high" : "medium"; + if (!stable) limitations.push("4-week and 8-week rates differ materially; confidence capped"); + } + return result; +} + +// ------------------------------------------------------------------ +// Stall risk (§3) + +export interface QueueSignals { + /** Expected heartbeat intervals missed by the live claim. */ + missedHeartbeatIntervals?: number; + /** True when the claim's lease is near expiry without progress. */ + leaseNearExpiryWithoutProgress?: boolean; + /** Requeues/retries in the trailing 14 days. */ + requeues14d?: number; +} + +export interface StallRiskInput { + ref: RefKey; + cutoffs: ItemHistoryCutoff[]; + /** Meaningful-activity proxy: the item's `updatedAt`. The design + * is explicit that until event typing exists this is a proxy, and + * the reason code says so. Omit to leave the signal unknown. */ + updatedAt?: string | null; + /** Queue heartbeat/requeue facts, when a queue source supplies + * them for this item. Omit to leave both signals unknown. */ + queue?: QueueSignals; + /** Evaluation instant; defaults to the latest complete cutoff. */ + asOf?: string; +} + +export interface StallSignal { + code: + | "blocked_edge_age" + | "no_meaningful_activity" + | "queue_heartbeat" + | "queue_requeues"; + /** Points contributed (0 when the signal did not fire). */ + contribution: number; + /** False when no source supplied this signal: it contributed + * nothing and reduced evidence coverage. */ + known: boolean; + /** When the contributing observation was made, when it fired. */ + observedAt: string | null; + detail: string; +} + +export interface StallRisk { + ref: RefKey; + asOf: string; + modelVersion: string; + score: number; + threshold: number; + atRisk: boolean; + /** Always false: score alone never escalates (§3). A concrete + * blocker or a dead claim enters Needs-you through its own path. */ + escalatesToNeedsYou: false; + /** Fraction of the four signals a source actually supplied. */ + evidenceCoverage: number; + signals: StallSignal[]; +} + +const STALL_WEIGHTS = { + blocked_edge_age: 30, + no_meaningful_activity: 20, + queue_heartbeat: 30, + queue_requeues: 20, +} as const; + +/** Versioned, explainable stall-risk score for one item (§3). */ +export function deriveStallRisk(input: StallRiskInput): StallRisk { + // Same rolling-origin rule as deriveEpicEta: only cutoffs observed + // at or before asOf take part. + const scopedCutoffs = input.asOf + ? input.cutoffs.filter((c) => atOrBefore(c.cutoffAt, input.asOf!)) + : input.cutoffs; + const complete = completeCutoffs(scopedCutoffs); + const latest = complete[complete.length - 1]; + const asOf = input.asOf ?? latest?.cutoffAt ?? new Date(0).toISOString(); + // The blocked-edge helper measures age through the last cutoff it is + // given. Bound its history to the effective asOf: when asOf is + // omitted, scopedCutoffs can contain later, unavailable cutoffs, and + // observations from them must not age an edge inside a result dated + // at the latest complete cutoff. + const boundedCutoffs = scopedCutoffs.filter((c) => atOrBefore(c.cutoffAt, asOf)); + const signals: StallSignal[] = []; + + // Blocked edge age: lower bound from first observation of the + // current episode of each edge on the item at the latest cutoff. + const item = latest?.items.find((i) => i.ref === input.ref); + if (item && item.blockedBy.length > 0) { + let fired: StallSignal | null = null; + let resolvedBlockers = 0; + for (const blocker of item.blockedBy) { + // A blocker the latest cutoff holds as closed/merged is resolved + // (graph.ts treats it the same way), even though the raw + // blockedBy relation persists in the history. A blocker absent + // from the pool cannot be shown resolved and stays unresolved. + const blockerItem = latest.items.find((i) => i.ref === blocker); + if (blockerItem && blockerItem.state !== "open") { + resolvedBlockers++; + continue; + } + const first = blockerFirstObserved(boundedCutoffs, input.ref, blocker); + if (first && first.lowerBoundAgeDays >= 7) { + fired = { + code: "blocked_edge_age", + contribution: STALL_WEIGHTS.blocked_edge_age, + known: true, + observedAt: first.firstObservedAt, + detail: `blocked by ${blocker} for at least ${first.lowerBoundAgeDays} days (first-observed lower bound, not the native edge age)`, + }; + break; + } + } + signals.push( + fired ?? { + code: "blocked_edge_age", + contribution: 0, + known: true, + observedAt: null, + detail: + resolvedBlockers > 0 + ? "blocked edges present but every in-pool blocker is resolved at the latest complete cutoff; no out-of-pool blocker was observed unresolved for 7+ days" + : "blocked edges present but none observed unresolved for 7+ days", + }, + ); + } else if (item) { + signals.push({ + code: "blocked_edge_age", + contribution: 0, + known: true, + observedAt: null, + detail: "no blocked-by edges observed at the latest complete cutoff", + }); + } else { + signals.push({ + code: "blocked_edge_age", + contribution: 0, + known: false, + observedAt: null, + detail: "item not present in the latest complete cutoff; blocker state unknown", + }); + } + + // Meaningful activity: updatedAt is a proxy until event typing + // exists, and the detail says so (§3). + if (input.updatedAt) { + const ageDays = Math.floor((Date.parse(asOf) - Date.parse(input.updatedAt)) / DAY_MS); + signals.push({ + code: "no_meaningful_activity", + contribution: ageDays >= 7 ? STALL_WEIGHTS.no_meaningful_activity : 0, + known: true, + observedAt: input.updatedAt, + detail: + ageDays >= 7 + ? `no update for ${ageDays} days (updatedAt proxy for meaningful activity; synchronization-only updates are not distinguished yet)` + : `last update ${Math.max(0, ageDays)} day(s) ago (updatedAt proxy)`, + }); + } else { + signals.push({ + code: "no_meaningful_activity", + contribution: 0, + known: false, + observedAt: null, + detail: "no updatedAt supplied; activity signal unknown", + }); + } + + // Queue heartbeat / lease signals: known only when a queue source + // supplied them for this item. + if (input.queue && (input.queue.missedHeartbeatIntervals !== undefined || input.queue.leaseNearExpiryWithoutProgress !== undefined)) { + const missed = input.queue.missedHeartbeatIntervals ?? 0; + const nearExpiry = input.queue.leaseNearExpiryWithoutProgress === true; + signals.push({ + code: "queue_heartbeat", + contribution: missed >= 2 || nearExpiry ? STALL_WEIGHTS.queue_heartbeat : 0, + known: true, + observedAt: asOf, + detail: + missed >= 2 + ? `claim missed ${missed} expected heartbeat intervals` + : nearExpiry + ? "claim lease approaching expiry without progress" + : "claim heartbeat within expected intervals", + }); + } else { + signals.push({ + code: "queue_heartbeat", + contribution: 0, + known: false, + observedAt: null, + detail: "no queue heartbeat source for this item; signal unknown", + }); + } + + if (input.queue && input.queue.requeues14d !== undefined) { + const n = input.queue.requeues14d; + signals.push({ + code: "queue_requeues", + contribution: n >= 2 ? STALL_WEIGHTS.queue_requeues : 0, + known: true, + observedAt: asOf, + detail: `${n} requeue(s)/retries in the trailing 14 days`, + }); + } else { + signals.push({ + code: "queue_requeues", + contribution: 0, + known: false, + observedAt: null, + detail: "no queue requeue source for this item; signal unknown", + }); + } + + const score = Math.min( + 100, + signals.reduce((a, s) => a + s.contribution, 0), + ); + return { + ref: input.ref, + asOf, + modelVersion: STALL_MODEL_VERSION, + score, + threshold: STALL_AT_RISK_THRESHOLD, + atRisk: score >= STALL_AT_RISK_THRESHOLD, + escalatesToNeedsYou: false, + evidenceCoverage: signals.filter((s) => s.known).length / signals.length, + signals, + }; +} diff --git a/pm-stack/aggregator/test/forecast-3982.test.ts b/pm-stack/aggregator/test/forecast-3982.test.ts new file mode 100644 index 0000000000..9274f4c414 --- /dev/null +++ b/pm-stack/aggregator/test/forecast-3982.test.ts @@ -0,0 +1,381 @@ +import { describe, expect, test } from "bun:test"; +import { deriveEpicEta, deriveStallRisk, FORECAST_MODEL_VERSION } from "../src/forecast.ts"; +import type { ItemHistoryCutoff, ItemHistoryItem } from "../src/item-history.ts"; + +const REPO = "developing-today/code"; +const EPIC = `${REPO}#100`; + +// Mondays, weekly. +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, + }; +} + +/** Children 1..total; `closesAtWeek[i]` = week index at which child + * i+1 closes (stays closed). */ +function history(total: number, closesAtWeek: (number | null)[]): ItemHistoryCutoff[] { + return W.map((at, week) => + cutoff( + at, + Array.from({ length: total }, (_, i) => + item(i + 1, { + state: closesAtWeek[i] !== null && closesAtWeek[i]! <= week ? "closed" : "open", + }), + ), + ), + ); +} + +describe("deriveEpicEta", () => { + test("missing history: not_enough_history, no dates, unavailable confidence", () => { + const eta = deriveEpicEta({ subjectRef: EPIC, cutoffs: [] }); + expect(eta.status).toBe("not_enough_history"); + expect(eta.p50).toBeNull(); + expect(eta.p80).toBeNull(); + expect(eta.confidence).toBe("unavailable"); + expect(eta.modelVersion).toBe(FORECAST_MODEL_VERSION); + }); + + test("explicit childRefs absent from the latest cutoff are unknown, not complete", () => { + // Requested child #2 is never observed in any cutoff; requested + // child #1 is closed throughout. The epic must not be declared + // complete (no p50 = p80 = asOf) while #2's state is unknown. + const cutoffs = history(1, [0]); + const eta = deriveEpicEta({ + subjectRef: EPIC, + cutoffs, + childRefs: [`${REPO}#1`, `${REPO}#2`], + }); + expect(eta.remainingUnits).toBe(0); + expect(eta.completedUnits).toBe(1); + expect(eta.status).toBe("not_enough_history"); + expect(eta.p50).toBeNull(); + expect(eta.p80).toBeNull(); + expect(eta.limitations.join(" ")).toContain("state unknown"); + expect(eta.limitations.join(" ")).toContain(`${REPO}#2`); + // Control: with only the observed child requested, nothing-left + // still returns the as-of instant itself. + const complete = deriveEpicEta({ subjectRef: EPIC, cutoffs, childRefs: [`${REPO}#1`] }); + expect(complete.p50).toBe(complete.asOf); + expect(complete.p80).toBe(complete.asOf); + }); + + test("incomplete cutoffs are excluded, never read as zero weeks", () => { + const cutoffs = history(6, [null, null, null, null, null, null]).map((c, i) => + i % 2 === 1 ? { ...c, coverage: { ...c.coverage, complete: false, unavailable: true } } : c, + ); + const eta = deriveEpicEta({ subjectRef: EPIC, cutoffs }); + expect(eta.inputCoverage.unavailableCutoffs).toBeGreaterThan(0); + expect(eta.inputCoverage.completeWeeks).toBeLessThan(cutoffs.length); + }); + + test("steady pace over 8 weeks: forecast with P50 <= P80 and a real sample", () => { + // 2 closures per week for 8 weeks (16 units), 8 children remain. + const closes: (number | null)[] = Array.from({ length: 24 }, (_, i) => + i < 16 ? Math.floor(i / 2) + 1 : null, + ); + const eta = deriveEpicEta({ subjectRef: EPIC, cutoffs: history(24, closes) }); + expect(eta.status).toBe("forecast"); + expect(eta.completedUnits).toBe(16); + expect(eta.remainingUnits).toBe(8); + expect(eta.sample.completionsPrimary).toBe(8); + expect(eta.p50).not.toBeNull(); + expect(eta.p80).not.toBeNull(); + expect(eta.p80! >= eta.p50!).toBe(true); + expect(eta.confidence).toBe("high"); + expect(eta.baselineSource).toBe(EPIC); + }); + + test("zero pace across a full primary window: no_measurable_pace, no dates", () => { + const eta = deriveEpicEta({ + subjectRef: EPIC, + cutoffs: history(5, [null, null, null, null, null]).slice(0, 6), + }); + expect(eta.status).toBe("no_measurable_pace"); + expect(eta.p50).toBeNull(); + expect(eta.remainingUnits).toBe(5); + }); + + test("sparse sample without a baseline: not_enough_history, no dates", () => { + const closes: (number | null)[] = [3, null, null, null, null, null]; + const eta = deriveEpicEta({ subjectRef: EPIC, cutoffs: history(6, closes).slice(0, 6) }); + expect(eta.status).toBe("not_enough_history"); + expect(eta.p50).toBeNull(); + expect(eta.p80).toBeNull(); + }); + + test("sparse sample with a named baseline: borrowed_baseline, low confidence, dates present", () => { + const closes: (number | null)[] = [3, null, null, null, null, null]; + const eta = deriveEpicEta({ + subjectRef: EPIC, + cutoffs: history(6, closes).slice(0, 6), + borrowedBaseline: { scopeRef: `${REPO}#200`, weeklyCompletions: [2, 3, 2, 3] }, + }); + expect(eta.status).toBe("borrowed_baseline"); + expect(eta.baselineSource).toBe(`${REPO}#200`); + expect(eta.confidence).toBe("low"); + expect(eta.p50).not.toBeNull(); + }); + + test("a reopened child is remaining work, not a completion", () => { + const cutoffs = history(6, [null, null, null, null, null, null]); + // Child 1 closes at week 2, reopens at week 4, stays open. + for (let w = 0; w < cutoffs.length; w++) { + const it = cutoffs[w]!.items[0]!; + it.state = w >= 2 && w < 4 ? "closed" : "open"; + } + const eta = deriveEpicEta({ subjectRef: EPIC, cutoffs }); + expect(eta.completedUnits).toBe(0); + expect(eta.remainingUnits).toBe(6); + }); + + test("merged PR children never count as units", () => { + const cutoffs = history(4, [1, 2, null, null]).slice(0, 5); + for (const c of cutoffs) { + c.items.push( + item(900, { kind: "pr", state: "merged" }), + ); + } + const eta = deriveEpicEta({ subjectRef: EPIC, cutoffs }); + expect(eta.completedUnits).toBe(2); + expect(eta.remainingUnits).toBe(2); + }); + + test("zero lower-quartile pace: P50 present, P80 explicitly unmeasurable, no crash", () => { + // Primary weeks [0, 1, 1, 1]: median pace 1, lower quartile 0. + const eta = deriveEpicEta({ + subjectRef: EPIC, + cutoffs: history(5, [2, 3, 4, null, null]).slice(0, 5), + }); + expect(eta.status).toBe("forecast"); + expect(eta.sample.completionsPrimary).toBe(3); + expect(eta.p50).not.toBeNull(); + expect(eta.p80).toBeNull(); + expect(eta.limitations.join(" ")).toContain("lower-quartile"); + }); + + test("inferred scope counts direct children only, not grandchildren via epicRef", () => { + const cutoffs = [ + cutoff(W[0]!, [ + item(1), + item(2, { parentRef: `${REPO}#1`, epicRef: EPIC }), + item(3, { state: "closed" }), + ]), + ]; + const eta = deriveEpicEta({ subjectRef: EPIC, cutoffs }); + expect(eta.remainingUnits).toBe(1); + expect(eta.completedUnits).toBe(1); + }); + + test("asOf excludes later cutoffs: a closure after asOf is not yet a completion", () => { + const eta = deriveEpicEta({ + subjectRef: EPIC, + cutoffs: history(3, [4, null, null]), + asOf: W[2]!, + }); + expect(eta.asOf).toBe(W[2]!); + expect(eta.completedUnits).toBe(0); + expect(eta.remainingUnits).toBe(3); + }); + +test("asOf compares as an instant: equal instant in another representation is included", () => { + // W[8] is "2026-11-02T00:00:00Z"; asOf writes the same instant with + // fractional seconds. String order would exclude the W[8] cutoff + // ("Z" > "."), instant order includes it. + const eta = deriveEpicEta({ + subjectRef: EPIC, + cutoffs: history(3, [4, null, null]), + asOf: "2026-11-02T00:00:00.000Z", + }); + expect(eta.inputCoverage.completeWeeks).toBe(9); + expect(eta.completedUnits).toBe(1); + }); + + test("asOf compares as an instant: an offset cutoff later than asOf is excluded", () => { + // The last cutoff written with a -05:00 offset is 05:00Z — after + // asOf at 00:00Z — although its string sorts before "Z". + const cutoffs = history(3, [4, null, null]); + cutoffs[cutoffs.length - 1] = { + ...cutoffs[cutoffs.length - 1]!, + cutoffAt: "2026-11-02T00:00:00-05:00", + }; + const eta = deriveEpicEta({ + subjectRef: EPIC, + cutoffs, + asOf: "2026-11-02T00:00:00Z", + }); + expect(eta.inputCoverage.completeWeeks).toBe(8); + }); + + test("effort stays explicit: unsized and open-ended remaining work are named, not sized", () => { + const cutoffs = history(4, [null, null, null, null]).slice(0, 5); + const latest = cutoffs[cutoffs.length - 1]!; + latest.items[0]!.effort = "l"; + latest.items[1]!.effort = "s"; + const eta = deriveEpicEta({ subjectRef: EPIC, cutoffs }); + expect(eta.remainingEffort.unsized).toBe(2); + expect(eta.remainingEffort.openEnded).toBe(1); + expect(eta.remainingEffort.byEffort).toEqual({ l: 1, s: 1 }); + expect(eta.limitations.join(" ")).toContain("unsized"); + }); +}); + +describe("deriveStallRisk", () => { + const REF = `${REPO}#7`; + const BLOCKER = `${REPO}#9`; + + function blockedHistory(): ItemHistoryCutoff[] { + return [ + cutoff(W[0]!, [item(7, { blockedBy: [BLOCKER] })]), + cutoff(W[2]!, [item(7, { blockedBy: [BLOCKER] })]), + ]; + } + + test("blocked edge unresolved 14 days (lower bound): +30 with the bound labelled", () => { + const risk = deriveStallRisk({ ref: REF, cutoffs: blockedHistory(), asOf: W[2]! }); + const signal = risk.signals.find((s) => s.code === "blocked_edge_age")!; + expect(signal.contribution).toBe(30); + expect(signal.detail).toContain("lower bound"); + expect(risk.score).toBe(30); + expect(risk.atRisk).toBe(false); + }); + + test("no-activity proxy signal: +20 when updatedAt is 7+ days old", () => { + const risk = deriveStallRisk({ + ref: REF, + cutoffs: blockedHistory(), + asOf: W[2]!, + updatedAt: "2026-09-10T00:00:00Z", + }); + const signal = risk.signals.find((s) => s.code === "no_meaningful_activity")!; + expect(signal.contribution).toBe(20); + expect(signal.detail).toContain("proxy"); + }); + + test("queue heartbeat signal: +30 at two missed intervals", () => { + const risk = deriveStallRisk({ + ref: REF, + cutoffs: blockedHistory(), + asOf: W[2]!, + queue: { missedHeartbeatIntervals: 2 }, + }); + expect(risk.signals.find((s) => s.code === "queue_heartbeat")!.contribution).toBe(30); + }); + + test("queue requeue signal: +20 at two requeues in 14 days", () => { + const risk = deriveStallRisk({ + ref: REF, + cutoffs: blockedHistory(), + asOf: W[2]!, + queue: { requeues14d: 3 }, + }); + expect(risk.signals.find((s) => s.code === "queue_requeues")!.contribution).toBe(20); + }); + + test("blocked + heartbeat = 60: at risk, informational only, never escalates", () => { + const risk = deriveStallRisk({ + ref: REF, + cutoffs: blockedHistory(), + asOf: W[2]!, + queue: { missedHeartbeatIntervals: 3 }, + }); + expect(risk.score).toBe(60); + expect(risk.atRisk).toBe(true); + expect(risk.escalatesToNeedsYou).toBe(false); + }); + + test("unsupplied signals stay unknown and reduce evidence coverage", () => { + const risk = deriveStallRisk({ ref: REF, cutoffs: blockedHistory(), asOf: W[2]! }); + expect(risk.signals.find((s) => s.code === "no_meaningful_activity")!.known).toBe(false); + expect(risk.signals.find((s) => s.code === "queue_heartbeat")!.known).toBe(false); + expect(risk.signals.find((s) => s.code === "queue_requeues")!.known).toBe(false); + expect(risk.evidenceCoverage).toBe(0.25); + // Unknown signals contribute nothing. + expect(risk.score).toBe(30); + }); + + test("a blocker closed at the latest cutoff is resolved: no blocked-edge points", () => { + const cutoffs = [ + cutoff(W[0]!, [item(7, { blockedBy: [BLOCKER] }), item(9, { state: "open" })]), + cutoff(W[2]!, [item(7, { blockedBy: [BLOCKER] }), item(9, { state: "closed" })]), + ]; + const risk = deriveStallRisk({ ref: REF, cutoffs, asOf: W[2]! }); + const signal = risk.signals.find((s) => s.code === "blocked_edge_age")!; + expect(signal.contribution).toBe(0); + expect(signal.detail).toContain("resolved"); + expect(risk.score).toBe(0); + }); + + test("default asOf bounds blocker age to the latest complete cutoff", () => { + // The edge is first observed at the complete Sep 7 cutoff (W[0]); + // a later UNAVAILABLE Sep 14 cutoff (W[1]) also lists it. With no + // explicit asOf the result is dated at the latest complete cutoff + // (Sep 7), where the edge's lower-bound age is 0 days: the later + // unavailable observation must not fire blocked-edge points. + const cutoffs = [ + cutoff(W[0]!, [item(7, { blockedBy: [BLOCKER] })]), + cutoff(W[1]!, [item(7, { blockedBy: [BLOCKER] })], false), + ]; + const risk = deriveStallRisk({ ref: REF, cutoffs }); + expect(risk.asOf).toBe(W[0]!); + const signal = risk.signals.find((s) => s.code === "blocked_edge_age")!; + expect(signal.contribution).toBe(0); + expect(risk.score).toBe(0); + }); + +test("asOf compares as an instant: same instant, fractional-second representation", () => { + // W[2] is "2026-09-21T00:00:00Z"; asOf writes the same instant as + // "2026-09-21T00:00:00.000Z". String order would scope the history + // to W[0] only (blocked age 0, no points); instant order keeps + // W[2], where the lower-bound age is 14 days. + const risk = deriveStallRisk({ + ref: REF, + cutoffs: blockedHistory(), + asOf: "2026-09-21T00:00:00.000Z", + }); + expect(risk.signals.find((s) => s.code === "blocked_edge_age")!.contribution).toBe(30); + }); + + test("all signals firing caps at 100", () => { + const risk = deriveStallRisk({ + ref: REF, + cutoffs: blockedHistory(), + asOf: W[2]!, + updatedAt: "2026-09-01T00:00:00Z", + queue: { missedHeartbeatIntervals: 2, requeues14d: 5 }, + }); + expect(risk.score).toBe(100); + expect(risk.evidenceCoverage).toBe(1); + }); +});