diff --git a/pm-stack/aggregator/src/genealogy.ts b/pm-stack/aggregator/src/genealogy.ts new file mode 100644 index 0000000000..f708ea73c6 --- /dev/null +++ b/pm-stack/aggregator/src/genealogy.ts @@ -0,0 +1,126 @@ +import type { ProjectPoolItem, RefKey, RoadmapRow } from "./model.ts"; + +export type GenealogyRelation = "parent" | "primary-parent" | "spawned-by" | "roadmap" | "priority"; + +export interface GenealogyAncestor { + ref: RefKey; + title: string; + kind: string | null; + relation: GenealogyRelation; +} + +export interface GenealogyRelease { + title: string; + dueOn: string | null; + ref: RefKey; +} + +export interface ItemGenealogy { + ancestors: GenealogyAncestor[]; + release: GenealogyRelease | null; + afterRefs: RefKey[]; + sentence: string; +} + +const labelTarget = (labels: string[], prefix: string): string | null => + labels.find((label) => label.startsWith(prefix))?.slice(prefix.length) ?? null; + +/** Derive the item's known genealogy using only verified pool edges and labels. */ +export function deriveGenealogy(item: ProjectPoolItem, pool: readonly ProjectPoolItem[]): ItemGenealogy { + const byRef = new Map(pool.map((entry) => [entry.ref, entry])); + const chain: ProjectPoolItem[] = []; + const seen = new Set([item.ref]); + let cursor = item.parentRef ? byRef.get(item.parentRef) : undefined; + while (cursor && !seen.has(cursor.ref)) { + chain.push(cursor); + seen.add(cursor.ref); + cursor = cursor.parentRef ? byRef.get(cursor.parentRef) : undefined; + } + + const ancestors: GenealogyAncestor[] = []; + const add = (entry: ProjectPoolItem | undefined, relation: GenealogyRelation) => { + if (entry && !ancestors.some((ancestor) => ancestor.ref === entry.ref && ancestor.relation === relation)) { + ancestors.push({ ref: entry.ref, title: entry.title, kind: entry.kind, relation }); + } + }; + for (const entry of chain) add(entry, "parent"); + const historicalParents = (item.historicalParentRefs ?? []).flatMap((ref) => { + const former = byRef.get(ref); + if (!former) return []; + add(former, "parent"); + const formerChain: ProjectPoolItem[] = [former]; + const formerSeen = new Set([item.ref, former.ref]); + let oldCursor = former.parentRef ? byRef.get(former.parentRef) : undefined; + while (oldCursor && !formerSeen.has(oldCursor.ref)) { + formerChain.push(oldCursor); + formerSeen.add(oldCursor.ref); + add(oldCursor, "parent"); + oldCursor = oldCursor.parentRef ? byRef.get(oldCursor.parentRef) : undefined; + } + return formerChain; + }); + + const nearestEpic = chain.find((entry) => entry.kind === "Epic"); + const primarySlug = labelTarget(item.labels ?? [], "primary-parent/"); + const primaryEpic = primarySlug + ? pool.find((entry) => (entry.labels ?? []).includes(`epic/${primarySlug}`) && entry.kind === "Epic") + : undefined; + add(primaryEpic ?? nearestEpic, "primary-parent"); + + const design = chain.find((entry) => (entry.labels ?? []).includes("kind/design") || entry.kind === "Design") ?? + (() => { + const designLabel = labelTarget(item.labels ?? [], "design/"); + return designLabel + ? pool.find((entry) => + (entry.labels ?? []).includes(`design/${designLabel}`) && + ((entry.labels ?? []).includes("kind/design") || entry.kind === "Design"), + ) + : undefined; + })(); + add(design, "spawned-by"); + + const roadmapItem = chain.find((entry) => (entry.labels ?? []).includes("kind/roadmap-item") || entry.kind === "Roadmap item"); + add(roadmapItem, "roadmap"); + const priority = roadmapItem + ? chain.find((entry) => entry.ref !== roadmapItem.ref && ((entry.labels ?? []).includes("kind/roadmap-item") || entry.kind === "Roadmap item")) + : undefined; + add(priority, "priority"); + + const releaseItem = priority ?? roadmapItem; + const release = releaseItem?.milestone + ? { title: releaseItem.milestone.title, dueOn: releaseItem.milestone.dueOn, ref: releaseItem.ref } + : null; + const afterRefs = [...new Set((roadmapItem ?? priority ?? item).blockedBy ?? [])]; + const epicPhrase = nearestEpic ? `as part of epic ${nearestEpic.title} (${nearestEpic.ref})` : "with no epic yet"; + const designPhrase = design ? `, spawned by design ${design.title} (${design.ref})` : ", with no design yet"; + const roadmapPhrase = roadmapItem ? `; on roadmap item ${roadmapItem.title} (${roadmapItem.ref})` : "; with no roadmap item yet"; + const priorityPhrase = priority ? `, overall priority ${priority.title} (${priority.ref})` : ""; + const releasePhrase = release ? `; release ${release.title}${release.dueOn ? ` due ${release.dueOn}` : ""}` : ""; + const historicalPhrase = historicalParents.length + ? ` Formerly part of ${historicalParents.map((former) => `${former.title} (${former.ref})`).join(" → ")}.` + : ""; + return { + ancestors, + release, + afterRefs, + sentence: `Working on ${item.title} ${epicPhrase}${designPhrase}${roadmapPhrase}${priorityPhrase}${releasePhrase}.${historicalPhrase}`, + }; +} + +/** Attach genealogy overlay fields to legacy Grist/repo roadmap rows when their links resolve. */ +export function enrichRoadmapRows(rows: readonly RoadmapRow[], pool: readonly ProjectPoolItem[]) { + const byRef = new Map(pool.map((item) => [item.ref, item])); + return rows.map((row) => { + const linked = [...row.links].sort((a, b) => Number(b.relation === "tracks") - Number(a.relation === "tracks")) + .map((link) => byRef.get(link.ref)).find((item): item is ProjectPoolItem => Boolean(item)); + const genealogy = linked ? deriveGenealogy(linked, pool) : null; + const roadmapRef = genealogy?.ancestors.find((ancestor) => ancestor.relation === "roadmap")?.ref; + const priorityRef = genealogy?.ancestors.find((ancestor) => ancestor.relation === "priority")?.ref ?? roadmapRef; + return { + ...row, + priority: priorityRef ?? null, + afterRefs: genealogy?.afterRefs ?? [], + releaseRef: genealogy?.release?.ref ?? null, + }; + }); +} diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index bab01eb076..ecb299d4eb 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -130,6 +130,8 @@ export interface ProjectPoolItem { * no epic ancestor, and when the parent chain leaves the pool (the * collector only knows Kind for items on the board). */ epicRef?: RefKey; + /** Former parent refs retained by the PM metadata record after a split. */ + historicalParentRefs?: RefKey[]; } export interface ProjectPoolEdgeDiagnostic { diff --git a/pm-stack/aggregator/src/projects.ts b/pm-stack/aggregator/src/projects.ts index 4ba5cdfe5b..359b6c5d63 100644 --- a/pm-stack/aggregator/src/projects.ts +++ b/pm-stack/aggregator/src/projects.ts @@ -51,7 +51,7 @@ export const PROJECT_QUERY = `query($id: ID!, $cursor: String) { databaseId type content { - ... on Issue { number title state url repository { nameWithOwner } updatedAt closedAt milestone { title dueOn closedAt } author { login } labels(first: 20) { nodes { name } } parent { number url repository { nameWithOwner } } blockedBy(first: 50) { nodes { number url repository { nameWithOwner } } } blocking(first: 50) { nodes { number url repository { nameWithOwner } } } } + ... on Issue { number title body state url repository { nameWithOwner } updatedAt closedAt milestone { title dueOn closedAt } author { login } labels(first: 20) { nodes { name } } parent { number url repository { nameWithOwner } } blockedBy(first: 50) { nodes { number url repository { nameWithOwner } } } blocking(first: 50) { nodes { number url repository { nameWithOwner } } } } ... on PullRequest { number title state url repository { nameWithOwner } updatedAt mergedAt closedAt milestone { title dueOn closedAt } author { login } isDraft } ... on DraftIssue { title } } @@ -82,6 +82,7 @@ interface GqlEdgeNode { interface GqlContent { number?: number; title?: string; + body?: string; state?: string; url?: string; repository?: { nameWithOwner?: string } | null; @@ -211,6 +212,9 @@ export function parseProjectItems(json: unknown, projectUrl = PROJECT_URL): Proj .map((n) => edgeRef(n, "blockedBy", edgeDiagnostics)) .filter((x): x is RefKey => x !== null) : []; + const historicalParentRefs = !isPr && typeof c.body === "string" + ? historicalParentsFromMetadata(c.body) + : []; const blocks = !isPr ? edgeNodes(c.blocking, "blocks", edgeDiagnostics) .map((n) => edgeRef(n, "blocks", edgeDiagnostics)) @@ -253,12 +257,34 @@ export function parseProjectItems(json: unknown, projectUrl = PROJECT_URL): Proj ...(parentRef ? { parentRef } : {}), ...(blockedBy.length ? { blockedBy } : {}), ...(blocks.length ? { blocks } : {}), + ...(historicalParentRefs.length ? { historicalParentRefs } : {}), ...(edgeDiagnostics.length ? { edgeDiagnostics } : {}), }); } return out; } +/** Read only explicitly historical parent links from the canonical PM metadata block. */ +export function historicalParentsFromMetadata(body: string): RefKey[] { + const block = /([\s\S]*?)/.exec(body)?.[1]; + if (!block) return []; + const json = /```json\s*([\s\S]*?)```/i.exec(block)?.[1]; + if (!json) return []; + try { + const metadata: unknown = JSON.parse(json); + if (!isRecord(metadata) || !Array.isArray(metadata.links)) return []; + return [...new Set(metadata.links.flatMap((link) => { + if (!isRecord(link) || link.relation !== "parent" || link.status !== "historical" || !isRecord(link.target)) return []; + const target = link.target; + if (typeof target.repo !== "string" || !Number.isSafeInteger(target.number) || (target.number as number) <= 0) return []; + const ref = refKey({ repo: target.repo, number: target.number as number }); + return isValidRef(ref) ? [ref] : []; + }))]; + } catch { + return []; + } +} + /** Resolve epic membership over a fully parsed pool (#2399): every * non-epic item whose sub-issue parent chain (within this pool) reaches * a Kind="Epic" item gains epicRef naming that epic. Epics themselves, @@ -603,6 +629,7 @@ export function isProjectPoolItem(v: unknown): v is ProjectPoolItem { (p.state === "open" || p.state === "closed" || p.state === "merged") && (p.parentRef === undefined || isValidRef(p.parentRef)) && (p.epicRef === undefined || isValidRef(p.epicRef)) && + (p.historicalParentRefs === undefined || (Array.isArray(p.historicalParentRefs) && p.historicalParentRefs.every(isValidRef))) && (p.blockedBy === undefined || (Array.isArray(p.blockedBy) && p.blockedBy.every(isValidRef))) && (p.blocks === undefined || (Array.isArray(p.blocks) && p.blocks.every(isValidRef))) && (p.edgeDiagnostics === undefined || diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 7027c7cb5b..ffabecd385 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -2031,6 +2031,8 @@ export interface ItemExtras { serviceLinks?: ItemServiceLink[]; /** Present when this item's Project-pool entry is an epic. */ epicRollup?: EpicRollup; + /** Honest chain summary derived from the live Project pool. */ + genealogySentence?: string; /** Project-pool briefs for linked refs (#1279). */ briefs?: Map; /** Real ready-for-agent dispatch state for explicitly labelled linked issues. */ @@ -2169,7 +2171,7 @@ export function renderItem( : ""; return layout( title, - `

${esc(title)}

subject: ${esc(subject)}

${epicRollup}${svcLinks}${dispatchSection}${stripHtml(items, links)} + `

${esc(title)}

subject: ${esc(subject)}

${extras?.genealogySentence ? `

${esc(extras.genealogySentence)}

` : ""}${epicRollup}${svcLinks}${dispatchSection}${stripHtml(items, links)} ${ extras?.briefs ? briefPanelsForRefs( diff --git a/pm-stack/aggregator/src/server.ts b/pm-stack/aggregator/src/server.ts index 7378114db7..09016e2329 100644 --- a/pm-stack/aggregator/src/server.ts +++ b/pm-stack/aggregator/src/server.ts @@ -142,6 +142,7 @@ import { SpendRollupStore } from "./spend-rollups.ts"; import { buildSpendCards, type SpendCardsView } from "./spend-cards.ts"; import { buildProgramData, programRefs } from "./program.ts"; import { buildReleaseSnapshots } from "./releases.ts"; +import { deriveGenealogy, enrichRoadmapRows } from "./genealogy.ts"; import { PROJECT_CONFIGS, allProjectRefs, @@ -3395,10 +3396,12 @@ async function handler(req: Request): Promise { } if (path === "/api/roadmap.json") { const { rows, items, reconciliation } = await roadmapContext(); + const pool = await source.projects().catch(() => [] as ProjectPoolItem[]); + const genealogyRows = enrichRoadmapRows(rows, pool); const resolved = await resolveView(url); if (!resolved) { const annotatedRows = await Promise.all( - rows.map(async (row) => ({ ...row, annotations: await roadmapAnnotationsStore.forObject(row.subject) })), + genealogyRows.map(async (row) => ({ ...row, annotations: await roadmapAnnotationsStore.forObject(row.subject) })), ); return json({ rows: annotatedRows, @@ -3407,14 +3410,13 @@ async function handler(req: Request): Promise { annotationAliases: await roadmapAnnotationsStore.aliasEntries(), }); } - const pool = await source.projects().catch(() => [] as ProjectPoolItem[]); const poolByRef = new Map(pool.map((p) => [p.ref, p])); // #8723: the same rule as the HTML twin -- items linked from a // kept row ship even when they fail the view themselves. const { rows: keptRows, items: keptItemMap } = filterRoadmapForView(rows, items, poolByRef, resolved.filters); const keptItems = [...keptItemMap.values()]; const annotatedKeptRows = await Promise.all( - keptRows.map(async (row) => ({ ...row, annotations: await roadmapAnnotationsStore.forObject(row.subject) })), + enrichRoadmapRows(keptRows, pool).map(async (row) => ({ ...row, annotations: await roadmapAnnotationsStore.forObject(row.subject) })), ); return json({ rows: annotatedKeptRows, @@ -4356,6 +4358,7 @@ async function handler(req: Request): Promise { // #1154: when one of the item's refs is in the Project pool, the // item page carries the status-request control for that pool item. const pooled = pool.find((p) => refs.includes(p.ref)); + const genealogy = pooled ? deriveGenealogy(pooled, pool) : null; const epicRollup = pooled?.kind === "Epic" ? buildEpicRollups(pool).get(pooled.ref) : undefined; const dispatchStates = await readyAgentDispatchStates(items); if (itemJsonMatch) { @@ -4363,6 +4366,7 @@ async function handler(req: Request): Promise { subject, linkedItems: [...items.values()], dispatchStates, + ...(genealogy ? { ancestors: genealogy.ancestors, release: genealogy.release } : {}), }); } const extras = { @@ -4383,6 +4387,7 @@ async function handler(req: Request): Promise { } : {}), ...(epicRollup ? { epicRollup } : {}), + ...(genealogy ? { genealogySentence: genealogy.sentence } : {}), briefs, ...(dispatchStates.length ? { dispatchStates } : {}), activity: { diff --git a/pm-stack/aggregator/test/genealogy.test.ts b/pm-stack/aggregator/test/genealogy.test.ts new file mode 100644 index 0000000000..24dd2a4c28 --- /dev/null +++ b/pm-stack/aggregator/test/genealogy.test.ts @@ -0,0 +1,69 @@ +import { describe, expect, test } from "bun:test"; +import { deriveGenealogy, enrichRoadmapRows } from "../src/genealogy.ts"; +import { historicalParentsFromMetadata } from "../src/projects.ts"; +import type { ProjectPoolItem, RefKey, RoadmapRow } from "../src/model.ts"; + +const ref = (n: number) => `developing-today/code#${n}` as RefKey; +function item(n: number, partial: Partial = {}): ProjectPoolItem { + return { + id: `PVTI_${n}`, url: "https://example.test/board", projectUrl: "https://example.test/board", + ref: ref(n), repo: "developing-today/code", number: n, + issueUrl: `https://github.com/developing-today/code/issues/${n}`, title: `Item ${n}`, + state: "open", contentKind: "issue", status: null, area: null, horizon: null, kind: null, + ...partial, + }; +} + +describe("genealogy read model", () => { + test("derives the verified parent, epic, roadmap, priority, release and blocker chain", () => { + const pool = [ + item(1, { title: "Overall priority", kind: "Roadmap item", labels: ["kind/roadmap-item"], milestone: { title: "Release 1", dueOn: "2026-12-01", closedAt: null } }), + item(2, { title: "Project roadmap", kind: "Roadmap item", labels: ["kind/roadmap-item"], parentRef: ref(1), blockedBy: [ref(9)] }), + item(3, { title: "Design", kind: "Design", labels: ["kind/design", "design/crate-split"], parentRef: ref(2) }), + item(4, { title: "Epic", kind: "Epic", labels: ["epic/crate-split"], parentRef: ref(3) }), + item(5, { title: "Task", parentRef: ref(4), labels: ["design/crate-split"] }), + ]; + const result = deriveGenealogy(pool[4]!, pool); + expect(result.ancestors.map(({ ref: r, relation }) => [r, relation])).toEqual([ + [ref(4), "parent"], [ref(3), "parent"], [ref(2), "parent"], [ref(1), "parent"], + [ref(4), "primary-parent"], [ref(3), "spawned-by"], [ref(2), "roadmap"], [ref(1), "priority"], + ]); + expect(result.release).toEqual({ title: "Release 1", dueOn: "2026-12-01", ref: ref(1) }); + expect(result.afterRefs).toEqual([ref(9)]); + expect(result.sentence).toContain("Working on Task as part of epic Epic"); + expect(result.sentence).toContain("release Release 1 due 2026-12-01"); + }); + + test("renders chain breaks honestly and enriches roadmap rows with known overlay refs", () => { + const lone = item(7, { title: "Orphan" }); + const result = deriveGenealogy(lone, [lone]); + expect(result.sentence).toContain("no epic yet"); + expect(result.sentence).toContain("no roadmap item yet"); + const row = { id: 1, subject: "grist:x/y/1", title: "Roadmap", area: "ID", status: "Now", horizon: "Now", source: "test", notes: "", links: [{ ref: ref(7), relation: "tracks" }] } satisfies RoadmapRow; + expect(enrichRoadmapRows([row], [lone])[0]).toMatchObject({ priority: null, afterRefs: [], releaseRef: null }); + }); + + test("reconstructs the design's crate-split worked chain from its real refs", () => { + const pool = [ + item(2056, { title: "ID program", kind: "Epic", labels: ["epic/id-program"] }), + item(3195, { title: "Crate split design", kind: "Design", labels: ["kind/design", "design/id-crate-split"], parentRef: ref(2056) }), + item(3447, { title: "Crate split epic", kind: "Epic", labels: ["epic/id-crate-split", "design/id-crate-split"], parentRef: ref(3195) }), + item(4403, { title: "First crate-split step", parentRef: ref(3447), labels: ["design/id-crate-split"] }), + ]; + const result = deriveGenealogy(pool[3]!, pool); + expect(result.ancestors.map((ancestor) => ancestor.ref)).toContain(ref(3195)); + expect(result.ancestors.map((ancestor) => ancestor.ref)).toContain(ref(3447)); + expect(result.ancestors.map((ancestor) => ancestor.ref)).toContain(ref(2056)); + expect(result.sentence).toContain("Crate split epic"); + expect(result.sentence).not.toContain("Formerly part of"); + }); + + test("renders a historical split parent only when canonical metadata marks it historical", () => { + const body = `\n\`\`\`json\n{"pm_meta":1,"links":[{"target":{"repo":"developing-today/code","number":99},"relation":"parent","status":"historical","since":"2026-11-02","until":"2026-11-12","reason":"split"},{"target":{"repo":"developing-today/code","number":98},"relation":"parent","status":"removed"}]}\n\`\`\`\n`; + const refs = historicalParentsFromMetadata(body); + expect(refs).toEqual([ref(99)]); + const former = item(99, { title: "Former epic" }); + const current = item(100, { title: "Split task", historicalParentRefs: refs }); + expect(deriveGenealogy(current, [current, former]).sentence).toContain("Formerly part of Former epic (developing-today/code#99)"); + }); +});