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

flow-metrics.ts

218 lines · 6.5 KB · TypeScript
/**
 * Flow metrics: pure functions that compute throughput, cycle time, column
 * dwell times, and activity timelines from WorkItem arrays. No kody:runtime,
 * no side effects, no storage.
 */
import type { WorkItem, WorkItemEvent } from './work-item.ts'
import { boardColumnFor, BOARD_COLUMNS, BOARD_COLUMN_LABELS, type BoardColumn } from './board.ts'

const MT = 'America/Denver'
const DAY_MS = 86_400_000

function dateInMT(ms: number): string {
	return new Intl.DateTimeFormat('en-CA', { timeZone: MT }).format(new Date(ms))
}

function median(sorted: number[]): number | null {
	if (!sorted.length) return null
	const mid = sorted.length >> 1
	return sorted.length % 2 ? sorted[mid]! : (sorted[mid - 1]! + sorted[mid]!) / 2
}

function p90(sorted: number[]): number | null {
	if (!sorted.length) return null
	return sorted[Math.ceil(0.9 * sorted.length) - 1]!
}

function firstEventTo(events: WorkItemEvent[], state: string): WorkItemEvent | undefined {
	return events.find((e) => e.to === state)
}

function lastEventTo(events: WorkItemEvent[], state: string): WorkItemEvent | undefined {
	for (let i = events.length - 1; i >= 0; i--) {
		if (events[i]!.to === state) return events[i]
	}
	return undefined
}

export function throughputByDay(
	items: WorkItem[],
	days = 14,
	now = Date.now(),
): Array<{ date: string; shipped: number; dropped: number; advanced: number }> {
	const buckets: Record<string, { shipped: number; dropped: number; advanced: number }> = {}
	const dates: string[] = []
	for (let d = days - 1; d >= 0; d--) {
		const dt = dateInMT(now - d * DAY_MS)
		dates.push(dt)
		buckets[dt] = { shipped: 0, dropped: 0, advanced: 0 }
	}
	const startDate = dates[0]!

	for (const item of items) {
		for (const e of item.events) {
			const eDate = dateInMT(Date.parse(e.at))
			if (eDate < startDate || !buckets[eDate]) continue
			if (e.to === 'shipped') buckets[eDate]!.shipped++
			else if (e.to === 'dropped') buckets[eDate]!.dropped++
			if (e.from !== null && e.from !== e.to) buckets[eDate]!.advanced++
		}
	}

	return dates.map((dt) => ({ date: dt, ...buckets[dt]! }))
}

export function cycleTime(items: WorkItem[]): { medianMs: number | null; p90Ms: number | null; sample: number; raw: number[] } {
	const raw: number[] = []

	for (const item of items) {
		const planned = firstEventTo(item.events, 'planned')
		if (!planned) continue
		const start = Date.parse(planned.at)

		let end: number | undefined
		if (item.pr?.merged?.at) {
			end = Date.parse(item.pr.merged.at)
		} else {
			const shipped = firstEventTo(item.events, 'shipped')
			if (shipped) end = Date.parse(shipped.at)
		}
		if (end === undefined || !isFinite(end) || !isFinite(start)) continue
		const ms = end - start
		if (ms >= 0) raw.push(ms)
	}

	raw.sort((a, b) => a - b)
	const sample = raw.length
	return {
		medianMs: sample >= 3 ? median(raw) : null,
		p90Ms: sample >= 3 ? p90(raw) : null,
		sample,
		raw,
	}
}

export function columnTimeDistribution(
	items: WorkItem[],
): Array<{ column: string; label: string; medianMs: number | null; sample: number }> {
	const durations: Record<string, number[]> = {}
	for (const col of BOARD_COLUMNS) durations[col] = []

	for (const item of items) {
		const events = item.events
		if (!events.length) continue

		let prevCol: string | null = null
		let prevAt: number | null = null

		for (const e of events) {
			const col = e.to as string
			const at = Date.parse(e.at)
			if (prevCol && prevAt && col !== prevCol && isFinite(at) && isFinite(prevAt)) {
				const dur = at - prevAt
				if (dur >= 0 && durations[prevCol]) durations[prevCol]!.push(dur)
			}
			prevCol = col
			prevAt = at
		}
		// Do NOT include the current (still-open) column
	}

	return BOARD_COLUMNS.map((col) => {
		const vals = durations[col]!.sort((a, b) => a - b)
		return {
			column: col,
			label: BOARD_COLUMN_LABELS[col] ?? col,
			medianMs: vals.length >= 3 ? median(vals) : null,
			sample: vals.length,
		}
	})
}

export function itemsByColumn(items: WorkItem[]): Array<{ column: string; label: string; count: number }> {
	const counts: Record<BoardColumn, number> = {} as Record<BoardColumn, number>
	for (const col of BOARD_COLUMNS) counts[col] = 0

	for (const item of items) {
		const col = boardColumnFor(item)
		counts[col]++
	}

	return BOARD_COLUMNS.map((col) => ({
		column: col,
		label: BOARD_COLUMN_LABELS[col] ?? col,
		count: counts[col],
	}))
}

function eventKind(e: WorkItemEvent): string {
	const r = e.reason ?? ''
	if (r.startsWith('nudge:')) return 'Nudge'
	if (r.startsWith('ship-pr:')) return 'Ship-pr update'
	if (r.startsWith('post-merge:')) return 'Post-merge'
	if (e.to === 'shipped' && /merge/i.test(r)) return 'Merged'
	if (e.from !== null && e.from !== e.to) return 'State change'
	return 'Event'
}

function eventDetail(e: WorkItemEvent): string {
	const parts: string[] = []
	if (e.from && e.from !== e.to) parts.push(e.from + ' to ' + e.to)
	else if (e.to) parts.push(e.to)
	if (e.reason) parts.push(e.reason.slice(0, 200))
	return parts.join(': ')
}

export function recentActivity(
	items: WorkItem[],
	limit = 20,
): Array<{ at: string; itemId: string; title: string; kind: string; detail: string }> {
	const all: Array<{ at: string; itemId: string; title: string; kind: string; detail: string }> = []

	for (const item of items) {
		for (const e of item.events) {
			all.push({
				at: e.at,
				itemId: item.id,
				title: item.title,
				kind: eventKind(e),
				detail: eventDetail(e),
			})
		}
	}

	all.sort((a, b) => (a.at > b.at ? -1 : a.at < b.at ? 1 : 0))
	return all.slice(0, limit)
}

export function completedItems(
	items: WorkItem[],
	sinceDays = 30,
	now = Date.now(),
): Array<{ id: string; title: string; state: string; cycleMs: number | null; shippedAt: string }> {
	const cutoff = now - sinceDays * DAY_MS
	const result: Array<{ id: string; title: string; state: string; cycleMs: number | null; shippedAt: string }> = []

	for (const item of items) {
		if (item.state !== 'shipped' && item.state !== 'dropped') continue
		const terminal = lastEventTo(item.events, item.state)
		if (!terminal) continue
		const at = Date.parse(terminal.at)
		if (!isFinite(at) || at < cutoff) continue

		let cycleMs: number | null = null
		const planned = firstEventTo(item.events, 'planned')
		if (planned) {
			let end: number | undefined
			if (item.pr?.merged?.at) end = Date.parse(item.pr.merged.at)
			else end = at
			const start = Date.parse(planned.at)
			if (isFinite(start) && isFinite(end) && end >= start) cycleMs = end - start
		}

		result.push({ id: item.id, title: item.title, state: item.state, cycleMs, shippedAt: terminal.at })
	}

	result.sort((a, b) => (a.shippedAt > b.shippedAt ? -1 : 1))
	return result
}