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-scan.ts

74 lines · 3.3 KB · TypeScript
/**
 * The factory's own GitHub path for card references: each sweep tick reads
 * the most recently updated closed PRs in every in-scope project repo (one
 * GET per repo, at most 10 repos) and applies `pr-refs.ts` to PRs merged
 * since the last tick. The first tick for a repo only sets its cursor, so old
 * PRs are never replayed. State: `factory:pr-refs:v1` (cursor plus the last
 * 100 processed PR URLs per repo).
 *
 * With `githubEventsMode: 'live'` the `@kody/github.pr.merged` event does this
 * work and the sweep skips the scan.
 */
import { githubReadonlyRequest, type GithubFetch } from '../lib/github-readonly.ts'
import { loadJson, saveJson } from '../lib/storage.ts'
import type { Ledger } from '../core/work-item.ts'
import { applyPrRefs, normalizeMergedPr, planPrRefs, type PrRefDecision } from './pr-refs.ts'

export const PR_REFS_KEY = 'factory:pr-refs:v1'
const MAX_REPOS = 10
const KEEP_SEEN = 100

type RepoCursor = { since: string; seen: string[] }
export type PrRefsState = { repos: Record<string, RepoCursor> }
type GhPr = { html_url?: string; number?: number; title?: string; body?: string | null; merged_at?: string | null; merge_commit_sha?: string | null }

export type PrScanResult = {
	repos: number
	merged: number
	decisions: Array<PrRefDecision & { prUrl: string }>
	changed: string[]
	errors: string[]
	/** Save the cursors. Call after the ledger is saved so a failed save replays next tick. */
	persist: () => Promise<void>
}

export async function scanMergedPrs(ledger: Ledger, repos: string[], github: GithubFetch, opts: { dryRun?: boolean; now?: () => number } = {}): Promise<PrScanResult> {
	const now = opts.now ?? Date.now
	const state = await loadJson<PrRefsState>(PR_REFS_KEY, { repos: {} })
	const out: PrScanResult = { repos: 0, merged: 0, decisions: [], changed: [], errors: [], persist: async () => {} }
	let dirty = false
	for (const repo of [...new Set(repos.map((r) => r.toLowerCase()))].slice(0, MAX_REPOS)) {
		out.repos++
		const cursor = state.repos[repo]
		if (!cursor) {
			state.repos[repo] = { since: new Date(now()).toISOString(), seen: [] }
			dirty = true
			continue
		}
		let prs: GhPr[]
		try {
			prs = await githubReadonlyRequest<GhPr[]>(github, `/repos/${repo}/pulls?state=closed&sort=updated&direction=desc&per_page=30`)
		} catch (error) {
			out.errors.push(`${repo}: ${error instanceof Error ? error.message : String(error)}`.slice(0, 300))
			continue
		}
		let newest = cursor.since
		for (const raw of Array.isArray(prs) ? prs : []) {
			if (!raw?.merged_at || raw.merged_at < cursor.since) continue
			const pr = normalizeMergedPr({ url: String(raw.html_url ?? ''), title: raw.title, body: raw.body ?? '', mergeCommit: raw.merge_commit_sha ?? null, mergedAt: raw.merged_at })
			if (!pr || cursor.seen.includes(pr.url)) continue
			out.merged++
			const plan = planPrRefs(ledger, pr)
			out.decisions.push(...plan.map((d) => ({ ...d, prUrl: pr.url })))
			if (!opts.dryRun) out.changed.push(...applyPrRefs(ledger, pr, plan, 'sweep').map((i) => i.id))
			cursor.seen = [pr.url, ...cursor.seen].slice(0, KEEP_SEEN)
			if (raw.merged_at > newest) newest = raw.merged_at
			dirty = true
		}
		// Keep the cursor a little behind the newest merge so a PR updated in the
		// same second is not missed; `seen` keeps it idempotent.
		cursor.since = newest
	}
	if (dirty && !opts.dryRun) out.persist = () => saveJson(PR_REFS_KEY, state)
	return out
}