/** * Factory health signals: how the factory itself is doing. `buildHealthReport` * is pure (stored facts in, verdicts out). `refreshPlatformSnapshot` is the * only part that asks the platform, and it stores what it saw so page loads * read storage only. */ import { listWakeAlerts, type WakeAlert } from '../events/wake-transport.ts' import { loadJson, saveJson, storageKeys } from '../lib/storage.ts' import { emptyLedger, type Ledger } from '../core/work-item.ts' import { toBoardCard, toPlanCard, defaultColumnTimeLimits } from '../core/board.ts' import { loadPlanStore } from '../core/plan.ts' import { loadSettings } from '../lib/settings.ts' import { EVENT_ANOMALY_THRESHOLD, FINGERPRINT_ANOMALY_THRESHOLD, LEASE_STALE_MS, MAX_WAKES_PER_HOUR, anomalyTripped, hourBucket, } from './fingerprint.ts' import type { HealthConfig } from './config.ts' import { runList, selfPackageId, withTimeout, type ListedRun } from './platform.ts' import { countByStatus, getCounters, getLastCounterUpdate, getLease, listHeartbeats, type Heartbeat, type Lease } from './store.ts' const SNAPSHOT_KEY = 'factory:health:platform:v1' const LOCKS_KEY = 'factory:locks:v1' const HOUR = 60 * 60 * 1000 export type Level = 'ok' | 'warn' | 'bad' | 'off' | 'unknown' export type RunGroup = { name: string; total: number; errors: number; lastAt: string | null; lastStatus: string | null; lastError: string | null } export type Probe = ({ ok: true } & T) | { ok: false; error: string } export type PlatformSnapshot = { collectedAt: string ok: boolean jobs: Probe<{ groups: RunGroup[] }> webhooks: Probe<{ groups: RunGroup[] }> errorRate: Probe<{ total: number; errors: number; windowStart: string | null }> openErrors: Probe<{ count: number; more: boolean }> stuckRuns: Probe<{ count: number; oldestAt: string | null; names: string[] }> } export const STUCK_RUN_MS = 30 * 60 * 1000 export function groupRuns(runs: ListedRun[]): RunGroup[] { const groups = new Map() for (const run of runs) { const name = run.name || 'unnamed' const group = groups.get(name) ?? { name, total: 0, errors: 0, lastAt: null, lastStatus: null, lastError: null } group.total++ if (run.status === 'error') group.errors++ const at = run.started_at ?? null if (at && (!group.lastAt || at > group.lastAt)) { group.lastAt = at group.lastStatus = run.status ?? null group.lastError = run.status === 'error' ? String(run.error_message || run.error_name || 'error').slice(0, 200) : null } groups.set(name, group) } return [...groups.values()].sort((a, b) => a.name.localeCompare(b.name)) } async function probe(fn: () => Promise): Promise> { try { const value = await withTimeout(fn(), 8_000, null) if (value === null) return { ok: false, error: 'timed out' } return { ok: true, ...value } } catch (error) { return { ok: false, error: (error instanceof Error ? error.message : String(error)).slice(0, 200) } } } /** Ask the platform about this package's job and webhook runs, and the org's recent runs. */ export async function collectPlatformSnapshot(now = Date.now()): Promise { const self = selfPackageId() const ownRuns = (surface: string) => async () => { if (!self) throw new Error('package id unavailable in this runtime') return { groups: groupRuns((await runList({ surface, package_id: self, error_triage: 'all', limit: 50 })).runs) } } const [jobs, webhooks, errorRate, openErrors, stuckRuns] = await Promise.all([ probe(ownRuns('job')), probe(ownRuns('webhook')), probe(async () => { const { runs } = await runList({ error_triage: 'all', limit: 100 }) const starts = runs.map((r) => r.started_at).filter((s): s is string => Boolean(s)).sort() return { total: runs.length, errors: runs.filter((r) => r.status === 'error').length, windowStart: starts[0] ?? null } }), probe(async () => { const page = await runList({ status: 'error', error_triage: 'open', limit: 100 }) return { count: page.runs.length, more: Boolean(page.next_cursor) } }), probe(async () => { const { runs } = await runList({ status: 'running', limit: 50 }) const stuck = runs.filter((r) => r.started_at && now - Date.parse(r.started_at) > STUCK_RUN_MS) const starts = stuck.map((r) => r.started_at as string).sort() return { count: stuck.length, oldestAt: starts[0] ?? null, names: [...new Set(stuck.map((r) => `${r.surface ?? 'run'} ${r.name ?? r.kody_id ?? ''}`.trim()))].slice(0, 5) } }), ]) return { collectedAt: new Date(now).toISOString(), ok: [jobs, webhooks, errorRate, openErrors, stuckRuns].every((p) => p.ok), jobs, webhooks, errorRate, openErrors, stuckRuns } } export async function refreshPlatformSnapshot(): Promise { const snapshot = await collectPlatformSnapshot() await saveJson(SNAPSHOT_KEY, snapshot) return snapshot } export type StaleItem = { id: string; title: string; state: string; projectId: string; updatedAt: string } export type HealthFacts = { now: number config: HealthConfig counts: Record /** Hour bucket (YYYY-MM-DDTHH) to count, for the last 24 hours. */ eventsByHour: Record fingerprintsByHour: Record wakesThisHour: number lastEventAt: string | null lease: Lease | null sweeps: Heartbeat[] snapshot: PlatformSnapshot | null staleItems: StaleItem[] parked: number /** Factory shadow mode: parked work is expected only while it is on. */ shadowMode?: boolean staleLocks: number stalledWorkCount: number stalledPlanCount: number /** Recent wake alerts (wakes @kody/wake-relay did not confirm), newest first. */ wakeAlerts?: WakeAlert[] } export type Signal = { id: string; title: string; level: Level; headline: string; detail: string } export type HealthReport = { level: Level summary: string reasons: string[] signals: Signal[] hours: Array<{ bucket: string; events: number; fingerprints: number }> facts: HealthFacts } export const STALE_RUNNING_MS = 6 * HOUR export const STALE_VERIFYING_MS = 7 * 24 * HOUR const SWEEP_OVERDUE_MS = 2 * HOUR + 15 * 60 * 1000 const SNAPSHOT_STALE_MS = 3 * HOUR export function ago(now: number, iso: string | null | undefined): string { const then = iso ? Date.parse(iso) : Number.NaN if (!Number.isFinite(then)) return 'never' const mins = Math.max(0, Math.round((now - then) / 60_000)) if (mins < 1) return 'just now' if (mins < 60) return `${mins} min ago` const hours = Math.round(mins / 60) if (hours < 48) return `${hours} h ago` return `${Math.round(hours / 24)} d ago` } const pct = (part: number, whole: number) => (whole > 0 ? Math.round((part / whole) * 100) : 0) function runGroupSignal(id: string, title: string, noun: string, probeResult: Probe<{ groups: RunGroup[] }> | undefined, now: number): Signal { if (!probeResult) return { id, title, level: 'unknown', headline: 'No reading yet', detail: 'Run the health sweep, or refresh signals, to read recent runs from Kody.' } if (!probeResult.ok) return { id, title, level: 'unknown', headline: 'Unavailable', detail: `Kody did not return ${noun} runs: ${probeResult.error}.` } const groups = probeResult.groups if (!groups.length) return { id, title, level: 'unknown', headline: `No recent ${noun} runs`, detail: `Kody has no retained ${noun} runs for this package.` } const total = groups.reduce((n, g) => n + g.total, 0) const errors = groups.reduce((n, g) => n + g.errors, 0) const failingNow = groups.filter((g) => g.lastStatus === 'error') const level: Level = failingNow.length ? 'bad' : errors ? 'warn' : 'ok' const detail = groups .map((g) => `${g.name}: last ${g.lastStatus === 'error' ? 'failed' : 'ran'} ${ago(now, g.lastAt)}, ${g.errors} of ${g.total} failed`) .join('. ') return { id, title, level, headline: `${total - errors} of ${total} recent ${noun} runs succeeded`, detail: `${detail}.` } } export function buildHealthReport(facts: HealthFacts): HealthReport { const { now, config, snapshot } = facts const bucket = hourBucket(new Date(now)) const hours: HealthReport['hours'] = [] for (let i = 23; i >= 0; i--) { const b = hourBucket(new Date(now - i * HOUR)) hours.push({ bucket: b, events: facts.eventsByHour[b] ?? 0, fingerprints: facts.fingerprintsByHour[b] ?? 0 }) } const eventsThisHour = facts.eventsByHour[bucket] ?? 0 const fingerprintsThisHour = facts.fingerprintsByHour[bucket] ?? 0 const events24h = hours.reduce((n, h) => n + h.events, 0) const breaker = anomalyTripped({ fingerprints: fingerprintsThisHour, events: eventsThisHour }) const signals: Signal[] = [] signals.push( !config.intakeEnabled ? { id: 'intake', title: 'Error intake', level: 'off', headline: 'Off', detail: 'Run errors are not being recorded. Turn on intake to start the feed.' } : { id: 'intake', title: 'Error intake', level: breaker ? 'bad' : 'ok', headline: `${events24h} ${events24h === 1 ? 'event' : 'events'} in 24 hours`, detail: `Last event ${ago(now, facts.lastEventAt)}. This hour: ${eventsThisHour} of ${EVENT_ANOMALY_THRESHOLD} events and ${fingerprintsThisHour} of ${FINGERPRINT_ANOMALY_THRESHOLD} new fingerprints before the breaker pauses wakes.${breaker ? ' The breaker is tripped for this hour.' : ''}`, }, ) const lastSweep = facts.sweeps[0] const sweepFailures = facts.sweeps.filter((s) => !s.ok).length const sweepAge = lastSweep ? now - Date.parse(lastSweep.at) : Number.POSITIVE_INFINITY const sweepExpected = config.reconcileEnabled || config.wakesEnabled let sweepLevel: Level = 'ok' if (!lastSweep) sweepLevel = sweepExpected ? 'warn' : 'off' else if (!lastSweep.ok) sweepLevel = 'bad' else if (sweepExpected && sweepAge > SWEEP_OVERDUE_MS) sweepLevel = 'warn' else if (sweepFailures) sweepLevel = 'warn' signals.push({ id: 'sweep', title: 'Health sweep', level: sweepLevel, headline: !lastSweep ? 'Has not run yet' : `Last ran ${ago(now, lastSweep.at)}${lastSweep.ok ? '' : ' and failed'}`, detail: !lastSweep ? sweepExpected ? 'A switch is on but no sweep has run. The health-sweep job or the next recorded run error starts one, or run one from this page.' : 'Runs every 30 minutes from the health-sweep job, after recorded run errors, and on demand from this page.' : `${facts.sweeps.length - sweepFailures} of the last ${facts.sweeps.length} sweeps succeeded. Latest: ${lastSweep.detail || 'no detail'} (${lastSweep.duration_ms} ms, ${lastSweep.source.replace('sweep:', '')}).${sweepExpected && sweepAge > SWEEP_OVERDUE_MS ? ' It is overdue: the health-sweep job may be off.' : ''}`, }) const lease = facts.lease const leaseAge = lease?.acquired_at ? now - Date.parse(lease.acquired_at) : 0 const awaiting = (facts.counts.claimed ?? 0) + (facts.counts.woken ?? 0) signals.push( !config.wakesEnabled ? { id: 'wakes', title: 'Patch wakes', level: 'off', headline: 'Off', detail: `No wake is sent while this is off. ${facts.counts.queued ?? 0} queued ${(facts.counts.queued ?? 0) === 1 ? 'fingerprint is' : 'fingerprints are'} waiting.` } : { id: 'wakes', title: 'Patch wakes', level: breaker || leaseAge > LEASE_STALE_MS ? 'warn' : 'ok', headline: `${facts.wakesThisHour} of ${MAX_WAKES_PER_HOUR} wakes used this hour`, detail: `${awaiting} with Patch, ${facts.counts.queued ?? 0} queued.${lease?.fingerprint ? ` Lease held ${ago(now, lease.acquired_at)} by ${lease.fingerprint}.` : ' No wake lease is held.'}${breaker ? ' Paused this hour by the anomaly breaker.' : ''}`, }, ) const recentAlerts = (facts.wakeAlerts ?? []).filter((a) => now - Date.parse(a.at) < 24 * HOUR) const lastAlert = recentAlerts[0] signals.push({ id: 'wake-delivery', title: 'Wake delivery', level: recentAlerts.length ? 'warn' : 'ok', headline: recentAlerts.length ? `${recentAlerts.length} ${recentAlerts.length === 1 ? 'wake' : 'wakes'} not confirmed in 24 hours` : 'Every wake confirmed', detail: lastAlert ? `Latest: ${lastAlert.bot || `role ${lastAlert.role}`} (${lastAlert.source}) ${lastAlert.status} ${ago(now, lastAlert.at)}: ${lastAlert.reason}. All wakes go through @kody/wake-relay; check its status page and mappings.` : 'All wakes go through @kody/wake-relay. A wake the relay does not confirm shows up here, on its card, and in Discord when notifications are on.', }) signals.push(runGroupSignal('jobs', 'Job runs', 'job', snapshot?.jobs, now)) signals.push(runGroupSignal('webhooks', 'Webhook deliveries', 'webhook', snapshot?.webhooks, now)) const failed = facts.counts.failed ?? 0 const stuck = snapshot?.stuckRuns const stuckCount = stuck?.ok ? stuck.count : 0 const staleParts: string[] = [] if (facts.staleItems.length) staleParts.push(`${facts.staleItems.length} work ${facts.staleItems.length === 1 ? 'item has' : 'items have'} not moved (running over 6 hours or verifying over 7 days)`) if (failed) staleParts.push(`${failed} ${failed === 1 ? 'wake' : 'wakes'} ended with no recorded outcome`) if (stuckCount && stuck?.ok) staleParts.push(`${stuckCount} Kody ${stuckCount === 1 ? 'run has' : 'runs have'} been running over 30 minutes (oldest started ${ago(now, stuck.oldestAt)}${stuck.names.length ? `: ${stuck.names.join(', ')}` : ''})`) if (facts.staleLocks) staleParts.push(`${facts.staleLocks} expired ${facts.staleLocks === 1 ? 'lock is' : 'locks are'} still stored`) const staleCount = facts.staleItems.length + failed + stuckCount signals.push({ id: 'staleness', title: 'Queue staleness', level: staleCount ? 'warn' : 'ok', headline: staleCount ? `${staleCount} stuck` : 'Nothing stuck', detail: `${staleParts.length ? `${staleParts.join('. ')}.` : 'No work item, wake, or run is past its window.'} ${facts.parked} work ${facts.parked === 1 ? 'item is' : 'items are'} parked before a session${facts.shadowMode ? ', as shadow mode intends' : ', waiting for a run slot or a decision'}.${stuck && !stuck.ok ? ' Running Kody runs could not be read.' : ''}`, }) const rate = snapshot?.errorRate const open = snapshot?.openErrors if (!rate || !rate.ok) { signals.push({ id: 'error-rate', title: 'Error rate', level: 'unknown', headline: rate ? 'Unavailable' : 'No reading yet', detail: rate ? `Kody did not return recent runs: ${rate.error}.` : 'Run the health sweep, or refresh signals, to read recent runs from Kody.' }) } else { const share = pct(rate.errors, rate.total) signals.push({ id: 'error-rate', title: 'Error rate', level: share >= 25 ? 'bad' : share >= 10 ? 'warn' : 'ok', headline: `${share}% of recent runs failed`, detail: `${rate.errors} of the last ${rate.total} retained runs in this org failed (since ${ago(now, rate.windowStart)}).${open?.ok ? ` ${open.count}${open.more ? ' or more' : ''} error ${open.count === 1 && !open.more ? 'run is' : 'runs are'} still open in Activity.` : ''}`, }) } // Stalls signal: computed from the work ledger and time limits const stalls = facts.stalledWorkCount ?? 0 const stalledPlanCount = facts.stalledPlanCount ?? 0 const totalStalls = stalls + stalledPlanCount signals.push({ id: 'stalls', title: 'Stalls', level: totalStalls > 5 ? 'bad' : totalStalls > 0 ? 'warn' : 'ok', headline: totalStalls ? `${totalStalls} stalled` : 'Nothing stalled', detail: totalStalls ? `${stalls} work ${stalls === 1 ? 'item' : 'items'} and ${stalledPlanCount} ${stalledPlanCount === 1 ? 'plan' : 'plans'} are past their column time limit. Open the Board to see which.` : 'No work items or plans are past their column time limits.', }) const reasons: string[] = [] for (const s of signals) if (s.level === 'bad' || s.level === 'warn') reasons.push(`${s.title}: ${s.headline}`) if (snapshot && now - Date.parse(snapshot.collectedAt) > SNAPSHOT_STALE_MS) reasons.push(`Platform signals were last read ${ago(now, snapshot.collectedAt)}`) const core = signals.filter((s) => ['intake', 'sweep', 'wakes'].includes(s.id)) // "Healthy" is only honest when the whole loop is running: every switch on and at least one sweep on record. const notOn: string[] = [] if (!config.intakeEnabled) notOn.push('Error intake is off') if (!config.reconcileEnabled) notOn.push('Reconcile is off') if (!config.wakesEnabled) notOn.push('Patch wakes are off') if (!lastSweep) notOn.push('The health sweep has never run') const allOff = core.every((s) => s.level === 'off') const level: Level = signals.some((s) => s.level === 'bad') ? 'bad' : reasons.length ? 'warn' : notOn.length ? 'off' : 'ok' const partial = level === 'off' && !allOff if (partial || (level !== 'off' && notOn.length)) reasons.push(...notOn) const summary = partial ? 'Partly on' : { ok: 'Healthy', warn: 'Needs attention', bad: 'Degraded', off: 'Not watching yet', unknown: 'Unknown' }[level] return { level, summary, reasons, signals, hours, facts } } type LockStore = { locks?: Record } /** Read everything the report needs from package storage. No platform calls. */ /** State a caller already loaded, so a composite read loads each storage key once. */ export type PreloadedFactoryState = { ledger: Ledger settings: Awaited> planStore: Awaited> } export async function loadHealthFacts(config: HealthConfig, now = Date.now(), preloaded?: PreloadedFactoryState): Promise { const since = hourBucket(new Date(now - 23 * HOUR)) const [counts, eventsByHour, fingerprintsByHour, wakes, lastEventAt, lease, sweepRows, snapshot, ledger, locks] = await Promise.all([ countByStatus(), getCounters('events:', since), getCounters('fingerprints:', since), getCounters('wakes:', hourBucket(new Date(now))), getLastCounterUpdate('events:'), getLease(), Promise.all(['sweep:job', 'sweep:event', 'sweep:manual'].map((source) => listHeartbeats(source, 12))), loadJson(SNAPSHOT_KEY, null), preloaded ? preloaded.ledger : loadJson(storageKeys.LEDGER_KEY, emptyLedger()), loadJson(LOCKS_KEY, { locks: {} }), ]) let wakeAlerts: WakeAlert[] = [] try { wakeAlerts = await listWakeAlerts(20) } catch { /* alert store unreadable; the signal shows ok */ } const items = Object.values(ledger.items ?? {}) const staleItems = items .filter((i) => { const age = now - Date.parse(i.updatedAt) return (i.state === 'running' && age > STALE_RUNNING_MS) || (i.state === 'verifying' && age > STALE_VERIFYING_MS) }) .sort((a, b) => a.updatedAt.localeCompare(b.updatedAt)) .slice(0, 10) .map((i) => ({ id: i.id, title: i.title, state: i.state, projectId: i.projectId, updatedAt: i.updatedAt })) let stalledWorkCount = 0 let stalledPlanCount = 0 let shadowMode: boolean | undefined try { const settings = preloaded ? preloaded.settings : await loadSettings() shadowMode = settings.shadowMode === true const limits = settings.columnTimeLimits ?? defaultColumnTimeLimits() for (const item of items) { const card = toBoardCard(item, limits, now, null, settings.runners) if (card.stalled && card.column !== 'shipped' && card.column !== 'dropped') stalledWorkCount++ } try { const planStore = preloaded ? preloaded.planStore : await loadPlanStore() if (planStore && planStore.plans) { for (const plan of Object.values(planStore.plans)) { if (!plan || plan.archived || plan.status === 'shipped') continue const card = toPlanCard(plan, limits, now) if (card.stalled) stalledPlanCount++ } } } catch { /* plans store may not exist yet or be malformed */ } } catch { /* settings or board import failed; stall counts stay 0 */ } return { now, config, counts, eventsByHour, fingerprintsByHour, wakesThisHour: wakes[hourBucket(new Date(now))] ?? 0, lastEventAt, lease, sweeps: sweepRows.flat().sort((a, b) => b.at.localeCompare(a.at)).slice(0, 12), snapshot, staleItems, wakeAlerts, parked: items.filter((i) => i.state === 'intake' || i.state === 'triaged' || i.state === 'planned').length, shadowMode, staleLocks: Object.values(locks.locks ?? {}).filter((l) => l.expiresAt && Date.parse(l.expiresAt) < now - HOUR).length, stalledWorkCount, stalledPlanCount, } }