From a06bc4ac479c293089276ca79bf9268ea2e6f1c6 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 14:47:24 -0600 Subject: [PATCH 1/2] aggregator: versioned item-history capture for forecasting (#3981 slice 1) --- pm-stack/aggregator/src/item-history.ts | 288 ++++++++++++++++++ pm-stack/aggregator/test/item-history.test.ts | 177 +++++++++++ 2 files changed, 465 insertions(+) create mode 100644 pm-stack/aggregator/src/item-history.ts create mode 100644 pm-stack/aggregator/test/item-history.test.ts diff --git a/pm-stack/aggregator/src/item-history.ts b/pm-stack/aggregator/src/item-history.ts new file mode 100644 index 0000000000..c302965c50 --- /dev/null +++ b/pm-stack/aggregator/src/item-history.ts @@ -0,0 +1,288 @@ +// Versioned item-history capture for forecasting (#3981, slice 1). +// +// The forecasting design (doc/2026-11-01T21-07-00Z_design_pm-stack_ +// forecasting.md §1, §3, §5) names one prerequisite before any ETA or +// stall-risk number may be claimed: a single versioned item-history +// source that records, at each complete weekly cutoff, the observed +// item scope and state, closure/reopen transitions, project/epic +// membership, effort, and blocker edges — with source freshness and +// coverage attached, so an incomplete week is excluded rather than +// silently read as zero throughput. This module is that source: the +// record shape, the capture from the live project projection, an +// append-only JSONL store, and the pure derivations forecasting and +// #1281 flow analytics share. There is deliberately no second +// collector or store: the writer is whatever job already assembles +// the project pool (the seam is `captureItemHistory`), and readers +// consume `ItemHistoryStore`. +// +// Honesty rules baked into the shape (from the issue's acceptance): +// - A cutoff whose source was unavailable is recorded with +// `coverage.unavailable: true` and `complete: false`. Unavailable is +// a distinct state from zero: derivations skip incomplete cutoffs +// entirely instead of counting them as zero-completion weeks, while +// a complete cutoff with no transitions IS a preserved zero week. +// - Transitions are *observed* transitions between consecutive +// complete cutoffs, stamped with the observing cutoff — never an +// exact historical event time backfilled from current state. +// - A blocker edge's age is a lower bound from the first cutoff that +// observed it (`firstObservedAt`), labelled as such everywhere it +// is returned. GitHub does not publish edge event times to this +// aggregator, so nothing here pretends otherwise. +// +// Ownership/retention: the store file lives beside the other durable +// aggregator stores (default `item-history.jsonl` in the aggregator +// data directory; `ITEM_HISTORY_FILE` overrides). It is append-only; +// compaction/retention follows the usage-snapshot precedent +// (snapshots.ts): keep raw cutoffs for at least 13 months so 8-week +// windows and backtests (§5 of the design) always have their inputs. + +import { appendFile, mkdir, readFile } from "node:fs/promises"; +import { dirname, join } from "node:path"; +import type { GhState, ProjectPoolItem, RefKey } from "./model.ts"; + +export const ITEM_HISTORY_SCHEMA_VERSION = 1; + +/** One item as observed at a cutoff. */ +export interface ItemHistoryItem { + ref: RefKey; + repo: string; + number: number; + /** GitHub state at observation time ("merged" for merged PRs). */ + state: GhState; + /** Project Status single-select value; null when unset. Distinct + * from GitHub state — the two disagree sometimes, and both are + * recorded so the disagreement stays visible downstream. */ + status: string | null; + /** The `effort/*` label suffix (xs/s/m/l/xl), or null when unsized. */ + effort: string | null; + parentRef?: RefKey; + epicRef?: RefKey; + /** Refs this item was observed blocked by at the cutoff, sorted. */ + blockedBy: RefKey[]; +} + +/** Source freshness/coverage for one cutoff. */ +export interface ItemHistoryCoverage { + /** Collector/source name (e.g. "projects-pool"). */ + source: string; + /** When the source data was fetched. */ + fetchedAt: string; + /** True only when the source was available for the full window + * this cutoff closes. Incomplete cutoffs are stored (so the gap is + * visible) but excluded from every derivation. */ + complete: boolean; + /** True when the source could not be read at all. Distinct from a + * complete observation of an empty scope. */ + unavailable: boolean; +} + +/** One weekly cutoff: the full observed scope at `cutoffAt`. */ +export interface ItemHistoryCutoff { + schemaVersion: number; + cutoffAt: string; + coverage: ItemHistoryCoverage; + items: ItemHistoryItem[]; +} + +/** The effort label suffix on an item, or null when unsized. */ +export function effortOf(labels: string[] | undefined): string | null { + for (const label of labels ?? []) { + if (label.startsWith("effort/")) return label.slice("effort/".length); + } + return null; +} + +/** + * Capture one cutoff from the live project projection. Pure: the + * caller supplies the pool items it already fetched plus the + * coverage facts about that fetch, and decides when a cutoff is due + * (the coverage weekly anchor, coverage.ts, is the natural clock). + */ +export function captureItemHistory( + pool: ProjectPoolItem[], + coverage: ItemHistoryCoverage, + cutoffAt: string, +): ItemHistoryCutoff { + const items = pool + .map((item) => { + const captured: ItemHistoryItem = { + ref: item.ref, + repo: item.repo, + number: item.number, + state: item.state, + status: item.status, + effort: effortOf(item.labels), + blockedBy: [...(item.blockedBy ?? [])].sort(), + }; + if (item.parentRef) captured.parentRef = item.parentRef; + if (item.epicRef) captured.epicRef = item.epicRef; + return captured; + }) + .sort((a, b) => a.ref.localeCompare(b.ref)); + return { + schemaVersion: ITEM_HISTORY_SCHEMA_VERSION, + cutoffAt, + coverage, + items, + }; +} + +/** Structural gate for one stored cutoff line. */ +export function isItemHistoryCutoff(v: unknown): v is ItemHistoryCutoff { + if (!v || typeof v !== "object") return false; + const c = v as Record; + if (c.schemaVersion !== ITEM_HISTORY_SCHEMA_VERSION) return false; + if (typeof c.cutoffAt !== "string" || Number.isNaN(Date.parse(c.cutoffAt))) return false; + const coverage = c.coverage as Record | undefined; + if (!coverage || typeof coverage !== "object") return false; + if (typeof coverage.source !== "string" || typeof coverage.fetchedAt !== "string") return false; + if (typeof coverage.complete !== "boolean" || typeof coverage.unavailable !== "boolean") { + return false; + } + if (!Array.isArray(c.items)) return false; + return c.items.every((raw) => { + if (!raw || typeof raw !== "object") return false; + const i = raw as Record; + return ( + typeof i.ref === "string" && + typeof i.repo === "string" && + Number.isInteger(i.number) && + (i.state === "open" || i.state === "closed" || i.state === "merged") && + (typeof i.status === "string" || i.status === null) && + (typeof i.effort === "string" || i.effort === null) && + Array.isArray(i.blockedBy) && + (i.blockedBy as unknown[]).every((b) => typeof b === "string") + ); + }); +} + +const DEFAULT_FILE = "item-history.jsonl"; + +/** Where the history store lives: `ITEM_HISTORY_FILE`, else + * `item-history.jsonl` inside `dataDir` (the aggregator's durable + * directory), else the bare file name. */ +export function itemHistoryFile(dataDir?: string): string { + const override = process.env.ITEM_HISTORY_FILE; + if (override) return override; + return dataDir ? join(dataDir, DEFAULT_FILE) : DEFAULT_FILE; +} + +/** Append-only JSONL store, one cutoff per line. */ +export class ItemHistoryStore { + constructor(private readonly file: string) {} + + /** Append one cutoff. A cutoff for an already-recorded `cutoffAt` + * is not written twice — re-running a collector for the same week + * must not double-count the week. Returns false when skipped. */ + async append(cutoff: ItemHistoryCutoff): Promise { + const existing = await this.readAll(); + if (existing.some((c) => c.cutoffAt === cutoff.cutoffAt)) return false; + await mkdir(dirname(this.file), { recursive: true }); + await appendFile(this.file, JSON.stringify(cutoff) + "\n", "utf8"); + return true; + } + + /** All stored cutoffs, oldest first. Malformed lines are skipped — + * one bad line must not blind every reader to the whole history — + * but a missing file is simply an empty history. */ + async readAll(): Promise { + let text: string; + try { + text = await readFile(this.file, "utf8"); + } catch { + return []; + } + const cutoffs: ItemHistoryCutoff[] = []; + for (const line of text.split("\n")) { + if (!line.trim()) continue; + try { + const parsed: unknown = JSON.parse(line); + if (isItemHistoryCutoff(parsed)) cutoffs.push(parsed); + } catch { + // Skip the malformed line; see the doc comment above. + } + } + return cutoffs.sort((a, b) => a.cutoffAt.localeCompare(b.cutoffAt)); + } +} + +/** One week's observed transitions between two complete cutoffs. */ +export interface WeeklyTransitions { + /** The cutoff closing the week. */ + cutoffAt: string; + /** Items observed open at the previous complete cutoff and + * closed/merged at this one. */ + completedRefs: RefKey[]; + /** Items observed closed/merged at the previous complete cutoff + * and open at this one. A reopened item leaves the completed + * count until it closes again (the design's throughput unit). */ + reopenedRefs: RefKey[]; +} + +/** + * Observed transitions per complete week. Only complete cutoffs take + * part: an incomplete cutoff neither contributes a week nor breaks + * the chain — the next complete cutoff is compared against the last + * complete one, and the gap stays visible in the stored cutoffs. + * Complete weeks with no transitions appear with empty lists: a + * zero-completion week is a real observation, preserved as such. + */ +export function weeklyTransitions(cutoffs: ItemHistoryCutoff[]): WeeklyTransitions[] { + const complete = cutoffs.filter((c) => c.coverage.complete && !c.coverage.unavailable); + const weeks: WeeklyTransitions[] = []; + for (let i = 1; i < complete.length; i++) { + const before = new Map(complete[i - 1]!.items.map((item) => [item.ref, item.state])); + const completedRefs: RefKey[] = []; + const reopenedRefs: RefKey[] = []; + for (const item of complete[i]!.items) { + const was = before.get(item.ref); + if (was === "open" && item.state !== "open") completedRefs.push(item.ref); + if (was !== undefined && was !== "open" && item.state === "open") { + reopenedRefs.push(item.ref); + } + } + weeks.push({ + cutoffAt: complete[i]!.cutoffAt, + completedRefs: completedRefs.sort(), + reopenedRefs: reopenedRefs.sort(), + }); + } + return weeks; +} + +/** Completed units per complete week, in order — the throughput + * series the forecasting estimator consumes (design §1). */ +export function weeklyCompletions(cutoffs: ItemHistoryCutoff[]): { cutoffAt: string; completed: number }[] { + return weeklyTransitions(cutoffs).map((week) => ({ + cutoffAt: week.cutoffAt, + completed: week.completedRefs.length, + })); +} + +/** + * The first observation of one blocker edge: the earliest cutoff + * that recorded `blockerRef` in `ref`'s blockedBy. The returned age + * is a LOWER BOUND on the edge's true age — the edge may be older + * than the history — and is labelled as such; no exact event time is + * fabricated. Null when the edge was never observed. + */ +export function blockerFirstObserved( + cutoffs: ItemHistoryCutoff[], + ref: RefKey, + blockerRef: RefKey, +): { firstObservedAt: string; lowerBoundAgeDays: number; lowerBound: true } | null { + const ordered = [...cutoffs].sort((a, b) => a.cutoffAt.localeCompare(b.cutoffAt)); + for (const cutoff of ordered) { + const item = cutoff.items.find((i) => i.ref === ref); + if (item && item.blockedBy.includes(blockerRef)) { + const last = ordered[ordered.length - 1]!; + const ageMs = Date.parse(last.cutoffAt) - Date.parse(cutoff.cutoffAt); + return { + firstObservedAt: cutoff.cutoffAt, + lowerBoundAgeDays: Math.max(0, Math.floor(ageMs / 86_400_000)), + lowerBound: true, + }; + } + } + return null; +} diff --git a/pm-stack/aggregator/test/item-history.test.ts b/pm-stack/aggregator/test/item-history.test.ts new file mode 100644 index 0000000000..140636eb7d --- /dev/null +++ b/pm-stack/aggregator/test/item-history.test.ts @@ -0,0 +1,177 @@ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + blockerFirstObserved, + captureItemHistory, + isItemHistoryCutoff, + ItemHistoryStore, + weeklyCompletions, + weeklyTransitions, + type ItemHistoryCoverage, + type ItemHistoryCutoff, +} from "../src/item-history.ts"; +import type { ProjectPoolItem } from "../src/model.ts"; + +const REPO = "developing-today/code"; +const W1 = "2026-10-05T00:00:00Z"; +const W2 = "2026-10-12T00:00:00Z"; +const W3 = "2026-10-19T00:00:00Z"; +const W4 = "2026-10-26T00:00:00Z"; + +function coverage(partial: Partial = {}): ItemHistoryCoverage { + return { + source: "projects-pool", + fetchedAt: W1, + complete: true, + unavailable: false, + ...partial, + }; +} + +function poolItem(number: number, partial: Partial = {}): ProjectPoolItem { + return { + id: `PVTI_${number}`, + url: `https://github.com/orgs/developing-today/projects/4/views/1?pane=issue&itemId=${number}`, + projectUrl: "https://github.com/orgs/developing-today/projects/4", + ref: `${REPO}#${number}`, + repo: REPO, + number, + issueUrl: `https://github.com/${REPO}/issues/${number}`, + title: `item ${number}`, + state: "open", + contentKind: "issue", + status: null, + area: null, + horizon: null, + kind: null, + ...partial, + }; +} + +function cutoff( + cutoffAt: string, + items: ProjectPoolItem[], + cov: Partial = {}, +): ItemHistoryCutoff { + return captureItemHistory(items, coverage({ fetchedAt: cutoffAt, ...cov }), cutoffAt); +} + +describe("captureItemHistory", () => { + test("records scope, state, status, effort, membership and blocker edges", () => { + const captured = cutoff(W1, [ + poolItem(7, { + state: "open", + status: "In Progress", + labels: ["effort/m", "kind/bug"], + parentRef: `${REPO}#6`, + epicRef: `${REPO}#5`, + blockedBy: [`${REPO}#9`, `${REPO}#8`], + }), + ]); + expect(captured.schemaVersion).toBe(1); + expect(captured.items).toEqual([ + { + ref: `${REPO}#7`, + repo: REPO, + number: 7, + state: "open", + status: "In Progress", + effort: "m", + parentRef: `${REPO}#6`, + epicRef: `${REPO}#5`, + blockedBy: [`${REPO}#8`, `${REPO}#9`], + }, + ]); + expect(isItemHistoryCutoff(captured)).toBe(true); + }); + + test("membership change is visible across cutoffs", () => { + const before = cutoff(W1, [poolItem(7, { epicRef: `${REPO}#5` })]); + const after = cutoff(W2, [poolItem(7, { epicRef: `${REPO}#11` })]); + expect(before.items[0]!.epicRef).toBe(`${REPO}#5`); + expect(after.items[0]!.epicRef).toBe(`${REPO}#11`); + }); +}); + +describe("weeklyTransitions / weeklyCompletions", () => { + test("close counts once; a reopen leaves the completed count until re-closed", () => { + const cutoffs = [ + cutoff(W1, [poolItem(7), poolItem(8)]), + cutoff(W2, [poolItem(7, { state: "closed" }), poolItem(8)]), + cutoff(W3, [poolItem(7), poolItem(8)]), // #7 reopened + cutoff(W4, [poolItem(7, { state: "closed" }), poolItem(8)]), + ]; + const weeks = weeklyTransitions(cutoffs); + expect(weeks[0]).toEqual({ cutoffAt: W2, completedRefs: [`${REPO}#7`], reopenedRefs: [] }); + expect(weeks[1]).toEqual({ cutoffAt: W3, completedRefs: [], reopenedRefs: [`${REPO}#7`] }); + expect(weeks[2]).toEqual({ cutoffAt: W4, completedRefs: [`${REPO}#7`], reopenedRefs: [] }); + expect(weeklyCompletions(cutoffs).map((w) => w.completed)).toEqual([1, 0, 1]); + }); + + test("a zero-completion week is preserved, not dropped", () => { + const cutoffs = [cutoff(W1, [poolItem(7)]), cutoff(W2, [poolItem(7)]), cutoff(W3, [poolItem(7)])]; + expect(weeklyCompletions(cutoffs)).toEqual([ + { cutoffAt: W2, completed: 0 }, + { cutoffAt: W3, completed: 0 }, + ]); + }); + + test("a missing-source week is excluded, never read as zero", () => { + const cutoffs = [ + cutoff(W1, [poolItem(7)]), + cutoff(W2, [], { complete: false, unavailable: true }), + cutoff(W3, [poolItem(7, { state: "closed" })]), + ]; + // The incomplete cutoff contributes no week; W3 is compared + // against the last complete cutoff (W1), so the closure is + // counted exactly once — and the gap stays stored and visible. + expect(weeklyCompletions(cutoffs)).toEqual([{ cutoffAt: W3, completed: 1 }]); + expect(cutoffs[1]!.coverage.unavailable).toBe(true); + expect(cutoffs[1]!.items).toEqual([]); + }); +}); + +describe("blockerFirstObserved", () => { + test("age is a labelled lower bound from first observation", () => { + const cutoffs = [ + cutoff(W1, [poolItem(7)]), + cutoff(W2, [poolItem(7, { blockedBy: [`${REPO}#9`] })]), + cutoff(W4, [poolItem(7, { blockedBy: [`${REPO}#9`] })]), + ]; + expect(blockerFirstObserved(cutoffs, `${REPO}#7`, `${REPO}#9`)).toEqual({ + firstObservedAt: W2, + lowerBoundAgeDays: 14, + lowerBound: true, + }); + expect(blockerFirstObserved(cutoffs, `${REPO}#7`, `${REPO}#42`)).toBeNull(); + }); +}); + +describe("ItemHistoryStore", () => { + let dir: string | null = null; + afterEach(async () => { + if (dir) await rm(dir, { recursive: true, force: true }); + dir = null; + }); + + test("append/read round-trips, dedupes a repeated cutoff, skips bad lines", async () => { + dir = await mkdtemp(join(tmpdir(), "item-history-")); + const file = join(dir, "item-history.jsonl"); + const store = new ItemHistoryStore(file); + expect(await store.readAll()).toEqual([]); + + const first = cutoff(W1, [poolItem(7)]); + expect(await store.append(first)).toBe(true); + expect(await store.append(first)).toBe(false); + expect(await store.append(cutoff(W2, [poolItem(7, { state: "closed" })]))).toBe(true); + + const { appendFile } = await import("node:fs/promises"); + await appendFile(file, "not json\n", "utf8"); + + const all = await store.readAll(); + expect(all.map((c) => c.cutoffAt)).toEqual([W1, W2]); + expect(weeklyCompletions(all)).toEqual([{ cutoffAt: W2, completed: 1 }]); + }); +}); From 8ea49db57a5b393f860e8c8ca8820b80fd007417 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:24:55 -0600 Subject: [PATCH 2/2] aggregator: disposition Codex P2s on item-history (#3981) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three Codex findings on PR #5133, all fixed: (1) capture ProjectPoolItem.contentKind as ItemHistoryItem.kind and count only issue items as completed units — a merged/closed PR no longer counts, and an issue plus its PR cannot double-count; (2) weeklyTransitions only forms a week from two consecutive complete cutoffs — an incomplete cutoff breaks the chain, so transitions spanning a missing week are attributed to no week instead of the next complete bucket; (3) blockerFirstObserved ages the current episode — a complete cutoff observing the item without the edge resets the episode, and an edge gone at the last complete cutoff returns null. Tests: missing-source expectation corrected, new PR-units test, new episode-reset tests; bun test test/item-history.test.ts 10 pass. --- pm-stack/aggregator/src/item-history.ts | 87 ++++++++++++++----- pm-stack/aggregator/test/item-history.test.ts | 65 ++++++++++++-- 2 files changed, 122 insertions(+), 30 deletions(-) diff --git a/pm-stack/aggregator/src/item-history.ts b/pm-stack/aggregator/src/item-history.ts index c302965c50..1bda7e710e 100644 --- a/pm-stack/aggregator/src/item-history.ts +++ b/pm-stack/aggregator/src/item-history.ts @@ -24,9 +24,11 @@ // - Transitions are *observed* transitions between consecutive // complete cutoffs, stamped with the observing cutoff — never an // exact historical event time backfilled from current state. -// - A blocker edge's age is a lower bound from the first cutoff that -// observed it (`firstObservedAt`), labelled as such everywhere it -// is returned. GitHub does not publish edge event times to this +// - A blocker edge's age is a lower bound from the first cutoff of +// its current uninterrupted episode (`firstObservedAt`): a complete +// cutoff that observes the item without the edge ends the episode, +// so a re-added edge starts a new one. The bound is labelled as +// such everywhere it is returned. GitHub does not publish edge event times to this // aggregator, so nothing here pretends otherwise. // // Ownership/retention: the store file lives beside the other durable @@ -47,6 +49,12 @@ export interface ItemHistoryItem { ref: RefKey; repo: string; number: number; + /** Content kind from the project pool. The forecasting unit is + * the native child issue (design SS1): PRs are recorded — their + * state is a real observation — but never counted as completed + * units in the derivations. Absent on lines written before kind + * was recorded; such items are treated as issues. */ + kind?: GhKind; /** GitHub state at observation time ("merged" for merged PRs). */ state: GhState; /** Project Status single-select value; null when unset. Distinct @@ -109,6 +117,7 @@ export function captureItemHistory( ref: item.ref, repo: item.repo, number: item.number, + kind: item.contentKind, state: item.state, status: item.status, effort: effortOf(item.labels), @@ -147,6 +156,7 @@ export function isItemHistoryCutoff(v: unknown): v is ItemHistoryCutoff { typeof i.ref === "string" && typeof i.repo === "string" && Number.isInteger(i.number) && + (i.kind === undefined || i.kind === "issue" || i.kind === "pr") && (i.state === "open" || i.state === "closed" || i.state === "merged") && (typeof i.status === "string" || i.status === null) && (typeof i.effort === "string" || i.effort === null) && @@ -210,10 +220,10 @@ export class ItemHistoryStore { export interface WeeklyTransitions { /** The cutoff closing the week. */ cutoffAt: string; - /** Items observed open at the previous complete cutoff and + /** Items observed open at the previous bounding cutoff and * closed/merged at this one. */ completedRefs: RefKey[]; - /** Items observed closed/merged at the previous complete cutoff + /** Items observed closed/merged at the previous bounding cutoff * and open at this one. A reopened item leaves the completed * count until it closes again (the design's throughput unit). */ reopenedRefs: RefKey[]; @@ -227,14 +237,31 @@ export interface WeeklyTransitions { * Complete weeks with no transitions appear with empty lists: a * zero-completion week is a real observation, preserved as such. */ +/** + * Observed transitions per complete week. A week exists only where + * two *consecutive stored* cutoffs are both complete: an incomplete + * cutoff breaks the chain, and transitions that span it fall in an + * unknown interval attributed to no week — the next complete cutoff + * becomes a fresh baseline instead of silently absorbing the gap + * weeks' completions into its own bucket. Complete weeks with no + * transitions appear with empty lists: a zero-completion week is a + * real observation, preserved as such. Only issue items count as + * units (design SS1): a PR closing or merging is not a completed + * unit, and an issue plus its PR never double-count. + */ export function weeklyTransitions(cutoffs: ItemHistoryCutoff[]): WeeklyTransitions[] { - const complete = cutoffs.filter((c) => c.coverage.complete && !c.coverage.unavailable); + const ordered = [...cutoffs].sort((a, b) => a.cutoffAt.localeCompare(b.cutoffAt)); const weeks: WeeklyTransitions[] = []; - for (let i = 1; i < complete.length; i++) { - const before = new Map(complete[i - 1]!.items.map((item) => [item.ref, item.state])); + for (let i = 1; i < ordered.length; i++) { + const prev = ordered[i - 1]!; + const cur = ordered[i]!; + if (!prev.coverage.complete || prev.coverage.unavailable) continue; + if (!cur.coverage.complete || cur.coverage.unavailable) continue; + const before = new Map(prev.items.map((item) => [item.ref, item.state])); const completedRefs: RefKey[] = []; const reopenedRefs: RefKey[] = []; - for (const item of complete[i]!.items) { + for (const item of cur.items) { + if (item.kind === "pr") continue; const was = before.get(item.ref); if (was === "open" && item.state !== "open") completedRefs.push(item.ref); if (was !== undefined && was !== "open" && item.state === "open") { @@ -242,7 +269,7 @@ export function weeklyTransitions(cutoffs: ItemHistoryCutoff[]): WeeklyTransitio } } weeks.push({ - cutoffAt: complete[i]!.cutoffAt, + cutoffAt: cur.cutoffAt, completedRefs: completedRefs.sort(), reopenedRefs: reopenedRefs.sort(), }); @@ -260,11 +287,18 @@ export function weeklyCompletions(cutoffs: ItemHistoryCutoff[]): { cutoffAt: str } /** - * The first observation of one blocker edge: the earliest cutoff - * that recorded `blockerRef` in `ref`'s blockedBy. The returned age - * is a LOWER BOUND on the edge's true age — the edge may be older - * than the history — and is labelled as such; no exact event time is - * fabricated. Null when the edge was never observed. + * The first observation of the CURRENT episode of one blocker edge: + * the earliest cutoff of the latest uninterrupted run that recorded + * `blockerRef` in `ref`'s blockedBy. A complete cutoff that observes + * the item without the edge ends the episode, so an edge removed and + * later re-added starts a new episode — the age of the new episode + * is never backdated across the removal. (An incomplete cutoff + * establishes neither presence-to-absence nor a reset: its scope is + * partial.) The returned age is a LOWER BOUND on the current + * episode's true age — the edge may predate the episode's first + * observation — and is labelled as such; no exact event time is + * fabricated. Null when the edge has no current episode (never + * observed, or observed removed at a later complete cutoff). */ export function blockerFirstObserved( cutoffs: ItemHistoryCutoff[], @@ -272,17 +306,22 @@ export function blockerFirstObserved( blockerRef: RefKey, ): { firstObservedAt: string; lowerBoundAgeDays: number; lowerBound: true } | null { const ordered = [...cutoffs].sort((a, b) => a.cutoffAt.localeCompare(b.cutoffAt)); + let episodeStart: string | null = null; for (const cutoff of ordered) { const item = cutoff.items.find((i) => i.ref === ref); - if (item && item.blockedBy.includes(blockerRef)) { - const last = ordered[ordered.length - 1]!; - const ageMs = Date.parse(last.cutoffAt) - Date.parse(cutoff.cutoffAt); - return { - firstObservedAt: cutoff.cutoffAt, - lowerBoundAgeDays: Math.max(0, Math.floor(ageMs / 86_400_000)), - lowerBound: true, - }; + if (!item) continue; + if (item.blockedBy.includes(blockerRef)) { + if (episodeStart === null) episodeStart = cutoff.cutoffAt; + } else if (cutoff.coverage.complete && !cutoff.coverage.unavailable) { + episodeStart = null; } } - return null; + if (episodeStart === null) return null; + const last = ordered[ordered.length - 1]!; + const ageMs = Date.parse(last.cutoffAt) - Date.parse(episodeStart); + return { + firstObservedAt: episodeStart, + lowerBoundAgeDays: Math.max(0, Math.floor(ageMs / 86_400_000)), + lowerBound: true, + }; } diff --git a/pm-stack/aggregator/test/item-history.test.ts b/pm-stack/aggregator/test/item-history.test.ts index 140636eb7d..9792891af3 100644 --- a/pm-stack/aggregator/test/item-history.test.ts +++ b/pm-stack/aggregator/test/item-history.test.ts @@ -76,6 +76,7 @@ describe("captureItemHistory", () => { ref: `${REPO}#7`, repo: REPO, number: 7, + kind: "issue", state: "open", status: "In Progress", effort: "m", @@ -120,17 +121,45 @@ describe("weeklyTransitions / weeklyCompletions", () => { test("a missing-source week is excluded, never read as zero", () => { const cutoffs = [ - cutoff(W1, [poolItem(7)]), + cutoff(W1, [poolItem(7), poolItem(8)]), cutoff(W2, [], { complete: false, unavailable: true }), - cutoff(W3, [poolItem(7, { state: "closed" })]), + cutoff(W3, [poolItem(7, { state: "closed" }), poolItem(8)]), + cutoff(W4, [poolItem(7, { state: "closed" }), poolItem(8, { state: "closed" })]), ]; - // The incomplete cutoff contributes no week; W3 is compared - // against the last complete cutoff (W1), so the closure is - // counted exactly once — and the gap stays stored and visible. - expect(weeklyCompletions(cutoffs)).toEqual([{ cutoffAt: W3, completed: 1 }]); + // The incomplete cutoff breaks the chain: #7's closure spans the + // gap, so it is attributed to NO week (never to W3's bucket, and + // the gap is not read as a zero week either). Buckets resume at + // the first uninterrupted pair (W3 -> W4), where #8 closes. + expect(weeklyTransitions(cutoffs)).toEqual([ + { cutoffAt: W4, completedRefs: [`${REPO}#8`], reopenedRefs: [] }, + ]); + expect(weeklyCompletions(cutoffs)).toEqual([{ cutoffAt: W4, completed: 1 }]); expect(cutoffs[1]!.coverage.unavailable).toBe(true); expect(cutoffs[1]!.items).toEqual([]); }); + + test("PR transitions never count as completed units", () => { + const cutoffs = [ + cutoff(W1, [ + poolItem(7), + poolItem(8, { contentKind: "pr" }), + poolItem(9, { contentKind: "pr" }), + ]), + cutoff(W2, [ + poolItem(7, { state: "closed" }), + poolItem(8, { contentKind: "pr", state: "merged" }), + poolItem(9, { contentKind: "pr", state: "closed" }), + ]), + ]; + // Only the issue is a unit (design SS1): the merged PR and the + // unmerged-but-closed PR contribute nothing, and an issue plus + // its PR can never double-count. + expect(weeklyTransitions(cutoffs)).toEqual([ + { cutoffAt: W2, completedRefs: [`${REPO}#7`], reopenedRefs: [] }, + ]); + expect(cutoffs[0]!.items.find((i) => i.number === 8)!.kind).toBe("pr"); + expect(cutoffs[0]!.items.find((i) => i.number === 7)!.kind).toBe("issue"); + }); }); describe("blockerFirstObserved", () => { @@ -147,6 +176,30 @@ describe("blockerFirstObserved", () => { }); expect(blockerFirstObserved(cutoffs, `${REPO}#7`, `${REPO}#42`)).toBeNull(); }); + + test("a re-added edge starts a new episode at its re-observation", () => { + const cutoffs = [ + cutoff(W1, [poolItem(7, { blockedBy: [`${REPO}#9`] })]), + cutoff(W2, [poolItem(7)]), // complete cutoff: edge observed absent + cutoff(W3, [poolItem(7, { blockedBy: [`${REPO}#9`] })]), // re-added + cutoff(W4, [poolItem(7, { blockedBy: [`${REPO}#9`] })]), + ]; + // Age runs from the current episode's first observation (W3), + // never backdated across the W2 removal: 7 days, not 21. + expect(blockerFirstObserved(cutoffs, `${REPO}#7`, `${REPO}#9`)).toEqual({ + firstObservedAt: W3, + lowerBoundAgeDays: 7, + lowerBound: true, + }); + }); + + test("an edge removed at the last complete cutoff has no current episode", () => { + const cutoffs = [ + cutoff(W1, [poolItem(7, { blockedBy: [`${REPO}#9`] })]), + cutoff(W2, [poolItem(7)]), + ]; + expect(blockerFirstObserved(cutoffs, `${REPO}#7`, `${REPO}#9`)).toBeNull(); + }); }); describe("ItemHistoryStore", () => {