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

triage.ts

160 lines · 4.5 KB · TypeScript
/**
 * Modest intake triage gate.
 * Prefers model credential (Cloudflare AI / typesafe jev shape).
 * If the model is unavailable, returns needs-review rather than inventing a yes.
 */
import { credential } from 'kody:runtime'
import { extraCareMatches, decideShip, type ShipDecision } from './policy.ts'
import type { WorkItem } from './work-item.ts'
import { loadSettings } from '../lib/settings.ts'
import { buildTriageRequestBody, parseChoice } from './triage-request.ts'

export type TriageVerdict = {
	decision: 'triaged' | 'needs-kent' | 'needs-review'
	ship: ShipDecision
	reason: string
	modelUsed: boolean
	modelError?: string
}

async function askModel(item: WorkItem): Promise<{
	ok: boolean
	value?: string
	confidence?: number
	error?: string
}> {
	const settings = await loadSettings()
	if (!settings.cloudflareAccountId) {
		return { ok: false, error: 'cloudflareAccountId not set in factory settings' }
	}
	let client: { fetch: typeof fetch; name?: string }
	try {
		client = (await credential('model')) as { fetch: typeof fetch; name?: string }
	} catch (err) {
		return {
			ok: false,
			error: err instanceof Error ? err.message : String(err),
		}
	}
	const url =
		'https://api.cloudflare.com/client/v4/accounts/' +
		settings.cloudflareAccountId +
		'/ai/run'
	const body = buildTriageRequestBody(item)
	try {
		const res = await client.fetch(url, {
			method: 'POST',
			headers: {
				'Content-Type': 'application/json',
				'cf-aig-gateway-id': settings.cloudflareAiGatewayId || 'kody',
				'x-kody-secret-resolution': 'headers-only',
			},
			body: JSON.stringify(body),
		})
		const text = await res.text()
		let data: unknown = text
		try {
			data = text ? JSON.parse(text) : null
		} catch {
			data = text
		}
		if (!res.ok) {
			return {
				ok: false,
				error: `model HTTP ${res.status}`,
			}
		}
		const parsed = parseChoice(data)
		if (!parsed) return { ok: false, error: 'model returned no choice' }
		return { ok: true, value: parsed.value, confidence: parsed.confidence }
	} catch (err) {
		return { ok: false, error: err instanceof Error ? err.message : String(err) }
	}
}

/**
 * Heuristic only used to shape the ship-bar inputs; never alone decides yes.
 */
function heuristicHints(item: WorkItem): {
	productDirectionNeeded: boolean
	care: ReturnType<typeof extraCareMatches>
} {
	const care = extraCareMatches({ title: item.title, labels: item.labels })
	const productDirectionNeeded =
		item.needsKent ||
		/\b(should we|product decision|which approach|design review)\b/i.test(
			`${item.title}\n${item.body}`,
		)
	return { productDirectionNeeded, care }
}

export async function triageWorkItem(item: WorkItem): Promise<TriageVerdict> {
	const hints = heuristicHints(item)
	const model = await askModel(item)

	if (!model.ok) {
		const ship = decideShip({
			isRightFix: false,
			isTwoWayDoor: hints.care.length === 0,
			matchesWrittenDecision: !hints.productDirectionNeeded,
			extraCare: hints.care,
			productDirectionNeeded: hints.productDirectionNeeded,
		})
		return {
			decision: 'needs-review',
			ship,
			reason: `model unavailable (${model.error ?? 'unknown'}); held for review`,
			modelUsed: false,
			modelError: model.error,
		}
	}

	const value = (model.value ?? 'needs_review').toLowerCase()
	if (value === 'needs_kent' || hints.productDirectionNeeded) {
		const ship = decideShip({
			isRightFix: false,
			isTwoWayDoor: hints.care.length === 0,
			matchesWrittenDecision: false,
			extraCare: hints.care,
			productDirectionNeeded: true,
		})
		return {
			decision: 'needs-kent',
			ship,
			reason: `model chose needs_kent (confidence ${model.confidence ?? 0})`,
			modelUsed: true,
		}
	}
	// Extra-care topics stay eligible for a PR; decideShip marks them high risk (human review).
	if (value === 'autopilot_ok' && !hints.productDirectionNeeded) {
		const ship = decideShip({
			isRightFix: true,
			isTwoWayDoor: true,
			matchesWrittenDecision: true,
			extraCare: hints.care,
			productDirectionNeeded: false,
		})
		if (ship.mayAutopilot) {
			return {
				decision: 'triaged',
				ship,
				reason: `model chose autopilot_ok (confidence ${model.confidence ?? 0})`,
				modelUsed: true,
			}
		}
	}

	const ship = decideShip({
		isRightFix: false,
		isTwoWayDoor: hints.care.length === 0,
		matchesWrittenDecision: !hints.productDirectionNeeded,
		extraCare: hints.care,
		productDirectionNeeded: hints.productDirectionNeeded,
	})
	return {
		decision: 'needs-review',
		ship,
		reason: `model chose ${value}; holding for review (confidence ${model.confidence ?? 0})`,
		modelUsed: true,
	}
}