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

cards-import-github.ts

122 lines · 6.6 KB · TypeScript
/**
 * Import every open GitHub issue of a project repo as a factory card.
 * Quiet: card.created events go out, pushes and card-route wakes do not.
 *
 * - No card yet: a new intake card (`source:github`, `gh:#n`, plus
 *   `sweep:nightly` unless `nightly: false`).
 * - Open card: its labels, priority, and needs-kent are refreshed from the
 *   issue and the tags added.
 * - Dropped card: reopened (the issue is still open): back to intake, or
 *   needs-kent when the issue is labeled so.
 * - Shipped card: left shipped and reported (`shipped-open-issue`).
 *
 * dryRun (default true) reports what it would do. Never writes to GitHub.
 *
 * @example
 * import importGithub from 'kody:@kody/kody-factory/cards/import-github'
 * await importGithub({ projectId: 'kody', dryRun: true })
 */
import { loadJson, saveJson, storageKeys } from '../lib/storage.ts'
import { emptyLedger, nowIso, type Ledger, type WorkItem } from '../core/work-item.ts'
import { parsePriorityLabel, rankOf } from '../core/priority-queue.ts'
import { loadProjects, primaryRepoRef } from '../projects/config.ts'
import { githubIssuesAdapter } from '../signals/adapters/github-issues.ts'
import { ingestSignals, refreshLabels } from '../signals/intake.ts'
import { githubCredentialFetch, githubReadonlyRequest, REPO_REF_RE } from '../lib/github-readonly.ts'
import { appBaseUrl, cardLink } from '../lib/links.ts'
import { NIGHTLY_TAG, withTags } from '../cards/tags.ts'
import { afterCardTriaged, type TriageChange } from '../cards/lifecycle.ts'

type GithubIssue = { number?: number; title?: string; body?: string | null; html_url?: string; labels?: Array<string | { name?: string }>; pull_request?: unknown; user?: { login?: string; type?: string } }

export type ImportRow = { number: number; title: string; author: string; authorType: string; cardId: string | null; cardUrl: string | null; state: string | null; action: 'created' | 'refreshed' | 'reopened' | 'unchanged' | 'shipped-open-issue' | 'would-create' | 'would-refresh' | 'would-reopen' }

export default async function importGithub(input: { projectId: string; repo?: string; dryRun?: boolean; nightly?: boolean; maxIssues?: number }) {
	const dryRun = input?.dryRun !== false
	const nightly = input?.nightly !== false
	const project = (await loadProjects()).projects[String(input?.projectId ?? '')]
	if (!project) throw new Error(`import-github: unknown projectId "${input?.projectId}"`)
	const repo = String(input.repo ?? primaryRepoRef(project) ?? '')
	if (!REPO_REF_RE.test(repo)) throw new Error('import-github: repo must be owner/name')
	if (!project.repos.some((r) => r.repoRef.toLowerCase() === repo.toLowerCase()) && project.repoRef?.toLowerCase() !== repo.toLowerCase()) {
		throw new Error(`import-github: ${repo} is not a repo of project ${project.id}`)
	}
	const max = Math.min(Math.max(Number(input.maxIssues ?? 300), 1), 500)
	const fetchFn = await githubCredentialFetch()
	const issues: GithubIssue[] = []
	for (let page = 1; page <= 5 && issues.length < max; page++) {
		const batch = await githubReadonlyRequest<GithubIssue[]>(fetchFn, `/repos/${repo}/issues?state=open&per_page=100&page=${page}`)
		if (!Array.isArray(batch) || batch.length === 0) break
		issues.push(...batch.filter((i) => !i.pull_request && typeof i.number === 'number'))
		if (batch.length < 100) break
	}

	const base = await appBaseUrl()
	const ledger = await loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger())
	const byFp = new Map<string, WorkItem>()
	for (const item of Object.values(ledger.items)) {
		const prev = byFp.get(item.fingerprint)
		// Prefer the open card when a fingerprint has more than one.
		if (!prev || (prev.state === 'dropped' || prev.state === 'shipped')) byFp.set(item.fingerprint, item)
	}
	const rows: ImportRow[] = []
	const toCreate = []
	const triaged: TriageChange[] = []
	const at = nowIso()
	for (const issue of issues.slice(0, max)) {
		const [signal] = await githubIssuesAdapter.normalize({ issue, repository: { full_name: repo } }, { projectId: project.id })
		if (!signal) continue
		if (nightly) signal.labels = withTags(signal.labels, [NIGHTLY_TAG])
		const author = String(issue.user?.login ?? '')
		const authorType = String(issue.user?.type ?? '')
		const row = (cardId: string | null, state: string | null, action: ImportRow['action']): ImportRow => ({ number: issue.number!, title: signal.title.slice(0, 200), author, authorType, cardId, cardUrl: cardId ? cardLink(base, cardId) : null, state, action })
		const existing = byFp.get(signal.fingerprint)
		if (!existing) {
			toCreate.push(signal)
			rows.push(row(null, null, 'would-create'))
			continue
		}
		if (existing.state === 'shipped') {
			rows.push(row(existing.id, existing.state, 'shipped-open-issue'))
			continue
		}
		if (existing.state === 'dropped') {
			const { priority, needsKent } = parsePriorityLabel(signal.labels)
			const to = needsKent ? 'needs-kent' : 'intake'
			const fresh = refreshLabels({ ...existing, state: to }, signal)
			const base2 = fresh?.after ?? { ...existing, state: to }
			const next: WorkItem = { ...base2, state: to, priority, needsKent, rank: rankOf(priority, needsKent), labels: withTags(base2.labels, nightly ? [NIGHTLY_TAG] : []), updatedAt: at, events: [...base2.events, { at, from: 'dropped', to, reason: 'reopened: the GitHub issue is still open (import)', actor: 'system' }] }
			if (!dryRun) {
				ledger.items[existing.id] = next
				triaged.push({ before: { state: existing.state, priority: existing.priority, needsKent: existing.needsKent, labels: existing.labels }, after: next, reason: 'reopened by import' })
			}
			rows.push(row(existing.id, to, dryRun ? 'would-reopen' : 'reopened'))
			continue
		}
		const change = refreshLabels(existing, signal)
		if (change) {
			if (!dryRun) {
				ledger.items[existing.id] = change.after
				triaged.push(change)
			}
			rows.push(row(existing.id, existing.state, dryRun ? 'would-refresh' : 'refreshed'))
		} else rows.push(row(existing.id, existing.state, 'unchanged'))
	}

	if (!dryRun) {
		if (triaged.length > 0) {
			await saveJson(storageKeys.LEDGER_KEY, ledger)
			await afterCardTriaged(triaged, { quiet: true })
		}
		if (toCreate.length > 0) {
			const result = await ingestSignals(toCreate, { shadow: false, quiet: true })
			for (const item of result.created) {
				const r = rows.find((x) => x.action === 'would-create' && `github-issue:${repo}:${x.number}` === item.fingerprint)
				if (r) Object.assign(r, { cardId: item.id, cardUrl: cardLink(base, item.id), state: item.state, action: 'created' })
			}
		}
	}
	const counts: Record<string, number> = {}
	for (const r of rows) counts[r.action] = (counts[r.action] ?? 0) + 1
	return { ok: true, dryRun, repo, projectId: project.id, openIssues: rows.length, counts, rows }
}