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

diff.ts

77 lines · 2.6 KB · TypeScript
/**
 * Compute a human-readable diff between the current factory config and an
 * import document. Used for the preview step before applying an import.
 */
import type { ConfigDocument, ConfigDiff, ConfigSettings } from './schema.ts'

function diffObject(from: Record<string, unknown>, to: Record<string, unknown>, keys: string[]): Array<{ key: string; from: unknown; to: unknown }> {
	const changes: Array<{ key: string; from: unknown; to: unknown }> = []
	for (const key of keys) {
		const a = from[key]
		const b = to[key]
		if (JSON.stringify(a) !== JSON.stringify(b)) {
			changes.push({ key, from: a, to: b })
		}
	}
	return changes
}

const SETTINGS_KEYS: Array<keyof ConfigSettings> = [
	'shadowMode', 'maxConcurrentRuns', 'agentMayMerge', 'sweepStartLimit',
	'agentDryRunDefault', 'killSwitch', 'postMergeFixTimeoutMinutes',
	'postMergePendingTimeoutMinutes', 'stallHealthEnabled', 'bugbotCursorLogin',
	'shipPrSummaryChannelId', 'discordNotificationsEnabled',
	'discordNotificationsChannelId', 'notificationRules',
]

export function computeDiff(current: ConfigDocument, incoming: ConfigDocument): ConfigDiff {
	const settingsChanges = diffObject(
		current.settings as unknown as Record<string, unknown>,
		incoming.settings as unknown as Record<string, unknown>,
		SETTINGS_KEYS as string[],
	)

	const currentIds = new Set(current.projects.map((p) => p.id))
	const incomingIds = new Set(incoming.projects.map((p) => p.id))

	const added = incoming.projects.filter((p) => !currentIds.has(p.id)).map((p) => p.id)
	const removed = current.projects.filter((p) => !incomingIds.has(p.id)).map((p) => p.id)

	const changed: ConfigDiff['projects']['changed'] = []
	for (const ip of incoming.projects) {
		const cp = current.projects.find((p) => p.id === ip.id)
		if (!cp) continue
		const changes = diffObject(
			cp as unknown as Record<string, unknown>,
			ip as unknown as Record<string, unknown>,
			['displayName', 'enabled', 'defaultRunnerId', 'repos', 'signalSources', 'sources', 'paused'],
		)
		if (changes.length > 0) {
			changed.push({ id: ip.id, changes })
		}
	}

	const jobChanges: ConfigDiff['jobs'] = []
	for (const ij of incoming.jobs) {
		const cj = current.jobs.find((j) => j.name === ij.name)
		if (cj && cj.enabled !== ij.enabled) {
			jobChanges.push({ name: ij.name, from: cj.enabled, to: ij.enabled })
		}
	}

	return {
		settings: settingsChanges,
		projects: { added, removed, changed },
		jobs: jobChanges,
	}
}

export function isDiffEmpty(diff: ConfigDiff): boolean {
	return (
		diff.settings.length === 0 &&
		diff.projects.added.length === 0 &&
		diff.projects.removed.length === 0 &&
		diff.projects.changed.length === 0 &&
		diff.jobs.length === 0
	)
}