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

issues.ts

197 lines · 6.7 KB · TypeScript
import githubRequest from 'kody:@kody/github/request'
import { issueRefsInText } from './pr-refs.ts'
import { commentFetchConcurrency, frictionLabel, type FrictionIssue, type IssueComment } from './shared.ts'

type GithubRequestResult = {
	ok?: boolean
	status?: number
	data?: unknown
	text?: string
}

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

type GithubComment = {
	id?: number
	body?: string | null
	created_at?: string | null
	user?: { login?: string | null } | null
}

function requireOk(result: GithubRequestResult, path: string) {
	if (result?.ok === false || (result.status && result.status >= 400)) {
		throw new Error(
			`GitHub ${path} failed (${result.status}): ${String(result.text || '').slice(0, 200)}`,
		)
	}
	return result.data
}

function asArray<T>(data: unknown): Array<T> {
	return Array.isArray(data) ? (data as Array<T>) : []
}

function issueLabels(issue: GithubIssue) {
	return (issue.labels || [])
		.map((label) => (typeof label === 'string' ? label : String(label?.name || '')))
		.filter(Boolean)
}

function toComment(comment: GithubComment): IssueComment {
	return {
		id: Number(comment.id || 0),
		userLogin: String(comment.user?.login || ''),
		createdAt: String(comment.created_at || ''),
		body: String(comment.body || ''),
	}
}

/**
 * List open issues (no pull requests), oldest first, WITHOUT comments. Pass
 * `label` to list only issues with that label. One request per 100 issues, so
 * this stays fast as the backlog grows. Fetch comments only for the issues a
 * run selects (`loadIssueComments`).
 */
export async function listOpenIssues(repoSlug: string, input: { label?: string } = {}): Promise<Array<FrictionIssue>> {
	const issues: Array<FrictionIssue> = []
	const labelQuery = input.label ? `labels=${encodeURIComponent(input.label)}&` : ''
	for (let page = 1; page <= 10; page += 1) {
		const path = `/repos/${repoSlug}/issues?${labelQuery}state=open&per_page=100&page=${page}`
		const data = asArray<GithubIssue>(requireOk(await githubRequest({ path }), path))
		for (const issue of data) {
			const number = Number(issue.number || 0)
			if (!number || issue.pull_request) continue
			issues.push({
				number,
				title: String(issue.title || ''),
				body: String(issue.body || ''),
				htmlUrl: String(issue.html_url || ''),
				userLogin: String(issue.user?.login || ''),
				createdAt: String(issue.created_at || ''),
				updatedAt: String(issue.updated_at || ''),
				labels: issueLabels(issue),
				comments: [],
			})
		}
		if (data.length < 100) break
	}
	issues.sort((left, right) => Date.parse(left.createdAt) - Date.parse(right.createdAt))
	return issues
}

/** Open `friction` issues, oldest first, without comments. */
export async function listFrictionIssues(repoSlug: string): Promise<Array<FrictionIssue>> {
	return await listOpenIssues(repoSlug, { label: frictionLabel })
}

/**
 * Make sure a repo label exists (bot account). Reads it first and creates it
 * only on 404; a 422 on create means another caller just made it.
 */
export async function ensureRepoLabel(
	repoSlug: string,
	label: { name: string; color: string; description: string },
): Promise<{ created: boolean }> {
	const readPath = `/repos/${repoSlug}/labels/${encodeURIComponent(label.name)}`
	const existing = (await githubRequest({ path: readPath })) as GithubRequestResult
	if (existing?.status !== 404) {
		requireOk(existing, `GET ${readPath}`)
		return { created: false }
	}
	const createPath = `/repos/${repoSlug}/labels`
	const created = (await githubRequest({
		method: 'POST',
		path: createPath,
		body: label,
		confirm: true,
	})) as GithubRequestResult
	if (created?.status === 422) return { created: false }
	requireOk(created, `POST ${createPath}`)
	return { created: true }
}

/** Add labels to one issue (bot account). */
export async function addIssueLabels(repoSlug: string, issueNumber: number, labels: Array<string>) {
	const path = `/repos/${repoSlug}/issues/${issueNumber}/labels`
	requireOk(await githubRequest({ method: 'POST', path, body: { labels }, confirm: true }), `POST ${path}`)
}

/** Post one comment on an issue (bot account, no @-mentions allowed). */
export async function postIssueComment(repoSlug: string, issueNumber: number, body: string) {
	const path = `/repos/${repoSlug}/issues/${issueNumber}/comments`
	requireOk(await githubRequest({ method: 'POST', path, body: { body }, confirm: true }), `POST ${path}`)
}

/**
 * Issue numbers referenced by open pull requests (title or body), mapped to
 * one PR URL each. Read-only; at most 5 pages of 100 open PRs.
 */
export async function listOpenPrIssueRefs(repoSlug: string): Promise<Map<number, string>> {
	const refs = new Map<number, string>()
	for (let page = 1; page <= 5; page += 1) {
		const path = `/repos/${repoSlug}/pulls?state=open&per_page=100&page=${page}`
		const data = asArray<GithubIssue>(requireOk(await githubRequest({ path }), path))
		for (const pr of data) {
			const url = String(pr.html_url || '')
			for (const number of issueRefsInText(`${pr.title || ''}\n${pr.body || ''}`, repoSlug)) {
				if (number !== Number(pr.number) && !refs.has(number)) refs.set(number, url)
			}
		}
		if (data.length < 100) break
	}
	return refs
}

async function listIssueComments(repoSlug: string, issueNumber: number) {
	const comments: Array<GithubComment> = []
	for (let page = 1; page <= 10; page += 1) {
		const path = `/repos/${repoSlug}/issues/${issueNumber}/comments?per_page=100&page=${page}`
		const pageComments = asArray<GithubComment>(
			requireOk(await githubRequest({ path }), path),
		)
		comments.push(...pageComments)
		if (pageComments.length < 100) break
	}
	return comments.map(toComment)
}

/** Run `task` over `items` with at most `limit` in flight; keeps input order. */
export async function mapWithConcurrency<T, R>(
	items: ReadonlyArray<T>,
	limit: number,
	task: (item: T, index: number) => Promise<R>,
): Promise<Array<R>> {
	const results = new Array<R>(items.length)
	let next = 0
	const workers = Array.from({ length: Math.max(1, Math.min(limit, items.length)) }, async () => {
		while (next < items.length) {
			const index = next
			next += 1
			results[index] = await task(items[index], index)
		}
	})
	await Promise.all(workers)
	return results
}

/** Fill `comments` for the given (already selected) issues only. */
export async function loadIssueComments(
	repoSlug: string,
	issues: ReadonlyArray<FrictionIssue>,
	concurrency = commentFetchConcurrency,
): Promise<Array<FrictionIssue>> {
	return await mapWithConcurrency(issues, concurrency, async (issue) => ({
		...issue,
		comments: await listIssueComments(repoSlug, issue.number),
	}))
}