import { lazy, Suspense, useState, type ReactNode } from 'react'; import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'; import { PageHeader } from '../components/ui/PageHeader'; import { Callout } from '../components/ui/Callout'; import { Disclosure } from '../components/ui/Disclosure'; import { Badge } from '../components/ui/Badge'; import { SkeletonCard, SkeletonTable } from '../components/ui/Skeleton'; import { useAuthStore } from '../stores/authStore'; import { FUNDAMENTAL_VISUAL } from '../lib/regime'; import { getEventStudy, getRegimeConfig, getRegimeFundamentals, getRegimeMonitor, refreshRegimeFundamentals, updateRegimeConfig, updateRegimeFundamentals, } from '../api/regime'; import type { CapexState, FundamentalState, EventStudyMetrics, EventStudyReport, GoodNewsReaction, RegimeBand, RegimeConfig, RegimeFundamentalContext, RegimeFundamentals, RegimeFundamentalsUpdate, RegimeMonitor, RegimeReading, } from '../lib/types'; const RegimeChart = lazy(() => import('../components/regime/RegimeChart')); const BAND_STYLES: Record = { stable: { text: 'text-emerald-400', bar: 'bg-emerald-400', ring: 'border-emerald-400/30', label: 'Stable' }, watch: { text: 'text-amber-400', bar: 'bg-amber-400', ring: 'border-amber-400/30', label: 'Watch' }, elevated: { text: 'text-orange-400', bar: 'bg-orange-400', ring: 'border-orange-400/30', label: 'Elevated' }, breaking: { text: 'text-red-400', bar: 'bg-red-400', ring: 'border-red-400/30', label: 'High stress' }, }; function TrendChip({ label, delta }: { label: string; delta: number | null | undefined }) { if (delta == null) { return {label}: n/a; } const color = delta === 0 ? 'text-gray-400' : delta > 0 ? 'text-red-400' : 'text-emerald-400'; const arrow = delta === 0 ? '→' : delta > 0 ? '↑' : '↓'; return ( {label}: {arrow} {delta > 0 ? '+' : ''}{delta} ); } function ScoreGauge({ label, reading, footnote, }: { label: string; reading: RegimeReading | undefined; footnote: ReactNode; }) { const score = reading?.score; const complete = reading?.band != null; const style = complete ? BAND_STYLES[reading.band as RegimeBand] : null; const position = Math.min(100, Math.max(0, score ?? 0)); const bands = reading?.bands; // No fallback ticks: the two axes have different thresholds, so guessing a // shared set would mislabel one of them. Render none rather than wrong ones. const ticks = bands ? [bands.watch, bands.elevated, bands.breaking] : []; return (
{label}
{score == null ? '—' : Math.round(score)} {score != null && / 100}
{style?.label ?? 'Incomplete'} coverage {Math.round(reading?.coverage ?? 0)}%
{score != null && ( <> {/* The quadrant divider is each axis's watch/elevated boundary, so it is already the middle tick below — drawing it again was two marks for one threshold. */}
{/* Thresholds come from the reading: the two axes no longer share them. */}
0 {ticks.map((tick) => ( {tick} ))} 100
)}

{footnote}

); } /** Mirrors `_capex_signal`: holding is the neutral case, so it takes the neutral * colour rather than an amber that reads as a third severity and sits close to * the Warning channel's orange. */ const CAPEX_COLOR: Record = { raising: FUNDAMENTAL_VISUAL.supportive.color, holding: FUNDAMENTAL_VISUAL.neutral.color, cutting: FUNDAMENTAL_VISUAL.adverse.color, unknown: FUNDAMENTAL_VISUAL.unknown.color, }; function sentenceCase(value: string): string { const text = value.replace(/_/g, ' '); return text.charAt(0).toUpperCase() + text.slice(1); } function reactionReading(reaction: GoodNewsReaction | null): { label: string; color: string } { switch (reaction) { case 'yes': return { label: 'Yes · good news sold', color: FUNDAMENTAL_VISUAL.adverse.color }; case 'no': return { label: 'No · ordinary reactions', color: FUNDAMENTAL_VISUAL.supportive.color }; case 'mixed': return { label: 'Mixed · no clear pattern', color: FUNDAMENTAL_VISUAL.neutral.color }; default: return { label: 'Unknown · not observed', color: FUNDAMENTAL_VISUAL.unknown.color }; } } function FundamentalSummaryCard({ overlay }: { overlay: RegimeFundamentalContext }) { const tone = FUNDAMENTAL_VISUAL[overlay.state] ?? FUNDAMENTAL_VISUAL.unknown; const observed = overlay.observed ?? Boolean(overlay.fetched_at); const status = !observed ? 'No usable observation. This channel remains Unknown.' : overlay.pending ? `Collected now; enters the point-in-time record ${overlay.effective_date ?? 'next session'}.` : overlay.stale ? 'The last state is retained for context, but stale evidence cannot confirm alerts.' : !overlay.usable ? 'An observation was collected, but no signal could be determined.' : null; return (
Fundamentals · context
{overlay.pending && } {overlay.stale && }
{tone.label} {sentenceCase(overlay.evidence_quality)} evidence
Capex
{sentenceCase(overlay.capex_signal)}
Reaction
{sentenceCase(overlay.reaction_signal)}
{status &&

{status}

} {(overlay.source || overlay.effective_date) && (

{overlay.source ?? 'stored observation'} {overlay.effective_date && ` · effective ${overlay.effective_date}`}

)}
); } function FundamentalEvidence({ overlay }: { overlay: RegimeFundamentalContext }) { const observed = overlay.observed ?? Boolean(overlay.fetched_at); if (!observed) return null; const capex = overlay.capex ?? {}; const reaction = reactionReading(overlay.good_news_stock_down); return (
Hyperscaler capex guidance
{Object.keys(capex).length === 0 ? (

No company-level observation.

) : (
{Object.entries(capex).map(([symbol, state]) => (
{symbol} {sentenceCase(state)}
))}
)}
Good news, stock down
{reaction.label}

Derived context: capex {overlay.capex_signal} · reaction {overlay.reaction_signal}.

{overlay.reasoning && (
Source reasoning

{overlay.reasoning}

)}
); } function ConfluenceStrip({ warning, context }: { warning: RegimeReading; context?: RegimeFundamentalContext }) { const warningElevated = warning.band === 'elevated' || warning.band === 'breaking'; if (!warningElevated || !context?.usable || context.state !== 'adverse') return null; return (
); } /** One table for both axes — they share a shape, and two panels invited * comparing numbers that are not on the same scale. */ function PillarTable({ state, warning }: { state: RegimeReading; warning: RegimeReading }) { const groups: { title: string; reading: RegimeReading }[] = [ { title: 'State', reading: state }, { title: 'Warning', reading: warning }, ]; return (
{groups.map(({ title, reading }) => ( {reading.pillars.map((pillar) => ( ))} ))}
Pillar / sensor Score Weight Contribution
{title} {reading.score ?? '—'} · {Math.round(reading.coverage)}% coverage
{pillar.label}
{pillar.sensors.map((sensor) => (
{sensor.id} {sensor.label}:{' '} {sensor.score == null ? 'n/a' : sensor.score}
))}
{pillar.score ?? '—'} {pillar.weight} {pillar.available ? pillar.contribution.toFixed(1) : '—'}
); } function MetaChip({ label, value, title }: { label: string; value: ReactNode; title?: string }) { return ( {label} {value} ); } /** Provenance strip — replaces three separate prose blocks. */ function MetaStrip({ data }: { data: RegimeMonitor }) { const quality = data.data_quality; const basket = data.basket; const days = (value: number | null | undefined) => (value == null ? '—' : `${value}d`); return (
{basket && ( )}
); } function StatTiles({ metrics }: { metrics: EventStudyMetrics }) { return (
{[ ['Warned', `${metrics.events_warned}/${metrics.events}`], ['Missed', metrics.events_missed], ['False alarms/year', metrics.false_alarms_per_year?.toFixed(1) ?? '—'], ['Median lead', metrics.median_lead_days == null ? '—' : `${metrics.median_lead_days}d`], ].map(([label, value]) => (
{label}
{value}
))}
); } function EventTable({ events }: { events: { date: string; warned: boolean; lead_days: number | null }[] }) { return (
{events.map((event) => ( ))}
Correction Warned Lead
{event.date} {event.warned ? 'yes' : 'no'} {event.lead_days == null ? '—' : `${event.lead_days}d`}
); } /** Shipped rule against ablations, external baselines, and chance. * * The two kinds answer different questions and must not be read as one list: * an ablation asks whether the quadrant machinery earns its place, a baseline * asks whether the score earns its complexity. */ function ComparisonTable({ report }: { report: EventStudyReport }) { const shipped = report.shipped; if (!shipped || !report.comparison?.length) return null; const rows = [ { id: 'shipped', label: 'Quadrant alert (shipped)', kind: 'shipped' as const, note: shipped.rule.entry, measurable: true, ...shipped.metrics, }, ...report.comparison, ]; const KIND_LABEL: Record = { shipped: 'shipped', ablation: 'ablation', baseline: 'baseline', fundamental: 'fundamental', }; return (
{rows.map((row) => ( {/* A rule whose input does not exist yet scores 0/N, and printing that would read as tested-and-failed. Say "not measurable". */} {row.measurable === false ? ( ) : ( <> )} ))} {report.null_model && ( )}
Rule Warned FA/yr Median lead
{row.label} {KIND_LABEL[row.kind]} {/* Not "no observations yet": once some exist but fewer than the minimum are covered, that is simply false. Matches the callout below. */} insufficient exposure — not measurable {row.events_warned}/{row.events} {row.false_alarms_per_year?.toFixed(1) ?? '—'} {row.median_lead_days == null ? '—' : `${row.median_lead_days}d`}
Random alarms, same firing rate null {report.null_model.mean_warned.toFixed(1)} ± {report.null_model.sd_warned.toFixed(1)}
); } function StudyVerdict({ report }: { report: EventStudyReport }) { const model = report.null_model; if (!model) return null; const chancePct = (model.p_at_least_observed * 100).toFixed(0); const indistinguishable = model.p_at_least_observed >= 0.1; // The number carries the claim, not the adjective. At ~10 corrections a p of // 0.09 is not evidence of anything, so "beats the null" would over-state a // result this panel is otherwise careful never to over-state. return ( {indistinguishable ? `Not distinguishable from chance (p = ${model.p_at_least_observed.toFixed(2)}).` : `Above the firing-rate null (p = ${model.p_at_least_observed.toFixed(2)}).`} {' '} Random alarms match or beat {model.observed_warned}/{model.events} warned corrections in {chancePct}% of{' '} {model.draws} draws placing {model.alarms_per_draw} alarms over the same sessions. Corrections cluster and random placement does not, so this is the floor, not the bar. ); } /** The credit sensor starts partway through, so Warning is a different * construct either side of it. The share is derived, never asserted: if one era * carries no corrections there is no comparison to draw and the per-era ratios * would be noise dressed up as a finding. */ function EraDisclosure({ eras, divider, }: { eras: NonNullable['by_era']>; divider: number | undefined; }) { const { pre_credit: pre, full_coverage: full } = eras; const total = pre.sessions + full.sessions; const share = total > 0 ? Math.round((pre.sessions / total) * 100) : 0; // An era holding one or two corrections has a recall of 0/1 or 1/2, which is // not a rate. Below this the eras get their false-alarm rates compared and // nothing else. const comparable = pre.events >= 3 && full.events >= 3; return (

{share}% of the evaluated sessions predate the credit sensor. W3 begins {eras.credit_from}, so before that Warning renormalises to W1+W2 and the fixed {divider} divider is applied to a different construct than it was reasoned about. Dropping the training split makes every correction evaluable; it does not make the coverage gap go away, it moves it from the threshold to the score. {comparable ? ( <> {' '}Two sensors:{' '} {pre.events_warned}/{pre.events} at{' '} {pre.false_alarms_per_year?.toFixed(1) ?? '—'} FA/yr. All three:{' '} {full.events_warned}/{full.events} at{' '} {full.false_alarms_per_year?.toFixed(1) ?? '—'} FA/yr. ) : ( <> {' '}The corrections do not straddle that boundary ({pre.events} before, {full.events} after), so the two eras cannot be compared on recall — only the false-alarm rates are meaningful ({pre.false_alarms_per_year?.toFixed(1) ?? '—'}{' '} vs {full.false_alarms_per_year?.toFixed(1) ?? '—'} per year). )}

); } function EventStudyBody({ report }: { report: EventStudyReport }) { const shipped = report.shipped; const eras = shipped?.by_era; return (
{report.generated_at && generated {new Date(report.generated_at).toLocaleDateString()}} {report.sample && {report.sample.evaluable_from} → {report.sample.end}}

{report.summary}

{shipped && } {shipped && shipped.events.length > 0 && ( )} {report.null_model && (

The null places {report.null_model.alarms_per_draw} alarms at random over the same sessions and at the shipped rule's firing rate. Corrections cluster while random placement does not, so this is a floor rather than a demanding benchmark: a clustering rule could beat it without genuine foresight.

)} {report.fundamental_coverage && !report.fundamental_coverage.measurable && (

Insufficient exposure — the fundamental rows are untested, not failed.{' '} The channel had usable context on{' '} {report.fundamental_coverage.sessions_eligible} of{' '} {report.fundamental_coverage.evaluable_sessions} {' '} evaluated sessions, covering{' '} {report.fundamental_coverage.events_covered} of{' '} {report.fundamental_coverage.events_evaluable} {' '} corrections ({report.fundamental_coverage.minimum_events} needed;{' '} {report.fundamental_coverage.observations} observation {report.fundamental_coverage.observations === 1 ? '' : 's'} recorded). Those rows are scored only on that window, never on the market rows' full sample — otherwise a fortnight of data would render as a 0/10 and read as a failed test. Read the market rows as a verdict on the technical sensors and the alert machinery only.

)} {eras && } {report.fitted && (

The original study, kept because it is what the methodology document reports: an{' '} {report.fitted.params.warn_percentile}th-percentile Warning threshold ( {report.fitted.params.warn_threshold}) frozen on the first{' '} {(report.fitted.params.train_fraction * 100).toFixed(0)}% of sessions and measured on the rest. Nothing consumes this rule — the shipped alert uses fixed dividers with hysteresis, confirmation and a cooldown.

{report.fitted.events.length > 0 && } {report.reliability && (report.reliability.underpowered || report.reliability.sensor_coverage_mismatch) && (
{report.reliability.underpowered && (

Underpowered. Only {report.reliability.events_in_holdout} of{' '} {report.reliability.events_detected} detected corrections fall in the holdout ( {report.reliability.minimum_events}+ needed). Read the direction, not the ratio.

)} {report.reliability.sensor_coverage_mismatch && (

Sensor coverage differs across the split.{' '} {report.reliability.train_full_sensor_share}% of training sessions had all{' '} {report.reliability.sensors_expected} Warning sensors versus{' '} {report.reliability.holdout_full_sensor_share}% of test sessions {report.params?.credit_sensor_from && ` — credit history begins ${report.params.credit_sensor_from}`} . The threshold was frozen on a partly different construct than it is measured against.

)}
)}
)}
); } function EventStudyPanel() { const study = useQuery({ queryKey: ['regime', 'event-study'], queryFn: getEventStudy }); return ( {study.isLoading && } {study.data === null && Not run yet — trigger “Event Study” in Admin → Jobs.} {study.data && !study.data.available && {study.data.reason ?? 'No data'}} {study.data?.available && } ); } const SELECT_CLASS = 'rounded-md border border-white/[0.08] bg-white/[0.03] px-2 py-1.5 text-xs text-gray-200'; const CAPEX_OPTIONS: { value: CapexState; label: string }[] = [ { value: 'raising', label: 'Raising' }, { value: 'holding', label: 'Holding' }, { value: 'cutting', label: 'Cutting' }, { value: 'unknown', label: 'Unknown' }, ]; function FundamentalsEditor({ data, onSave, onRefresh, saving, refreshing, }: { data: RegimeFundamentals; onSave: (body: RegimeFundamentalsUpdate) => void; onRefresh: () => void; saving: boolean; refreshing: boolean; }) { const [capex, setCapex] = useState>(() => ({ ...data.capex })); const [reaction, setReaction] = useState(data.good_news_stock_down); const values = Object.values(capex); const counts = { cutting: values.filter((s) => s === 'cutting').length, holding: values.filter((s) => s === 'holding').length, raising: values.filter((s) => s === 'raising').length, unknown: values.filter((s) => s === 'unknown').length, }; // Mirrors _capex_signal: any cut is adverse on partial evidence, any hold is // neutral, all-known-raising is supportive, nothing known is unknown. No // average — an average would let cuts and unknowns land on "neutral". const capexSignal: FundamentalState = counts.cutting > 0 ? 'adverse' : counts.holding > 0 ? 'neutral' : counts.raising > 0 ? 'supportive' : 'unknown'; const reactionSignal: FundamentalState = reaction === 'yes' ? 'adverse' : reaction === 'no' ? 'supportive' : reaction === 'mixed' ? 'neutral' : 'unknown'; return (
Source: {data.source} {data.fetched_at && · fetched {new Date(data.fetched_at).toLocaleDateString()}} {data.effective_date && · effective {data.effective_date}} {data.locked && }
{data.reasoning &&

{data.reasoning}

}
Capex guidance by hyperscaler {capexSignal}
{Object.entries(capex).map(([symbol, state]) => ( ))}

{counts.cutting} cutting · {counts.holding} holding · {counts.raising} raising · {counts.unknown} unknown. Any cut reads adverse on partial evidence; supportive needs every known name raising.

{data.locked && }
); } function ConfigEditor({ data, onSave, saving }: { data: RegimeConfig; onSave: (updates: Partial) => void; saving: boolean }) { const [basket, setBasket] = useState(data.breadth_basket.join(', ')); const [staleness, setStaleness] = useState(data.fundamental_staleness_days); const symbols = basket.split(/[\s,]+/).map((symbol) => symbol.trim().toUpperCase()).filter(Boolean); return (