import { d as attr_style, f as stringify, x as head, c as escape_html, a as attr, b as attr_class, e as ensure_array_like, y as bind_props, g as derived } from './dev-BNpEUZI3.js';
import { o as onDestroy } from './index-server-DocJvixA.js';
import './client-CW9E6S_J.js';
import { a as Breadcrumb, B as Badge, T as Tabs, C as Card, I as IconButton } from './Tabs-DzG6Bn9a.js';
import { H as Hover_label, r as resolveEdgeStyleForWebGL, A as ALL_EDGE_KINDS, d as describeEdgeKind, E as EDGE_STYLE } from './no-face-up-DcejJLy-.js';
import '@cosmograph/cosmos';
import './chunk-DDP5xfzh.js';
import 'node:module';
import './internal-DYSVC9SL.js';
import '@sveltejs/kit/internal';
import '@sveltejs/kit/internal/server';

//#region src/lib/graph/types.ts
/**
* Default fire duration, in milliseconds.
*
* Matches the `--ease-pulse` motion token (1200ms) so synapse sparks
* travel in lockstep with pulse CSS animations.
*/
var FIRE_DURATION_MS = 1200;
/**
* Ordered list of every substrate CLEO projects. Mirror of
* {@link SubstrateId}. Consumers use this to iterate in a stable order
* without enumerating the union by hand.
*/
var ALL_SUBSTRATES = [
	"brain",
	"nexus",
	"tasks",
	"conduit",
	"agent-registry"
];
//#endregion
//#region src/lib/graph/firing-queue.ts
/**
* CLEO Studio — synapse firing queue.
*
* A small, allocation-frugal queue that tracks active "edge fires" and
* returns per-frame travel progress + a resolved WebGL colour tuple.
* The renderer uses the output to draw travelling sparks along each
* firing edge.
*
* @task T990
* @wave 1A
*/
/**
* Queue holding every in-flight synapse fire.
*
* Implementation notes:
* - Entries are kept in insertion order in a plain array. Expired
*   entries are filtered out on each `tick`.
* - `tick` takes a `nowMs` argument so tests (and the renderer) can
*   inject a deterministic clock.
* - The queue is edge-aware: if the caller passes a
*   `Map<string, GraphEdge>` into {@link FiringQueue.tick}, the result
*   includes colour resolved from the edge's kind. Otherwise a neutral
*   white fallback is used.
*/
var FiringQueue = class {
	queue = [];
	/** Duration in ms every fire travels from source to target. */
	duration;
	/**
	* @param duration - Override travel duration in ms.
	*   Defaults to {@link FIRE_DURATION_MS}.
	*/
	constructor(duration = FIRE_DURATION_MS) {
		this.duration = duration;
	}
	/** Number of currently-tracked fires. */
	get size() {
		return this.queue.length;
	}
	/**
	* Enqueue a new fire. Safe to call every frame — duplicates on the
	* same edge are permitted and render as multiple sparks in flight.
	*
	* @param ev - The fire event to enqueue.
	*/
	enqueue(ev) {
		this.queue.push(ev);
	}
	/** Drop every in-flight fire. Used on teardown. */
	clear() {
		this.queue.length = 0;
	}
	/**
	* Advance the queue to `nowMs` and return every fire still in
	* flight, with its normalised travel progress.
	*
	* Expired entries are removed in-place. The returned array is a
	* fresh allocation each call — the renderer is free to retain refs.
	*
	* @param nowMs - Current timestamp (`performance.now()` or
	*   `Date.now()`). Must be monotonic across calls.
	* @param edgesById - Optional edge lookup for colour resolution.
	*/
	tick(nowMs, edgesById) {
		const out = [];
		const duration = this.duration;
		let write = 0;
		for (let read = 0; read < this.queue.length; read++) {
			const ev = this.queue[read];
			const age = nowMs - ev.emittedAt;
			if (age < 0) {
				if (write !== read) this.queue[write] = ev;
				write++;
				continue;
			}
			if (age >= duration) continue;
			const t = age / duration;
			const edge = edgesById?.get(ev.edgeId);
			const colorRgb = edge ? resolveEdgeStyleForWebGL(edge.kind) : [
				1,
				1,
				1
			];
			out.push({
				edgeId: ev.edgeId,
				t,
				colorRgb,
				intensity: ev.intensity
			});
			if (write !== read) this.queue[write] = ev;
			write++;
		}
		this.queue.length = write;
		return out;
	}
};
//#endregion
//#region src/lib/graph/renderers/ThreeBrainRenderer.svelte
function ThreeBrainRenderer($$renderer, $$props) {
	$$renderer.component(($$renderer) => {
		/**
		* Props for {@link ThreeBrainRenderer}.
		*/
		/** Nodes to render. */
		/** Edges to render. */
		/** Fired when the user clicks a node. Passes the full node. */
		/** Fired when the user clicks empty canvas (no node under pointer). */
		/** Fired when hover starts/ends. Passes null on leave. */
		/** UnrealBloomPass strength override. Defaults to 1.6. */
		/** CSS height of the canvas. */
		/** Set of currently-pulsing node ids (drives per-point flash). */
		/** Queued synapse fires — consumed by {@link FiringQueue}. */
		/**
		* When true, render the synaptic edge web. Default `true` per
		* operator directive — the living-brain view needs the web visible.
		*/
		/**
		* Substrate to drill-down into. When set, the camera animates to
		* that substrate's cortical region, dims non-members to 0.14, and
		* brightens members. Pass `null` for full-brain view.
		*/
		let { height = "100%"} = $$props;
		let hoveredNode = null;
		let hoverX = 0;
		let hoverY = 0;
		const firingQueue = new FiringQueue(FIRE_DURATION_MS);
		/** Visual node cloud — additive gaussian sprite Points. */
		/** Synaptic base layer — additive LineSegments. */
		/** Bridge layer — cross-substrate edges, violet, slightly thicker. */
		/**
		* Pre-allocated spark pool for travelling-synapse fire sparks.
		* Avoids per-frame GC churn.
		*/
		/** Highlight overlay for edges connected to the hovered node. */
		/** Shared gaussian sprite texture. */
		let refs = null;
		let simulation = null;
		let clusterLabels = [];
		let focusTween = null;
		onDestroy(() => {
			if (refs) disposeScene(refs);
			refs = null;
			simulation?.stop();
			simulation = null;
			if (focusTween) focusTween.cancelled = true;
			focusTween = null;
		});
		function disposeScene(r) {
			r.resizeObserver.disconnect();
			r.controls.dispose();
			r.nodePoints.geometry.dispose();
			r.nodePoints.material.dispose();
			r.edgeLines.geometry.dispose();
			r.edgeLines.material.dispose();
			r.bridgeLines.geometry.dispose();
			r.bridgeLines.material.dispose();
			r.edgeHighlight.geometry.dispose();
			r.edgeHighlight.material.dispose();
			r.sparkPoints.geometry.dispose();
			r.sparkPoints.material.dispose();
			r.spriteTex.dispose();
			for (const h of clusterLabels) {
				h.obj.element.remove();
				h.obj.parent?.remove(h.obj);
			}
			clusterLabels = [];
			r.renderer.dispose();
			firingQueue.clear();
		}
		$$renderer.push(`<div class="brain-renderer svelte-ipcfhc"${attr_style(`height: ${stringify(height)};`)}><canvas class="brain-canvas svelte-ipcfhc" aria-label="3D living-brain canvas"></canvas> <div class="brain-css2d svelte-ipcfhc" aria-hidden="true"></div> `);
		Hover_label($$renderer, {
			node: hoveredNode,
			x: hoverX,
			y: hoverY
		});
		$$renderer.push(`<!----></div>`);
	});
}

//#endregion
//#region src/lib/components/LivingBrainCosmograph.svelte
function LivingBrainCosmograph($$renderer, $$props) {
	$$renderer.component(($$renderer) => {
		/**
		* Props for {@link LivingBrainCosmograph}.
		*/
		/** Nodes (kit contract). */
		/** Edges (kit contract). */
		/** Fired when the user clicks a node. Passes the node. */
		/** Fired when the user clicks empty canvas. */
		/** CSS height of the canvas. */
		/**
		* Set of node IDs currently pulsing (new/updated).
		*
		* cosmos.gl 2.0 has no per-node animation API; when the set is
		* non-empty we `zoomToPointByIndex` on the first pulsing node and
		* briefly brighten its colour, restoring after
		* {@link PULSE_DURATION_MS}.
		*/
		/**
		* Called when cosmos.gl fails to initialise (e.g. no WebGL).  The
		* parent page should fall back to the 3D renderer so the operator
		* never sees a blank canvas.
		*/
		let { nodes, height = "100%"} = $$props;
		let cosmos = null;
		/** ResizeObserver reference so we can rebuild on size change. */
		let resizeObs = null;
		onDestroy(() => {
			resizeObs?.disconnect();
			resizeObs = null;
			cosmos?.destroy();
			cosmos = null;
		});
		$$renderer.push(`<div class="lbc-wrap svelte-1fx55sa"${attr_style(`height: ${stringify(height)}; position: relative;`)}>`);
		$$renderer.push("<!--[-1-->");
		$$renderer.push(`<div class="lbc-canvas svelte-1fx55sa"></div> `);
		if (nodes.length === 0) {
			$$renderer.push("<!--[0-->");
			$$renderer.push(`<div class="lbc-empty svelte-1fx55sa">No data to display</div>`);
		} else $$renderer.push("<!--[-1-->");
		$$renderer.push(`<!--]--> <div class="lbc-badge svelte-1fx55sa" aria-label="GPU-accelerated renderer active">GPU</div>`);
		$$renderer.push(`<!--]--></div>`);
	});
}
//#endregion
//#region src/lib/components/brain/BrainControlsDock.svelte
function BrainControlsDock($$renderer, $$props) {
	$$renderer.component(($$renderer) => {
		/**
		* Props for {@link BrainControlsDock}.
		*/
		/** Which edge kinds are currently visible. */
		/** Whether the synapse line layer is visible. */
		/** When true, hide all intra-substrate edges (show bridges only). */
		/** When true, the ambient d3 sim is paused. */
		/** Fired when an edge-kind chip is toggled. */
		/** Fired when synapse toggle is changed. */
		/** Fired when bridges-only toggle is changed. */
		/** Fired when breathing-pause toggle is changed. */
		/** Fired when the reset-view button is pressed. */
		let { enabledKinds, showSynapses, showBridgesOnly, breathingPaused} = $$props;
		$$renderer.push(`<footer class="controls-dock svelte-xiv1be" aria-label="Canvas controls"><div class="dock-section controls-toggles svelte-xiv1be"><span class="dock-eyebrow svelte-xiv1be">Canvas</span> <div class="toggle-group svelte-xiv1be" role="group" aria-label="Canvas visibility toggles"><button type="button"${attr_class("dock-toggle svelte-xiv1be", void 0, { "active": showSynapses })}${attr("aria-pressed", showSynapses)} title="Toggle synapse edge lines (s)"><span${attr_class("toggle-dot svelte-xiv1be", void 0, { "on": showSynapses })} aria-hidden="true"></span> synapses <kbd class="shortcut-hint svelte-xiv1be" aria-hidden="true">s</kbd></button> <button type="button"${attr_class("dock-toggle svelte-xiv1be", void 0, { "active": showBridgesOnly })}${attr("aria-pressed", showBridgesOnly)} title="Show only cross-substrate bridge edges (b)"><span${attr_class("toggle-dot svelte-xiv1be", void 0, { "on": showBridgesOnly })} aria-hidden="true"></span> bridges only <kbd class="shortcut-hint svelte-xiv1be" aria-hidden="true">b</kbd></button> <button type="button"${attr_class("dock-toggle svelte-xiv1be", void 0, { "active": breathingPaused })}${attr("aria-pressed", breathingPaused)} title="Pause ambient simulation breathing"><span${attr_class("toggle-dot svelte-xiv1be", void 0, { "on": breathingPaused })} aria-hidden="true"></span> ${escape_html(breathingPaused ? "paused" : "breathing")}</button></div></div> <div class="dock-divider svelte-xiv1be" aria-hidden="true"></div> <div class="dock-section edge-section svelte-xiv1be"><span class="dock-eyebrow svelte-xiv1be">Edge taxonomy — toggle to filter</span> <div class="edge-grid svelte-xiv1be"><!--[-->`);
		const each_array = ensure_array_like(ALL_EDGE_KINDS);
		for (let $$index = 0, $$length = each_array.length; $$index < $$length; $$index++) {
			let k = each_array[$$index];
			const style = EDGE_STYLE[k];
			$$renderer.push(`<button type="button"${attr_class("edge-kind svelte-xiv1be", void 0, { "active": enabledKinds.has(k) })}${attr("aria-pressed", enabledKinds.has(k))}${attr("title", describeEdgeKind(k))}><span${attr_class("edge-swatch svelte-xiv1be", void 0, { "dashed": Boolean(style.dash) })}${attr_style(`--swatch-color: ${stringify(style.color)};`)} aria-hidden="true"></span> <span class="edge-name svelte-xiv1be">${escape_html(k)}</span></button>`);
		}
		$$renderer.push(`<!--]--></div></div> <div class="dock-actions svelte-xiv1be"><button type="button" class="reset-btn svelte-xiv1be" title="Fit camera to graph (f)" aria-label="Reset camera view to fit the graph">fit view <kbd class="shortcut-hint svelte-xiv1be" aria-hidden="true">f</kbd></button></div></footer>`);
	});
}
//#endregion
//#region src/lib/components/brain/BrainLoadingSkeleton.svelte
function BrainLoadingSkeleton($$renderer, $$props) {
	/**
	* Props for {@link BrainLoadingSkeleton}.
	*/
	/** Whether the skeleton is currently visible. */
	/** Optional CSS height for the skeleton area. */
	let { visible = true, height = "100%" } = $$props;
	/**
	* Ghost cluster descriptors — approximate substrate positions in the
	* canvas viewport as percentage offsets from top-left. Positions mirror
	* the d3-force-3d z-axis bias used by ThreeBrainRenderer.
	*/
	const GHOST_CLUSTERS = [
		{
			id: "brain",
			label: "BRAIN",
			cssVar: "var(--info)",
			top: "18%",
			left: "22%",
			width: "22%",
			height: "14%"
		},
		{
			id: "nexus",
			label: "NEXUS",
			cssVar: "var(--success)",
			top: "42%",
			left: "52%",
			width: "26%",
			height: "16%"
		},
		{
			id: "tasks",
			label: "TASKS",
			cssVar: "var(--warning)",
			top: "62%",
			left: "20%",
			width: "20%",
			height: "12%"
		},
		{
			id: "conduit",
			label: "CONDUIT",
			cssVar: "var(--accent)",
			top: "28%",
			left: "58%",
			width: "16%",
			height: "10%"
		},
		{
			id: "agent-registry",
			label: "SIGNALDOCK",
			cssVar: "var(--danger)",
			top: "70%",
			left: "55%",
			width: "18%",
			height: "10%"
		}
	];
	if (visible) {
		$$renderer.push("<!--[0-->");
		$$renderer.push(`<div class="skeleton-canvas svelte-trzjgq"${attr_style(`height: ${stringify(height)};`)} aria-hidden="true" data-brain-skeleton=""><div class="ambient-glow svelte-trzjgq"></div> <!--[-->`);
		const each_array = ensure_array_like(GHOST_CLUSTERS);
		for (let $$index = 0, $$length = each_array.length; $$index < $$length; $$index++) {
			let cluster = each_array[$$index];
			$$renderer.push(`<div class="ghost-cluster svelte-trzjgq"${attr_style(` top: ${stringify(cluster.top)}; left: ${stringify(cluster.left)}; width: ${stringify(cluster.width)}; height: ${stringify(cluster.height)}; --ghost-color: ${stringify(cluster.cssVar)}; `)}><div class="ghost-label svelte-trzjgq"><span class="ghost-substrate svelte-trzjgq">${escape_html(cluster.label)}</span> <span class="ghost-dash svelte-trzjgq">·</span> <span class="ghost-count svelte-trzjgq">—</span> <span class="ghost-dash svelte-trzjgq">·</span> <span class="ghost-count svelte-trzjgq">—</span></div> <div class="shimmer-overlay svelte-trzjgq"></div></div>`);
		}
		$$renderer.push(`<!--]--> <div class="ghost-dots svelte-trzjgq" aria-hidden="true"><!--[-->`);
		const each_array_1 = ensure_array_like({ length: 48 });
		for (let i = 0, $$length = each_array_1.length; i < $$length; i++) {
			each_array_1[i];
			$$renderer.push(`<div class="ghost-dot svelte-trzjgq"${attr_style(` top: ${stringify(10 + (i * 7 + i * i * 3) % 78)}%; left: ${stringify(8 + (i * 13 + i * 5) % 82)}%; width: ${stringify(3 + i % 5)}px; height: ${stringify(3 + i % 5)}px; animation-delay: ${stringify(i * 137 % 2e3)}ms; opacity: ${stringify(.08 + i % 7 * .02)}; `)}></div>`);
		}
		$$renderer.push(`<!--]--></div> <div class="scan-line svelte-trzjgq"></div></div>`);
	} else $$renderer.push("<!--[-1-->");
	$$renderer.push(`<!--]-->`);
}
//#endregion
//#region src/lib/components/brain/RegionMeter.svelte
function RegionMeter($$renderer, $$props) {
	$$renderer.component(($$renderer) => {
		/**
		* Props for {@link RegionMeter}.
		*/
		/** Substrate id. Drives colour and region label lookup. */
		/** Human-readable region name (e.g. "HIPPOCAMPUS"). */
		/** Current live neuron (node) count. */
		/** Rolling 5-second firing rate as a percentage [0..100]. */
		/** Number of bridge edges to/from other substrates. */
		/** 60-sample ring buffer of firing rate history. Oldest first. */
		/** CSS custom property reference for the substrate colour. */
		/** Whether this substrate is currently actively firing (drives pulse dot). */
		/** Click handler — fires when the card is clicked. */
		let { substrate, regionName, neuronCount, firingRate, bridgeCount, history = [], colorVar, firing = false} = $$props;
		/**
		* Build an SVG polyline path string from an array of [0..100] values.
		* Uses the last SPARK_SAMPLES entries, normalised to a 120x28 viewport.
		*/
		function buildSparkPath(values) {
			const samples = values.slice(-60);
			if (samples.length < 2) return "";
			const w = 120;
			const h = 28;
			const max = Math.max(...samples, 1);
			const step = w / (samples.length - 1);
			return `M ${samples.map((v, i) => {
				const x = i * step;
				const y = h - v / max * h;
				return `${x.toFixed(1)},${y.toFixed(1)}`;
			}).join(" L ")}`;
		}
		const sparkPath = derived(() => buildSparkPath(history));
		const firingRateDisplay = derived(() => firingRate.toFixed(1));
		const firingRatePct = derived(() => Math.min(100, firingRate));
		$$renderer.push(`<button type="button"${attr_class("region-meter svelte-zrzlbu", void 0, { "firing": firing })}${attr_style(`--meter-color: ${stringify(colorVar)};`)}${attr("aria-label", `${stringify(regionName)} region: ${stringify(neuronCount)} neurons, ${stringify(firingRateDisplay())}% firing rate, ${stringify(bridgeCount)} bridges`)}${attr("data-substrate", substrate)}><div class="color-bar svelte-zrzlbu" aria-hidden="true"></div> <div class="meter-body svelte-zrzlbu"><div class="meter-header svelte-zrzlbu"><div class="meter-name-row svelte-zrzlbu"><span${attr_class("firing-dot svelte-zrzlbu", void 0, { "active": firing })} aria-hidden="true"></span> <span class="region-name svelte-zrzlbu">${escape_html(regionName)}</span></div> <div class="meter-stats svelte-zrzlbu"><span class="stat-group svelte-zrzlbu"><span class="stat-val svelte-zrzlbu">${escape_html(neuronCount.toLocaleString())}</span> <span class="stat-label svelte-zrzlbu">neurons</span></span> <span class="sep svelte-zrzlbu" aria-hidden="true">·</span> <span class="stat-group svelte-zrzlbu"><span class="stat-val firing-val svelte-zrzlbu">${escape_html(firingRateDisplay())}%</span> <span class="stat-label svelte-zrzlbu">firing</span></span> <span class="sep svelte-zrzlbu" aria-hidden="true">·</span> <span class="stat-group svelte-zrzlbu"><span class="stat-val svelte-zrzlbu">${escape_html(bridgeCount)}</span> <span class="stat-label svelte-zrzlbu">bridges</span></span></div></div> <div class="rate-bar-track svelte-zrzlbu" aria-hidden="true" role="presentation"><div class="rate-bar-fill svelte-zrzlbu"${attr_style(`width: ${stringify(firingRatePct())}%`)}></div></div> `);
		if (sparkPath()) {
			$$renderer.push("<!--[0-->");
			$$renderer.push(`<div class="sparkline-wrap svelte-zrzlbu" aria-hidden="true"><svg class="sparkline svelte-zrzlbu" viewBox="0 0 120 28" preserveAspectRatio="none" aria-hidden="true" focusable="false"><path${attr("d", sparkPath())} class="spark-path svelte-zrzlbu"></path><path${attr("d", `${stringify(sparkPath())} L 120,28 L 0,28 Z`)} class="spark-fill svelte-zrzlbu"></path></svg></div>`);
		} else {
			$$renderer.push("<!--[-1-->");
			$$renderer.push(`<div class="sparkline-empty svelte-zrzlbu" aria-hidden="true"><span class="spark-placeholder svelte-zrzlbu">no history</span></div>`);
		}
		$$renderer.push(`<!--]--></div></button>`);
	});
}
//#endregion
//#region src/lib/components/brain/BrainMonitorPanel.svelte
function BrainMonitorPanel($$renderer, $$props) {
	$$renderer.component(($$renderer) => {
		/**
		* A recent live bridge firing event shown in the Active Bridges strip.
		*/
		/**
		* Per-region live stats fed by the page shell.
		*/
		/**
		* Props for {@link BrainMonitorPanel}.
		*/
		/** Currently selected node, or null for the Region Monitor view. */
		/** All currently rendered edges — used for neighbor + bridge computation. */
		/** All currently rendered nodes — used for neighbor label lookup. */
		/** Live region stats for each of the 5 substrates. */
		/** Recent bridge firing events (last 10). */
		/** Fired when the user clicks a neighbor node. */
		/** Fired when the panel is dismissed (close button or Esc). */
		/** Fired when a substrate chip in the monitor is clicked (focus substrate). */
		let { selectedNode, edges, nodes, regionStats, bridgeEvents} = $$props;
		const substratePalette = {
			brain: "var(--info)",
			nexus: "var(--success)",
			tasks: "var(--warning)",
			conduit: "var(--accent)",
			"agent-registry": "var(--danger)"
		};
		const substrateTone = {
			brain: "info",
			nexus: "success",
			tasks: "warning",
			conduit: "accent",
			"agent-registry": "danger"
		};
		/**
		* Bridge edges originating from or targeting the selected node where
		* `meta.isBridge === true` OR the source/target substrates differ.
		*/
		const bridgeEdges = derived(() => {
			if (!selectedNode) return [];
			const nodeId = selectedNode.id;
			return edges.filter((e) => {
				if (e.source !== nodeId && e.target !== nodeId) return false;
				if (e.meta?.isBridge === true) return true;
				const otherId = e.source === nodeId ? e.target : e.source;
				const otherNode = nodes.find((n) => n.id === otherId);
				return otherNode !== void 0 && otherNode.substrate !== selectedNode.substrate;
			});
		});
		/**
		* All edges touching the selected node, grouped by the target substrate.
		* Self-substrate edges and bridge edges are separated.
		*/
		const neighborsBySubstrate = derived(() => {
			if (!selectedNode) return /* @__PURE__ */ new Map();
			const nodeId = selectedNode.id;
			const map = /* @__PURE__ */ new Map();
			for (const edge of edges) {
				if (edge.source !== nodeId && edge.target !== nodeId) continue;
				const neighborId = edge.source === nodeId ? edge.target : edge.source;
				const neighbor = nodes.find((n) => n.id === neighborId);
				if (!neighbor) continue;
				if (!map.has(neighbor.substrate)) map.set(neighbor.substrate, []);
				map.get(neighbor.substrate).push(neighbor);
			}
			return map;
		});
		/**
		* Source preview text for the selected node, derived from substrate type.
		* Returns null when no meaningful preview can be constructed.
		*/
		const sourcePreview = derived(() => {
			if (!selectedNode) return null;
			const meta = selectedNode.meta;
			switch (selectedNode.substrate) {
				case "nexus": {
					const filePath = meta?.file_path ?? meta?.path;
					if (typeof filePath === "string") return {
						kind: "file",
						value: `${filePath}${typeof meta?.line_start === "number" && typeof meta?.line_end === "number" ? `:${meta.line_start}–${meta.line_end}` : ""}`
					};
					return null;
				}
				case "brain": {
					const narrative = typeof meta?.body === "string" ? meta.body : typeof meta?.content === "string" ? meta.content : null;
					if (narrative) return {
						kind: "text",
						value: narrative.slice(0, 200)
					};
					return null;
				}
				case "tasks": {
					const status = typeof meta?.status === "string" ? meta.status : "";
					const priority = typeof meta?.priority === "string" ? meta.priority : "";
					if (status || priority) return {
						kind: "status",
						value: [status, priority].filter(Boolean).join(" · ")
					};
					return null;
				}
				default: return null;
			}
		});
		/**
		* Format a millisecond timestamp as a human-readable "Xs ago" / "Xm ago" label.
		*/
		function relativeTime(ms) {
			const diff = Math.max(0, Date.now() - ms);
			if (diff < 6e4) return `${Math.round(diff / 1e3)}s ago`;
			if (diff < 36e5) return `${Math.round(diff / 6e4)}m ago`;
			return `${Math.round(diff / 36e5)}h ago`;
		}
		if (selectedNode) {
			$$renderer.push("<!--[0-->");
			const node = selectedNode;
			{
				function header($$renderer) {
					$$renderer.push(`<div class="panel-header-row svelte-10eqtmz"><div class="panel-header-left svelte-10eqtmz"><span class="panel-eyebrow svelte-10eqtmz">Node detail</span> `);
					Badge($$renderer, {
						tone: substrateTone[node.substrate],
						pill: true,
						size: "sm",
						children: ($$renderer) => {
							$$renderer.push(`<!---->${escape_html(node.substrate)} · ${escape_html(node.kind)}`);
						}});
					$$renderer.push(`<!----></div> `);
					IconButton($$renderer, {
						"aria-label": "Close node detail panel",
						children: ($$renderer) => {
							$$renderer.push(`<!---->×`);
						}});
					$$renderer.push(`<!----></div>`);
				}
				Card($$renderer, {
					elevation: 2,
					padding: "compact",
					header,
					children: ($$renderer) => {
						$$renderer.push(`<div class="detail-body svelte-10eqtmz"><h2 class="node-label svelte-10eqtmz">${escape_html(node.label)}</h2> <dl class="detail-fields svelte-10eqtmz"><dt class="svelte-10eqtmz">ID</dt> <dd class="mono svelte-10eqtmz">${escape_html(node.id)}</dd> `);
						if (node.weight !== void 0) {
							$$renderer.push("<!--[0-->");
							$$renderer.push(`<dt class="svelte-10eqtmz">Weight</dt> <dd class="tabnum svelte-10eqtmz">${escape_html(node.weight.toFixed(3))}</dd>`);
						} else $$renderer.push("<!--[-1-->");
						$$renderer.push(`<!--]--> `);
						if (node.freshness !== void 0) {
							$$renderer.push("<!--[0-->");
							$$renderer.push(`<dt class="svelte-10eqtmz">Freshness</dt> <dd class="tabnum svelte-10eqtmz">${escape_html((node.freshness * 100).toFixed(0))}%</dd>`);
						} else $$renderer.push("<!--[-1-->");
						$$renderer.push(`<!--]--> `);
						if (node.category) {
							$$renderer.push("<!--[0-->");
							$$renderer.push(`<dt class="svelte-10eqtmz">Cluster</dt> <dd class="svelte-10eqtmz">${escape_html(node.category)}</dd>`);
						} else $$renderer.push("<!--[-1-->");
						$$renderer.push(`<!--]--></dl> `);
						if (sourcePreview()) {
							$$renderer.push("<!--[0-->");
							$$renderer.push(`<div class="source-preview svelte-10eqtmz">`);
							if (sourcePreview().kind === "file") {
								$$renderer.push("<!--[0-->");
								$$renderer.push(`<span class="preview-label svelte-10eqtmz">File</span> <code class="preview-file svelte-10eqtmz">${escape_html(sourcePreview().value)}</code>`);
							} else if (sourcePreview().kind === "text") {
								$$renderer.push("<!--[1-->");
								$$renderer.push(`<span class="preview-label svelte-10eqtmz">Narrative</span> <p class="preview-text svelte-10eqtmz">${escape_html(sourcePreview().value)}${escape_html(sourcePreview().value.length === 200 ? "…" : "")}</p>`);
							} else if (sourcePreview().kind === "status") {
								$$renderer.push("<!--[2-->");
								$$renderer.push(`<span class="preview-label svelte-10eqtmz">Status</span> <span class="preview-status svelte-10eqtmz">${escape_html(sourcePreview().value)}</span>`);
							} else $$renderer.push("<!--[-1-->");
							$$renderer.push(`<!--]--></div>`);
						} else $$renderer.push("<!--[-1-->");
						$$renderer.push(`<!--]--> `);
						if (neighborsBySubstrate().size > 0) {
							$$renderer.push("<!--[0-->");
							$$renderer.push(`<section class="neighbors-section svelte-10eqtmz" aria-label="Connected neighbors"><div class="section-eyebrow svelte-10eqtmz">Connected neighbors</div> <!--[-->`);
							const each_array = ensure_array_like([...neighborsBySubstrate().entries()]);
							for (let $$index_1 = 0, $$length = each_array.length; $$index_1 < $$length; $$index_1++) {
								let [substrate, neighbors] = each_array[$$index_1];
								$$renderer.push(`<div class="neighbor-group svelte-10eqtmz"><div class="neighbor-substrate-label svelte-10eqtmz"${attr_style(`--ng-color: ${stringify(substratePalette[substrate])};`)}><span class="ng-dot svelte-10eqtmz" aria-hidden="true"></span> ${escape_html(substrate)} <span class="ng-count svelte-10eqtmz">${escape_html(neighbors.length)}</span></div> <ul class="neighbor-list svelte-10eqtmz" role="list"><!--[-->`);
								const each_array_1 = ensure_array_like(neighbors.slice(0, 8));
								for (let $$index = 0, $$length = each_array_1.length; $$index < $$length; $$index++) {
									let neighbor = each_array_1[$$index];
									$$renderer.push(`<li class="svelte-10eqtmz"><button type="button" class="neighbor-btn svelte-10eqtmz">${escape_html(neighbor.label)}</button></li>`);
								}
								$$renderer.push(`<!--]--> `);
								if (neighbors.length > 8) {
									$$renderer.push("<!--[0-->");
									$$renderer.push(`<li class="neighbor-overflow svelte-10eqtmz">+${escape_html(neighbors.length - 8)} more</li>`);
								} else $$renderer.push("<!--[-1-->");
								$$renderer.push(`<!--]--></ul></div>`);
							}
							$$renderer.push(`<!--]--></section>`);
						} else $$renderer.push("<!--[-1-->");
						$$renderer.push(`<!--]--> `);
						if (bridgeEdges().length > 0) {
							$$renderer.push("<!--[0-->");
							$$renderer.push(`<section class="bridges-section svelte-10eqtmz" aria-label="Cross-substrate bridges"><div class="section-eyebrow svelte-10eqtmz">Bridges</div> <ul class="bridge-list svelte-10eqtmz" role="list"><!--[-->`);
							const each_array_2 = ensure_array_like(bridgeEdges());
							for (let $$index_2 = 0, $$length = each_array_2.length; $$index_2 < $$length; $$index_2++) {
								let edge = each_array_2[$$index_2];
								const isSource = edge.source === node.id;
								const otherId = isSource ? edge.target : edge.source;
								const otherNode = nodes.find((n) => n.id === otherId);
								const otherSubstrate = otherNode?.substrate ?? "brain";
								$$renderer.push(`<li class="bridge-item svelte-10eqtmz"><div class="bridge-direction svelte-10eqtmz"${attr_style(`--bridge-color: ${stringify(substratePalette[otherSubstrate])};`)}${attr("aria-label", `${stringify(isSource ? "to" : "from")} ${stringify(otherSubstrate)}`)}><span class="bridge-arrow svelte-10eqtmz" aria-hidden="true">${escape_html(isSource ? "→" : "←")}</span> <span class="bridge-substrate svelte-10eqtmz">${escape_html(otherSubstrate)}</span></div> `);
								Badge($$renderer, {
									tone: "neutral",
									size: "sm",
									children: ($$renderer) => {
										$$renderer.push(`<!---->${escape_html(edge.kind)}`);
									}});
								$$renderer.push(`<!----> `);
								if (otherNode) {
									$$renderer.push("<!--[0-->");
									$$renderer.push(`<button type="button" class="bridge-target-btn svelte-10eqtmz">${escape_html(otherNode.label)}</button>`);
								} else {
									$$renderer.push("<!--[-1-->");
									$$renderer.push(`<span class="bridge-unknown svelte-10eqtmz">${escape_html(otherId)}</span>`);
								}
								$$renderer.push(`<!--]--></li>`);
							}
							$$renderer.push(`<!--]--></ul></section>`);
						} else $$renderer.push("<!--[-1-->");
						$$renderer.push(`<!--]--> `);
						if (node.meta && Object.keys(node.meta).length > 0) {
							$$renderer.push("<!--[0-->");
							$$renderer.push(`<details class="meta-details svelte-10eqtmz"><summary class="svelte-10eqtmz">Raw metadata</summary> <pre class="meta-pre svelte-10eqtmz">${escape_html(JSON.stringify(node.meta, null, 2))}</pre></details>`);
						} else $$renderer.push("<!--[-1-->");
						$$renderer.push(`<!--]--></div>`);
					}});
			}
		} else {
			$$renderer.push("<!--[-1-->");
			{
				function header($$renderer) {
					$$renderer.push(`<div class="monitor-header svelte-10eqtmz"><span class="panel-eyebrow svelte-10eqtmz">Brain Monitor</span> <span class="monitor-live-dot svelte-10eqtmz" aria-hidden="true"></span> <span class="monitor-label svelte-10eqtmz">LIVE</span></div>`);
				}
				Card($$renderer, {
					elevation: 1,
					padding: "compact",
					header,
					children: ($$renderer) => {
						$$renderer.push(`<div class="region-meters svelte-10eqtmz" role="list" aria-label="Substrate region monitors"><!--[-->`);
						const each_array_3 = ensure_array_like(regionStats);
						for (let $$index_3 = 0, $$length = each_array_3.length; $$index_3 < $$length; $$index_3++) {
							let stats = each_array_3[$$index_3];
							$$renderer.push(`<div role="listitem" class="svelte-10eqtmz">`);
							RegionMeter($$renderer, {
								substrate: stats.substrate,
								regionName: stats.regionName,
								neuronCount: stats.neuronCount,
								firingRate: stats.firingRate,
								bridgeCount: stats.bridgeCount,
								history: stats.history,
								colorVar: stats.colorVar,
								firing: stats.firing});
							$$renderer.push(`<!----></div>`);
						}
						$$renderer.push(`<!--]--></div> `);
						if (bridgeEvents.length > 0) {
							$$renderer.push("<!--[0-->");
							$$renderer.push(`<div class="active-bridges svelte-10eqtmz" aria-label="Recent bridge firing events"><div class="section-eyebrow bridges-eyebrow svelte-10eqtmz">Active bridges</div> <ul class="bridge-events-list svelte-10eqtmz" role="list"><!--[-->`);
							const each_array_4 = ensure_array_like(bridgeEvents.slice(0, 10));
							for (let $$index_4 = 0, $$length = each_array_4.length; $$index_4 < $$length; $$index_4++) {
								let ev = each_array_4[$$index_4];
								$$renderer.push(`<li class="bridge-event-row svelte-10eqtmz"><span class="bridge-from-dot svelte-10eqtmz"${attr_style(`--dot-color: ${stringify(substratePalette[ev.fromSubstrate])};`)} aria-hidden="true"></span> <span class="bridge-event-text svelte-10eqtmz"><span class="bridge-region-label svelte-10eqtmz">${escape_html(ev.fromSubstrate.toUpperCase())}</span> <span class="bridge-arrow-icon svelte-10eqtmz" aria-hidden="true">→</span> <span class="bridge-region-label svelte-10eqtmz">${escape_html(ev.toSubstrate.toUpperCase())}</span></span> <span class="bridge-kind-chip svelte-10eqtmz">${escape_html(ev.edgeKind)}</span> <span class="bridge-time svelte-10eqtmz">${escape_html(relativeTime(ev.timestampMs))}</span></li>`);
							}
							$$renderer.push(`<!--]--></ul></div>`);
						} else $$renderer.push("<!--[-1-->");
						$$renderer.push(`<!--]-->`);
					}});
			}
		}
		$$renderer.push(`<!--]-->`);
	});
}
//#endregion
//#region src/lib/components/brain/BrainSearchBar.svelte
function BrainSearchBar($$renderer, $$props) {
	$$renderer.component(($$renderer) => {
		/**
		* Props for {@link BrainSearchBar}.
		*/
		/** All currently rendered nodes — used for client-side fallback filtering. */
		/** Fired when the user selects a search result. */
		/** External ref to focus this input — expose via bind:searchInput. */
		let { nodes, onResultSelect, searchInput = null } = $$props;
		let query = "";
		let open = false;
		$$renderer.push(`<div class="search-wrap svelte-1dpy914" data-brain-search=""><div${attr_class("search-shell svelte-1dpy914", void 0, { "open": open })}><span class="search-icon svelte-1dpy914" aria-hidden="true"><svg width="14" height="14" viewBox="0 0 16 16" fill="none" aria-hidden="true"><circle cx="6.5" cy="6.5" r="4.5" stroke="currentColor" stroke-width="1.5"></circle><line x1="10.5" y1="10.5" x2="14" y2="14" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"></line></svg></span> <input type="search" class="search-input svelte-1dpy914" placeholder="Search observations, symbols, tasks..." autocomplete="off"${attr("spellcheck", false)} aria-label="Search brain nodes"${attr("aria-expanded", open)} aria-autocomplete="list" aria-haspopup="listbox"${attr("aria-activedescendant", void 0)} role="combobox"${attr("value", query)}/> `);
		$$renderer.push("<!--[-1-->");
		$$renderer.push(`<!--]--> `);
		$$renderer.push("<!--[-1-->");
		$$renderer.push(`<!--]--></div> `);
		$$renderer.push("<!--[-1-->");
		$$renderer.push(`<!--]--></div>`);
		bind_props($$props, { searchInput });
	});
}
//#endregion
//#region src/lib/components/brain/BrainStreamIndicator.svelte
function BrainStreamIndicator($$renderer, $$props) {
	/**
	* Props for {@link BrainStreamIndicator}.
	*/
	/** Whether streaming is currently active. */
	/**
	* Simulation warmup progress [0..100].
	* Drives the corner progress bar. At 100 the bar fades out.
	*/
	let { warmupProgress } = $$props;
	const warmupDone = derived(() => warmupProgress >= 100);
	if (!warmupDone()) {
		$$renderer.push("<!--[0-->");
		$$renderer.push(`<div class="stream-overlay svelte-8cv3a8" aria-live="polite" aria-label="Brain data loading status">`);
		$$renderer.push("<!--[-1-->");
		$$renderer.push(`<!--]--> `);
		if (!warmupDone()) {
			$$renderer.push("<!--[0-->");
			$$renderer.push(`<div class="warmup-bar-wrap svelte-8cv3a8"${attr("aria-label", `Simulation warming up: ${stringify(warmupProgress)}%`)}><span class="warmup-label svelte-8cv3a8">simulation warming ${escape_html(warmupProgress)}%</span> <div class="warmup-track svelte-8cv3a8" role="progressbar"${attr("aria-valuenow", warmupProgress)}${attr("aria-valuemin", 0)}${attr("aria-valuemax", 100)}><div class="warmup-fill svelte-8cv3a8"${attr_style(`width: ${stringify(warmupProgress)}%`)}></div></div></div>`);
		} else $$renderer.push("<!--[-1-->");
		$$renderer.push(`<!--]--></div>`);
	} else $$renderer.push("<!--[-1-->");
	$$renderer.push(`<!--]-->`);
}
//#endregion
//#region src/lib/components/brain/SubstrateLegend.svelte
function SubstrateLegend($$renderer, $$props) {
	$$renderer.component(($$renderer) => {
		/**
		* Props for {@link SubstrateLegend}.
		*/
		/** Which substrates are currently enabled (visible). */
		/** Node counts per substrate for the chip labels. */
		/** Substrates currently firing (drives pulse dot). */
		/** The currently focused (solo-zoomed) substrate, or null. */
		/** Which substrate is in solo mode (all others hidden). */
		/** Fired on click — focus this substrate. */
		/** Fired on shift-click — toggle visibility. */
		/** Fired on double-click — enter or exit solo mode. */
		const ALL_SUBSTRATES = [
			"brain",
			"nexus",
			"tasks",
			"conduit",
			"agent-registry"
		];
		const SUBSTRATE_META = {
			brain: {
				label: "brain",
				colorVar: "var(--info)",
				regionName: "BRAIN"
			},
			nexus: {
				label: "nexus",
				colorVar: "var(--success)",
				regionName: "NEXUS"
			},
			tasks: {
				label: "tasks",
				colorVar: "var(--warning)",
				regionName: "TASKS"
			},
			conduit: {
				label: "conduit",
				colorVar: "var(--accent)",
				regionName: "CONDUIT"
			},
			"agent-registry": {
				label: "agent-registry",
				colorVar: "var(--danger)",
				regionName: "SIGNALDOCK"
			}
		};
		let { enabledSubstrates, nodeCounts, firingSubstrates = /* @__PURE__ */ new Set(), focusSubstrate, soloSubstrate} = $$props;
		$$renderer.push(`<div class="substrate-legend svelte-82sgjp" role="group" aria-label="Substrate filters"><!--[-->`);
		const each_array = ensure_array_like(ALL_SUBSTRATES);
		for (let $$index = 0, $$length = each_array.length; $$index < $$length; $$index++) {
			let s = each_array[$$index];
			const meta = SUBSTRATE_META[s];
			const enabled = enabledSubstrates.has(s);
			const firing = firingSubstrates.has(s);
			const isFocused = focusSubstrate === s;
			const isSolo = soloSubstrate === s;
			const count = nodeCounts[s] ?? 0;
			$$renderer.push(`<button type="button"${attr_class("substrate-chip svelte-82sgjp", void 0, {
				"enabled": enabled,
				"focused": isFocused,
				"solo": isSolo,
				"firing": firing
			})}${attr_style(`--chip-color: ${stringify(meta.colorVar)};`)}${attr("aria-pressed", enabled)}${attr("aria-label", `${stringify(meta.label)}: ${stringify(count)} nodes${stringify(isSolo ? ", solo mode" : "")}${stringify(firing ? ", firing" : "")}`)} title="Click to focus · Shift+click to toggle · Double-click to solo"${attr("data-substrate", s)}><span${attr_class("fire-dot svelte-82sgjp", void 0, { "firing": firing })} aria-hidden="true"></span> <span class="chip-label svelte-82sgjp">${escape_html(meta.label)}</span> <span class="chip-count svelte-82sgjp">${escape_html(count.toLocaleString())}</span> `);
			if (isSolo) {
				$$renderer.push("<!--[0-->");
				$$renderer.push(`<span class="solo-badge svelte-82sgjp" aria-hidden="true">solo</span>`);
			} else $$renderer.push("<!--[-1-->");
			$$renderer.push(`<!--]--></button>`);
		}
		$$renderer.push(`<!--]--> `);
		$$renderer.push("<!--[-1-->");
		$$renderer.push(`<!--]--></div>`);
	});
}
//#endregion
//#region src/routes/brain/+page.svelte
function _page($$renderer, $$props) {
	$$renderer.component(($$renderer) => {
		let { data } = $$props;
		let rawGraph = data.graph;
		let connectionStatus = "connecting";
		let bridge = null;
		const substratePalette = {
			brain: "var(--info)",
			nexus: "var(--success)",
			tasks: "var(--warning)",
			conduit: "var(--accent)",
			"agent-registry": "var(--danger)"
		};
		/**
		* Load phase:
		*   'skeleton' — Phase 0: server HTML delivered, renderer not yet mounted.
		*   'streaming' — Phase 1/2: tier-0 nodes displayed, remainder streaming in.
		*   'ready'     — Phase 2 complete: all nodes rendered.
		*/
		let loadPhase = "skeleton";
		/** Simulation warmup progress [0..100] — driven by ThreeBrainRenderer when available. */
		let warmupProgress = 0;
		let enabledSubstrates = new Set([...ALL_SUBSTRATES]);
		let enabledKinds = new Set(ALL_EDGE_KINDS);
		let minWeight = 0;
		let useTimeSlider = false;
		let viewMode = "3d";
		let selectedNode = null;
		/**
		* Substrate drill-down target. `null` means full brain. Setting this
		* animates the 3D camera to that substrate's centroid.
		*/
		let focusSubstrate = null;
		/**
		* Solo substrate — when set, all other substrates are hidden. Double-click
		* a SubstrateLegend chip to enter, double-click again to exit.
		*/
		let soloSubstrate = null;
		/** Whether the 3D renderer draws edge line segments. */
		let showSynapses = false;
		/** When true, hide intra-substrate edges and show only bridge edges. */
		let showBridgesOnly = false;
		/** When true, pause the ambient d3 sim breathing. */
		let breathingPaused = false;
		/**
		* Rolling firing rate history for each substrate. Each entry is a rate
		* value in [0..100]. Capped at HISTORY_SAMPLES samples.
		*/
		let firingHistory = {
			brain: [],
			nexus: [],
			tasks: [],
			conduit: [],
			"agent-registry": []
		};
		/** Currently-firing substrates (drives pulse dots). */
		let firingSubstrates = /* @__PURE__ */ new Set();
		/** Recent bridge events for the Active Bridges strip. */
		let recentBridgeEvents = [];
		function toGraphNode(n, degree, maxDegree) {
			const isHub = degree / Math.max(1, maxDegree) > .55 || (n.weight ?? 0) >= .85;
			return {
				id: n.id,
				substrate: n.substrate,
				kind: n.kind,
				label: n.label,
				category: n.meta?.cluster_id ?? n.substrate,
				weight: n.weight,
				freshness: freshnessFor(n),
				meta: {
					...n.meta,
					isHub
				}
			};
		}
		function toGraphEdge(e, idx) {
			const kind = ALL_EDGE_KINDS.includes(e.type) ? e.type : "relates_to";
			const sourceSubstrate = rawGraph.nodes.find((n) => n.id === e.source)?.substrate;
			const targetSubstrate = rawGraph.nodes.find((n) => n.id === e.target)?.substrate;
			const isBridge = sourceSubstrate !== void 0 && targetSubstrate !== void 0 && sourceSubstrate !== targetSubstrate;
			return {
				id: `e${idx}:${e.source}>${e.target}:${e.type}`,
				source: e.source,
				target: e.target,
				kind,
				weight: e.weight,
				directional: true,
				meta: {
					isBridge,
					bridgeType: isBridge ? `${sourceSubstrate}->${targetSubstrate}` : void 0
				}
			};
		}
		function freshnessFor(n) {
			if (!n.createdAt) return .3;
			const t = Date.parse(n.createdAt);
			if (!Number.isFinite(t)) return .3;
			const age = Math.max(0, Date.now() - t);
			return Math.max(.15, 1 - age / (720 * 60 * 60 * 1e3));
		}
		let filterDate = derived(() => null);
		/**
		* Compute the effective enabled substrates, accounting for solo mode.
		* When soloSubstrate is set, only that substrate's nodes are shown.
		*/
		let effectiveSubstrates = derived(() => {
			return enabledSubstrates;
		});
		let filteredRaw = derived(() => {
			const filteredNodes = rawGraph.nodes.filter((n) => {
				if (!effectiveSubstrates().has(n.substrate)) return false;
				if ((n.weight ?? 1) < minWeight) return false;
				if (filterDate() !== null && n.createdAt !== null && n.createdAt.slice(0, 10) > filterDate()) return false;
				return true;
			});
			const allowedIds = new Set(filteredNodes.map((n) => n.id));
			return {
				nodes: filteredNodes,
				edges: rawGraph.edges.filter((e) => {
					if (!allowedIds.has(e.source) || !allowedIds.has(e.target)) return false;
					const kind = ALL_EDGE_KINDS.includes(e.type) ? e.type : "relates_to";
					if (!enabledKinds.has(kind)) return false;
					return true;
				})
			};
		});
		let renderGraph = derived(() => {
			const { nodes: ns, edges: es } = filteredRaw();
			const serverBridges = data.bridges ?? [];
			const nodeIdSet = new Set(ns.map((n) => n.id));
			const visibleBridges = serverBridges.filter((b) => nodeIdSet.has(b.source) && nodeIdSet.has(b.target));
			const degree = /* @__PURE__ */ new Map();
			for (const e of es) {
				degree.set(e.source, (degree.get(e.source) ?? 0) + 1);
				degree.set(e.target, (degree.get(e.target) ?? 0) + 1);
			}
			for (const b of visibleBridges) {
				degree.set(b.source, (degree.get(b.source) ?? 0) + 1);
				degree.set(b.target, (degree.get(b.target) ?? 0) + 1);
			}
			const maxDegree = Math.max(1, ...degree.values());
			const allEdges = [...es.map((e, i) => toGraphEdge(e, i)), ...visibleBridges];
			const edges = allEdges;
			return {
				nodes: ns.map((n) => toGraphNode(n, degree.get(n.id) ?? 0, maxDegree)),
				edges
			};
		});
		let totalNodes = derived(() => renderGraph().nodes.length);
		let totalEdges = derived(() => renderGraph().edges.length);
		let hubNodes = derived(() => renderGraph().nodes.filter((n) => n.meta?.isHub === true));
		const REGION_NAMES = {
			brain: "BRAIN",
			nexus: "NEXUS",
			tasks: "TASKS",
			conduit: "CONDUIT",
			"agent-registry": "SIGNALDOCK"
		};
		/**
		* Bridge edge count per substrate — edges where source and target have
		* different substrates, involving this substrate.
		*/
		const bridgeCounts = derived(() => {
			const counts = {
				brain: 0,
				nexus: 0,
				tasks: 0,
				conduit: 0,
				"agent-registry": 0
			};
			for (const edge of renderGraph().edges) {
				if (edge.meta?.isBridge !== true) continue;
				const srcNode = renderGraph().nodes.find((n) => n.id === edge.source);
				const tgtNode = renderGraph().nodes.find((n) => n.id === edge.target);
				if (srcNode) counts[srcNode.substrate] = (counts[srcNode.substrate] ?? 0) + 1;
				if (tgtNode) counts[tgtNode.substrate] = (counts[tgtNode.substrate] ?? 0) + 1;
			}
			return counts;
		});
		const regionStats = derived(() => ALL_SUBSTRATES.map((s) => ({
			substrate: s,
			regionName: REGION_NAMES[s],
			neuronCount: rawGraph.counts.nodes[s] ?? 0,
			firingRate: (firingHistory[s]?.slice(-5) ?? []).reduce((a, b) => a + b, 0) / Math.max(1, (firingHistory[s]?.slice(-5) ?? []).length),
			bridgeCount: bridgeCounts()[s] ?? 0,
			history: firingHistory[s] ?? [],
			firing: firingSubstrates.has(s),
			colorVar: substratePalette[s]
		})));
		let searchInput = null;
		onDestroy(() => {
			bridge?.dispose();
			bridge = null;
		});
		function handleSearchResultSelect(node) {
			selectedNode = node;
			focusSubstrate = node.substrate;
		}
		const tabItems = [{
			value: "3d",
			label: "3D canvas"
		}, {
			value: "flat",
			label: "Flat 2D"
		}];
		function statusTone(status) {
			switch (status) {
				case "connected": return "success";
				case "connecting":
				case "error": return "warning";
				case "disconnected": return "neutral";
				default: return "neutral";
			}
		}
		let $$settled = true;
		let $$inner_renderer;
		function $$render_inner($$renderer) {
			head("9heiib", $$renderer, ($$renderer) => {
				$$renderer.title(($$renderer) => {
					$$renderer.push(`<title>Brain — CLEO Studio</title>`);
				});
				$$renderer.push(`<meta name="description" content="Living 3D neural map of CLEO's BRAIN, NEXUS, TASKS, CONDUIT, and SIGNALDOCK substrates."/>`);
			});
			$$renderer.push(`<div class="brain-shell svelte-9heiib" data-brain-shell=""><header class="brain-header svelte-9heiib"><div class="brain-header-top svelte-9heiib">`);
			Breadcrumb($$renderer, { items: [{
				label: "CLEO Studio",
				href: "/"
			}, { label: "Brain" }] });
			$$renderer.push(`<!----> `);
			BrainSearchBar($$renderer, {
				nodes: renderGraph().nodes,
				onResultSelect: handleSearchResultSelect,
				get searchInput() {
					return searchInput;
				},
				set searchInput($$value) {
					searchInput = $$value;
					$$settled = false;
				}
			});
			$$renderer.push(`<!----> <div class="brain-live svelte-9heiib">`);
			Badge($$renderer, {
				tone: statusTone(connectionStatus),
				pill: true,
				size: "sm",
				children: ($$renderer) => {
					{
						$$renderer.push("<!--[1-->");
						$$renderer.push(`Connecting…`);
					}
					$$renderer.push(`<!--]-->`);
				}});
			$$renderer.push(`<!----> <span class="brain-live-counts svelte-9heiib"><span class="num svelte-9heiib">${escape_html(totalNodes())}</span> nodes<span class="sep svelte-9heiib">·</span> <span class="num svelte-9heiib">${escape_html(totalEdges())}</span> edges `);
			if (rawGraph.truncated) {
				$$renderer.push("<!--[0-->");
				Badge($$renderer, {
					tone: "warning",
					size: "sm",
					children: ($$renderer) => {
						$$renderer.push(`<!---->truncated`);
					}});
			} else $$renderer.push("<!--[-1-->");
			$$renderer.push(`<!--]--></span></div></div> <div class="brain-header-hero svelte-9heiib"><div class="hero-label svelte-9heiib">Living substrate · macro view</div> <h1 class="hero-title svelte-9heiib">Cortical nebula of CLEO.</h1> <p class="hero-sub svelte-9heiib">One pane, five substrates, one physics. Click any node to open its provenance;
        hover to trace live synapses across BRAIN, NEXUS, TASKS, CONDUIT, and SIGNALDOCK.</p></div> <div class="brain-controls cluster-flow svelte-9heiib">`);
			Tabs($$renderer, {
				items: tabItems,
				label: "Canvas mode",
				get value() {
					return viewMode;
				},
				set value($$value) {
					viewMode = $$value;
					$$settled = false;
				}
			});
			$$renderer.push(`<!----> `);
			SubstrateLegend($$renderer, {
				enabledSubstrates,
				nodeCounts: rawGraph.counts.nodes,
				firingSubstrates,
				focusSubstrate,
				soloSubstrate});
			$$renderer.push(`<!----> <label class="weight-block svelte-9heiib"><span class="weight-label svelte-9heiib">min weight</span> <input type="range" min="0" max="1" step="0.05"${attr("value", minWeight)} class="range svelte-9heiib" aria-label="Minimum node weight"/> <span class="weight-val svelte-9heiib">${escape_html(minWeight.toFixed(2))}</span></label> <div class="time-block svelte-9heiib"><button type="button"${attr_class("time-chip svelte-9heiib", void 0, { "active": useTimeSlider })}${attr("aria-pressed", useTimeSlider)}>Time</button> `);
			$$renderer.push("<!--[-1-->");
			$$renderer.push(`<!--]--></div> <div class="kbd-strip svelte-9heiib" aria-label="Keyboard shortcuts"><span class="kbd-item svelte-9heiib"><kbd class="svelte-9heiib">1–5</kbd> focus substrate</span> <span class="kbd-item svelte-9heiib"><kbd class="svelte-9heiib">0</kbd> clear</span> <span class="kbd-item svelte-9heiib"><kbd class="svelte-9heiib">f</kbd> fit</span> <span class="kbd-item svelte-9heiib"><kbd class="svelte-9heiib">/</kbd> search</span> <span class="kbd-item svelte-9heiib"><kbd class="svelte-9heiib">s</kbd> synapses</span> <span class="kbd-item svelte-9heiib"><kbd class="svelte-9heiib">b</kbd> bridges</span> <span class="kbd-item svelte-9heiib"><kbd class="svelte-9heiib">Esc</kbd> dismiss</span></div></div></header> <main id="main" class="brain-body svelte-9heiib" tabindex="-1"><section class="brain-canvas-wrap svelte-9heiib" aria-label="Brain canvas">`);
			BrainLoadingSkeleton($$renderer, {
				visible: loadPhase === "skeleton",
				height: "100%"
			});
			$$renderer.push(`<!----> <div class="edge-rail svelte-9heiib" aria-hidden="true"></div> <div${attr_class("brain-canvas-host svelte-9heiib", void 0, { "skeleton-visible": loadPhase === "skeleton" })}>`);
			if (viewMode === "3d") {
				$$renderer.push("<!--[0-->");
				ThreeBrainRenderer($$renderer, {
					nodes: renderGraph().nodes,
					edges: renderGraph().edges,
					height: "100%"
				});
			} else {
				$$renderer.push("<!--[-1-->");
				LivingBrainCosmograph($$renderer, {
					nodes: renderGraph().nodes,
					edges: renderGraph().edges,
					height: "100%"});
			}
			$$renderer.push(`<!--]--></div> `);
			BrainStreamIndicator($$renderer, {
				warmupProgress
			});
			$$renderer.push(`<!----> `);
			$$renderer.push("<!--[-1-->");
			$$renderer.push(`<!--]--></section> <aside class="brain-side svelte-9heiib" aria-label="Brain monitor and node detail">`);
			BrainMonitorPanel($$renderer, {
				selectedNode,
				edges: renderGraph().edges,
				nodes: renderGraph().nodes,
				regionStats: regionStats(),
				bridgeEvents: recentBridgeEvents});
			$$renderer.push(`<!----> `);
			if (!selectedNode && hubNodes().length > 0) {
				$$renderer.push("<!--[0-->");
				$$renderer.push(`<div class="hub-panel svelte-9heiib"><div class="hub-eyebrow svelte-9heiib">Hub nodes · ${escape_html(hubNodes().length)}</div> <ul class="node-list svelte-9heiib" role="list"><!--[-->`);
				const each_array = ensure_array_like(hubNodes().slice(0, 80));
				for (let $$index = 0, $$length = each_array.length; $$index < $$length; $$index++) {
					let hub = each_array[$$index];
					$$renderer.push(`<li><button type="button" class="node-row svelte-9heiib"><span class="row-dot svelte-9heiib"${attr_style(`--row-tint: ${stringify(substratePalette[hub.substrate])}`)} aria-hidden="true"></span> <span class="row-label svelte-9heiib">${escape_html(hub.label)}</span> <span class="row-meta svelte-9heiib">${escape_html(hub.substrate)}</span></button></li>`);
				}
				$$renderer.push(`<!--]--></ul></div>`);
			} else $$renderer.push("<!--[-1-->");
			$$renderer.push(`<!--]--></aside></main> `);
			BrainControlsDock($$renderer, {
				enabledKinds,
				showSynapses,
				showBridgesOnly,
				breathingPaused});
			$$renderer.push(`<!----></div>`);
		}
		do {
			$$settled = true;
			$$inner_renderer = $$renderer.copy();
			$$render_inner($$inner_renderer);
		} while (!$$settled);
		$$renderer.subsume($$inner_renderer);
	});
}

export { _page as default };
//# sourceMappingURL=_page.svelte-8fLXUNL5.js.map
