/** * 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 '

No undelivered wakes on record.

' return `` } 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 ? `` : 'never' const STATUS_LABEL: Record = { 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 `${esc(label)}` } const LEVEL_LABEL: Record = { ok: 'Healthy', warn: 'Attention', bad: 'Degraded', off: 'Off', unknown: 'Unknown' } const levelChip = (level: Level, text?: string) => `${esc(text ?? LEVEL_LABEL[level])}` function flashHtml(flash?: string): string { return flash ? `
${esc(flash)}
` : '' } function postForm(bp: string, fields: Record, label: string, opts: { cls?: string; confirm?: string; disabled?: boolean } = {}): string { const hidden = Object.entries(fields) .map(([k, v]) => ``) .join('') return `
${hidden}
` } const SWITCH_COPY: Array<[keyof Pick, 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 `
  • ${title}${desc}
    ${on ? 'On' : 'Off'}${postForm( bp, { action: 'set-switch', name: key, value: on ? '0' : '1' }, on ? 'Turn off' : 'Turn on', { confirm: on ? undefined : confirm }, )}
  • ` }).join('') return `

    Switches

    Everything starts off. Intake and reconcile never send a wake; only the last switch does.

      ${rows}
    ` } 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) => ``) .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 `
    24 hours ago${total} ${total === 1 ? 'event' : 'events'}Now
    ` } function signalsSection(report: HealthReport): string { const cards = report.signals .map( (s) => `

    ${esc(s.title)}

    ${levelChip(s.level)}

    ${esc(s.headline)}

    ${esc(s.detail)}

    ${s.id === 'intake' ? hoursChart(report) : ''}
    `, ) .join('') return `

    Health signals

    ${cards}
    ` } function staleSection(bp: string, report: HealthReport): string { const items = report.facts.staleItems if (!items.length) return '' const rows = items .map( (i) => `
  • ${esc(i.title)}${esc(i.projectId)} · last moved ${esc(ago(report.facts.now, i.updatedAt))}
    ${esc(i.state)}
  • `, ) .join('') return `

    Stuck work items

    Open work queue
      ${rows}
    ` } 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 `
  • ${esc(r.owner)} · ${esc(r.error_family)}
    ${esc(r.surface)}${r.count} ${r.count === 1 ? 'occurrence' : 'occurrences'}First ${when(now, r.first_seen)}Last ${when(now, r.last_seen)}${runs} linked ${runs === 1 ? 'run' : 'runs'}${r.wake_count ? `${r.wake_count} ${r.wake_count === 1 ? 'wake' : 'wakes'}` : ''}
    ${r.summary ? `

    ${esc(r.summary)}

    ` : ''}
    ${statusChip(r.status)}
  • ` } 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 = { 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]) => `${label} ${groupCount[value] ?? 0}`, ).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 ? `
      ${fingerprints.map((r) => fingerprintRow(bp, r, report.facts.now)).join('')}
    ` : `
    ${icon('check')}

    ${esc(empty)}

    ` return `

    Error fingerprints

    One row per failing run family in the ${esc(opts.org)} org: surface, owner, and error family.

    ${fingerprints.length} shown

    ${list}
    ` } 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) => `
    ${label}${esc(value)}${esc(sub)}
    ` const reasons = report.reasons.length ? `
      ${report.reasons.map((r) => `
    • ${esc(r)}
    • `).join('')}
    ` : `

    ${report.level === 'off' ? 'The feed is switched off, so there is nothing to judge yet.' : 'No signal needs attention.'}

    ` const main = `

    Factory health

    The factory looking at itself: its jobs, its intake, what is stuck, and the run errors in this org.

    ${flashHtml(opts.flash)}
    Overall

    ${esc(report.summary)}

    ${levelChip(report.level, report.summary)}
    ${reasons}
    ${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' })}
    ${facts.config.reconcileEnabled ? '' : '

    Run reconcile now is unavailable while the Reconcile switch is off: a reconcile writes Activity triage across this org.

    '}

    Platform signals read ${snapshot ? when(facts.now, snapshot.collectedAt) : 'never'}. Times shown in Mountain Time.

    Key numbers

    ${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`)}
    ${signalsSection(report)} ${staleSection(bp, report)} ${fingerprintsSection(opts, bp)}
    ${switchesCard(bp, facts.config)}

    Wake path

    Every wake goes through @kody/wake-relay, which holds each bot's wake URL and key. The check sends one dry-run wake request that the relay logs without posting.

    ${wakeAlertsHtml(facts)}
    ${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.' }) : ''}

    ${facts.lease?.fingerprint ? `Lease held ${esc(ago(facts.now, facts.lease.acquired_at))} by ${esc(facts.lease.fingerprint)}.` : 'No wake lease is held.'}

    ` return renderShell({ basePath: opts.basePath, view: 'health', title: 'Factory health', main }) } const TIMELINE_LABEL: Record = { '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 ? `` : '

    No runs linked.

    ' const timeline = opts.timeline.length ? `
      ${opts.timeline .map((e) => `
    1. ${esc(TIMELINE_LABEL[e.kind] ?? e.kind)} by ${esc(e.actor)} · ${when(now, e.at)}${e.detail ? `
      ${esc(e.detail)}
      ` : ''}
    2. `) .join('')}
    ` : '

    Nothing recorded yet.

    ' 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) => `` const main = `

    ${esc(r.owner)}

    ${id}

    ${statusChip(r.status)}
    ${flashHtml(opts.flash)}

    What is failing

    ${esc(r.sample_message || 'No message recorded.')}
    Org
    ${esc(r.org)}
    Surface
    ${esc(r.surface)}
    Owner
    ${esc(r.owner)}
    Error family
    ${esc(r.error_family)}
    Occurrences
    ${r.count}
    First seen
    ${esc(fmtTime(r.first_seen))} (${esc(ago(now, r.first_seen))})
    Last seen
    ${esc(fmtTime(r.last_seen))} (${esc(ago(now, r.last_seen))})
    Wakes
    ${r.wake_count}${r.woken_at ? `, last ${esc(ago(now, r.woken_at))}` : ''}

    Outcome

    ${r.outcome ? `

    ${statusChip(r.outcome === 'failed' ? 'failed' : r.outcome)} recorded ${when(now, r.completed_at)}${r.classification ? ` · ${esc(r.classification)}` : ''}

    ` : '

    No outcome recorded yet.

    '} ${r.summary ? `
    ${esc(r.summary)}
    ` : ''} ${r.pr_url && /^https:\/\//.test(r.pr_url) ? `

    ${esc(r.pr_url)}

    ` : ''}

    Linked runs

    The ${r.run_ids.length === 1 ? 'latest run' : `latest ${r.run_ids.length} runs`} in ${esc(r.org)} Activity, newest first.

    ${runs}

    History

    ${timeline}

    Mark an outcome

    Outcome ${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.')}

    Wake Patch again

    ${esc(wakeNote)}

    ${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.', })}
    ` 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: `

    Fingerprint not found

    It may have been recorded under a different id.

    Back to Factory health

    `, }) }