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
66 changes: 63 additions & 3 deletions pm-stack/aggregator/scripts/metadata-sweeper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -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<Set<string> | null> {
const refs = new Set<string>();
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<IngestionItem | null> {
const command = kind === "issue" ? "issue" : "pr";
const stdout = await runFleet([
Expand All @@ -346,7 +384,7 @@ async function main(): Promise<void> {
const db = openMetadataStore(options.dryRun ? ":memory:" : options.dbPath, (path) => new Database(path));
try {
const scratch = await mkdtemp(join(tmpdir(), "metadata-sweeper-"));
const summary: Record<string, SweepCounts & { dbRows: number }> = {};
const summary: Record<string, SweepCounts & { dbRows: number; violations: PrimaryParentViolation[] }> = {};
try {
for (const repo of options.repos) {
const counts: SweepCounts = {
Expand All @@ -356,8 +394,10 @@ async function main(): Promise<void> {
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),
Expand Down Expand Up @@ -397,6 +437,7 @@ async function main(): Promise<void> {
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
Expand All @@ -409,8 +450,9 @@ async function main(): Promise<void> {
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) {
Expand All @@ -421,6 +463,24 @@ async function main(): Promise<void> {
continue;
}
}

// Primary-parent convention (design §3): validate and report
// violations in the audit output, never resolve them here.
let ancestorRefs: Set<string> | 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) {
Expand Down Expand Up @@ -476,7 +536,7 @@ async function main(): Promise<void> {
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 });
Expand Down
180 changes: 180 additions & 0 deletions pm-stack/aggregator/scripts/sync-primary-parent-labels.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
#!/usr/bin/env bun
// Create the `primary-parent/<slug>` label family from the current
// `epic/<slug>` 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 <owner/name>
// [--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 <owner/name> [--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 <owner/name> (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();
Loading