← 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.
Files
/**
* Server-rendered Factory health pages: the factory looking at itself.
* Pure (no kody:runtime). Every action is a plain form POST, so the pages
* work without JavaScript.
*/
import { esc, icon, renderShell } from './ui.ts'
import { ACTIVITY_ORIGIN, type HealthConfig } from '../health/config.ts'
import { MAX_WAKES_PER_HOUR, activityUrlFor } from '../health/fingerprint.ts'
import { ago, type HealthReport, type Level } from '../health/signals.ts'
import type { FingerprintRecord, TimelineEvent } from '../health/store.ts'
const TZ = 'America/Denver'
const BAD_FLASH = /^(error|invalid|unknown|could not|no wake|wakes are off|not sent)/i
function wakeAlertsHtml(facts: { now: number; wakeAlerts?: Array<{ at: string; bot: string; role: string; source: string; status: string; reason: string; cardId?: string }> }): string {
const alerts = (facts.wakeAlerts ?? []).slice(0, 5)
if (!alerts.length) return '<p class="small muted">No undelivered wakes on record.</p>'
return `<ul class="reasons">${alerts.map((a) => `<li>${esc(a.bot || `role ${a.role}`)} (${esc(a.source)}) ${esc(a.status)} ${esc(ago(facts.now, a.at))}: ${esc(a.reason)}${a.cardId ? ` (card ${esc(a.cardId)})` : ''}</li>`).join('')}</ul>`
}
export function fmtTime(iso: string | null | undefined): string {
const t = iso ? Date.parse(iso) : Number.NaN
if (!Number.isFinite(t)) return 'never'
return new Intl.DateTimeFormat('en-US', { timeZone: TZ, month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }).format(new Date(t))
}
const when = (now: number, iso: string | null | undefined) =>
iso ? `<time datetime="${esc(iso)}" title="${esc(fmtTime(iso))}">${esc(ago(now, iso))}</time>` : 'never'
const STATUS_LABEL: Record<string, [string, string]> = {
queued: ['Queued', 'st-intake'],
claimed: ['Waking Patch', 'st-running'],
woken: ['With Patch', 'st-running'],
fixed: ['Fixed', 'st-shipped'],
recommendation: ['Recommendation', 'st-needs-kent'],
noise: ['Noise', 'st-dropped'],
failed: ['No outcome', 'lvl-bad'],
skipped_execute: ['Skipped', 'st-dropped'],
}
export function statusChip(status: string): string {
const [label, cls] = STATUS_LABEL[status] ?? [status, 'off']
return `<span class="chip ${cls}">${esc(label)}</span>`
}
const LEVEL_LABEL: Record<Level, string> = { ok: 'Healthy', warn: 'Attention', bad: 'Degraded', off: 'Off', unknown: 'Unknown' }
const levelChip = (level: Level, text?: string) => `<span class="chip lvl-${level}">${esc(text ?? LEVEL_LABEL[level])}</span>`
function flashHtml(flash?: string): string {
return flash ? `<div class="flash${BAD_FLASH.test(flash) ? ' bad' : ''}" role="status">${esc(flash)}</div>` : ''
}
function postForm(bp: string, fields: Record<string, string>, label: string, opts: { cls?: string; confirm?: string; disabled?: boolean } = {}): string {
const hidden = Object.entries(fields)
.map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}"/>`)
.join('')
return `<form class="inline" method="post" action="${bp}/factory-health"${opts.confirm ? ` data-confirm="${esc(opts.confirm)}"` : ''}>${hidden}<button type="submit" class="${opts.cls ?? 'btn small'}"${opts.disabled ? ' disabled' : ''}>${esc(label)}</button></form>`
}
const SWITCH_COPY: Array<[keyof Pick<HealthConfig, 'intakeEnabled' | 'reconcileEnabled' | 'wakesEnabled'>, string, string, string]> = [
['intakeEnabled', 'Error intake', 'Record each failing run family in this org as one fingerprint. Marks known noise in Activity. Never wakes anyone.', 'Turn on error intake? Run errors in this org start being recorded as fingerprints, and known noise is marked in Activity. No wake is sent.'],
['reconcileEnabled', 'Reconcile', 'Let the sweep scan open error runs into fingerprints and mark Activity rows for recorded outcomes. Never wakes anyone.', 'Turn on reconcile? The sweep starts scanning open error runs and marking Activity rows for recorded outcomes. No wake is sent.'],
['wakesEnabled', 'Patch wakes', `Let the sweep wake Patch about queued fingerprints: at most ${MAX_WAKES_PER_HOUR} an hour, one at a time.`, 'Turn on Patch wakes? The next sweep can wake Patch about queued fingerprints, up to 3 an hour.'],
]
function switchesCard(bp: string, config: HealthConfig): string {
const rows = SWITCH_COPY.map(([key, title, desc, confirm]) => {
const on = config[key]
return `<li><div><b>${title}</b><span class="d">${desc}</span></div><div class="sw"><span class="chip ${on ? 'on' : 'off'}">${on ? 'On' : 'Off'}</span>${postForm(
bp,
{ action: 'set-switch', name: key, value: on ? '0' : '1' },
on ? 'Turn off' : 'Turn on',
{ confirm: on ? undefined : confirm },
)}</div></li>`
}).join('')
return `<section class="card" aria-labelledby="sw-h"><div class="card-head"><h2 id="sw-h">Switches</h2></div>
<p class="muted small" style="margin:-8px 0 14px">Everything starts off. Intake and reconcile never send a wake; only the last switch does.</p>
<ul class="kv">${rows}</ul></section>`
}
function hoursChart(report: HealthReport): string {
const max = Math.max(1, ...report.hours.map((h) => h.events))
const total = report.hours.reduce((n, h) => n + h.events, 0)
const bars = report.hours
.map((h) => `<i style="height:${h.events ? Math.max(8, Math.round((h.events / max) * 100)) : 2}%"${h.events ? '' : ' class="zero"'}></i>`)
.join('')
const peak = report.hours.reduce((a, b) => (b.events > a.events ? b : a))
const label = total
? `Error events per hour over the last 24 hours: ${total} in total, peaking at ${peak.events} in the hour starting ${fmtTime(`${peak.bucket}:00:00.000Z`)}.`
: 'No error events recorded in the last 24 hours.'
return `<figure class="spark-fig"><div class="spark" role="img" aria-label="${esc(label)}">${bars}</div><figcaption class="small muted"><span>24 hours ago</span><span>${total} ${total === 1 ? 'event' : 'events'}</span><span>Now</span></figcaption></figure>`
}
function signalsSection(report: HealthReport): string {
const cards = report.signals
.map(
(s) => `<article class="card hsig" aria-labelledby="sig-${s.id}"><div class="hsig-top"><h3 id="sig-${s.id}">${esc(s.title)}</h3>${levelChip(s.level)}</div>
<p class="hsig-head">${esc(s.headline)}</p><p class="muted small">${esc(s.detail)}</p>${s.id === 'intake' ? hoursChart(report) : ''}</article>`,
)
.join('')
return `<section aria-labelledby="sig-h" class="stack"><h2 id="sig-h">Health signals</h2><div class="hsigs">${cards}</div></section>`
}
function staleSection(bp: string, report: HealthReport): string {
const items = report.facts.staleItems
if (!items.length) return ''
const rows = items
.map(
(i) => `<li><div><b>${esc(i.title)}</b><span class="d">${esc(i.projectId)} · last moved ${esc(ago(report.facts.now, i.updatedAt))}</span></div><span class="chip st-${esc(i.state)}">${esc(i.state)}</span></li>`,
)
.join('')
return `<section class="card" aria-labelledby="stale-h"><div class="card-head"><h2 id="stale-h">Stuck work items</h2><a class="link" href="${bp}/work">Open work queue</a></div><ul class="kv">${rows}</ul></section>`
}
const GROUPS: Array<[string, string]> = [
['open', 'Open'],
['in-flight', 'With Patch'],
['done', 'Closed'],
['all', 'All'],
]
function listUrl(bp: string, group: string, query: string): string {
const params = new URLSearchParams()
if (group !== 'open') params.set('status', group)
if (query) params.set('q', query)
const qs = params.toString()
return `${bp}/factory-health${qs ? `?${qs}` : ''}#fingerprints`
}
export function fingerprintUrl(bp: string, fingerprint: string): string {
return `${bp}/factory-health/fingerprint?id=${encodeURIComponent(fingerprint)}`
}
function fingerprintRow(bp: string, r: FingerprintRecord, now: number): string {
const runs = r.run_ids.length
return `<li class="frow"><div class="frow-main"><a class="row-title" href="${fingerprintUrl(bp, r.fingerprint)}">${esc(r.owner)} <span class="muted">· ${esc(r.error_family)}</span></a>
<div class="row-meta"><span>${esc(r.surface)}</span><span><b>${r.count}</b> ${r.count === 1 ? 'occurrence' : 'occurrences'}</span><span>First ${when(now, r.first_seen)}</span><span>Last ${when(now, r.last_seen)}</span><span>${runs} linked ${runs === 1 ? 'run' : 'runs'}</span>${r.wake_count ? `<span>${r.wake_count} ${r.wake_count === 1 ? 'wake' : 'wakes'}</span>` : ''}</div>
${r.summary ? `<p class="small frow-sum">${esc(r.summary)}</p>` : ''}</div>${statusChip(r.status)}</li>`
}
function fingerprintsSection(opts: HealthPageOptions, bp: string): string {
const { report, fingerprints, group, query } = opts
const counts = report.facts.counts
const sum = (keys: string[]) => keys.reduce((n, k) => n + (counts[k] ?? 0), 0)
const groupCount: Record<string, number> = {
open: sum(['queued', 'claimed', 'woken', 'failed']),
'in-flight': sum(['claimed', 'woken']),
done: sum(['fixed', 'recommendation', 'noise', 'skipped_execute']),
all: sum(Object.keys(counts)),
}
const tabs = GROUPS.map(
([value, label]) => `<a href="${listUrl(bp, value, query)}"${value === group ? ' aria-current="true"' : ''}>${label} <span class="n">${groupCount[value] ?? 0}</span></a>`,
).join('')
const empty = query
? 'No fingerprint matches that search.'
: !opts.report.facts.config.intakeEnabled && !groupCount.all
? 'Nothing recorded yet. Turn on error intake, or run a reconcile, to start the feed.'
: 'Nothing here. No fingerprint is in this state.'
const list = fingerprints.length
? `<ul class="list flist">${fingerprints.map((r) => fingerprintRow(bp, r, report.facts.now)).join('')}</ul>`
: `<div class="card empty"><div class="bubble">${icon('check')}</div><p>${esc(empty)}</p></div>`
return `<section aria-labelledby="fp-h" class="stack" id="fingerprints"><h2 id="fp-h">Error fingerprints</h2>
<p class="muted small" style="margin-top:-8px">One row per failing run family in the ${esc(opts.org)} org: surface, owner, and error family.</p>
<form class="toolbar" method="get" action="${bp}/factory-health" role="search">
${group !== 'open' ? `<input type="hidden" name="status" value="${esc(group)}"/>` : ''}
<label class="search"><span class="sr">Search fingerprints</span>${icon('search')}<input type="search" name="q" value="${esc(query)}" placeholder="Search fingerprints or messages" autocomplete="off"/></label>
<button type="submit" class="btn">Search</button>
<nav class="tabs" aria-label="Filter by status">${tabs}</nav>
</form>
<p class="muted small" role="status">${fingerprints.length} shown</p>
${list}</section>`
}
export type HealthPageOptions = {
basePath: string
report: HealthReport
fingerprints: FingerprintRecord[]
group: string
query: string
org: string
flash?: string
}
export function renderHealth(opts: HealthPageOptions): string {
const bp = esc(opts.basePath)
const { report } = opts
const { facts } = report
const counts = facts.counts
const snapshot = facts.snapshot
const stat = (label: string, value: string | number, sub: string) => `<div class="stat"><span>${label}</span><b>${esc(value)}</b><small>${esc(sub)}</small></div>`
const reasons = report.reasons.length
? `<ul class="reasons">${report.reasons.map((r) => `<li>${esc(r)}</li>`).join('')}</ul>`
: `<p class="muted">${report.level === 'off' ? 'The feed is switched off, so there is nothing to judge yet.' : 'No signal needs attention.'}</p>`
const main = `
<header class="page-head"><div><h1>Factory health</h1><p>The factory looking at itself: its jobs, its intake, what is stuck, and the run errors in this org.</p></div></header>
${flashHtml(opts.flash)}
<section class="card hsummary lvl-${report.level}" aria-labelledby="ov-h">
<div class="hsummary-top"><div><span class="eyebrow">Overall</span><h2 id="ov-h">${esc(report.summary)}</h2></div>${levelChip(report.level, report.summary)}</div>
${reasons}
<div class="row-btns">${postForm(bp, { action: 'sweep' }, 'Run reconcile now', { cls: 'btn', disabled: !facts.config.reconcileEnabled, confirm: 'Run one reconcile sweep now? It scans open error runs across this org into fingerprints and marks Activity rows for known noise and recorded outcomes. It only wakes Patch if the wakes switch is on.' })}${postForm(bp, { action: 'refresh-signals' }, 'Refresh signals', { cls: 'btn' })}</div>
${facts.config.reconcileEnabled ? '' : '<p class="small muted">Run reconcile now is unavailable while the Reconcile switch is off: a reconcile writes Activity triage across this org.</p>'}
<p class="small muted">Platform signals read ${snapshot ? when(facts.now, snapshot.collectedAt) : 'never'}. Times shown in Mountain Time.</p>
</section>
<section aria-labelledby="hs-h"><h2 id="hs-h" class="sr">Key numbers</h2><div class="stats">
${stat('Queued', counts.queued ?? 0, 'Waiting for triage')}
${stat('With Patch', (counts.claimed ?? 0) + (counts.woken ?? 0), `${facts.wakesThisHour} of ${MAX_WAKES_PER_HOUR} wakes used this hour`)}
${stat('No outcome', counts.failed ?? 0, 'Woken, nothing recorded')}
${stat('Closed', (counts.fixed ?? 0) + (counts.recommendation ?? 0) + (counts.noise ?? 0) + (counts.skipped_execute ?? 0), `${counts.fixed ?? 0} fixed, ${counts.recommendation ?? 0} to decide, ${counts.noise ?? 0} noise`)}
</div></section>
${signalsSection(report)}
${staleSection(bp, report)}
${fingerprintsSection(opts, bp)}
<div class="settings">
${switchesCard(bp, facts.config)}
<section class="card stack" aria-labelledby="wk-h"><div class="card-head" style="margin:0"><h2 id="wk-h">Wake path</h2></div>
<p class="muted small">Every wake goes through <code>@kody/wake-relay</code>, which holds each bot's wake URL and key. The check sends one dry-run wake request that the relay logs without posting.</p>
${wakeAlertsHtml(facts)}
<div class="row-btns">${postForm(bp, { action: 'check-wake' }, 'Check wake path', { cls: 'btn' })}${facts.lease?.fingerprint ? postForm(bp, { action: 'release-lease' }, 'Release wake lease', { cls: 'btn', confirm: 'Release the wake lease? Only do this when a wake died without recording an outcome.' }) : ''}</div>
<p class="small muted">${facts.lease?.fingerprint ? `Lease held ${esc(ago(facts.now, facts.lease.acquired_at))} by ${esc(facts.lease.fingerprint)}.` : 'No wake lease is held.'}</p>
</section>
</div>`
return renderShell({ basePath: opts.basePath, view: 'health', title: 'Factory health', main })
}
const TIMELINE_LABEL: Record<string, string> = {
'first-seen': 'First seen',
requeued: 'Queued again',
wake: 'Patch woken',
're-wake': 'Patch woken again',
'wake-failed': 'Wake not sent',
outcome: 'Outcome recorded',
skipped: 'Skipped',
}
export function renderFingerprint(opts: {
basePath: string
record: FingerprintRecord
timeline: TimelineEvent[]
config: HealthConfig
wakesThisHour: number
now: number
flash?: string
}): string {
const bp = esc(opts.basePath)
const { record: r, now } = opts
const id = esc(r.fingerprint)
const runs = r.run_ids.length
? `<ul class="runs">${r.run_ids
.map((runId) => `<li><a href="${esc(activityUrlFor(ACTIVITY_ORIGIN, r.org, runId))}" rel="noreferrer">${icon('external')}<span>${esc(runId)}</span></a>${runId === r.sample_run_id ? ' <span class="chip">Latest</span>' : ''}</li>`)
.join('')}</ul>`
: '<p class="muted">No runs linked.</p>'
const timeline = opts.timeline.length
? `<ol class="events">${opts.timeline
.map((e) => `<li><b>${esc(TIMELINE_LABEL[e.kind] ?? e.kind)}</b> <span class="muted">by ${esc(e.actor)} · ${when(now, e.at)}</span>${e.detail ? `<div>${esc(e.detail)}</div>` : ''}</li>`)
.join('')}</ol>`
: '<p class="muted">Nothing recorded yet.</p>'
const capLeft = Math.max(0, MAX_WAKES_PER_HOUR - opts.wakesThisHour)
const wakeNote = !opts.config.wakesEnabled
? 'Patch wakes are switched off, so nothing is sent. Turn the switch on from Factory health first.'
: capLeft === 0
? `The hourly cap of ${MAX_WAKES_PER_HOUR} wakes is used up. Try again next hour.`
: `Sends this fingerprint to Patch now. ${capLeft} of ${MAX_WAKES_PER_HOUR} wakes left this hour.`
const outcomeChoice = (value: string, label: string, sub: string) =>
`<label class="theme-opt"><input type="radio" name="outcome" value="${value}" required${r.outcome === value ? ' checked' : ''}/><span><b>${label}</b><small>${sub}</small></span></label>`
const main = `
<nav aria-label="Breadcrumb" class="crumb"><a href="${bp}/factory-health#fingerprints">Factory health</a><span aria-hidden="true">/</span><span>Fingerprint</span></nav>
<header class="page-head"><div><h1 class="fp-title">${esc(r.owner)}</h1><p class="repo">${id}</p></div>${statusChip(r.status)}</header>
${flashHtml(opts.flash)}
<div class="grid2">
<div class="stack">
<section class="card stack" aria-labelledby="fd-h"><h2 id="fd-h">What is failing</h2>
<div class="body-text">${esc(r.sample_message || 'No message recorded.')}</div>
<dl class="meta">
<dt>Org</dt><dd>${esc(r.org)}</dd>
<dt>Surface</dt><dd>${esc(r.surface)}</dd>
<dt>Owner</dt><dd>${esc(r.owner)}</dd>
<dt>Error family</dt><dd>${esc(r.error_family)}</dd>
<dt>Occurrences</dt><dd>${r.count}</dd>
<dt>First seen</dt><dd>${esc(fmtTime(r.first_seen))} (${esc(ago(now, r.first_seen))})</dd>
<dt>Last seen</dt><dd>${esc(fmtTime(r.last_seen))} (${esc(ago(now, r.last_seen))})</dd>
<dt>Wakes</dt><dd>${r.wake_count}${r.woken_at ? `, last ${esc(ago(now, r.woken_at))}` : ''}</dd>
</dl></section>
<section class="card stack" aria-labelledby="fo-h"><h2 id="fo-h">Outcome</h2>
${r.outcome ? `<p>${statusChip(r.outcome === 'failed' ? 'failed' : r.outcome)} <span class="muted small">recorded ${when(now, r.completed_at)}${r.classification ? ` · ${esc(r.classification)}` : ''}</span></p>` : '<p class="muted">No outcome recorded yet.</p>'}
${r.summary ? `<div class="body-text">${esc(r.summary)}</div>` : ''}
${r.pr_url && /^https:\/\//.test(r.pr_url) ? `<p><a href="${esc(r.pr_url)}" rel="noreferrer">${esc(r.pr_url)}</a></p>` : ''}
</section>
<section class="card stack" aria-labelledby="fr-h"><h2 id="fr-h">Linked runs</h2><p class="muted small">The ${r.run_ids.length === 1 ? 'latest run' : `latest ${r.run_ids.length} runs`} in ${esc(r.org)} Activity, newest first.</p>${runs}</section>
<section class="card stack" aria-labelledby="ft-h"><h2 id="ft-h">History</h2>${timeline}</section>
</div>
<div class="stack">
<section class="card" aria-labelledby="fa-h"><h2 id="fa-h">Mark an outcome</h2>
<form method="post" action="${bp}/factory-health" class="stack" style="margin-top:14px">
<input type="hidden" name="action" value="outcome"/><input type="hidden" name="fingerprint" value="${id}"/>
<fieldset class="theme-group"><legend>Outcome</legend>
${outcomeChoice('fixed', 'Fixed', 'The cause is fixed. Matching open Activity rows are marked resolved.')}
${outcomeChoice('recommendation', 'Recommendation', 'A person needs to decide. Activity rows stay open.')}
${outcomeChoice('noise', 'Noise', 'Not worth fixing. Activity rows are marked resolved, and repeats stay closed.')}
</fieldset>
<label class="field">Summary <small>Optional. What was wrong, or what you recommend.</small><textarea name="summary" maxlength="1800">${esc(r.summary ?? '')}</textarea></label>
<label class="field">Pull request <small>Optional link.</small><input type="url" name="prUrl" value="${esc(r.pr_url ?? '')}" placeholder="https://github.com/owner/repo/pull/1" inputmode="url"/></label>
<div><button type="submit" class="btn primary">Save outcome</button></div>
</form></section>
<section class="card stack" aria-labelledby="fw-h"><h2 id="fw-h">Wake Patch again</h2>
<p class="muted small">${esc(wakeNote)}</p>
<div>${postForm(bp, { action: 'rewake', fingerprint: r.fingerprint }, 'Wake Patch again', {
cls: 'btn',
disabled: !opts.config.wakesEnabled || capLeft === 0,
confirm: 'Wake Patch about this fingerprint now? This sends one wake.',
})}</div>
</section>
</div>
</div>`
return renderShell({ basePath: opts.basePath, view: 'health', title: `${r.owner} · Factory health`, main })
}
export function renderFingerprintMissing(basePath: string): string {
const bp = esc(basePath)
return renderShell({
basePath,
view: 'health',
title: 'Fingerprint not found',
main: `<header class="page-head"><div><h1>Fingerprint not found</h1><p>It may have been recorded under a different id.</p></div></header><p><a class="btn" href="${bp}/factory-health">Back to Factory health</a></p>`,
})
}