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

in-flight-rules.ts

64 lines · 2.5 KB · TypeScript
import { inFlightMaxAgeDays } from './shared.ts'

export type SessionPr = { url: string; state: string }

/** Devin session states after which the session does no more work. */
const terminalStatuses = new Set(['exit', 'error', 'finished', 'expired', 'stopped'])

export function isTerminalSessionStatus(status: unknown) {
	return terminalStatuses.has(String(status ?? '').trim().toLowerCase())
}

export function isOpenPrState(state: unknown) {
	const value = String(state ?? '').trim().toLowerCase()
	return value === 'open' || value === 'draft'
}

/** Normalize Devin `pull_requests` entries (`pr_url`/`pr_state` or `url`/`state`). */
export function sessionPrs(pullRequests: unknown): Array<SessionPr> {
	if (!Array.isArray(pullRequests)) return []
	return pullRequests
		.map((entry) => {
			const record = (entry ?? {}) as Record<string, unknown>
			return {
				url: String(record.pr_url ?? record.url ?? ''),
				state: String(record.pr_state ?? record.state ?? ''),
			}
		})
		.filter((entry) => entry.url)
}

export type HoldDecision = { holds: boolean; reason: string }

/**
 * Does a group session still hold its issues (count against the in-flight
 * cap and stay out of new groups)?
 *
 * - Older than `inFlightMaxAgeDays`: no (stale sessions must not block forever).
 * - Never got a session id: no.
 * - Status unknown (the Devin read failed): yes, to stay safe.
 * - Any open PR: yes, until it merges or closes.
 * - Reported an outcome, or reached a terminal status: no.
 * - Otherwise (still running, suspended, or waiting): yes.
 */
export function sessionHoldsIssues(input: {
	createdAt: string
	sessionId: string | null
	now?: number
	status?: string | null
	statusError?: boolean
	prs?: ReadonlyArray<SessionPr>
	outcomeRecorded?: boolean
}): HoldDecision {
	const now = input.now ?? Date.now()
	const created = Date.parse(input.createdAt)
	if (Number.isFinite(created) && now - created > inFlightMaxAgeDays * 86_400_000) {
		return { holds: false, reason: 'older-than-max-age' }
	}
	if (!input.sessionId) return { holds: false, reason: 'no-session' }
	if (input.statusError) return { holds: true, reason: 'status-unknown' }
	if ((input.prs ?? []).some((pr) => isOpenPrState(pr.state))) return { holds: true, reason: 'open-pr' }
	if (input.outcomeRecorded) return { holds: false, reason: 'outcome-recorded' }
	if (isTerminalSessionStatus(input.status)) return { holds: false, reason: `session-${String(input.status).toLowerCase()}` }
	return { holds: true, reason: `session-${String(input.status || 'unknown').toLowerCase()}` }
}