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

251 lines · 6.6 KB · TypeScript
/**
 * Pure project model + Kent seed coordinates (no kody:runtime).
 */
import type { AgentAdapterRef } from '../adapters/agent/types.ts'

export type RepoHost = 'github' | 'gitlab' | 'kody-native'

export type ProjectRepo = {
	id: string
	repoRef: string
	host: RepoHost
	enabled: boolean
	displayName?: string
}

export type ProjectConfig = {
	id: string
	displayName: string
	repoRef: string | null
	repoHost: RepoHost
	repos: ProjectRepo[]
	planningAdapterId: string
	agents: AgentAdapterRef[]
	defaultRunnerId: string
	signalSources: string[]
	/** Optional pluggable observation sources (see src/adapters/registry.ts). Absent = off. */
	sources?: ProjectSources
	enabled: boolean
	/** Per-project kill switch: when true, the sweep skips new agent runs for this project. */
	paused?: boolean
}

export type ProjectSources = {
	githubRelease?: { enabled: boolean; repos?: string[]; expectWithinHours?: number }
}

function normalizeSources(raw: unknown): ProjectSources | undefined {
	const gr = (raw as ProjectSources | undefined)?.githubRelease
	if (!gr || typeof gr !== 'object') return undefined
	const repos = Array.isArray(gr.repos) ? gr.repos.map(String).filter((r) => REPO_REF_RE.test(r)) : undefined
	const hours = Number(gr.expectWithinHours)
	return {
		githubRelease: {
			enabled: gr.enabled === true,
			...(repos ? { repos } : {}),
			...(Number.isFinite(hours) && hours > 0 ? { expectWithinHours: Math.min(hours, 24 * 90) } : {}),
		},
	}
}

export type ProjectsState = {
	version: 2
	projects: Record<string, ProjectConfig>
	defaultProjectId: string | null
}

const PROJECT_ID_RE = /^[a-z][a-z0-9_-]{0,63}$/
const REPO_REF_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/

export function emptyProjects(): ProjectsState {
	return { version: 2, projects: {}, defaultProjectId: null }
}

export function isValidProjectId(id: string): boolean {
	return PROJECT_ID_RE.test(id)
}

export function isValidRepoRef(repoRef: string): boolean {
	return REPO_REF_RE.test(repoRef)
}

export function repoIdFromRef(repoRef: string): string {
	return repoRef.replace(/\//g, '__').toLowerCase()
}

export function normalizeProject(raw: Partial<ProjectConfig> & { id: string }): ProjectConfig {
	if (!isValidProjectId(raw.id)) {
		throw new Error(`invalid project id "${raw.id}" (use lowercase letters, digits, _-)`)
	}
	const reposIn = Array.isArray(raw.repos) ? raw.repos : []
	const repos: ProjectRepo[] = []
	const seenRefs = new Set<string>()
	for (const r of reposIn) {
		if (!r || typeof r !== 'object') continue
		const repoRef = String(r.repoRef ?? '').trim()
		if (!repoRef) continue
		if (!isValidRepoRef(repoRef)) {
			throw new Error(`invalid repoRef "${repoRef}" (expected owner/name)`)
		}
		const key = repoRef.toLowerCase()
		if (seenRefs.has(key)) {
			throw new Error(`duplicate repoRef "${repoRef}" on project ${raw.id}`)
		}
		seenRefs.add(key)
		repos.push({
			id: String(r.id ?? repoIdFromRef(repoRef)),
			repoRef,
			host: (r.host as RepoHost) || 'github',
			enabled: r.enabled !== false,
			displayName: r.displayName ? String(r.displayName) : undefined,
		})
	}
	if (repos.length === 0 && raw.repoRef) {
		const repoRef = String(raw.repoRef).trim()
		if (!isValidRepoRef(repoRef)) {
			throw new Error(`invalid repoRef "${repoRef}" (expected owner/name)`)
		}
		repos.push({
			id: repoIdFromRef(repoRef),
			repoRef,
			host: raw.repoHost ?? 'github',
			enabled: true,
		})
	}
	const primary = repos.find((r) => r.enabled) ?? repos[0] ?? null
	return {
		id: raw.id,
		displayName: String(raw.displayName ?? raw.id),
		repoRef: primary?.repoRef ?? null,
		repoHost: primary?.host ?? raw.repoHost ?? 'github',
		repos,
		planningAdapterId: String(raw.planningAdapterId ?? 'github-projects'),
		agents:
			Array.isArray(raw.agents) && raw.agents.length > 0
				? raw.agents
				: [
						{ runnerId: 'devin', role: 'implementer' },
						{ runnerId: 'single-agent', role: 'single' },
					],
		defaultRunnerId: String(raw.defaultRunnerId ?? 'devin'),
		signalSources: Array.isArray(raw.signalSources)
			? raw.signalSources.map(String)
			: [
					'sentry',
					'github-issues',
					'feedback',
					'friction',
					'ci-failure',
					'discord',
					'email',
					'x',
				],
		...(normalizeSources(raw.sources) ? { sources: normalizeSources(raw.sources) } : {}),
		enabled: raw.enabled !== false,
	}
}

export function migrateState(
	raw: ProjectsState | { version?: number; projects?: Record<string, ProjectConfig>; defaultProjectId?: string | null },
): ProjectsState {
	const projects: Record<string, ProjectConfig> = {}
	for (const [id, p] of Object.entries(raw.projects ?? {})) {
		projects[id] = normalizeProject({ ...p, id: p.id ?? id })
	}
	return {
		version: 2,
		projects,
		defaultProjectId: raw.defaultProjectId ?? null,
	}
}

/** Verified public coordinates (2026-11-05). kody-hq/kody-video and kody-hq/kody-exchange do not exist. */
export const KENT_SEED_PROJECTS: ReadonlyArray<Partial<ProjectConfig> & { id: string }> = [
	{
		id: 'kody',
		displayName: 'Kody',
		repos: [{ id: 'kody-hq__kody', repoRef: 'kody-hq/kody', host: 'github', enabled: true }],
		enabled: true,
		defaultRunnerId: 'devin',
	},
	{
		id: 'kody-video',
		displayName: 'Kody Video',
		repos: [
			{
				id: 'kentcdodds__kody-video',
				repoRef: 'kentcdodds/kody-video',
				host: 'github',
				enabled: true,
			},
		],
		enabled: true,
		defaultRunnerId: 'devin',
	},
	{
		id: 'kody-exchange',
		displayName: 'Kody Exchange',
		repos: [
			{
				id: 'kentcdodds__kody-exchange',
				repoRef: 'kentcdodds/kody-exchange',
				host: 'github',
				enabled: true,
			},
		],
		enabled: true,
		defaultRunnerId: 'devin',
	},
	{
		id: 'kody-celld',
		displayName: 'Kody Celld',
		repos: [
			{
				id: 'kody-hq__kody-celld',
				repoRef: 'kody-hq/kody-celld',
				host: 'github',
				enabled: true,
			},
		],
		enabled: true,
		defaultRunnerId: 'devin',
	},
	{
		id: 'mediarss',
		displayName: 'MediaRSS',
		repos: [
			{
				id: 'kentcdodds__mediarss',
				repoRef: 'kentcdodds/mediarss',
				host: 'github',
				enabled: true,
			},
		],
		enabled: true,
		defaultRunnerId: 'devin',
	},
]

export function defaultKodyOrgProject(): ProjectConfig {
	return normalizeProject(KENT_SEED_PROJECTS[0]!)
}

export function findProjectByRepoRef(
	state: ProjectsState,
	repoRef: string,
): { project: ProjectConfig; repo: ProjectRepo } | null {
	const needle = repoRef.toLowerCase()
	for (const project of Object.values(state.projects)) {
		if (!project.enabled) continue
		const repo = project.repos.find(
			(r) => r.enabled && r.repoRef.toLowerCase() === needle,
		)
		if (repo) return { project, repo }
	}
	return null
}

export function primaryRepoRef(project: ProjectConfig): string | null {
	const enabled = project.repos.find((r) => r.enabled)
	return enabled?.repoRef ?? project.repoRef
}