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

board.ts

383 lines · 11.7 KB · TypeScript
/**
 * Board column mapping for the ship pipeline kanban.
 * One pure function maps a work item to its board column, entry time, and
 * in-review substate. No side effects, no imports from kody:runtime.
 */
import type { WorkItem } from './work-item.ts'
import { sessionUrlFor } from '../adapters/agent/session-url.ts'
import type { RunnerSettings } from '../adapters/agent/runners.ts'
import { ACTIVE_WATCH, type PostMergePhase } from './post-merge.ts'
import type { Plan, PlanStatus } from './plan.ts'

export const BOARD_COLUMNS = [
	'intake',
	'triaged',
	'planned',
	'running',
	'in-review',
	'watching-main',
	'shipped',
	'needs-kent',
	'dropped',
] as const
export type BoardColumn = (typeof BOARD_COLUMNS)[number]

export const PLAN_COLUMNS = ['exploring', 'proposed', 'decided', 'in-progress', 'shipped'] as const
export type PlanColumn = (typeof PLAN_COLUMNS)[number]

export const BOARD_COLUMN_LABELS: Record<BoardColumn, string> = {
	intake: 'Intake',
	triaged: 'Triaged',
	planned: 'Planned',
	running: 'Running',
	'in-review': 'In review',
	'watching-main': 'Watching main',
	shipped: 'Shipped',
	'needs-kent': 'Needs Kent',
	dropped: 'Dropped',
}

export type ReviewSubstate =
	| 'waiting'
	| 'needs_attention'
	| 'action_available'
	| 'ready_to_merge'
	| 'done'
	| 'blocked'

export type WatchSubstate = PostMergePhase

export type BoardCard = {
	id: string
	kind: 'work'
	column: BoardColumn
	title: string
	priority: number | null
	projectId: string
	repoRef: string | null
	source: string
	prNumber: number | null
	prUrl: string | null
	reviewSubstate: ReviewSubstate | null
	watchSubstate: WatchSubstate | null
	runId: string | null
	sessionUrl: string | null
	claimedBy: string | null
	claimExpiresAt: string | null
	enteredColumnAt: string
	ageMs: number
	limitMs: number
	stalled: boolean
	stalledBy: number
	shipPr?: { status: string; at: string; note?: string }
	categoryGuess?: string | null
	categoryConfirmed?: string | null
	categoryConfirmedBy?: string | null
}

export type PlanCard = {
	id: string
	kind: 'plan'
	column: PlanColumn
	title: string
	priority: number | null
	projectId: string
	linkedWorkCount: number
	enteredColumnAt: string
	ageMs: number
	limitMs: number
	stalled: boolean
	stalledBy: number
	archived: boolean
}

export type ColumnTimeLimits = {
	intake: number
	triaged: number
	planned: number
	running: number
	'in-review': number
	'watching-main': number
	'needs-kent': number
	exploring: number
	proposed: number
	decided: number
	'in-progress': number
}

export function defaultColumnTimeLimits(): ColumnTimeLimits {
	const H = 60 * 60_000
	const D = 24 * H
	return {
		intake: 2 * H,
		triaged: 4 * H,
		planned: 24 * H,
		running: 6 * H,
		'in-review': 24 * H,
		'watching-main': 3 * H,
		'needs-kent': 48 * H,
		exploring: 30 * D,
		proposed: 14 * D,
		decided: 14 * D,
		'in-progress': 21 * D,
	}
}

/** Determine the board column for a work item. */
export function boardColumnFor(item: WorkItem): BoardColumn {
	if (item.state === 'dropped') return 'dropped'
	if (item.state === 'needs-kent') return 'needs-kent'

	if (item.state === 'shipped') {
		if (item.postMerge && ACTIVE_WATCH.has(item.postMerge.phase)) return 'watching-main'
		return 'shipped'
	}

	if (item.state === 'verifying') {
		if (item.pr && !item.pr.merged) return 'in-review'
		return 'in-review'
	}

	if (item.state === 'running') {
		if (item.pr && !item.pr.merged) return 'in-review'
		return 'running'
	}

	if (item.state === 'planned') return 'planned'
	if (item.state === 'triaged') return 'triaged'
	return 'intake'
}

/** Derive in-review substate from PR data. Mirrors ship-pr tick exit statuses. */
export function reviewSubstateFor(item: WorkItem): ReviewSubstate | null {
	const pr = item.pr
	if (!pr || pr.merged) return null

	const gh = pr.github
	if (!gh) {
		if (pr.reviewState === 'approved' && pr.ready) return 'ready_to_merge'
		if (pr.reviewState === 'changes_requested') return 'needs_attention'
		return 'waiting'
	}

	if (gh.checks === 'failure') return gh.merged ? 'done' : 'needs_attention'
	if (gh.checks === 'pending') return 'waiting'

	if (pr.reviewState === 'approved' && pr.ready) return 'ready_to_merge'
	if (pr.reviewState === 'changes_requested') return 'needs_attention'
	if (pr.reviewState === 'pending' || pr.reviewState === 'none') {
		if (gh.checks === 'success') return 'action_available'
		return 'waiting'
	}

	return 'waiting'
}

/**
 * Find when the item entered its current board column by scanning events.
 * Falls back to createdAt for intake items without events.
 */
export function columnEntryTime(item: WorkItem, column: BoardColumn): string {
	if (column === 'watching-main' && item.postMerge?.startedAt) {
		return item.postMerge.startedAt
	}

	if (column === 'in-review' && item.pr) {
		const prLinked = item.pr.updatedAt
		const lastRunEvent = findLastEventTo(item, 'running')
		const lastVerifyEvent = findLastEventTo(item, 'verifying')
		const candidates = [prLinked, lastRunEvent, lastVerifyEvent].filter(Boolean) as string[]
		if (candidates.length) return candidates.sort()[0]!
	}

	const stateForColumn = columnToStates(column)
	for (let i = item.events.length - 1; i >= 0; i--) {
		const e = item.events[i]!
		if (stateForColumn.has(e.to)) {
			if (i === 0 || !stateForColumn.has(item.events[i - 1]?.to ?? '')) {
				return e.at
			}
		}
	}

	return item.createdAt
}

function findLastEventTo(item: WorkItem, state: string): string | null {
	for (let i = item.events.length - 1; i >= 0; i--) {
		if (item.events[i]!.to === state) return item.events[i]!.at
	}
	return null
}

function columnToStates(col: BoardColumn): Set<string> {
	switch (col) {
		case 'intake': return new Set(['intake'])
		case 'triaged': return new Set(['triaged'])
		case 'planned': return new Set(['planned'])
		case 'running': return new Set(['running'])
		case 'in-review': return new Set(['running', 'verifying'])
		case 'watching-main': return new Set(['shipped'])
		case 'shipped': return new Set(['shipped'])
		case 'needs-kent': return new Set(['needs-kent'])
		case 'dropped': return new Set(['dropped'])
	}
}

/** Compute stall info for a card. */
export function stallInfo(ageMs: number, limitMs: number): { stalled: boolean; stalledBy: number; warm: boolean } {
	if (limitMs <= 0) return { stalled: false, stalledBy: 0, warm: false }
	const ratio = ageMs / limitMs
	return {
		stalled: ratio >= 1,
		stalledBy: Math.max(0, ageMs - limitMs),
		warm: ratio >= 0.75 && ratio < 1,
	}
}

/** Build a board card from a work item. */
export function toBoardCard(item: WorkItem, limits: ColumnTimeLimits, now: number, claim?: { agent: string; expiresAt: string } | null, runners?: RunnerSettings): BoardCard {
	const column = boardColumnFor(item)
	const enteredAt = columnEntryTime(item, column)
	const ageMs = Math.max(0, now - Date.parse(enteredAt))
	const limitMs = limits[column as keyof ColumnTimeLimits] ?? 0
	const { stalled, stalledBy } = stallInfo(ageMs, limitMs)
	const reviewSub = column === 'in-review' ? reviewSubstateFor(item) : null
	const watchSub = column === 'watching-main' ? (item.postMerge?.phase ?? null) : null

	// The runner decides the link (its start URL, else its sessionUrlTemplate).
	const sessionUrl = sessionUrlFor(item, runners)

	return {
		id: item.id,
		kind: 'work',
		column,
		title: item.title,
		priority: item.priority,
		projectId: item.projectId,
		repoRef: item.repoRef,
		source: item.source,
		prNumber: item.pr?.number ?? null,
		prUrl: item.pr?.url ?? null,
		reviewSubstate: reviewSub,
		watchSubstate: watchSub,
		runId: item.runId,
		sessionUrl,
		claimedBy: claim?.agent ?? null,
		claimExpiresAt: claim?.expiresAt ?? null,
		enteredColumnAt: enteredAt,
		ageMs,
		limitMs,
		stalled,
		stalledBy,
		shipPr: (item as WorkItem & { shipPr?: BoardCard['shipPr'] }).shipPr,
		categoryGuess: item.categoryGuess ?? null,
		categoryConfirmed: item.categoryConfirmed ?? null,
		categoryConfirmedBy: item.categoryConfirmedBy ?? null,
	}
}

/** Build a plan card. */
export function toPlanCard(plan: Plan, limits: ColumnTimeLimits, now: number): PlanCard {
	const column = plan.status as PlanColumn
	const enteredAt = plan.statusChangedAt
	const ageMs = Math.max(0, now - Date.parse(enteredAt))
	const limitMs = limits[column as keyof ColumnTimeLimits] ?? 0
	const { stalled, stalledBy } = stallInfo(ageMs, limitMs)

	return {
		id: plan.id,
		kind: 'plan',
		column,
		title: plan.title,
		priority: plan.priority,
		projectId: plan.projectId,
		linkedWorkCount: plan.workItemIds.length,
		enteredColumnAt: enteredAt,
		ageMs,
		limitMs,
		stalled,
		stalledBy,
		archived: plan.archived,
	}
}

/** Format age as human readable. */
export function formatAge(ms: number): string {
	if (ms < 60_000) return 'just now'
	const m = Math.floor(ms / 60_000)
	if (m < 60) return `${m}m`
	const h = Math.floor(m / 60)
	const rm = m % 60
	if (h < 24) return rm ? `${h}h ${rm}m` : `${h}h`
	const d = Math.floor(h / 24)
	const rh = h % 24
	return rh ? `${d}d ${rh}h` : `${d}d`
}

/** Suggested next action for a stalled card. */
export function suggestAction(card: BoardCard): string {
	switch (card.column) {
		case 'intake': return 'waiting for triage; run sweep or triage manually'
		case 'triaged': return 'waiting to be planned; check priority and plan'
		case 'planned': return 'queued for an agent; check concurrency and scope'
		case 'running':
			if (card.sessionUrl) return `running ${formatAge(card.ageMs)}, session may be idle: check the session`
			return `running ${formatAge(card.ageMs)} with no session link`
		case 'in-review':
			if (card.reviewSubstate === 'needs_attention') return 'CI failing or changes requested: run ship-pr tick'
			if (card.reviewSubstate === 'ready_to_merge') return 'ready to merge: merge the PR'
			if (card.reviewSubstate === 'action_available') return 'CI green, review pending: review the PR'
			return `in review ${formatAge(card.ageMs)}: check PR status`
		case 'watching-main':
			if (card.watchSubstate === 'implementer-notified') return 'implementer was asked to fix main; waiting on the fix'
			return 'watching main CI after merge'
		case 'needs-kent': return `needs Kent for ${formatAge(card.ageMs)}: make a decision`
		default: return ''
	}
}

/** Suggested action for a stalled plan. */
export function suggestPlanAction(card: PlanCard): string {
	switch (card.column) {
		case 'exploring': return `exploring for ${formatAge(card.ageMs)}: decide or archive`
		case 'proposed': return `proposed for ${formatAge(card.ageMs)}: decide or deprioritize`
		case 'decided': return `decided ${formatAge(card.ageMs)} ago but not started: create work items`
		case 'in-progress': return `in progress for ${formatAge(card.ageMs)}: check linked work`
		default: return ''
	}
}

/** Valid board column transitions for work items via move-card. */
const VALID_MOVES: Partial<Record<BoardColumn, BoardColumn[]>> = {
	intake: ['triaged', 'needs-kent', 'dropped'],
	triaged: ['planned', 'needs-kent', 'dropped'],
	planned: ['needs-kent', 'dropped'],
	'needs-kent': ['intake', 'triaged', 'planned', 'dropped'],
	dropped: ['intake'],
}

/** Check if a move is allowed. Returns null if valid, or a reason string if not. */
export function validateMove(from: BoardColumn, to: BoardColumn): string | null {
	if (from === to) return 'already in that column'
	const allowed = VALID_MOVES[from]
	if (!allowed || !allowed.includes(to)) {
		return `cannot move from ${BOARD_COLUMN_LABELS[from]} to ${BOARD_COLUMN_LABELS[to]}; that transition is managed by the sweep`
	}
	return null
}

/** Map board column back to work item state for a move. */
export function columnToState(col: BoardColumn): string {
	switch (col) {
		case 'intake': return 'intake'
		case 'triaged': return 'triaged'
		case 'planned': return 'planned'
		case 'running': return 'running'
		case 'in-review': return 'running'
		case 'watching-main': return 'shipped'
		case 'shipped': return 'shipped'
		case 'needs-kent': return 'needs-kent'
		case 'dropped': return 'dropped'
	}
}