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

record-outcome.ts

106 lines · 4.1 KB · TypeScript
import { denverDayKey, truncate } from './shared.ts'
import { getGroupSession, recordOutcome as writeOutcome } from './storage.ts'
import { applyCardOutcomes, type CardOutcome } from './card-outcomes.ts'

export type IssueOutcome =
	| 'fixed'
	| 'already-fixed'
	| 'invalid'
	| 'skipped'
	| 'not-reached'
	// all-issues mode
	| 'stale'
	| 'waiting'
	| 'needs-kent'

export type RecordOutcomeInput = {
	outcome: 'fixed' | 'skipped' | 'closed' | 'failed'
	summary: string
	prUrl?: string
	/** Group key from the sweep prompt (Devin sessions). */
	groupKey?: string
	/** Legacy Cursor agent id. Pass `groupKey` instead for Devin sessions. */
	agentId?: string
	/** One entry per issue in the group. */
	issues?: Array<{ number: number; outcome: IssueOutcome }>
	/** Nightly card run: one entry per card in the group. */
	cards?: Array<{ cardId: string; outcome: CardOutcome; note?: string }>
}

const allowedOutcomes = new Set(['fixed', 'skipped', 'closed', 'failed'])
const allowedIssueOutcomes = new Set([
	'fixed',
	'already-fixed',
	'invalid',
	'skipped',
	'not-reached',
	'stale',
	'waiting',
	'needs-kent',
])

/**
 * Final report from a friction-log sweep session. Devin sessions pass the
 * `groupKey` from their prompt; a recorded outcome releases the group's
 * issues from the in-flight count once no PR is open.
 */
export default async function recordOutcome(input: RecordOutcomeInput) {
	const outcome = String(input?.outcome || '')
	if (!allowedOutcomes.has(outcome)) {
		throw new Error(`outcome must be one of ${[...allowedOutcomes].join(', ')}`)
	}
	const summary = truncate(input?.summary, 600).trim()
	if (!summary) throw new Error('summary is required')
	const groupKey = String(input?.groupKey || '').trim()
	const agentId = String(input?.agentId || '').trim()
	const key = groupKey || agentId
	if (!key) throw new Error('groupKey is required (agentId for legacy agents)')
	if (groupKey && !(await getGroupSession(groupKey))) {
		throw new Error(`unknown groupKey: ${truncate(groupKey, 120)}`)
	}
	let issuesJson: string | null = null
	if (input?.issues !== undefined) {
		if (!Array.isArray(input.issues)) throw new Error('issues must be an array')
		const issues = input.issues.map((entry) => {
			const number = Number(entry?.number)
			const issueOutcome = String(entry?.outcome || '')
			if (!Number.isInteger(number) || number <= 0) throw new Error('issues[].number must be a positive integer')
			if (!allowedIssueOutcomes.has(issueOutcome)) {
				throw new Error(`issues[].outcome must be one of ${[...allowedIssueOutcomes].join(', ')}`)
			}
			return { number, outcome: issueOutcome }
		})
		issuesJson = JSON.stringify(issues.slice(0, 100))
	}

	let cardsJson: string | null = null
	let cardResults: Awaited<ReturnType<typeof applyCardOutcomes>> | null = null
	if (input?.cards !== undefined) {
		if (!Array.isArray(input.cards)) throw new Error('cards must be an array')
		const session = groupKey ? await getGroupSession(groupKey) : null
		const allowed = new Set<string>(session?.card_ids_json ? (JSON.parse(session.card_ids_json) as string[]) : [])
		const cards = input.cards.slice(0, 100).map((entry) => {
			const cardId = String(entry?.cardId ?? '').trim()
			const cardOutcome = String(entry?.outcome || '')
			if (!/^[A-Za-z0-9_-]{4,80}$/.test(cardId)) throw new Error('cards[].cardId is required')
			if (allowed.size > 0 && !allowed.has(cardId)) throw new Error(`cards[].cardId ${cardId} is not in group ${truncate(groupKey, 80)}`)
			if (!allowedIssueOutcomes.has(cardOutcome)) throw new Error(`cards[].outcome must be one of ${[...allowedIssueOutcomes].join(', ')}`)
			return { cardId, outcome: cardOutcome as CardOutcome, ...(entry?.note ? { note: truncate(entry.note, 1200) } : {}) }
		})
		cardsJson = JSON.stringify(cards)
		cardResults = await applyCardOutcomes(cards, { groupKey: key, prUrl: input.prUrl ? String(input.prUrl) : null, summary })
	}

	const record = {
		agent_id: key,
		day: denverDayKey(),
		outcome,
		summary,
		pr_url: input.prUrl ? String(input.prUrl) : null,
		completed_at: new Date().toISOString(),
		issues_json: issuesJson,
		cards_json: cardsJson,
	}
	await writeOutcome(record)
	return { ok: true, ...record, ...(cardResults ? { cards: cardResults } : {}) }
}