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

policy.ts

199 lines · 5.5 KB · TypeScript
/**
 * Autopilot policy: extra-care topics (always a human call), risk tiers, ship bar.
 * Everything else, including cleanup, friction, and CI fixes, is eligible for
 * a PR-only agent run; skills give positive instructions instead of bans.
 * Absorbed from:
 * - @kentcdodds/friction-log extra-care.ts
 * - Grok Bot skill kody-new-issue-autopilot (ship only right + two-way + written decision)
 * - ship-pr risk tiers (low / medium / high)
 */

export type RiskTier = 'low' | 'medium' | 'high'

export type ExtraCareTopic = {
	id: string
	label: string
	labels: ReadonlyArray<string>
	patterns: ReadonlyArray<RegExp>
}

/** Extra-care areas: agents may open PRs; they are high risk and always get human review and merge. */
export const extraCareTopics: ReadonlyArray<ExtraCareTopic> = [
	{
		id: 'auth',
		label: 'authentication or authorization',
		labels: [],
		patterns: [
			/\b(auth|authn|authz|authenticat\w*|authoriz\w*|oauth\w*)\b/i,
			/\b(log ?in|sign[- ]?in|sign[- ]?up|signup)\b/i,
			/\bsession cookies?\b/i,
			/\bpermissions?\b/i,
			/\baccess control\b/i,
		],
	},
	{
		id: 'isolation',
		label: 'tenant or per-user isolation',
		labels: [],
		patterns: [/\bisolation\b/i, /\b(cross[- ]origin|cors)\b/i, /\bper[- ](user|org|tenant)\b/i],
	},
	{
		id: 'billing',
		label: 'billing, credits, or metering',
		labels: ['billing'],
		patterns: [/\b(billing|stripe|credits?|metering|invoices?|pricing|payments?)\b/i],
	},
	{
		id: 'data-dropping-migration',
		label: 'a migration or cleanup that drops data',
		labels: [],
		patterns: [
			/\bdata[- ]dropping\b/i,
			/\b(drop|purge|truncate)\b[^.]{0,60}\b(columns?|tables?|data|rows|records)\b/i,
		],
	},
	{
		id: 'disaster-recovery',
		label: 'backups or disaster recovery',
		labels: [],
		patterns: [/\b(disaster recovery|backups?|restores?|point[- ]in[- ]time)\b/i],
	},
	{
		id: 'secrets',
		label: 'secrets or credentials',
		labels: ['credentials'],
		patterns: [/\b(secrets?|credentials?|api keys?|private keys?)\b/i],
	},
	{
		id: 'security',
		label: 'security hardening',
		labels: ['security'],
		patterns: [],
	},
	{
		id: 'production-token-split',
		label: 'token handling and production token splits',
		labels: [],
		patterns: [/\b(prod(uction)? tokens?|token splits?|api[_ ]tokens?)\b/i],
	},
	{
		id: 'search-ranking',
		label: 'search ranking',
		labels: [],
		patterns: [/\b(search[- ]ranking|ranking|re-?rank\w*|relevance)\b/i],
	},
	{
		id: 'publish-idempotency',
		label: 'publish idempotency',
		labels: [],
		patterns: [/\bpublish\w*\b.*\bidempoten\w*/i, /\bidempoten\w*.*\bpublish\w*/i],
	},
]

export type ExtraCareMatch = {
	id: string
	label: string
	via: 'label' | 'title'
	match: string
}

export function extraCareMatches(issue: {
	title: string
	labels: ReadonlyArray<string>
}): Array<ExtraCareMatch> {
	const labels = new Set(issue.labels.map((label) => label.toLowerCase()))
	const title = String(issue.title ?? '')
	const matches: Array<ExtraCareMatch> = []
	for (const topic of extraCareTopics) {
		const label = topic.labels.find((name) => labels.has(name.toLowerCase()))
		if (label) {
			matches.push({ id: topic.id, label: topic.label, via: 'label', match: label })
			continue
		}
		for (const pattern of topic.patterns) {
			const hit = pattern.exec(title)
			if (hit) {
				matches.push({ id: topic.id, label: topic.label, via: 'title', match: hit[0] })
				break
			}
		}
	}
	return matches
}

/** @deprecated use extraCareTopics */
export const neverAutopilotTopics = extraCareTopics

export function extraCarePromptList(): string {
	return extraCareTopics.map((topic) => `- ${topic.label}`).join('\n')
}

/**
 * Ship bar from kody-new-issue-autopilot:
 * ship only when the recommended fix is the right fix, it is a two-way door,
 * and it matches a written product decision.
 */
export type ShipDecisionInput = {
	isRightFix: boolean
	isTwoWayDoor: boolean
	matchesWrittenDecision: boolean
	extraCare: ExtraCareMatch[]
	/** When true, extra-care areas still auto-implement with high risk, but product direction waits. */
	productDirectionNeeded: boolean
}

export type ShipDecision = {
	mayAutopilot: boolean
	risk: RiskTier
	reasons: string[]
}

export function decideShip(input: ShipDecisionInput): ShipDecision {
	const reasons: string[] = []
	if (!input.isRightFix) reasons.push('fix is not clearly the right fix')
	if (!input.isTwoWayDoor) reasons.push('one-way door; needs human')
	if (!input.matchesWrittenDecision) reasons.push('no matching written product decision')
	if (input.productDirectionNeeded) reasons.push('needs owner product direction')

	const mayAutopilot =
		input.isRightFix &&
		input.isTwoWayDoor &&
		input.matchesWrittenDecision &&
		!input.productDirectionNeeded

	let risk: RiskTier = 'low'
	if (input.extraCare.length > 0) risk = 'high'
	else if (!input.isTwoWayDoor) risk = 'high'
	else if (!mayAutopilot) risk = 'medium'

	return { mayAutopilot, risk, reasons }
}

export type FactoryPolicyConfig = {
	/** Shadow mode: record decisions, do not start runners or merge. */
	shadowMode: boolean
	/** Max concurrent agent runs across all projects. */
	maxConcurrentRuns: number
	/** Agent merge policy from autopilot interview. */
	agentMayMerge: 'low' | 'low+medium' | 'none'
	alwaysHuman: string[]
	mustNotDo: string[]
}

export const defaultPolicyConfig = (): FactoryPolicyConfig => ({
	shadowMode: true,
	maxConcurrentRuns: 3,
	agentMayMerge: 'low',
	alwaysHuman: [
		'auth',
		'payments',
		'migrations that drop data',
		'public API breaks',
		'store releases',
	],
	mustNotDo: [
		'paste secrets into chat, issues, or PRs',
		'force-push default branch',
		'enable live webhooks without owner approval',
	],
})