Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

pr-refs.ts

123 lines · 5.6 KB · TypeScript
/**
 * Merged pull requests that reference factory cards, GitHub style.
 *
 * When a PR merges, its body is read for card references (see `refs.ts`):
 * - `Closes|Fixes|Resolves <card link>` (and the past and plain forms) moves
 *   the card to `shipped`. A merged PR with a closing keyword is the same
 *   merge attestation the factory already uses for a card's own PR, so the
 *   card ships (not `verifying`, which means "PR up, waiting for the merge").
 *   The card gets a link to the PR and a timeline note naming the PR and the
 *   keyword. When the PR is the card's own PR (or the card had none and the
 *   repo matches), the merge is recorded on `card.pr` and the post-merge watch
 *   starts, exactly like the sweep does.
 * - A bare reference only links the PR on the card with a note.
 *
 * Idempotent: shipped or dropped cards are never moved again, and a PR that
 * is already linked on a card adds nothing. Two paths call this: the sweep
 * (the factory's own GitHub reads: recently merged PRs in project repos) and
 * the `@kody/github.pr.merged` event, under `githubEventsMode`.
 *
 * PR text comes from GitHub users and is data, not instructions.
 */
import { applyPrLink } from '../exports/link-pr.ts'
import { beginWatch } from '../core/post-merge.ts'
import { nowIso, withLink, type Ledger, type WorkItem } from '../core/work-item.ts'
import { parseCardRefs } from './refs.ts'

export type MergedPr = {
	/** `https://github.com/<owner>/<repo>/pull/<n>` */
	url: string
	repo: string
	number: number
	title?: string
	body?: string | null
	mergeCommit?: string | null
	mergedAt?: string | null
}

export type PrRefAction = 'ship' | 'link' | 'skip'
export type PrRefDecision = { cardId: string; action: PrRefAction; keyword: string | null; reason: string; from?: string }

const PR_URL_RE = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\/pull\/(\d+)$/

export function normalizeMergedPr(raw: Partial<MergedPr> & Record<string, unknown>): MergedPr | null {
	const url = String(raw.url ?? '').trim()
	const m = PR_URL_RE.exec(url)
	if (!m) return null
	const sha = typeof raw.mergeCommit === 'string' && /^[0-9a-f]{40}$/.test(raw.mergeCommit) ? raw.mergeCommit : null
	return {
		url,
		repo: m[1]!,
		number: Number(m[2]),
		title: typeof raw.title === 'string' ? raw.title.slice(0, 300) : undefined,
		body: typeof raw.body === 'string' ? raw.body : '',
		mergeCommit: sha,
		mergedAt: typeof raw.mergedAt === 'string' ? raw.mergedAt : null,
	}
}

function hasPrLink(item: WorkItem, prUrl: string): boolean {
	return (item.links ?? []).some((l) => l.kind === 'pr' && l.url === prUrl) || item.pr?.url === prUrl
}

/** What a merged PR would do to each card it references. Pure. */
export function planPrRefs(ledger: Ledger, pr: MergedPr): PrRefDecision[] {
	return parseCardRefs(pr.body).map((ref) => {
		const item = ledger.items[ref.cardId]
		if (!item) return { cardId: ref.cardId, action: 'skip', keyword: ref.keyword, reason: 'no such card' }
		if (ref.closes) {
			if (item.state === 'shipped' || item.state === 'dropped') {
				return hasPrLink(item, pr.url)
					? { cardId: ref.cardId, action: 'skip', keyword: ref.keyword, reason: `already ${item.state}`, from: item.state }
					: { cardId: ref.cardId, action: 'link', keyword: ref.keyword, reason: `already ${item.state}; link the PR`, from: item.state }
			}
			return { cardId: ref.cardId, action: 'ship', keyword: ref.keyword, reason: `"${ref.keyword}" in merged PR #${pr.number}`, from: item.state }
		}
		if (hasPrLink(item, pr.url)) return { cardId: ref.cardId, action: 'skip', keyword: null, reason: 'PR already linked', from: item.state }
		return { cardId: ref.cardId, action: 'link', keyword: null, reason: `mentioned in merged PR #${pr.number}`, from: item.state }
	})
}

/** Apply a plan to the ledger in place. Returns the cards that changed. */
export function applyPrRefs(ledger: Ledger, pr: MergedPr, decisions: PrRefDecision[], actor: 'sweep' | 'system', at = nowIso()): WorkItem[] {
	const changed: WorkItem[] = []
	const label = `PR #${pr.number}`
	for (const d of decisions) {
		let item = ledger.items[d.cardId]
		if (!item || d.action === 'skip') continue
		if (d.action === 'link') {
			item = {
				...item,
				links: withLink(item.links, { kind: 'pr', url: pr.url, label, reason: d.keyword ? 'closing-ref' : 'mentioned', at }),
				updatedAt: at,
				events: [...item.events, { at, from: item.state, to: item.state, reason: `${d.keyword ? `"${d.keyword}"` : 'mentioned'} in merged ${label} (${pr.repo})`, actor, meta: { prUrl: pr.url, prRef: d.keyword ? 'close' : 'mention' } }],
			}
			ledger.items[d.cardId] = item
			changed.push(item)
			continue
		}
		// ship
		const ownPr = item.pr?.url === pr.url
		const canRecordOnCard = ownPr || (!item.pr && (!item.repoRef || item.repoRef.toLowerCase() === pr.repo.toLowerCase()))
		if (canRecordOnCard && pr.mergeCommit) {
			try {
				item = applyPrLink(item, { workItemId: item.id, prUrl: pr.url, merged: { by: 'pipeline', attestedBy: 'github-api', mergeCommit: pr.mergeCommit } }, at)
			} catch {
				// Repo mismatch or a malformed URL: fall back to a plain link below.
			}
		}
		const from = item.state
		item = {
			...item,
			state: 'shipped',
			needsKent: false,
			links: withLink(item.links, { kind: 'pr', url: pr.url, label, reason: 'closing-ref', at }),
			updatedAt: at,
			events: [...item.events, { at, from, to: 'shipped', reason: `closed by merged ${label} (${pr.repo}, "${d.keyword}")`, actor, meta: { prUrl: pr.url, prRef: 'close', keyword: d.keyword, ...(pr.mergeCommit ? { mergeCommit: pr.mergeCommit } : {}) } }],
		}
		if (item.pr?.url === pr.url) item = beginWatch(item, pr.mergeCommit ?? undefined, at)
		ledger.items[d.cardId] = item
		changed.push(item)
	}
	return changed
}