Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 126 additions & 0 deletions pm-stack/aggregator/src/genealogy.ts
Original file line number Diff line number Diff line change
@@ -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<RefKey>([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<RefKey>([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") ??

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recognize the existing design tracking label

When a native ancestor is a design tracking issue marked with the existing design label rather than kind/design or Project Kind Design, this predicate skips it and the label-based fallback applies the same exclusion. The hierarchy design's §2 defines tracking issues using design plus design/<name>, and pm-stack/design-register-2026-11-11.md records tracking issues #9539, #9521, #9399 and #8884 on Project #4 with the plain design label. Their descendants can therefore receive “with no design yet” and no spawned-by ancestor despite a known design in the native chain. Recognize the existing tracking marker in both lookups without treating every issue carrying a design-family membership label as a tracking issue.

Useful? React with 👍 / 👎.

(() => {
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");

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include the linked roadmap item when deriving roadmap overlays

When a roadmap row's tracks link names a roadmap-item issue itself, chain contains only its parents, so this lookup skips the tracked roadmap item. For a standalone roadmap item with a release milestone, enrichRoadmapRows consequently returns releaseRef: null; if it has an overall-priority parent, that parent is treated as the project roadmap item and its blockers replace the tracked item's blockedBy edges. Include the linked item when resolving the roadmap level so rows tracking roadmap issues retain their own sequencing and release information.

Useful? React with 👍 / 👎.

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;
Comment on lines +89 to +92

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Distinguish release milestones from rolling program milestones

If the selected roadmap or priority issue carries a rolling program milestone, this condition exposes it as a release in /api/item and renders “release ” in the item header. The repository explicitly supports rolling program milestones separately from bounded releases, and milestoneKind in src/releases.ts already implements that distinction. Select a release-classified milestone rather than treating every milestone as a release; when the priority has no eligible release, also consider the roadmap item's release milestone.

Useful? React with 👍 / 👎.

const afterRefs = [...new Set((roadmapItem ?? priority ?? item).blockedBy ?? [])];
const epicPhrase = nearestEpic ? `as part of epic ${nearestEpic.title} (${nearestEpic.ref})` : "with no epic yet";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use the resolved primary parent in the genealogy sentence

When an issue has a valid primary-parent/<slug> label but no native epic ancestor, primaryEpic is successfully resolved and added to the API ancestors, yet the rendered sentence still uses only nearestEpic and says “with no epic yet”. This contradicts the supported label-based primary-parent representation and makes the HTML disagree with its JSON twin. Build the epic phrase from the resolved primary epic, falling back to the native epic.

Useful? React with 👍 / 👎.

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,
};
});
}
2 changes: 2 additions & 0 deletions pm-stack/aggregator/src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
29 changes: 28 additions & 1 deletion pm-stack/aggregator/src/projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
}
Expand Down Expand Up @@ -82,6 +82,7 @@ interface GqlEdgeNode {
interface GqlContent {
number?: number;
title?: string;
body?: string;
state?: string;
url?: string;
repository?: { nameWithOwner?: string } | null;
Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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*pm-metadata:start\s*-->([\s\S]*?)<!--\s*pm-metadata:end\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,
Expand Down Expand Up @@ -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 ||
Expand Down
4 changes: 3 additions & 1 deletion pm-stack/aggregator/src/render.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<RefKey, ItemBrief>;
/** Real ready-for-agent dispatch state for explicitly labelled linked issues. */
Expand Down Expand Up @@ -2169,7 +2171,7 @@ export function renderItem(
: "";
return layout(
title,
`<h1>${esc(title)}</h1><p class="muted">subject: <code>${esc(subject)}</code></p>${epicRollup}${svcLinks}${dispatchSection}${stripHtml(items, links)}
`<h1>${esc(title)}</h1><p class="muted">subject: <code>${esc(subject)}</code></p>${extras?.genealogySentence ? `<p class="genealogy">${esc(extras.genealogySentence)}</p>` : ""}${epicRollup}${svcLinks}${dispatchSection}${stripHtml(items, links)}
${
extras?.briefs
? briefPanelsForRefs(
Expand Down
11 changes: 8 additions & 3 deletions pm-stack/aggregator/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -3395,10 +3396,12 @@ async function handler(req: Request): Promise<Response> {
}
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,
Expand All @@ -3407,14 +3410,13 @@ async function handler(req: Request): Promise<Response> {
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,
Expand Down Expand Up @@ -4356,13 +4358,15 @@ async function handler(req: Request): Promise<Response> {
// #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) {
return json({
subject,
linkedItems: [...items.values()],
dispatchStates,
...(genealogy ? { ancestors: genealogy.ancestors, release: genealogy.release } : {}),
});
}
const extras = {
Expand All @@ -4383,6 +4387,7 @@ async function handler(req: Request): Promise<Response> {
}
: {}),
...(epicRollup ? { epicRollup } : {}),
...(genealogy ? { genealogySentence: genealogy.sentence } : {}),
briefs,
...(dispatchStates.length ? { dispatchStates } : {}),
activity: {
Expand Down
69 changes: 69 additions & 0 deletions pm-stack/aggregator/test/genealogy.test.ts
Original file line number Diff line number Diff line change
@@ -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> = {}): 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 = `<!-- pm-metadata:start -->\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<!-- pm-metadata:end -->`;
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)");
});
});