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

project-detail.ts

463 lines · 16.8 KB · TypeScript
/**
 * Project detail data assembly. Loads the ledger once, computes metrics with
 * pure functions, and optionally reads live sources (Devin, runList, GitHub)
 * with strict timeouts. Each section degrades independently. No storage writes.
 */
import { loadJson, storageKeys } from '../lib/storage.ts'
import { emptyLedger, type Ledger, type WorkItem } from '../core/work-item.ts'
import { loadSettings } from '../lib/settings.ts'
import { loadProjects, type ProjectConfig } from '../projects/config.ts'
import { loadPlanStore } from '../core/plan.ts'
import { toBoardCard, type BoardCard } from '../core/board.ts'
import { inPilotScope } from '../core/scope.ts'
import { loadClaims } from '../exports/claim.ts'
import { withTimeout, selfPackageId, runList, type ListedRun } from '../health/platform.ts'
import { resolveAgentRunner } from '../adapters/agent/index.ts'
import { runSessionUrl, runnerIdOf } from '../adapters/agent/session-url.ts'
import type { RunnerSettings } from '../adapters/agent/runners.ts'
import { optionalGithubFetch } from '../lib/github-permissions.ts'
import { githubReadonlyRequest, type GithubFetch } from '../lib/github-readonly.ts'
import { memCached } from '../lib/mem-cache.ts'

type Section<T> = T | { error: string }

function err(msg: string): { error: string } { return { error: msg } }

export type SessionInfo = {
	workItemId: string
	title: string
	runId: string
	url: string | null
	state: string
	prUrl: string | null
	prNumber: number | null
	startedAt: string
	column: string
	source: 'runId' | 'link' | 'postMerge'
}

export type DevinLiveStatus = {
	runId: string
	state: string
	url: string | null
	updatedAt: string | null
}

export type RunGroup = {
	name: string
	surface: string
	total: number
	errors: number
	skipped: number
	lastAt: string | null
	lastStatus: string | null
	lastError: string | null
	attribution: 'factory-wide' | 'repo-specific'
	projectId: string | null
	repoRef: string | null
}

export type RunsSummary = {
	groups: RunGroup[]
	deploys: Array<{ id: string; at: string; commit: string | null; status: string }>
	total24h: number
	errors24h: number
	total7d: number
	errors7d: number
	delivered24h: number
	byDay: Array<{ date: string; total: number; errors: number; deliveries: number }>
}

export type PrInfo = {
	url: string
	number: number | null
	state: string
	checks: string
	reviewState: string
	ready: boolean
	itemId: string
	title: string
}

export type MainCiInfo = {
	repo: string
	status: string
	checkedAt: string
}

type FlowMetrics = typeof import('../core/flow-metrics.ts')

let _flowMod: FlowMetrics | null = null
async function flowMod(): Promise<FlowMetrics> {
	if (!_flowMod) _flowMod = await import('../core/flow-metrics.ts')
	return _flowMod
}

export type ProjectOverview = {
	project: ProjectConfig
	inPilotScope: boolean
	agents: Section<{
		sessions: SessionInfo[]
		devinLive: DevinLiveStatus[] | { error: string }
		t3Note: string
	}>
	runs: Section<RunsSummary>
	flow: {
		throughput: Array<{ date: string; shipped: number; dropped: number; advanced: number }>
		cycleTime: { medianMs: number | null; p90Ms: number | null; sample: number }
		columnTimes: Array<{ column: string; label: string; medianMs: number | null; sample: number }>
		stalls: BoardCard[]
		byColumn: Array<{ column: string; label: string; count: number }>
		recentActivity: Array<{ at: string; itemId: string; title: string; kind: string; detail: string }>
		linkedPlans: Array<{ id: string; title: string; status: string; priority: number | null }>
		completed: Array<{ id: string; title: string; state: string; cycleMs: number | null; shippedAt: string }>
	}
	prs: {
		open: PrInfo[]
		mainCi: Section<MainCiInfo> | null
		postMergeWatches: Array<{ itemId: string; title: string; phase: string; startedAt: string }>
	}
	generatedAt: string
}

function sessionKey(id: string): string {
	return id.replace(/^devin-/, '').split('/').pop() ?? id
}

function extractSessions(items: WorkItem[], boardCards: BoardCard[], runners?: RunnerSettings, defaultRunnerId = 'devin'): SessionInfo[] {
	const cardMap = new Map<string, BoardCard>()
	for (const c of boardCards) cardMap.set(c.id, c)

	const sessions: SessionInfo[] = []
	const seen = new Set<string>()

	for (const item of items) {
		const card = cardMap.get(item.id)
		const runId = item.runId
		if (runId && !/dry|noop/.test(runId)) {
			const key = sessionKey(runId)
			if (!seen.has(key)) {
				seen.add(key)
				sessions.push({
					workItemId: item.id, title: item.title, runId,
					url: runSessionUrl(runId, runnerIdOf(item, defaultRunnerId), runners, item.links) ?? '',
					state: item.state, prUrl: item.pr?.url ?? null, prNumber: item.pr?.number ?? null,
					startedAt: item.events.find((e) => e.to === 'running')?.at ?? item.updatedAt,
					column: card?.column ?? item.state, source: 'runId',
				})
			}
		}
		if (item.postMerge?.implementerRunId) {
			const key = sessionKey(item.postMerge.implementerRunId)
			if (!seen.has(key)) {
				seen.add(key)
				sessions.push({
					workItemId: item.id, title: item.title,
					runId: item.postMerge.implementerRunId,
					url: runSessionUrl(item.postMerge.implementerRunId, runnerIdOf({ events: item.events, runId: item.postMerge.implementerRunId }, defaultRunnerId), runners, item.links) ?? '',
					state: 'post-merge', prUrl: item.pr?.url ?? null, prNumber: item.pr?.number ?? null,
					startedAt: item.postMerge.startedAt, column: card?.column ?? 'watching-main', source: 'postMerge',
				})
			}
		}
		for (const link of item.links ?? []) {
			if (link.kind === 'session' && link.url) {
				const linkId = link.url.split('/').pop() ?? ''
				const key = sessionKey(linkId)
				if (!seen.has(key)) {
					seen.add(key)
					sessions.push({
						workItemId: item.id, title: item.title,
						runId: linkId, url: link.url, state: item.state,
						prUrl: item.pr?.url ?? null, prNumber: item.pr?.number ?? null,
						startedAt: link.at, column: card?.column ?? item.state, source: 'link',
					})
				}
			}
		}
	}
	sessions.sort((a, b) => b.startedAt.localeCompare(a.startedAt))
	return sessions.slice(0, 20)
}

async function fetchDevinLive(sessions: SessionInfo[], projectConfig: ProjectConfig): Promise<DevinLiveStatus[] | { error: string }> {
	const runnerId = projectConfig.defaultRunnerId ?? 'devin'
	const runner = (await resolveAgentRunner(runnerId)) ?? (await resolveAgentRunner('devin'))
	if (!runner) return err('No agent runner configured')

	const recent = sessions.filter((s) => s.state === 'running' || s.state === 'post-merge' || s.state === 'verifying').slice(0, 5)
	if (!recent.length) return []

	const cacheKey = 'devin-live:' + projectConfig.id
	const cached = await memCached(cacheKey, 60_000, async () => {
		const results: DevinLiveStatus[] = []
		for (const s of recent) {
			try {
				const status = await withTimeout(runner.status(s.runId), 5_000, null)
				if (status) {
					results.push({ runId: s.runId, state: status.state, url: status.url ?? null, updatedAt: status.updatedAt ?? null })
				}
			} catch { /* skip individual failures */ }
		}
		return results
	})
	return cached
}

function redactError(raw: string | null | undefined): string {
	if (!raw) return ''
	return String(raw).replace(/\?[^\s)}\]"']*/g, '?...').slice(0, 160)
}

type AnyRun = ListedRun & Record<string, unknown>

function runMeta(r: AnyRun): { repoRef: string | null; projectId: string | null; skipped: boolean } {
	const meta = (r.metadata && typeof r.metadata === 'object' ? r.metadata : {}) as Record<string, unknown>
	const result = (meta.result && typeof meta.result === 'object' ? meta.result : {}) as Record<string, unknown>
	const repoRef = typeof result.repoRef === 'string' ? result.repoRef : (typeof meta.repoRef === 'string' ? meta.repoRef : null)
	const projectId = typeof result.projectId === 'string' ? result.projectId : (typeof meta.projectId === 'string' ? meta.projectId : null)
	const skipped = typeof result.reason === 'string' && /^ignored|^skipped/i.test(result.reason)
	return { repoRef, projectId, skipped }
}

function processRuns(allRuns: AnyRun[], projectRepoRefs: Set<string>) {
	const EXCLUDE_SURFACES = new Set(['app_fetch', 'export'])
	const gm = new Map<string, RunGroup>()
	const byDay = new Map<string, { total: number; errors: number; deliveries: number }>()
	const deploys: RunsSummary['deploys'] = []

	const automationRuns: AnyRun[] = []
	for (const r of allRuns) {
		const surface = String(r.surface ?? '')
		if (EXCLUDE_SURFACES.has(surface)) continue
		if (surface === 'workflow') {
			deploys.push({
				id: r.id,
				at: r.finished_at ?? r.started_at ?? '',
				commit: typeof r.published_commit === 'string' ? r.published_commit.slice(0, 12) : null,
				status: r.status ?? 'unknown',
			})
			continue
		}
		automationRuns.push(r)
	}

	for (const r of automationRuns) {
		const name = r.name || 'unnamed'
		const surface = String(r.surface ?? '')
		const rm = runMeta(r)
		const isRepoSpecific = rm.repoRef ? projectRepoRefs.has(rm.repoRef.toLowerCase()) : false
		const attribution: 'factory-wide' | 'repo-specific' = isRepoSpecific ? 'repo-specific' : 'factory-wide'

		const key = name + ':' + surface
		const g = gm.get(key) ?? { name, surface, total: 0, errors: 0, skipped: 0, lastAt: null, lastStatus: null, lastError: null, attribution, projectId: rm.projectId, repoRef: rm.repoRef }
		g.total++
		if (rm.skipped) g.skipped++
		if (r.status === 'error') {
			g.errors++
			const errMsg = redactError(r.error_message as string | undefined) || redactError(r.error_name as string | undefined) || 'error'
			g.lastError = errMsg
		}
		const at = r.finished_at ?? r.started_at ?? null
		if (at && (!g.lastAt || at > g.lastAt)) { g.lastAt = at; g.lastStatus = r.status ?? null }
		if (isRepoSpecific) { g.attribution = 'repo-specific'; g.repoRef = rm.repoRef }
		gm.set(key, g)

		if (at) {
			const day = at.slice(0, 10)
			const d = byDay.get(day) ?? { total: 0, errors: 0, deliveries: 0 }
			d.total++
			if (r.status === 'error') d.errors++
			if (surface === 'webhook') d.deliveries++
			byDay.set(day, d)
		}
	}

	return {
		groups: [...gm.values()].sort((a, b) => a.name.localeCompare(b.name)),
		deploys: deploys.sort((a, b) => b.at.localeCompare(a.at)).slice(0, 5),
		byDay,
		automationRuns,
	}
}

async function fetchRuns(repoRefs: Set<string>): Promise<Section<RunsSummary>> {
	const cacheKey = 'package-runs'
	try {
		return await memCached(cacheKey, 60_000, async () => {
			const self = selfPackageId()
			if (!self) return err('Package ID not available')
			const page1 = await withTimeout(runList({ package_id: self, error_triage: 'all', limit: 100 }), 5_000, null)
			if (!page1) return err('Run list timed out')
			let allRuns = page1.runs as AnyRun[]
			if (page1.next_cursor) {
				const page2 = await withTimeout(runList({ package_id: self, error_triage: 'all', limit: 100, cursor: page1.next_cursor }), 5_000, null)
				if (page2) allRuns = allRuns.concat(page2.runs as AnyRun[])
			}
			const { groups, deploys, byDay, automationRuns } = processRuns(allRuns, repoRefs)

			const now = Date.now()
			const d1 = now - 24 * 60 * 60_000
			const d7 = now - 7 * 24 * 60 * 60_000
			let total24h = 0, errors24h = 0, total7d = 0, errors7d = 0, delivered24h = 0
			for (const r of automationRuns) {
				const at = r.finished_at ?? r.started_at ?? undefined
				if (!at) continue
				const t = Date.parse(at)
				if (t >= d1) { total24h++; if (r.status === 'error') errors24h++; if (String(r.surface) === 'webhook') delivered24h++ }
				if (t >= d7) { total7d++; if (r.status === 'error') errors7d++ }
			}

			const days: RunsSummary['byDay'] = []
			for (let i = 6; i >= 0; i--) {
				const d = new Date(now - i * 24 * 60 * 60_000).toISOString().slice(0, 10)
				const entry = byDay.get(d)
				days.push({ date: d, total: entry?.total ?? 0, errors: entry?.errors ?? 0, deliveries: entry?.deliveries ?? 0 })
			}

			return { groups, deploys, total24h, errors24h, total7d, errors7d, delivered24h, byDay: days } as RunsSummary
		})
	} catch (e) {
		return err(e instanceof Error ? e.message : String(e))
	}
}

function extractPrs(items: WorkItem[]): PrInfo[] {
	return items
		.filter((i) => i.pr && !i.pr.merged && (i.state === 'running' || i.state === 'verifying'))
		.map((i) => ({
			url: i.pr!.url,
			number: i.pr!.number,
			state: i.pr!.github?.state ?? 'open',
			checks: i.pr!.github?.checks ?? 'unknown',
			reviewState: i.pr!.reviewState,
			ready: i.pr!.ready,
			itemId: i.id,
			title: i.title,
		}))
}

function extractPostMergeWatches(items: WorkItem[]): Array<{ itemId: string; title: string; phase: string; startedAt: string }> {
	return items
		.filter((i) => i.postMerge && (i.postMerge.phase === 'watching' || i.postMerge.phase === 'implementer-notified'))
		.map((i) => ({ itemId: i.id, title: i.title, phase: i.postMerge!.phase, startedAt: i.postMerge!.startedAt }))
}

async function fetchMainCi(repoRef: string | null, inScope: boolean): Promise<Section<MainCiInfo> | null> {
	if (!repoRef) return null
	const cacheKey = 'main-ci:' + repoRef
	try {
		return await memCached(cacheKey, 150_000, async () => {
			let gh: GithubFetch | null = null
			try { gh = await optionalGithubFetch() } catch {
				return err('Main CI unavailable: could not read GitHub with the factory access')
			}
			if (!gh) {
				return inScope
					? err('Main CI unavailable: could not read GitHub with the factory access')
					: err('The factory GitHub access covers only the pilot repo')
			}

			const [owner, name] = repoRef.split('/')
			const repoPath = `/repos/${encodeURIComponent(owner!)}/${encodeURIComponent(name!)}`
			const repo = await withTimeout(
				githubReadonlyRequest<{ default_branch?: string }>(gh, repoPath),
				3_000, null,
			)
			if (!repo) return err('Main CI unavailable: could not read ' + repoRef + ' (timeout or access)')
			const branch = repo.default_branch || 'main'
			const status = await withTimeout(
				githubReadonlyRequest<{ state?: string }>(gh, `${repoPath}/commits/${encodeURIComponent(branch)}/status`),
				3_000, null,
			)
			return {
				repo: repoRef,
				status: status?.state ?? 'unknown',
				checkedAt: new Date().toISOString(),
			}
		})
	} catch {
		return err('Main CI unavailable: could not read GitHub with the factory access')
	}
}

export async function loadProjectOverview(projectId: string): Promise<ProjectOverview | null> {
	const [ledger, settings, projects, claims] = await Promise.all([
		loadJson<Ledger>(storageKeys.LEDGER_KEY, emptyLedger()),
		loadSettings(),
		loadProjects(),
		loadClaims(),
	])

	const project = projects.projects[projectId]
	if (!project) return null

	const now = Date.now()
	const limits = settings.columnTimeLimits
	const claimsData = claims
	const allItems = Object.values(ledger.items)
	const items = allItems.filter((i) => i.projectId === projectId)

	const boardCards: BoardCard[] = items.map((i) => {
		const cl = claimsData.claims[i.id]
		return toBoardCard(i, limits, now, cl && Date.parse(cl.expiresAt) > now ? cl : null, settings.runners)
	})
	const stalledCards = boardCards.filter((c) => c.stalled && c.column !== 'shipped' && c.column !== 'dropped')

	const pilotScope = settings.pilotScope
	const inScope = inPilotScope(pilotScope, projectId, project.repos[0]?.repoRef ?? null)

	const sessions = extractSessions(items, boardCards, settings.runners, projects.projects[projectId]?.defaultRunnerId ?? 'devin')

	const repoRefs = new Set(project.repos.filter((r) => r.enabled).map((r) => r.repoRef.toLowerCase()))
	const primaryRepo = project.repos.find((r) => r.enabled)?.repoRef ?? null

	const flow = flowMod()

	const [devinLive, runs, mainCi, fm] = await Promise.all([
		fetchDevinLive(sessions, project).catch(() => err('Could not reach agent runner')),
		fetchRuns(repoRefs),
		fetchMainCi(primaryRepo, inScope),
		flow,
	])

	const t3Links = items.flatMap((i) => (i.links ?? []).filter((l) => l.url.includes('app.t3.codes')))
	const t3Note = t3Links.length
		? t3Links.length + ' T3 Code thread' + (t3Links.length === 1 ? '' : 's') + ' linked from work items.'
		: 'T3 Code threads are not reported to the factory yet.'

	let linkedPlans: Array<{ id: string; title: string; status: string; priority: number | null }> = []
	try {
		const planStore = await loadPlanStore()
		linkedPlans = Object.values(planStore.plans)
			.filter((p) => p.projectId === projectId && !p.archived)
			.map((p) => ({ id: p.id, title: p.title, status: p.status, priority: p.priority }))
	} catch { /* plans store may be empty or malformed */ }

	return {
		project,
		inPilotScope: inScope,
		agents: {
			sessions,
			devinLive: devinLive as DevinLiveStatus[] | { error: string },
			t3Note,
		},
		runs: runs as Section<RunsSummary>,
		flow: {
			throughput: fm.throughputByDay(items, 14, now),
			cycleTime: fm.cycleTime(items),
			columnTimes: fm.columnTimeDistribution(items),
			stalls: stalledCards,
			byColumn: fm.itemsByColumn(items),
			recentActivity: fm.recentActivity(items, 20),
			linkedPlans,
			completed: fm.completedItems(items, 14, now),
		},
		prs: {
			open: extractPrs(items),
			mainCi: mainCi as Section<MainCiInfo> | null,
			postMergeWatches: extractPostMergeWatches(items),
		},
		generatedAt: new Date(now).toISOString(),
	}
}