diff --git a/pm-stack/aggregator/scripts/metadata-sweeper.ts b/pm-stack/aggregator/scripts/metadata-sweeper.ts index bfb074863..f600661a3 100644 --- a/pm-stack/aggregator/scripts/metadata-sweeper.ts +++ b/pm-stack/aggregator/scripts/metadata-sweeper.ts @@ -38,11 +38,15 @@ import { join } from "node:path"; import { Database } from "bun:sqlite"; import { buildTriagePacket, + collectPrimaryParentViolations, + itemRefKey, openMetadataStore, + primaryParentLabels, runMetadataCheck, storeOutcome, type EpicSlugMap, type IngestionItem, + type PrimaryParentViolation, } from "../src/metadata-ingestion.ts"; const USAGE = @@ -321,9 +325,43 @@ interface SweepCounts { writtenBack: number; needsTriage: number; forwarded: number; + primaryParentViolations: number; errors: number; } +/** Ancestor chain of a native parent, as `repo#number` keys, for the + * primary-parent ancestor rule (design §3). Returns null when the chain + * could not be read: an unreadable chain never manufactures a finding. */ +async function fetchAncestorRefs( + repo: string, + parent: { repo: string; number: number }, +): Promise | null> { + const refs = new Set(); + let cursor = { repo: parent.repo, number: parent.number }; + try { + // GitHub's hierarchy is shallow in practice; 10 bounds a cycle or a + // pathological chain without silently truncating a realistic one. + for (let depth = 0; depth < 10; depth++) { + refs.add(itemRefKey(cursor)); + const stdout = await runFleet([ + "gh", + "api", + `repos/${cursor.repo}/issues/${cursor.number}/parent`, + "--jq", + "{number: .number, repo_url: .repository_url}", + ]); + const parsed = JSON.parse(stdout) as { number?: unknown; repo_url?: unknown }; + if (!Number.isSafeInteger(parsed.number) || typeof parsed.repo_url !== "string") break; + const match = /\/repos\/([^/]+\/[^/]+)$/.exec(parsed.repo_url); + if (!match?.[1]) break; + cursor = { repo: match[1], number: parsed.number as number }; + } + return refs; + } catch { + return null; + } +} + async function fetchOne(repo: string, kind: "issue" | "pr", number: number): Promise { const command = kind === "issue" ? "issue" : "pr"; const stdout = await runFleet([ @@ -346,7 +384,7 @@ async function main(): Promise { const db = openMetadataStore(options.dryRun ? ":memory:" : options.dbPath, (path) => new Database(path)); try { const scratch = await mkdtemp(join(tmpdir(), "metadata-sweeper-")); - const summary: Record = {}; + const summary: Record = {}; try { for (const repo of options.repos) { const counts: SweepCounts = { @@ -356,8 +394,10 @@ async function main(): Promise { writtenBack: 0, needsTriage: 0, forwarded: 0, + primaryParentViolations: 0, errors: 0, }; + const violations: PrimaryParentViolation[] = []; try { const [issues, prs] = await Promise.all([ listItems(repo, "issue", options.limit), @@ -397,6 +437,7 @@ async function main(): Promise { for (const item of items) { counts.scanned++; try { + let checked = item; let outcome = runMetadataCheck(item, { epicSlugs, ingestedBy: "metadata-sweeper" }); // Native parent is authoritative (see resolveAscertainedParent): // consult it before finalizing any ascertained outcome, not @@ -409,8 +450,9 @@ async function main(): Promise { if (item.kind === "issue" && !item.nativeParent && outcome.kind !== "current") { const parent = await fetchNativeParent(repo, item.number); if (parent) { + checked = { ...item, nativeParent: parent }; outcome = runMetadataCheck( - { ...item, nativeParent: parent }, + checked, { epicSlugs, ingestedBy: "metadata-sweeper" }, ); } else if (parent === undefined) { @@ -421,6 +463,24 @@ async function main(): Promise { continue; } } + + // Primary-parent convention (design §3): validate and report + // violations in the audit output, never resolve them here. + let ancestorRefs: Set | undefined; + if (checked.kind === "issue" && checked.nativeParent && primaryParentLabels(checked.labels).length > 0) { + const chain = await fetchAncestorRefs(repo, checked.nativeParent); + if (chain === null) { + console.error( + `metadata-sweeper: ${repo}#${checked.number}: ancestor chain unread; ancestor rule not checked`, + ); + } else { + ancestorRefs = chain; + } + } + for (const violation of collectPrimaryParentViolations(checked, epicSlugs, ancestorRefs)) { + counts.primaryParentViolations++; + violations.push(violation); + } if (outcome.kind === "needs-triage") { counts.needsTriage++; if (options.forwardTriage && !options.dryRun) { @@ -476,7 +536,7 @@ async function main(): Promise { console.error(`metadata-sweeper: repo ${repo}: ${(error as Error).message}`); } const row = db.query("SELECT COUNT(*) AS count FROM pm_metadata_items").get() as { count: number }; - summary[repo] = { ...counts, dbRows: Number(row.count) }; + summary[repo] = { ...counts, dbRows: Number(row.count), violations }; } } finally { await rm(scratch, { recursive: true, force: true }); diff --git a/pm-stack/aggregator/scripts/sync-primary-parent-labels.ts b/pm-stack/aggregator/scripts/sync-primary-parent-labels.ts new file mode 100644 index 000000000..7ea40033d --- /dev/null +++ b/pm-stack/aggregator/scripts/sync-primary-parent-labels.ts @@ -0,0 +1,180 @@ +#!/usr/bin/env bun +// Create the `primary-parent/` label family from the current +// `epic/` family (design §3 of +// doc/2026-11-12T22-50-00Z_design_pm-board-hierarchy-genealogy). +// +// The label family is sparse on purpose: a label exists so the primary +// parent can be marked when the native sub-issue slot cannot carry it, so +// the registry mirrors the epics that exist today. Labels are the only +// primary-parent form queryable in GitHub, so they must exist before any +// backfill can apply them. +// +// Idempotent: existing primary-parent labels are reported and left alone, +// never re-coloured or re-described. `--dry-run` performs the read and +// prints what it would create without writing. +// +// Argument contract (#3352): the whole command line is declared here and +// parsed strictly before any subprocess, network, or write. Unknown flags, +// stray positionals, and `--opt=value` (vs `--opt value`) are usage +// errors (exit 2). `--help` prints this usage and exits 0. +// +// Usage: +// bun run scripts/sync-primary-parent-labels.ts --repo +// [--dry-run] [--help] +// Env: FLEET_BIN (default `fleet`). +import { execFile } from "node:child_process"; + +const USAGE = + "sync-primary-parent-labels: usage: bun run scripts/sync-primary-parent-labels.ts " + + "--repo [--dry-run] [--help]"; + +interface Options { + repo: string; + dryRun: boolean; +} + +function usageError(message: string): never { + console.error(`sync-primary-parent-labels: ${message}\n${USAGE}`); + process.exit(2); +} + +function parseArgs(argv: string[]): Options { + let repo: string | null = null; + let dryRun = false; + for (let i = 0; i < argv.length; i++) { + const arg = argv[i] as string; + if (arg.includes("=") && arg.startsWith("--")) usageError(`use '--opt value', not '${arg}'`); + switch (arg) { + case "--repo": { + const value = argv[i + 1]; + if (value === undefined || value.trim() === "" || value.startsWith("-")) { + usageError("--repo requires a non-empty value"); + } + repo = value.trim(); + i++; + break; + } + case "--dry-run": + dryRun = true; + break; + case "--help": + console.log(USAGE); + process.exit(0); + break; + default: + usageError(`unknown argument '${arg}'`); + break; + } + } + if (repo === null) usageError("--repo is required"); + if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) usageError(`--repo must be (got ${JSON.stringify(repo)})`); + return { repo, dryRun }; +} + +const FLEET_BIN = process.env.FLEET_BIN ?? "fleet"; + +function runFleet(args: string[]): string { + const result = Bun.spawnSync([FLEET_BIN, ...args], { stdout: "pipe", stderr: "pipe" }); + if (result.exitCode !== 0) { + const stderr = new TextDecoder().decode(result.stderr).trim(); + throw new Error(`fleet ${args.slice(0, 2).join(" ")} failed: ${stderr || `exit ${result.exitCode}`}`); + } + return new TextDecoder().decode(result.stdout); +} + +interface GhLabel { + name?: string; + color?: string; +} + +/** GitHub caps label names at 50 characters; `primary-parent/` is 16, so a + * 34-character slug is the longest that fits. */ +const LABEL_NAME_MAX = 50; +const PRIMARY_PARENT_PREFIX = "primary-parent/"; + +export interface LabelPlan { + slug: string; + name: string; + color: string; + description: string; +} + +export function planPrimaryParentLabels(labels: GhLabel[]): { + plan: LabelPlan[]; + existing: string[]; + skippedTooLong: string[]; +} { + const names = labels.map((label) => label.name ?? "").filter(Boolean); + const existing = new Set(names.filter((name) => name.startsWith(PRIMARY_PARENT_PREFIX))); + const plan: LabelPlan[] = []; + const skippedTooLong: string[] = []; + const taken = new Set(names); + for (const label of labels) { + const name = label.name ?? ""; + if (!name.startsWith("epic/")) continue; + const slug = name.slice("epic/".length).trim(); + if (!slug) continue; + const target = `${PRIMARY_PARENT_PREFIX}${slug}`; + if (target.length > LABEL_NAME_MAX) { + skippedTooLong.push(target); + continue; + } + if (existing.has(target) || taken.has(target)) continue; + plan.push({ + slug, + name: target, + color: (label.color ?? "").replace(/^#/, "") || "5319e7", + description: `Primary parent epic ${slug} (design §3)`, + }); + taken.add(target); + } + return { plan, existing: [...existing].sort(), skippedTooLong }; +} + +function main(): void { + const options = parseArgs(process.argv.slice(2)); + const labels = JSON.parse(runFleet(["gh", "label", "list", "--repo", options.repo, "--limit", "500", "--json", "name,color"])) as GhLabel[]; + const { plan, existing, skippedTooLong } = planPrimaryParentLabels(labels); + const created: string[] = []; + const failures: { name: string; error: string }[] = []; + for (const entry of plan) { + if (options.dryRun) { + created.push(entry.name); + continue; + } + try { + runFleet([ + "gh", + "label", + "create", + entry.name, + "--repo", + options.repo, + "--color", + entry.color, + "--description", + entry.description, + ]); + created.push(entry.name); + } catch (error) { + failures.push({ name: entry.name, error: (error as Error).message }); + } + } + console.log( + JSON.stringify( + { + repo: options.repo, + dryRun: options.dryRun, + existingPrimaryParentLabels: existing.length, + created: created.sort(), + failed: failures, + skippedTooLong, + }, + null, + 2, + ), + ); + if (failures.length > 0) process.exit(1); +} + +if (import.meta.main) main(); diff --git a/pm-stack/aggregator/src/metadata-ingestion.ts b/pm-stack/aggregator/src/metadata-ingestion.ts index cd7ddf4d5..31e80194c 100644 --- a/pm-stack/aggregator/src/metadata-ingestion.ts +++ b/pm-stack/aggregator/src/metadata-ingestion.ts @@ -199,6 +199,117 @@ function toRecord(item: IngestionItem, parsed: ParsedPmMetadata): PmMetadataReco }; } +/** Canonical `repo#number` key for cross-repo ancestor comparisons. */ +export function itemRefKey(ref: { repo: string; number: number }): string { + return `${ref.repo.toLowerCase()}#${ref.number}`; +} + +/** `primary-parent/` labels carried by an item, in label order. */ +export function primaryParentLabels(labels: string[]): string[] { + return labels.filter((label) => label.startsWith("primary-parent/")); +} + +export type PrimaryParentViolationKind = + /** More than one `primary-parent/*` label names a parent. */ + | "multiple-primary-parent-labels" + /** The label and the native sub-issue parent name different parents, and + * the label is not an ancestor of the native parent (program-level label). */ + | "label-native-disagreement" + /** A `primary-parent/` label whose slug resolves to no epic. */ + | "unresolved-primary-parent-label"; + +export interface PrimaryParentViolation { + kind: PrimaryParentViolationKind; + /** Human-readable finding, as it should appear in audit output. */ + message: string; + item: { repo: string; number: number; kind: "issue" | "pr" }; + labels: string[]; + labelParents: ResolvedParent[]; + nativeParent: ResolvedParent | null; +} + +/** + * Collector-side validation of the primary-parent convention (design §3): + * at most one `primary-parent/` per issue, and when a native + * sub-issue parent exists the label must either agree with it or name one + * of its ancestors (the program-level parent). + * + * `ancestorRefs` is the native parent's ancestor chain as + * {@link itemRefKey} values. Pass it when known; pass `undefined` when the + * chain could not be read, in which case only direct agreement is checked + * (an unreadable chain must not manufacture a disagreement finding). + * + * This never resolves a violation: it reports it, exactly as the design + * requires. Resolution stays a human/reconcile decision. + */ +export function collectPrimaryParentViolations( + item: IngestionItem, + epicSlugs: EpicSlugMap, + ancestorRefs?: ReadonlySet, +): PrimaryParentViolation[] { + const labels = primaryParentLabels(item.labels); + if (labels.length === 0) return []; + const violations: PrimaryParentViolation[] = []; + const base = { + item: { repo: item.repo, number: item.number, kind: item.kind }, + labels, + }; + + const unresolved = labels.filter((label) => !epicSlugs.has(label.slice("primary-parent/".length).trim().toLowerCase())); + if (unresolved.length > 0) { + violations.push({ + ...base, + kind: "unresolved-primary-parent-label", + message: `primary-parent label(s) name no known epic: ${unresolved.join(", ")}`, + labelParents: [], + nativeParent: item.nativeParent ?? null, + }); + } + + const labelParents: ResolvedParent[] = []; + for (const label of labels) { + const slug = label.slice("primary-parent/".length).trim().toLowerCase(); + const epic = epicSlugs.get(slug); + if (!epic) continue; + if (!labelParents.some((parent) => parent.repo === epic.repo && parent.number === epic.number)) { + labelParents.push({ repo: epic.repo, number: epic.number, kind: "epic" }); + } + } + + const distinct = new Set(labelParents.map((parent) => itemRefKey(parent))); + if (labels.length > 1) { + violations.push({ + ...base, + kind: "multiple-primary-parent-labels", + message: + distinct.size > 1 + ? `${labels.length} primary-parent labels name ${distinct.size} distinct parents (${[...distinct].join(", ")})` + : `${labels.length} primary-parent labels present; at most one is allowed`, + labelParents, + nativeParent: item.nativeParent ?? null, + }); + } + + const nativeParent = item.nativeParent ?? null; + if (nativeParent && labelParents.length > 0 && ancestorRefs !== undefined) { + const agrees = labelParents.some((parent) => itemRefKey(parent) === itemRefKey(nativeParent)); + const ancestorAgrees = labelParents.some((parent) => ancestorRefs.has(itemRefKey(parent))); + if (!agrees && !ancestorAgrees) { + violations.push({ + ...base, + kind: "label-native-disagreement", + message: + `primary-parent label names ${labelParents.map((parent) => itemRefKey(parent)).join(", ")} but the native parent is ` + + `${itemRefKey(nativeParent)} and the label is not one of its ancestors`, + labelParents, + nativeParent, + }); + } + } + + return violations; +} + function triageEvidence( item: IngestionItem, reasons: string[], diff --git a/pm-stack/aggregator/test/primary-parent-validation.test.ts b/pm-stack/aggregator/test/primary-parent-validation.test.ts new file mode 100644 index 000000000..74dcf48e0 --- /dev/null +++ b/pm-stack/aggregator/test/primary-parent-validation.test.ts @@ -0,0 +1,170 @@ +import { describe, expect, test } from "bun:test"; +import { + collectPrimaryParentViolations, + itemRefKey, + primaryParentLabels, + type EpicSlugMap, + type IngestionItem, +} from "../src/metadata-ingestion.ts"; +import { planPrimaryParentLabels } from "../scripts/sync-primary-parent-labels.ts"; + +// Oracle for these tests: the invariants in design §3 of +// doc/2026-11-12T22-50-00Z_design_pm-board-hierarchy-genealogy/note.md — +// at most one primary-parent/* per issue, and label/native agreement or the +// label naming an ancestor of the native parent; violations are reported, +// never resolved. + +const EPICS: EpicSlugMap = new Map([ + ["id-crate-split", { repo: "developing-today/code", number: 3447 }], + ["id-program", { repo: "developing-today/code", number: 9060 }], + ["pm-stack", { repo: "developing-today/code", number: 8983 }], +]); + +function item(overrides: Partial = {}): IngestionItem { + return { + repo: "developing-today/code", + number: 9999, + kind: "issue", + title: "A descendant", + body: "", + labels: [], + state: "OPEN", + author: "someone", + createdAt: "2026-11-20T00:00:00Z", + updatedAt: "2026-11-21T00:00:00Z", + ...overrides, + }; +} + +const ref = (number: number): string => itemRefKey({ repo: "developing-today/code", number }); + +describe("primaryParentLabels", () => { + test("selects only the primary-parent family", () => { + expect(primaryParentLabels(["epic/id-program", "primary-parent/id-program", "kind/feature"])).toEqual([ + "primary-parent/id-program", + ]); + expect(primaryParentLabels(["epic/id-program"])).toEqual([]); + }); +}); + +describe("collectPrimaryParentViolations (§3 invariants)", () => { + test("no labels is not a violation", () => { + expect(collectPrimaryParentViolations(item(), EPICS)).toEqual([]); + }); + + test("a single label with no native parent is fine", () => { + expect(collectPrimaryParentViolations(item({ labels: ["primary-parent/id-program"] }), EPICS)).toEqual([]); + }); + + test("a single label agreeing with the native parent is fine", () => { + const violations = collectPrimaryParentViolations( + item({ + labels: ["primary-parent/id-program"], + nativeParent: { repo: "developing-today/code", number: 9060, kind: "sub-issue" }, + }), + EPICS, + new Set([ref(9060)]), + ); + expect(violations).toEqual([]); + }); + + test("a label naming an ancestor of the native parent is allowed (program-level parent)", () => { + const violations = collectPrimaryParentViolations( + item({ + labels: ["primary-parent/id-program"], + // Native parent is #3447 (crate-split); its ancestor chain includes the program epic #9060. + nativeParent: { repo: "developing-today/code", number: 3447, kind: "sub-issue" }, + }), + EPICS, + new Set([ref(3447), ref(9060)]), + ); + expect(violations).toEqual([]); + }); + + test("a label disagreeing with the native parent and not an ancestor is reported", () => { + const violations = collectPrimaryParentViolations( + item({ + labels: ["primary-parent/pm-stack"], + nativeParent: { repo: "developing-today/code", number: 3447, kind: "sub-issue" }, + }), + EPICS, + new Set([ref(3447), ref(9060)]), + ); + expect(violations.map((violation) => violation.kind)).toEqual(["label-native-disagreement"]); + expect(violations[0]?.message).toContain("developing-today/code#8983"); + expect(violations[0]?.message).toContain("developing-today/code#3447"); + }); + + test("an unreadable ancestor chain never manufactures a disagreement", () => { + const violations = collectPrimaryParentViolations( + item({ + labels: ["primary-parent/id-program"], + nativeParent: { repo: "developing-today/code", number: 3447, kind: "sub-issue" }, + }), + EPICS, + undefined, + ); + expect(violations).toEqual([]); + }); + + test("two labels are a violation even when they name the same epic", () => { + const violations = collectPrimaryParentViolations( + item({ labels: ["primary-parent/id-program", "primary-parent/ID-PROGRAM"] }), + EPICS, + ); + expect(violations.map((violation) => violation.kind)).toEqual(["multiple-primary-parent-labels"]); + expect(violations[0]?.message).toContain("at most one is allowed"); + }); + + test("two labels naming distinct epics report both targets", () => { + const violations = collectPrimaryParentViolations( + item({ labels: ["primary-parent/id-program", "primary-parent/pm-stack"] }), + EPICS, + ); + expect(violations.map((violation) => violation.kind)).toEqual(["multiple-primary-parent-labels"]); + expect(violations[0]?.message).toContain("2 distinct parents"); + expect(violations[0]?.labelParents.map((parent) => parent.number).sort()).toEqual([8983, 9060]); + }); + + test("a label naming no known epic is reported, never silently dropped", () => { + const violations = collectPrimaryParentViolations(item({ labels: ["primary-parent/ghost-epic"] }), EPICS); + expect(violations.map((violation) => violation.kind)).toEqual(["unresolved-primary-parent-label"]); + expect(violations[0]?.labels).toEqual(["primary-parent/ghost-epic"]); + }); + + test("multiplicity and unresolved findings coexist", () => { + const violations = collectPrimaryParentViolations( + item({ labels: ["primary-parent/ghost-epic", "primary-parent/id-program"] }), + EPICS, + ); + expect(violations.map((violation) => violation.kind).sort()).toEqual([ + "multiple-primary-parent-labels", + "unresolved-primary-parent-label", + ]); + }); +}); + +describe("planPrimaryParentLabels (label family registry)", () => { + const labels = [ + { name: "epic/id-crate-split", color: "5319e7" }, + { name: "epic/pm-stack", color: "1d76db" }, + { name: "epic/already-there", color: "5319e7" }, + { name: "primary-parent/already-there", color: "5319e7" }, + { name: "kind/feature", color: "a2eeef" }, + ]; + + test("plans one label per epic slug that lacks one, reusing the epic colour", () => { + const { plan, existing } = planPrimaryParentLabels(labels); + expect(existing).toEqual(["primary-parent/already-there"]); + expect(plan.map((entry) => entry.name)).toEqual(["primary-parent/id-crate-split", "primary-parent/pm-stack"]); + expect(plan[1]?.color).toBe("1d76db"); + expect(plan[0]?.description).toContain("id-crate-split"); + }); + + test("a slug too long for GitHub's 50-character label limit is skipped, not truncated", () => { + const long = `epic/${"x".repeat(36)}`; + const { plan, skippedTooLong } = planPrimaryParentLabels([{ name: long, color: "5319e7" }]); + expect(plan).toEqual([]); + expect(skippedTooLong).toEqual([`primary-parent/${"x".repeat(36)}`]); + }); +});