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

pipeline.ts

235 lines · 7.4 KB · TypeScript
/**
 * Signal processing pipeline: receive -> verify -> route -> dispatch -> record.
 * Connects the inbound handler with routing and destination dispatch.
 */
import { getSource, verifyHmac } from './sources/index.ts'
import { insertRecord, updateRecord, evictOldRecords, incrementRejection, type SignalRecord } from './records/index.ts'
import { MAX_REDACTED_PAYLOAD_SIZE } from './records/types.ts'
import { routeSignal } from './routing/index.ts'
import { dispatch, type PromptContext } from './destinations/index.ts'
import type { SourceRecord } from './sources/types.ts'

function newSignalId(): string {
	return `sig_${crypto.randomUUID().replace(/-/g, '').slice(0, 16)}`
}

function nowIso(): string {
	return new Date().toISOString()
}

async function computeDigest(payload: string): Promise<string> {
	const data = new TextEncoder().encode(payload)
	const hash = await crypto.subtle.digest('SHA-256', data)
	return Array.from(new Uint8Array(hash), (b) => b.toString(16).padStart(2, '0')).join('')
}

function redact(payload: string): string {
	if (payload.length <= MAX_REDACTED_PAYLOAD_SIZE) return payload
	return payload.slice(0, MAX_REDACTED_PAYLOAD_SIZE - 20) + '...[truncated]'
}

function extractTitle(payload: unknown): string | null {
	if (!payload || typeof payload !== 'object') return null
	const rec = payload as Record<string, unknown>
	if (typeof rec.title === 'string') return rec.title
	const issue = rec.issue as Record<string, unknown> | undefined
	if (issue && typeof issue.title === 'string') return issue.title
	const alert = rec.alert as Record<string, unknown> | undefined
	if (alert && typeof alert.title === 'string') return alert.title
	return null
}

function extractBody(payload: unknown): string {
	if (!payload || typeof payload !== 'object') return ''
	const rec = payload as Record<string, unknown>
	if (typeof rec.body === 'string') return rec.body
	const issue = rec.issue as Record<string, unknown> | undefined
	if (issue && typeof issue.body === 'string') return issue.body
	return ''
}

function extractLabels(payload: unknown): string[] {
	if (!payload || typeof payload !== 'object') return []
	const rec = payload as Record<string, unknown>
	const labelsRaw = rec.labels ?? (rec.issue as Record<string, unknown> | undefined)?.labels
	if (!Array.isArray(labelsRaw)) return []
	return labelsRaw.map((l) =>
		typeof l === 'string' ? l : String((l as { name?: string }).name ?? ''),
	).filter(Boolean)
}

export type ProcessResult = {
	signalId: string
	verified: boolean
	routed: boolean
	dispatched: boolean
	record: SignalRecord
	error?: string
}

export async function processSignal(input: {
	sourceId: string
	payload: string
	signature?: string
	headers?: Record<string, string>
	dryRun?: boolean
}): Promise<ProcessResult> {
	const source = await getSource(input.sourceId)
	if (!source) throw new Error(`Unknown source: ${input.sourceId}`)
	if (!source.enabled) throw new Error(`Source "${input.sourceId}" is disabled`)

	const signalId = newSignalId()
	const receivedAt = nowIso()
	const digest = await computeDigest(input.payload)

	let verified = false
	let verifyError: string | null = null
	if (source.kind === 'sentry') {
		// Sentry reaches the factory as @kody/sentry-events events now; the factory holds no Sentry secret.
		verifyError = 'Sentry signals arrive as @kody/sentry-events.issue.alerted events; point Sentry at the @kody/sentry-events webhook'
	} else if (source.signingSecretName && input.signature) {
		verified = await verifyHmac(input.sourceId, input.payload, input.signature)
	} else if (!source.signingSecretName) {
		verifyError = 'Source signing secret is not configured'
	} else if (!input.signature) {
		verifyError = 'Missing signature header'
	}

	let parsed: unknown = null
	try { parsed = JSON.parse(input.payload) } catch { parsed = null }

	const title = extractTitle(parsed) ?? 'Inbound signal'
	const body = extractBody(parsed)
	const labels = extractLabels(parsed)

	const record: SignalRecord = {
		id: signalId,
		sourceId: input.sourceId,
		receivedAt,
		verified,
		payloadDigest: digest,
		redactedPayload: redact(input.payload),
		routingDecision: null,
		destinationResults: [],
		status: 'received',
		error: null,
		projectId: null,
		title,
	}

	if (!verified) {
		record.status = 'rejected'
		record.error = verifyError ?? 'HMAC verification failed'
		record.redactedPayload = ''
		record.payloadDigest = digest
		if (!input.dryRun) await incrementRejection(input.sourceId, record.error)
		return { signalId, verified: false, routed: false, dispatched: false, record }
	}

	const projectId = resolveProjectId(source, parsed)
	record.projectId = projectId

	if (!projectId) {
		record.status = 'failed'
		record.error = 'Could not resolve project for signal'
		if (!input.dryRun) await insertRecord(record)
		return { signalId, verified: true, routed: false, dispatched: false, record }
	}

	if (!input.dryRun) {
		await insertRecord(record)
		await evictOldRecords()
	}

	const routing = await routeSignal({
		title,
		body,
		source: source.kind,
		labels,
		projectId,
	})

	record.routingDecision = {
		destination: routing.destination,
		confidence: routing.confidence,
		modelUsed: routing.modelUsed,
		escalated: routing.escalated,
		reason: routing.reason,
		labels: routing.labels,
		projectId,
	}
	record.status = 'routed'
	if (!input.dryRun) await updateRecord(signalId, { routingDecision: record.routingDecision, status: 'routed', projectId })

	const ctx: PromptContext = {
		title,
		body,
		source: source.kind,
		sourceId: source.id,
		projectId,
		severity: 'medium',
		labels,
		receivedAt,
		signalId,
	}

	const mapping = (await import('./routing/config.ts')).getRoutingConfig(projectId)
		.then((c) => c.criteria[routing.labels[0] ?? ''])
	const templateId = (await mapping)?.promptTemplateId ?? null

	const result = await dispatch(routing.destination, ctx, {
		templateId,
		shadow: true,
		dryRun: input.dryRun,
	})

	record.destinationResults = [{ destination: result.destination, ok: result.ok, detail: result.detail, at: nowIso() }]
	record.status = result.ok ? 'dispatched' : 'failed'
	if (!result.ok) record.error = result.detail

	if (!input.dryRun) {
		await updateRecord(signalId, {
			destinationResults: record.destinationResults,
			status: record.status,
			error: record.error,
		})
	}

	return {
		signalId,
		verified: true,
		routed: true,
		dispatched: result.ok,
		record,
	}
}

export async function replaySignal(signalId: string, opts?: { dryRun?: boolean }): Promise<ProcessResult> {
	const { getRecord } = await import('./records/index.ts')
	const existing = await getRecord(signalId)
	if (!existing) throw new Error(`Signal record "${signalId}" not found`)

	return processSignal({
		sourceId: existing.sourceId,
		payload: existing.redactedPayload,
		dryRun: opts?.dryRun !== false,
	})
}

function resolveProjectId(source: SourceRecord, payload: unknown): string | null {
	if (source.projectScope.length === 1) return source.projectScope[0]!
	if (source.projectScope.length > 1 && payload && typeof payload === 'object') {
		const rec = payload as Record<string, unknown>
		const repo = (rec.repository as Record<string, unknown> | undefined)?.full_name ?? rec.repo
		if (typeof repo === 'string') {
			// TODO: match repo to project via project config
		}
		const projectId = rec.projectId ?? rec.project_id
		if (typeof projectId === 'string' && source.projectScope.includes(projectId)) {
			return projectId
		}
		return source.projectScope[0]!
	}
	if (source.projectScope.length > 0) return source.projectScope[0]!
	return null
}