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

overlap.ts

108 lines · 4.7 KB · TypeScript
/**
 * Overlap suppression: before work is queued or an agent starts, look for an
 * open PR that references the issue (one bounded GitHub read per repo) and
 * for another in-flight work item / agent session on the same source.
 */
import type { Ledger, WorkItem } from './work-item.ts'
import { githubReadonlyRequest, type GithubFetch } from '../lib/github-readonly.ts'

export type OpenPr = { number: number; url: string; title: string; body: string }
export type Overlap = { kind: 'open-pr' | 'active-session'; url: string; label: string }

const IN_FLIGHT = new Set(['planned', 'running', 'verifying'])

/** Open PRs for a repo (newest 50). Cached per call site via the map. */
export async function listOpenPrs(fetchFn: GithubFetch, repoRef: string, cache?: Map<string, OpenPr[]>): Promise<OpenPr[]> {
	const key = repoRef.toLowerCase()
	const hit = cache?.get(key)
	if (hit) return hit
	const [owner, name] = repoRef.split('/')
	const raw = await githubReadonlyRequest<Array<Record<string, unknown>>>(
		fetchFn,
		`/repos/${encodeURIComponent(owner!)}/${encodeURIComponent(name!)}/pulls?state=open&per_page=50`,
	)
	const prs = (Array.isArray(raw) ? raw : []).map((p) => ({
		number: Number(p.number),
		url: String(p.html_url ?? ''),
		title: String(p.title ?? ''),
		body: String(p.body ?? ''),
	})).filter((p) => p.url.startsWith('https://github.com/'))
	cache?.set(key, prs)
	return prs
}

/** True when the PR text references issue #n of repoRef (#n, owner/repo#n, or the issue URL). */
export function prReferencesIssue(pr: Pick<OpenPr, 'title' | 'body'>, repoRef: string, issueNumber: number): boolean {
	const text = `${pr.title}\n${pr.body}`
	const n = String(issueNumber)
	const esc = repoRef.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')
	return (
		new RegExp(`(^|[^\\w/#])#${n}(?!\\d)`).test(text) ||
		new RegExp(`\\b${esc}#${n}(?!\\d)`, 'i').test(text) ||
		new RegExp(`github\\.com/${esc}/issues/${n}(?!\\d)`, 'i').test(text)
	)
}

export function issueNumberOf(item: Pick<WorkItem, 'source' | 'externalId'>): number | null {
	if (item.source !== 'github-issues') return null
	const n = Number(item.externalId)
	return Number.isInteger(n) && n > 0 ? n : null
}

/** Another in-flight item on the same source (fingerprint or issue), with its session/PR URL. */
export function activeSessionOverlap(
	ledger: Ledger,
	item: Pick<WorkItem, 'id' | 'projectId' | 'fingerprint' | 'externalId' | 'repoRef' | 'source'>,
	runUrls: Record<string, string | undefined> = {},
): Overlap | null {
	for (const other of Object.values(ledger.items)) {
		if (other.id === item.id || !IN_FLIGHT.has(other.state)) continue
		const same =
			other.fingerprint === item.fingerprint ||
			(item.externalId != null && other.externalId === item.externalId && other.source === item.source &&
				(other.repoRef ?? '').toLowerCase() === (item.repoRef ?? '').toLowerCase())
		if (!same) continue
		if (other.state === 'planned' && !other.runId) continue
		const url = (other.runId && runUrls[other.runId]) || other.links?.find((l) => l.kind === 'session')?.url || other.pr?.url
		return { kind: 'active-session', url: url ?? `factory:${other.id}`, label: `In flight as ${other.id} (${other.state})` }
	}
	return null
}

export async function openPrOverlap(
	fetchFn: GithubFetch | null,
	item: Pick<WorkItem, 'source' | 'externalId' | 'repoRef'>,
	cache?: Map<string, OpenPr[]>,
): Promise<Overlap | null> {
	const n = issueNumberOf(item)
	if (!fetchFn || n == null || !item.repoRef) return null
	const prs = await listOpenPrs(fetchFn, item.repoRef, cache)
	const pr = prs.find((p) => prReferencesIssue(p, item.repoRef!, n))
	return pr ? { kind: 'open-pr', url: pr.url, label: `Open PR #${pr.number}: ${pr.title.slice(0, 120)}` } : null
}

/** Source close/delete recorded on the item and not undone by a later reopen. */
export function sourceClosedEvent(item: Pick<WorkItem, 'events'>): string | null {
	for (let i = item.events.length - 1; i >= 0; i--) {
		const state = item.events[i]?.meta?.['externalState']
		if (state === 'open') return null
		if (state === 'closed' || state === 'deleted') return String(state)
	}
	return null
}

/** Live GitHub issue state ('open' | 'closed'), or null when unknown or not a GitHub issue. */
export async function liveIssueState(
	fetchFn: GithubFetch | null,
	item: Pick<WorkItem, 'source' | 'externalId' | 'repoRef'>,
): Promise<'open' | 'closed' | null> {
	const n = issueNumberOf(item)
	if (!fetchFn || n == null || !item.repoRef) return null
	const [owner, name] = item.repoRef.split('/')
	const raw = await githubReadonlyRequest<Record<string, unknown>>(
		fetchFn,
		`/repos/${encodeURIComponent(owner!)}/${encodeURIComponent(name!)}/issues/${n}`,
	)
	const state = String(raw?.state ?? '')
	return state === 'open' || state === 'closed' ? state : null
}