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

outcome.ts

217 lines · 9.4 KB · TypeScript
/**
 * Outcomes for a fingerprint (fixed, recommendation, noise), the Activity
 * soft-triage that follows them, and the single-fingerprint wake used by both
 * the sweep and the re-wake action.
 */
import { appBaseUrl } from '../lib/links.ts'
import {
	MAX_WAKES_PER_HOUR,
	OUTCOMES,
	SKIP_WAKE_OUTCOMES,
	IN_FLIGHT_STATUSES,
	fingerprintFor,
	hourBucket,
	matchFamiliesOverlap,
	softTriageForOutcome,
	truncate,
} from './fingerprint.ts'
import type { HealthConfig } from './config.ts'
import { runList, softTriageRuns } from './platform.ts'
import {
	addTimeline,
	claimFingerprint,
	getCounter,
	getFingerprint,
	initSchema,
	listSiblings,
	refundCounterSlot,
	releaseLease,
	reserveCounterSlot,
	tryAcquireLease,
	unclaimFingerprint,
	updateFingerprint,
	type FingerprintRecord,
} from './store.ts'
import { buildPatchPrompt } from './wake.ts'
import { routeWake } from '../events/wake-transport.ts'

const SURFACES = new Set(['execute', 'export', 'subscription', 'app_fetch', 'app_realtime', 'job', 'workflow', 'retriever', 'webhook'])

/** Open Activity rows whose fingerprint matches this record. Pages a bounded window. */
export async function listMatchingOpenRunIds(record: FingerprintRecord): Promise<string[]> {
	if (!SURFACES.has(record.surface)) return []
	const ids: string[] = []
	let cursor: string | undefined
	for (let page = 0; page < 8; page++) {
		const listed = await runList({
			status: 'error',
			error_triage: 'open',
			surface: record.surface,
			...(record.package_id ? { package_id: record.package_id } : {}),
			limit: 100,
			...(cursor ? { cursor } : {}),
		})
		for (const run of listed.runs) {
			if (run.id && fingerprintFor(record.org, run) === record.fingerprint) ids.push(run.id)
		}
		if (!listed.next_cursor || !listed.runs.length) break
		cursor = listed.next_cursor
	}
	return [...new Set(ids)]
}

/** Soft-triage every matching open Activity row. Best effort: returns 0 when the platform refuses. */
export async function applyTriageToMatchingOpenRuns(record: FingerprintRecord, triage: 'ignored' | 'resolved', note: string) {
	try {
		const ids = [...new Set([...(await listMatchingOpenRunIds(record)), ...record.run_ids])]
		return { matched: ids.length, updated: await softTriageRuns(ids, triage, note) }
	} catch {
		return { matched: 0, updated: 0 }
	}
}

export type RecordOutcomeInput = {
	fingerprint: string
	outcome: 'fixed' | 'recommendation' | 'noise' | 'failed'
	summary?: string
	classification?: 'package' | 'platform' | 'noise'
	prUrl?: string | null
	/** Who recorded it, for the timeline (for example `patch` or `kent`). */
	actor?: string
	dryRun?: boolean
}

const RECORDABLE = new Set<string>([...OUTCOMES, 'failed'])
const CLASSIFICATIONS = new Set(['package', 'platform', 'noise'])

/**
 * Record how a fingerprint ended. Caller mistakes return `{ ok: true, skipped, error }`
 * instead of throwing, so a bad call never becomes a new error run.
 */
export async function recordOutcome(input: RecordOutcomeInput) {
	const fingerprint = String(input?.fingerprint || '').trim()
	const outcome = String(input?.outcome || '')
	if (!fingerprint) return { ok: true as const, skipped: 'invalid-input' as const, error: 'fingerprint is required' }
	if (!RECORDABLE.has(outcome)) {
		return { ok: true as const, skipped: 'invalid-input' as const, error: `outcome must be one of ${[...RECORDABLE].join(', ')}` }
	}
	const prUrl = typeof input.prUrl === 'string' ? input.prUrl.trim() : ''
	if (prUrl && !/^https:\/\/[^\s]+$/.test(prUrl)) {
		return { ok: true as const, skipped: 'invalid-input' as const, error: 'prUrl must be an https URL' }
	}
	await initSchema()
	const record = await getFingerprint(fingerprint)
	if (!record) return { ok: true as const, skipped: 'unknown-fingerprint' as const, error: `unknown fingerprint: ${fingerprint}` }

	const summary = truncate(String(input.summary || '').trim(), 1800)
	const classification =
		input.classification && CLASSIFICATIONS.has(input.classification)
			? input.classification
			: outcome === 'noise'
				? 'noise'
				: record.classification
	const actor = String(input.actor || 'agent').slice(0, 40)
	if (input.dryRun === true) return { ok: true as const, dryRun: true as const, fingerprint, outcome, wouldTriage: softTriageForOutcome(outcome) }

	await updateFingerprint(fingerprint, {
		status: outcome,
		outcome,
		summary: summary || record.summary,
		classification,
		completed_at: new Date().toISOString(),
		pr_url: prUrl || record.pr_url,
	})
	await releaseLease(fingerprint)
	await addTimeline(fingerprint, 'outcome', actor, `${outcome}${summary ? `: ${summary}` : ''}`)

	const soft = softTriageForOutcome(outcome)
	const triaged = soft
		? (await applyTriageToMatchingOpenRuns(record, soft, `Factory health ${outcome}: ${truncate(summary || 'no summary', 200)}`)).updated
		: 0
	return { ok: true as const, fingerprint, outcome, triaged }
}

/** Statuses a person may re-wake from. `claimed` is never one: that wake is already going out. */
const CLAIMABLE_MANUAL = ['queued', 'woken', 'failed', 'fixed', 'recommendation', 'noise', 'skipped_execute']

export type WakeAction =
	| { ok: true; fingerprint: string; woke: true; requestId?: string }
	| { ok: true; fingerprint: string; dryRun: true; wouldWake: true; promptChars: number }
	| { ok: boolean; fingerprint: string; skipped: string; detail?: string }

/**
 * Wake Patch for one fingerprint under the global lease and the hourly cap.
 * Callers decide whether wakes are allowed at all; this never checks the switch.
 */
export async function wakeOne(record: FingerprintRecord, config: HealthConfig, opts: { dryRun?: boolean; actor: string; manual?: boolean }): Promise<WakeAction> {
	const fingerprint = record.fingerprint
	const dryRun = opts.dryRun === true
	const bucket = hourBucket()
	const wakesThisHour = await getCounter(`wakes:${bucket}`)
	if (wakesThisHour >= MAX_WAKES_PER_HOUR) return { ok: true, fingerprint, skipped: 'hourly-cap', detail: `${wakesThisHour} wakes this hour` }

	if (!opts.manual) {
		const siblings = await listSiblings(record)
		const inFlight = siblings.find((s) => IN_FLIGHT_STATUSES.has(s.status) && s.status !== 'queued' && matchFamiliesOverlap(s, record))
		if (inFlight) return { ok: true, fingerprint, skipped: 'in-flight-sibling', detail: inFlight.fingerprint }
		const handled = siblings.find((s) => SKIP_WAKE_OUTCOMES.has(s.outcome || s.status) && matchFamiliesOverlap(s, record))
		if (handled) {
			const summary = `Same-owner sibling ${handled.fingerprint} is already ${handled.outcome || handled.status}; no wake sent.`
			if (!dryRun) {
				await updateFingerprint(fingerprint, { status: 'noise', outcome: 'noise', classification: 'noise', completed_at: new Date().toISOString(), summary })
				await addTimeline(fingerprint, 'outcome', 'sweep', `noise: ${summary}`)
			}
			return { ok: true, fingerprint, skipped: 'handled-sibling', detail: handled.fingerprint }
		}
	}

	const prompt = buildPatchPrompt({ record, wakesThisHour, capPerHour: MAX_WAKES_PER_HOUR, manual: opts.manual, baseUrl: await appBaseUrl() })
	if (dryRun) return { ok: true, fingerprint, dryRun: true, wouldWake: true, promptChars: prompt.length }

	// Claim, lease, and cap are each one conditional statement, so two sweeps
	// racing on the same fingerprint cannot both get past this point.
	const previous = record.status
	const claimable = opts.manual ? CLAIMABLE_MANUAL.filter((status) => status === previous) : ['queued']
	if (!(await claimFingerprint(fingerprint, claimable))) return { ok: true, fingerprint, skipped: 'already-claimed' }
	const lease = await tryAcquireLease(fingerprint, opts.actor)
	if (!lease.ok) {
		await unclaimFingerprint(fingerprint, previous)
		return { ok: true, fingerprint, skipped: 'lease-held', detail: lease.heldBy }
	}
	const capKey = `wakes:${bucket}`
	if (!(await reserveCounterSlot(capKey, MAX_WAKES_PER_HOUR))) {
		await unclaimFingerprint(fingerprint, previous)
		await releaseLease(fingerprint)
		return { ok: true, fingerprint, skipped: 'hourly-cap', detail: `${MAX_WAKES_PER_HOUR} wakes this hour` }
	}

	// Through @kody/wake-relay. ok means the request was emitted; delivery is confirmed
	// by the relay, and an undelivered wake raises a wake alert.
	const requested = await routeWake({ source: 'health', bot: config.wakeBotName, prompt, reason: `run-error fingerprint ${fingerprint}`, ref: fingerprint })
	const result = { ok: requested.ok, error: requested.detail }
	if (!result.ok) {
		await refundCounterSlot(capKey)
		await unclaimFingerprint(fingerprint, previous)
		await releaseLease(fingerprint)
		await addTimeline(fingerprint, 'wake-failed', opts.actor, result.error || 'wake failed')
		return { ok: false, fingerprint, skipped: 'wake-failed', detail: result.error }
	}
	await updateFingerprint(fingerprint, {
		status: 'woken',
		outcome: null,
		completed_at: null,
		wake_count: record.wake_count + 1,
		woken_at: new Date().toISOString(),
	})
	await addTimeline(fingerprint, opts.manual ? 're-wake' : 'wake', opts.actor, 'Sent to Patch through @kody/wake-relay')
	return { ok: true, fingerprint, woke: true, requestId: requested.requestId }
}

/** Re-wake one fingerprint on request. Honors the wakes switch, the lease, and the hourly cap. */
export async function rewake(fingerprint: string, config: HealthConfig, actor: string): Promise<WakeAction> {
	await initSchema()
	const record = await getFingerprint(fingerprint)
	if (!record) return { ok: false, fingerprint, skipped: 'unknown-fingerprint' }
	if (!config.wakesEnabled) return { ok: false, fingerprint, skipped: 'wakes-off' }
	return wakeOne(record, config, { actor, manual: true })
}