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

wake-transport.ts

273 lines · 11.0 KB · TypeScript
/**
 * Every factory bot wake goes through `@kody/wake-relay`.
 *
 * The factory emits `@kody/factory.wake.requested` (a role, and a bot when a
 * specific bot was asked for) and records the request as pending. The relay
 * posts it and answers `wake.delivered` or `wake.failed`.
 *
 * The factory never posts to a bot itself. When a wake cannot be confirmed
 * (the emit failed, the relay answered `wake.failed`, or no answer arrived in
 * `wakeAlertMinutes`, checked by the sweep job), the factory raises a wake
 * alert: it is listed on the Factory health page and in `./events/status`, the
 * matching card (if any) gets a `wake-undelivered` label and timeline event,
 * and a Discord message goes to the factory notifications channel when Discord
 * notifications are on.
 */
import postMessage from 'kody:@kody/discord/post-message'
import { loadSettings } from '../lib/settings.ts'
import { loadJson, saveJson } from '../lib/storage.ts'
import { updateLedgerItem } from '../lib/update-helpers.ts'
import { TOPICS, emitFactoryEvent } from './emit.ts'
import { buildWakeRequest, type WakeRequestInput } from './wake-request.ts'

export type WakeRouteInput = WakeRequestInput

export type PendingStatus = 'pending' | 'delivered' | 'failed' | 'undelivered' | 'emit-failed'
export type PendingWake = {
	requestId: string
	/** Bot the request named, or '' when the relay routes by role. */
	bot: string
	role: string
	source: string
	ref: string
	reason: string
	prompt: string
	cardId?: string
	createdAt: string
	status: PendingStatus
	/** Self-test wakes: alerts are recorded but never posted to Discord. */
	selfTest?: boolean
	resolvedAt?: string
	detail?: string
}

export type WakeAlert = {
	at: string
	requestId: string
	bot: string
	role: string
	source: string
	ref: string
	cardId?: string
	status: Exclude<PendingStatus, 'pending' | 'delivered'>
	reason: string
	discord?: 'sent' | 'off' | 'failed' | 'skipped'
	cardMarked?: boolean
}

const PENDING_PREFIX = 'factory:wake-pending:'
const INDEX_KEY = 'factory:wake-pending:index:v1'
const INDEX_LIMIT = 200
export const WAKE_ALERTS_KEY = 'factory:wake-alerts:v1'
const ALERT_LIMIT = 100
export const WAKE_UNDELIVERED_LABEL = 'wake-undelivered'

function pendingKey(requestId: string) {
	return `${PENDING_PREFIX}${requestId}`
}

export async function loadPending(requestId: string): Promise<PendingWake | null> {
	const v = await loadJson<PendingWake | null>(pendingKey(requestId), null)
	return v && typeof v === 'object' && typeof v.requestId === 'string' ? v : null
}

async function savePending(entry: PendingWake) {
	await saveJson(pendingKey(entry.requestId), entry)
}

async function loadIndex(): Promise<string[]> {
	const raw = await loadJson<{ ids?: string[] }>(INDEX_KEY, { ids: [] })
	return Array.isArray(raw?.ids) ? raw.ids.filter((x) => typeof x === 'string') : []
}

async function addToIndex(requestId: string) {
	const ids = (await loadIndex()).filter((x) => x !== requestId)
	ids.unshift(requestId)
	await saveJson(INDEX_KEY, { ids: ids.slice(0, INDEX_LIMIT) })
}

export async function listPending(limit = 20): Promise<PendingWake[]> {
	const out: PendingWake[] = []
	for (const id of (await loadIndex()).slice(0, Math.min(Math.max(limit, 1), INDEX_LIMIT))) {
		const entry = await loadPending(id)
		if (entry) out.push({ ...entry, prompt: entry.prompt.slice(0, 200) })
	}
	return out
}

export async function listWakeAlerts(limit = 20): Promise<WakeAlert[]> {
	const raw = await loadJson<{ alerts?: WakeAlert[] }>(WAKE_ALERTS_KEY, { alerts: [] })
	const alerts = Array.isArray(raw?.alerts) ? raw.alerts : []
	return alerts.slice(0, Math.min(Math.max(limit, 1), ALERT_LIMIT))
}

type AlertDeps = { postDiscord: (input: { channelId: string; content: string }) => Promise<unknown> }
const realPostDiscord: AlertDeps['postDiscord'] = (input) => postMessage(input)
let alertDeps: AlertDeps = { postDiscord: realPostDiscord }
export function setAlertDepsForTests(deps: Partial<AlertDeps> | null) {
	alertDeps = { postDiscord: realPostDiscord, ...(deps ?? {}) }
}

function oneLine(text: string, max: number) {
	const flat = text.replace(/\s+/g, ' ').trim()
	return flat.length > max ? flat.slice(0, max - 1) + '…' : flat
}

/** Record one undelivered wake. Never throws and never posts to a bot. */
export async function raiseWakeAlert(entry: PendingWake, status: WakeAlert['status'], reason: string): Promise<WakeAlert> {
	const alert: WakeAlert = {
		at: new Date().toISOString(),
		requestId: entry.requestId,
		bot: entry.bot,
		role: entry.role,
		source: entry.source,
		ref: entry.ref,
		...(entry.cardId ? { cardId: entry.cardId } : {}),
		status,
		reason: oneLine(reason, 300),
	}
	if (entry.cardId) {
		try {
			await updateLedgerItem(entry.cardId, (cur) => ({
				...cur,
				labels: cur.labels.includes(WAKE_UNDELIVERED_LABEL) ? cur.labels : [...cur.labels, WAKE_UNDELIVERED_LABEL],
				events: [...cur.events, { at: alert.at, from: cur.state, to: cur.state, reason: `wake ${status} (${entry.bot || entry.role}): ${alert.reason}`, actor: 'system', meta: { requestId: entry.requestId } }],
			}))
			alert.cardMarked = true
		} catch {
			alert.cardMarked = false
		}
	}
	if (entry.selfTest) {
		alert.discord = 'skipped'
	} else {
		try {
			const settings = await loadSettings()
			const channelId = settings.discordNotificationsChannelId?.trim()
			if (!settings.discordNotificationsEnabled || !channelId) {
				alert.discord = 'off'
			} else {
				const who = entry.bot || `role ${entry.role}`
				await alertDeps.postDiscord({
					channelId,
					content: `**[WAKE NOT DELIVERED]** ${who} (${entry.source}${entry.cardId ? `, card ${entry.cardId}` : ''}): ${alert.reason}\nRequest ${entry.requestId}. Check @kody/wake-relay status and the factory health page.`,
				})
				alert.discord = 'sent'
			}
		} catch {
			alert.discord = 'failed'
		}
	}
	try {
		const raw = await loadJson<{ alerts?: WakeAlert[] }>(WAKE_ALERTS_KEY, { alerts: [] })
		const alerts = Array.isArray(raw?.alerts) ? raw.alerts : []
		await saveJson(WAKE_ALERTS_KEY, { alerts: [alert, ...alerts.filter((a) => a.requestId !== alert.requestId)].slice(0, ALERT_LIMIT) })
	} catch (error) {
		console.error(`factory wake alert not stored request=${entry.requestId}: ${error instanceof Error ? error.message.slice(0, 200) : 'error'}`)
	}
	console.warn(`factory wake ${status} request=${entry.requestId} bot=${entry.bot || '-'} role=${entry.role} (${alert.reason})`)
	return alert
}

/**
 * Request one wake through the relay. `ok: true` means the request was emitted
 * and is pending a relay answer. `ok: false` means the emit failed; an alert was
 * raised and the caller should keep its own retry state (for example leave a
 * fingerprint queued).
 */
export async function requestWake(input: WakeRouteInput, extra: { selfTest?: boolean } = {}): Promise<{ ok: boolean; requestId: string; detail?: string }> {
	const { requestId, payload } = buildWakeRequest(input)
	const entry: PendingWake = {
		requestId,
		bot: String(payload.bot ?? ''),
		role: String(payload.role),
		source: input.source,
		ref: String(payload.ref),
		reason: String(payload.reason),
		prompt: String(payload.prompt),
		...(input.cardId ? { cardId: input.cardId } : {}),
		createdAt: new Date(input.now ?? Date.now()).toISOString(),
		status: 'pending',
		...(extra.selfTest ? { selfTest: true } : {}),
	}
	try {
		// Record before emitting, so a fast wake.failed always finds the entry.
		await savePending(entry)
		await addToIndex(requestId)
	} catch (error) {
		return { ok: false, requestId, detail: error instanceof Error ? error.message : String(error) }
	}
	let emitted: { emitted: boolean; error?: string; skipped?: string }
	try {
		emitted = await emitFactoryEvent(TOPICS.wakeRequested, `wake:${requestId}`, payload)
	} catch (error) {
		emitted = { emitted: false, error: error instanceof Error ? error.message : String(error) }
	}
	if (!emitted.emitted) {
		const detail = `emit failed (${emitted.error ?? emitted.skipped ?? 'unknown'})`
		const next: PendingWake = { ...entry, status: 'emit-failed', resolvedAt: new Date().toISOString(), detail }
		await savePending(next).catch(() => {})
		await raiseWakeAlert(next, 'emit-failed', detail)
		return { ok: false, requestId, detail }
	}
	console.info(`factory wake via relay request=${requestId} bot=${entry.bot || '-'} role=${entry.role} source=${input.source}`)
	return { ok: true, requestId }
}

/** Same as `requestWake`; kept as the name every wake caller uses. */
export const routeWake = requestWake

export type RelayEnvelope = {
	event?: string
	source?: { type?: string; kody_id?: string }
	payload?: Record<string, unknown>
}

/** Expected relay `source.kody_id`. A fork that renames the relay changes this one line. */
export const RELAY_KODY_ID = 'wake-relay'

/** Handle `@kody/wake-relay.wake.delivered` or `.wake.failed`. */
export async function handleWakeResult(kind: 'delivered' | 'failed', envelope: RelayEnvelope = {}) {
	if (envelope.source?.type !== 'package' || envelope.source?.kody_id !== RELAY_KODY_ID) {
		return { handled: false, reason: `ignored: unexpected source ${envelope.source?.kody_id ?? 'none'}` }
	}
	const p = envelope.payload ?? {}
	const requestId = typeof p.requestId === 'string' ? p.requestId : ''
	if (!requestId) return { handled: false, reason: 'missing requestId' }
	const entry = await loadPending(requestId)
	// Dry-run requests and unknown ids have no pending entry: nothing to do.
	if (!entry) return { handled: false, requestId, reason: 'no pending wake' }
	if (entry.status !== 'pending') return { handled: false, requestId, reason: `already ${entry.status}` }
	if (kind === 'delivered' && p.dryRun !== true) {
		const next: PendingWake = { ...entry, status: 'delivered', resolvedAt: new Date().toISOString(), detail: typeof p.httpStatus === 'number' ? `HTTP ${p.httpStatus}` : p.timedOut === true ? 'sent (timed out waiting for ack)' : 'delivered' }
		await savePending(next)
		return { handled: true, requestId, status: next.status }
	}
	const why = kind === 'failed' ? `relay failed: ${typeof p.reason === 'string' ? p.reason.slice(0, 200) : 'unknown'}` : 'relay answered dryRun only'
	const next: PendingWake = { ...entry, status: 'failed', resolvedAt: new Date().toISOString(), detail: why }
	await savePending(next)
	await raiseWakeAlert(next, 'failed', why)
	return { handled: true, requestId, status: next.status }
}

/** Sweep: pending wakes with no relay answer in `wakeAlertMinutes` raise a wake alert. */
export async function reconcilePendingWakes(now = Date.now()) {
	let minutes = 5
	try {
		minutes = (await loadSettings()).wakeAlertMinutes
	} catch {
		/* default */
	}
	const alerted: Array<{ requestId: string; status: PendingStatus }> = []
	for (const id of await loadIndex()) {
		const entry = await loadPending(id)
		if (!entry || entry.status !== 'pending') continue
		if (now - Date.parse(entry.createdAt) < minutes * 60_000) continue
		const why = `no relay answer in ${minutes} min`
		const next: PendingWake = { ...entry, status: 'undelivered', resolvedAt: new Date(now).toISOString(), detail: why }
		await savePending(next)
		await raiseWakeAlert(next, 'undelivered', why)
		alerted.push({ requestId: id, status: next.status })
	}
	return { checked: true, alerted }
}