import { Boxes, AlertTriangle, BriefcaseBusiness, CheckCircle2, ClipboardCheck, Database, Eye, FileText, GitBranch, ListChecks, Map, Play, RefreshCw, } from "lucide-react"; import { EpiphanyGraphViewer, validateEpiphanyGraphsState } from "@epiphanygraph/epiphany-graph-viewer"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { createAquariumRenderer } from "./aquariumFluid"; import { loadOperatorSnapshot, runOperatorAction } from "./operatorApi"; import type { ArtifactBundle, OperatorAction, OperatorActionResult, OperatorSnapshot, StatusRequest } from "./types"; import type { EpiphanyCodeRef, EpiphanyGraphsState } from "@epiphanygraph/epiphany-graph-viewer"; import type { AquariumAgentProjection, AquariumOptionFrame, AquariumRenderer, AquariumUiFrame } from "./aquariumFluid"; const roleOrder = ["implementation", "imagination", "research", "eyes", "modeling", "verification", "reorientation"]; const constellationSpecs = [ { id: "coordinator", laneId: "coordinator", name: "Self", title: "Coordinator", glyph: "S", shape: "core", color: "#f15f45", glow: "#f7bd58", baseX: 49, baseY: 43, driftX: 1.9, driftY: 1.4, phase: 0.2, }, { id: "imagination", laneId: "imagination", name: "Imagination", title: "Planner", glyph: "I", shape: "kite", color: "#9f6ee7", glow: "#eb8fc9", baseX: 29, baseY: 25, driftX: 2.3, driftY: 1.6, phase: 1.4, }, { id: "research", laneId: "research", name: "Eyes", title: "Research", glyph: "E", shape: "lens", color: "#2877b8", glow: "#63c5da", baseX: 80, baseY: 23, driftX: 2.1, driftY: 1.7, phase: 2.1, }, { id: "modeling", laneId: "modeling", name: "Body", title: "Modeling", glyph: "B", shape: "hex", color: "#2f9b67", glow: "#92d876", baseX: 21, baseY: 58, driftX: 1.8, driftY: 1.5, phase: 3.2, }, { id: "implementation", laneId: "implementation", name: "Hands", title: "Implementation", glyph: "H", shape: "capsule", color: "#cf5a2f", glow: "#f1ad4e", baseX: 48, baseY: 64, driftX: 2.6, driftY: 1.2, phase: 4.4, }, { id: "verification", laneId: "verification", name: "Soul", title: "Verification", glyph: "V", shape: "diamond", color: "#4e63b6", glow: "#a6a9f4", baseX: 78, baseY: 61, driftX: 1.7, driftY: 1.9, phase: 5.2, }, { id: "reorientation", laneId: "reorientation", name: "Life", title: "Continuity", glyph: "L", shape: "seed", color: "#148d87", glow: "#58ddc4", baseX: 63, baseY: 29, driftX: 1.4, driftY: 2.2, phase: 6.0, }, ] as const; type ConstellationSpec = (typeof constellationSpecs)[number]; type ProjectedAgent = ConstellationSpec & { status: string; tone: string; thought: string; detail: string; activity: number; jobs: number; review: string; }; type AquariumOption = { label: string; deck?: DeckId; subdeck?: string; action?: OperatorAction; }; const deckSubmenus = { command: ["run", "connection", "signals"], state: ["environment", "planning", "graph"], agents: ["lanes", "findings", "jobs"], artifacts: ["bundles"], } as const; const deckLabels: Record = { command: "Command", state: "State", agents: "Agents", artifacts: "Artifacts", }; type DeckId = keyof typeof deckSubmenus; const aquariumOptionsByAgent: Record = { coordinator: [ { label: "Signals", deck: "command", subdeck: "signals" }, { label: "Run", deck: "command", subdeck: "run" }, { label: "Checkpoint", action: "prepareCheckpoint" }, ], imagination: [ { label: "Planning", deck: "state", subdeck: "planning" }, { label: "Launch", action: "launchImagination" }, { label: "Read", action: "readImaginationResult" }, { label: "Accept", action: "acceptImagination" }, ], research: [ { label: "State", deck: "state", subdeck: "graph" }, { label: "Artifacts", deck: "artifacts", subdeck: "bundles" }, ], modeling: [ { label: "Graph", deck: "state", subdeck: "graph" }, { label: "Launch", action: "launchModeling" }, { label: "Read", action: "readModelingResult" }, { label: "Accept", action: "acceptModeling" }, ], implementation: [ { label: "Run", deck: "command", subdeck: "run" }, { label: "Continue", action: "continueImplementation" }, { label: "Artifacts", deck: "artifacts", subdeck: "bundles" }, ], verification: [ { label: "Findings", deck: "agents", subdeck: "findings" }, { label: "Launch", action: "launchVerification" }, { label: "Read", action: "readVerificationResult" }, { label: "Accept", action: "acceptVerification" }, ], reorientation: [ { label: "Continuity", deck: "command", subdeck: "signals" }, { label: "Launch", action: "launchReorient" }, { label: "Read", action: "readReorientResult" }, { label: "Accept", action: "acceptReorient" }, ], }; const actionButtons: Array<{ action: OperatorAction; label: string; runningLabel: string; title: string; requiresThread?: boolean; requiresReadyState?: boolean; requiresImaginationPatch?: boolean; requiresModelingPatch?: boolean; requiresVerificationResult?: boolean; requiresReorientResult?: boolean; requiresPlanningDraft?: boolean; requiresContinueImplementation?: boolean; icon: "file" | "check" | "play" | "eye" | "accept" | "runtime" | "plan" | "ide"; }> = [ { action: "statusSnapshot", label: "Status Snapshot", runningLabel: "Writing", title: "Write an auditable status snapshot", icon: "file", }, { action: "coordinatorPlan", label: "Coordinator Plan", runningLabel: "Running", title: "Run a review-gated coordinator plan", icon: "check", }, { action: "inspectUnity", label: "Inspect Unity", runningLabel: "Inspecting", title: "Resolve the project-pinned Unity editor and write runtime artifacts", icon: "runtime", }, { action: "inspectRider", label: "Inspect Rider", runningLabel: "Inspecting", title: "Inspect Rider, solution, and source control status through the local bridge", icon: "ide", }, { action: "prepareCheckpoint", label: "Prepare Checkpoint", runningLabel: "Preparing", title: "Seed durable Epiphany state for this GUI operator thread", icon: "accept", }, { action: "adoptObjectiveDraft", label: "Adopt Draft", runningLabel: "Adopting", title: "Adopt the selected Objective Draft as the active implementation objective", requiresThread: true, requiresReadyState: true, requiresPlanningDraft: true, icon: "plan", }, { action: "continueImplementation", label: "Continue Implementation", runningLabel: "Implementing", title: "Run a bounded implementation turn when the coordinator has cleared specialist lanes", requiresThread: true, requiresReadyState: true, requiresContinueImplementation: true, icon: "play", }, { action: "launchImagination", label: "Launch Imagination", runningLabel: "Launching", title: "Launch the fixed imagination/planning worker for this thread", requiresThread: true, requiresReadyState: true, icon: "play", }, { action: "readImaginationResult", label: "Read Imagination", runningLabel: "Reading", title: "Read the latest imagination/planning finding", requiresThread: true, icon: "eye", }, { action: "acceptImagination", label: "Accept Imagination", runningLabel: "Accepting", title: "Accept a reviewed planning-only patch into Epiphany state", requiresThread: true, requiresReadyState: true, requiresImaginationPatch: true, icon: "accept", }, { action: "launchModeling", label: "Launch Modeling", runningLabel: "Launching", title: "Launch the fixed modeling/checkpoint worker for this thread", requiresThread: true, requiresReadyState: true, icon: "play", }, { action: "readModelingResult", label: "Read Modeling", runningLabel: "Reading", title: "Read the latest modeling/checkpoint finding", requiresThread: true, icon: "eye", }, { action: "acceptModeling", label: "Accept Modeling", runningLabel: "Accepting", title: "Accept a reviewed modeling graph/checkpoint patch into Epiphany state", requiresThread: true, requiresReadyState: true, requiresModelingPatch: true, icon: "accept", }, { action: "launchVerification", label: "Launch Verification", runningLabel: "Launching", title: "Launch the fixed verification/review worker for this thread", requiresThread: true, requiresReadyState: true, icon: "play", }, { action: "readVerificationResult", label: "Read Verification", runningLabel: "Reading", title: "Read the latest verification/review finding", requiresThread: true, icon: "eye", }, { action: "acceptVerification", label: "Accept Verification", runningLabel: "Accepting", title: "Accept a reviewed verification finding into Epiphany state", requiresThread: true, requiresReadyState: true, requiresVerificationResult: true, icon: "accept", }, { action: "launchReorient", label: "Launch Reorient", runningLabel: "Launching", title: "Launch the bounded reorient-worker for this thread", requiresThread: true, requiresReadyState: true, icon: "play", }, { action: "readReorientResult", label: "Read Reorient", runningLabel: "Reading", title: "Read the latest reorient-worker finding", requiresThread: true, icon: "eye", }, { action: "acceptReorient", label: "Accept Reorient", runningLabel: "Accepting", title: "Accept a completed reorient-worker finding into Epiphany state", requiresThread: true, requiresReadyState: true, requiresReorientResult: true, icon: "accept", }, ]; function text(value: unknown, fallback = "none"): string { if (value === null || value === undefined || value === "") { return fallback; } if (typeof value === "string") { return value; } if (typeof value === "number" || typeof value === "boolean") { return String(value); } return fallback; } function displayLabel(value: unknown, fallback = "none"): string { return text(value, fallback).replace(/([a-z])([A-Z])/g, "$1 $2"); } function listText(value: unknown, fallback = "none"): string { return Array.isArray(value) && value.length > 0 ? value.map(String).join(", ") : fallback; } function objectList(value: unknown): any[] { return Array.isArray(value) ? value.filter((item) => item && typeof item === "object") : []; } function countText(value: unknown): string { return typeof value === "number" ? String(value) : text(value, "0"); } function statusClass(value: unknown): string { const lower = text(value).toLowerCase(); if (lower.includes("blocked") || lower.includes("critical") || lower.includes("regather")) return "danger"; if (lower.includes("needed") || lower.includes("review") || lower.includes("prepare") || lower.includes("high")) return "warn"; if (lower.includes("completed") || lower.includes("ready") || lower.includes("continue") || lower.includes("pass")) return "ok"; return "neutral"; } function projectedThought(value: unknown, fallback: string): string { const cleaned = text(value, fallback).replace(/\s+/g, " ").trim(); if (cleaned.length <= 136) return cleaned; return `${cleaned.slice(0, 132).trim()}...`; } function projectedActivity(status: unknown, jobCount = 0): number { const lower = text(status).toLowerCase(); const jobBoost = Math.min(jobCount * 0.06, 0.18); if (lower.includes("critical") || lower.includes("panic") || lower.includes("fatal")) return 1; if (lower.includes("failed") || lower.includes("error") || lower.includes("high")) return 0.74 + jobBoost; if (lower.includes("running") || lower.includes("launch") || lower.includes("active")) return 0.58 + jobBoost; if (lower.includes("blocked") || lower.includes("needed") || lower.includes("regather")) return 0.38 + jobBoost; if (lower.includes("prepare") || lower.includes("review") || lower.includes("ready")) return 0.3 + jobBoost; if (lower.includes("completed") || lower.includes("continue") || lower.includes("pass")) return 0.24 + jobBoost; if (lower.includes("idle")) return 0.12 + jobBoost; return 0.22 + jobBoost; } function findingSummary(result: any): string | undefined { const finding = result?.finding; return finding?.summary ?? finding?.nextSafeMove ?? finding?.mode ?? finding?.verdict ?? result?.note; } const emptyGraphState: EpiphanyGraphsState = { architecture: { nodes: [], edges: [] }, dataflow: { nodes: [], edges: [] }, links: [], }; function normalizeGraphState(value: any): EpiphanyGraphsState { if (!value || typeof value !== "object") return emptyGraphState; return { architecture: normalizeGraph(value.architecture), dataflow: normalizeGraph(value.dataflow), links: objectList(value.links).map((link) => ({ dataflow_node_id: text(link.dataflow_node_id ?? link.dataflowNodeId, ""), architecture_node_id: text(link.architecture_node_id ?? link.architectureNodeId, ""), relationship: link.relationship ?? null, code_refs: normalizeCodeRefs(link.code_refs ?? link.codeRefs), })).filter((link) => link.dataflow_node_id && link.architecture_node_id), }; } function normalizeGraph(value: any) { return { nodes: objectList(value?.nodes).map((node) => ({ id: text(node.id, ""), title: text(node.title ?? node.id, "Untitled node"), purpose: text(node.purpose ?? node.summary, "No purpose recorded."), mechanism: node.mechanism ?? null, metaphor: node.metaphor ?? null, status: node.status ?? null, code_refs: normalizeCodeRefs(node.code_refs ?? node.codeRefs), })).filter((node) => node.id), edges: objectList(value?.edges).map((edge) => ({ id: edge.id ?? null, source_id: text(edge.source_id ?? edge.sourceId, ""), target_id: text(edge.target_id ?? edge.targetId, ""), kind: text(edge.kind, "link"), label: edge.label ?? null, mechanism: edge.mechanism ?? null, code_refs: normalizeCodeRefs(edge.code_refs ?? edge.codeRefs), })).filter((edge) => edge.source_id && edge.target_id), }; } function normalizeCodeRefs(value: any): EpiphanyCodeRef[] { return objectList(value).map((ref) => ({ path: text(ref.path, ""), start_line: typeof ref.start_line === "number" ? ref.start_line : ref.startLine, end_line: typeof ref.end_line === "number" ? ref.end_line : ref.endLine, symbol: ref.symbol ?? null, note: ref.note ?? null, })).filter((ref) => ref.path); } function graphRecordCount(state: EpiphanyGraphsState): number { return state.architecture.nodes.length + state.architecture.edges.length + state.dataflow.nodes.length + state.dataflow.edges.length + state.links.length; } function codeRefLabel(ref: EpiphanyCodeRef): string { const line = ref.start_line ? `:${ref.start_line}` : ""; const symbol = ref.symbol ? ` ${ref.symbol}` : ""; return `${ref.path}${line}${symbol}`; } function useSnapshot() { const [snapshot, setSnapshot] = useState(null); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [actionResult, setActionResult] = useState(null); const [runningAction, setRunningAction] = useState(null); const [request, setRequest] = useState({}); async function refresh(nextRequest = request) { setLoading(true); setError(null); try { const result = await loadOperatorSnapshot(nextRequest); setSnapshot(result); const loadedThreadId = result.status?.threadId; const loadedState = result.status?.scene?.scene?.stateStatus; if ( !nextRequest.threadId && loadedState !== "missing" && typeof loadedThreadId === "string" && loadedThreadId.length > 0 ) { setRequest((current) => (current.threadId ? current : { ...current, threadId: loadedThreadId })); } } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setLoading(false); } } async function runAction(action: OperatorAction) { setRunningAction(action); setError(null); setActionResult(null); try { const result = await runOperatorAction(action, request); setActionResult(result); const nextRequest = result.threadId ? { ...request, threadId: result.threadId } : request; if (result.threadId) { setRequest(nextRequest); } await refresh(nextRequest); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setRunningAction(null); } } useEffect(() => { void refresh({}); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return { snapshot, loading, error, request, setRequest, refresh, actionResult, runningAction, runAction }; } export function App() { const { snapshot, loading, error, request, setRequest, refresh, actionResult, runningAction, runAction } = useSnapshot(); const [selectedCodeRef, setSelectedCodeRef] = useState(null); const [activeDeck, setActiveDeck] = useState("command"); const [subdeckByDeck, setSubdeckByDeck] = useState>({ command: "run", state: "environment", agents: "lanes", artifacts: "bundles", }); const status = snapshot?.status; const scene = status?.scene?.scene ?? {}; const pressure = status?.pressure?.pressure ?? {}; const reorient = status?.reorient?.decision ?? {}; const crrc = status?.crrc?.recommendation ?? {}; const coordinator = status?.coordinator ?? {}; const roles = useMemo(() => { const lanes = status?.roles?.roles; if (!Array.isArray(lanes)) return []; return [...lanes].sort((a, b) => roleOrder.indexOf(text(a.id)) - roleOrder.indexOf(text(b.id))); }, [status]); const jobs: any[] = Array.isArray(status?.jobs?.jobs) ? status.jobs.jobs : []; const planningResponse = status?.planning ?? {}; const planningState = planningResponse?.planning ?? {}; const planningSummary = planningResponse?.summary ?? {}; const planningCaptures = objectList(planningState?.captures); const backlogItems = objectList(planningState?.backlog_items ?? planningState?.backlogItems); const roadmapStreams = objectList(planningState?.roadmap_streams ?? planningState?.roadmapStreams); const objectiveDrafts = objectList(planningState?.objective_drafts ?? planningState?.objectiveDrafts); const roleResults = status?.roleResults ?? {}; const reorientResult = status?.reorientResult ?? {}; const latestArtifact = snapshot?.artifacts?.[0]; const latestImplementationArtifact = useMemo( () => (snapshot?.artifacts ?? []).find((artifact) => artifact.implementationAudit), [snapshot?.artifacts], ); const latestImplementationAudit = latestImplementationArtifact?.implementationAudit; const latestRuntimeArtifact = useMemo( () => (snapshot?.artifacts ?? []).find((artifact) => artifact.runtimeAudit), [snapshot?.artifacts], ); const latestRuntimeAudit = latestRuntimeArtifact?.runtimeAudit; const latestRiderArtifact = useMemo( () => (snapshot?.artifacts ?? []).find((artifact) => artifact.riderAudit), [snapshot?.artifacts], ); const latestRiderAudit = latestRiderArtifact?.riderAudit; const implementationNoDiffPending = Boolean(latestArtifact?.implementationAudit) && latestArtifact?.implementationAudit?.workspaceChanged === false; const readyState = scene.stateStatus === "ready"; const currentThreadId = request.threadId; const imaginationFinding = roleResults?.imagination?.finding; const canAcceptImagination = text(roleResults?.imagination?.status).toLowerCase() === "completed" && Boolean(imaginationFinding?.statePatch?.planning); const modelingFinding = roleResults?.modeling?.finding; const canAcceptModeling = text(roleResults?.modeling?.status).toLowerCase() === "completed" && Boolean(modelingFinding?.statePatch); const canAcceptVerification = text(roleResults?.verification?.status).toLowerCase() === "completed"; const canAcceptReorient = text(reorientResult?.status).toLowerCase() === "completed"; const canContinueImplementation = text(coordinator.action).toLowerCase() === "continueimplementation"; const selectedDraft = objectiveDrafts.find((draft) => text(draft.id, "") === request.planningDraftId); const selectedDraftStatus = text(selectedDraft?.status).toLowerCase(); const canAdoptDraft = Boolean(selectedDraft) && !["adopted", "rejected", "superseded"].includes(selectedDraftStatus); const unityBridge = latestRuntimeAudit?.editorBridge; const installedEditors = latestRuntimeAudit?.installedEditors ?? []; const candidatePaths = latestRuntimeAudit?.candidatePaths ?? []; const searchRoots = latestRuntimeAudit?.searchRoots ?? []; const unityBridgeReady = latestRuntimeAudit?.status === "ready" && unityBridge?.exists === true; const epiphanyState = status?.read?.thread?.epiphanyState ?? status?.scene?.scene?.epiphanyState ?? {}; const graphState = useMemo(() => normalizeGraphState(epiphanyState?.graphs), [epiphanyState]); const graphIssues = useMemo(() => validateEpiphanyGraphsState(graphState), [graphState]); const graphCount = graphRecordCount(graphState); const riderInstallations = latestRiderAudit?.installations ?? []; const riderSearchRoots = latestRiderAudit?.searchRoots ?? []; const riderChangedFiles = latestRiderAudit?.vcs?.changedFiles ?? []; const activeSubdeck = subdeckByDeck[activeDeck]; const activeDeckTitle = deckLabels[activeDeck]; const graphMenuActive = activeDeck === "state" && activeSubdeck === "graph"; function selectDeck(deck: DeckId) { setActiveDeck(deck); } function selectSubdeck(deck: DeckId, subdeck: string) { setSubdeckByDeck((current) => ({ ...current, [deck]: subdeck })); } function actionBlocked(action: OperatorAction) { const button = actionButtons.find((item) => item.action === action); if (!button) return true; return Boolean( runningAction !== null || (button.requiresThread && !currentThreadId) || (button.requiresReadyState && !readyState) || (button.requiresImaginationPatch && !canAcceptImagination) || (button.requiresModelingPatch && !canAcceptModeling) || (button.requiresVerificationResult && !canAcceptVerification) || (button.requiresReorientResult && !canAcceptReorient) || (button.requiresPlanningDraft && !canAdoptDraft) || (button.requiresContinueImplementation && !canContinueImplementation) || (button.requiresContinueImplementation && implementationNoDiffPending), ); } function handleAquariumOption(option: AquariumOption) { if (option.deck) { selectDeck(option.deck); if (option.subdeck) { selectSubdeck(option.deck, option.subdeck); } } if (option.action && !actionBlocked(option.action)) { void runAction(option.action); } } const actionControls = actionButtons.map((button) => { const needsThread = button.requiresThread && !currentThreadId; const needsState = button.requiresReadyState && !readyState; const needsImagination = button.requiresImaginationPatch && !canAcceptImagination; const needsModeling = button.requiresModelingPatch && !canAcceptModeling; const needsVerification = button.requiresVerificationResult && !canAcceptVerification; const needsReorient = button.requiresReorientResult && !canAcceptReorient; const needsPlanningDraft = button.requiresPlanningDraft && !canAdoptDraft; const needsImplementation = button.requiresContinueImplementation && !canContinueImplementation; const needsNoDiffReview = button.requiresContinueImplementation && implementationNoDiffPending; const disabled = runningAction !== null || needsThread || needsState || needsImagination || needsModeling || needsVerification || needsReorient || needsPlanningDraft || needsImplementation || needsNoDiffReview; const title = needsThread ? "Prepare a checkpoint or enter a persisted thread id first" : needsState ? "Prepare Epiphany state before launching this lane" : needsImagination ? "Read a completed imagination result with a planning patch before accepting it" : needsModeling ? "Read a completed modeling result with a state patch before accepting it" : needsVerification ? "Read a completed verification result before accepting it" : needsReorient ? "Read a completed reorient result before accepting it" : needsPlanningDraft ? "Select a draft objective that has not already been adopted" : needsImplementation ? "Run the coordinator and clear review gates before continuing implementation" : needsNoDiffReview ? "Review the latest no-diff implementation artifact or run another lane before retrying" : button.title; return ( ); }); const aquariumPanelLines = (() => { if (activeDeck === "command" && activeSubdeck === "run") { return [ text(actionResult?.summary, "Choose a bounded operation; review gates stay explicit."), text(actionResult?.artifactPath, "No fresh artifact path."), ]; } if (activeDeck === "command" && activeSubdeck === "connection") { return [ `Thread: ${text(status?.threadId)}`, `State: ${text(scene.stateStatus)} rev ${text(scene.revision)}`, `Repo: ${text(snapshot?.repoRoot)}`, `Draft: ${text(request.planningDraftId)}`, ]; } if (activeDeck === "command" && activeSubdeck === "signals") { return [ `Action: ${text(coordinator.action ?? crrc.action, "unknown")}`, `Target: ${text(coordinator.targetRole ?? crrc.recommendedSceneAction)}`, `Review: ${text(coordinator.requiresReview)}`, `Pressure: ${text(pressure.level)}`, `Reorient: ${text(reorient.action)} / ${text(reorient.nextAction)}`, ]; } if (activeDeck === "state" && activeSubdeck === "environment") { return [ `Unity: ${unityBridgeReady ? "bridge ready" : text(latestRuntimeAudit?.status, "unknown")}`, `Editor: ${text(latestRuntimeAudit?.editorPath, "missing")}`, `Rider: ${text(latestRiderAudit?.status, "unknown")}`, `Solution: ${text(latestRiderAudit?.solutionPath)}`, `Changed files: ${riderChangedFiles.length}`, ]; } if (activeDeck === "state" && activeSubdeck === "planning") { return [ `Captures: ${countText(planningSummary?.captureCount)} / pending ${countText(planningSummary?.pendingCaptureCount)}`, `Backlog: ${countText(planningSummary?.backlogItemCount)} / ready ${countText(planningSummary?.readyBacklogItemCount)}`, `Drafts: ${countText(planningSummary?.objectiveDraftCount)}`, text(selectedDraft?.title, "No draft objective selected."), ]; } if (activeDeck === "state" && activeSubdeck === "graph") { return [ `Architecture: ${graphState.architecture.nodes.length} nodes / ${graphState.architecture.edges.length} edges`, `Dataflow: ${graphState.dataflow.nodes.length} nodes / ${graphState.dataflow.edges.length} edges`, `Links: ${graphState.links.length}`, `Issues: ${graphIssues.length}`, ]; } if (activeDeck === "agents" && activeSubdeck === "lanes") { return roles.slice(0, 8).map((role) => `${text(role.title)}: ${text(role.status)} / ${text(role.note)}`); } if (activeDeck === "agents" && activeSubdeck === "findings") { return [ `Imagination: ${text(roleResults.imagination?.status)}`, `Modeling: ${text(roleResults.modeling?.status)}`, `Verification: ${text(roleResults.verification?.status)}`, `Reorient: ${text(reorientResult?.status)}`, ]; } if (activeDeck === "agents" && activeSubdeck === "jobs") { return jobs.length ? jobs.slice(0, 8).map((job) => `${text(job.id)}: ${text(job.status)} / ${text(job.kind)}`) : ["No jobs loaded."]; } return (snapshot?.artifacts ?? []).length ? (snapshot?.artifacts ?? []).slice(0, 8).map((artifact) => `${artifact.name}: ${artifact.files.length} files`) : ["No dogfood artifact bundles found."]; })(); const aquariumUi: AquariumUiFrame = { eyebrow: "Epiphany MVP", title: "Operator Console", reason: text(coordinator.reason ?? crrc.reason, "No recommendation loaded yet."), activeDeckLabel: activeDeckTitle, activeSubdeck, statuses: [ { label: displayLabel(coordinator.action ?? crrc.action, "unknown"), tone: statusClass(coordinator.action ?? crrc.action) }, { label: `pressure ${text(pressure.level, "unknown")}`, tone: statusClass(pressure.level) }, { label: `continuity ${text(reorient.action, "unknown")}`, tone: statusClass(reorient.action) }, ], deckButtons: (Object.keys(deckSubmenus) as DeckId[]).map((deck) => ({ key: `ui:deck:${deck}`, label: deckLabels[deck], tone: activeDeck === deck ? "warn" : "neutral", })), subdeckButtons: deckSubmenus[activeDeck].map((subdeck) => ({ key: `ui:subdeck:${activeDeck}:${subdeck}`, label: subdeck, tone: activeSubdeck === subdeck ? "warn" : "neutral", })), actionButtons: activeDeck === "command" && activeSubdeck === "run" ? actionButtons.map((button) => ({ key: `ui:action:${button.action}`, label: runningAction === button.action ? button.runningLabel : button.label, disabled: actionBlocked(button.action), tone: actionBlocked(button.action) ? "neutral" : "ok", })) : [], panelTitle: `${activeDeckTitle} / ${activeSubdeck}`, panelLines: aquariumPanelLines, alert: error ?? (latestRuntimeAudit ? `Unity: ${text(latestRuntimeAudit.projectVersion)} is ${text(latestRuntimeAudit.status)}.` : undefined), }; useEffect(() => { if (objectiveDrafts.length === 0) return; const draftIds = new Set(objectiveDrafts.map((draft) => text(draft.id, "")).filter(Boolean)); setRequest((current) => { if (current.planningDraftId && draftIds.has(current.planningDraftId)) { return current; } const firstDraft = objectiveDrafts.find((draft) => text(draft.status).toLowerCase() === "draft") ?? objectiveDrafts[0]; const firstDraftId = text(firstDraft?.id, ""); return firstDraftId ? { ...current, planningDraftId: firstDraftId } : current; }); }, [objectiveDrafts, setRequest]); return (
); } function Panel({ title, icon, children }: { title: string; icon: React.ReactNode; children: React.ReactNode }) { return (
{children}
); } function AgentConstellation({ roles, roleResults, reorientResult, coordinator, crrc, pressure, reorient, jobs, variant = "band", activeDeck, activeSubdeck, ui, onAgentOption, isActionBlocked, }: { roles: any[]; roleResults: any; reorientResult: any; coordinator: any; crrc: any; pressure: any; reorient: any; jobs: any[]; variant?: "band" | "fullscreen"; activeDeck?: DeckId; activeSubdeck?: string; ui?: AquariumUiFrame; onAgentOption?: (option: AquariumOption) => void; isActionBlocked?: (action: OperatorAction) => boolean; }) { const canvasRef = useRef(null); const crispCanvasRef = useRef(null); const optionByKeyRef = useRef(new globalThis.Map()); const uiOptionByKeyRef = useRef(new globalThis.Map()); const rendererRef = useRef(null); const agentNodeRefs = useRef(new globalThis.Map()); const thoughtNodeRefs = useRef(new globalThis.Map()); const [selectedAgentId, setSelectedAgentId] = useState("coordinator"); const agents = useMemo(() => { return constellationSpecs.map((spec) => { const lane = roles.find((role) => text(role.id).toLowerCase() === spec.laneId); const result = roleResults?.[spec.laneId] ?? (spec.id === "research" ? roleResults?.eyes ?? roleResults?.research : undefined); const ownedJobs = jobs.filter((job) => { const owner = text(job.ownerRole).toLowerCase(); const kind = text(job.kind).toLowerCase(); return owner.includes(spec.laneId) || owner.includes(spec.id) || kind.includes(spec.laneId); }); let status = text(lane?.status ?? result?.status, "idle"); let thought = projectedThought( lane?.note ?? findingSummary(result), "Quiet. Waiting for a bounded signal.", ); let detail = text(lane?.ownerRole ?? result?.bindingId, spec.title); let review = result?.finding?.statePatch ? "patch review" : "none"; if (spec.id === "coordinator") { status = text(coordinator?.action ?? crrc?.action, "unknown"); thought = projectedThought( coordinator?.reason ?? crrc?.reason, "No coordinator projection loaded yet.", ); detail = `target ${text(coordinator?.targetRole ?? crrc?.recommendedSceneAction, "none")}`; review = text(coordinator?.requiresReview, "false") === "true" ? "required" : "not required"; } else if (spec.id === "reorientation") { status = text(lane?.status ?? reorient?.action ?? reorientResult?.status, "idle"); thought = projectedThought( lane?.note ?? findingSummary(reorientResult) ?? reorient?.nextAction, "Continuity is quiet.", ); detail = `pressure ${text(pressure?.level, "unknown")}`; review = text(reorientResult?.status).toLowerCase() === "completed" ? "read result" : "none"; } else if (spec.id === "research" && !lane && !result) { status = "idle"; thought = "Watching for proven paths before the machine invents one in a shed."; detail = "future lane"; review = "none"; } return { ...spec, status, tone: statusClass(status), thought, detail, activity: Math.min(projectedActivity(status, ownedJobs.length), 1), jobs: ownedJobs.length, review, }; }); }, [coordinator, crrc, jobs, pressure, reorient, reorientResult, roleResults, roles]); const selectedAgent = agents.find((agent) => agent.id === selectedAgentId) ?? agents[0]; const aquariumAgents = useMemo(() => { const optionsByKey = new globalThis.Map(); const framedAgents = agents.map((agent) => { const options: AquariumOptionFrame[] = (aquariumOptionsByAgent[agent.id] ?? []).map((option, index) => { const key = `${agent.id}:${index}:${option.label}`; optionsByKey.set(key, option); return { key, label: option.label, disabled: option.action ? Boolean(isActionBlocked?.(option.action)) : false, }; }); return { ...agent, options, }; }); optionByKeyRef.current = optionsByKey; return framedAgents; }, [agents, isActionBlocked]); useEffect(() => { const uiOptions = new globalThis.Map(); for (const button of ui?.deckButtons ?? []) { const deck = button.key.split(":")[2] as DeckId | undefined; if (deck && deck in deckLabels) { uiOptions.set(button.key, { label: button.label, deck }); } } for (const button of ui?.subdeckButtons ?? []) { const [, , deck, subdeck] = button.key.split(":"); if (deck && subdeck && deck in deckLabels) { uiOptions.set(button.key, { label: button.label, deck: deck as DeckId, subdeck }); } } for (const button of ui?.actionButtons ?? []) { const action = button.key.split(":")[2] as OperatorAction | undefined; if (action) { uiOptions.set(button.key, { label: button.label, action }); } } uiOptionByKeyRef.current = uiOptions; }, [ui]); useEffect(() => { const canvas = canvasRef.current; const crispCanvas = crispCanvasRef.current; if (!canvas) return; const renderer = createAquariumRenderer(canvas, crispCanvas); rendererRef.current = renderer; return () => { renderer.dispose(); rendererRef.current = null; }; }, []); const bindAgentNode = useCallback((id: string, node: HTMLButtonElement | null) => { if (node) { agentNodeRefs.current.set(id, node); } else { agentNodeRefs.current.delete(id); } }, []); const bindThoughtNode = useCallback((id: string, node: HTMLDivElement | null) => { if (node) { thoughtNodeRefs.current.set(id, node); } else { thoughtNodeRefs.current.delete(id); } }, []); const applyProjectionFrame = useCallback((projections: AquariumAgentProjection[]) => { for (const projection of projections) { const agentNode = agentNodeRefs.current.get(projection.id); const thoughtNode = thoughtNodeRefs.current.get(projection.id); const properties: Array<[string, string]> = [ ["--agent-x", `${projection.xPercent}%`], ["--agent-y", `${projection.yPercent}%`], ["--agent-tilt", `${projection.tilt}deg`], ["--agent-bubble-tilt", `${projection.tilt * 0.32}deg`], ["--agent-glow-pulse", String(projection.glowPulse)], ["--agent-glow-radius", `${14 + projection.glowPulse * 10}px`], ["--agent-hover-glow", `${projection.hover * (6 + projection.glowPulse * 8)}px`], ["--agent-expression", String(projection.expression)], ["--agent-hover", String(projection.hover)], ["--agent-ack", String(projection.acknowledgement)], ["--agent-scale", String(1 + projection.acknowledgement * 0.035 + projection.hover * 0.018)], ]; for (const [name, value] of properties) { agentNode?.style.setProperty(name, value); thoughtNode?.style.setProperty(name, value); } } }, []); useEffect(() => { rendererRef.current?.setFrame({ activeLabel: activeDeck ? `${deckLabels[activeDeck]} / ${activeSubdeck ?? ""}` : undefined, agents: aquariumAgents, onProjectionFrame: applyProjectionFrame, selectedAgentId, ui, variant, }); }, [activeDeck, activeSubdeck, applyProjectionFrame, aquariumAgents, selectedAgentId, ui, variant]); function handlePointerMove(event: React.PointerEvent) { rendererRef.current?.setPointerClient(event.clientX, event.clientY); } function handlePointerDown(event: React.PointerEvent) { event.currentTarget.setPointerCapture(event.pointerId); rendererRef.current?.pointerDownClient(event.clientX, event.clientY); } function handlePointerUp(event: React.PointerEvent) { if (event.currentTarget.hasPointerCapture(event.pointerId)) { event.currentTarget.releasePointerCapture(event.pointerId); } rendererRef.current?.pointerUp(); } function handlePointerLeave() { rendererRef.current?.clearPointer(); rendererRef.current?.pointerUp(); } function handleAgentPointerEnter(agentId: string, event: React.PointerEvent) { rendererRef.current?.setPointerClient(event.clientX, event.clientY); rendererRef.current?.setHoveredAgent(agentId); } function handleAgentPointerMove(event: React.PointerEvent) { rendererRef.current?.setPointerClient(event.clientX, event.clientY); } function handleAgentPointerLeave() { rendererRef.current?.setHoveredAgent(null); } function handleAgentPointerDown(agentId: string) { rendererRef.current?.wakeSoundscape(); rendererRef.current?.acknowledgeAgent(agentId, "touch"); } function handleCanvasClick() { const optionKey = rendererRef.current?.pickOption(); if (optionKey) { const option = optionByKeyRef.current.get(optionKey) ?? uiOptionByKeyRef.current.get(optionKey); if (option) { onAgentOption?.(option); } return; } const agentId = rendererRef.current?.pickAgent(); if (agentId) { setSelectedAgentId(agentId); } } return (
rendererRef.current?.wakeSoundscape()} onKeyDownCapture={() => rendererRef.current?.wakeSoundscape()} > {variant === "band" && (
} />
{text(coordinator?.action ?? crrc?.action, "unknown")} pressure {text(pressure?.level, "unknown")} continuity {text(reorient?.action, "unknown")}
)}
); } function SectionHeader({ title, icon }: { title: string; icon: React.ReactNode }) { return (
{icon}

{title}

); } function ActionIcon({ icon }: { icon: "file" | "check" | "play" | "eye" | "accept" | "runtime" | "plan" | "ide" }) { if (icon === "file") return