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

model.ts

304 lines · 11.2 KB · TypeScript
/**
 * Factory reports: what an audit or scheduled review found, recorded whether
 * or not it needs work. A report can file zero, one, or many cards, and every
 * card it files links back to it. Pure (no kody:runtime) so it is unit-testable.
 */
import type { WorkItemPriority, WorkItemState } from '../core/work-item.ts'

export const FINDING_SEVERITIES = ['info', 'notice', 'warning', 'critical'] as const
export type FindingSeverity = (typeof FINDING_SEVERITIES)[number]

export const REPORT_LIMITS = {
	title: 200,
	source: 60,
	summary: 8000,
	findings: 40,
	findingTitle: 200,
	findingDetail: 1500,
	cards: 20,
	cardTitle: 200,
	cardBody: 8000,
	cardLabels: 10,
	metrics: 30,
	links: 10,
	/** Newest reports kept in storage. */
	stored: 150,
} as const

export type ReportFinding = {
	id: string
	title: string
	severity: FindingSeverity
	/** Markdown. */
	detail?: string
	/** True when the owner should see it even without a card. */
	flagged: boolean
	/** Card filed for this finding, when one was. */
	cardId?: string | null
}

export type ReportCardRef = {
	cardId: string
	/** Stable key from the poster (dedupes across reports while the card is open). */
	key: string
	title: string
	/** `created` by this report, or an `existing` open card the report found again. */
	relation: 'created' | 'existing'
	state: WorkItemState
	needsKent: boolean
	findingId?: string
}

export type ReportLink = { url: string; label?: string }

export type ReportPeriod = { start?: string; end?: string; label?: string }

export type FactoryReport = {
	id: string
	/** Who posted it, e.g. `ci-review`. Also the source of the cards it files. */
	source: string
	title: string
	projectId: string | null
	period: ReportPeriod | null
	/** Markdown. */
	summary: string
	findings: ReportFinding[]
	metrics: Record<string, number | string> | null
	links: ReportLink[]
	cards: ReportCardRef[]
	/** Has cards or flagged findings. Quiet reports are recorded without a push. */
	noteworthy: boolean
	createdAt: string
	idempotencyKey: string | null
	push: { sent: number; skipped?: string } | null
}

export type ReportCardSpec = {
	/** Stable key for this piece of work (for example an opportunity id). */
	key: string
	title: string
	/** Markdown brief for whoever picks the card up. */
	body?: string
	priority?: WorkItemPriority
	/** True for a decision or recommendation for the owner: the card waits in Needs you and no agent starts on it. */
	needsKent?: boolean
	labels?: string[]
	repoRef?: string
	/** Finding this card comes from. */
	findingId?: string
}

export type PostReportInput = {
	source: string
	title: string
	/** Factory project for the cards. Required when `cards` is not empty. */
	projectId?: string
	period?: ReportPeriod
	/** Markdown summary. */
	summary: string
	findings?: Array<Partial<ReportFinding> & { title: string }>
	cards?: ReportCardSpec[]
	metrics?: Record<string, number | string>
	links?: Array<ReportLink | string>
	/** Same key from the same source returns the first report instead of posting twice. */
	idempotencyKey?: string
	/** Default true: push when the report files new cards or has flagged findings. */
	notify?: boolean
	/** Validate and return the report and cards it would file. Writes nothing. */
	dryRun?: boolean
}

const NAME = 'reports/post'

function str(v: unknown, max: number): string | undefined {
	if (typeof v !== 'string') return undefined
	const t = v.trim()
	return t ? t.slice(0, max) : undefined
}

export function httpsUrl(v: unknown): string | undefined {
	const s = str(v, 500)
	if (!s) return undefined
	try {
		const u = new URL(s)
		return u.protocol === 'https:' ? u.toString() : undefined
	} catch {
		return undefined
	}
}

const SLUG_RE = /^[a-z0-9][a-z0-9._-]{0,59}$/
const KEY_RE = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,159}$/

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

export type NormalizedReportInput = {
	source: string
	title: string
	projectId: string | null
	period: ReportPeriod | null
	summary: string
	findings: ReportFinding[]
	cards: Array<Required<Pick<ReportCardSpec, 'key' | 'title'>> & ReportCardSpec & { body: string; labels: string[]; needsKent: boolean; priority: WorkItemPriority }>
	metrics: Record<string, number | string> | null
	links: ReportLink[]
	idempotencyKey: string | null
	notify: boolean
	dryRun: boolean
}

/** Validate and clip a post. Throws a readable error for bad input. */
export function normalizeReportInput(input: PostReportInput): NormalizedReportInput {
	if (!input || typeof input !== 'object') throw new Error(`${NAME}: input is required`)
	const source = str(input.source, REPORT_LIMITS.source)?.toLowerCase()
	if (!source || !SLUG_RE.test(source)) throw new Error(`${NAME}: source must be a short slug like "ci-review"`)
	const title = str(input.title, REPORT_LIMITS.title)
	if (!title) throw new Error(`${NAME}: title is required`)
	const summary = str(input.summary, REPORT_LIMITS.summary)
	if (!summary) throw new Error(`${NAME}: summary is required`)
	const projectId = str(input.projectId, 80) ?? null

	let period: ReportPeriod | null = null
	if (input.period && typeof input.period === 'object') {
		const p: ReportPeriod = {}
		const start = str(input.period.start, 40)
		const end = str(input.period.end, 40)
		const label = str(input.period.label, 80)
		if (start) p.start = start
		if (end) p.end = end
		if (label) p.label = label
		period = Object.keys(p).length ? p : null
	}

	const rawFindings = Array.isArray(input.findings) ? input.findings : []
	if (rawFindings.length > REPORT_LIMITS.findings) throw new Error(`${NAME}: at most ${REPORT_LIMITS.findings} findings`)
	const seenFindings = new Set<string>()
	const findings: ReportFinding[] = rawFindings.map((f, index) => {
		const ftitle = str(f?.title, REPORT_LIMITS.findingTitle)
		if (!ftitle) throw new Error(`${NAME}: findings[${index}].title is required`)
		const id = str(f.id, 160) ?? `f${index + 1}`
		if (!KEY_RE.test(id)) throw new Error(`${NAME}: findings[${index}].id has unsupported characters`)
		if (seenFindings.has(id)) throw new Error(`${NAME}: duplicate finding id ${id}`)
		seenFindings.add(id)
		const severity = (FINDING_SEVERITIES as readonly string[]).includes(String(f.severity)) ? (f.severity as FindingSeverity) : 'info'
		const detail = str(f.detail, REPORT_LIMITS.findingDetail)
		return {
			id,
			title: ftitle,
			severity,
			...(detail ? { detail } : {}),
			flagged: f.flagged === true || severity === 'critical',
			cardId: null,
		}
	})

	const rawCards = Array.isArray(input.cards) ? input.cards : []
	if (rawCards.length > REPORT_LIMITS.cards) throw new Error(`${NAME}: at most ${REPORT_LIMITS.cards} cards per report`)
	if (rawCards.length && !projectId) throw new Error(`${NAME}: projectId is required when the report files cards`)
	const seenKeys = new Set<string>()
	const cards = rawCards.map((c, index) => {
		const key = str(c?.key, 160)
		if (!key || !KEY_RE.test(key)) throw new Error(`${NAME}: cards[${index}].key is required (letters, digits, . _ : / -)`)
		if (seenKeys.has(key)) throw new Error(`${NAME}: duplicate card key ${key}`)
		seenKeys.add(key)
		const ctitle = str(c.title, REPORT_LIMITS.cardTitle)
		if (!ctitle) throw new Error(`${NAME}: cards[${index}].title is required`)
		const priority = c.priority === 0 || c.priority === 1 || c.priority === 2 || c.priority === 3 ? c.priority : null
		const findingId = str(c.findingId, 160)
		if (findingId && !seenFindings.has(findingId)) throw new Error(`${NAME}: cards[${index}].findingId ${findingId} is not a finding in this report`)
		const labels = (Array.isArray(c.labels) ? c.labels : [])
			.filter((l): l is string => typeof l === 'string')
			.map((l) => l.trim().slice(0, 60))
			.filter(Boolean)
			.slice(0, REPORT_LIMITS.cardLabels)
		const repoRef = str(c.repoRef, 200)
		return {
			key,
			title: ctitle,
			body: str(c.body, REPORT_LIMITS.cardBody) ?? '',
			priority,
			needsKent: c.needsKent === true,
			labels,
			...(repoRef ? { repoRef } : {}),
			...(findingId ? { findingId } : {}),
		}
	})

	let metrics: Record<string, number | string> | null = null
	if (input.metrics && typeof input.metrics === 'object' && !Array.isArray(input.metrics)) {
		const entries = Object.entries(input.metrics)
			.filter(([k, v]) => typeof k === 'string' && k.length <= 60 && ((typeof v === 'number' && Number.isFinite(v)) || typeof v === 'string'))
			.slice(0, REPORT_LIMITS.metrics)
			.map(([k, v]) => [k, typeof v === 'string' ? v.slice(0, 120) : v] as const)
		metrics = entries.length ? Object.fromEntries(entries) : null
	}

	const links = (Array.isArray(input.links) ? input.links : [])
		.slice(0, REPORT_LIMITS.links)
		.map((l) => (typeof l === 'string' ? { url: httpsUrl(l) } : { url: httpsUrl(l?.url), label: str(l?.label, 80) }))
		.filter((l): l is { url: string; label?: string } => !!l.url)
		.map((l) => (l.label ? { url: l.url, label: l.label } : { url: l.url }))

	const idem = typeof input.idempotencyKey === 'string' ? input.idempotencyKey.trim() : ''
	if (idem && !KEY_RE.test(idem)) throw new Error(`${NAME}: invalid idempotencyKey`)

	return {
		source,
		title,
		projectId,
		period,
		summary,
		findings,
		cards,
		metrics,
		links,
		idempotencyKey: idem || null,
		notify: input.notify !== false,
		dryRun: input.dryRun === true,
	}
}

/** Noteworthy: files or links cards, or has a flagged finding. */
export function isNoteworthy(report: Pick<FactoryReport, 'cards' | 'findings'>): boolean {
	return report.cards.length > 0 || report.findings.some((f) => f.flagged)
}

/** Push only when there is something new for the owner: a new card or a flagged finding. Repeat sightings of open cards stay quiet. */
export function shouldPushReport(report: Pick<FactoryReport, 'cards' | 'findings'>): boolean {
	return report.cards.some((c) => c.relation === 'created') || report.findings.some((f) => f.flagged)
}

/** Short push text: `2 new cards (1 needs you) · 1 flagged finding`. */
export function reportPushBody(report: Pick<FactoryReport, 'cards' | 'findings' | 'summary'>): string {
	const created = report.cards.filter((c) => c.relation === 'created')
	const needsYou = created.filter((c) => c.needsKent).length
	const flagged = report.findings.filter((f) => f.flagged).length
	const parts: string[] = []
	if (created.length) parts.push(`${created.length} new card${created.length === 1 ? '' : 's'}${needsYou ? ` (${needsYou} need${needsYou === 1 ? 's' : ''} you)` : ''}`)
	if (flagged) parts.push(`${flagged} flagged finding${flagged === 1 ? '' : 's'}`)
	const lead = report.summary.replace(/[#*_`>]/g, '').replace(/\s+/g, ' ').trim()
	return [parts.join(' · '), lead].filter(Boolean).join(' · ').slice(0, 240)
}

export function reportPath(reportId: string): string {
	return `/reports/${encodeURIComponent(reportId)}`
}

export type ReportStore = { version: 1; reports: Record<string, FactoryReport> }

export function emptyReportStore(): ReportStore {
	return { version: 1, reports: {} }
}

/** Newest first. */
export function sortedReports(store: ReportStore): FactoryReport[] {
	return Object.values(store.reports).sort((a, b) => b.createdAt.localeCompare(a.createdAt))
}

/** Keep the newest `REPORT_LIMITS.stored` reports. Returns a new store. */
export function pruneReports(store: ReportStore, keep: number = REPORT_LIMITS.stored): ReportStore {
	const kept = sortedReports(store).slice(0, keep)
	return { version: 1, reports: Object.fromEntries(kept.map((r) => [r.id, r])) }
}