# Integrate `Visualizer` from Motion Garden

You are helping me add the **Visualizer** component to an existing project.
Everything you need is below — full source, dependencies, props and the
behavioural contract. Read it all before writing anything.

- **Component:** Visualizer
- **Category:** Power-User Systems
- **Summary:** A live map of a multi-agent system: the orchestrator burns at the centre with a tick ring of its own daily load, agent pools sit on the inner ring with beams sized by their share, and every agent and tool orbits its pool. Sparks ride the beams home, faster where the work is fresher. Hover for a readout, filter to a week, or pick an agent and it glides out of the constellation into a drilldown of its latest runs, blocked work and timing. All geometry is pure and deterministic: labels are placed against collision boxes rather than measured, and orbs shrink until nothing touches. The keyboard walks the ring clockwise, and below 640px it becomes a ranked list.
- **Reference:** https://motion-garden.netlify.app/components/visualizer
- **Full catalog (for you, the agent):** https://motion-garden.netlify.app/llms.txt

## Stack this source assumes

- React 19 with the Next.js App Router (never the `pages/` directory)
- TypeScript, strict
- Tailwind CSS v4, CSS-first config (utilities are inline; no `tailwind.config` needed)

If my project differs, adapt the integration — but do not rewrite the animation math to suit a different stack. Ask me first.

## Dependencies

```bash
bun add lucide-react clsx tailwind-merge
```

## Design tokens this source uses

Some classes in the source are Motion Garden theme tokens, not stock Tailwind (`text-ink`, `bg-panel`, `font-display` and the like). Without them, parts of the component render unstyled. Add this to my global CSS, after the Tailwind import:

```css
@theme inline {
  --color-panel: var(--sg-panel);
  --color-raised: var(--sg-raised);
  --color-hairline: var(--sg-hairline);
  --color-ink: var(--sg-ink);
  --color-ink-dim: var(--sg-ink-dim);
  --color-ink-mute: var(--sg-ink-mute);
  --color-accent: var(--sg-accent);
  --color-accent-muted: var(--sg-accent-muted);
}

:root {
  --sg-panel: #ffffff;
  --sg-raised: #eceaef;
  --sg-hairline: #dde2e7;
  --sg-ink: #16191d;
  --sg-ink-dim: #545b64;
  --sg-ink-mute: #878e97;
  --sg-accent: #7e22ce;
  --sg-accent-muted: #d8b4fe;
}

.dark {
  --sg-panel: #101215;
  --sg-raised: #191d21;
  --sg-hairline: #2a2f36;
  --sg-ink: #e2e6e9;
  --sg-ink-dim: #bcc2c8;
  --sg-ink-mute: #6c737c;
  --sg-accent: #a855f7;
  --sg-accent-muted: #5b3a7a;
}
```

The values are Motion Garden's own light and dark themes. If my project already has tokens for these roles, point the `--sg-*` variables at mine instead and tell me which you mapped. `.dark` assumes class-based dark mode — adapt the selector to how my project switches themes.

## Files to create

14 files — all of them are required. Paths are as shipped; the component may live anywhere in my project, but keep every peer file at the exact path shown so the import aliases resolve.

### 1. `components/registry/visualizer/visualizer.tsx`

```tsx
"use client";

import * as React from "react";
import { List as ListIcon, Orbit as OrbitIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { BackButton, Drilldown, Kbd } from "./drilldown";
import { displayName, formatCount, plural, READOUT } from "./format";
import { useContainerWidth, useInView, useNow, usePageVisible } from "./hooks";
import {
	MAX_SENDERS,
	categoryShares,
	combinedDaily,
	layoutFocus,
	layoutOrbit,
	normalizeSenders,
	type OrbitSender,
	type WeekIndex,
} from "./layout";
import { OrbitList } from "./list";
import { BEAM_MS, BLOOM_MS, EASE, IGNITION_MS } from "./motion";
import { TimeRail } from "./rail";
import { OrbitScene, makeOrbitIds, type SceneFocus } from "./scene";
import { Segmented } from "./segmented";
import type { OrbitGroup, OrbitNodeData } from "./types";
import { AGENT_VOCAB, capitalize, type OrbitVocab } from "./vocab";

type View = "constellation" | "list";
type WeekKey = "all" | "w1" | "w2" | "w3" | "w4";
type WeekOption = { key: WeekKey; label: string; spoken: string; week: WeekIndex | null };

const WEEK_KEYS = ["w1", "w2", "w3", "w4"] as const;

function weekOptions(period: OrbitVocab["period"]): WeekOption[] {
	if (!period) return [{ key: "all", label: "", spoken: "", week: null }];
	return [
		{ key: "all", ...period.all, week: null },
		...period.weeks.slice(0, 4).map(([label, spoken], i) => ({ key: WEEK_KEYS[i]!, label, spoken, week: i as WeekIndex })),
	];
}

const LIST_BELOW = 640;
const PUSH = 1.3;
const NO_GROUPS: OrbitGroup[] = [];

function stageHeight(width: number): number {
	if (width >= 1024) return 470;
	if (width >= 768) return 450;
	if (width >= LIST_BELOW) return 420;
	return Math.round(Math.min(420, Math.max(320, width)));
}

const STYLES = `
@keyframes co-rise { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
@keyframes co-bloom { from { opacity: 0; transform: scale(0.6); } 60% { opacity: 1; transform: scale(1.03); } to { opacity: 1; transform: scale(1); } }
@keyframes co-draw { to { stroke-dashoffset: 0; } }
@keyframes co-fade { from { opacity: 0; } }
@keyframes co-ignite { from { opacity: 0; transform: scale(0.97); } }
@keyframes co-comet { from { offset-distance: 0%; opacity: 0; } 8% { opacity: 1; } 85% { opacity: 1; } to { offset-distance: 100%; opacity: 0; } }
@keyframes co-flare { 0% { opacity: 0; transform: scale(0.6); } 12% { opacity: 0.9; } to { opacity: 0; transform: scale(2.4); } }
@keyframes co-dust { 0% { opacity: 0; transform: none; } 15% { opacity: 1; } to { opacity: 0; transform: translate(var(--dx), var(--dy)); } }
@keyframes co-dolly { from { transform: scale(1.12); } }
[data-co] .co-entrance { animation: co-rise 320ms ${EASE} backwards; animation-delay: calc(var(--i, 0) * 55ms + 60ms); }
[data-co] .co-bloom { animation: co-bloom ${BLOOM_MS}ms ${EASE} both; }
[data-co] .co-fade { animation: co-fade 360ms ${EASE} backwards; }
[data-co] .co-draw-on { stroke-dasharray: 1; stroke-dashoffset: 1; animation: co-draw ${BEAM_MS}ms ${EASE} forwards; animation-delay: var(--draw-delay, 380ms); }
[data-co] .co-comet { offset-rotate: auto; animation: co-comet ${BEAM_MS}ms ${EASE} both; }
[data-co] .co-flare { animation: co-flare 700ms ${EASE} both; }
[data-co] .co-dust { animation: co-dust 1100ms cubic-bezier(0.2, 0.7, 0.3, 1) both; }
[data-co] .co-dolly { animation: co-dolly 1600ms ${EASE} backwards; }
[data-co][data-intro="off"] :is(.co-entrance, .co-bloom, .co-fade, .co-dolly) { animation: none; }
[data-co][data-intro="off"] .co-draw-on { animation-duration: 1ms; animation-delay: 0ms; }
[data-co][data-hold] * { animation-play-state: paused; }
[data-co][data-paused] :is(.animate-pulse, .co-flare) { animation-play-state: paused; }
[data-co] .orbit-halo { paint-order: stroke; stroke-linejoin: round; stroke-width: 3.5px; stroke: var(--orbit-halo); }
@media (prefers-reduced-motion: reduce) {
	[data-co] *, [data-co] *::before, [data-co] *::after { animation-duration: 1ms !important; animation-iteration-count: 1 !important; transition-duration: 1ms !important; transition-delay: 0ms !important; }
}
`;

export interface VisualizerProps {
	nodes: OrbitNodeData[];
	groups?: OrbitGroup[];
	vocab?: OrbitVocab;
	className?: string;
	defaultView?: "constellation" | "list";
	showPeriods?: boolean;
	maxNodes?: number;
	ambient?: boolean;
	sparkSpeed?: number;
	ignition?: boolean;
	showLegend?: boolean;
	showSunLabel?: boolean;
	sunLabelColor?: string;
	accent?: string;
	filament?: string;
	agentColor?: string;
	toolColor?: string;
	groupColorA?: string;
	groupColorB?: string;
	paused?: boolean;
	reducedMotion?: boolean;
}

export default function Visualizer({
	nodes: nodesIn,
	groups = NO_GROUPS,
	vocab = AGENT_VOCAB,
	className,
	defaultView = "constellation",
	showPeriods = true,
	maxNodes = 24,
	ambient: ambientOn = true,
	sparkSpeed = 1,
	ignition = true,
	showLegend = true,
	showSunLabel = true,
	sunLabelColor = "#1a1408",
	accent = "#e6c27a",
	filament = "#5ee1d9",
	agentColor = "#5fd3a6",
	toolColor = "#e6c27a",
	groupColorA = "#f08bb0",
	groupColorB = "#a99bff",
	paused = false,
	reducedMotion = false,
}: VisualizerProps): React.JSX.Element {
	const rootRef = React.useRef<HTMLDivElement>(null);
	const width = useContainerWidth(rootRef);
	const now = useNow();
	const { inView, seen, known } = useInView(rootRef);
	const held = known && !seen;
	const pageVisible = usePageVisible();

	const cap = Math.max(1, Math.min(MAX_SENDERS, Math.round(maxNodes)));
	const senders = React.useMemo(() => normalizeSenders(nodesIn).slice(0, cap), [nodesIn, cap]);
	const byId = React.useMemo(() => new Map(senders.map((s) => [s.id, s])), [senders]);
	const allShares = React.useMemo(() => categoryShares(senders, groups, null), [senders, groups]);
	const period = showPeriods ? vocab.period : null;
	const options = React.useMemo(() => weekOptions(period), [period]);
	const total = allShares.reduce((a, c) => a + c.count, 0);
	const railDaily = React.useMemo(() => combinedDaily(senders), [senders]);

	const [weekKey, setWeekKey] = React.useState<WeekKey>("all");
	const week = (options.find((o) => o.key === weekKey) ?? options[0]!).week;
	const [userView, setUserView] = React.useState<View | null>(null);
	React.useEffect(() => setUserView(null), [defaultView]);
	const view: View = userView ?? (width > 0 && width < LIST_BELOW ? "list" : defaultView);

	const [focusId, setFocusId] = React.useState<string | null>(null);
	const [activeId, setActiveId] = React.useState<string | null>(null);
	const [hoverId, setHoverId] = React.useState<string | null>(null);
	const [keyFocusId, setKeyFocusId] = React.useState<string | null>(null);
	const [announcement, setAnnouncement] = React.useState("");
	const [settled, setSettled] = React.useState(false);
	const introDone = settled || !ignition || reducedMotion;
	const [glide, setGlide] = React.useState(0);
	const [glideDone, setGlideDone] = React.useState(0);
	const restoreRef = React.useRef<string | null>(null);

	const uid = React.useId().replace(/[^a-zA-Z0-9_-]/g, "");
	const ids = React.useMemo(() => makeOrbitIds(uid), [uid]);

	const stageH = stageHeight(width);
	const layout = React.useMemo(
		() => (width > 0 && senders.length ? layoutOrbit(senders, groups, width, stageH, week) : null),
		[senders, groups, width, stageH, week],
	);
	const groupLabel = (id: string) => layout?.categories.find((c) => c.id === id)?.label ?? groups.find((g) => g.id === id)?.label ?? id;

	const focusSender = focusId ? byId.get(focusId) : undefined;
	const [expanded, setExpanded] = React.useState(false);
	const expandedView = expanded && focusSender && vocab.expand ? vocab.expand : null;
	const focusIds = React.useMemo(
		() => (focusSender ? vocab.focus.cards(focusSender, now).map((c) => c.id) : []),
		[focusSender, vocab, now],
	);
	const focusGeom = React.useMemo(
		() => (focusSender && width > 0 ? layoutFocus(width, stageH, focusIds) : null),
		[focusSender, width, stageH, focusIds],
	);
	const compactFocus = expandedView ? true : (focusGeom?.compact ?? false);
	const [pushId, setPushId] = React.useState<string | null>(null);
	const pushNode = pushId ? layout?.senders.find((s) => s.id === pushId) : undefined;
	const push = reducedMotion || !pushNode ? 1 : PUSH;
	const sceneFocus: SceneFocus =
		focusSender && focusGeom && !compactFocus && view === "constellation"
			? {
					id: focusSender.id,
					x: pushNode ? pushNode.x + (focusGeom.orb.x - pushNode.x) / push : focusGeom.orb.x,
					y: pushNode ? pushNode.y + (focusGeom.orb.y - pushNode.y) / push : focusGeom.orb.y,
					r: focusGeom.orb.r / push,
				}
			: null;

	const constellationReady = layout !== null && view === "constellation" && !held;
	React.useEffect(() => {
		if (!constellationReady || introDone) return;
		const t = window.setTimeout(() => setSettled(true), IGNITION_MS);
		return () => window.clearTimeout(t);
	}, [constellationReady, introDone]);

	React.useEffect(() => {
		if (glide === glideDone) return;
		const t = window.setTimeout(() => setGlideDone(glide), 760);
		return () => window.clearTimeout(t);
	}, [glide, glideDone]);

	const ambient = ambientOn && introDone && !reducedMotion && inView && pageVisible && view === "constellation" && !focusSender;
	const igniting = !introDone && !held;
	const gliding = glide !== glideDone;

	const legendCounts = React.useMemo(() => {
		const agents = senders.filter((s) => s.kind === "agent").length;
		return { agents, tools: senders.length - agents, flagged: senders.filter((s) => s.flagged > 0).length };
	}, [senders]);
	const tabStop = activeId && byId.has(activeId) ? activeId : (senders[0]?.id ?? null);

	React.useEffect(() => {
		if (focusId !== null || !restoreRef.current) return;
		const id = CSS.escape(restoreRef.current);
		restoreRef.current = null;
		rootRef.current
			?.querySelector<HTMLElement | SVGElement>(`[data-orbit-sender="${id}"], [data-orbit-row="${id}"]`)
			?.focus({ preventScroll: true });
	}, [focusId]);

	const open = React.useCallback(
		(id: string) => {
			const s = byId.get(id);
			if (!s) return;
			setSettled(true);
			setHoverId(null);
			setKeyFocusId(null);
			setActiveId(id);
			setFocusId(id);
			setPushId(id);
			setExpanded(false);
			setGlide((g) => g + 1);
			setAnnouncement(`${displayName(s)}: ${vocab.describe(s, now)}. Press Escape to go back.`);
		},
		[byId, now, vocab],
	);

	const back = React.useCallback(() => {
		restoreRef.current = focusId;
		setFocusId(null);
		setExpanded(false);
		setGlide((g) => g + 1);
		setAnnouncement(`Back to the ${view === "list" ? "list" : "constellation"}.`);
	}, [focusId, view]);

	const ringOrder = React.useMemo(
		() => (layout ? [...layout.senders].sort((a, b) => a.ring - b.ring).map((s) => s.id) : []),
		[layout],
	);

	const navigate = React.useCallback(
		(id: string, key: string) => {
			const n = ringOrder.length;
			if (!n) return;
			const i = Math.max(0, ringOrder.indexOf(id));
			let next = id;
			if (key === "ArrowRight" || key === "ArrowDown") next = ringOrder[(i + 1) % n]!;
			else if (key === "ArrowLeft" || key === "ArrowUp") next = ringOrder[(i - 1 + n) % n]!;
			else if (key === "Home") next = senders[0]!.id;
			else if (key === "End") next = senders[senders.length - 1]!.id;
			setActiveId(next);
			rootRef.current
				?.querySelector<SVGElement>(`[data-orbit-sender="${CSS.escape(next)}"]`)
				?.focus({ preventScroll: true });
		},
		[ringOrder, senders],
	);

	const labels = layout?.categories;
	const ariaLabelFor = React.useCallback(
		(node: OrbitSender) => {
			const s = byId.get(node.id);
			if (!s) return node.id;
			const amount = plural(node.value, vocab.unit[0], vocab.unit[1]);
			const parts = [
				displayName(s),
				week === null ? amount : `${amount} in ${vocab.window.week(week)}`,
				`${formatCount(s.flagged)} ${vocab.flag.label}`,
			];
			if (now !== null) parts.push(vocab.recencyLong(s, now));
			parts.push(labels?.find((c) => c.id === node.category)?.label ?? s.group);
			return parts.join(", ");
		},
		[byId, week, now, vocab, labels],
	);

	const onWeek = (next: string) => {
		const option = options.find((o) => o.key === next);
		if (!option) return;
		setWeekKey(option.key);
		const lead = [...categoryShares(senders, groups, option.week)].sort((a, b) => b.value - a.value)[0];
		setAnnouncement(`${option.spoken}.${lead && lead.value > 0 ? ` ${lead.label} leads with ${lead.text}.` : ""}`);
	};

	const onView = (next: string) => {
		const v = next as View;
		if (v === view) return;
		setSettled(true);
		setUserView(v);
		setFocusId(null);
		setExpanded(false);
		setHoverId(null);
		setAnnouncement(v === "list" ? "List view." : "Constellation view.");
	};

	const onKeyDown = (e: React.KeyboardEvent) => {
		if (e.key === "Escape" && focusSender) {
			e.preventDefault();
			e.stopPropagation();
			if (expandedView) setExpanded(false);
			else back();
		}
	};

	const fixedStage = width > 0 && ((view === "constellation" && !compactFocus) || (focusSender && !compactFocus));

	return (
		<div
			ref={rootRef}
			data-co=""
			data-intro={introDone ? "off" : undefined}
			data-hold={held && !introDone ? "" : undefined}
			data-paused={paused ? "" : undefined}
			onKeyDown={onKeyDown}
			className={cn("relative min-w-0 text-ink [--orbit-halo:var(--sg-panel)]", className)}
			style={
				{
					"--orbit-sun-paint": `url(#${ids.sun})`,
					"--co-accent": accent,
					"--co-filament": filament,
					"--co-agent": agentColor,
					"--co-tool": toolColor,
					"--co-cat-0": groupColorA,
					"--co-cat-1": groupColorB,
					"--co-sun-label": sunLabelColor,
				} as React.CSSProperties
			}
		>
			<style href="visualizer" precedence="default">
				{STYLES}
			</style>
			{senders.length > 0 && (
				<div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-3">
					<p className={cn(READOUT, "tabular-nums")}>
						{formatCount(total)} {vocab.unit[1]} · {plural(senders.length, vocab.node[0], vocab.node[1])} ·{" "}
						{plural(allShares.length, vocab.group[0], vocab.group[1])}
					</p>
					<div className="flex flex-wrap items-center gap-2">
						<Segmented
							label="View"
							value={view}
							onChange={onView}
							options={[
								{
									value: "constellation",
									spoken: "Constellation",
									label: (
										<>
											<OrbitIcon className="size-3.5" />
											<span className="hidden sm:inline">Constellation</span>
										</>
									),
								},
								{
									value: "list",
									spoken: "List",
									label: (
										<>
											<ListIcon className="size-3.5" />
											<span className="hidden sm:inline">List</span>
										</>
									),
								},
							]}
						/>
					</div>
				</div>
			)}

			{period && senders.length > 0 && (
				<TimeRail
					daily={railDaily}
					options={options}
					value={weekKey}
					onChange={onWeek}
					inert={focusSender ? true : undefined}
					className={cn("mt-3 transition-opacity", focusSender && "opacity-0")}
				/>
			)}

			{senders.length === 0 ? (
				<EmptyOrbit vocab={vocab} sunLabel={showSunLabel} />
			) : width === 0 ? (
				<div className="mt-4 h-[360px] sm:h-[470px]" aria-hidden />
			) : (
				<div className="mt-4 grid *:[grid-area:1/1]">
					<div className="flex min-w-0 flex-col justify-center">
						<div
							className={cn("relative", focusSender && "overflow-clip")}
							style={fixedStage ? { height: stageH } : undefined}
						>
							{view === "constellation" && layout && !(focusSender && compactFocus) && (
								<div
									inert={focusSender ? true : undefined}
									className="absolute inset-0"
									style={{
										transform: focusSender && push !== 1 ? `scale(${push})` : undefined,
										transformOrigin: pushNode ? `${pushNode.x}px ${pushNode.y}px` : undefined,
										transition: gliding ? `transform 640ms ${EASE}` : undefined,
										willChange: gliding ? "transform" : undefined,
									}}
								>
									<OrbitScene
										layout={layout}
										senders={byId}
										ids={ids}
										focus={sceneFocus}
										activeId={tabStop}
										hoverId={hoverId}
										tipId={hoverId ?? keyFocusId}
										ambient={ambient}
										igniting={igniting}
										paused={paused}
										sparkSpeed={Math.max(0.05, sparkSpeed)}
										sunLabel={showSunLabel}
										gliding={gliding}
										now={now}
										vocab={vocab}
										ariaLabelFor={ariaLabelFor}
										onHover={setHoverId}
										onFocusNode={setKeyFocusId}
										onActivate={open}
										onNavigate={navigate}
									/>
								</div>
							)}
							{view === "list" && layout && !focusSender && (
								<OrbitList senders={senders} categories={layout.categories} week={week} now={now} vocab={vocab} onOpen={open} />
							)}
							{focusSender && expandedView && (
								<section key={focusSender.id} aria-label={`${displayName(focusSender)} details`} className="flex flex-col gap-4">
									<BackButton returnTo={displayName(focusSender)} onBack={() => setExpanded(false)} />
									{expandedView.render(focusSender)}
								</section>
							)}
							{focusSender && focusGeom && !expandedView && (
								<Drilldown
									key={focusSender.id}
									sender={focusSender}
									group={groupLabel(focusSender.group)}
									focus={vocab.focus}
									more={vocab.expand ? { label: vocab.expand.label(focusSender), onClick: () => setExpanded(true) } : undefined}
									geom={focusGeom}
									showOrb={view === "list" || compactFocus}
									now={now}
									reduced={reducedMotion}
									returnTo={view === "list" ? "list" : "constellation"}
									onBack={back}
									onAnnounce={setAnnouncement}
								/>
							)}
						</div>
						{showLegend && view === "constellation" && !(focusSender && compactFocus) && (
							<Legend vocab={vocab} counts={legendCounts} hidden={!!focusSender} />
						)}
					</div>
					{(view !== "list" || focusSender) && layout && (
						<div aria-hidden inert className="invisible min-w-0">
							<OrbitList senders={senders} categories={layout.categories} week={week} now={now} vocab={vocab} onOpen={() => {}} />
						</div>
					)}
					<div aria-hidden inert className="invisible flex min-w-0 flex-col">
						<div style={{ height: stageH }} />
						{showLegend && <Legend vocab={vocab} counts={legendCounts} hidden />}
					</div>
				</div>
			)}

			<p id={ids.hint} className="sr-only">
				{vocab.srHint}
			</p>
			<p aria-live="polite" className="sr-only">
				{announcement}
			</p>
		</div>
	);
}

function Legend({
	vocab,
	counts,
	hidden,
}: {
	vocab: OrbitVocab;
	counts: { agents: number; tools: number; flagged: number };
	hidden: boolean;
}) {
	return (
		<div
			aria-hidden={hidden || undefined}
			className={cn("mt-3 flex flex-wrap items-center justify-between gap-x-6 gap-y-2 text-[12px] text-ink-dim", hidden && "invisible")}
		>
			<ul aria-label="Legend" className="flex flex-wrap items-center gap-x-4 gap-y-1.5">
				<li className="inline-flex items-center gap-1.5">
					<span className="size-2.5 rounded-full bg-(--co-agent)" />
					{vocab.legend.person}
					<LegendCount n={counts.agents} />
				</li>
				<li className="inline-flex items-center gap-1.5">
					<span className="size-2.5 rounded-full bg-(--co-tool)" />
					{vocab.legend.machine}
					<LegendCount n={counts.tools} />
				</li>
				<li className="inline-flex items-center gap-1.5">
					<span className="size-1.5 rounded-full bg-(--co-filament)" />
					{capitalize(vocab.flag.label)}
					<LegendCount n={counts.flagged} />
				</li>
				<li className="inline-flex items-center gap-1.5">
					<span aria-hidden className="h-2.5 w-px bg-(--co-accent)" />
					{vocab.legend.ring}
				</li>
			</ul>
			<p className="hidden items-center gap-1.5 lg:inline-flex">
				{vocab.legend.hint} · <Kbd>←</Kbd>
				<Kbd>→</Kbd> to move · <Kbd>Esc</Kbd> to return
			</p>
		</div>
	);
}

function LegendCount({ n }: { n: number }) {
	return <span className="font-mono text-[11px] text-ink-mute tabular-nums">{formatCount(n)}</span>;
}

function EmptyOrbit({ vocab, sunLabel }: { vocab: OrbitVocab; sunLabel: boolean }) {
	return (
		<div className="flex flex-col items-center gap-5 py-10 text-center">
			<svg width="168" height="168" viewBox="0 0 168 168" aria-hidden>
				<circle cx="84" cy="84" r="80" fill="none" strokeWidth={1} strokeDasharray="1 7" strokeLinecap="round" className="stroke-hairline" />
				<circle cx="84" cy="84" r="52" fill="none" strokeWidth={1} className="stroke-hairline" />
				<circle cx="84" cy="84" r="27" className="fill-(--co-accent)/10" />
				<circle cx="84" cy="84" r="18" className="fill-(--co-accent)" />
				{sunLabel && (
					<text x="84" y="84" textAnchor="middle" dominantBaseline="central" className="fill-(--co-sun-label) text-[7px] font-semibold">
						{vocab.sun}
					</text>
				)}
			</svg>
			<div>
				<p className="text-[17px] text-ink">{vocab.empty.title}</p>
				<p className="mx-auto mt-1 max-w-[340px] text-[13px] text-ink-dim">{vocab.empty.body}</p>
			</div>
		</div>
	);
}
```

### 2. `components/registry/visualizer/scene.tsx` — supporting file, required

```tsx
"use client";

import * as React from "react";
import { cn } from "@/lib/utils";
import { CHIP_H, textWidth, type OrbitCategory, type OrbitLayout, type OrbitSender } from "./layout";
import { displayName, formatCount } from "./format";
import { EASE, beamArrive, beamStart, seeded, senderStart } from "./motion";
import type { OrbitNodeData } from "./types";
import type { OrbitVocab } from "./vocab";

export type OrbitIds = {
	sun: string;
	sunGlow: string;
	wash: string;
	glow: string;
	gloss: (key: "person" | "machine" | "cat-0" | "cat-1") => string;
	beam: (i: number) => string;
	hint: string;
};

export function makeOrbitIds(uid: string): OrbitIds {
	return {
		sun: `${uid}-sun`,
		sunGlow: `${uid}-sun-glow`,
		wash: `${uid}-wash`,
		glow: `${uid}-glow`,
		gloss: (key) => `${uid}-gloss-${key}`,
		beam: (i) => `${uid}-beam-${i}`,
		hint: `${uid}-hint`,
	};
}

const stageSeed = (width: number, height: number) => Math.imul(width, 73856093) ^ Math.imul(height, 19349663);

function stars(width: number, height: number) {
	const rand = seeded(stageSeed(width, height));
	const count = Math.round(clampNum((width * height) / 9000, 18, 64));
	return Array.from({ length: count }, (_, i) => ({
		x: Math.round(rand() * width * 10) / 10,
		y: Math.round(rand() * height * 10) / 10,
		r: 0.45 + rand() * 0.8,
		o: 0.18 + rand() * 0.4,
		twinkle: i % 9 === 0,
		dur: 2.6 + rand() * 3.2,
	}));
}

function clampNum(v: number, lo: number, hi: number) {
	return Math.min(hi, Math.max(lo, v));
}

function dust(width: number, height: number, reach: number) {
	const rand = seeded(stageSeed(width, height) ^ 0x5bd1e995);
	return Array.from({ length: 28 }, (_, i) => {
		const a = ((i + rand() * 0.8) / 28) * Math.PI * 2;
		const d = reach * (0.6 + rand() * 0.8);
		return {
			dx: Math.round(Math.cos(a) * d),
			dy: Math.round(Math.sin(a) * d),
			size: 1.5 + rand() * 1.5,
			delay: Math.round(80 + rand() * 140),
		};
	});
}

function Gloss({ id, color }: { id: string; color: string }) {
	return (
		<radialGradient id={id} cx="0.4" cy="0.36" r="0.72" fx="0.32" fy="0.26">
			<stop offset="0" style={{ stopColor: `color-mix(in oklab, ${color} 30%, white)` }} />
			<stop offset="0.45" style={{ stopColor: color }} />
			<stop offset="1" style={{ stopColor: `color-mix(in oklab, ${color} 52%, black)` }} />
		</radialGradient>
	);
}

export type SceneFocus = { id: string; x: number; y: number; r: number } | null;

type SceneProps = {
	layout: OrbitLayout;
	senders: Map<string, OrbitNodeData>;
	ids: OrbitIds;
	focus: SceneFocus;
	activeId: string | null;
	hoverId: string | null;
	tipId: string | null;
	ambient: boolean;
	igniting: boolean;
	paused: boolean;
	sparkSpeed: number;
	sunLabel: boolean;
	gliding: boolean;
	now: number | null;
	vocab: OrbitVocab;
	ariaLabelFor: (s: OrbitSender) => string;
	onHover: (id: string | null) => void;
	onFocusNode: (id: string | null) => void;
	onActivate: (id: string) => void;
	onNavigate: (id: string, key: string) => void;
};

const NAV_KEYS = new Set(["ArrowRight", "ArrowDown", "ArrowLeft", "ArrowUp", "Home", "End"]);

export const OrbitScene = React.memo(function OrbitScene({
	layout,
	senders,
	ids,
	focus,
	activeId,
	hoverId,
	tipId,
	ambient,
	igniting,
	paused,
	sparkSpeed,
	sunLabel,
	gliding,
	now,
	vocab,
	ariaLabelFor,
	onHover,
	onFocusNode,
	onActivate,
	onNavigate,
}: SceneProps) {
	const { width, height, cx, cy, sun, rings, categories } = layout;
	const focused = focus !== null;
	const field = React.useMemo(() => stars(width, height), [width, height]);
	const hovered = hoverId ? layout.senders.find((s) => s.id === hoverId) : undefined;
	const fade = { opacity: focused ? 0 : 1, transition: `opacity 320ms ${EASE}` };
	const sunFont = clampNum((sun.r * 1.75) / Math.max(1, textWidth(vocab.sun, 1)), 7, 11);
	const glowR = sun.ringInner + sun.ringMax + clampNum(layout.scale * 0.09, 24, 48);
	const motes = React.useMemo(() => dust(width, height, glowR * 1.6), [width, height, glowR]);

	const arrive = React.useMemo(() => new Map(categories.map((c) => [c.id, beamArrive(c.order)])), [categories]);
	const senderDelay = React.useMemo(() => {
		const seen = new Map<string, number>();
		const out = new Map<string, number>();
		for (const s of [...layout.senders].sort((a, b) => a.ring - b.ring)) {
			const k = seen.get(s.category) ?? 0;
			seen.set(s.category, k + 1);
			out.set(s.id, senderStart(arrive.get(s.category) ?? 0, k));
		}
		return out;
	}, [layout.senders, arrive]);

	const live = React.useMemo(
		() => layout.senders.filter((s) => senders.get(s.id)?.recent[0]?.status === "running"),
		[layout.senders, senders],
	);

	const starsRef = React.useRef<HTMLDivElement>(null);
	const drift = ambient && !paused;
	const setDrift = (x: number, y: number) => {
		starsRef.current?.style.setProperty("--co-px", `${x.toFixed(2)}px`);
		starsRef.current?.style.setProperty("--co-py", `${y.toFixed(2)}px`);
	};
	React.useEffect(() => {
		if (!drift) setDrift(0, 0);
	}, [drift]);

	return (
		<div
			className="co-dolly absolute inset-0"
			style={{ transformOrigin: `${cx}px ${cy}px` }}
			onPointerMove={(e) => {
				if (!drift || e.pointerType !== "mouse") return;
				const box = e.currentTarget.getBoundingClientRect();
				const nx = ((e.clientX - box.left) / box.width) * 2 - 1;
				const ny = ((e.clientY - box.top) / box.height) * 2 - 1;
				setDrift(-nx * 8, -ny * 8);
			}}
			onPointerLeave={() => setDrift(0, 0)}
		>
			<div aria-hidden className="pointer-events-none absolute inset-0" style={fade}>
				<div
					ref={starsRef}
					className="absolute inset-0"
					style={{ transform: "translate3d(var(--co-px, 0px), var(--co-py, 0px), 0)", transition: "transform 600ms ease-out" }}
				>
					<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} className="absolute inset-0 hidden dark:block">
						<defs>
							<radialGradient id={ids.wash}>
								<stop offset="0" style={{ stopColor: "var(--co-filament)", stopOpacity: 0.07 }} />
								<stop offset="1" style={{ stopColor: "var(--co-filament)", stopOpacity: 0 }} />
							</radialGradient>
						</defs>
						<ellipse cx={cx} cy={cy} rx={rings.r2.rx + 90} ry={rings.r2.ry + 70} fill={`url(#${ids.wash})`} />
						{[false, true].map((bright) => (
							<path
								key={String(bright)}
								d={field
									.filter((s) => !s.twinkle && s.o > 0.38 === bright)
									.map((s) => `M${s.x} ${s.y}h0`)
									.join("")}
								className="stroke-ink"
								strokeOpacity={bright ? 0.42 : 0.2}
								strokeWidth={bright ? 1.6 : 1.1}
								strokeLinecap="round"
							/>
						))}
					</svg>
					{field
						.filter((s) => s.twinkle)
						.map((s, i) => (
							<span
								key={i}
								className={cn("absolute hidden size-[2.5px] rounded-full bg-ink dark:block", ambient && "animate-pulse")}
								style={{ left: s.x - 1.25, top: s.y - 1.25, opacity: s.o + 0.25, animationDuration: `${s.dur}s` }}
							/>
						))}
				</div>
				{ambient &&
					live.map((s) => {
						const R = s.r + 3;
						return (
							<span
								key={s.id}
								className="co-flare absolute rounded-full border-[1.5px] border-(--co-filament)"
								style={{
									left: s.x - R,
									top: s.y - R,
									width: R * 2,
									height: R * 2,
									animationDuration: "2400ms",
									animationIterationCount: "infinite",
									animationDelay: `${(s.rank * 370) % 2400}ms`,
								}}
							/>
						);
					})}
				{ambient && (
					<div
						className="absolute animate-pulse rounded-full"
						style={{
							left: cx - glowR * 1.25,
							top: cy - glowR * 1.25,
							width: glowR * 2.5,
							height: glowR * 2.5,
							background:
								"radial-gradient(closest-side, color-mix(in oklab, var(--co-accent) 16%, transparent), color-mix(in oklab, var(--co-accent) 5%, transparent) 55%, transparent)",
							animationDuration: "6s",
						}}
					/>
				)}
			</div>
			<svg
				width={width}
				height={height}
				viewBox={`0 0 ${width} ${height}`}
				className="absolute inset-0 block select-none"
				role="group"
				aria-label={vocab.sceneLabel}
				aria-describedby={ids.hint}
			>
				<defs>
					<radialGradient id={ids.sun} cx="0.4" cy="0.36" r="0.7" fx="0.34" fy="0.28">
						<stop offset="0" style={{ stopColor: "#fff6de" }} />
						<stop offset="0.38" style={{ stopColor: "var(--co-accent)" }} />
						<stop offset="1" style={{ stopColor: "color-mix(in oklab, var(--co-accent) 45%, black)" }} />
					</radialGradient>
					<radialGradient id={ids.sunGlow}>
						<stop offset="0.25" style={{ stopColor: "var(--co-accent)", stopOpacity: 0.34 }} />
						<stop offset="0.6" style={{ stopColor: "var(--co-accent)", stopOpacity: 0.08 }} />
						<stop offset="1" style={{ stopColor: "var(--co-accent)", stopOpacity: 0 }} />
					</radialGradient>
					<filter id={ids.glow} x="-40%" y="-40%" width="180%" height="180%">
						<feGaussianBlur stdDeviation="3.2" />
					</filter>
					<Gloss id={ids.gloss("person")} color="var(--co-agent)" />
					<Gloss id={ids.gloss("machine")} color="var(--co-tool)" />
					<Gloss id={ids.gloss("cat-0")} color="var(--co-cat-0)" />
					<Gloss id={ids.gloss("cat-1")} color="var(--co-cat-1)" />
					{categories.map((c, i) => (
						<linearGradient
							key={c.id}
							id={ids.beam(i)}
							gradientUnits="userSpaceOnUse"
							x1={c.beam.from.x}
							y1={c.beam.from.y}
							x2={c.beam.to.x}
							y2={c.beam.to.y}
						>
							<stop offset="0" style={{ stopColor: "var(--co-accent)", stopOpacity: 0.95 }} />
							<stop offset="0.55" style={{ stopColor: "var(--co-accent)", stopOpacity: 0.5 }} />
							<stop offset="1" style={{ stopColor: "var(--co-accent)", stopOpacity: 0.08 }} />
						</linearGradient>
					))}
				</defs>

				<g aria-hidden className="pointer-events-none" style={fade}>
					<ellipse
						cx={cx}
						cy={cy}
						rx={rings.r1.rx}
						ry={rings.r1.ry}
						fill="none"
						className="stroke-hairline"
						strokeWidth={1}
					/>
					<ellipse
						cx={cx}
						cy={cy}
						rx={rings.r2.rx}
						ry={rings.r2.ry}
						fill="none"
						className="stroke-hairline"
						strokeWidth={1}
						strokeDasharray="1 7"
						strokeLinecap="round"
					/>
				</g>

				<g aria-hidden className="pointer-events-none" style={fade} fill="none" strokeLinecap="round">
					{categories.map((c, i) => {
						const delay = { ["--draw-delay" as string]: `${beamStart(c.order)}ms` };
						const lit = hovered?.category === c.id;
						return (
							<g key={c.id}>
								<path
									d={c.beam.d}
									pathLength={1}
									stroke={`url(#${ids.beam(i)})`}
									className="co-draw-on hidden dark:inline"
									filter={`url(#${ids.glow})`}
									style={{
										...delay,
										strokeWidth: c.beam.width * 3,
										opacity: lit ? 0.5 : 0.28,
										transition: `stroke-width 600ms ${EASE}, opacity 240ms`,
									}}
								/>
								<path
									d={c.beam.d}
									pathLength={1}
									stroke={`url(#${ids.beam(i)})`}
									className="co-draw-on"
									style={{ ...delay, strokeWidth: c.beam.width, transition: `stroke-width 600ms ${EASE}` }}
								/>
								<path
									d={c.beam.filament}
									pathLength={1}
									className="co-draw-on hidden stroke-(--co-filament) dark:inline"
									strokeWidth={0.8}
									style={{ ["--draw-delay" as string]: `${beamStart(c.order) + 100}ms`, opacity: 0.45 }}
								/>
								<path
									d={c.beam.arrow}
									className="co-fade stroke-(--co-accent)/80"
									strokeWidth={1.2}
									strokeLinejoin="round"
									style={{ animationDelay: `${arrive.get(c.id)}ms` }}
								/>
							</g>
						);
					})}
				</g>

				<g aria-hidden className="pointer-events-none" style={fade} fill="none" strokeLinecap="round">
					{layout.senders.map((s) => (
						<path
							key={s.id}
							d={s.link}
							className={cn(
								"co-entrance transition-[stroke,opacity] duration-200",
								s.id === hoverId ? "stroke-(--co-accent)" : "stroke-ink-mute/70 dark:stroke-(--co-filament)/45",
							)}
							strokeWidth={s.id === hoverId ? 1.4 : 1.1}
							strokeDasharray="0.5 4.5"
							style={{ animationDelay: `${(arrive.get(s.category) ?? 0) + 40}ms`, opacity: s.weight > 0 ? 1 : 0.45 }}
						/>
					))}
				</g>

				<g aria-hidden className="pointer-events-none" style={fade}>
					<g className="co-bloom origin-center [transform-box:fill-box]">
						<circle cx={cx} cy={cy} r={glowR} fill={`url(#${ids.sunGlow})`} className="hidden dark:inline" />
						<circle
							cx={cx}
							cy={cy}
							r={sun.ringInner + sun.ringMax + 4}
							className="fill-(--co-accent)/[0.07]"
						/>
						<path
							d={sun.ring}
							pathLength={1}
							className="co-draw-on stroke-(--co-accent)/85"
							strokeWidth={1.6}
							strokeLinecap="round"
							fill="none"
							style={{ ["--draw-delay" as string]: "140ms" }}
						/>
						<circle cx={cx} cy={cy} r={sun.r + 3} fill="none" className="stroke-(--co-accent)/40" />
						<circle
							cx={cx}
							cy={cy}
							r={sun.r}
							className="fill-(--orbit-sun-paint) drop-shadow-[0_0_16px_color-mix(in_oklab,var(--co-accent)_55%,transparent)]"
						/>
						{sunLabel && (
							<text
								x={cx}
								y={cy}
								textAnchor="middle"
								dominantBaseline="central"
								className="fill-(--co-sun-label) font-semibold"
								style={{ fontSize: sunFont }}
							>
								{vocab.sun}
							</text>
						)}
					</g>
				</g>

				<g style={fade}>
					{categories.map((c) => (
						<CategoryNode
							key={c.id}
							c={c}
							ids={ids}
							vocab={vocab}
							delay={arrive.get(c.id) ?? 0}
							dim={!!hovered && hovered.category !== c.id}
						/>
					))}
				</g>

				<g>
					{layout.senders.map((s) => {
						const isFocus = focus?.id === s.id;
						const stat = senders.get(s.id);
						return (
							<SenderNode
								key={s.id}
								s={s}
								ids={ids}
								flagged={stat?.flagged ?? 0}
								delay={senderDelay.get(s.id) ?? 0}
								tabbable={activeId === s.id}
								hovered={hoverId === s.id}
								dim={focused ? !isFocus : !!hovered && hovered.category !== s.category}
								hidden={focused && !isFocus}
								target={isFocus ? focus : null}
								gliding={gliding}
								ariaLabel={ariaLabelFor(s)}
								onHover={onHover}
								onFocusNode={onFocusNode}
								onActivate={onActivate}
								onNavigate={onNavigate}
							/>
						);
					})}
				</g>
			</svg>

			{igniting && (
				<div aria-hidden className="pointer-events-none absolute inset-0">
					<div className="hidden dark:block">
						{motes.map((m, i) => (
							<span
								key={i}
								className="co-dust absolute rounded-full bg-[color-mix(in_oklab,var(--co-accent)_60%,white)]"
								style={
									{
										left: cx - m.size / 2,
										top: cy - m.size / 2,
										width: m.size,
										height: m.size,
										animationDelay: `${m.delay}ms`,
										"--dx": `${m.dx}px`,
										"--dy": `${m.dy}px`,
									} as React.CSSProperties
								}
							/>
						))}
					</div>
					{categories.map((c) => {
						const R = c.r + 6;
						return (
							<React.Fragment key={c.id}>
								<span
									className="co-comet absolute top-0 left-0 h-[3px] w-[18px] rounded-full bg-[linear-gradient(90deg,transparent,color-mix(in_oklab,var(--co-accent)_35%,white))] shadow-[0_0_8px_2px_color-mix(in_oklab,var(--co-accent)_55%,transparent)]"
									style={{ offsetPath: `path("${c.beam.d}")`, animationDelay: `${beamStart(c.order)}ms` }}
								/>
								<span
									className="co-flare absolute rounded-full border-[1.5px] border-(--co-accent)"
									style={{ left: c.x - R, top: c.y - R, width: R * 2, height: R * 2, animationDelay: `${arrive.get(c.id)}ms` }}
								/>
							</React.Fragment>
						);
					})}
				</div>
			)}

			{ambient && !focused && (
				<div aria-hidden className="pointer-events-none absolute inset-0 overflow-hidden">
					{categories.flatMap((c) =>
						Array.from({ length: c.particles.count }, (_, j) => (
							<Spark
								key={`${c.id}-${j}`}
								track={c.beam.track}
								dur={c.particles.dur / sparkSpeed}
								phase={(j + 0.35) / c.particles.count}
								paused={paused}
							/>
						)),
					)}
				</div>
			)}

			<OrbitTooltip layout={layout} senders={senders} tipId={focused ? null : tipId} now={now} vocab={vocab} />
		</div>
	);
});

function Spark({ track, dur, phase, paused }: { track: string; dur: number; phase: number; paused: boolean }) {
	const ref = React.useRef<HTMLSpanElement>(null);
	const anims = React.useRef<Animation[]>([]);
	const pausedRef = React.useRef(paused);
	pausedRef.current = paused;
	React.useEffect(() => {
		const el = ref.current;
		const dot = el?.firstElementChild as HTMLElement | null;
		if (!el || !dot || typeof el.animate !== "function") return;
		const points = track
			.split(" ")
			.map((p) => p.split(",").map(Number) as [number, number])
			.reverse();
		const timing: KeyframeAnimationOptions = {
			duration: dur * 1000,
			delay: -phase * dur * 1000,
			iterations: Infinity,
			easing: "cubic-bezier(0.45, 0, 0.3, 1)",
		};
		const move = el.animate(
			points.map(([x, y]) => ({ transform: `translate(${x}px, ${y}px)` })),
			timing,
		);
		const glow = dot.animate(
			[{ opacity: 0 }, { opacity: 1, offset: 0.14 }, { opacity: 1, offset: 0.8 }, { opacity: 0 }],
			timing,
		);
		anims.current = [move, glow];
		if (pausedRef.current) for (const a of anims.current) a.pause();
		return () => {
			move.cancel();
			glow.cancel();
			anims.current = [];
		};
	}, [track, dur, phase]);
	React.useEffect(() => {
		for (const a of anims.current) {
			if (paused) a.pause();
			else a.play();
		}
	}, [paused]);
	return (
		<span ref={ref} className="absolute top-0 left-0 will-change-transform">
			<span className="block size-[3.5px] -translate-x-1/2 -translate-y-1/2 rounded-full bg-[color-mix(in_oklab,var(--co-accent)_22%,white)] opacity-0 shadow-[0_0_6px_2px_color-mix(in_oklab,var(--co-accent)_50%,transparent)]" />
		</span>
	);
}

function CategoryNode({
	c,
	ids,
	vocab,
	delay,
	dim,
}: {
	c: OrbitCategory;
	ids: OrbitIds;
	vocab: OrbitVocab;
	delay: number;
	dim: boolean;
}) {
	const tone = `var(--co-cat-${c.tone})`;
	const label = c.labelPos;
	return (
		<g
			transform={`translate(${c.x} ${c.y})`}
			role="img"
			aria-label={`${c.label}: ${c.shareText} of ${vocab.mass}, ${formatCount(c.value)} ${vocab.unit[1]}`}
			style={{ ["--cat" as string]: tone, opacity: dim ? 0.6 : 1, transition: "opacity 240ms" }}
		>
			<g className="co-bloom origin-center [transform-box:fill-box]" style={{ animationDelay: `${delay - 80}ms` }}>
				<circle
					r={c.slotR + 12}
					fill="none"
					className="hidden stroke-(--cat) dark:inline"
					strokeOpacity={0.14}
					strokeWidth={1}
				/>
				<circle
					r={c.r + 6}
					fill="none"
					className="stroke-(--cat)"
					strokeOpacity={0.35}
					strokeWidth={1}
					style={{ r: c.r + 6, transition: `r 600ms ${EASE}` }}
				/>
				<circle
					r={c.r}
					className="fill-(--cat-gloss) drop-shadow-[0_0_10px_color-mix(in_oklab,var(--cat)_60%,transparent)]"
					style={{
						["--cat-gloss" as string]: `url(#${ids.gloss(c.tone === 0 ? "cat-0" : "cat-1")})`,
						r: c.r,
						transition: `r 600ms ${EASE}`,
					}}
				/>
			</g>
			{label && (
				<g aria-hidden className="co-entrance pointer-events-none" style={{ animationDelay: `${delay + 60}ms` }}>
					<g transform={`translate(${-c.x} ${-c.y})`}>
						<text
							x={label.x}
							y={label.nameY}
							textAnchor={label.anchor}
							dominantBaseline="central"
							className="orbit-halo fill-ink tracking-[-0.01em]"
							style={{ fontSize: label.size }}
						>
							{c.label}
						</text>
						{label.chip && (
							<g>
								<rect
									x={label.chip.x}
									y={label.chip.y}
									width={label.chip.w}
									height={label.chip.h}
									rx={5}
									className="fill-[color-mix(in_oklab,var(--co-accent)_14%,var(--sg-panel))] stroke-(--co-accent)/30"
									strokeWidth={1}
								/>
								<text
									x={label.chip.x + label.chip.w / 2}
									y={label.chip.y + label.chip.h / 2}
									textAnchor="middle"
									dominantBaseline="central"
									className="fill-[color-mix(in_oklab,var(--co-accent)_72%,var(--sg-ink))] font-mono text-[10px] font-medium tabular-nums"
								>
									{c.shareText}
								</text>
							</g>
						)}
					</g>
				</g>
			)}
		</g>
	);
}

type SenderNodeProps = {
	s: OrbitSender;
	ids: OrbitIds;
	flagged: number;
	delay: number;
	tabbable: boolean;
	hovered: boolean;
	dim: boolean;
	hidden: boolean;
	target: SceneFocus;
	gliding: boolean;
	ariaLabel: string;
	onHover: (id: string | null) => void;
	onFocusNode: (id: string | null) => void;
	onActivate: (id: string) => void;
	onNavigate: (id: string, key: string) => void;
};

function SenderNode({
	s,
	ids,
	flagged,
	delay,
	tabbable,
	hovered,
	dim,
	hidden,
	target,
	gliding,
	ariaLabel,
	onHover,
	onFocusNode,
	onActivate,
	onNavigate,
}: SenderNodeProps) {
	const kind = s.person ? "person" : "machine";
	const role = s.person ? "agent" : "tool";
	const x = target ? target.x : s.x;
	const y = target ? target.y : s.y;
	const r = target ? target.r : s.r;
	const quiet = s.weight === 0;
	const hit = Math.max(s.slotR + 6, 13);
	const dot = { cx: r * 0.74, cy: -r * 0.74 };
	const chip = s.label.chip;
	const name = s.label.name;

	return (
		<g
			data-orbit-sender={s.id}
			role="button"
			tabIndex={tabbable ? 0 : -1}
			aria-label={ariaLabel}
			className="group/node cursor-pointer outline-none"
			style={{
				transform: `translate(${x}px, ${y}px)`,
				opacity: hidden ? 0 : dim ? 0.5 : 1,
				transition: gliding ? `transform 640ms ${EASE}, opacity 300ms ${EASE}` : `opacity 300ms ${EASE}`,
				pointerEvents: hidden ? "none" : undefined,
				["--node" as string]: `var(--co-${role})`,
				["--node-gloss" as string]: `url(#${ids.gloss(kind)})`,
			}}
			onClick={() => onActivate(s.id)}
			onKeyDown={(e) => {
				if (e.key === "Enter" || e.key === " ") {
					e.preventDefault();
					onActivate(s.id);
				} else if (NAV_KEYS.has(e.key)) {
					e.preventDefault();
					onNavigate(s.id, e.key);
				}
			}}
			onFocus={() => onFocusNode(s.id)}
			onBlur={() => onFocusNode(null)}
			onPointerEnter={() => onHover(s.id)}
			onPointerLeave={() => onHover(null)}
		>
			<g className="co-bloom origin-center [transform-box:fill-box]" style={{ animationDelay: `${delay}ms` }}>
				<g
					className="origin-center transition-transform duration-200 [transform-box:fill-box]"
					style={{ transform: hovered && !target ? "scale(1.14)" : undefined }}
				>
					<circle r={hit} fill="transparent" />
					<circle
						r={s.slotR + 5}
						fill="none"
						className="stroke-(--co-filament) opacity-0 transition-opacity group-focus-visible/node:opacity-100"
						strokeWidth={2}
						style={{ r: target ? r + 6 : s.slotR + 5, transition: `r 520ms ${EASE}, opacity 150ms` }}
					/>
					<circle
						r={r}
						className="fill-(--node-gloss) drop-shadow-[0_0_7px_color-mix(in_oklab,var(--node)_55%,transparent)]"
						style={{
							r,
							opacity: quiet && !target ? 0.55 : 1,
							transition: `r 560ms ${EASE}, opacity 300ms`,
						}}
					/>
					{flagged > 0 && (
						<circle
							r={2.8}
							className="fill-(--co-filament) stroke-panel"
							strokeWidth={1.5}
							style={{ cx: dot.cx, cy: dot.cy, opacity: target ? 0 : 1, transition: `cx 520ms ${EASE}, cy 520ms ${EASE}, opacity 200ms` }}
						/>
					)}
				</g>
			</g>
			{(chip || name) && (
				<g
					aria-hidden
					className="co-entrance"
					style={{ animationDelay: `${delay + 60}ms` }}
				>
					<g style={{ opacity: target ? 0 : 1, transition: "opacity 200ms" }}>
						{chip && (
							<g transform={`translate(${chip.x - s.x} ${chip.y - s.y})`}>
								<rect
									width={chip.w}
									height={CHIP_H}
									rx={CHIP_H / 2}
									className={cn(
										"fill-panel/80 stroke-hairline",
										hovered && "stroke-(--co-accent)/60",
									)}
									strokeWidth={1}
								/>
								<text
									x={chip.w / 2}
									y={CHIP_H / 2}
									textAnchor="middle"
									dominantBaseline="central"
									className={cn("fill-ink font-mono text-[10px] tabular-nums", quiet && "fill-ink-mute")}
								>
									{s.value}
								</text>
							</g>
						)}
						{name && (
							<text
								x={name.x - s.x}
								y={name.y - s.y}
								textAnchor={name.anchor}
								dominantBaseline="central"
								className={cn(
									"orbit-halo text-[11.5px] transition-colors",
									hovered ? "fill-ink" : "fill-ink-dim",
								)}
							>
								{name.text}
							</text>
						)}
					</g>
				</g>
			)}
		</g>
	);
}

function OrbitTooltip({
	layout,
	senders,
	tipId,
	now,
	vocab,
}: {
	layout: OrbitLayout;
	senders: Map<string, OrbitNodeData>;
	tipId: string | null;
	now: number | null;
	vocab: OrbitVocab;
}) {
	const node = tipId ? layout.senders.find((s) => s.id === tipId) : undefined;
	const stat = tipId ? senders.get(tipId) : undefined;
	if (!node || !stat) return null;
	const W = 236;
	const H = 118;
	const gap = node.slotR + 14;
	const preferRight = node.side === "right";
	let left = preferRight ? node.x + gap : node.x - gap - W;
	if (left + W > layout.width - 6) left = node.x - gap - W;
	if (left < 6) left = Math.min(layout.width - W - 6, node.x + gap);
	const top = clampNum(node.y - H / 2, 6, layout.height - H - 6);
	const week = layout.week;

	return (
		<div
			aria-hidden
			className="pointer-events-none absolute z-20 rounded-[18px] border border-hairline bg-panel/85 px-4 py-3.5 text-ink shadow-[0_26px_50px_-24px_rgb(0_0_0/0.6)] backdrop-blur-md transition-opacity duration-150 starting:opacity-0"
			style={{ left, top, width: W }}
		>
			<p className="truncate text-[15px] leading-tight">{displayName(stat)}</p>
			<p className="mt-0.5 truncate font-mono text-[11px] text-ink-dim">{stat.detail}</p>
			<div className="mt-2.5 flex items-baseline gap-3">
				<p className="text-[22px] leading-none tabular-nums">{formatCount(node.value)}</p>
				<p className="text-[12px] text-ink-dim">
					{week === null ? `${vocab.unit[1]} · ${vocab.window.all}` : `${vocab.unit[1]} in ${vocab.window.week(week)}`}
				</p>
			</div>
			<p className="mt-2 flex items-center gap-2 text-[12px] text-ink-dim">
				{stat.flagged > 0 ? (
					<span className="inline-flex items-center gap-1.5 text-ink">
						<span className="size-1.5 rounded-full bg-(--co-filament)" />
						{stat.flagged} {vocab.flag.label}
					</span>
				) : (
					<span>{vocab.flag.clear}</span>
				)}
				<span aria-hidden>·</span>
				<span className="truncate">
					{now !== null ? vocab.recency(stat, now) : layout.categories.find((c) => c.id === node.category)?.label}
				</span>
			</p>
		</div>
	);
}
```

### 3. `components/registry/visualizer/drilldown.tsx` — supporting file, required

```tsx
"use client";

import * as React from "react";
import { ArrowLeft, ArrowRight } from "lucide-react";
import { useAnimationLoop } from "@/hooks/use-animation-loop";
import { cn } from "@/lib/utils";
import {
	ROW_GAP,
	ROW_H,
	ROWS_HEADER,
	activityTicks,
	arcOffsets,
	fanCurve,
	panelTop,
	stackRows,
	ticksPath,
	type FocusCardId,
	type FocusLayout,
} from "./layout";
import { displayName, formatCount, READOUT } from "./format";
import { EASE, arriveAt } from "./motion";
import type { OrbitNodeData } from "./types";
import type { FocusCardSpec, OrbitFocus } from "./vocab";

const CURVE = { delay: 420, stagger: 70, dur: 620 };
const FAN = { delay: 760, stagger: 60, dur: 560 };
const cardArrive = (i: number) => arriveAt(CURVE.delay + i * CURVE.stagger, CURVE.dur);
const rowArrive = (i: number) => arriveAt(FAN.delay + i * FAN.stagger, FAN.dur);

type Card = FocusCardSpec;

type DrilldownProps = {
	sender: OrbitNodeData;
	group: string;
	focus: OrbitFocus;
	more?: { label: string; onClick: () => void };
	geom: FocusLayout;
	showOrb: boolean;
	now: number | null;
	reduced: boolean;
	returnTo: string;
	onBack: () => void;
	onAnnounce: (message: string) => void;
};

export function BackButton({ returnTo, onBack }: { returnTo: string; onBack: () => void }) {
	const ref = React.useRef<HTMLButtonElement>(null);
	React.useEffect(() => {
		ref.current?.focus({ preventScroll: true });
	}, []);
	return (
		<div className="flex items-center gap-2.5">
			<button
				ref={ref}
				type="button"
				onClick={onBack}
				className="inline-flex h-9 items-center gap-2 rounded-full bg-raised pr-4 pl-3 text-[13px] text-ink ring-1 ring-hairline transition-colors hover:bg-panel focus-visible:ring-2 focus-visible:ring-(--co-filament)/60 focus-visible:outline-none"
			>
				<ArrowLeft className="size-4" />
				Back to {returnTo}
			</button>
			<span className="hidden items-center gap-1.5 text-[11.5px] text-ink-dim sm:inline-flex">
				<Kbd>Esc</Kbd>
			</span>
		</div>
	);
}

export function Drilldown({ sender, group, focus, more, geom, showOrb, now, reduced, returnTo, onBack, onAnnounce }: DrilldownProps) {
	const cards = React.useMemo(() => focus.cards(sender, now), [focus, sender, now]);
	const rowsId = cards[0]?.id ?? "rows";
	const rows = React.useMemo(() => focus.rows(sender, now).slice(0, 5), [focus, sender, now]);
	const [selected, setSelected] = React.useState<FocusCardId>(rowsId);
	const uid = React.useId().replace(/[^a-zA-Z0-9_-]/g, "");
	const role = sender.kind === "agent" ? "agent" : "tool";

	const select = (id: FocusCardId) => {
		setSelected(id);
		const card = cards.find((c) => c.id === id);
		if (card) onAnnounce(`${card.label}: ${card.value}.`);
	};

	const style = {
		["--node" as string]: `var(--co-${role})`,
		["--node-gloss" as string]: `url(#${uid}-gloss)`,
	} as React.CSSProperties;

	const back = <BackButton returnTo={returnTo} onBack={onBack} />;

	if (geom.compact) {
		return (
			<section aria-label={`${displayName(sender)} details`} className="flex flex-col gap-4" style={style}>
				{back}
				<div className="flex items-center gap-4">
					<svg width={geom.height} height={geom.height} className="shrink-0 overflow-visible" aria-hidden>
						<FocusDefs uid={uid} />
						<ActivityRing sender={sender} geom={geom} uid={uid} showOrb reduced={reduced} />
					</svg>
					<Identity sender={sender} className="min-w-0 text-left" />
				</div>
				<div className="grid grid-cols-2 gap-2">
					{cards.map((card, i) => (
						<StatCard
							key={card.id}
							card={card}
							selected={selected === card.id}
							onSelect={select}
							reduced={reduced}
							delay={200 + i * 50}
							compact
							className={cn("h-[60px]", cards.length % 2 === 1 && i === cards.length - 1 && "col-span-2")}
						/>
					))}
				</div>
				<Detail focus={focus} sender={sender} selected={selected} rowsId={rowsId} rows={rows} more={more} now={now} reduced={reduced} compact />
			</section>
		);
	}

	const selectedCard = geom.cards.find((c) => c.id === selected) ?? geom.cards[0]!;
	const stack = stackRows(geom.detail, rows.length + (more ? 1 : 0));
	const from = { x: selectedCard.x + selectedCard.w + 2, y: selectedCard.cy };
	const panelY = panelTop(geom.detail, selectedCard.cy, focus.panelHeight[selected] ?? 240);
	const span = (stack.centers.at(-1) ?? 0) - (stack.centers[0] ?? 0);
	const offsets = arcOffsets(stack.centers, (stack.centers[0]! + stack.centers.at(-1)!) / 2, Math.max(1, span * 1.1));
	const rowEnds = stack.centers.slice(0, rows.length).map((y, i) => ({ x: geom.detail.x - 4 + (offsets[i] ?? 0), y }));
	const detailCurves =
		selected === rowsId
			? rowEnds.map((to) => fanCurve(from, to))
			: [fanCurve(from, { x: geom.detail.x - 4, y: panelY + 28 })];
	const { orb } = geom;

	return (
		<section aria-label={`${displayName(sender)} details`} className="absolute inset-0" style={style}>
			<svg width={geom.width} height={geom.height} className="pointer-events-none absolute inset-0" aria-hidden>
				<FocusDefs uid={uid} />
				<ellipse
					cx={orb.x}
					cy={orb.y}
					rx={geom.detail.x + geom.detail.w * 0.55 - orb.x}
					ry={geom.height * 0.62}
					fill="none"
					className="stroke-hairline"
					strokeWidth={1}
					strokeDasharray="1 7"
					strokeLinecap="round"
					style={fadeStyle(reduced, 200, 900)}
				/>
				<ActivityRing sender={sender} geom={geom} uid={uid} showOrb={showOrb} reduced={reduced} />
				<g fill="none" strokeLinecap="round">
					{geom.curves.map((d, i) => {
						const on = geom.cards[i]?.id === selected;
						return (
							<path
								key={i}
								d={d}
								pathLength={1}
								className={cn(
									"transition-[stroke,stroke-width] duration-300",
									on ? "stroke-(--co-accent)" : "stroke-ink-mute/60 dark:stroke-(--co-filament)/35",
								)}
								strokeWidth={on ? 1.6 : 1}
								style={drawStyle(reduced, CURVE.delay + i * CURVE.stagger, CURVE.dur)}
							/>
						);
					})}
				</g>
				{geom.cards.map((c, i) => (
					<Port key={c.id} x={c.x - 4} y={c.cy} on={c.id === selected} style={fadeStyle(reduced, cardArrive(i), 240)} />
				))}
				{!reduced && <Sparks paths={geom.curves} delay={CURVE.delay} stagger={CURVE.stagger} dur={CURVE.dur} />}
			</svg>

			<svg
				key={`fan-${selected}`}
				width={geom.width}
				height={geom.height}
				className="pointer-events-none absolute inset-0"
				aria-hidden
			>
				<g fill="none" strokeLinecap="round">
					{detailCurves.map((d, i) => (
						<path
							key={i}
							d={d}
							pathLength={1}
							className="stroke-(--co-accent)/65"
							strokeWidth={1.1}
							style={drawStyle(reduced, FAN.delay + i * FAN.stagger, FAN.dur)}
						/>
					))}
				</g>
				{selected === rowsId &&
					rowEnds.map((p, i) => <Port key={i} x={p.x} y={p.y} on style={fadeStyle(reduced, rowArrive(i), 240)} />)}
				{!reduced && <Sparks paths={detailCurves} delay={FAN.delay} stagger={FAN.stagger} dur={FAN.dur} />}
			</svg>

			<div className="absolute top-0 left-0">{back}</div>

			<Identity
				sender={sender}
				className="absolute w-[260px] -translate-x-1/2 text-center"
				style={{ left: geom.orb.x, top: Math.max(44, geom.orb.y - geom.ring.outer - 66) }}
			/>
			<div
				className="absolute flex -translate-x-1/2 flex-col items-center gap-2"
				style={{ left: geom.orb.x, top: geom.orb.y + geom.ring.outer + 14 }}
			>
				<span className="inline-flex h-6 items-center gap-1.5 rounded-full bg-raised px-2.5 text-[11.5px] text-ink ring-1 ring-hairline">
					<span className="size-1.5 rounded-full bg-(--node)" />
					{focus.chip(sender, group)}
				</span>
				<p className={cn(READOUT, "text-[10px]")}>{focus.ringCaption}</p>
			</div>

			{geom.cards.map((pos, i) => {
				const card = cards.find((c) => c.id === pos.id)!;
				return (
					<StatCard
						key={card.id}
						card={card}
						selected={selected === card.id}
						onSelect={select}
						reduced={reduced}
						delay={cardArrive(i) - 60}
						className="absolute"
						style={{ left: pos.x, top: pos.y, width: pos.w, height: pos.h }}
					/>
				);
			})}

			<div
				key={`detail-${selected}`}
				className="absolute"
				style={{
					left: geom.detail.x,
					top: selected === rowsId ? stack.top : panelY,
					width: geom.detail.w,
				}}
			>
				<Detail
					focus={focus}
					sender={sender}
					selected={selected}
					rowsId={rowsId}
					rows={rows}
					more={more}
					now={now}
					reduced={reduced}
					offsets={offsets}
				/>
			</div>
		</section>
	);
}

function drawStyle(reduced: boolean, delay: number, dur: number): React.CSSProperties | undefined {
	if (reduced) return undefined;
	return {
		strokeDasharray: 1,
		strokeDashoffset: 1,
		animation: `co-draw ${dur}ms ${EASE} ${delay}ms forwards`,
	};
}

function riseStyle(reduced: boolean, delay: number): React.CSSProperties | undefined {
	if (reduced) return undefined;
	return { animation: `co-rise 420ms ${EASE} ${delay}ms backwards` };
}

function igniteStyle(reduced: boolean, delay: number): React.CSSProperties | undefined {
	if (reduced) return undefined;
	return { animation: `co-ignite 380ms ${EASE} ${delay}ms backwards` };
}

function fadeStyle(reduced: boolean, delay: number, dur: number): React.CSSProperties | undefined {
	if (reduced) return undefined;
	return { animation: `co-fade ${dur}ms ${EASE} ${delay}ms backwards` };
}

function Port({ x, y, on, style }: { x: number; y: number; on: boolean; style?: React.CSSProperties }) {
	return (
		<rect
			x={x}
			y={y - 7}
			width={3}
			height={14}
			rx={1.5}
			className={cn("transition-[fill] duration-300", on ? "fill-(--co-accent)" : "fill-ink-mute/50 dark:fill-(--co-filament)/45")}
			style={style}
		/>
	);
}

function FocusDefs({ uid }: { uid: string }) {
	return (
		<defs>
			<radialGradient id={`${uid}-gloss`} cx="0.4" cy="0.36" r="0.72" fx="0.32" fy="0.26">
				<stop offset="0" style={{ stopColor: "color-mix(in oklab, var(--node) 30%, white)" }} />
				<stop offset="0.45" style={{ stopColor: "var(--node)" }} />
				<stop offset="1" style={{ stopColor: "color-mix(in oklab, var(--node) 52%, black)" }} />
			</radialGradient>
			<radialGradient id={`${uid}-halo`}>
				<stop offset="0.3" style={{ stopColor: "var(--node)", stopOpacity: 0 }} />
				<stop offset="0.5" style={{ stopColor: "var(--node)", stopOpacity: 0.16 }} />
				<stop offset="1" style={{ stopColor: "var(--node)", stopOpacity: 0 }} />
			</radialGradient>
		</defs>
	);
}

function ActivityRing({
	sender,
	geom,
	uid,
	showOrb,
	reduced,
}: {
	sender: OrbitNodeData;
	geom: FocusLayout;
	uid: string;
	showOrb: boolean;
	reduced: boolean;
}) {
	const { orb, ring } = geom;
	const ticks = activityTicks(sender.daily, orb.x, orb.y, ring.inner, ring.maxLen);
	const d = ticksPath(ticks);
	const busiest = ticks.reduce((best, t) => (t.value > best.value ? t : best), ticks[0] ?? { value: 0, x2: 0, y2: 0 });
	return (
		<g>
			<circle cx={orb.x} cy={orb.y} r={ring.outer + 26} fill={`url(#${uid}-halo)`} className="hidden dark:inline" />
			<circle
				cx={orb.x}
				cy={orb.y}
				r={ring.inner - 3.5}
				fill="none"
				className="stroke-hairline"
				strokeWidth={1}
			/>
			<path
				d={d}
				pathLength={1}
				fill="none"
				strokeLinecap="round"
				strokeWidth={2.4}
				className="stroke-(--node)"
				style={drawStyle(reduced, 260, 900)}
			/>
			{busiest.value > 0 && (
				<circle
					cx={busiest.x2}
					cy={busiest.y2}
					r={2.6}
					className="fill-ink"
					style={riseStyle(reduced, 1100)}
				/>
			)}
			{showOrb && (
				<g className="origin-center [transform-box:fill-box]" style={reduced ? undefined : { animation: `co-bloom 700ms ${EASE} both` }}>
					<circle
						cx={orb.x}
						cy={orb.y}
						r={orb.r}
						strokeWidth={1}
						className={cn(
							"fill-(--node-gloss) stroke-none drop-shadow-[0_0_12px_color-mix(in_oklab,var(--node)_55%,transparent)]",
						)}
					/>
				</g>
			)}
		</g>
	);
}

function Sparks({ paths, delay, stagger, dur }: { paths: string[]; delay: number; stagger: number; dur: number }) {
	return (
		<g>
			{paths.map((d, i) => {
				const begin = `${(delay + i * stagger) / 1000}s`;
				return (
					<g key={i} opacity={0}>
						<circle r={4} className="fill-(--co-accent)" opacity={0.3} />
						<circle r={1.5} className="fill-[color-mix(in_oklab,var(--co-accent)_22%,white)]" />
						<animateMotion dur={`${dur}ms`} begin={begin} path={d} calcMode="spline" keyPoints="0;1" keyTimes="0;1" keySplines="0.23 1 0.32 1" fill="freeze" />
						<animate attributeName="opacity" values="0;1;1;0" keyTimes="0;0.1;0.75;1" dur={`${dur + 260}ms`} begin={begin} fill="freeze" />
					</g>
				);
			})}
		</g>
	);
}

function Identity({ sender, className, style }: { sender: OrbitNodeData; className?: string; style?: React.CSSProperties }) {
	return (
		<div className={className} style={style}>
			<h3 className="truncate text-[20px] leading-tight tracking-[-0.01em] text-ink">{displayName(sender)}</h3>
			<p className="mt-1 truncate font-mono text-[11.5px] text-ink-dim">{sender.detail}</p>
		</div>
	);
}

function StatCard({
	card,
	selected,
	onSelect,
	reduced,
	delay,
	compact = false,
	className,
	style,
}: {
	card: Card;
	selected: boolean;
	onSelect: (id: FocusCardId) => void;
	reduced: boolean;
	delay: number;
	compact?: boolean;
	className?: string;
	style?: React.CSSProperties;
}) {
	const Icon = card.icon;
	return (
		<button
			type="button"
			data-orbit-card={card.id}
			aria-label={card.spoken.charAt(0).toUpperCase() + card.spoken.slice(1)}
			aria-pressed={selected}
			onClick={() => onSelect(card.id)}
			className={cn(
				"group flex items-center rounded-[16px] text-left transition-[background-color,box-shadow,color] duration-200",
				compact ? "gap-2.5 px-3" : "gap-3 px-3.5",
				"focus-visible:ring-2 focus-visible:ring-(--co-filament)/60 focus-visible:outline-none",
				selected
					? "bg-[linear-gradient(100deg,color-mix(in_oklab,var(--co-accent)_26%,var(--sg-panel)),color-mix(in_oklab,var(--co-accent)_8%,var(--sg-panel))_70%)] text-ink shadow-[inset_0_1px_0_color-mix(in_oklab,white_14%,transparent),0_0_0_1px_color-mix(in_oklab,var(--co-accent)_50%,transparent),0_0_34px_-6px_color-mix(in_oklab,var(--co-accent)_45%,transparent)]"
					: "bg-[linear-gradient(100deg,color-mix(in_oklab,var(--co-filament)_9%,var(--sg-raised)),var(--sg-raised)_55%)] text-ink ring-1 ring-hairline hover:ring-(--co-accent)/35",
				className,
			)}
			style={{ ...style, ...igniteStyle(reduced, delay) }}
		>
			<span
				className={cn(
					"grid shrink-0 place-items-center rounded-full",
					compact ? "size-7" : "size-8",
					selected ? "bg-(--co-accent)/15 text-(--co-accent)" : "bg-panel text-ink-dim",
				)}
			>
				<Icon className="size-4" />
			</span>
			<span className="min-w-0">
				<span className="block truncate text-[20px] leading-none tracking-[-0.02em] tabular-nums">
					<CountUp key={card.value} value={card.value} delay={delay} reduced={reduced} />
				</span>
				<span className={cn("mt-1 block truncate text-[12px]", selected ? "text-ink-dim" : "text-ink-mute")}>{card.label}</span>
			</span>
		</button>
	);
}

const COUNTABLE = /^(\d{1,3}(?:,\d{3})*|\d+)(%?)$/;
const COUNT_MS = 700;

function CountUp({ value, delay, reduced }: { value: string; delay: number; reduced: boolean }) {
	const ref = React.useRef<HTMLSpanElement>(null);
	const match = reduced ? null : COUNTABLE.exec(value);
	const target = match ? Number(match[1]!.replaceAll(",", "")) : 0;
	const suffix = match?.[2] ?? "";
	useAnimationLoop({
		target: ref,
		halted: !match,
		paintWhenHalted: false,
		onFrame: ({ elapsed }) => {
			const el = ref.current;
			if (!el) return false;
			const t = Math.min(1, Math.max(0, (elapsed * 1000 - delay) / COUNT_MS));
			el.textContent = t >= 1 ? value : `${formatCount(target * (1 - (1 - t) ** 3))}${suffix}`;
			if (t >= 1) return false;
		},
	});
	return <span ref={ref}>{value}</span>;
}

function Detail({
	focus,
	sender,
	selected,
	rowsId,
	rows,
	more,
	now,
	reduced,
	offsets,
	compact = false,
}: {
	focus: OrbitFocus;
	sender: OrbitNodeData;
	selected: FocusCardId;
	rowsId: FocusCardId;
	rows: { key: string; node: React.ReactNode }[];
	more?: { label: string; onClick: () => void };
	now: number | null;
	reduced: boolean;
	offsets?: number[];
	compact?: boolean;
}) {
	const shift = (i: number) => (offsets?.[i] ? `${offsets[i]}px 0` : undefined);
	const bow = offsets?.length ? Math.max(0, ...offsets) : 0;
	if (selected === rowsId) {
		const note = focus.rowsNote(sender);
		return (
			<div>
				<div
					className="flex items-center justify-between gap-3"
					style={{ height: ROWS_HEADER, ...riseStyle(reduced, compact ? 200 : rowArrive(0) - 120) }}
				>
					<p className={READOUT}>{focus.rowsTitle(sender)}</p>
					{note && <p className="text-[12px] text-[color-mix(in_oklab,var(--co-accent)_72%,var(--sg-ink))]">{note}</p>}
				</div>
				{rows.length === 0 ? (
					<p className="rounded-[14px] bg-raised px-4 py-3 text-[13px] text-ink-dim ring-1 ring-hairline">
						{focus.emptyRows}
					</p>
				) : (
					<ul className="flex flex-col" style={{ gap: ROW_GAP, paddingRight: bow }}>
						{rows.map((row, i) => (
							<li
								key={row.key}
								style={{ height: ROW_H, translate: shift(i), ...riseStyle(reduced, compact ? 260 + i * 60 : rowArrive(i) - 40) }}
							>
								{row.node}
							</li>
						))}
					</ul>
				)}
				{more && (
					<button
						type="button"
						onClick={more.onClick}
						className="group mt-2 inline-flex h-9 items-center gap-2 rounded-full px-4 text-[13px] text-ink-dim ring-1 ring-hairline transition-colors hover:text-ink hover:ring-(--co-accent)/40 focus-visible:ring-2 focus-visible:ring-(--co-filament)/60 focus-visible:outline-none"
						style={{
							translate: shift(rows.length),
							...riseStyle(reduced, compact ? 260 + rows.length * 60 : rowArrive(rows.length) - 40),
						}}
					>
						{more.label}
						<ArrowRight className="size-3.5 transition-transform duration-200 group-hover:translate-x-0.5" />
					</button>
				)}
			</div>
		);
	}

	return (
		<div
			className="rounded-[20px] border border-hairline bg-panel/80 p-5 text-ink shadow-[0_26px_50px_-24px_rgb(0_0_0/0.6)] backdrop-blur-md"
			style={riseStyle(reduced, compact ? 120 : rowArrive(0) - 40)}
		>
			{focus.panel(sender, selected, now)}
		</div>
	);
}

export function Kbd({ children }: { children: React.ReactNode }) {
	return (
		<kbd className="inline-flex h-5 min-w-5 items-center justify-center rounded-[5px] border border-hairline bg-raised px-1.5 font-mono text-[10.5px] text-ink-dim">
			{children}
		</kbd>
	);
}
```

### 4. `components/registry/visualizer/list.tsx` — supporting file, required

```tsx
"use client";

import * as React from "react";
import { ChevronRight } from "lucide-react";
import { cn } from "@/lib/utils";
import { senderValue, type OrbitCategory, type WeekIndex } from "./layout";
import { displayName, formatCount, plural } from "./format";
import type { OrbitNodeData } from "./types";
import { capitalize, type OrbitVocab } from "./vocab";

function initials(name: string, fallback: string): string {
	const words = (name.trim() || fallback).split(/[\s._@-]+/).filter(Boolean);
	const letters = words.length > 1 ? words[0]![0]! + words[1]![0]! : (words[0] ?? "?").slice(0, 2);
	return letters.toUpperCase();
}

const PREVIEW_ROWS = 8;

export function OrbitList({
	senders,
	categories,
	week,
	now,
	vocab,
	onOpen,
}: {
	senders: OrbitNodeData[];
	categories: OrbitCategory[];
	week: WeekIndex | null;
	now: number | null;
	vocab: OrbitVocab;
	onOpen: (id: string) => void;
}) {
	const [expanded, setExpanded] = React.useState(false);
	const ranked = React.useMemo(
		() =>
			senders
				.map((s, i) => ({ s, i, v: senderValue(s, week) }))
				.sort((a, b) => b.v - a.v || b.s.count - a.s.count || a.i - b.i),
		[senders, week],
	);
	const shown = expanded ? ranked : ranked.slice(0, PREVIEW_ROWS);
	const byShare = [...categories].sort((a, b) => b.value - a.value || a.order - b.order);
	const period = week === null ? vocab.window.all : vocab.window.week(week);
	const labelOf = new Map(categories.map((c) => [c.id, c.label]));

	return (
		<div className="@container flex flex-col gap-5">
			<CategoryBar categories={byShare} label={`${capitalize(vocab.mass)} by ${vocab.group[0]}, ${period}`} />
			<ol aria-label={`${capitalize(vocab.node[1])} ranked by ${vocab.mass}, ${period}`} className="flex flex-col gap-1">
				{shown.map(({ s, v }, idx) => (
					<li key={s.id}>
						<Row sender={s} group={labelOf.get(s.group) ?? s.group} rank={idx + 1} value={v} week={week} now={now} vocab={vocab} onOpen={onOpen} />
					</li>
				))}
			</ol>
			{ranked.length > PREVIEW_ROWS && (
				<button
					type="button"
					onClick={() => setExpanded((x) => !x)}
					aria-expanded={expanded}
					className="self-start rounded-full px-3.5 py-2 text-[13px] text-ink-dim ring-1 ring-hairline transition-colors hover:text-ink focus-visible:ring-2 focus-visible:ring-(--co-filament)/60 focus-visible:outline-none"
				>
					{expanded ? "Show top 8" : `Show all ${ranked.length} ${vocab.node[1]}`}
				</button>
			)}
		</div>
	);
}

function CategoryBar({ categories, label }: { categories: OrbitCategory[]; label: string }) {
	const total = categories.reduce((a, c) => a + c.value, 0);
	const summary = categories.map((c) => `${c.label} ${c.shareText}`).join(", ");
	return (
		<div>
			<div role="img" aria-label={`${label}: ${summary}`} className="flex h-2.5 w-full gap-0.5 overflow-hidden rounded-full">
				{total > 0 &&
					categories.map((c, i) => (
						<span
							key={c.id}
							className="h-full transition-[flex-grow] duration-500"
							style={{
								flexGrow: c.value,
								flexBasis: 0,
								minWidth: c.value > 0 ? 3 : 0,
								background: `color-mix(in oklab, var(--co-cat-${c.tone}) ${Math.max(28, 100 - i * 12)}%, transparent)`,
							}}
						/>
					))}
			</div>
			<ul className="mt-2.5 flex flex-wrap gap-x-4 gap-y-1.5 text-[12px] text-ink-dim" aria-hidden>
				{categories.map((c, i) => (
					<li key={c.id} className="inline-flex items-center gap-1.5">
						<span
							className="size-2 rounded-full"
							style={{ background: `color-mix(in oklab, var(--co-cat-${c.tone}) ${Math.max(28, 100 - i * 12)}%, transparent)` }}
						/>
						{c.label}
						<span className="text-ink tabular-nums">{c.shareText}</span>
					</li>
				))}
			</ul>
		</div>
	);
}

function Row({
	sender,
	group,
	rank,
	value,
	week,
	now,
	vocab,
	onOpen,
}: {
	sender: OrbitNodeData;
	group: string;
	rank: number;
	value: number;
	week: WeekIndex | null;
	now: number | null;
	vocab: OrbitVocab;
	onOpen: (id: string) => void;
}) {
	const person = sender.kind === "agent";
	const name = displayName(sender);
	const label = [
		`${rank}. ${name}`,
		week === null ? plural(value, vocab.unit[0], vocab.unit[1]) : `${plural(value, vocab.unit[0], vocab.unit[1])} in ${vocab.window.week(week)}`,
		`${formatCount(sender.flagged)} ${vocab.flag.label}`,
		group,
		now === null ? null : vocab.recencyLong(sender, now),
	]
		.filter(Boolean)
		.join(", ");

	return (
		<button
			type="button"
			data-orbit-row={sender.id}
			onClick={() => onOpen(sender.id)}
			aria-label={label}
			className={cn(
				"group grid h-[52px] w-full items-center gap-2 rounded-[14px] px-2.5 text-left transition-colors duration-150 @xl:gap-3",
				"grid-cols-[1.25rem_2rem_minmax(0,1fr)_2.25rem_3.5rem]",
				"@xl:grid-cols-[1.5rem_2rem_minmax(0,1fr)_6.5rem_2.75rem_4.25rem_1rem]",
				"@3xl:grid-cols-[1.5rem_2rem_minmax(0,1.25fr)_minmax(6.5rem,0.55fr)_minmax(6.5rem,1fr)_3rem_4.5rem_4.5rem_1rem]",
				"hover:bg-raised focus-visible:ring-2 focus-visible:ring-(--co-filament)/60 focus-visible:outline-none",
			)}
		>
			<span className="font-mono text-[11px] text-ink-mute tabular-nums">{rank}</span>
			<span
				className={cn(
					"grid size-8 place-items-center rounded-full font-mono text-[10px] font-semibold text-[#0b1616]",
					person ? "bg-(--co-agent)" : "bg-(--co-tool)",
				)}
			>
				{initials(sender.name, sender.id)}
			</span>
			<span className="min-w-0">
				<span className="block truncate text-[14px] leading-tight text-ink">{name}</span>
				<span className="block truncate text-[11.5px] text-ink-dim">{sender.detail}</span>
			</span>
			<span className="hidden truncate text-[12px] text-ink-dim @xl:block">{group}</span>
			<Spark daily={sender.daily} week={week} person={person} className="hidden h-5 w-full @3xl:block" />
			<span className={cn("text-right text-[16px] text-ink tabular-nums", value === 0 && "text-ink-mute")}>{formatCount(value)}</span>
			<span className="flex justify-start">
				{sender.flagged > 0 && (
					<span className="rounded-full bg-(--co-accent)/15 px-2 py-0.5 text-[11px] whitespace-nowrap text-[color-mix(in_oklab,var(--co-accent)_72%,var(--sg-ink))] tabular-nums">
						{sender.flagged} {vocab.flag.chip}
					</span>
				)}
			</span>
			<span className="hidden text-right text-[12px] text-ink-dim @3xl:block">{now === null ? "" : vocab.ago(sender, now)}</span>
			<ChevronRight className="hidden size-4 text-ink-mute transition-transform duration-150 group-hover:translate-x-0.5 @xl:block" />
		</button>
	);
}

function Spark({ daily, week, person, className }: { daily: number[]; week: WeekIndex | null; person: boolean; className?: string }) {
	const n = daily.length || 1;
	const max = Math.max(1, ...daily);
	const W = 104;
	const H = 20;
	const bw = W / n;
	const start = week === null ? -1 : n - 28 + week * 7;
	return (
		<svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" className={className} aria-hidden>
			{daily.map((v, i) => {
				const h = v > 0 ? Math.max(2, (v / max) * H) : 1;
				const inWeek = week === null || (i >= start && i < start + 7);
				return (
					<rect
						key={i}
						x={i * bw + 0.5}
						y={H - h}
						width={Math.max(1, bw - 1.2)}
						height={h}
						rx={0.8}
						className={person ? "fill-(--co-agent)" : "fill-(--co-tool)"}
						opacity={v === 0 ? 0.25 : inWeek ? 0.95 : 0.22}
					/>
				);
			})}
		</svg>
	);
}
```

### 5. `components/registry/visualizer/segmented.tsx` — supporting file, required

```tsx
"use client";

import * as React from "react";
import { cn } from "@/lib/utils";

export type SegmentedOption = {
	value: string;
	label: React.ReactNode;
	spoken?: string;
};

export function Segmented({
	label,
	value,
	options,
	onChange,
	className,
	inert,
}: {
	label: string;
	value: string;
	options: SegmentedOption[];
	onChange: (value: string) => void;
	className?: string;
	inert?: boolean;
}) {
	const refs = React.useRef<(HTMLButtonElement | null)[]>([]);

	const onKeyDown = (e: React.KeyboardEvent, i: number) => {
		const n = options.length;
		let next = -1;
		if (e.key === "ArrowRight" || e.key === "ArrowDown") next = (i + 1) % n;
		else if (e.key === "ArrowLeft" || e.key === "ArrowUp") next = (i - 1 + n) % n;
		else if (e.key === "Home") next = 0;
		else if (e.key === "End") next = n - 1;
		if (next < 0) return;
		e.preventDefault();
		onChange(options[next]!.value);
		refs.current[next]?.focus();
	};

	return (
		<div
			role="radiogroup"
			aria-label={label}
			inert={inert}
			className={cn("inline-flex items-center gap-0.5 rounded-full bg-raised p-1", className)}
		>
			{options.map((o, i) => {
				const on = o.value === value;
				return (
					<button
						key={o.value}
						ref={(el) => {
							refs.current[i] = el;
						}}
						type="button"
						role="radio"
						aria-checked={on}
						aria-label={o.spoken}
						tabIndex={on ? 0 : -1}
						onClick={() => onChange(o.value)}
						onKeyDown={(e) => onKeyDown(e, i)}
						className={cn(
							"inline-flex h-8 items-center gap-1.5 rounded-full px-3 text-[13px] tabular-nums transition-colors duration-200",
							"focus-visible:ring-2 focus-visible:ring-accent/60 focus-visible:ring-offset-1 focus-visible:ring-offset-raised focus-visible:outline-none",
							on ? "bg-accent text-on-accent" : "text-ink-dim hover:text-ink",
						)}
					>
						{o.label}
					</button>
				);
			})}
		</div>
	);
}
```

### 6. `components/registry/visualizer/layout.ts` — supporting file, required

```tsx
import type { OrbitGroup, OrbitNodeData } from "./types";

export type WeekIndex = 0 | 1 | 2 | 3;
export type Side = "left" | "right";
export type Point = { x: number; y: number };
export type Box = { x: number; y: number; w: number; h: number };

export const MAX_SENDERS = 24;
export const MAX_GROUPS = 7;
export const WEEKS: readonly WeekIndex[] = [0, 1, 2, 3];

export function resolveGroups(senders: readonly OrbitNodeData[], groups: readonly OrbitGroup[]): OrbitGroup[] {
	const out: OrbitGroup[] = [];
	const seen = new Set<string>();
	const source = groups.length ? groups : senders.map((s) => ({ id: s.group, label: s.group, count: 0 }));
	for (const g of source) {
		if (!g.id || seen.has(g.id)) continue;
		seen.add(g.id);
		out.push(g);
		if (out.length === MAX_GROUPS) break;
	}
	return out;
}

function groupOf(s: OrbitNodeData, ids: ReadonlySet<string>, fallback: string): string {
	return ids.has(s.group) ? s.group : fallback;
}

const TAU = Math.PI * 2;
const HOUR = 3_600_000;
const WEEK_SHARE = 7 / 30;

export const SENDER_NAME_SIZE = 11.5;
export const CHIP_H = 15;
export const CATEGORY_NAME_SIZE = 14;
const CHIP_FONT = 10;
const MONO_EM = 0.6;
const LABEL_H = 15;

export const clamp = (v: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, v));
const r2 = (n: number) => Math.round(n * 100) / 100;
const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
const norm = (t: number) => ((t % TAU) + TAU) % TAU;

function onEllipse(cx: number, cy: number, rx: number, ry: number, t: number): Point {
	return { x: cx + rx * Math.sin(t), y: cy - ry * Math.cos(t) };
}

function glyph(ch: string): number {
	if (ch === " ") return 0.27;
	if ("iljI.,:;'|!".includes(ch)) return 0.27;
	if ("tfr()[]-".includes(ch)) return 0.37;
	if ("mwMW@".includes(ch)) return 0.86;
	if (ch >= "0" && ch <= "9") return 0.58;
	if (ch >= "A" && ch <= "Z") return 0.67;
	return 0.56;
}

export function textWidth(text: string, size: number): number {
	let w = 0;
	for (const ch of text) w += glyph(ch);
	return w * size;
}

export function chipWidth(chars: number): number {
	return Math.ceil(chars * CHIP_FONT * MONO_EM + 11);
}

export function shortLabel(text: string, max = 16): string {
	return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
}

function boxHitsCircle(b: Box, c: Point, r: number): boolean {
	const nx = clamp(c.x, b.x, b.x + b.w);
	const ny = clamp(c.y, b.y, b.y + b.h);
	return (c.x - nx) ** 2 + (c.y - ny) ** 2 < r * r;
}

function boxesHit(a: Box, b: Box, pad = 0): boolean {
	return a.x < b.x + b.w + pad && a.x + a.w + pad > b.x && a.y < b.y + b.h + pad && a.y + a.h + pad > b.y;
}

function boxInside(b: Box, width: number, height: number, pad: number): boolean {
	return b.x >= pad && b.y >= pad && b.x + b.w <= width - pad && b.y + b.h <= height - pad;
}

function segHitsBox(p: Point, q: Point, b: Box, halfWidth: number): boolean {
	const steps = Math.max(2, Math.ceil(Math.hypot(q.x - p.x, q.y - p.y) / 4));
	for (let i = 0; i <= steps; i++) {
		const t = i / steps;
		if (boxHitsCircle(b, { x: lerp(p.x, q.x, t), y: lerp(p.y, q.y, t) }, halfWidth)) return true;
	}
	return false;
}

export function senderValue(s: OrbitNodeData, week: WeekIndex | null): number {
	const v = week === null ? s.count : s.weekly?.[week];
	return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0;
}

type CategoryAgg = {
	id: string;
	label: string;
	count: number;
	weeks: [number, number, number, number];
	senderCount: number;
	lastAt: number;
};

function aggregateCategories(senders: readonly OrbitNodeData[], groupsIn: readonly OrbitGroup[]): CategoryAgg[] {
	const groups = resolveGroups(senders, groupsIn);
	const ids = new Set(groups.map((g) => g.id));
	const fallback = groups.at(-1)?.id ?? "";
	const bySender = new Map<string, { count: number; weeks: number[]; n: number; lastAt: number }>();
	for (const s of senders) {
		const cat = groupOf(s, ids, fallback);
		const acc = bySender.get(cat) ?? { count: 0, weeks: [0, 0, 0, 0], n: 0, lastAt: -Infinity };
		acc.count += senderValue(s, null);
		for (const w of WEEKS) acc.weeks[w]! += senderValue(s, w);
		acc.n += 1;
		const t = Date.parse(s.lastAt);
		if (!Number.isNaN(t)) acc.lastAt = Math.max(acc.lastAt, t);
		bySender.set(cat, acc);
	}
	const out: CategoryAgg[] = [];
	for (const g of groups) {
		const acc = bySender.get(g.id);
		const given = Number.isFinite(g.count) ? Math.max(0, g.count) : 0;
		const count = Math.max(given, acc?.count ?? 0);
		if (count <= 0 && !acc?.n) continue;
		const weeks = WEEKS.map((w) => {
			if (acc && acc.count > 0) return (count * acc.weeks[w]!) / acc.count;
			return count * WEEK_SHARE;
		}) as CategoryAgg["weeks"];
		out.push({ id: g.id, label: g.label, count, weeks, senderCount: acc?.n ?? 0, lastAt: acc?.lastAt ?? -Infinity });
	}
	return out;
}

export type CategoryShare = { id: string; label: string; count: number; value: number; pct: number; text: string };

export function categoryShares(
	senders: readonly OrbitNodeData[],
	groups: readonly OrbitGroup[],
	week: WeekIndex | null = null,
): CategoryShare[] {
	const aggs = aggregateCategories(normalizeSenders(senders), groups);
	const values = aggs.map((c) => (week === null ? c.count : c.weeks[week]));
	const pcts = sharePercents(values);
	return aggs.map((c, i) => ({
		id: c.id,
		label: c.label,
		count: c.count,
		value: values[i]!,
		pct: pcts[i]!,
		text: formatShare(pcts[i]!, values[i]!),
	}));
}

export function sharePercents(values: number[]): number[] {
	const total = values.reduce((a, b) => a + b, 0);
	if (total <= 0) return values.map(() => 0);
	const raw = values.map((v) => (v / total) * 100);
	const floors = raw.map(Math.floor);
	let left = 100 - floors.reduce((a, b) => a + b, 0);
	const order = raw.map((v, i) => ({ i, rem: v - Math.floor(v) })).sort((a, b) => b.rem - a.rem || a.i - b.i);
	for (const { i } of order) {
		if (left <= 0) break;
		floors[i]! += 1;
		left -= 1;
	}
	return floors;
}

export function formatShare(pct: number, value: number): string {
	if (value > 0 && pct < 1) return "<1%";
	return `${pct}%`;
}

export type Tick = { x1: number; y1: number; x2: number; y2: number; value: number; day: number };

export function activityTicks(
	daily: readonly number[],
	cx: number,
	cy: number,
	inner: number,
	maxLen: number,
): Tick[] {
	const n = daily.length;
	if (!n) return [];
	const max = Math.max(1, ...daily.map((v) => (Number.isFinite(v) ? v : 0)));
	return daily.map((raw, day) => {
		const value = Number.isFinite(raw) && raw > 0 ? raw : 0;
		const t = ((day + 0.5) / n) * TAU;
		const len = value > 0 ? Math.max(2, (maxLen * value) / max) : 0;
		const a = onEllipse(cx, cy, inner, inner, t);
		const b = onEllipse(cx, cy, inner + len, inner + len, t);
		return { x1: r2(a.x), y1: r2(a.y), x2: r2(b.x), y2: r2(b.y), value, day };
	});
}

export function ticksPath(ticks: readonly Tick[]): string {
	return ticks
		.map((t) =>
			t.value > 0 ? `M${t.x1} ${t.y1}L${t.x2} ${t.y2}` : `M${t.x1} ${t.y1}l0.01 0`,
		)
		.join("");
}

export function combinedDaily(senders: readonly OrbitNodeData[], days = 30): number[] {
	const out = new Array<number>(days).fill(0);
	for (const s of senders) {
		const d = s.daily ?? [];
		for (let i = 0; i < Math.min(days, d.length); i++) {
			const v = d[d.length - 1 - i];
			if (typeof v === "number" && Number.isFinite(v) && v > 0) out[days - 1 - i]! += v;
		}
	}
	return out;
}

function quad(p0: Point, c: Point, p2: Point, t: number): Point {
	const u = 1 - t;
	return { x: u * u * p0.x + 2 * u * t * c.x + t * t * p2.x, y: u * u * p0.y + 2 * u * t * c.y + t * t * p2.y };
}

function quadPath(p0: Point, c: Point, p2: Point): string {
	return `M${r2(p0.x)} ${r2(p0.y)}Q${r2(c.x)} ${r2(c.y)} ${r2(p2.x)} ${r2(p2.y)}`;
}

function quadLength(p0: Point, c: Point, p2: Point): number {
	let len = 0;
	let prev = p0;
	for (let i = 1; i <= 16; i++) {
		const p = quad(p0, c, p2, i / 16);
		len += Math.hypot(p.x - prev.x, p.y - prev.y);
		prev = p;
	}
	return len;
}

function quadTrack(p0: Point, c: Point, p2: Point, n = 18): string {
	const fine = Array.from({ length: 65 }, (_, i) => quad(p0, c, p2, i / 64));
	const cum = [0];
	for (let i = 1; i < fine.length; i++) cum.push(cum[i - 1]! + Math.hypot(fine[i]!.x - fine[i - 1]!.x, fine[i]!.y - fine[i - 1]!.y));
	const total = cum.at(-1) || 1;
	const out: string[] = [];
	let k = 1;
	for (let i = 0; i <= n; i++) {
		const target = (total * i) / n;
		while (k < cum.length - 1 && cum[k]! < target) k++;
		const seg = cum[k]! - cum[k - 1]! || 1;
		const f = (target - cum[k - 1]!) / seg;
		const a = fine[k - 1]!;
		const b = fine[k]!;
		out.push(`${r2(lerp(a.x, b.x, f))},${r2(lerp(a.y, b.y, f))}`);
	}
	return out.join(" ");
}

function chevron(tip: Point, dir: Point, len: number): string {
	const n = Math.hypot(dir.x, dir.y) || 1;
	const ux = dir.x / n;
	const uy = dir.y / n;
	const c = Math.cos(0.49);
	const s = Math.sin(0.49);
	const arm = (sign: number) => ({
		x: tip.x - len * (ux * c - sign * uy * s),
		y: tip.y - len * (uy * c + sign * ux * s),
	});
	const a = arm(1);
	const b = arm(-1);
	return `M${r2(a.x)} ${r2(a.y)}L${r2(tip.x)} ${r2(tip.y)}L${r2(b.x)} ${r2(b.y)}`;
}

export function fanCurve(from: Point, to: Point): string {
	const dx = (to.x - from.x) * 0.55;
	return `M${r2(from.x)} ${r2(from.y)}C${r2(from.x + dx)} ${r2(from.y)} ${r2(to.x - dx)} ${r2(to.y)} ${r2(to.x)} ${r2(to.y)}`;
}

type ArcTable = { total: number; at: (t: number) => number; inverse: (s: number) => number };

function arcTable(rx: number, ry: number): ArcTable {
	const N = 720;
	const cum = new Float64Array(N + 1);
	for (let k = 1; k <= N; k++) {
		const t = ((k - 0.5) / N) * TAU;
		cum[k] = cum[k - 1]! + Math.hypot(rx * Math.cos(t), ry * Math.sin(t)) * (TAU / N);
	}
	const total = cum[N]!;
	const at = (t: number) => {
		const turns = Math.floor(t / TAU);
		const f = ((t - turns * TAU) / TAU) * N;
		const k = Math.min(N - 1, Math.floor(f));
		return turns * total + cum[k]! + (cum[k + 1]! - cum[k]!) * (f - k);
	};
	const inverse = (s: number) => {
		const turns = Math.floor(s / total);
		const rest = s - turns * total;
		let lo = 0;
		let hi = N;
		while (hi - lo > 1) {
			const mid = (lo + hi) >> 1;
			if (cum[mid]! <= rest) lo = mid;
			else hi = mid;
		}
		const seg = cum[lo + 1]! - cum[lo]!;
		const f = seg > 0 ? (rest - cum[lo]!) / seg : 0;
		return turns * TAU + ((lo + f) / N) * TAU;
	};
	return { total, at, inverse };
}

export function ringRotation(demand: readonly number[], aspect = 1): number {
	const n = demand.length;
	if (n <= 1) return Math.PI / 2;
	const step = TAU / n;
	const canonical = Math.PI / n;
	const K = 72;
	const flatness = (t: number) => {
		const hx = aspect * Math.abs(Math.cos(t));
		return hx / Math.hypot(hx, Math.sin(t)) || 0;
	};
	let best = canonical;
	let bestScore = Infinity;
	for (let k = 0; k < K; k++) {
		const t0 = canonical + (k / K) * TAU;
		let flat = 0;
		let lean = 0;
		for (let i = 0; i < n; i++) {
			const t = t0 + i * step;
			flat += demand[i]! * flatness(t);
			lean += demand[i]! * Math.sin(t);
		}
		const score = flat + 0.6 * Math.abs(lean) + 1e-3 * Math.min(k, K - k);
		if (score < bestScore - 1e-9) {
			bestScore = score;
			best = t0;
		}
	}
	return norm(best);
}

export type OrbitSun = { x: number; y: number; r: number; ringInner: number; ringMax: number; ring: string };

export type CategoryLabel = {
	side: Side;
	anchor: "start" | "middle" | "end";
	x: number;
	nameY: number;
	size: number;
	chip: Box | null;
	box: Box;
};

export type OrbitCategory = {
	id: string;
	label: string;
	order: number;
	tone: 0 | 1;
	angle: number;
	x: number;
	y: number;
	r: number;
	slotR: number;
	count: number;
	value: number;
	share: number;
	sharePct: number;
	shareText: string;
	side: Side;
	sector: { start: number; end: number };
	labelPos: CategoryLabel | null;
	beam: {
		d: string;
		filament: string;
		track: string;
		arrow: string;
		width: number;
		from: Point;
		to: Point;
		length: number;
	};
	senderCount: number;
	particles: { count: number; dur: number };
};

export type SenderLabel = {
	chip: Box | null;
	name: { text: string; x: number; y: number; anchor: "start" | "end"; box: Box } | null;
};

export type OrbitSender = {
	id: string;
	rank: number;
	ring: number;
	category: string;
	person: boolean;
	angle: number;
	x: number;
	y: number;
	r: number;
	slotR: number;
	value: number;
	weight: number;
	side: Side;
	label: SenderLabel;
	link: string;
};

export type OrbitLayout = {
	width: number;
	height: number;
	cx: number;
	cy: number;
	scale: number;
	rings: { r1: { rx: number; ry: number }; r2: { rx: number; ry: number } };
	sun: OrbitSun;
	categories: OrbitCategory[];
	senders: OrbitSender[];
	week: WeekIndex | null;
	total: number;
};

export type OrbitInput = {
	senders: readonly OrbitNodeData[];
	groups: readonly OrbitGroup[];
};

export function normalizeSenders(senders: readonly OrbitNodeData[]): OrbitNodeData[] {
	const seen = new Set<string>();
	const out: OrbitNodeData[] = [];
	for (const s of senders) {
		const key = s.id.trim().toLowerCase();
		if (!key || seen.has(key)) continue;
		seen.add(key);
		out.push(s);
	}
	return out
		.map((s, i) => ({ s, i }))
		.sort((a, b) => senderValue(b.s, null) - senderValue(a.s, null) || a.i - b.i)
		.slice(0, MAX_SENDERS)
		.map(({ s }) => s);
}

export function layoutOrbit(
	sendersIn: readonly OrbitNodeData[],
	groupsIn: readonly OrbitGroup[],
	widthIn: number,
	heightIn: number,
	week: WeekIndex | null = null,
): OrbitLayout {
	const width = Math.max(120, Math.round(widthIn));
	const height = Math.max(120, Math.round(heightIn));
	const senders = normalizeSenders(sendersIn);
	const aggs = aggregateCategories(senders, groupsIn);
	const ringGroups = resolveGroups(senders, groupsIn);
	const ringIds = new Set(ringGroups.map((g) => g.id));
	const fallbackGroup = ringGroups.at(-1)?.id ?? "";

	const S = Math.min(width, height);
	const cx = width / 2;
	const cy = height / 2;
	const pad = 8;

	const sunR = clamp(S * 0.06, 14, 27);
	const ringInner = sunR + clamp(S * 0.012, 4, 6);
	const ringMax = clamp(S * 0.03, 6, 13);
	const catRMax = clamp(S * 0.04, 9, 18);
	const catRMin = clamp(S * 0.017, 5, 8);
	const sRMax = clamp(S * 0.031, 7, 14);
	const sRMin = clamp(S * 0.009, 3, 4.5);
	const wobble = clamp(S * 0.04, 8, 19);
	const labelRoom = width >= 640 ? clamp(width * 0.11, 104, 160) : 0;

	const r2y = Math.max(40, Math.min(S * 0.42, height / 2 - pad - sRMax - wobble - 2));
	const r2xMax = width / 2 - pad - sRMax - wobble - 2;
	const r2x = Math.max(40, Math.min(clamp(width / 2 - pad - sRMax - wobble - labelRoom, r2y, r2y * 2.15), r2xMax));
	const r1x = r2x * (0.27 / 0.42);
	const r1y = r2y * (0.27 / 0.42);

	const n = aggs.length;
	const step = n ? TAU / n : TAU;
	const demand = aggs.map((c) => c.senderCount + 0.35);
	const theta0 = ringRotation(demand, r2x / r2y);
	const catValues = aggs.map((c) => (week === null ? c.count : c.weeks[week]));
	const catAllMax = Math.max(1, ...aggs.map((c) => c.count));
	const catWeekMax = Math.max(1, ...aggs.flatMap((c) => c.weeks));
	const catRadius = (v: number, max: number) => (v > 0 ? Math.max(catRMin, catRMax * Math.sqrt(v / max)) : catRMin * 0.8);
	const percents = sharePercents(catValues);
	const modeTotal = catValues.reduce((a, b) => a + b, 0);
	const modeMaxCat = Math.max(...catValues, 0);

	const left = new Array<number>(n).fill(step / 2);
	const right = new Array<number>(n).fill(step / 2);
	if (n > 1) {
		for (let i = 0; i < n; i++) {
			const j = (i + 1) % n;
			right[i] = (step * demand[i]!) / (demand[i]! + demand[j]!);
			left[j] = step - right[i]!;
		}
	} else if (n === 1) {
		left[0] = Math.PI;
		right[0] = Math.PI;
	}

	const catGeo = aggs.map((c, i) => {
		const angle = norm(theta0 + i * step);
		const p = onEllipse(cx, cy, r1x, r1y, angle);
		const slotR = Math.max(catRadius(c.count, catAllMax), ...c.weeks.map((w) => catRadius(w, catWeekMax)));
		return { angle, ...p, slotR };
	});

	const arc = arcTable(r2x, r2y);
	const spacing = clamp(S * 0.14, 26, 70);
	type Slot = { s: OrbitNodeData; rank: number; cat: number; angle: number };
	const slots: Slot[] = [];
	const rankOf = new Map(senders.map((s, i) => [s, i]));
	aggs.forEach((c, ci) => {
		const members = senders.filter((s) => groupOf(s, ringIds, fallbackGroup) === c.id);
		const k = members.length;
		if (!k) return;
		const theta = catGeo[ci]!.angle;
		const la = arc.at(theta - left[ci]!);
		const lb = arc.at(theta + right[ci]!);
		const sp = Math.min(spacing, (lb - la) / k);
		const axis = arc.at(theta);
		const half = ((k - 1) * sp) / 2;
		const lc = clamp(axis, la + sp / 2 + half, lb - sp / 2 - half);
		const positions = Array.from({ length: k }, (_, j) => lc - half + j * sp);
		const order = positions
			.map((pos, j) => ({ pos, j, d: Math.abs(pos - axis) }))
			.sort((x, y) => x.d - y.d || x.j - y.j);
		members.forEach((s, m) => {
			slots.push({ s, rank: rankOf.get(s)!, cat: ci, angle: norm(arc.inverse(order[m]!.pos)) });
		});
	});

	const ringOrder = [...slots].sort((a, b) => a.angle - b.angle || a.rank - b.rank);
	const ringIndex = new Map(ringOrder.map((sl, i) => [sl, i]));

	const baseline = LABEL_H + 5;
	const nudged = new Map<Slot, Point>();
	const settled: { x: number; y: number; side: Side }[] = [];
	for (const sl of ringOrder) {
		const t = sl.angle;
		const base = onEllipse(cx, cy, r2x, r2y, t);
		const side: Side = base.x >= cx - 0.5 ? "right" : "left";
		const c = Math.cos(t);
		const near = settled.filter((p) => p.side === side && Math.abs(p.x - base.x) < 150).map((p) => base.y - p.y);
		let off = 0;
		if (near.some((dy) => Math.abs(dy) < baseline) && Math.abs(c) > 0.08) {
			const clears = (o: number) => Math.min(...near.map((dy) => Math.abs(dy - o * c)));
			const candidates = [0, -wobble, wobble, ...near.flatMap((dy) => [(dy - baseline) / c, (dy + baseline) / c])]
				.filter((o) => Math.abs(o) <= wobble + 1e-9)
				.sort((a, b) => Math.abs(a) - Math.abs(b) || b - a);
			const ok = candidates.find((o) => clears(o) >= baseline - 1e-6);
			off = ok ?? candidates.reduce((best, o) => (clears(o) > clears(best) + 1e-9 ? o : best), 0);
		}
		const p = onEllipse(cx, cy, r2x + off, r2y + off, t);
		nudged.set(sl, p);
		settled.push({ ...p, side });
	}
	const allMax = Math.max(1, ...senders.map((s) => senderValue(s, null)));
	const weekMax = Math.max(1, ...senders.flatMap((s) => WEEKS.map((w) => senderValue(s, w))));
	const radius = (v: number, max: number) => (v > 0 ? Math.max(sRMin, sRMax * Math.sqrt(v / max)) : sRMin * 0.75);

	type Node = {
		slot: Slot;
		ring: number;
		x: number;
		y: number;
		rAll: number;
		rWeeks: number[];
		slotR: number;
	};
	const nodes: Node[] = slots.map((slot) => {
		const ring = ringIndex.get(slot)!;
		const p = nudged.get(slot)!;
		const rAll = radius(senderValue(slot.s, null), allMax);
		const rWeeks = WEEKS.map((w) => radius(senderValue(slot.s, w), weekMax));
		const slotR = Math.max(rAll, ...rWeeks);
		return {
			slot,
			ring,
			x: clamp(p.x, pad + slotR, width - pad - slotR),
			y: clamp(p.y, pad + slotR, height - pad - slotR),
			rAll,
			rWeeks,
			slotR,
		};
	});

	const minGap = 3;
	const scaleNode = (nd: Node, f: number) => {
		nd.rAll *= f;
		nd.rWeeks = nd.rWeeks.map((r) => r * f);
		nd.slotR *= f;
	};
	for (let pass = 0; pass < 6; pass++) {
		let changed = false;
		for (let i = 0; i < nodes.length; i++) {
			for (let j = i + 1; j < nodes.length; j++) {
				const a = nodes[i]!;
				const b = nodes[j]!;
				const d = Math.hypot(a.x - b.x, a.y - b.y);
				if (d < a.slotR + b.slotR + minGap) {
					const f = Math.max(0.05, (d - minGap) / (a.slotR + b.slotR));
					scaleNode(a, f);
					scaleNode(b, f);
					changed = true;
				}
			}
			const a = nodes[i]!;
			for (const c of catGeo) {
				const d = Math.hypot(a.x - c.x, a.y - c.y);
				if (d < a.slotR + c.slotR + minGap) {
					scaleNode(a, Math.max(0.05, (d - minGap - c.slotR) / a.slotR));
					changed = true;
				}
			}
		}
		if (!changed) break;
	}

	const sunRingOuter = ringInner + ringMax;
	const modeMaxSenderValue = Math.max(0, ...senders.map((s) => senderValue(s, week)));
	const wMax = clamp(S * 0.017, 3.5, 8);
	const beamGeo = catGeo.map((c, i) => {
		const dx = c.x - cx;
		const dy = c.y - cy;
		const len = Math.hypot(dx, dy) || 1;
		const ux = dx / len;
		const uy = dy / len;
		const from = { x: cx + ux * (sunR + 2), y: cy + uy * (sunR + 2) };
		const to = { x: c.x - ux * (c.slotR + 3), y: c.y - uy * (c.slotR + 3) };
		const mid = { x: (from.x + to.x) / 2, y: (from.y + to.y) / 2 };
		const bl = Math.hypot(to.x - from.x, to.y - from.y);
		const ctrl = { x: mid.x - uy * bl * 0.13, y: mid.y + ux * bl * 0.13 };
		const ctrl2 = { x: mid.x - uy * bl * 0.3, y: mid.y + ux * bl * 0.3 };
		const value = catValues[i]!;
		const width = r2(1.25 + (wMax - 1.25) * (modeMaxCat > 0 ? value / modeMaxCat : 0));
		let tipT = 0;
		let tip = from;
		while (tipT < 0.5 && Math.hypot(tip.x - cx, tip.y - cy) < sunRingOuter + 5) {
			tipT += 0.01;
			tip = quad(from, ctrl, to, tipT);
		}
		const inbound = {
			x: -(2 * (1 - tipT) * (ctrl.x - from.x) + 2 * tipT * (to.x - ctrl.x)),
			y: -(2 * (1 - tipT) * (ctrl.y - from.y) + 2 * tipT * (to.y - ctrl.y)),
		};
		return {
			d: quadPath(from, ctrl, to),
			filament: quadPath(from, ctrl2, to),
			track: quadTrack(from, ctrl, to),
			arrow: chevron(tip, inbound, 3.5 + width),
			width,
			from,
			ctrl,
			to,
			length: quadLength(from, ctrl, to),
		};
	});

	const sunObstacle = { c: { x: cx, y: cy }, r: sunRingOuter + 4 };
	const catCircles = catGeo.map((c) => ({ c: { x: c.x, y: c.y }, r: c.slotR + 4 }));
	const senderCircles = nodes.map((nd) => ({ c: { x: nd.x, y: nd.y }, r: nd.slotR + 2 }));
	const beamSegments = beamGeo.flatMap((b) => {
		const segs: { p: Point; q: Point; hw: number }[] = [];
		let prev = b.from;
		for (let i = 1; i <= 10; i++) {
			const p = quad(b.from, b.ctrl, b.to, i / 10);
			segs.push({ p: prev, q: p, hw: wMax / 2 + 2 });
			prev = p;
		}
		return segs;
	});

	const placed: Box[] = [];
	const catFont = S < 420 ? 12.5 : CATEGORY_NAME_SIZE;
	const catLabels: (CategoryLabel | null)[] = new Array(catGeo.length).fill(null);
	const catPriority = catGeo.map((_, i) => i).sort((a, b) => aggs[b]!.count - aggs[a]!.count || a - b);
	for (const i of catPriority) {
		const c = catGeo[i]!;
		const name = aggs[i]!.label;
		const nameW = textWidth(name, catFont);
		const nameH = Math.round(catFont + 3);
		const chipW = chipWidth(4);
		const side: Side = c.x >= cx - 0.5 ? "right" : "left";
		const out = side === "right" ? 1 : -1;
		const gap = c.slotR + 8;
		const diag = c.slotR * 0.7 + 4;
		const variants = [
			{ withChip: true, w: Math.max(nameW, chipW), h: nameH + 3 + 16 },
			{ withChip: false, w: nameW, h: nameH },
		];
		const hard = (b: Box) =>
			!boxInside(b, width, height, 2) ||
			boxHitsCircle(b, sunObstacle.c, sunObstacle.r) ||
			catCircles.some((o, k) => k !== i && boxHitsCircle(b, o.c, o.r)) ||
			placed.some((p) => boxesHit(p, b, 4));
		const soft = (b: Box) =>
			senderCircles.filter((o) => boxHitsCircle(b, o.c, o.r)).length +
			(beamSegments.some((sg) => segHitsBox(sg.p, sg.q, b, sg.hw)) ? 1 : 0);
		type Cand = { box: Box; anchor: CategoryLabel["anchor"]; x: number };
		const beside = (dir: number, w: number, h: number, dy = 0): Cand => ({
			box: { x: dir > 0 ? c.x + gap : c.x - gap - w, y: c.y - h / 2 + dy, w, h },
			anchor: dir > 0 ? "start" : "end",
			x: c.x + dir * gap,
		});
		const corner = (dir: number, up: boolean, w: number, h: number): Cand => ({
			box: { x: dir > 0 ? c.x + diag : c.x - diag - w, y: up ? c.y - diag - h : c.y + diag, w, h },
			anchor: dir > 0 ? "start" : "end",
			x: c.x + dir * diag,
		});
		let chosen: (Cand & { withChip: boolean }) | null = null;
		for (const v of variants) {
			const { w, h } = v;
			const candidates: Cand[] = [
				beside(out, w, h),
				{ box: { x: c.x - w / 2, y: c.y - c.slotR - 6 - h, w, h }, anchor: "middle", x: c.x },
				{ box: { x: c.x - w / 2, y: c.y + c.slotR + 6, w, h }, anchor: "middle", x: c.x },
				corner(out, true, w, h),
				corner(out, false, w, h),
				beside(-out, w, h),
				corner(-out, true, w, h),
				corner(-out, false, w, h),
			];
			let bestSoft = Infinity;
			for (const cand of candidates) {
				if (hard(cand.box)) continue;
				const sc = soft(cand.box);
				if (sc < bestSoft) {
					bestSoft = sc;
					chosen = { ...cand, withChip: v.withChip };
				}
				if (sc === 0) break;
			}
			if (chosen) break;
		}
		if (!chosen) continue;
		const box = chosen.box;
		placed.push(box);
		const chipX = chosen.anchor === "start" ? box.x : chosen.anchor === "end" ? box.x + box.w - chipW : chosen.x - chipW / 2;
		catLabels[i] = {
			side,
			anchor: chosen.anchor,
			x: chosen.anchor === "start" ? box.x : chosen.anchor === "end" ? box.x + box.w : chosen.x,
			nameY: box.y + nameH / 2,
			size: catFont,
			chip: chosen.withChip ? { x: chipX, y: box.y + nameH + 3, w: chipW, h: 16 } : null,
			box,
		};
	}

	const catBoxes = [...placed];
	const unitBoxes: Box[] = [];
	const byRank = [...nodes].sort((a, b) => a.slot.rank - b.slot.rank);
	const labels = new Map<Node, SenderLabel>();
	for (const nd of byRank) {
		const s = nd.slot.s;
		const side: Side = nd.x >= cx - 0.5 ? "right" : "left";
		const out = side === "right" ? 1 : -1;
		const digits = String(Math.round(Math.max(senderValue(s, null), ...WEEKS.map((w) => senderValue(s, w))))).length;
		const cw = chipWidth(digits);
		const text = shortLabel(displayNameOf(s));
		const nw = textWidth(text, SENDER_NAME_SIZE);
		const others = senderCircles.filter((_, k) => nodes[k] !== nd);
		const clear = (b: Box) =>
			boxInside(b, width, height, 2) &&
			!boxHitsCircle(b, sunObstacle.c, sunObstacle.r) &&
			!catCircles.some((o) => boxHitsCircle(b, o.c, o.r)) &&
			!others.some((o) => boxHitsCircle(b, o.c, o.r)) &&
			!catBoxes.some((p) => boxesHit(p, b, 3)) &&
			!unitBoxes.some((p) => boxesHit(p, b, 3));

		const chipAt = (dy: number, inset: number): Box => {
			const x0 = out > 0 ? nd.x + inset : nd.x - inset - cw;
			return { x: x0, y: nd.y + dy - CHIP_H / 2, w: cw, h: CHIP_H };
		};
		const nameAfter = (chip: Box): Box => {
			const x0 = out > 0 ? chip.x + chip.w + 5 : chip.x - 5 - nw;
			return { x: x0, y: chip.y + (CHIP_H - LABEL_H) / 2, w: nw, h: LABEL_H };
		};
		const lift = nd.slotR * 0.8 + CHIP_H / 2 + 1;
		const chipCandidates = [
			chipAt(0, nd.slotR + 4),
			chipAt(-lift, nd.slotR * 0.45),
			chipAt(lift, nd.slotR * 0.45),
		];

		let label: SenderLabel = { chip: null, name: null };
		for (const chip of chipCandidates) {
			const name = nameAfter(chip);
			if (clear(chip) && clear(name) && !boxesHit(chip, name)) {
				label = {
					chip,
					name: {
						text,
						x: out > 0 ? name.x : name.x + name.w,
						y: name.y + LABEL_H / 2,
						anchor: out > 0 ? "start" : "end",
						box: name,
					},
				};
				break;
			}
		}
		if (!label.chip) {
			const chip = chipCandidates.find(clear);
			if (chip) label = { chip, name: null };
		}
		if (label.chip) unitBoxes.push(label.chip);
		if (label.name) unitBoxes.push(label.name.box);
		labels.set(nd, label);
	}

	const newest = Math.max(...aggs.map((c) => c.lastAt), -Infinity);
	const maxShare = Math.max(...catValues, 0);

	const categoriesOut: OrbitCategory[] = aggs.map((c, i) => {
		const g = catGeo[i]!;
		const value = catValues[i]!;
		const ageH = Number.isFinite(c.lastAt) && Number.isFinite(newest) ? (newest - c.lastAt) / HOUR : 96;
		const fresh = 1 - clamp(ageH / 96, 0, 1);
		const speed = lerp(38, 115, fresh);
		const b = beamGeo[i]!;
		return {
			id: c.id,
			label: c.label,
			order: i,
			tone: (i % 2) as 0 | 1,
			angle: g.angle,
			x: r2(g.x),
			y: r2(g.y),
			r: r2(week === null ? catRadius(c.count, catAllMax) : catRadius(value, catWeekMax)),
			slotR: r2(g.slotR),
			count: c.count,
			value,
			share: modeTotal > 0 ? value / modeTotal : 0,
			sharePct: percents[i]!,
			shareText: formatShare(percents[i]!, value),
			side: g.x >= cx - 0.5 ? "right" : "left",
			sector: { start: g.angle - left[i]!, end: g.angle + right[i]! },
			labelPos: catLabels[i] ?? null,
			beam: { d: b.d, filament: b.filament, track: b.track, arrow: b.arrow, width: b.width, from: b.from, to: b.to, length: r2(b.length) },
			senderCount: c.senderCount,
			particles: {
				count: value > 0 ? 1 + Math.round((2 * value) / (maxShare || 1)) : 0,
				dur: r2(clamp(b.length / speed, 1.2, 9)),
			},
		};
	});

	const sendersOut: OrbitSender[] = byRank.map((nd) => {
		const s = nd.slot.s;
		const value = senderValue(s, week);
		const cat = catGeo[nd.slot.cat]!;
		return {
			id: s.id,
			rank: nd.slot.rank,
			ring: nd.ring,
			category: aggs[nd.slot.cat]!.id,
			person: s.kind === "agent",
			angle: nd.slot.angle,
			x: r2(nd.x),
			y: r2(nd.y),
			r: r2(week === null ? nd.rAll : nd.rWeeks[week]!),
			slotR: r2(nd.slotR),
			value,
			weight: modeMaxSenderValue > 0 ? value / modeMaxSenderValue : 0,
			side: nd.x >= cx - 0.5 ? "right" : "left",
			label: labels.get(nd)!,
			link: `M${r2(cat.x)} ${r2(cat.y)}L${r2(nd.x)} ${r2(nd.y)}`,
		};
	});

	const sunTicks = activityTicks(combinedDaily(senders), cx, cy, ringInner, ringMax);

	return {
		width,
		height,
		cx,
		cy,
		scale: S,
		rings: { r1: { rx: r2(r1x), ry: r2(r1y) }, r2: { rx: r2(r2x), ry: r2(r2y) } },
		sun: { x: cx, y: cy, r: r2(sunR), ringInner: r2(ringInner), ringMax: r2(ringMax), ring: ticksPath(sunTicks) },
		categories: categoriesOut,
		senders: sendersOut,
		week,
		total: modeTotal,
	};
}

function displayNameOf(s: OrbitNodeData): string {
	return s.name?.trim() || s.id;
}

export function inSector(t: number, sector: { start: number; end: number }): boolean {
	const span = sector.end - sector.start;
	if (span >= TAU - 1e-9) return true;
	const rel = norm(t - sector.start);
	return rel <= span + 1e-9;
}

export type FocusCardId = "rows" | "flagged" | "timing" | "recency" | "extra";
export type FocusCard = Box & { id: FocusCardId; cy: number };

export type FocusLayout = {
	compact: boolean;
	width: number;
	height: number;
	orb: { x: number; y: number; r: number };
	ring: { inner: number; maxLen: number; outer: number };
	cards: FocusCard[];
	curves: string[];
	detail: Box;
};

export const FOCUS_MIN_WIDTH = 720;
export const CARD_H = 60;
const CARD_GAP = 10;

export function layoutFocus(widthIn: number, heightIn: number, cardIds: readonly FocusCardId[]): FocusLayout {
	const width = Math.max(120, Math.round(widthIn));
	const height = Math.max(120, Math.round(heightIn));
	const S = Math.min(width, height);
	const r = clamp(S * 0.066, 22, 32);
	const inner = r + 9;
	const maxLen = clamp(S * 0.05, 16, 24);
	const outer = inner + maxLen;

	if (width < FOCUS_MIN_WIDTH) {
		const size = 2 * (outer + 10);
		return {
			compact: true,
			width,
			height: size,
			orb: { x: size / 2, y: size / 2, r },
			ring: { inner, maxLen, outer },
			cards: [],
			curves: [],
			detail: { x: 0, y: 0, w: width, h: 0 },
		};
	}

	const margin = 20;
	let orbX = clamp(width * 0.14, outer + 44, 176);
	let gap1 = clamp(width * 0.085, 52, 128);
	const cardW = clamp(width * 0.17, 176, 216);
	let gap2 = clamp(width * 0.06, 44, 100);
	const detailMax = 460;
	const used = orbX + outer + gap1 + cardW + gap2;
	const detailW = clamp(width - used - margin, 240, detailMax);
	const free = width - margin - (used + detailW);
	if (free > 0) {
		orbX += free * 0.2;
		gap1 += free * 0.35;
		gap2 += free * 0.25;
	}
	const orbY = height / 2;
	const cardsX = orbX + outer + gap1;
	const total = cardIds.length * CARD_H + Math.max(0, cardIds.length - 1) * CARD_GAP;
	const top = orbY - total / 2;
	const cards: FocusCard[] = cardIds.map((id, i) => {
		const y = top + i * (CARD_H + CARD_GAP);
		return { id, x: r2(cardsX), y: r2(y), w: r2(cardW), h: CARD_H, cy: r2(y + CARD_H / 2) };
	});
	const from = { x: orbX + outer + 6, y: orbY };
	const curves = cards.map((c) => fanCurve(from, { x: c.x - 2, y: c.cy }));
	const detailX = cardsX + cardW + gap2;
	return {
		compact: false,
		width,
		height,
		orb: { x: r2(orbX), y: r2(orbY), r },
		ring: { inner, maxLen, outer },
		cards,
		curves,
		detail: { x: r2(detailX), y: 12, w: r2(Math.min(detailW, width - detailX - 12)), h: height - 24 },
	};
}

export const ROW_H = 54;
export const ROW_GAP = 8;
export const ROWS_HEADER = 30;

export function stackRows(detail: Box, count: number): { top: number; centers: number[] } {
	const total = ROWS_HEADER + count * ROW_H + Math.max(0, count - 1) * ROW_GAP;
	const top = clamp(detail.y + (detail.h - total) / 2, detail.y, Math.max(detail.y, detail.y + detail.h - total));
	const first = top + ROWS_HEADER;
	return { top: r2(top), centers: Array.from({ length: count }, (_, i) => r2(first + i * (ROW_H + ROW_GAP) + ROW_H / 2)) };
}

export function arcOffsets(centers: readonly number[], originY: number, radius: number): number[] {
	if (centers.length < 2) return centers.map(() => 0);
	const offs = centers.map((y) => {
		const dy = Math.min(Math.abs(y - originY), radius);
		return radius - Math.sqrt(radius * radius - dy * dy);
	});
	const max = Math.max(...offs);
	return offs.map((o) => r2(max - o));
}

export function panelTop(detail: Box, anchorY: number, estimatedH: number): number {
	return r2(clamp(anchorY - 28, detail.y, Math.max(detail.y, detail.y + detail.h - estimatedH)));
}
```

### 7. `components/registry/visualizer/vocab.tsx` — supporting file, required

```tsx
import type * as React from "react";
import { ArrowUpRight, Clock3, Gauge, ListChecks, ShieldAlert, Timer, type LucideIcon } from "lucide-react";
import { cn } from "@/lib/utils";
import { formatAge, formatAgo, formatAgoLong, formatCount, formatMs, formatStamp, plural, READOUT } from "./format";
import type { FocusCardId } from "./layout";
import type { OrbitNodeData, OrbitRun, OrbitRunStatus } from "./types";

export type FocusCardSpec = { id: FocusCardId; icon: LucideIcon; value: string; label: string; spoken: string };

export type OrbitFocus = {
	cards: (s: OrbitNodeData, now: number | null) => FocusCardSpec[];
	rows: (s: OrbitNodeData, now: number | null) => { key: string; node: React.ReactNode }[];
	rowsTitle: (s: OrbitNodeData) => string;
	rowsNote: (s: OrbitNodeData) => string | null;
	emptyRows: string;
	panel: (s: OrbitNodeData, id: FocusCardId, now: number | null) => React.ReactNode;
	panelHeight: Partial<Record<FocusCardId, number>>;
	chip: (s: OrbitNodeData, group: string) => string;
	ringCaption: string;
};

export type OrbitVocab = {
	sun: string;
	unit: readonly [one: string, many: string];
	node: readonly [one: string, many: string];
	group: readonly [one: string, many: string];
	mass: string;
	flag: { label: string; chip: string; clear: string };
	period: {
		all: { label: string; spoken: string };
		weeks: readonly (readonly [label: string, spoken: string])[];
	} | null;
	window: { all: string; week: (index: number) => string };
	legend: { person: string; machine: string; ring: string; hint: string };
	srHint: string;
	sceneLabel: string;
	empty: { title: string; body: string };
	recency: (s: OrbitNodeData, now: number) => string;
	recencyLong: (s: OrbitNodeData, now: number) => string;
	ago: (s: OrbitNodeData, now: number) => string;
	describe: (s: OrbitNodeData, now: number | null) => string;
	focus: OrbitFocus;
	expand?: { label: (s: OrbitNodeData) => string; render: (s: OrbitNodeData) => React.ReactNode };
};

export const capitalize = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);

const HOUR = 3_600_000;

const STATUS: Record<OrbitRunStatus, { label: string; color: string }> = {
	ok: { label: "Done", color: "var(--co-agent)" },
	running: { label: "Running", color: "var(--co-filament)" },
	blocked: { label: "Blocked", color: "var(--co-accent)" },
	failed: { label: "Failed", color: "#f87171" },
};

function successRate(s: OrbitNodeData): number | null {
	const done = s.recent.filter((r) => r.status !== "running");
	if (!done.length) return null;
	return Math.round((100 * done.filter((r) => r.status === "ok").length) / done.length);
}

function agentCards(s: OrbitNodeData, now: number | null): FocusCardSpec[] {
	const median = formatMs(s.medianMs);
	const ago = now === null ? "—" : formatAgo(s.lastAt, now);
	const cards: FocusCardSpec[] = [
		{ id: "rows", icon: ListChecks, value: formatCount(s.count), label: "Tasks", spoken: plural(s.count, "task") },
		{ id: "flagged", icon: ShieldAlert, value: formatCount(s.flagged), label: "Blocked", spoken: `${formatCount(s.flagged)} blocked` },
		{ id: "timing", icon: Timer, value: median, label: "Median run", spoken: median === "—" ? "median run time unknown" : `median run ${median}` },
		{ id: "recency", icon: Clock3, value: ago, label: "Last run", spoken: `last run ${ago}` },
	];
	const rate = successRate(s);
	if (rate !== null) cards.push({ id: "extra", icon: Gauge, value: `${rate}%`, label: "Success rate", spoken: `${rate} percent of runs succeed` });
	return cards;
}

function RunRow({ run, now }: { run: OrbitRun; now: number | null }) {
	const age = now === null ? null : Math.max(0, (now - Date.parse(run.at)) / HOUR);
	const tone = STATUS[run.status];
	const body = (
		<>
			<span className="size-2 shrink-0 rounded-full" style={{ background: tone.color }} />
			<span className="min-w-0 flex-1">
				<span className="block truncate text-[13.5px] leading-tight text-ink">{run.title}</span>
				<span className="mt-0.5 block truncate text-[11.5px] text-ink-dim">
					{tone.label} · {formatStamp(run.at)}
					{run.durationMs !== null && ` · ${formatMs(run.durationMs)}`}
				</span>
			</span>
			<span className="shrink-0 font-mono text-[11px] text-ink-dim tabular-nums">{age === null ? "" : formatAge(age)}</span>
		</>
	);
	const shell = "group flex h-full items-center gap-3 rounded-[14px] bg-raised px-3.5 ring-1 ring-hairline";
	if (!run.href) return <div className={shell}>{body}</div>;
	return (
		<a
			href={run.href}
			className={cn(
				shell,
				"transition-shadow duration-200 hover:ring-(--co-accent)/40 focus-visible:ring-2 focus-visible:ring-(--co-filament)/60 focus-visible:outline-none",
			)}
		>
			{body}
			<ArrowUpRight className="size-3.5 shrink-0 text-ink-mute transition-transform duration-200 group-hover:translate-x-0.5 group-hover:-translate-y-0.5 group-hover:text-ink" />
		</a>
	);
}

function WeeklyBars({ weekly, title }: { weekly: number[]; title: string }) {
	const weeks = [0, 1, 2, 3].map((i) => weekly[i] ?? 0);
	const max = Math.max(1, ...weeks);
	return (
		<div className="mt-4">
			<p className={READOUT}>{title}</p>
			<ul className="mt-2 grid grid-cols-4 items-end gap-2" style={{ height: 64 }}>
				{weeks.map((v, i) => (
					<li key={i} className="flex h-full flex-col items-center justify-end gap-1">
						<span className="font-mono text-[10.5px] text-ink-dim tabular-nums">{v}</span>
						<span
							className={cn("w-full rounded-[4px]", i === 3 ? "bg-(--co-accent)" : "bg-ink/15")}
							style={{ height: `${Math.max(3, (v / max) * 36)}px` }}
						/>
						<span className="font-mono text-[10px] text-ink-mute">W{i + 1}</span>
					</li>
				))}
			</ul>
		</div>
	);
}

function Big({ children }: { children: React.ReactNode }) {
	return <p className="mt-2 text-[34px] leading-none text-ink tabular-nums">{children}</p>;
}

function AgentPanel({ s, id, now }: { s: OrbitNodeData; id: FocusCardId; now: number | null }) {
	if (id === "flagged") {
		const stuck = s.recent.filter((r) => r.status === "blocked" || r.status === "failed").slice(0, 3);
		return (
			<>
				<p className={READOUT}>Blocked</p>
				<Big>{formatCount(s.flagged)}</Big>
				{stuck.length === 0 ? (
					<p className="mt-2 text-[13px] text-ink-dim">Nothing is waiting on a human.</p>
				) : (
					<ul className="mt-3 flex flex-col gap-2">
						{stuck.map((r) => (
							<li key={r.id} className="flex min-w-0 items-center gap-2 text-[12.5px]">
								<span className="size-1.5 shrink-0 rounded-full" style={{ background: STATUS[r.status].color }} />
								<span className="truncate text-ink">{r.title}</span>
							</li>
						))}
					</ul>
				)}
			</>
		);
	}
	if (id === "timing") {
		const slowest = [...s.recent].filter((r) => r.durationMs !== null).sort((a, b) => b.durationMs! - a.durationMs!)[0];
		return (
			<>
				<p className={READOUT}>Median run</p>
				<Big>{formatMs(s.medianMs)}</Big>
				{slowest && (
					<p className="mt-2 truncate text-[13px] text-ink-dim">
						Slowest recent: {slowest.title} · {formatMs(slowest.durationMs)}
					</p>
				)}
				<WeeklyBars weekly={s.weekly} title="Tasks per week" />
			</>
		);
	}
	if (id === "extra") {
		const counts = (["ok", "failed", "blocked"] as const).map((k) => ({ k, n: s.recent.filter((r) => r.status === k).length }));
		const done = counts.reduce((a, c) => a + c.n, 0) || 1;
		return (
			<>
				<p className={READOUT}>Success rate</p>
				<Big>{successRate(s) ?? "—"}%</Big>
				<div className="mt-4 flex h-1.5 overflow-hidden rounded-full bg-ink/10">
					{counts.map(({ k, n }) => (
						<span key={k} className="h-full" style={{ width: `${(100 * n) / done}%`, background: STATUS[k].color }} />
					))}
				</div>
				<p className="mt-2 text-[13px] text-ink-dim">
					{counts.map(({ k, n }) => `${n} ${STATUS[k].label.toLowerCase()}`).join(" · ")} · last {plural(s.recent.length, "run")}
				</p>
			</>
		);
	}
	return (
		<>
			<p className={READOUT}>Last run</p>
			<p className="mt-2 text-[28px] leading-none text-ink">{now === null ? "—" : formatAgo(s.lastAt, now)}</p>
			<p className="mt-1.5 text-[13px] text-ink-dim">{formatStamp(s.lastAt)}</p>
			<WeeklyBars weekly={s.weekly} title="Per week" />
		</>
	);
}

export const AGENT_FOCUS: OrbitFocus = {
	cards: agentCards,
	rows: (s, now) => s.recent.slice(0, 5).map((run) => ({ key: run.id, node: <RunRow run={run} now={now} /> })),
	rowsTitle: () => "Latest runs",
	rowsNote: (s) => (s.flagged > 0 ? `${formatCount(s.flagged)} blocked` : null),
	emptyRows: "No runs in this window.",
	panel: (s, id, now) => <AgentPanel s={s} id={id} now={now} />,
	panelHeight: { flagged: 220, timing: 236, recency: 244, extra: 190 },
	chip: (s, group) => `${group} · ${s.kind === "agent" ? "Agent" : "Tool"}`,
	ringCaption: "30 days · 1 tick = 1 day",
};

export const AGENT_VOCAB: OrbitVocab = {
	sun: "Orchestrator",
	unit: ["task", "tasks"],
	node: ["worker", "workers"],
	group: ["pool", "pools"],
	mass: "the work",
	flag: { label: "blocked", chip: "blocked", clear: "All clear" },
	period: {
		all: { label: "All", spoken: "All 30 days" },
		weeks: [
			["W1", "Week 1, the oldest"],
			["W2", "Week 2"],
			["W3", "Week 3"],
			["W4", "Week 4, the most recent"],
		],
	},
	window: { all: "30 days", week: (i) => `week ${i + 1}` },
	legend: { person: "Agents", machine: "Tools", ring: "Ring around the orchestrator: tasks per day, 30 days", hint: "Select an agent or tool to focus" },
	srHint: "Arrow keys move between agents and tools. Enter opens one. Escape returns.",
	sceneLabel: "Agents and tools in orbit around the orchestrator",
	empty: {
		title: "Nothing in orbit yet",
		body: "Once agents start taking work, the busiest agents and tools will circle here, grouped by pool.",
	},
	recency: (s, now) => `Last run ${formatAgo(s.lastAt, now)}`,
	recencyLong: (s, now) => `last run ${formatAgoLong(s.lastAt, now)}`,
	ago: (s, now) => formatAgo(s.lastAt, now),
	describe: (s, now) =>
		agentCards(s, now)
			.map((c) => c.spoken)
			.join(", "),
	focus: AGENT_FOCUS,
};
```

### 8. `components/registry/visualizer/format.ts` — supporting file, required

```tsx
import type { OrbitNodeData } from "./types";

const MINUTE = 60_000;
const HOUR = 3_600_000;
const DAY = 86_400_000;

const NUMBER = new Intl.NumberFormat("en-US");

export function formatCount(n: number): string {
	return NUMBER.format(Math.round(n));
}

export function formatAge(hours: number): string {
	if (!Number.isFinite(hours) || hours < 0) return "—";
	if (hours < 1) return `${Math.max(1, Math.round(hours * 60))}m`;
	if (hours < 24) return `${Math.round(hours)}h`;
	const days = hours / 24;
	if (days < 14) return `${Math.round(days)}d`;
	return `${Math.round(days / 7)}w`;
}

export function formatAgo(iso: string, now: number): string {
	const t = Date.parse(iso);
	if (Number.isNaN(t)) return "—";
	const diff = Math.max(0, now - t);
	if (diff < MINUTE) return "just now";
	return `${formatAge(diff / HOUR)} ago`;
}

export function formatAgoLong(iso: string, now: number): string {
	const t = Date.parse(iso);
	if (Number.isNaN(t)) return "unknown";
	const diff = Math.max(0, now - t);
	const plural = (n: number, unit: string) => `${n} ${unit}${n === 1 ? "" : "s"} ago`;
	if (diff < MINUTE) return "just now";
	if (diff < HOUR) return plural(Math.round(diff / MINUTE), "minute");
	if (diff < DAY) return plural(Math.round(diff / HOUR), "hour");
	if (diff < 14 * DAY) return plural(Math.round(diff / DAY), "day");
	return plural(Math.round(diff / (7 * DAY)), "week");
}

export function formatStamp(iso: string): string {
	const d = new Date(iso);
	if (Number.isNaN(d.getTime())) return "—";
	const day = d.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" });
	const h = d.getHours();
	const h12 = h % 12 === 0 ? 12 : h % 12;
	return `${day} · ${h12}:${String(d.getMinutes()).padStart(2, "0")} ${h < 12 ? "am" : "pm"}`;
}

export function displayName(node: Pick<OrbitNodeData, "name" | "id">): string {
	return node.name?.trim() || node.id;
}

export function formatMs(ms: number | null | undefined): string {
	if (ms === null || ms === undefined || !Number.isFinite(ms) || ms < 0) return "—";
	if (ms < 1000) return `${Math.round(ms)}ms`;
	if (ms < 60_000) return `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)}s`;
	const m = Math.floor(ms / 60_000);
	const sec = Math.round((ms % 60_000) / 1000);
	return sec ? `${m}m ${sec}s` : `${m}m`;
}

export function plural(n: number, one: string, many = `${one}s`): string {
	return `${formatCount(n)} ${n === 1 ? one : many}`;
}

export const READOUT = "font-mono text-[11px] uppercase tracking-[0.06em] text-ink-mute";
```

### 9. `components/registry/visualizer/hooks.ts` — supporting file, required

```tsx
"use client";

import * as React from "react";
import { useAnimationLoop } from "@/hooks/use-animation-loop";

export function useContainerWidth(ref: React.RefObject<HTMLElement | null>): number {
	const [width, setWidth] = React.useState(0);
	useAnimationLoop({
		target: ref,
		halted: true,
		paintWhenHalted: false,
		onResize: (m) => {
			const next = Math.round(m.width / (ref.current?.currentCSSZoom || 1));
			setWidth((prev) => (prev === next ? prev : next));
		},
	});
	return width;
}

export type Visibility = {
	inView: boolean;
	seen: boolean;
	known: boolean;
};

export function useInView(ref: React.RefObject<Element | null>): Visibility {
	const [state, setState] = React.useState<Visibility>({ inView: true, seen: false, known: false });
	React.useEffect(() => {
		const el = ref.current;
		if (!el || typeof IntersectionObserver === "undefined") return;
		const io = new IntersectionObserver(
			([entry]) => {
				const inView = entry?.isIntersecting ?? true;
				setState((prev) => ({ inView, seen: prev.seen || inView, known: true }));
			},
			{ rootMargin: "40px" },
		);
		io.observe(el);
		return () => io.disconnect();
	}, [ref]);
	return state;
}

function subscribeVisibility(onChange: () => void) {
	document.addEventListener("visibilitychange", onChange);
	return () => document.removeEventListener("visibilitychange", onChange);
}

export function usePageVisible(): boolean {
	return React.useSyncExternalStore(
		subscribeVisibility,
		() => !document.hidden,
		() => true,
	);
}

function subscribeMinute(onChange: () => void) {
	const id = window.setInterval(onChange, 30_000);
	return () => window.clearInterval(id);
}

const minuteStamp = () => Math.floor(Date.now() / 60_000) * 60_000;

export function useNow(): number | null {
	return React.useSyncExternalStore(subscribeMinute, minuteStamp, () => null);
}
```

### 10. `components/registry/visualizer/types.ts` — supporting file, required

```tsx
export type OrbitRunStatus = "ok" | "failed" | "running" | "blocked";

export type OrbitRun = {
	id: string;
	title: string;
	status: OrbitRunStatus;
	at: string;
	durationMs: number | null;
	href?: string;
};

export type OrbitNodeData = {
	id: string;
	name: string;
	detail: string;
	group: string;
	kind: "agent" | "tool";
	count: number;
	flagged: number;
	lastAt: string;
	daily: number[];
	weekly: number[];
	medianMs: number | null;
	recent: OrbitRun[];
};

export type OrbitGroup = { id: string; label: string; count: number };
```

### 11. `components/registry/visualizer/motion.ts` — supporting file, required

```tsx
export const EASE = "cubic-bezier(0.23, 1, 0.32, 1)";

export const ARRIVE = 0.45;

export function arriveAt(delay: number, dur: number): number {
	return Math.round(delay + dur * ARRIVE);
}

export const BEAM_MS = 700;
export const BLOOM_MS = 700;

export const beamStart = (i: number) => 220 + i * 60;
export const beamArrive = (i: number) => arriveAt(beamStart(i), BEAM_MS);
export const senderStart = (catArrive: number, k: number) => catArrive + 120 + Math.min(k, 7) * 40;

export const IGNITION_MS = Math.max(2000, senderStart(beamArrive(6), 7) + BLOOM_MS);

export function seeded(seed: number): () => number {
	let a = seed >>> 0;
	return () => {
		a = (a + 0x6d2b79f5) >>> 0;
		let t = a;
		t = Math.imul(t ^ (t >>> 15), t | 1);
		t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
		return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
	};
}
```

### 12. `components/registry/visualizer/rail.tsx` — supporting file, required

```tsx
"use client";

import * as React from "react";
import { cn } from "@/lib/utils";
import type { WeekIndex } from "./layout";
import { EASE } from "./motion";

export type RailOption = { key: string; label: string; spoken: string; week: WeekIndex | null };

type Band = { start: number; end: number };

function weekBand(week: WeekIndex, days: number): Band {
	const start = Math.max(0, days - (4 - week) * 7);
	return { start, end: Math.min(days, start + 7) };
}

export function TimeRail({
	daily,
	options,
	value,
	onChange,
	label = "Time range",
	className,
	inert,
}: {
	daily: readonly number[];
	options: readonly RailOption[];
	value: string;
	onChange: (key: string) => void;
	label?: string;
	className?: string;
	inert?: boolean;
}) {
	const days = Math.max(1, daily.length);
	const max = Math.max(1, ...daily);
	const stop = Math.max(0, options.findIndex((o) => o.key === value));
	const current = options[stop];
	const band: Band = current?.week == null ? { start: 0, end: days } : weekBand(current.week, days);
	const all = current?.week == null;
	const [dragging, setDragging] = React.useState(false);

	const go = (i: number) => {
		const next = options[Math.max(0, Math.min(options.length - 1, i))];
		if (next && next.key !== value) onChange(next.key);
	};

	const pick = (e: React.PointerEvent<HTMLDivElement>) => {
		const box = e.currentTarget.getBoundingClientRect();
		const day = Math.floor(((e.clientX - box.left) / Math.max(1, box.width)) * days);
		let best = -1;
		options.forEach((o, i) => {
			if (o.week === null) return;
			if (best === -1 || day >= weekBand(o.week, days).start) best = i;
		});
		if (best !== -1) go(best);
	};

	const onKeyDown = (e: React.KeyboardEvent) => {
		let next = stop;
		if (e.key === "ArrowRight" || e.key === "ArrowUp" || e.key === "PageUp") next = stop + 1;
		else if (e.key === "ArrowLeft" || e.key === "ArrowDown" || e.key === "PageDown") next = stop - 1;
		else if (e.key === "Home") next = 0;
		else if (e.key === "End") next = options.length - 1;
		else return;
		e.preventDefault();
		go(next);
	};

	const pct = (d: number) => `${(100 * d) / days}%`;

	return (
		<div inert={inert} className={cn("grid grid-cols-[auto_minmax(0,1fr)] items-center gap-x-3 gap-y-1.5", className)}>
			<button
				type="button"
				aria-pressed={all}
				onClick={() => go(0)}
				className={cn(
					"h-7 rounded-full px-3 text-[12px] leading-none transition-colors focus-visible:ring-2 focus-visible:ring-accent/60 focus-visible:outline-none",
					all ? "bg-accent text-on-accent" : "bg-raised text-ink-dim hover:text-ink",
				)}
			>
				{options[0]?.label}
			</button>
			<div
				role="slider"
				tabIndex={0}
				aria-label={label}
				aria-valuemin={0}
				aria-valuemax={options.length - 1}
				aria-valuenow={stop}
				aria-valuetext={current?.spoken}
				onKeyDown={onKeyDown}
				onPointerDown={(e) => {
					if (e.button !== 0 && e.pointerType === "mouse") return;
					e.currentTarget.setPointerCapture(e.pointerId);
					setDragging(true);
					pick(e);
				}}
				onPointerMove={(e) => {
					if (dragging) pick(e);
				}}
				onPointerUp={() => setDragging(false)}
				onPointerCancel={() => setDragging(false)}
				className={cn(
					"relative h-7 touch-none rounded-[8px] bg-raised outline-none select-none focus-visible:ring-2 focus-visible:ring-accent/60",
					dragging ? "cursor-grabbing" : "cursor-pointer",
				)}
			>
				<span
					aria-hidden
					className="absolute inset-y-0 rounded-[8px] bg-accent-muted"
					style={{ left: pct(band.start), width: pct(band.end - band.start), transition: `left 320ms ${EASE}, width 320ms ${EASE}` }}
				/>
				<span aria-hidden className="absolute inset-0 flex items-end gap-px overflow-hidden rounded-[8px] p-[3px]">
					{daily.map((v, d) => {
						const on = d >= band.start && d < band.end;
						return (
							<span
								key={d}
								className={cn(
									"min-w-0 flex-1 rounded-[1.5px] transition-colors duration-200",
									on ? "bg-accent" : "bg-[color-mix(in_oklab,var(--color-ink-mute)_32%,var(--color-raised))]",
								)}
								style={{ height: `${Math.max(12, (100 * Math.max(0, v)) / max)}%` }}
							/>
						);
					})}
				</span>
			</div>
			<span aria-hidden />
			<div aria-hidden className="relative h-2.5">
				{options.map((o) => {
					if (o.week === null) return null;
					const b = weekBand(o.week, days);
					return (
						<span
							key={o.key}
							className={cn(
								"absolute top-0 -translate-x-1/2 font-mono text-[10px] leading-none transition-colors",
								o.key === value ? "text-accent" : "text-ink-mute",
							)}
							style={{ left: pct((b.start + b.end) / 2) }}
						>
							{o.label}
						</span>
					);
				})}
			</div>
		</div>
	);
}
```

### 13. `lib/utils.ts` — peer util, required

```tsx
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs));
}
```

### 14. `hooks/use-animation-loop.ts` — peer hook, required

```tsx
"use client";

import { useCallback, useEffect, useLayoutEffect, useMemo, useRef } from "react";

export interface Metrics {
  width: number;
  height: number;
  dpr: number;
  bufferWidth: number;
  bufferHeight: number;
}

export interface FrameInfo {
  now: number;
  dt: number;
  elapsed: number;
  frame: number;
}

export interface AnimationLoopHandle {
  start(): void;
  stop(): void;
  paint(): void;
  resize(): void;
  readonly running: boolean;
}

export interface AnimationLoopOptions {
  target: React.RefObject<HTMLElement | null>;
  halted?: boolean;
  dpr?: number | "auto";
  onResize?(metrics: Metrics): void;
  onFrame?(info: FrameInfo): void | false;
  paintWhenHalted?: boolean;
  resizeDebounceMs?: number;
  gl?(): WebGLRenderingContext | WebGL2RenderingContext | null | undefined;
  onDispose?(): void;
  deps?: unknown[];
}

const MAX_DT = 1 / 15;

export function useAnimationLoop(
  options: AnimationLoopOptions,
): AnimationLoopHandle {
  const opts = useRef(options);
  useLayoutEffect(() => {
    opts.current = options;
  });

  const raf = useRef<number | null>(null);
  const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
  const running = useRef(false);
  const disposed = useRef(false);
  const startedAt = useRef(0);
  const last = useRef(0);
  const frame = useRef(0);

  const measure = useCallback((): Metrics | null => {
    const el = opts.current.target.current;
    if (!el) return null;
    const rect = el.getBoundingClientRect();
    const cap = opts.current.dpr ?? "auto";
    const limit = cap === "auto" ? 2 : cap;
    const dpr = Math.min(
      typeof window === "undefined" ? 1 : window.devicePixelRatio || 1,
      limit,
    );
    return {
      width: rect.width,
      height: rect.height,
      dpr,
      bufferWidth: Math.max(1, Math.round(rect.width * dpr)),
      bufferHeight: Math.max(1, Math.round(rect.height * dpr)),
    };
  }, []);

  const tick = useCallback(function tick(now: number) {
    if (disposed.current) return;

    if (startedAt.current === 0) startedAt.current = now;
    const dt = last.current === 0 ? 0 : Math.min((now - last.current) / 1000, MAX_DT);
    last.current = now;

    const info: FrameInfo = {
      now,
      dt,
      elapsed: (now - startedAt.current) / 1000,
      frame: frame.current++,
    };

    const verdict = opts.current.onFrame?.(info);

    if (disposed.current) return;

    if (verdict === false || opts.current.halted) {
      running.current = false;
      raf.current = null;
      return;
    }
    raf.current = requestAnimationFrame(tick);
  }, []);

  const start = useCallback(() => {
    if (disposed.current || running.current) return;
    running.current = true;
    last.current = 0;
    raf.current = requestAnimationFrame(tick);
  }, [tick]);

  const stop = useCallback(() => {
    running.current = false;
    if (raf.current !== null) {
      cancelAnimationFrame(raf.current);
      raf.current = null;
    }
  }, []);

  const paint = useCallback(() => start(), [start]);

  const resize = useCallback(() => {
    const metrics = measure();
    if (!metrics) return;
    opts.current.onResize?.(metrics);
    if (opts.current.paintWhenHalted !== false) paint();
    else if (!opts.current.halted) start();
  }, [measure, paint, start]);

  const deps = options.deps ?? [];

  useEffect(() => {
    disposed.current = false;
    const el = opts.current.target.current;
    if (!el) return;

    const run = () => {
      if (disposed.current) return;
      resize();
    };

    const observer = new ResizeObserver(() => {
      const wait = opts.current.resizeDebounceMs ?? 0;
      if (wait <= 0) {
        run();
        return;
      }
      if (timer.current !== null) clearTimeout(timer.current);
      timer.current = setTimeout(() => {
        timer.current = null;
        run();
      }, wait);
    });
    observer.observe(el);

    resize();
    if (!opts.current.halted) start();

    return () => {
      disposed.current = true;
      running.current = false;
      if (raf.current !== null) {
        cancelAnimationFrame(raf.current);
        raf.current = null;
      }
      if (timer.current !== null) {
        clearTimeout(timer.current);
        timer.current = null;
      }
      observer.disconnect();
      opts.current.onDispose?.();
      const context = opts.current.gl?.();
      context?.getExtension("WEBGL_lose_context")?.loseContext();
      startedAt.current = 0;
      last.current = 0;
      frame.current = 0;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, deps);

  const halted = options.halted ?? false;
  useEffect(() => {
    if (!halted) start();
  }, [halted, start]);

  return useMemo<AnimationLoopHandle>(
    () => ({
      start,
      stop,
      paint,
      resize,
      get running() {
        return running.current;
      },
    }),
    [start, stop, paint, resize],
  );
}
```


## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `defaultView` | `"constellation" | "list"` | `"constellation"` | What a wide stage opens on. Below 640px the list always wins, because ring 2 has nowhere to put its labels at that width and a constellation without names is decoration. |
| `showPeriods` | `boolean` | `true` | Show the W1–W4 toggle. Picking a week resizes every orb and beam to that week's volume, but the layout keeps its slots, since each orb reserved room for its largest week up front, and so nothing jumps around. |
| `maxNodes` | `number` | `24` | How many of the busiest nodes take a seat on ring 2. The pools keep their full totals, so a trimmed ring still reports true shares. Range 3–24. |
| `ambient` | `boolean` | `true` | Sparks on the beams, twinkling stars and a breathing sun. It only runs once the entrance has settled, while the widget is on screen and the tab is visible, and never inside a drilldown. |
| `sparkSpeed` | `number` | `1` | Multiplier on how fast sparks travel. The base speed is already tied to recency, so a pool that went quiet days ago drifts while a busy one streams. Range 0.25–3 ×. |
| `ignition` | `boolean` | `true` | Play the staggered entrance: the sun blooms, beams draw, then pools, agents and labels follow. It waits until the widget is first on screen and never replays on a week switch. |
| `showLegend` | `boolean` | `true` | Legend and keyboard hint under the stage. |
| `showSunLabel` | `boolean` | `true` | Name the sun. Its size is fitted to the sun's diameter rather than fixed, so a longer name shrinks instead of spilling across the tick ring. |
| `sunLabelColor` | `string (hex)` | `"#1a1408"` | Colour of the sun's name. The sun is lightest at its centre, so a dark ink reads best. Ignored while `showSunLabel` is `false`. |
| `accent` | `string (hex)` | `"#e6c27a"` | The sun, the beams, the tick rings and the blocked chip. |
| `filament` | `string (hex)` | `"#5ee1d9"` | The thin filament beside each beam, the dotted links, focus rings and the flag dot. |
| `agentColor` | `string (hex)` | `"#5fd3a6"` | Orbs for agents. |
| `toolColor` | `string (hex)` | `"#e6c27a"` | Orbs for tools and services. |
| `groupColorA` | `string (hex)` | `"#f08bb0"` | Pools alternate between this and groupColorB around the inner ring. |
| `groupColorB` | `string (hex)` | `"#a99bff"` | The second pool colour. |

## Usage

```tsx
import Visualizer from "@/components/registry/visualizer/visualizer";

<Visualizer
  defaultView="constellation"
  showPeriods={true}
  maxNodes={24}
  ambient={true}
  sparkSpeed={1}
  ignition={true}
  showLegend={true}
  showSunLabel={true}
  sunLabelColor="#1a1408"
  accent="#e6c27a"
  filament="#5ee1d9"
  agentColor="#5fd3a6"
  toolColor="#e6c27a"
  groupColorA="#f08bb0"
  groupColorB="#a99bff"
/>
```

The import path matches the file path above; change it if you move the component. Every value shown is the documented default — pass only what you actually want to change. The snippet lists the tunable props only: if the component's props type in the source requires others (content, handlers, data), pass those too.

## Integration rules

- Keep the `"use client"` directive. This is a client component and will not render as a Server Component.
- It fills its parent. Give the wrapper an explicit height (or a definite grid area) — against a height-auto parent it collapses to nothing.
- It takes a `reducedMotion` prop and quiesces when true. Wire it to a `prefers-reduced-motion` listener rather than hardcoding `false`.
- It runs a free-running animation loop. Halt it when off-screen or backgrounded if you care about battery.
- The `touch-action: none` on the hit target is load-bearing — without it a finger drag scrolls the page instead of driving the effect. Do not strip it as a stray utility class.
- The peer hook is required, not optional. Copy it to `hooks/use-animation-loop.ts` so the component's `@/hooks/use-animation-loop` import resolves.
- `lib/utils.ts` is required, not optional. It exports the `cn` helper the component imports from `@/lib/utils` — keep it at that path, or rewrite every `cn` import to wherever you already keep yours. If your project is shadcn-based you almost certainly have this file already; keep yours and drop mine.
- The supporting files are part of the component, not examples. Copy every file listed, preserving the directory layout — they import each other by relative path.
- It owns a GPU/canvas context and releases it on unmount. Preserve the cleanup return — leaking contexts kills the tab after a few navigations.

## Your task

1. Tell me where in my project this should live and why.
2. Create the files above verbatim.
3. Add the design tokens to my global CSS, or map them to tokens I already have.
4. Wire the component into the place I point you at, with sensible props for that context.
5. Flag anything in my setup that conflicts with the stack assumptions above.

Do not restyle the component or alter the animation math unless I ask.
