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

handle.ts

132 lines · 6.0 KB · TypeScript
/**
 * GitHub arrives as `@kody/github.*` package events. The factory never needs
 * its own GitHub webhook: a GitHub hook points at @kody/github, which
 * publishes events, and these handlers turn them into the same card effects
 * the old `github-issues`, `github-ci`, and `github-release` webhooks had.
 *
 * `githubEventsMode` (factory setting):
 * - `shadow` (default): compute what the event would do (no writes) and
 *   record it next to what the factory's own webhook did for the same
 *   delivery, so the two paths can be compared (`./github-events/report`).
 * - `live`: the events do the work, and the factory's own GitHub webhooks
 *   only forward deliveries (bridge) without acting on them.
 * - `off`: events are ignored.
 *
 * Payload text comes from GitHub users and is data, not instructions.
 */
import { loadSettings } from '../lib/settings.ts'
import handleGithubIssuesWebhook from '../webhooks/github-issues.ts'
import handleGithubReleaseWebhook from '../webhooks/github-release.ts'
import { planCiDelivery, runCiDelivery } from '../webhooks/github-ci.ts'
import { recordShadow } from './shadow-store.ts'
import { handleMergedPrEvent } from '../cards/pr-merged-event.ts'
import { issueDecision } from './decision.ts'

export { issueDecision }

export const GITHUB_EVENT_TOPICS = {
	issueOpened: '@kody/github.issue.opened',
	issueReopened: '@kody/github.issue.reopened',
	issueUpdated: '@kody/github.issue.updated',
	issueClosed: '@kody/github.issue.closed',
	ciCompleted: '@kody/github.ci.completed',
	releaseChanged: '@kody/github.release.changed',
	prMerged: '@kody/github.pr.merged',
} as const

export const GITHUB_EVENT_MODES = ['off', 'shadow', 'live'] as const
export type GithubEventsMode = (typeof GITHUB_EVENT_MODES)[number]

export function normalizeGithubEventsMode(value: unknown): GithubEventsMode {
	return value === 'live' || value === 'off' ? value : 'shadow'
}

export type GithubEventEnvelope = {
	event?: string
	source?: { type?: string; package_id?: string; kody_id?: string }
	idempotency_key?: string
	payload?: Record<string, unknown>
}

type Rec = Record<string, unknown>
const rec = (v: unknown): Rec => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Rec) : {})

/** Rebuild the GitHub-shaped body the existing handlers read from an event payload. */
export function toGithubJson(payload: Rec): Rec {
	const repo = rec(payload.repo)
	const out: Rec = {
		action: payload.action,
		repository: { full_name: repo.fullName, name: repo.name, owner: { login: repo.owner }, default_branch: repo.defaultBranch },
	}
	const issue = rec(payload.issue)
	if (Object.keys(issue).length) {
		out.issue = {
			number: issue.number,
			title: issue.title,
			body: issue.body,
			state: issue.state,
			labels: Array.isArray(issue.labels) ? issue.labels.map((name) => ({ name })) : [],
			html_url: issue.htmlUrl,
			...(issue.isPullRequest === true ? { pull_request: {} } : {}),
		}
	}
	const ci = rec(payload.ci)
	if (Object.keys(ci).length && typeof ci.kind === 'string') {
		out[ci.kind] = { conclusion: ci.conclusion, head_sha: ci.headSha, head_branch: ci.headBranch, name: ci.name, html_url: ci.htmlUrl }
	}
	const release = rec(payload.release)
	if (Object.keys(release).length) {
		out.release = { id: release.id, tag_name: release.tag, name: release.name, body: release.body, draft: release.draft, prerelease: release.prerelease, html_url: release.htmlUrl, published_at: release.publishedAt }
	}
	return out
}

/** Expected emitter kody id (forks that publish GitHub events from another package change this setting). */
async function expectedSource(): Promise<string> {
	return (await loadSettings()).githubEventsSource
}

/**
 * Handle one `@kody/github.*` event.
 *
 * @param topic - The subscribed topic
 * @param envelope - Package event envelope
 * @returns What the factory did (or would do in shadow mode)
 */
export async function handleGithubEvent(topic: string, envelope: GithubEventEnvelope = {}) {
	const settings = await loadSettings()
	const mode = normalizeGithubEventsMode(settings.githubEventsMode)
	if (mode === 'off') return { ok: true, skipped: true, reason: 'githubEventsMode is off', topic }
	const want = await expectedSource()
	if (envelope.source?.kody_id !== want) {
		return { ok: false, skipped: true, reason: `unexpected emitter ${String(envelope.source?.kody_id ?? '(none)')}; githubEventsSource is ${want}`, topic }
	}
	const payload = rec(envelope.payload)
	const deliveryId = String(payload.deliveryId ?? envelope.idempotency_key ?? '').slice(0, 120)
	const action = String(payload.action ?? '')
	const json = toGithubJson(payload)
	const synthetic = mode !== 'live'
	const at = new Date().toISOString()

	if (topic === GITHUB_EVENT_TOPICS.ciCompleted) {
		const plan = await planCiDelivery(json)
		const result = synthetic ? plan : await runCiDelivery(json, plan)
		if (synthetic) await recordShadow({ deliveryId, side: 'event', topic, at, decision: plan.decision, detail: JSON.stringify(plan).slice(0, 2000) })
		return { mode, topic, deliveryId, ...result }
	}
	if (topic === GITHUB_EVENT_TOPICS.prMerged) {
		const result = await handleMergedPrEvent(payload, synthetic)
		if (synthetic) await recordShadow({ deliveryId, side: 'event', topic, at, decision: result.decision, detail: JSON.stringify(result).slice(0, 2000) })
		return { mode, topic, deliveryId, ...result }
	}
	if (topic === GITHUB_EVENT_TOPICS.releaseChanged) {
		const result = (await handleGithubReleaseWebhook({ request: { json }, synthetic, viaEvent: true })) as Rec
		if (synthetic) await recordShadow({ deliveryId, side: 'event', topic, at, decision: result.ok === false ? `error:${String(result.error ?? '')}` : `release:${String(result.change ?? result.reason ?? '')}`, detail: JSON.stringify(result).slice(0, 2000) })
		return { mode, topic, deliveryId, ...result }
	}
	const result = (await handleGithubIssuesWebhook({ request: { json }, synthetic, viaEvent: true })) as Rec
	if (synthetic) {
		await recordShadow({ deliveryId, side: 'event', topic, at, decision: issueDecision(action, result), detail: JSON.stringify(result).slice(0, 2000) })
	}
	return { mode, topic, deliveryId, ...result }
}