Large World graph, agent platform, brain stack & dashboard rebuild

Frontend
- Large World: collapse org/company/team tiers into one expandable React Flow
  hierarchy (WorldFlow) with per-click expand, persisted node positions, a
  compact tree sidebar, wrench multi-select delete across levels, and a sized
  right slide-out (phone/tablet/full) showing an agent summary + drill button.
- Agent page: GitHub-style animated contribution grid (VitalsCard), collapsible
  System Prompt + Personality cards, restructured anatomy cards, bigger avatar
  with name/title header row, Markdown/JSON-aware rendering, brain registry +
  history, avatar generate/upload.
- User-icon menu (Infrastructure/Brains/Tools/Profile/Credits) + ToolPanel;
  Master Planner deploy wizard (Specialists/Swarm/Scheduled/Triggered);
  Team Runs view; reap-progress modal; dashboard is the single live interface.

Backend
- cm-brain crate (.brain as the agent definition) + brain apply/history.
- Hard-purge reap (FK-ordered) + sandbox release + SSE batch-delete.
- Swarm self-verifying loop, mode-aware planner, web.search tool, webhooks
  (migration 0013), org/company/team delete endpoints, scheduler sweeps.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
This commit is contained in:
Omar Sobh
2026-06-22 23:21:54 -07:00
co-authored by Claude Opus 4.8
parent 9f266d5806
commit 34f744734b
123 changed files with 9591 additions and 1098 deletions
@@ -0,0 +1,301 @@
"use client";
// Master Planner — the "+" deploy interface. A mode selector (top-right) picks how
// to deploy: Specialists (domain-expert team) · Swarm (self-verifying loop) ·
// Scheduled (date/time) · Triggered (webhook). You chat with Opus 4.8; it proposes,
// and the build action depends on the mode.
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Activity, CalendarClock, Send, Sparkles, Users, Webhook } from "lucide-react";
const mono = "'JetBrains Mono', ui-monospace, monospace";
type Mode = "specialists" | "swarm" | "scheduled" | "triggered";
const MODES: { key: Mode; label: string; hint: string }[] = [
{ key: "specialists", label: "Specialists", hint: "domain experts" },
{ key: "swarm", label: "Swarm", hint: "self-verifying loop" },
{ key: "scheduled", label: "Scheduled", hint: "date / time" },
{ key: "triggered", label: "Triggered", hint: "webhook" },
];
const INTRO: Record<Mode, string> = {
specialists: "Describe what you need — e.g. “a team of specialists for a React Native app: a Rust backend expert, a RN UI dev, and a release engineer.”",
swarm: "Describe a job to verify-loop — e.g. “analyze 100 EV companies; every figure needs a resolvable source URL.” I'll turn it into a checklist the verifier enforces.",
scheduled: "Describe a team and when it should run — e.g. “a market-news digest team, every weekday at 7am.”",
triggered: "Describe a team to fire from a webhook — e.g. “when a support ticket arrives, triage and draft a reply.”",
};
type Member = { name: string; role: string; model: string; rationale?: string };
type Proposal = { team_name: string; topology_kind: string; schedule?: { cron?: string; one_shot_at?: string; prompt: string } | null; members: Member[] };
type SwarmSpec = { goal: string; checklist: string[]; task_count?: number; worker_model?: string };
type Msg = { role: "user" | "planner"; content: string };
type Step = { node_id: string; role: string; phase: string; output: string };
async function readSse(url: string, body: unknown, onEvt: (e: Record<string, unknown>) => void) {
const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
if (!res.ok || !res.body) throw new Error(`${res.status}`);
const reader = res.body.getReader();
const dec = new TextDecoder();
let buf = "";
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buf += dec.decode(value, { stream: true });
let i;
while ((i = buf.indexOf("\n\n")) >= 0) {
const frame = buf.slice(0, i); buf = buf.slice(i + 2);
const line = frame.split("\n").find((l) => l.startsWith("data:"));
if (!line) continue;
try { onEvt(JSON.parse(line.slice(5).trim())); } catch { /* skip */ }
}
}
}
export function MasterPlannerModal({ onClose }: { onClose: () => void }) {
const router = useRouter();
const [mode, setMode] = useState<Mode>("specialists");
const [messages, setMessages] = useState<Msg[]>([{ role: "planner", content: INTRO.specialists }]);
const [input, setInput] = useState("");
const [thinking, setThinking] = useState(false);
const [proposal, setProposal] = useState<Proposal | null>(null);
const [swarm, setSwarm] = useState<SwarmSpec | null>(null);
const [building, setBuilding] = useState(false);
const [buildProg, setBuildProg] = useState<{ pct: number; label: string } | null>(null);
const [error, setError] = useState<string | null>(null);
const [webhookUrl, setWebhookUrl] = useState<string | null>(null);
// Swarm run viewer
const [runSteps, setRunSteps] = useState<Step[]>([]);
const [runStatus, setRunStatus] = useState<string | null>(null);
const [runFinal, setRunFinal] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const esRef = useRef<EventSource | null>(null);
useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, [onClose]);
useEffect(() => { scrollRef.current?.scrollTo({ top: 1e9, behavior: "smooth" }); }, [messages, thinking]);
useEffect(() => () => { esRef.current?.close(); }, []);
function switchMode(m: Mode) {
if (m === mode) return;
esRef.current?.close();
setMode(m); setMessages([{ role: "planner", content: INTRO[m] }]); setInput("");
setProposal(null); setSwarm(null); setError(null); setBuildProg(null); setWebhookUrl(null);
setRunSteps([]); setRunStatus(null); setRunFinal(null);
}
async function send() {
const text = input.trim();
if (!text || thinking) return;
const next: Msg[] = [...messages, { role: "user", content: text }];
setMessages(next); setInput(""); setThinking(true); setError(null);
try {
await readSse("/api/planner/chat", { mode, messages: next.map((m) => ({ role: m.role === "user" ? "user" : "assistant", content: m.content })) }, (e) => {
if (e.stage === "error") setError(String(e.label || "error"));
else if (e.stage === "done") {
if (e.reply) setMessages((m) => [...m, { role: "planner", content: String(e.reply) }]);
if (e.proposal) setProposal(e.proposal as Proposal);
if (e.swarm) setSwarm(e.swarm as SwarmSpec);
}
});
} catch { setError("Network error"); }
setThinking(false);
}
async function buildTeam() {
if (!proposal || building) return;
setBuilding(true); setError(null); setBuildProg({ pct: 2, label: "Starting…" });
try {
await readSse("/api/planner/scaffold", proposal, async (e) => {
if (e.stage === "error") { setError(String(e.label || "build error")); setBuilding(false); }
else if (e.stage === "done") {
setBuildProg({ pct: 100, label: String(e.label || "Deployed") });
const teamId = e.team_id ? String(e.team_id) : null;
if (mode === "triggered" && teamId) {
// Mint a webhook for the freshly-built team and surface the URL.
try {
const r = await fetch(`/api/teams/${teamId}/webhooks`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ task: proposal.schedule?.prompt || "" }) });
const d = r.ok ? await r.json() : null;
if (d?.url) setWebhookUrl(`${window.location.origin}${d.url}`);
} catch { /* ignore */ }
setBuilding(false);
} else {
setBuilding(false);
setTimeout(() => { onClose(); if (teamId) router.push(`/?team=${teamId}`); router.refresh(); }, 800);
}
} else setBuildProg({ pct: Number(e.pct ?? 0), label: String(e.label || "") });
});
} catch { setError("Network error"); setBuilding(false); }
}
async function runSwarm() {
if (!swarm || building) return;
setBuilding(true); setError(null); setRunSteps([]); setRunFinal(null); setRunStatus("queued");
try {
const res = await fetch("/api/swarm/run", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(swarm) });
if (res.status !== 202) { setError(`Run failed (${res.status})`); setBuilding(false); return; }
const { run_id } = (await res.json()) as { run_id: string };
setRunStatus("running");
const es = new EventSource(`/api/topology-runs/${run_id}/events`);
esRef.current = es;
es.addEventListener("step", (ev) => { try { setRunSteps((s) => [...s, JSON.parse((ev as MessageEvent).data) as Step]); } catch { /* skip */ } });
es.addEventListener("done", (ev) => {
try { const d = JSON.parse((ev as MessageEvent).data) as { status: string; final_output: string | null }; setRunStatus(d.status); if (d.final_output) setRunFinal(d.final_output); } catch { /* skip */ }
es.close(); esRef.current = null; setBuilding(false);
});
es.onerror = () => { es.close(); esRef.current = null; setBuilding(false); };
} catch { setError("Network error"); setBuilding(false); }
}
const chip: React.CSSProperties = { fontFamily: mono, fontSize: 10, padding: "2px 7px", borderRadius: 5, background: "rgba(255,255,255,.06)", color: "#cfcfd5" };
const buildLabel = mode === "scheduled" ? "Build & schedule" : mode === "triggered" ? "Build & create webhook" : "Build team";
const hasRightPanel = (mode === "swarm" && swarm) || (mode !== "swarm" && proposal);
return (
<div onClick={onClose} role="presentation" style={{ position: "fixed", inset: 0, zIndex: 100, background: "rgba(0,0,0,.62)", backdropFilter: "blur(4px)", display: "flex", alignItems: "center", justifyContent: "center", padding: 24, animation: "cm-fade .18s ease" }}>
<div onClick={(e) => e.stopPropagation()} role="dialog" aria-modal="true" aria-label="Master Planner" style={{ width: "100%", maxWidth: 960, height: "86vh", display: "flex", flexDirection: "column", borderRadius: 16, background: "#0d0d10", border: "1px solid rgba(255,255,255,.1)", boxShadow: "0 30px 90px rgba(0,0,0,.6)", overflow: "hidden", animation: "scale-in .18s ease" }}>
{/* Header + mode selector */}
<div style={{ flex: "none", display: "flex", alignItems: "center", gap: 10, padding: "14px 18px", borderBottom: "1px solid rgba(255,255,255,.07)" }}>
<span style={{ width: 32, height: 32, borderRadius: 9, background: "rgba(201,138,240,.14)", border: "1px solid rgba(201,138,240,.32)", display: "flex", alignItems: "center", justifyContent: "center", color: "#c98af0" }}><Sparkles size={16} /></span>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 16, fontWeight: 700, color: "#f3f3f5" }}>Master Planner</div>
<div style={{ fontSize: 11.5, color: "#8a8a92" }}>Claude Opus 4.8 designs &amp; deploys.</div>
</div>
<div style={{ display: "flex", gap: 3, padding: 3, borderRadius: 9, background: "rgba(255,255,255,.04)", border: "1px solid rgba(255,255,255,.08)" }}>
{MODES.map((m) => (
<button key={m.key} type="button" onClick={() => switchMode(m.key)} title={m.hint} style={{ padding: "5px 10px", borderRadius: 7, border: 0, cursor: "pointer", fontSize: 11.5, fontWeight: 600, background: mode === m.key ? "#c98af0" : "transparent", color: mode === m.key ? "#1a0820" : "#9a9aa2" }}>{m.label}</button>
))}
</div>
<button type="button" onClick={onClose} aria-label="Close" style={{ width: 28, height: 28, borderRadius: 8, border: "1px solid rgba(255,255,255,.12)", background: "transparent", color: "#9a9aa2", cursor: "pointer" }}></button>
</div>
<div style={{ flex: 1, minHeight: 0, display: "flex" }}>
{/* Chat */}
<div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", borderRight: hasRightPanel ? "1px solid rgba(255,255,255,.07)" : undefined }}>
<div ref={scrollRef} style={{ flex: 1, minHeight: 0, overflowY: "auto", padding: 16, display: "flex", flexDirection: "column", gap: 12 }}>
{messages.map((m, i) => (
<div key={i} style={{ alignSelf: m.role === "user" ? "flex-end" : "flex-start", maxWidth: "85%", borderRadius: 12, padding: "9px 12px", fontSize: 13, lineHeight: 1.5, background: m.role === "user" ? "#ff6f61" : "#16161b", color: m.role === "user" ? "#1a0d0b" : "#e6e6ea", whiteSpace: "pre-wrap" }}>{m.content}</div>
))}
{thinking ? <div style={{ alignSelf: "flex-start", fontFamily: mono, fontSize: 11, color: "#c98af0" }}>Planning with Opus 4.8</div> : null}
{error ? <div style={{ alignSelf: "center", fontSize: 11.5, color: "#ff8a7a" }}>{error}</div> : null}
</div>
<div style={{ flex: "none", display: "flex", gap: 8, padding: 12, borderTop: "1px solid rgba(255,255,255,.07)" }}>
<textarea value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); } }} placeholder="Describe what you want…" rows={1} style={{ flex: 1, resize: "none", padding: "9px 11px", borderRadius: 9, border: "1px solid rgba(255,255,255,.12)", background: "#141417", color: "#eaeaee", fontSize: 13, fontFamily: "inherit" }} />
<button type="button" onClick={send} disabled={thinking || !input.trim()} aria-label="Send" style={{ flex: "none", width: 40, borderRadius: 9, border: 0, background: thinking || !input.trim() ? "rgba(255,111,97,.3)" : "#ff6f61", color: "#1a0d0b", cursor: thinking || !input.trim() ? "default" : "pointer", display: "flex", alignItems: "center", justifyContent: "center" }}><Send size={16} /></button>
</div>
</div>
{/* Right panel — proposal (team modes) or swarm spec / run viewer */}
{hasRightPanel ? (
<div style={{ flex: "none", width: 376, display: "flex", flexDirection: "column", background: "#0a0a0d" }}>
{mode === "swarm" && swarm ? (
<SwarmPanel swarm={swarm} steps={runSteps} status={runStatus} final={runFinal} building={building} onRun={runSwarm} />
) : proposal ? (
<div style={{ flex: 1, minHeight: 0, display: "flex", flexDirection: "column" }}>
<div style={{ flex: 1, minHeight: 0, overflowY: "auto", padding: 14 }}>
<div style={{ fontFamily: mono, fontSize: 9.5, letterSpacing: ".1em", color: "#c98af0", marginBottom: 6 }}>PROPOSED TEAM</div>
<div style={{ fontSize: 16, fontWeight: 700, color: "#f3f3f5" }}>{proposal.team_name}</div>
<div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 6 }}>
<span style={chip}>{proposal.topology_kind}</span>
<span style={chip}>{proposal.members.length} agents</span>
{proposal.schedule?.cron ? <span style={{ ...chip, color: "#7fd0a0" }}> {proposal.schedule.cron}</span> : null}
{proposal.schedule?.one_shot_at ? <span style={{ ...chip, color: "#7fd0a0" }}> {proposal.schedule.one_shot_at}</span> : null}
{mode === "triggered" ? <span style={{ ...chip, color: "#7fc8ff" }}>webhook</span> : null}
</div>
<div style={{ display: "flex", flexDirection: "column", gap: 8, marginTop: 12 }}>
{proposal.members.map((m, i) => (
<div key={i} style={{ borderRadius: 10, border: "1px solid rgba(255,255,255,.08)", background: "#101013", padding: 10 }}>
<div style={{ display: "flex", alignItems: "center", gap: 7 }}>
<span style={{ fontSize: 13, fontWeight: 600, color: "#eaeaee" }}>{m.name}</span>
<span style={{ flex: 1 }} />
<span style={{ fontFamily: mono, fontSize: 9, padding: "2px 6px", borderRadius: 5, background: "rgba(201,138,240,.14)", color: "#d9b3f5" }}>{m.model}</span>
</div>
<div style={{ fontFamily: mono, fontSize: 9.5, color: "#6a6a72", marginTop: 2 }}>{m.role}</div>
{m.rationale ? <div style={{ fontSize: 10.5, color: "#8a8a92", marginTop: 5, lineHeight: 1.45 }}>{m.rationale}</div> : null}
</div>
))}
</div>
{webhookUrl ? (
<div style={{ marginTop: 12, borderRadius: 10, border: "1px solid rgba(127,200,255,.3)", background: "rgba(127,200,255,.06)", padding: 11 }}>
<div style={{ fontFamily: mono, fontSize: 9.5, letterSpacing: ".1em", color: "#7fc8ff", marginBottom: 5, display: "flex", alignItems: "center", gap: 5 }}><Webhook size={11} />WEBHOOK URL</div>
<div style={{ fontFamily: mono, fontSize: 10.5, color: "#e6e6ea", wordBreak: "break-all", lineHeight: 1.5 }}>{webhookUrl}</div>
<button type="button" onClick={() => { navigator.clipboard?.writeText(webhookUrl); }} style={{ marginTop: 8, padding: "5px 10px", borderRadius: 7, border: "1px solid rgba(127,200,255,.3)", background: "transparent", color: "#7fc8ff", fontSize: 11, cursor: "pointer" }}>Copy POST to fire the team</button>
</div>
) : null}
</div>
<div style={{ flex: "none", padding: 12, borderTop: "1px solid rgba(255,255,255,.07)", display: "flex", flexDirection: "column", gap: 8 }}>
{buildProg ? (
<div>
<div style={{ display: "flex", justifyContent: "space-between", fontFamily: mono, fontSize: 9.5, color: "#9a9aa2", marginBottom: 4 }}><span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{buildProg.label}</span><span>{buildProg.pct}%</span></div>
<div style={{ height: 5, borderRadius: 3, background: "rgba(255,255,255,.08)", overflow: "hidden" }}><div style={{ width: `${buildProg.pct}%`, height: "100%", background: "linear-gradient(90deg,#c98af0,#ff6f61)", transition: "width .3s ease" }} /></div>
</div>
) : null}
{webhookUrl ? (
<button type="button" onClick={onClose} style={{ width: "100%", padding: "10px 0", borderRadius: 10, border: 0, background: "#5fd08a", color: "#06140c", fontSize: 13, fontWeight: 700, cursor: "pointer" }}>Done</button>
) : (
<button type="button" onClick={buildTeam} disabled={building} style={{ width: "100%", padding: "10px 0", borderRadius: 10, border: 0, background: building ? "rgba(255,111,97,.3)" : "#ff6f61", color: "#1a0d0b", fontSize: 13, fontWeight: 700, cursor: building ? "default" : "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7 }}>
{mode === "scheduled" ? <CalendarClock size={15} /> : mode === "triggered" ? <Webhook size={15} /> : <Users size={15} />}
{building ? "Building…" : buildLabel}
</button>
)}
</div>
</div>
) : null}
</div>
) : null}
</div>
</div>
</div>
);
}
function statusColor(s: string): string {
const t = s.toLowerCase();
if (t === "ok" || t === "completed" || t === "done") return "#7fd0a0";
if (t === "error" || t === "failed") return "#ff8a7a";
return "#f0c264";
}
function SwarmPanel({ swarm, steps, status, final, building, onRun }: { swarm: SwarmSpec; steps: Step[]; status: string | null; final: string | null; building: boolean; onRun: () => void }) {
const started = status !== null;
return (
<div style={{ flex: 1, minHeight: 0, display: "flex", flexDirection: "column" }}>
<div style={{ flex: 1, minHeight: 0, overflowY: "auto", padding: 14 }}>
<div style={{ fontFamily: mono, fontSize: 9.5, letterSpacing: ".1em", color: "#c98af0", marginBottom: 6, display: "flex", alignItems: "center", gap: 5 }}><Activity size={11} />SWARM JOB</div>
<div style={{ fontSize: 13.5, color: "#eaeaee", lineHeight: 1.5 }}>{swarm.goal}</div>
<div style={{ fontFamily: mono, fontSize: 9.5, letterSpacing: ".1em", color: "#6a6a72", margin: "12px 0 6px" }}>VERIFY CHECKLIST</div>
<div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
{(swarm.checklist || []).map((c, i) => (
<div key={i} style={{ fontSize: 11.5, color: "#cfcfd5", display: "flex", gap: 6 }}><span style={{ color: "#7fd0a0" }}></span>{c}</div>
))}
</div>
{started ? (
<div style={{ marginTop: 14 }}>
<div style={{ fontFamily: mono, fontSize: 10, color: statusColor(status || "running"), textTransform: "uppercase", marginBottom: 8 }}>{status === "running" || status === "queued" ? "● running" : status}</div>
<div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
{steps.map((s, i) => {
const reject = s.output.startsWith("✗");
const pass = s.output.startsWith("✓");
return (
<div key={i} style={{ borderRadius: 9, border: "1px solid rgba(255,255,255,.08)", background: "#101013", padding: 9 }}>
<div style={{ fontFamily: mono, fontSize: 9, color: pass ? "#7fd0a0" : reject ? "#ff8a7a" : "#5ec8d8", marginBottom: 3 }}>{s.role}</div>
<div style={{ fontSize: 11.5, color: "#cfcfd5", lineHeight: 1.45, whiteSpace: "pre-wrap", maxHeight: 120, overflow: "hidden" }}>{s.output}</div>
</div>
);
})}
{final ? (
<div style={{ borderRadius: 9, border: "1px solid rgba(127,208,160,.3)", background: "rgba(127,208,160,.06)", padding: 10 }}>
<div style={{ fontFamily: mono, fontSize: 9.5, letterSpacing: ".1em", color: "#7fd0a0", marginBottom: 5 }}>FINAL REPORT</div>
<div style={{ fontSize: 11.5, color: "#e6e6ea", lineHeight: 1.5, whiteSpace: "pre-wrap" }}>{final}</div>
</div>
) : null}
</div>
</div>
) : null}
</div>
{!started ? (
<div style={{ flex: "none", padding: 12, borderTop: "1px solid rgba(255,255,255,.07)" }}>
<button type="button" onClick={onRun} disabled={building} style={{ width: "100%", padding: "10px 0", borderRadius: 10, border: 0, background: building ? "rgba(94,200,216,.3)" : "#5ec8d8", color: "#04181c", fontSize: 13, fontWeight: 700, cursor: building ? "default" : "pointer", display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 7 }}><Activity size={15} />{building ? "Starting…" : "Run swarm"}</button>
</div>
) : null}
</div>
);
}