@harness-engineering/dashboard 0.7.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,24 @@
1
+ import{r as c,j as e,c as Ls}from"./react-Dauv-dA-.js";import{N as Ds,u as X,a as Os,b as qt,B as Ps,R as Fs,c as Se,d as _s}from"./react-router-rpxWuPlF.js";import{aa as Yt,ab as zs,ac as Bs,ad as oe,ae as Hs,af as Vt,ag as Ws,ah as Gs,ai as Jt,aj as Us,ak as we,al as qs,am as Ys,an as Vs,ao as Js,ap as Be,aq as Xs,ar as He,as as Ks,at as Qs,au as Zs,av as ea,aw as it,ax as ta,ay as sa,az as aa,aA as lt,aB as na,aC as ra,aD as Xt,aE as ot,aF as ct,aG as Kt,aH as Qt,aI as Zt,aJ as es,aK as ia,aL as et,aM as la,aN as te,aO as se,aP as oa,aQ as dt,aR as Ee,aS as ts,aT as ca,aU as xt,aV as ss,aW as as,aX as da,aY as xa}from"./vendor-CUJ5XKnx.js";import{u as Re,a as de,m as y,A as W,b as ua,c as bt}from"./framer-motion-CKCla3Ft.js";import{q as ns}from"./virtuoso-DIddGMdU.js";import{h as ma,v as ha}from"./syntax-highlighter-DWwEaa3J.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))n(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function a(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(r){if(r.ep)return;r.ep=!0;const i=a(r);fetch(r.href,i)}})();const tt="harness-last-thread-id";let jt=3;function pa(){var t;try{return((t=globalThis.localStorage)==null?void 0:t.getItem(tt))??null}catch{return null}}function fa(t){var s,a;try{t?(s=globalThis.localStorage)==null||s.setItem(tt,t):(a=globalThis.localStorage)==null||a.removeItem(tt)}catch{}}function ga(t){switch(t){case"chat":return"user";case"attention":return"alert";case"agent":return"organism";case"analysis":case"system":return"system"}}function ya(t){switch(t){case"attention":return"pending";default:return"active"}}function ba(t,s){switch(t){case"agent":return`agent:${s.issueId}`;case"attention":return`attn:${s.interactionId}`;case"chat":return`chat:${s.sessionId}`;default:return crypto.randomUUID()}}function ja(t,s){switch(t){case"chat":return s.command&&s.command.split(":").pop()||"New Chat";case"attention":return`Attention: ${s.issueId}`;case"analysis":return s.analysisTitle;case"agent":return s.issueTitle||s.identifier;case"system":return"System";default:return"Thread"}}function Na(t){const s=[],a=[],n=[],r=[];for(const i of t.values()){if(i.type==="system"){r.push(i);continue}if(i.type==="attention"&&i.status==="pending"){s.push(i);continue}if(i.status==="completed"||i.status==="dismissed"){n.push(i);continue}a.push(i)}return s.sort((i,l)=>l.createdAt-i.createdAt),a.sort((i,l)=>l.updatedAt-i.updatedAt),n.sort((i,l)=>l.updatedAt-i.updatedAt),{attention:s,active:a,recent:n,system:r}}function va(t){return Na(t.threads)}function rs(){const t=E.getState();for(const s of t.threads.values()){if(s.type!=="chat"||s.meta.command)continue;const a=t.messages.get(s.id);if(!a||a.length===0)return s}return t.createThread("chat",{sessionId:crypto.randomUUID(),command:null})}const E=Yt((t,s)=>({threads:new Map,activeThreadId:null,lastThreadId:pa(),hydrated:!1,messages:new Map,panelState:new Map,createThread(a,n){const r=ba(a,n),i=s().threads.get(r);if(i)return i;const l=Date.now(),o={id:r,type:a,title:ja(a,n),status:ya(a),createdAt:l,updatedAt:l,avatar:ga(a),unread:a==="attention",meta:n};return t(d=>{const u=new Map(d.threads);return u.set(o.id,o),{threads:u}}),o},closeThread(a){const n=s().threads.get(a);if((n==null?void 0:n.type)==="chat"){const r=n.meta.sessionId;fetch(`/api/sessions/${r}`,{method:"DELETE"}).catch(()=>{})}t(r=>{const i=new Map(r.threads);i.delete(a);const l=new Map(r.messages);l.delete(a);const o=new Map(r.panelState);o.delete(a);const d=r.activeThreadId===a?null:r.activeThreadId;return{threads:i,messages:l,panelState:o,activeThreadId:d}})},claimThread(a){t(n=>{const r=n.threads.get(a);if(!r)return n;const i={...r,status:"active",unread:!1,updatedAt:Date.now()},l=new Map(n.threads);return l.set(a,i),{threads:l}})},dismissThread(a){t(n=>{const r=n.threads.get(a);if(!r)return n;const i={...r,status:"dismissed",unread:!1,updatedAt:Date.now()},l=new Map(n.threads);return l.set(a,i),{threads:l}})},setActiveThread(a){t({activeThreadId:a}),a&&(fa(a),t({lastThreadId:a}))},updateThread(a,n){t(r=>{const i=r.threads.get(a);if(!i)return r;const l={...i,...n,updatedAt:Date.now()},o=new Map(r.threads);return o.set(a,l),{threads:o}})},markSourceHydrated(){jt--,jt<=0&&t({hydrated:!0})},setMessages(a,n){t(r=>{const i=new Map(r.messages);return i.set(a,n),{messages:i}})},appendMessage(a,n){t(r=>{const i=new Map(r.messages),l=i.get(a)??[];return i.set(a,[...l,n]),{messages:i}})},updateLastMessage(a,n){t(r=>{const i=new Map(r.messages),l=i.get(a);if(!l||l.length===0)return r;const o=[...l];return o[o.length-1]=n(o[o.length-1]),i.set(a,o),{messages:i}})},updatePanelState(a,n){t(r=>{const i=new Map(r.panelState),l=i.get(a)??{todos:[],phase:null,skill:null,startedAt:null,artifacts:[],contextSources:[]};return i.set(a,{...l,...n}),{panelState:i}})}}));function is(t){for(const s of E.getState().threads.values())if(s.type==="agent"&&s.meta.issueId===t)return s;return null}async function wa(){try{const t=await fetch("/api/streams");if(!t.ok)return;const s=await t.json(),a=E.getState();for(const n of s){if(is(n.issueId))continue;const r=n.attempts.at(-1);if(r&&!r.endedAt)continue;const l=a.createThread("agent",{issueId:n.issueId,identifier:n.identifier,phase:"completed",issueTitle:n.title??n.identifier,issueDescription:null,startedAt:(r==null?void 0:r.startedAt)??new Date().toISOString(),backendName:null});a.updateThread(l.id,{status:"completed"})}}finally{E.getState().markSourceHydrated()}}function ka(t,s,a){var i,l,o;const n=E.getState(),r=is(t);if(a.has(t)){if(r){const d=r.meta;(d.phase!==s.phase||d.backendName!==(((i=s.session)==null?void 0:i.backendName)??null))&&n.updateThread(r.id,{meta:{...d,phase:s.phase,backendName:((l=s.session)==null?void 0:l.backendName)??null}})}return}a.add(t),r||n.createThread("agent",{issueId:t,identifier:s.identifier,phase:s.phase,issueTitle:s.issue.title,issueDescription:s.issue.description,startedAt:s.startedAt,backendName:((o=s.session)==null?void 0:o.backendName)??null})}function Sa(t){const s=E.getState();for(const a of s.threads.values())a.type==="agent"&&a.status==="active"&&(t.has(a.meta.issueId)||s.updateThread(a.id,{status:"completed"}))}function Ca(t){const s=c.useRef(new Set),a=c.useRef(!1);c.useEffect(()=>{a.current||(a.current=!0,wa())},[]),c.useEffect(()=>{if(!t.snapshot)return;const n=new Set;for(const[r,i]of t.snapshot.running)n.add(r),ka(r,i,s.current);Sa(n)},[t.snapshot])}function Ma(t){const s=E.getState().threads;for(const a of s.values())if(a.type==="attention"&&a.meta.interactionId===t)return!0;return!1}function Nt(t){E.getState().createThread("attention",{interactionId:t.id,issueId:t.issueId,reasons:t.reasons,context:t.context})}function Ta(t){const s=c.useRef(new Set),a=c.useRef(!1);c.useEffect(()=>{a.current||(a.current=!0,fetch("/api/interactions").then(n=>n.ok?n.json():[]).then(n=>{for(const r of n)r.status!=="resolved"&&(s.current.has(r.id)||(s.current.add(r.id),Ma(r.id)||Nt(r)))}).catch(()=>{}).finally(()=>E.getState().markSourceHydrated()))},[]),c.useEffect(()=>{for(const n of t.interactions)s.current.has(n.id)||(s.current.add(n.id),Nt(n))},[t.interactions])}function Ia(){const t=c.useRef(!1);c.useEffect(()=>{t.current||(t.current=!0,fetch("/api/sessions").then(s=>s.ok?s.json():[]).then(s=>{if(!Array.isArray(s))return;const a=E.getState();for(const n of s){if(!(n!=null&&n.sessionId)||a.threads.has(`chat:${n.sessionId}`))continue;const r=a.createThread("chat",{sessionId:n.sessionId,command:n.command??null});n.label&&n.label!=="New Chat"&&a.updateThread(r.id,{title:n.label}),Array.isArray(n.messages)&&n.messages.length>0&&a.setMessages(r.id,n.messages)}}).catch(()=>{}).finally(()=>E.getState().markSourceHydrated()))},[])}function $a(t){return typeof t.content=="string"?t.content:t.content==null?"":typeof t.content=="object"?JSON.stringify(t.content):String(t.content)}function Aa(t,s){const a=t[t.length-1];(a==null?void 0:a.kind)==="text"?t[t.length-1]={kind:"text",text:a.text+s}:((a==null?void 0:a.kind)==="status"&&t.pop(),t.push({kind:"text",text:s}))}function Ea(t,s){const a=t[t.length-1];(a==null?void 0:a.kind)==="thinking"?t[t.length-1]={kind:"thinking",text:a.text+s}:t.push({kind:"thinking",text:s})}function Ra(t,s){const a=s.match(/^Calling (\S+)\(([\s\S]*)\)$/);a?t.push({kind:"tool_use",tool:a[1],...a[2]!=null?{args:a[2]}:{}}):t.push({kind:"tool_use",tool:s})}function La(t,s){const a=t[t.length-1];(a==null?void 0:a.kind)==="status"?t[t.length-1]={kind:"status",text:s}:t.push({kind:"status",text:s})}function ls(t,s){const a=$a(s);switch(s.type){case"text":Aa(t,a);break;case"thought":Ea(t,a);break;case"call":Ra(t,a);break;case"result":a&&t.push({kind:"text",text:a});break;case"rate_limit":t.push({kind:"status",text:"Rate limit — cooling down..."});break;case"status":La(t,a);break;case"turn_start":break;default:a&&t.push({kind:"status",text:a});break}}function Da(t,s){const a=t.findIndex(r=>r.backendName===s.backendName);if(a===-1)return[...t,s];const n=t.slice();return n[a]=s,n}const Oa=1e3,Pa=3e4,vt=500;function Fa(){return`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`}function _a(t,s){const{issueId:a,event:n}=s;if(!a||!n)return t;const r=[...t[a]??[]];ls(r,n);const i=r.length>vt?r.slice(r.length-vt):r;return{...t,[a]:i}}function za(t,s){const a=Object.keys(t).filter(r=>!s.has(r));if(a.length===0)return t;const n={...t};for(const r of a)delete n[r];return n}function Ba(t,s){return t.some(a=>a.id===s.id)?t:[...t,s]}function Ha(t,s){switch(t.type){case"state_change":s.setSnapshot(t.data);break;case"interaction_new":s.setInteractions(a=>Ba(a,t.data));break;case"agent_event":s.setAgentEvents(a=>_a(a,t.data));break;case"maintenance:started":s.setMaintenanceEvent({type:"maintenance:started",data:t.data});break;case"maintenance:error":s.setMaintenanceEvent({type:"maintenance:error",data:t.data});break;case"maintenance:completed":s.setMaintenanceEvent({type:"maintenance:completed",data:t.data});break;case"maintenance:baseref_fallback":s.setMaintenanceEvent({type:"maintenance:baseref_fallback",data:t.data});break;case"local-model:status":s.setLocalModelStatuses(a=>Da(a,t.data));break}}function os(t,s,a,n,r){const i=new WebSocket(Fa());return i.onopen=()=>{t.current&&(a.current=0,n(!0))},i.onmessage=l=>{if(t.current)try{const o=JSON.parse(l.data);if(typeof o!="object"||o===null||!("type"in o))return;Ha(o,r)}catch{}},i.onclose=()=>{if(!t.current)return;n(!1);const l=Math.min(Oa*2**a.current,Pa);a.current+=1,s.current=setTimeout(()=>os(t,s,a,n,r),l)},i.onerror=()=>{},i}function ke(){const[t,s]=c.useState(null),[a,n]=c.useState([]),[r,i]=c.useState({}),[l,o]=c.useState(null),[d,u]=c.useState([]),[x,f]=c.useState(!1),m=c.useRef(null),p=c.useRef(0),h=c.useCallback(g=>{n(b=>b.filter(j=>j.id!==g))},[]);return c.useEffect(()=>{const g={current:!0},j=os(g,m,p,f,{setSnapshot:s,setInteractions:n,setAgentEvents:i,setMaintenanceEvent:o,setLocalModelStatuses:u});return()=>{g.current=!1,j.close(),m.current&&clearTimeout(m.current)}},[]),c.useEffect(()=>{if(!t)return;const g=new Set(t.running.map(([b])=>b));i(b=>za(b,g))},[t]),{snapshot:t,interactions:a,agentEvents:r,maintenanceEvent:l,localModelStatuses:d,connected:x,removeInteraction:h,setInteractions:n}}const cs=c.createContext({pulse:{stressLevel:0,isHealthy:!0,totalIssues:0},setPulse:()=>{}});function Wa({children:t}){const[s,a]=c.useState({stressLevel:0,isHealthy:!0,totalIssues:0});return e.jsx(cs.Provider,{value:{pulse:s,setPulse:a},children:t})}const Ga=()=>c.useContext(cs),wt=["rgba(12, 106, 158, 0.4)","rgba(14, 143, 160, 0.35)","rgba(10, 80, 120, 0.3)","rgba(16, 185, 129, 0.25)","rgba(8, 104, 120, 0.3)"];function Ua(t){return Array.from({length:t},(s,a)=>({id:a,left:`${Math.random()*100}%`,top:`${Math.random()*100}%`,size:2.5+Math.random()*6,color:wt[a%wt.length],driftX:`${(Math.random()-.5)*200}px`,driftY:`${(Math.random()-.5)*150-50}px`,driftScale:.7+Math.random()*.9,duration:`${15+Math.random()*25}s`,delay:`${Math.random()*-20}s`}))}function qa({mouseX:t,mouseY:s}){const{pulse:a}=Ga(),n=c.useMemo(()=>Ua(85),[]),r={damping:50,stiffness:100},i=Re(0,r),l=Re(0,r);c.useEffect(()=>{i.set(t),l.set(s)},[t,s,i,l]);const o=de(i,[0,2e3],[20,-20]),d=de(l,[0,1200],[20,-20]),u=de(i,[0,2e3],[40,-40]),x=de(l,[0,1200],[40,-40]),f=de(i,[0,2e3],[10,-10]),m=de(l,[0,1200],[10,-10]),p=a.stressLevel>.5;return e.jsxs("div",{className:"pointer-events-none fixed inset-0 -z-10 overflow-hidden transition-colors duration-1000",style:{background:"linear-gradient(180deg, #010408 0%, #020a14 30%, #030e1c 60%, #010610 100%)"},children:[e.jsx(y.div,{style:{x:o,y:d,background:p?"radial-gradient(circle at center, rgba(180, 80, 20, 0.12) 0%, rgba(120, 40, 10, 0.04) 40%, transparent 80%)":"radial-gradient(circle at center, rgba(12, 106, 158, 0.12) 0%, rgba(8, 104, 120, 0.04) 40%, transparent 80%)",transform:"translate3d(0,0,0)"},animate:{scale:[1,1.12,.95,1.05,1],opacity:[.5,.7,.4,.65,.5],x:[0,30,-20,15,0],y:[0,-25,10,-15,0]},transition:{duration:25,repeat:1/0,ease:"easeInOut"},className:"absolute -left-[10%] -top-[10%] h-[65%] w-[65%] rounded-full transition-all duration-[2s]"}),e.jsx(y.div,{style:{x:u,y:x,background:p?"radial-gradient(circle at center, rgba(120, 40, 10, 0.08) 0%, rgba(180, 80, 20, 0.02) 40%, transparent 80%)":"radial-gradient(circle at center, rgba(8, 104, 120, 0.08) 0%, rgba(10, 80, 60, 0.02) 40%, transparent 80%)",transform:"translate3d(0,0,0)"},animate:{scale:[1.1,.9,1.15,.95,1.1],opacity:[.3,.5,.25,.45,.3],x:[0,-40,20,-10,0],y:[0,20,-30,15,0]},transition:{duration:32,repeat:1/0,ease:"easeInOut"},className:"absolute -bottom-[15%] -right-[10%] h-[70%] w-[70%] rounded-full transition-all duration-[2s]"}),e.jsx(y.div,{style:{x:f,y:m,background:"radial-gradient(circle at center, rgba(12, 106, 158, 0.06) 0%, rgba(8, 68, 80, 0.02) 40%, transparent 80%)",transform:"translate3d(0,0,0)"},animate:{scale:[1,1.3,.85,1.15,1],opacity:[.2,.4,.15,.35,.2],x:[0,50,-30,20,0],y:[0,-40,30,-20,0]},transition:{duration:40,repeat:1/0,ease:"easeInOut"},className:"absolute left-[15%] top-[25%] h-[55%] w-[55%] rounded-full"}),e.jsx(y.div,{animate:{x:[0,80,-60,40,0],y:[0,-50,30,-20,0],scale:[1,1.2,.9,1.1,1],opacity:[.15,.25,.1,.2,.15]},transition:{duration:50,repeat:1/0,ease:"easeInOut"},className:"absolute left-[40%] top-[50%] h-[40%] w-[50%] rounded-full",style:{background:"radial-gradient(circle at center, rgba(2, 8, 20, 0.7) 0%, rgba(1, 4, 8, 0.35) 40%, transparent 80%)",transform:"translate3d(0,0,0)"}}),e.jsx(y.div,{animate:{x:[0,-70,50,-30,0],y:[0,40,-50,25,0],scale:[1.1,.85,1.2,.95,1.1],opacity:[.1,.2,.08,.18,.1]},transition:{duration:38,repeat:1/0,ease:"easeInOut",delay:8},className:"absolute left-[-5%] top-[10%] h-[50%] w-[45%] rounded-full",style:{background:"radial-gradient(circle at center, rgba(2, 12, 24, 0.6) 0%, rgba(1, 6, 12, 0.25) 40%, transparent 80%)",transform:"translate3d(0,0,0)"}}),e.jsx(y.div,{animate:{backgroundPosition:["0% 0%","50% 100%","100% 0%"],opacity:[.015,.03,.015]},transition:{duration:20,repeat:1/0,ease:"easeInOut"},className:"absolute inset-0",style:{backgroundImage:`
2
+ radial-gradient(ellipse 400px 120px at 25% 8%, rgba(12, 106, 158, 0.15), transparent),
3
+ radial-gradient(ellipse 300px 90px at 55% 4%, rgba(8, 104, 120, 0.1), transparent),
4
+ radial-gradient(ellipse 350px 100px at 75% 12%, rgba(12, 106, 158, 0.08), transparent)
5
+ `,backgroundSize:"200% 200%",transform:"translate3d(0,0,0)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, transparent 0%, transparent 40%, rgba(1, 4, 8, 0.5) 100%)",transform:"translate3d(0,0,0)"}}),n.map(h=>e.jsx("div",{className:"plankton",style:{left:h.left,top:h.top,width:h.size,height:h.size,backgroundColor:h.color,"--drift-x":h.driftX,"--drift-y":h.driftY,"--drift-scale":h.driftScale,"--drift-duration":h.duration,"--drift-delay":h.delay,transform:"translate3d(0,0,0)"}},h.id)),a.stressLevel>.7&&e.jsx(y.div,{animate:{opacity:[0,.04,0]},transition:{duration:3,repeat:1/0},className:"absolute inset-0 bg-red-500/10 pointer-events-none"})]})}function C(t,s){return t+(Math.random()-.5)*2*s}function kt(t,s){return t.replace(/Q\s+([\d.]+)\s+([\d.]+)/,(a,n,r)=>{const i=parseFloat(n)+(Math.random()-.5)*2*s,l=parseFloat(r)+(Math.random()-.5)*2*s;return`Q ${i.toFixed(1)} ${l.toFixed(1)}`})}function qe(t,s,a,n){const r=[];for(let l=0;l<s;l++){const o=l/s*Math.PI*2,d=a+(Math.random()-.5)*n;r.push({x:t+Math.cos(o)*d,y:t+Math.sin(o)*d})}let i=`M ${r[0].x.toFixed(1)} ${r[0].y.toFixed(1)}`;for(let l=0;l<s;l++){const o=r[(l+1)%s],d=r[l],u=(d.x+o.x)/2,x=(d.y+o.y)/2;i+=` Q ${d.x.toFixed(1)} ${d.y.toFixed(1)}, ${u.toFixed(1)} ${x.toFixed(1)}`}return i+=" Z",i}function ne(t,s,a){return Math.min(Math.max((t-s)/a,0),1)}function he(t,s){return t.replace(/,\s*[\d.]+\)$/,`, ${s})`)}function Ya(){const t=Math.random()*360,s=(t+140+Math.random()*40)%360,a=Math.random()*Math.PI*2,n=Math.random(),r=n<.3?null:n<.39?"medusa":n<.48?"lurker":n<.57?"radiant":n<.65?"bristle":n<.73?"tendril":n<.81?"nebula":n<.89?"wraith":"coral";let i,l,o,d,u,x,f,m,p=.8+Math.random()*.4,h=3+Math.floor(Math.random()*2),g,b;switch(r){case"medusa":{i=5+Math.floor(Math.random()*3);const j=Math.PI*1.3;l=Array.from({length:i},(N,v)=>a+Math.PI*.5+v/(i-1||1)*j-j/2+C(0,.15)),o=l.map(()=>.85+Math.random()*.45),d=l.map(()=>(Math.random()-.3)*2.5),u=l.map(()=>Math.random()<.25),x=16+Math.floor(Math.random()*5),f=.25+Math.random()*.3,m=.95+Math.random()*.2,p=.9+Math.random()*.3,h=3,g="stripes",b={twinCore:!1,rings:Math.random()<.3,cometTail:!1,ghostMembrane:!1};break}case"lurker":{i=3+Math.floor(Math.random()*3);const j=Math.PI*2/i;l=Array.from({length:i},(N,v)=>a+v*j+C(0,j*.2)),o=Array.from({length:i},(N,v)=>v===0?1.2+Math.random()*.25:.3+Math.random()*.2),d=Array.from({length:i},(N,v)=>v===0?(Math.random()-.5)*2:(Math.random()-.5)*.5),u=l.map(()=>!1),x=8+Math.floor(Math.random()*3),f=1.5+Math.random()*.5,m=.75+Math.random()*.1,p=.7+Math.random()*.15,g="none",b={twinCore:!1,rings:!1,cometTail:!1,ghostMembrane:!1};break}case"radiant":{i=5,l=Array.from({length:5},(j,N)=>a+N/5*Math.PI*2),o=Array.from({length:5},()=>.5+Math.random()*.15),d=Array.from({length:5},()=>(Math.random()-.5)*.5),u=Array.from({length:5},()=>!0),x=12+Math.floor(Math.random()*4),f=.35+Math.random()*.25,m=1+Math.random()*.2,p=1+Math.random()*.2,h=3,g="spots",b={twinCore:!1,rings:!1,cometTail:!1,ghostMembrane:Math.random()<.25};break}case"bristle":{i=8+Math.floor(Math.random()*2);const j=Math.PI*2/i;l=Array.from({length:i},(N,v)=>a+v*j+C(0,j*.08)),o=Array.from({length:i},()=>.35+Math.random()*.15),d=Array.from({length:i},()=>(Math.random()-.5)*.25),u=l.map(()=>!1),x=8+Math.floor(Math.random()*3),f=.3+Math.random()*.25,m=.8+Math.random()*.15,p=.8+Math.random()*.15,g="rings",b={twinCore:!1,rings:!1,cometTail:!1,ghostMembrane:!1};break}case"tendril":{i=6+Math.floor(Math.random()*3);const j=Math.PI*.65;l=Array.from({length:i},(N,v)=>a+v/(i-1||1)*j-j/2+C(0,.1)),o=Array.from({length:i},()=>.7+Math.random()*.55),d=Array.from({length:i},()=>(Math.random()-.5)*2),u=l.map(()=>Math.random()<.35),x=10+Math.floor(Math.random()*4),f=1.2+Math.random()*.8,m=.8+Math.random()*.15,p=.8+Math.random()*.15,g="veins",b={twinCore:!1,rings:!1,cometTail:Math.random()<.4,ghostMembrane:!1};break}case"nebula":{i=Math.floor(Math.random()*3),l=Array.from({length:i},(j,N)=>a+N*Math.PI+C(0,.5)),o=Array.from({length:i},()=>.25+Math.random()*.2),d=Array.from({length:i},()=>(Math.random()-.5)*.8),u=l.map(()=>!1),x=6+Math.floor(Math.random()*3),f=.15+Math.random()*.15,m=1.1+Math.random()*.15,p=1.15+Math.random()*.25,h=4,g="rings",b={twinCore:!1,rings:Math.random()<.35,cometTail:!1,ghostMembrane:Math.random()<.4};break}case"wraith":{i=6+Math.floor(Math.random()*2);const j=Math.PI*2/i;l=Array.from({length:i},(N,v)=>a+v*j+C(0,j*.25)),o=Array.from({length:i},()=>.7+Math.random()*.5),d=Array.from({length:i},()=>(Math.random()-.5)*3.5),u=l.map(()=>Math.random()<.25),x=10+Math.floor(Math.random()*5),f=1.5+Math.random()*.5,m=.85+Math.random()*.2,p=.85+Math.random()*.15,g="veins",b={twinCore:!0,rings:!0,cometTail:!1,ghostMembrane:Math.random()<.3};break}case"coral":{i=4+Math.floor(Math.random()*2);const j=Math.PI*2/i;l=Array.from({length:i},(N,v)=>a+v*j+C(0,j*.15)),o=Array.from({length:i},()=>.9+Math.random()*.4),d=Array.from({length:i},()=>(Math.random()-.5)*1.2),u=l.map(()=>!0),x=10+Math.floor(Math.random()*3),f=.2+Math.random()*.2,m=.9+Math.random()*.15,p=.9+Math.random()*.2,h=3,g="spots",b={twinCore:!1,rings:!1,cometTail:!1,ghostMembrane:Math.random()<.2};break}default:{i=4+Math.floor(Math.random()*6);const j=Math.PI*2/i;l=Array.from({length:i},(v,S)=>a+S*j+C(0,j*.35)),o=Array.from({length:i},()=>.6+Math.random()*.7),d=Array.from({length:i},()=>(Math.random()-.5)*3),u=l.map(()=>Math.random()<.55),x=8+Math.floor(Math.random()*11),f=.5+Math.random()*1.5,m=.75+Math.random()*.45,h=3+Math.floor(Math.random()*2);const N=["spots","stripes","rings","veins","none","none"];g=N[Math.floor(Math.random()*N.length)],b={twinCore:Math.random()<.12,rings:Math.random()<.1,cometTail:Math.random()<.1,ghostMembrane:Math.random()<.1}}}return{hue:t,accentHue:s,eggAspect:.6+Math.random()*.25,coreScale:p,growthOffset:(Math.random()-.5)*.1,clusterAngle:Math.random()*Math.PI*2,clusterSpread:4+Math.random()*3.5,divisionRounds:h,membraneLobes:x,sparkRate:f,armCount:i,armAngles:l,armLengths:o,armCurves:d,connectorMask:u,bodyRadius:m,pattern:g,species:r,mutation:b}}function Va(t){const r=[];for(let l=0;l<t.armCount;l++){const o=t.armAngles[l],d=t.armLengths[l],u=t.armCurves[l],x=Math.min(22*d,24),f=28+Math.cos(o)*x,m=28+Math.sin(o)*x,p=(28+f)/2,h=(28+m)/2,g=o+Math.PI/2,b=u*x*.35,j=p+Math.cos(g)*b,N=h+Math.sin(g)*b,v=`M 28 28 Q ${j.toFixed(1)} ${N.toFixed(1)} ${f.toFixed(1)} ${m.toFixed(1)}`,S=Math.sqrt((f-28)**2+(m-28)**2)*1.15;r.push({d:v,baselen:S,weight:.7+Math.random()*.25,endX:f,endY:m})}const i=[];for(let l=0;l<t.armCount;l++){if(!t.connectorMask[l])continue;const o=r[l],d=r[(l+1)%t.armCount],u=(o.endX+d.endX)/2,x=(o.endY+d.endY)/2,f=28-u,m=28-x,p=Math.sqrt(f**2+m**2)||1,h=p*.4,g=u-f/p*h,b=x-m/p*h,j=`M ${o.endX.toFixed(1)} ${o.endY.toFixed(1)} Q ${g.toFixed(1)} ${b.toFixed(1)} ${d.endX.toFixed(1)} ${d.endY.toFixed(1)}`,N=Math.sqrt((d.endX-o.endX)**2+(d.endY-o.endY)**2)*1.1;i.push({d:j,baselen:N,weight:.3+Math.random()*.15,endX:d.endX,endY:d.endY})}return{arms:r,connectors:i}}function St(t,s){const a=(s+20)%360;return{primary:`hsla(${t}, 68%, 73%, 1)`,primarySoft:`hsla(${t}, 55%, 82%, 1)`,primaryDeep:`hsla(${t}, 75%, 50%, 1)`,accent:`hsla(${s}, 62%, 58%, 1)`,accentAlt:`hsla(${a}, 55%, 55%, 1)`,core:`hsla(${t}, 60%, 80%, 1)`,sparkColors:[`hsla(${(t+45)%360}, 85%, 56%, 0.95)`,`hsla(${s}, 70%, 55%, 0.9)`,`hsla(${(t-25+360)%360}, 65%, 62%, 0.85)`,`hsla(${(t+90)%360}, 60%, 60%, 0.9)`,`hsla(${t}, 70%, 73%, 1)`,`hsla(${a}, 60%, 58%, 1)`],planktonColors:[`hsla(${t}, 55%, 73%, 1)`,`hsla(${t}, 68%, 55%, 1)`,`hsla(${s}, 62%, 58%, 1)`,`hsla(${a}, 55%, 55%, 1)`,`hsla(${t}, 55%, 82%, 1)`]}}const q=[.4,0,.2,1],Ct=[.7,0,.3,1];function Ja({d:t,len:s,delay:a,duration:n,color:r,repeatDelay:i,weight:l,hitCount:o}){const d=.03+l*.06,u=.4+l*.35,x=.6+l*.5;return e.jsxs(e.Fragment,{children:[e.jsx("path",{d:t,stroke:r,strokeWidth:u,opacity:d,fill:"none",strokeLinecap:"round"}),o>0&&e.jsxs(e.Fragment,{children:[e.jsx(y.path,{d:t,stroke:r,strokeWidth:u+.8,fill:"none",strokeLinecap:"round",strokeDasharray:"3 5",initial:{strokeDashoffset:0,opacity:.25},animate:{strokeDashoffset:[0,-(s+10)],opacity:[.25,.18,.06,0]},transition:{duration:.5,ease:"easeOut"},style:{strokeOpacity:.15}},`whip-a-${o}`),e.jsx(y.path,{d:t,stroke:r,strokeWidth:u+3,fill:"none",strokeLinecap:"round",strokeDasharray:"4 6",initial:{strokeDashoffset:2,opacity:.12},animate:{strokeDashoffset:[2,-(s+8)],opacity:[.12,.08,.03,0]},transition:{duration:.7,ease:"easeOut",delay:.08},style:{strokeOpacity:.05}},`whip-b-${o}`)]}),e.jsx(y.path,{d:t,stroke:r,strokeWidth:x+4,fill:"none",strokeLinecap:"round",strokeDasharray:`6 ${s+6}`,animate:{strokeDashoffset:[8,-(s+8)]},transition:{duration:n,delay:a,repeat:1/0,ease:Ct,repeatDelay:i},style:{opacity:.04}}),e.jsx(y.path,{d:t,stroke:r,strokeWidth:x,fill:"none",strokeLinecap:"round",strokeDasharray:`3.5 ${s+8}`,animate:{strokeDashoffset:[8,-(s+8)]},transition:{duration:n,delay:a,repeat:1/0,ease:Ct,repeatDelay:i},style:{opacity:.4}})]})}function Xa({cx:t,cy:s,r:a,delay:n,color:r}){const i=c.useMemo(()=>({x:[0,C(0,2),C(0,1.5),C(0,2.5),0],y:[0,C(0,1.5),C(0,2.5),C(0,2),0],dur:C(8,3)}),[]),l=c.useMemo(()=>C(3.5,1.5),[]);return e.jsxs(y.g,{animate:{x:i.x,y:i.y},transition:{duration:i.dur,repeat:1/0,ease:"easeInOut"},children:[e.jsx(y.circle,{cx:t,cy:s,r:a+2.5,fill:r,animate:{opacity:[0,C(.07,.03),0],r:[a+1,a+C(4,1),a+1]},transition:{duration:l*1.3,delay:n,repeat:1/0,ease:q}}),e.jsx(y.circle,{cx:t,cy:s,r:a,fill:r,animate:{opacity:[.2,.65,.2],r:[a*.9,a*C(1.06,.06),a*.9]},transition:{duration:l,delay:n,repeat:1/0,ease:q}})]})}function Ka({d:t,len:s,color:a,speed:n,intensity:r}){const i=.8+r*1;return e.jsxs(e.Fragment,{children:[e.jsx(y.path,{d:t,stroke:a,strokeWidth:i+2,fill:"none",strokeLinecap:"round",strokeDasharray:`5 ${s+4}`,initial:{strokeDashoffset:6,opacity:0},animate:{strokeDashoffset:-(s+4),opacity:[0,r*.2,0]},transition:{duration:n*1.5,ease:"easeOut"},style:{filter:"blur(2px)"}}),e.jsx(y.path,{d:t,stroke:a,strokeWidth:i,fill:"none",strokeLinecap:"round",strokeDasharray:`3 ${s+5}`,initial:{strokeDashoffset:5,opacity:0},animate:{strokeDashoffset:-(s+5),opacity:[0,r*.6,r*.35,0]},transition:{duration:n*1.2,ease:"easeOut"}})]})}function Qa({primary:t,accent:s}){const a=c.useMemo(()=>C(6,1.5),[]);return e.jsxs(e.Fragment,{children:[e.jsx(y.circle,{cx:"28",cy:"28",r:"3",fill:"none",stroke:t,strokeWidth:"0.8",animate:{r:[4,18,26],opacity:[0,.2,0],strokeWidth:[.6,.35,.1]},transition:{duration:a,repeat:1/0,ease:[.25,.1,.25,1]}}),e.jsx(y.circle,{cx:"28",cy:"28",r:"3",fill:"none",stroke:s,strokeWidth:"0.5",animate:{r:[5,15,22],opacity:[0,.12,0],strokeWidth:[.4,.25,.06]},transition:{duration:a*.85,repeat:1/0,delay:a*.35,ease:[.25,.1,.25,1]}})]})}function Za({count:t,pool:s,colors:a}){const n=c.useMemo(()=>Array.from({length:s},()=>{const r=Math.random()*Math.PI*2,i=12+Math.random()*18,l=28+Math.cos(r)*i,o=28+Math.sin(r)*i,d=Math.random()>.8,u=d?.5+Math.random()*.4:.15+Math.random()*.35,x=d?.6:1,f=[0,C(0,4*x),C(0,3*x),C(0,5*x),0],m=[0,C(0,5*x),C(0,3*x),C(0,4*x),0],p=d?C(28,10):C(16,6),h=d?C(5,2):C(2.5,1),g=d?C(.35,.15):C(.5,.2),b=Math.random()*6,j=a[Math.floor(Math.random()*a.length)];return{cx:l,cy:o,r:u,driftX:f,driftY:m,driftDur:p,blinkDur:h,blinkPeak:g,blinkDelay:b,color:j}}),[s,a]);return e.jsx(e.Fragment,{children:n.slice(0,t).map((r,i)=>e.jsx(y.circle,{cx:r.cx,cy:r.cy,r:r.r,fill:r.color,animate:{x:r.driftX,y:r.driftY,opacity:[0,r.blinkPeak,.05,r.blinkPeak*.6,0]},transition:{x:{duration:r.driftDur,repeat:1/0,ease:"easeInOut"},y:{duration:r.driftDur*1.1,repeat:1/0,ease:"easeInOut"},opacity:{duration:r.blinkDur,delay:r.blinkDelay,repeat:1/0,ease:"easeInOut"}}},`plankton-${i}`))})}function Mt({color:t,tier:s,points:a=14,scale:n=1}){const i=a,l=c.useMemo(()=>Array.from({length:8},()=>qe(28,i,18*n,5*n)),[n]),o=c.useMemo(()=>Array.from({length:8},()=>qe(28,i,24*n,7*n)),[n]),d=c.useMemo(()=>Array.from({length:8},()=>qe(28,i,27*n,9*n)),[n]),u=c.useMemo(()=>C(12,2),[]),x=c.useMemo(()=>C(15,2),[]),f=c.useMemo(()=>C(18,3),[]);return e.jsxs(e.Fragment,{children:[s==="full"&&e.jsx(y.path,{d:d[0],animate:{d},transition:{duration:f,repeat:1/0,ease:"easeInOut",repeatType:"reverse"},fill:t.replace("1)","0.012)"),stroke:t,strokeWidth:"0.15",strokeOpacity:"0.04",style:{filter:"blur(3px)"}}),s!=="compact"&&e.jsx(y.path,{d:o[0],animate:{d:o},transition:{duration:x,repeat:1/0,ease:"easeInOut",repeatType:"reverse"},fill:t.replace("1)","0.02)"),stroke:t,strokeWidth:"0.3",strokeOpacity:"0.07",style:{filter:"blur(2px)"}}),e.jsx(y.path,{d:l[0],animate:{d:l},transition:{duration:u,repeat:1/0,ease:"easeInOut",repeatType:"reverse"},fill:t.replace("1)","0.035)"),stroke:t,strokeWidth:s==="compact"?"0.4":"0.5",strokeOpacity:s==="compact"?"0.12":"0.14",style:{filter:s==="compact"?"blur(1px)":"blur(1.5px)"}})]})}function en({type:t,color:s,accentColor:a,radius:n}){var u,x,f,m;const r=c.useMemo(()=>C(9,3),[]),i=28,l=28,o=c.useMemo(()=>{switch(t){case"spots":return{circles:Array.from({length:6+Math.floor(Math.random()*4)},()=>{const p=Math.random()*Math.PI*2,h=2+Math.random()*n*.7;return{x:i+Math.cos(p)*h,y:l+Math.sin(p)*h,r:1.2+Math.random()*2}})};case"stripes":{const p=5+Math.floor(Math.random()*4);return{lines:Array.from({length:p},(h,g)=>{const b=g/p*Math.PI*2+Math.random()*.3,j=n*(.5+Math.random()*.5);return{x1:i+Math.cos(b)*3,y1:l+Math.sin(b)*3,x2:i+Math.cos(b)*j,y2:l+Math.sin(b)*j}})}}case"rings":return{rings:[.35,.55,.75,.9].filter(()=>Math.random()>.15).map(p=>n*p)};case"veins":return{paths:Array.from({length:4+Math.floor(Math.random()*3)},()=>{const p=Math.random()*Math.PI*2,h=n*(.5+Math.random()*.5),g=i+Math.cos(p)*h,b=l+Math.sin(p)*h,j=p+(Math.random()-.5)*1,N=h*(.3+Math.random()*.4),v=i+Math.cos(j)*N,S=l+Math.sin(j)*N;return`M ${i} ${l} Q ${v.toFixed(1)} ${S.toFixed(1)} ${g.toFixed(1)} ${b.toFixed(1)}`})};default:return null}},[t,n]);if(!o)return null;const d=t==="spots"?a:s;return e.jsxs(y.g,{animate:{opacity:[.5,.85,.5]},transition:{duration:r,repeat:1/0,ease:q},children:[(u=o.circles)==null?void 0:u.map((p,h)=>e.jsx("circle",{cx:p.x,cy:p.y,r:p.r,fill:d,opacity:.3,style:{filter:"blur(0.5px)"}},`s${h}`)),(x=o.lines)==null?void 0:x.map((p,h)=>e.jsx("line",{x1:p.x1,y1:p.y1,x2:p.x2,y2:p.y2,stroke:d,strokeWidth:.8,opacity:.25,strokeLinecap:"round"},`l${h}`)),(f=o.rings)==null?void 0:f.map((p,h)=>e.jsx("circle",{cx:i,cy:l,r:p,fill:"none",stroke:d,strokeWidth:.6,opacity:.2},`r${h}`)),(m=o.paths)==null?void 0:m.map((p,h)=>e.jsx("path",{d:p,fill:"none",stroke:d,strokeWidth:.6,opacity:.2,strokeLinecap:"round"},`p${h}`))]})}function tn({growth:t,color:s,aspect:a}){const l=7*a,o=c.useMemo(()=>C(3.5,.5),[]),d=ne(t,.12,.1);return e.jsxs(y.g,{initial:{scale:.2,opacity:0},animate:{scale:1,opacity:1,rotate:d>0?[0,-3*d,2.5*d,-4*d,3*d,0]:0},transition:{scale:{duration:1.2,ease:[.16,1,.3,1]},opacity:{duration:.8,ease:"easeOut"},rotate:{duration:1.5,repeat:1/0,ease:"easeInOut"}},style:{transformOrigin:"28px 28px"},children:[e.jsx(y.ellipse,{cx:28,cy:28,rx:l+6,ry:13,fill:he(s,.06),animate:{rx:[l+4,l+9,l+4],ry:[11,16,11],opacity:[.03,.1,.03]},transition:{duration:4,repeat:1/0,ease:q},style:{filter:"blur(4px)"}}),e.jsx(y.ellipse,{cx:28,cy:28,rx:l+2,ry:9,fill:he(s,.12),animate:{rx:[l+1,l+4,l+1],ry:[8,11,8],opacity:[.06,.18,.06]},transition:{duration:o,repeat:1/0,ease:q},style:{filter:"blur(2.5px)"}}),e.jsx(y.ellipse,{cx:28,cy:28,rx:l,ry:7,fill:he(s,.65),stroke:he(s,.25),strokeWidth:.5,animate:{scaleX:[1,.94,1.05,.97,1],scaleY:[1,1.07,.95,1.04,1],opacity:[.55,.8,.6,.75,.55]},transition:{duration:o,repeat:1/0,ease:q},style:{transformOrigin:"28px 28px"}}),e.jsx(y.ellipse,{cx:28,cy:28,rx:l*.4,ry:7*.45,fill:"rgba(255,255,255,0.45)",animate:{opacity:[.12,.4,.18,.32,.12],rx:[l*.3,l*.5,l*.35,l*.45,l*.3],ry:[7*.35,7*.55,7*.4,7*.5,7*.35]},transition:{duration:o*.7,repeat:1/0,ease:q}})]})}function Tt({growth:t,baseR:s,color:a,divisionRounds:n,clusterAngle:r,clusterSpread:i,growthOffset:l}){const o=c.useMemo(()=>`goo-${Math.random().toString(36).slice(2,8)}`,[]),d=c.useMemo(()=>C(8,2.5),[]),u=c.useMemo(()=>({x:[0,C(0,1.2),C(0,.8),C(0,1),0],y:[0,C(0,.8),C(0,1.2),C(0,1),0]}),[]),x=c.useMemo(()=>{const M=[r];for(let L=1;L<n;L++)M.push(M[L-1]+Math.PI*(.4+Math.random()*.2));return M},[r,n]),f=1<<n,m=c.useMemo(()=>Array.from({length:f},()=>({dx:[0,C(0,.6),C(0,.4),C(0,.5),0],dy:[0,C(0,.4),C(0,.6),C(0,.5),0],dur:C(14,5)})),[f]),p=l,h=ne(t,.15+p,.12);if(h<=0)return null;const g=.28,b=.12,j=[];for(let M=0;M<n;M++)j.push(ne(t,g+M*b+p,.1));const N=[];let v=i;for(let M=0;M<n;M++)N.push(v),v*=.6;const S=j.reduce((M,L)=>M+L,0),T=s*Math.pow(.85,S),w=(.8+T*.25).toFixed(1),k=28,$=[];for(let M=0;M<f;M++){let L=k,O=k;for(let R=0;R<n;R++){const Y=M>>R&1?1:-1,Q=N[R]*j[R]*.5;L+=Y*Math.cos(x[R])*Q,O+=Y*Math.sin(x[R])*Q}$.push({x:L,y:O,r:T})}return e.jsxs(y.g,{animate:{x:u.x,y:u.y},transition:{duration:12,repeat:1/0,ease:"easeInOut"},style:{opacity:h,transition:"opacity 0.5s ease-out"},children:[e.jsx("defs",{children:e.jsxs("filter",{id:o,children:[e.jsx("feGaussianBlur",{in:"SourceGraphic",stdDeviation:w,result:"blur"}),e.jsx("feColorMatrix",{in:"blur",mode:"matrix",values:"1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 24 -9"})]})}),e.jsx(y.g,{filter:`url(#${o})`,animate:{scaleX:[1,1.015,.985,1.01,.99,1],scaleY:[1,.99,1.02,.985,1.01,1]},transition:{duration:d,repeat:1/0,ease:q},style:{transformOrigin:"28px 28px"},children:$.map((M,L)=>e.jsx(y.circle,{cx:M.x,cy:M.y,r:M.r,animate:{cx:M.x,cy:M.y,r:M.r},transition:{duration:.25,ease:"easeOut"},fill:a},L))}),$.slice(0,6).map((M,L)=>{const O=m[L];return e.jsx(y.g,{animate:{x:M.x-k+O.dx[0],y:M.y-k+O.dy[0]},transition:{duration:.25,ease:"easeOut"},children:e.jsxs(y.g,{animate:{x:O.dx,y:O.dy},transition:{duration:O.dur,repeat:1/0,ease:"easeInOut"},children:[e.jsx(y.circle,{cx:k,cy:k,r:M.r+2,fill:a,animate:{opacity:[0,.08,.02,.06,0]},transition:{duration:d*1.1,repeat:1/0,ease:q,delay:L*.37%d},style:{filter:"blur(1.5px)"}}),e.jsx(y.circle,{cx:k,cy:k,r:M.r*.25,fill:"rgba(255,255,255,1)",animate:{opacity:[.04,.18,.06,.14,.04]},transition:{duration:d*.8,repeat:1/0,ease:q,delay:L*.29%d}})]})},`ov-${L}`)})]})}function J({size:t=56,growthDuration:s=20}){const a=t<=40?"compact":t<=80?"standard":"full",{genome:n,palette:r,armData:i}=c.useMemo(()=>{const I=Ya(),F=St(I.hue,I.accentHue),z=Va(I);return{genome:I,palette:F,armData:z}},[]),[l,o]=c.useState(0),[d,u]=c.useState(0);c.useEffect(()=>{const I=performance.now(),F=setInterval(()=>{const B=(performance.now()-I)/1e3,ce=Math.min(B/s,1),Ue=1-(1-ce)*(1-ce);if(o(Ue),u(B),ce>=1&&B>s+1){clearInterval(F);const pe=setInterval(()=>{u((performance.now()-I)/1e3)},2e3);z.current=pe}},100),z={current:F};return()=>clearInterval(z.current)},[s]);const x=c.useRef(l);x.current=l;const f=n.growthOffset,m=(I,F)=>ne(l,I+f,F),p=1-m(.2,.12),h=m(.22,.18),g=a==="compact"||l<.5+f?"compact":l<.75+f||a!=="full"?"standard":"full",b=a==="full"?14:a==="standard"?6:0,j=b+4,N=l>=1?Math.floor(Math.sin(d*.03)*2+2):0,v=Math.floor((b+N)*m(.65,.25)),S=l>=.85+f&&a==="full",T=l>=1?Math.sin(d*.005)*8:0,w=c.useMemo(()=>{if(T===0)return r;const I=n.hue+T;return St(I,n.accentHue+T*.5)},[Math.round(T*2),n.hue,n.accentHue,r]),k=c.useMemo(()=>({driftDir:Math.random()>.5?360:-360,driftDur:C(200,80),wobbleAngles:[0,C(8,5),C(-5,4),C(25,15),C(-6,5),C(10,6),C(-20,12),C(6,4),0],wobbleDur:C(40,15)}),[]),$=c.useRef(i);$.current=i;const M=c.useMemo(()=>{if(a==="compact")return[];const I=[...i.arms,...i.connectors],F=i.arms.length;return I.map((z,B)=>{const ce=B>=F;return{origIdx:B,d:kt(z.d,4),len:z.baselen,delay:Math.random()*4,duration:C(1.4,.6),color:ce?B%2===0?w.accent:w.accentAlt:z.weight>.75?w.primary:w.primaryDeep,repeatDelay:C(2.5,1.5),weight:z.weight}})},[a,i,w]),L=c.useMemo(()=>{if(a==="compact")return[];const I=he(w.primary,.9),F=he(w.primaryDeep,.9);return i.arms.map((z,B)=>({cx:C(z.endX,1.5),cy:C(z.endY,1.5),r:C(1.6,.3),color:B%3===2?F:I,delay:Math.random()*2}))},[a,i,w]),[O,R]=c.useState([]),[G,Y]=c.useState(!1),[Q,U]=c.useState(()=>Array(20).fill(0)),A=c.useRef(0),P=c.useRef(!1);c.useEffect(()=>{if(a==="compact")return;P.current=!1;const I=()=>{if(P.current)return;const z=$.current,B=[...z.arms,...z.connectors];if(x.current<.55+n.growthOffset||B.length===0){setTimeout(I,300+Math.random()*700);return}Y(!0),setTimeout(()=>{if(P.current)return;Y(!1);const pe=Math.floor(Math.random()*B.length),ft=B[pe],gt=++A.current,yt=C(.5,.2),Rs=C(.8,.2);U(fe=>{const ge=[...fe];return ge[pe]=(ge[pe]??0)+1,ge}),R(fe=>[...fe,{id:gt,d:kt(ft.d,6),len:ft.baselen,color:w.sparkColors[Math.floor(Math.random()*w.sparkColors.length)],speed:yt,intensity:Rs}]),setTimeout(()=>{R(fe=>fe.filter(ge=>ge.id!==gt))},yt*1.3*1e3+400)},180);const Ue=(a==="full"?1200+Math.random()*4e3:2500+Math.random()*6e3)/n.sparkRate;setTimeout(I,Ue)},F=setTimeout(I,400+Math.random()*1500);return()=>{P.current=!0,clearTimeout(F)}},[a,n,w]);const H=c.useMemo(()=>C(3.8,.3)*n.coreScale,[n.coreScale]),_=1+m(.7,.2)*.6;return e.jsxs("svg",{width:t,height:t,viewBox:"0 0 56 56",fill:"none",className:"flex-shrink-0 overflow-visible",style:{filter:t>=80?"drop-shadow(0 2px 6px rgba(0,0,0,0.4))":void 0},children:[t>=80&&e.jsx("defs",{children:e.jsxs("radialGradient",{id:"depth-glow",cx:"0.4",cy:"0.35",r:"0.6",children:[e.jsx("stop",{offset:"0%",stopColor:"rgba(255,255,255,0.06)"}),e.jsx("stop",{offset:"100%",stopColor:"rgba(0,0,0,0)"})]})}),t>=80&&e.jsx("circle",{cx:"28",cy:"28",r:"22",fill:"url(#depth-glow)",opacity:l>.3?.7:0,style:{transition:"opacity 1s"}}),j>0&&v>0&&e.jsx(Za,{count:v,pool:j,colors:w.planktonColors}),e.jsx(y.g,{animate:{rotate:[0,k.driftDir]},transition:{duration:k.driftDur,repeat:1/0,ease:"linear"},style:{transformOrigin:"28px 28px"},children:e.jsxs(y.g,{animate:{rotate:k.wobbleAngles},transition:{duration:k.wobbleDur,repeat:1/0,ease:"easeInOut"},style:{transformOrigin:"28px 28px"},children:[p>0&&e.jsx("g",{style:{opacity:p,transition:"opacity 0.5s ease-out"},children:e.jsx(tn,{growth:l,color:w.primary,aspect:n.eggAspect})}),h>0&&e.jsx("g",{style:{opacity:h,transition:"opacity 0.5s ease-out"},children:e.jsx(Mt,{color:w.primary,tier:g,points:n.membraneLobes,scale:n.bodyRadius})}),h>0&&n.pattern!=="none"&&e.jsx("g",{style:{opacity:h,transition:"opacity 0.5s ease-out"},children:e.jsx(en,{type:n.pattern,color:w.primary,accentColor:w.accent,radius:18*n.bodyRadius})}),S&&e.jsx(Qa,{primary:w.primary,accent:w.accent}),M.map((I,F)=>{const z=.3+f+F/Math.max(M.length-1,1)*.3,B=ne(l,z,.1);return B<=0?null:e.jsx("g",{style:{opacity:B,transition:"opacity 0.5s ease-out"},children:e.jsx(Ja,{d:I.d,len:I.len,delay:I.delay,duration:I.duration,color:I.color,repeatDelay:I.repeatDelay,weight:I.weight,hitCount:Q[I.origIdx]??0})},I.origIdx)}),l>=.55+f&&O.map(I=>e.jsx(Ka,{d:I.d,len:I.len,color:I.color,speed:I.speed,intensity:I.intensity},I.id)),L.map((I,F)=>{const z=.5+f+F/Math.max(L.length-1,1)*.2,B=ne(l,z,.1);return B<=0?null:e.jsx("g",{style:{opacity:B,transition:"opacity 0.5s ease-out"},children:e.jsx(Xa,{cx:I.cx,cy:I.cy,r:I.r*_,delay:I.delay,color:I.color})},F)}),e.jsx(Tt,{growth:l,baseR:H,color:w.core,divisionRounds:n.divisionRounds,clusterAngle:n.clusterAngle,clusterSpread:n.clusterSpread,growthOffset:f}),n.mutation.twinCore&&l>.5&&e.jsx(y.g,{animate:{rotate:[0,360]},transition:{duration:30,repeat:1/0,ease:"linear"},style:{transformOrigin:"28px 28px",opacity:ne(l,.5,.15)},children:e.jsx("g",{transform:"translate(7, 0)",children:e.jsx(Tt,{growth:l,baseR:H*.55,color:w.accent,divisionRounds:Math.max(2,n.divisionRounds-1),clusterAngle:n.clusterAngle+Math.PI*.7,clusterSpread:n.clusterSpread*.5,growthOffset:f+.1})})}),e.jsx(W,{children:G&&l>=.55+f&&a!=="compact"&&e.jsx(y.circle,{cx:"28",cy:"28",r:H+2,fill:"rgba(255,255,255,1)",initial:{opacity:0},animate:{opacity:.08},exit:{opacity:0},transition:{duration:.4,ease:"easeOut"},style:{filter:"blur(2px)"}},"anticipation")}),n.mutation.rings&&l>.7&&e.jsxs(e.Fragment,{children:[e.jsx(y.circle,{cx:"28",cy:"28",r:"12",fill:"none",stroke:w.primary,strokeWidth:"0.3",animate:{r:[10,14,10],opacity:[0,.12,0],strokeWidth:[.2,.4,.2]},transition:{duration:7,repeat:1/0,ease:q}}),e.jsx(y.circle,{cx:"28",cy:"28",r:"20",fill:"none",stroke:w.accent,strokeWidth:"0.2",animate:{r:[17,22,17],opacity:[0,.08,0],strokeWidth:[.15,.3,.15]},transition:{duration:9.5,repeat:1/0,ease:q,delay:2}})]}),n.mutation.ghostMembrane&&l>.6&&e.jsx(y.g,{animate:{x:[0,2.5,-1.5,3,0],y:[0,-2,3,-1,0]},transition:{duration:20,repeat:1/0,ease:"easeInOut"},style:{opacity:.3},children:e.jsx(Mt,{color:w.accent,tier:"compact",points:Math.max(6,n.membraneLobes-3),scale:n.bodyRadius*.85})}),n.mutation.cometTail&&l>.5&&e.jsx(e.Fragment,{children:[0,1,2,3,4].map(I=>e.jsx(y.circle,{cx:"28",cy:"28",r:.5+I*.15,fill:w.primary,animate:{x:[0,-(4+I*3),-(2+I*2),-(5+I*2.5),0],y:[0,2+I*1.5,-(1+I),3+I*.8,0],opacity:[0,.2-I*.03,.05,.15-I*.02,0]},transition:{duration:12+I*2,repeat:1/0,ease:"easeInOut",delay:I*.8},style:{filter:"blur(1px)"}},`tail-${I}`))})]})})]})}function Ye(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function Ve(t){const s=Math.floor(t/1e3);if(s<60)return`${s}s`;const a=Math.floor(s/60),n=s%60;return a<60?`${a}m ${n}s`:`${Math.floor(a/60)}h ${a%60}m`}function sn({stats:t}){const[s,a]=c.useState(0);return c.useEffect(()=>{if(!t.startedAt||!t.isRunning)return;a(Date.now()-t.startedAt);const n=setInterval(()=>{a(Date.now()-t.startedAt)},1e3);return()=>clearInterval(n)},[t.startedAt,t.isRunning]),e.jsxs("div",{className:"border-b border-white/[0.06] pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(zs,{size:12,className:"text-semantic-success"}),e.jsx("h4",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:"Agent Details"})]}),e.jsxs("div",{className:"flex flex-col gap-1.5 mb-3",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-neutral-muted",children:"Identifier"}),e.jsx("span",{className:"font-mono text-neutral-text truncate ml-3 text-right max-w-[160px]",children:t.identifier})]}),e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-neutral-muted",children:"Phase"}),e.jsx("span",{className:"text-semantic-success font-medium",children:t.phase})]}),t.backendName&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-neutral-muted",children:"Backend"}),e.jsx("span",{className:"text-primary-500 font-mono",children:t.backendName})]}),t.pr&&e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-neutral-muted",children:"PR"}),e.jsxs("span",{className:"flex items-center gap-1 text-primary-500",children:[e.jsx(Bs,{size:10}),"#",t.pr.number,e.jsx("span",{className:"text-neutral-muted text-[10px]",children:t.pr.status})]})]})]}),t.totalTokens>0&&e.jsxs("div",{className:"rounded-lg border border-white/[0.06] bg-white/[0.02] p-3 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[e.jsx(oe,{size:10,className:"text-neutral-muted"}),e.jsx("span",{className:"text-[9px] font-black uppercase tracking-[0.15em] text-neutral-muted",children:"Session Stats"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-sm font-bold text-neutral-text",children:t.turnCount}),e.jsx("span",{className:"text-[8px] uppercase tracking-widest text-neutral-muted",children:"Turns"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-sm font-bold text-neutral-text",children:Ye(t.totalTokens)}),e.jsx("span",{className:"text-[8px] uppercase tracking-widest text-neutral-muted",children:"Tokens"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-sm font-bold text-semantic-success",children:Ye(t.inputTokens)}),e.jsx("span",{className:"text-[8px] uppercase tracking-widest text-neutral-muted",children:"Input"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-sm font-bold text-primary-500",children:Ye(t.outputTokens)}),e.jsx("span",{className:"text-[8px] uppercase tracking-widest text-neutral-muted",children:"Output"})]})]})]}),e.jsx("div",{className:"flex items-center gap-2 text-xs text-neutral-muted",children:t.isRunning?e.jsxs(e.Fragment,{children:[e.jsx(Hs,{size:10,className:"animate-spin"}),e.jsxs("span",{children:["Running for ",Ve(s)]})]}):t.durationMs?e.jsxs(e.Fragment,{children:[e.jsx(Vt,{size:10}),e.jsxs("span",{children:["Duration: ",Ve(t.durationMs)]})]}):t.startedAt?e.jsxs(e.Fragment,{children:[e.jsx(Ws,{size:10}),e.jsx("span",{children:Ve(Date.now()-t.startedAt)})]}):null})]})}function an({todos:t}){if(t.length===0)return null;const s=t.filter(a=>a.completed).length;return e.jsxs("div",{className:"border-b border-white/[0.06] pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Gs,{size:12,className:"text-neutral-muted"}),e.jsx("h4",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:"Tasks"}),e.jsxs("span",{className:"text-[9px] text-neutral-muted/60 tabular-nums",children:[s,"/",t.length]}),e.jsx("div",{className:"flex-1 h-1 rounded-full bg-white/[0.06] overflow-hidden",children:e.jsx(y.div,{className:"h-full rounded-full bg-semantic-success",initial:{width:0},animate:{width:`${s/t.length*100}%`},transition:{duration:.3}})})]}),e.jsx(W,{mode:"popLayout",children:t.map(a=>e.jsxs(y.div,{layout:!0,initial:{opacity:0,x:-8},animate:{opacity:1,x:0},exit:{opacity:0,x:8},className:"flex items-start gap-2 py-0.5",children:[a.completed?e.jsx(Jt,{size:14,className:"text-semantic-success flex-shrink-0 mt-0.5"}):e.jsx(Us,{size:14,className:"text-neutral-muted/40 flex-shrink-0 mt-0.5"}),e.jsx("span",{className:["text-xs leading-relaxed",a.completed?"text-neutral-muted/50 line-through":"text-neutral-text"].join(" "),children:a.text})]},a.id))})]})}function nn(t){const s=Math.floor(t/1e3);if(s<60)return`${s}s`;const a=Math.floor(s/60),n=s%60;return`${a}m ${n}s`}function rn({phase:t,skill:s,startedAt:a}){const[n,r]=c.useState(0);return c.useEffect(()=>{if(!a)return;const i=setInterval(()=>{r(Date.now()-a)},1e3);return()=>clearInterval(i)},[a]),!t&&!s?null:e.jsxs("div",{className:"border-b border-white/[0.06] pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(we,{size:12,className:"text-neutral-muted"}),e.jsx("h4",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:"Status"})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[t&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{size:12,className:"text-primary-500"}),e.jsx("span",{className:"text-xs text-neutral-text",children:t})]}),s&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-neutral-muted",children:"Skill:"}),e.jsx("span",{className:"text-xs text-neutral-text font-mono",children:s})]}),a&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vt,{size:12,className:"text-neutral-muted"}),e.jsx("span",{className:"text-xs text-neutral-muted tabular-nums",children:nn(n)})]})]})]})}const ln={created:"text-semantic-success",modified:"text-semantic-warning",deleted:"text-semantic-error"},on={created:"+",modified:"~",deleted:"-"};function cn({artifacts:t}){return t.length===0?null:e.jsxs("div",{className:"border-b border-white/[0.06] pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(qs,{size:12,className:"text-neutral-muted"}),e.jsx("h4",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:"Artifacts"}),e.jsx("span",{className:"text-[9px] text-neutral-muted/60 tabular-nums",children:t.length})]}),e.jsx(W,{mode:"popLayout",children:t.map(s=>e.jsxs(y.div,{layout:!0,initial:{opacity:0,x:-8},animate:{opacity:1,x:0},className:"flex items-center gap-2 py-0.5 group",children:[e.jsx("span",{className:`text-[10px] font-bold ${ln[s.action]}`,children:on[s.action]}),e.jsx("span",{className:"text-xs text-neutral-text font-mono truncate flex-1",children:s.path.split("/").pop()}),e.jsx("span",{className:"hidden group-hover:block",children:e.jsx(Ys,{size:10,className:"text-neutral-muted"})})]},s.path))})]})}function dn({status:t}){switch(t){case"loaded":return e.jsx(Jt,{size:10,className:"text-semantic-success"});case"loading":return e.jsx(Be,{size:10,className:"text-primary-500 animate-spin"});case"error":return e.jsx(Js,{size:10,className:"text-semantic-error"})}}function xn({sources:t}){return t.length===0?null:e.jsxs("div",{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Vs,{size:12,className:"text-neutral-muted"}),e.jsx("h4",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:"Context Sources"})]}),e.jsx("div",{className:"flex flex-col gap-1",children:t.map(s=>e.jsxs("div",{className:"flex items-center gap-2 py-0.5",children:[e.jsx(dn,{status:s.status}),e.jsx("span",{className:"text-xs text-neutral-muted",children:s.name})]},s.name))})]})}const un={todos:[],phase:null,skill:null,startedAt:null,artifacts:[],contextSources:[]};function mn(t){return t.todos.length>0||t.phase!==null||t.skill!==null||t.artifacts.length>0||t.contextSources.length>0||t.agentStats!=null}function hn({state:t,onClose:s}){const a=t??un,n=mn(a);return e.jsx(W,{children:n&&e.jsx(y.aside,{initial:{width:0,opacity:0},animate:{width:320,opacity:1},exit:{width:0,opacity:0},transition:{duration:.2,ease:"easeInOut"},className:"flex-shrink-0 border-l border-white/[0.06] bg-neutral-surface/10 backdrop-blur-xl overflow-hidden",children:e.jsxs("div",{className:"w-[320px] h-screen flex flex-col",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-white/[0.06] px-4 py-3",children:[e.jsx("h3",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:"Context"}),s&&e.jsx("button",{onClick:s,className:"text-neutral-muted hover:text-white transition-colors",children:e.jsx(Xs,{size:14})})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 no-scrollbar flex flex-col gap-3",children:[a.agentStats&&e.jsx(sn,{stats:a.agentStats}),e.jsx(an,{todos:a.todos}),!a.agentStats&&e.jsx(rn,{phase:a.phase,skill:a.skill,startedAt:a.startedAt}),e.jsx(cn,{artifacts:a.artifacts}),e.jsx(xn,{sources:a.contextSources})]})]})})})}const pn=[{page:"health",label:"Health",route:"/s/health"},{page:"graph",label:"Graph",route:"/s/graph"},{page:"impact",label:"Impact",route:"/s/impact"},{page:"decay",label:"Decay Trends",route:"/s/decay"},{page:"traceability",label:"Traceability",route:"/s/traceability"},{page:"orchestrator",label:"Orchestrator",route:"/s/orchestrator"},{page:"maintenance",label:"Maintenance",route:"/s/maintenance"},{page:"streams",label:"Streams",route:"/s/streams"},{page:"roadmap",label:"Roadmap",route:"/s/roadmap"},{page:"adoption",label:"Adoption",route:"/s/adoption"},{page:"tokens",label:"API Tokens",route:"/s/tokens"},{page:"webhooks",label:"Webhooks",route:"/s/webhooks"},{page:"insights-cache",label:"Prompt Cache",route:"/s/insights-cache"},{page:"proposals",label:"Proposals",route:"/s/proposals"},{page:"routing",label:"Routing",route:"/s/routing"}];function fn({size:t=32}){const a=!ua(),n=c.useMemo(()=>185+Math.floor(Math.random()*12)-6,[]);return e.jsxs("div",{className:"relative flex items-center justify-center shrink-0 mr-3",style:{width:t,height:t},children:[e.jsx(y.div,{className:"absolute inset-[-4px] rounded-full",style:{background:`radial-gradient(circle, hsla(${n}, 95%, 60%, 0.2) 0%, hsla(${n}, 90%, 45%, 0.1) 50%, transparent 75%)`},...a?{animate:{scale:[1,1.15,1],opacity:[.4,.7,.4]},transition:{duration:4,repeat:1/0,ease:"easeInOut"}}:{}}),a&&e.jsx(y.div,{className:"absolute inset-[-8px] rounded-full",style:{background:`radial-gradient(circle, hsla(${n}, 100%, 75%, 0.3) 0%, transparent 60%)`},animate:{scale:[.9,1.4,.9],opacity:[0,.4,0]},transition:{duration:6,repeat:1/0,ease:"easeInOut",times:[0,.3,1]}}),e.jsxs("svg",{viewBox:"0 0 100 100",className:"w-full h-full overflow-visible relative z-10",children:[e.jsxs("defs",{children:[e.jsxs("radialGradient",{id:"sigil-bio-core",children:[e.jsx("stop",{offset:"0%",stopColor:`hsl(${n+10}, 100%, 95%)`}),e.jsx("stop",{offset:"25%",stopColor:`hsl(${n}, 100%, 72%)`}),e.jsx("stop",{offset:"55%",stopColor:`hsl(${n-5}, 90%, 50%)`}),e.jsx("stop",{offset:"100%",stopColor:`hsl(${n-15}, 80%, 22%)`})]}),e.jsx("filter",{id:"sig-glow",children:e.jsx("feGaussianBlur",{in:"SourceGraphic",stdDeviation:"2"})})]}),e.jsxs(y.g,{...a?{animate:{rotate:360},transition:{duration:45,repeat:1/0,ease:"linear"}}:{},style:{transformOrigin:"50px 50px"},children:[e.jsx("circle",{cx:"50",cy:"50",r:"42",fill:"none",stroke:`hsla(${n}, 90%, 65%, 0.15)`,strokeWidth:"3",strokeDasharray:"10 5",filter:"url(#sig-glow)"}),e.jsx("circle",{cx:"50",cy:"50",r:"42",fill:"none",stroke:`hsla(${n}, 85%, 72%, 0.6)`,strokeWidth:"1.6",strokeDasharray:"10 5"})]}),e.jsxs(y.g,{...a?{animate:{rotate:-360},transition:{duration:28,repeat:1/0,ease:"linear"}}:{},style:{transformOrigin:"50px 50px"},children:[e.jsx("circle",{cx:"50",cy:"50",r:"28",fill:"none",stroke:`hsla(${n+20}, 80%, 68%, 0.15)`,strokeWidth:"2.5",strokeDasharray:"6 8",filter:"url(#sig-glow)"}),e.jsx("circle",{cx:"50",cy:"50",r:"28",fill:"none",stroke:`hsla(${n+20}, 80%, 74%, 0.5)`,strokeWidth:"1.2",strokeDasharray:"6 8"})]}),e.jsx(y.circle,{cx:"50",cy:"50",r:"18",fill:"url(#sigil-bio-core)",filter:"url(#sig-glow)",...a?{animate:{r:[16,20,16],opacity:[.5,.8,.5]},transition:{duration:4,repeat:1/0,ease:"easeInOut"}}:{},opacity:.6}),e.jsx(y.circle,{cx:"50",cy:"50",r:"14",fill:"url(#sigil-bio-core)",...a?{animate:{r:[13,15,13]},transition:{duration:3,repeat:1/0,ease:"easeInOut"}}:{}}),e.jsx(y.circle,{cx:"50",cy:"50",r:"6",fill:`hsl(${n+10}, 100%, 90%)`,...a?{animate:{r:[5,7,5],opacity:[.9,1,.9]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut"}}:{}}),e.jsx("circle",{cx:"50",cy:"50",r:"2.5",fill:"white"}),a&&[0,120,240].map((r,i)=>e.jsx(y.g,{animate:{rotate:i%2===0?360:-360},transition:{duration:8+i*4,repeat:1/0,ease:"linear"},style:{transformOrigin:"50px 50px"},children:e.jsx(y.circle,{cx:86,cy:"50",r:2.5-i*.3,fill:`hsla(${n+i*40}, 95%, 78%, 1)`,animate:{opacity:[.5,1,.5]},transition:{duration:1.8,delay:i*.4,repeat:1/0,ease:"easeInOut"},style:{transform:`rotate(${r}deg)`,transformOrigin:"50px 50px"}})},r))]})]})}function Ce({label:t,count:s,defaultOpen:a=!0,children:n}){const[r,i]=c.useState(a);return e.jsxs("div",{className:"mb-1",children:[e.jsxs("button",{onClick:()=>i(!r),className:"flex w-full items-center gap-2 px-3 py-2 text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted hover:text-neutral-text transition-colors",children:[e.jsx(y.div,{animate:{rotate:r?0:-90},transition:{duration:.2},children:e.jsx(He,{size:12})}),e.jsx("span",{className:"flex-1 text-left",children:t}),s!==void 0&&s>0&&e.jsx("span",{className:"rounded-full bg-primary-500/20 px-1.5 py-0.5 text-[8px] font-bold text-primary-500 tabular-nums",children:s})]}),e.jsx(W,{initial:!1,children:r&&e.jsx(y.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:"easeInOut"},className:"overflow-hidden",children:n})})]})}const gn={health:we,graph:aa,impact:oe,decay:sa,traceability:ta,orchestrator:it,maintenance:ea,streams:Zs,roadmap:Qs,adoption:Ks};function yn({page:t,label:s,route:a}){const n=gn[t]??we;return e.jsxs(Ds,{to:a,className:({isActive:r})=>["flex items-center gap-2.5 rounded-lg px-3 py-1.5 text-xs font-medium transition-all duration-200",r?"bg-white/[0.08] text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.06)]":"text-neutral-muted hover:text-neutral-text hover:bg-white/[0.04]"].join(" "),children:[e.jsx(n,{size:14,className:"flex-shrink-0 opacity-60"}),e.jsx("span",{children:s})]})}function bn({thread:t}){const s="h-5 w-5 flex-shrink-0 rounded-md flex items-center justify-center";switch(t.avatar){case"organism":return e.jsx("div",{className:`${s} bg-secondary-400/15`,children:e.jsx(it,{size:12,className:"text-secondary-400"})});case"alert":return e.jsx("div",{className:`${s} bg-semantic-warning/15`,children:e.jsx(Xt,{size:12,className:"text-semantic-warning"})});case"user":return e.jsx("div",{className:`${s} bg-primary-500/15`,children:e.jsx(ra,{size:12,className:"text-primary-500"})});default:return e.jsx("div",{className:`${s} bg-white/[0.06]`,children:e.jsx(na,{size:12,className:"text-neutral-muted"})})}}function jn({thread:t}){return t.status==="pending"?e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-semantic-warning animate-pulse flex-shrink-0"}):t.status==="active"?e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-semantic-success flex-shrink-0"}):null}function Je({thread:t,dimmed:s}){const a=X(),r=E(i=>i.activeThreadId)===t.id;return e.jsxs("button",{onClick:()=>{E.getState().setActiveThread(t.id),a(`/t/${t.id}`)},className:["group flex w-full items-center gap-2 rounded-lg px-3 py-1.5 text-xs transition-all duration-150",r?"bg-white/[0.08] text-white":s?"text-neutral-muted/60 hover:text-neutral-muted hover:bg-white/[0.03]":"text-neutral-text hover:bg-white/[0.04]"].join(" "),children:[e.jsx(bn,{thread:t}),e.jsx("span",{className:"flex-1 truncate text-left",children:t.title}),e.jsx(jn,{thread:t}),t.unread&&e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary-500 flex-shrink-0"}),t.type!=="attention"&&e.jsx("span",{onClick:i=>{i.stopPropagation(),E.getState().closeThread(t.id),r&&a("/")},className:"hidden group-hover:flex h-4 w-4 items-center justify-center rounded text-neutral-muted hover:text-white hover:bg-white/[0.08]",children:e.jsx(lt,{size:10})})]})}function Nn(){const t=X(),s=E(i=>i.threads),a=c.useMemo(()=>va({threads:s}),[s]),n=()=>{const i=rs();E.getState().setActiveThread(i.id),t(`/t/${i.id}`)},r=()=>{const i=E.getState(),l=i.createThread("analysis",{analysisTitle:"New Analysis",description:"",labels:[]});i.setActiveThread(l.id),t(`/t/${l.id}`)};return e.jsxs("aside",{className:"flex h-screen w-[280px] flex-shrink-0 flex-col border-r border-white/[0.06]",children:[e.jsxs("div",{className:"flex items-center border-b border-white/[0.06] px-4 py-3",children:[e.jsx(fn,{size:32}),e.jsxs("div",{className:"flex flex-col flex-1",children:[e.jsx("span",{className:"text-[11px] font-black tracking-tight text-neutral-text",children:"Harness"}),e.jsx("span",{className:"text-[8px] font-bold uppercase tracking-[0.2em] text-primary-500/70",children:"Engineering"})]})]}),e.jsxs("div",{className:"flex-1 flex flex-col bg-neutral-surface/20 backdrop-blur-xl overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-white/[0.06] px-3 py-2.5",children:[e.jsxs("button",{onClick:n,className:"flex flex-1 items-center justify-center gap-1.5 rounded-lg bg-primary-500/10 border border-primary-500/20 px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest text-primary-500 hover:bg-primary-500/20 transition-colors",children:[e.jsx(ot,{size:12}),"New Chat"]}),e.jsxs("button",{onClick:r,className:"flex items-center justify-center gap-1.5 rounded-lg bg-white/[0.04] border border-white/[0.08] px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest text-neutral-muted hover:text-neutral-text hover:bg-white/[0.08] transition-colors",children:[e.jsx(ct,{size:12}),"Analyze"]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto py-2 no-scrollbar",children:[e.jsx(Ce,{label:"Active",count:a.active.length,children:a.active.length===0?e.jsx("p",{className:"px-3 py-2 text-[10px] text-neutral-muted/50 italic",children:"No active threads"}):a.active.map(i=>e.jsx(Je,{thread:i},i.id))}),e.jsx(Ce,{label:"Attention",count:a.attention.length,defaultOpen:!1,children:a.attention.length===0?e.jsx("p",{className:"px-3 py-2 text-[10px] text-neutral-muted/50 italic",children:"No pending items"}):a.attention.map(i=>e.jsx(Je,{thread:i},i.id))}),e.jsx(Ce,{label:"Recent",count:a.recent.length,defaultOpen:!1,children:a.recent.length===0?e.jsx("p",{className:"px-3 py-2 text-[10px] text-neutral-muted/50 italic",children:"No recent threads"}):a.recent.map(i=>e.jsx(Je,{thread:i,dimmed:!0},i.id))}),e.jsx(Ce,{label:"System",children:e.jsx("div",{className:"flex flex-col gap-0.5 px-1",children:pn.map(i=>e.jsx(yn,{page:i.page,label:i.label,route:i.route},i.page))})})]})]})]})}const ds=c.createContext({});function vn({children:t}){const s=Os(),[a,n]=c.useState({x:0,y:0}),[r,i]=c.useState(!1),l=E(m=>m.activeThreadId),o=s.pathname.startsWith("/s/"),d=ke();Ta(d),Ca(d),Ia();const u=E(m=>l?m.panelState.get(l)??null:null),x=o?null:u;c.useEffect(()=>{i(!0);const m=setTimeout(()=>i(!1),800);return()=>clearTimeout(m)},[s.pathname]);const f=m=>{n({x:m.clientX,y:m.clientY})};return e.jsxs("div",{className:"h-screen flex text-neutral-text selection:bg-primary-500/30 overflow-hidden relative",onMouseMove:f,children:[e.jsx("div",{className:"neural-noise"}),e.jsx(qa,{mouseX:a.x,mouseY:a.y}),e.jsx("div",{className:"organism-float",style:{left:200,top:10},children:e.jsx(J,{size:50,growthDuration:18})}),e.jsx("div",{className:"organism-float organism-float-2",style:{left:"60%",top:"70%"},children:e.jsx(J,{size:80,growthDuration:25})}),e.jsx("div",{className:"organism-float organism-float-3",style:{left:"30%",top:"40%"},children:e.jsx(J,{size:60,growthDuration:30})}),e.jsx(Nn,{}),e.jsxs("main",{className:"flex-1 flex flex-col relative min-w-0 overflow-y-auto",children:[e.jsx(W,{children:r&&e.jsx(y.div,{initial:{scaleX:0,opacity:0},animate:{scaleX:1,opacity:1},exit:{opacity:0},transition:{duration:.8,ease:"circOut"},className:"absolute top-0 left-0 right-0 h-[2px] bg-gradient-to-r from-primary-500 via-secondary-400 to-primary-500 z-50 origin-left shadow-[0_0_15px_var(--color-primary-500)]"})}),e.jsx(ds.Provider,{value:d.agentEvents,children:e.jsx(W,{mode:"wait",children:e.jsx(y.div,{initial:{opacity:0,y:4},animate:{opacity:1,y:0},exit:{opacity:0,y:-4},transition:{duration:.15,ease:"easeInOut"},className:"flex-1 flex flex-col",children:t},s.pathname)})})]}),e.jsx(hn,{state:x})]})}const le=[{id:"harness:validate",name:"Validate Project",description:"Run comprehensive project health checks and dependency validation.",category:"health",slashCommand:"/harness:validate"},{id:"harness:verify",name:"Verify Implementation",description:"Deep audit of implemented artifacts against their specs and plans.",category:"health",slashCommand:"/harness:verify"},{id:"harness:integrity",name:"Check Integrity",description:"Verify codebase integrity and find missing or orphaned files.",category:"health",slashCommand:"/harness:integrity"},{id:"harness:security-scan",name:"Security Scan",description:"Scan codebase for secrets, vulnerabilities, and misconfigurations.",category:"security",slashCommand:"/harness:security-scan",contextSources:["/api/checks"]},{id:"harness:supply-chain-audit",name:"Supply Chain Audit",description:"Analyze dependency tree for security risks and license compliance.",category:"security",slashCommand:"/harness:supply-chain-audit"},{id:"harness:perf",name:"Performance Audit",description:"Analyze performance bottlenecks and resource utilization.",category:"performance",slashCommand:"/harness:perf",contextSources:["/api/checks"]},{id:"harness:enforce-architecture",name:"Enforce Architecture",description:"Check for architectural violations and boundary drift.",category:"architecture",slashCommand:"/harness:enforce-architecture",contextSources:["/api/checks"]},{id:"harness:dependency-health",name:"Dependency Health",description:"Evaluate dependency graph for cycles and outdated packages.",category:"architecture",slashCommand:"/harness:dependency-health"},{id:"harness:code-review",name:"Code Review",description:"Perform an automated deep-context code review of recent changes.",category:"code-quality",slashCommand:"/harness:code-review"},{id:"harness:codebase-cleanup",name:"Codebase Cleanup",description:"Identify and remove redundant or unreachable code.",category:"code-quality",slashCommand:"/harness:codebase-cleanup"},{id:"harness:cleanup-dead-code",name:"Cleanup Dead Code",description:"Specifically target and remove exported symbols with no consumers.",category:"code-quality",slashCommand:"/harness:cleanup-dead-code"},{id:"harness:detect-doc-drift",name:"Detect Doc Drift",description:"Find mismatches between implementation and documentation.",category:"code-quality",slashCommand:"/harness:detect-doc-drift"},{id:"harness:knowledge-pipeline",name:"Knowledge Pipeline",description:"Extract business knowledge, detect drift, materialize docs, and report coverage gaps.",category:"code-quality",slashCommand:"/harness:knowledge-pipeline"},{id:"harness:brainstorming",name:"Brainstorm",description:"Explore ideas, architectural patterns, and implementation strategies.",category:"workflow",slashCommand:"/harness:brainstorming"},{id:"harness:planning",name:"Plan Feature",description:"Generate a detailed implementation plan with atomic tasks.",category:"workflow",slashCommand:"/harness:planning"},{id:"harness:execution",name:"Execute Plan",description:"Implement a feature or fix task-by-task with atomic commits.",category:"workflow",slashCommand:"/harness:execution"},{id:"harness:tdd",name:"TDD Loop",description:"Execute a test-driven development cycle for a specific unit.",category:"workflow",slashCommand:"/harness:tdd"},{id:"harness:debugging",name:"Debug Issue",description:"Analyze logs, traces, and code to find and fix the root cause.",category:"workflow",slashCommand:"/harness:debugging"},{id:"harness:refactoring",name:"Refactor Code",description:"Safely reorganize code for better maintainability without changing behavior.",category:"workflow",slashCommand:"/harness:refactoring"},{id:"harness:onboarding",name:"Codebase Onboarding",description:"Get a high-level overview of the project structure and patterns.",category:"workflow",slashCommand:"/harness:onboarding"},{id:"harness:autopilot",name:"Autopilot",description:"Run an autonomous agent loop to solve a complex issue.",category:"workflow",slashCommand:"/harness:autopilot"},{id:"harness:roadmap-pilot",name:"Roadmap Pilot",description:"Autonomously execute the next logical item on the roadmap.",category:"workflow",slashCommand:"/harness:roadmap-pilot"},{id:"harness:roadmap-sync",name:"Roadmap Sync",description:"Update existing roadmap feature statuses based on current codebase state.",category:"workflow",slashCommand:"/harness:roadmap --sync"},{id:"harness:roadmap-add",name:"Add to Roadmap",description:"Interactively add a new feature to the roadmap.",category:"workflow",slashCommand:"/harness:roadmap --add"}],wn={health:es,security:Zt,performance:we,architecture:Qt,"code-quality":Kt,workflow:oe},kn={health:"text-emerald-400 bg-emerald-400/10 border-emerald-400/20",security:"text-red-400 bg-red-400/10 border-red-400/20",performance:"text-amber-400 bg-amber-400/10 border-amber-400/20",architecture:"text-blue-400 bg-blue-400/10 border-blue-400/20","code-quality":"text-purple-400 bg-purple-400/10 border-purple-400/20",workflow:"text-secondary-400 bg-secondary-400/10 border-secondary-400/20"};function Sn({skill:t,onClick:s}){const a=wn[t.category],n=kn[t.category];return e.jsxs("button",{onClick:s,className:"group flex items-center gap-3 w-full px-3 py-2.5 rounded-lg border border-white/5 bg-white/[0.02] hover:bg-white/[0.06] hover:border-white/10 transition-all text-left",children:[e.jsx("div",{className:`flex-shrink-0 p-1.5 rounded-md border ${n}`,children:e.jsx(a,{size:14})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("h4",{className:"text-xs font-semibold text-white group-hover:text-primary-300 transition-colors",children:t.name}),e.jsx("span",{className:"text-[9px] font-mono text-neutral-muted/30 hidden sm:inline",children:t.slashCommand})]}),e.jsx("p",{className:"text-[10px] leading-snug text-neutral-muted truncate",children:t.description})]}),e.jsx(ia,{size:14,className:"flex-shrink-0 text-neutral-muted/20 group-hover:text-primary-400 transition-colors"})]})}const Cn=[{id:"workflow",label:"Workflow"},{id:"health",label:"Health"},{id:"security",label:"Security"},{id:"architecture",label:"Architecture"},{id:"code-quality",label:"Code Quality"},{id:"performance",label:"Performance"}];function xs({onSelect:t}){const[s,a]=c.useState(""),n=c.useMemo(()=>{const i=s.toLowerCase();return i?le.filter(l=>l.name.toLowerCase().includes(i)||l.id.toLowerCase().includes(i)||l.description.toLowerCase().includes(i)||l.slashCommand.toLowerCase().includes(i)):le},[s]),r=c.useMemo(()=>{const i={};for(const l of n)i[l.category]||(i[l.category]=[]),i[l.category].push(l);return i},[n]);return e.jsxs("div",{className:"flex flex-col gap-4 h-full",children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-3 flex items-center pointer-events-none text-neutral-muted",children:e.jsx(et,{size:15})}),e.jsx("input",{type:"text",value:s,onChange:i=>a(i.target.value),placeholder:"Search skills, commands, or categories...",className:"w-full bg-white/5 border border-white/10 rounded-xl py-2.5 pl-10 pr-4 text-sm text-white placeholder-neutral-muted focus:outline-none focus:ring-2 focus:ring-primary-500/20 focus:border-primary-500/40 transition-all",autoFocus:!0})]}),e.jsx("div",{className:"flex-1 overflow-y-auto pr-1 no-scrollbar",children:e.jsx(W,{mode:"popLayout",children:n.length>0?e.jsx("div",{className:"flex flex-col gap-5 pb-4",children:Cn.map(i=>{const l=r[i.id];return l?e.jsxs(y.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},exit:{opacity:0,scale:.95},transition:{duration:.3},children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("h3",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:i.label}),e.jsx("div",{className:"flex-1 h-px bg-white/5"})]}),e.jsx("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-1.5",children:l.map(o=>e.jsx(Sn,{skill:o,onClick:()=>t(o)},o.id))})]},i.id):null})}):e.jsxs(y.div,{initial:{opacity:0},animate:{opacity:1},className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"mb-3 rounded-full bg-white/5 p-3 text-neutral-muted",children:e.jsx(et,{size:24})}),e.jsx("h4",{className:"text-sm font-bold text-white mb-1",children:"No skills match"}),e.jsx("p",{className:"text-xs text-neutral-muted",children:"Try different keywords."})]})})})]})}function us(){const t=X(),s=()=>{const r=rs();E.getState().setActiveThread(r.id),t(`/t/${r.id}`)},a=()=>{const r=E.getState(),i=r.createThread("analysis",{analysisTitle:"New Analysis",description:"",labels:[]});r.setActiveThread(i.id),t(`/t/${i.id}`)},n=r=>{const i=E.getState(),l=i.createThread("chat",{sessionId:crypto.randomUUID(),command:r.slashCommand});i.setActiveThread(l.id),t(`/t/${l.id}`)};return e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center px-8 py-12",children:[e.jsx(y.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},transition:{duration:.6,ease:[.16,1,.3,1]},className:"mb-8",children:e.jsx(J,{size:80})}),e.jsx(y.h2,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.1,duration:.4},className:"text-2xl font-black tracking-tight text-white mb-2",children:"What would you like to do?"}),e.jsx(y.p,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.15,duration:.4},className:"text-sm text-neutral-muted mb-8",children:"Start a chat, run an analysis, or select a skill below."}),e.jsxs(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.2,duration:.4},className:"flex items-center gap-3 mb-10",children:[e.jsxs("button",{onClick:s,className:"flex items-center gap-2 rounded-xl bg-primary-500/10 border border-primary-500/20 px-5 py-2.5 text-sm font-bold text-primary-500 hover:bg-primary-500/20 transition-colors",children:[e.jsx(ot,{size:16}),"New Chat"]}),e.jsxs("button",{onClick:a,className:"flex items-center gap-2 rounded-xl bg-white/[0.04] border border-white/[0.08] px-5 py-2.5 text-sm font-bold text-neutral-text hover:bg-white/[0.08] transition-colors",children:[e.jsx(ct,{size:16}),"New Analysis"]})]}),e.jsxs(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.25,duration:.4},className:"w-full max-w-2xl",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(la,{size:14,className:"text-neutral-muted"}),e.jsx("h3",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:"Skills & Commands"}),e.jsx("div",{className:"flex-1 h-px bg-white/5"})]}),e.jsx("div",{className:"max-h-[50vh] overflow-y-auto rounded-xl border border-white/[0.06] bg-neutral-surface/30 p-4 backdrop-blur-sm",children:e.jsx(xs,{onSelect:n})})]})]})}function ms(t){const s=t.toLowerCase();return s==="agent"||s==="subagent"||s==="skill"||s.startsWith("harness:")}function We(t,s){const a=[/^>\s/,/^\$\s/,/^RUN\s/,/^[@\w-]+\/@?[\w-]+/,/\[\d{1,2}m/,/\[\]\s\[\d{2}/,/^(\s*\||\s*\+|-{3,})/,/^(\s*[✔✘ℹ⚠]\s)/,/^\s*\d+\s+import\s+/i,/^\s*\d+\s+export\s+/i,/^\s*\d+\s+\w+/,/import\s+.*\s+from\s+['"]/,/const\s+.*\s+=\s+require\(/],n=t.trim().split(`
6
+ `);if(n.length===0)return!1;const r=n.filter(i=>a.some(l=>l.test(i.trim()))).length;return r/n.length>.1||r>0}function hs(t){return t.includes("todo")}function ps(t){return t.includes("interaction")||t.includes("question")||t.includes("ask")||t.includes("human")}function Mn(t){if(t.kind!=="tool_use")return!1;if(ms(t.tool))return!0;const s=t.tool.toLowerCase();return hs(s)||ps(s)}function Tn(t,s,a){const n=[];for(let r=a+1;r<t.length;r++){if(s.has(r))continue;const i=t[r];if(Mn(i)||i.kind==="text"&&!We(i.text))break;n.push(r)}return n}function fs(t,s,a,n,r){const i=[];let l=a;const o=u=>r?r.includes(u):u<t.length;for(;o(l);){if(n.has(l)){l++;continue}const u=t[l];if(u.kind==="tool_use"||u.kind==="thinking")break;if(u.kind==="text")if(We(u.text,s.tool))i.push(u.text),n.add(l);else break;else u.kind==="status"&&(i.push(u.text),n.add(l));l++}if(i.length===0)return s;const d=i.join(`
7
+
8
+ `);return{...s,result:s.result?`${d}
9
+
10
+ ${s.result}`:d}}function In(t,s){const a=[],n=new Set;for(const r of s){if(n.has(r))continue;const i=t[r];i.kind==="tool_use"?a.push(fs(t,i,r+1,n,s)):a.push(i)}return a}function $n(t){for(let s=t.length-1;s>=0;s--)if(t[s].kind==="activity"){t[s].isLastGroup=!0;return}}function Ge(t){t.activityGroup.length!==0&&(t.segments.push({kind:"activity",blocks:t.activityGroup,startIndex:t.activityGroupStart,isLastGroup:!1}),t.activityGroup=[])}function st(t,s,a){t.activityGroup.length===0&&(t.activityGroupStart=a),t.activityGroup.push(s)}function An(t,s,a){Ge(t);const n=Tn(t.blocks,t.consumedIndices,a);n.forEach(i=>t.consumedIndices.add(i));const r=In(t.blocks,n);t.segments.push({kind:"agent",block:s,childBlocks:r,childStartIndex:n[0]??a+1,childIsLastGroup:n.length>0&&n[n.length-1]===t.blocks.length-1,index:a})}function En(t,s,a){Ge(t),t.segments.push({kind:"todo",block:s,index:a})}function Rn(t,s,a){Ge(t),t.segments.push({kind:"interaction",block:s,index:a,isPending:t.isStreaming&&a===t.blocks.length-1})}function Ln(t,s,a){const n=fs(t.blocks,s,a+1,t.consumedIndices,void 0);st(t,n,a)}function Dn(t,s,a){const n=s.tool.toLowerCase();if(ms(s.tool))return An(t,s,a);if(hs(n))return En(t,s,a);if(ps(n))return Rn(t,s,a);Ln(t,s,a)}function On(t,s,a){s.kind==="tool_use"?Dn(t,s,a):s.kind==="thinking"||s.kind==="status"||s.kind==="text"&&We(s.text)?st(t,s,a):(Ge(t),t.segments.push({kind:"text",block:s,index:a}))}function Pn(t,s){if(t.length===0)return[];const a={blocks:t,segments:[],consumedIndices:new Set,activityGroup:[],activityGroupStart:0,isStreaming:s};for(let n=0;n<t.length;n++)a.consumedIndices.has(n)||On(a,t[n],n);return a.activityGroup.length>0?a.segments.push({kind:"activity",blocks:a.activityGroup,startIndex:a.activityGroupStart,isLastGroup:!0}):$n(a.segments),s&&a.segments.push({kind:"streaming"}),a.segments}function Fn(t){switch(t.kind){case"agent":return`agent-${t.index}`;case"todo":return`todo-${t.index}`;case"interaction":return`interaction-${t.index}`;case"activity":return`ag-${t.startIndex}`;case"text":return`text-${t.index}`;case"streaming":return"streaming"}}const Me=["Thinking deeply…","Analyzing the codebase…","Connecting the dots…","Weaving through the code…","Exploring possibilities…","Building a mental model…","Following the thread…","Mapping dependencies…","Tracing the logic…","Piecing it together…","Diving into the details…","Reasoning through options…","Scanning for patterns…","Synthesizing insights…","Crafting a response…","Running the numbers…","Almost there…","Working through it…","Processing your request…","Engineering a solution…"];function _n({index:t,total:s}){const a=1-Math.abs(t-s/2)/(s/2),n=.4+a*.6,r=.1+a*.1,i=1.2+(1-a)*2,l=.3+a*.5;return e.jsx(y.div,{animate:{scaleY:[r,n,r*1.3,n*.7,r],opacity:[l*.6,l,l*.7,l*.9,l*.6]},transition:{duration:i,repeat:1/0,delay:t*.08,ease:"easeInOut"},className:"w-[1.5px] h-5 rounded-full origin-bottom",style:{background:"linear-gradient(to top, rgba(139,92,246,0.8), rgba(34,211,238,0.6))"}})}function gs(){const[t,s]=c.useState(()=>Math.floor(Math.random()*Me.length)),[a,n]=c.useState(0),r=c.useRef(Date.now());c.useEffect(()=>{const l=setInterval(()=>{s(o=>{let d;do d=Math.floor(Math.random()*Me.length);while(d===o&&Me.length>1);return d})},4500+Math.random()*2e3);return()=>clearInterval(l)},[]),c.useEffect(()=>{const l=setInterval(()=>{n(Math.floor((Date.now()-r.current)/1e3))},1e3);return()=>clearInterval(l)},[]);const i=l=>l<60?`${l}s`:`${Math.floor(l/60)}m ${l%60}s`;return e.jsxs(y.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.8},className:"relative flex items-center gap-4 py-5 px-4",children:[e.jsx(y.div,{className:"absolute left-0 top-1/2 w-20 h-20 -translate-x-1/4 -translate-y-1/2 rounded-full pointer-events-none",animate:{opacity:[.05,.1,.07,.09,.05],scale:[.95,1.08,.98,1.04,.95]},transition:{duration:7,repeat:1/0,ease:"easeInOut"},style:{background:"radial-gradient(circle, rgba(139,92,246,0.35) 0%, rgba(79,70,229,0.08) 50%, transparent 70%)",filter:"blur(12px)"}}),e.jsx(y.div,{animate:{y:[0,-2,1,-1.5,0]},transition:{duration:7,repeat:1/0,ease:"easeInOut"},className:"shrink-0 relative z-10",children:e.jsx(J,{size:80})}),e.jsxs("div",{className:"relative flex-1 min-w-0 flex items-center h-10",children:[e.jsx("div",{className:"absolute inset-0 flex items-end justify-start gap-[2.5px] opacity-[0.15] pointer-events-none overflow-hidden blur-[0.5px]",children:Array.from({length:20}).map((l,o)=>e.jsx(_n,{index:o,total:20},o))}),e.jsxs("div",{className:"relative z-10 flex flex-col justify-center",children:[e.jsx(W,{mode:"wait",children:e.jsx(y.span,{initial:{opacity:0,x:-4,filter:"blur(3px)"},animate:{opacity:.9,x:0,filter:"blur(0px)"},exit:{opacity:0,x:4,filter:"blur(2px)"},transition:{duration:.4},className:"text-[11px] font-semibold tracking-[0.08em] text-neutral-muted uppercase leading-none",children:Me[t]},t)}),e.jsx("div",{className:"h-3.5 flex items-center mt-1",children:a>2&&e.jsxs(y.span,{initial:{opacity:0},animate:{opacity:.3},className:"text-[8px] font-mono text-neutral-muted/60 tabular-nums tracking-[0.15em]",children:["T+",i(a)]})})]})]})]})}function ys(t,s){if(!s)return"";const a=t.toLowerCase();try{const n=JSON.parse(s);if(a.includes("todo")&&n.todos&&Array.isArray(n.todos))return`Updating ${n.todos.length} tasks`;if(a==="bash"&&(n.command||n.args))return(n.command||n.args).replace(/cd\s+("[^"]+"|'[^']+'|[^\s]+)\s*&&\s*/g,"").slice(0,100);if(a==="agent"||a==="subagent"||n.subagent_type){const r=n.subagent_type||n.type;if(r&&n.description)return`${r}: ${n.description}`.slice(0,100);if(n.description)return n.description.slice(0,100)}return n.path||n.file_path||n.filePath?(n.path||n.file_path||n.filePath).split("/").slice(-2).join("/"):JSON.stringify(n).slice(0,100)}catch{return s.slice(0,100)}}function It({block:t}){return e.jsxs("details",{className:"rounded border border-neutral-border/50 bg-neutral-surface/50 backdrop-blur-sm group",children:[e.jsxs("summary",{className:"cursor-pointer px-3 py-1.5 text-xs font-medium text-neutral-muted select-none flex items-center gap-2",children:[e.jsx("div",{className:"h-1 w-1 rounded-full bg-secondary-400 group-open:animate-pulse"}),"Thinking..."]}),e.jsx("div",{className:"border-t border-neutral-border/50 px-3 py-2",children:e.jsx("p",{className:"whitespace-pre-wrap text-xs leading-relaxed text-neutral-muted",children:t.text})})]})}function $t({block:t}){return e.jsxs("div",{className:"flex items-center gap-2 px-1 py-0.5",children:[e.jsx("span",{className:"inline-block h-1.5 w-1.5 animate-pulse rounded-full bg-yellow-500 shadow-[0_0_8px_rgba(234,179,8,0.6)]"}),e.jsx("span",{className:"font-mono text-[10px] tracking-widest text-neutral-muted",children:t.text})]})}function zn({text:t}){return e.jsxs("div",{className:"my-2 rounded border border-neutral-border/30 bg-neutral-surface/20 backdrop-blur-sm overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 border-b border-neutral-border/10 bg-neutral-surface/40 select-none",children:[e.jsxs("div",{className:"flex gap-1 mr-1",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-neutral-border/30"}),e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-neutral-border/30"}),e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-neutral-border/30"})]}),e.jsx("span",{className:"text-[10px] font-black tracking-[0.2em] text-neutral-muted/60 uppercase",children:"Terminal Output"})]}),e.jsx("div",{className:"px-3 py-3 bg-neutral-bg/20",children:e.jsx("div",{className:"prose prose-invert prose-xs selection:bg-secondary-400/20 whitespace-pre-wrap",children:e.jsx(te,{remarkPlugins:[se],children:t})})})]})}function bs({block:t}){if(We(t.text))return e.jsx(zn,{text:t.text});const s=[...t.text.matchAll(/<?!--\s*packed:\s*(.*?)\s*-->?/g)],a=t.text.replace(/<?!--\s*packed:\s*(.*?)\s*-->?/g,"").replace(/\n{3,}/g,`
11
+
12
+ `).trim();return e.jsxs("div",{className:"flex flex-col gap-2 relative",children:[s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((n,r)=>e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-secondary-500/10 px-2.5 py-0.5 text-[10px] font-medium text-secondary-300 border border-secondary-500/20",title:"Graph context packing applied",children:[e.jsx("svg",{className:"w-3 h-3 text-secondary-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 8h14M5 8a2 2 0 110-4h14a2 2 0 110 4M5 8v10a2 2 0 002 2h10a2 2 0 002-2V8m-9 4h4"})}),e.jsxs("span",{children:["Packed: ",n[1]]})]},r))}),a.length>0&&e.jsx("div",{className:"prose prose-invert prose-sm max-w-none py-1 selection:bg-primary-500/30",children:e.jsx(te,{remarkPlugins:[se],components:{code(n){const{node:r,className:i,children:l,...o}=n,d=!(i&&/language-(\w+)/.test(i)),u=/language-(\w+)/.exec(i??"");return!d&&u?e.jsxs("div",{className:"relative group my-4",children:[e.jsx("div",{className:"absolute -inset-2 bg-gradient-to-r from-primary-500/10 to-secondary-400/10 rounded-xl blur opacity-0 group-hover:opacity-100 transition-opacity"}),e.jsxs("div",{className:"relative rounded-lg border border-neutral-border overflow-hidden shadow-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between px-4 py-2 bg-neutral-surface/80 border-b border-neutral-border",children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-neutral-muted",children:u[1]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-neutral-border"}),e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-neutral-border"})]})]}),e.jsx(ma,{...o,style:ha,language:u[1],PreTag:"div",className:"!bg-neutral-surface/40 !m-0 !p-4 !text-[11px] font-mono leading-relaxed",children:(Array.isArray(l)?l.join(""):typeof l=="string"?l:"").replace(/\n$/,"")})]})]}):e.jsx("code",{className:`${i} bg-neutral-surface/60 px-1.5 py-0.5 rounded text-secondary-400 font-mono text-[11px] border border-neutral-border`,...o,children:l})}},children:a})})]})}function Le({block:t,forceResult:s,isPending:a=!1,attribution:n}){const[r,i]=c.useState(()=>{const x=t.tool.toLowerCase();return x.includes("interaction")||x.includes("question")||x.includes("ask")||x.includes("human")}),l=t.result||s,o=l!==void 0,d=t.tool.toLowerCase().includes("todo");let u=null;if(d&&t.args)try{const x=JSON.parse(t.args);x.todos&&Array.isArray(x.todos)&&(u=x.todos)}catch{}return e.jsxs("div",{className:"relative overflow-hidden rounded border border-neutral-border/50 bg-neutral-surface/50 backdrop-blur-sm transition-all duration-200",children:[a&&!o&&e.jsx(y.div,{initial:{top:"-10%"},animate:{top:"110%"},transition:{duration:1.5,repeat:1/0,ease:"linear"},className:"absolute left-0 right-0 h-4 bg-gradient-to-b from-transparent via-secondary-400/20 to-transparent pointer-events-none z-10"}),e.jsxs("div",{className:"flex cursor-pointer items-center gap-2 px-3 py-2 select-none relative z-20 hover:bg-white/5 active:bg-white/10 transition-colors",onClick:()=>i(!r),children:[e.jsx(y.span,{animate:{rotate:r?90:0},className:"text-[9px] text-secondary-400 font-bold",children:"▶"}),e.jsx("span",{className:"text-[10px] font-black tracking-[0.2em] text-neutral-text capitalize truncate max-w-[300px]",children:(()=>{if(t.tool.toLowerCase()==="bash"&&t.args)try{const x=JSON.parse(t.args);if(x.description)return x.description}catch{}return t.tool.replace(/_/g," ")})()}),t.args&&e.jsx("span",{className:"truncate font-mono text-[9px] text-neutral-muted/60",title:t.args,children:ys(t.tool,t.args)}),n&&e.jsx("span",{className:"ml-2 inline-flex items-center gap-1 rounded bg-secondary-500/10 px-1.5 py-0.5 text-[8px] font-bold uppercase tracking-wider text-secondary-400 border border-secondary-400/20",children:n}),o&&e.jsx("div",{className:"ml-auto flex items-center gap-2",children:e.jsx("span",{className:`text-[9px] font-bold uppercase tracking-wider px-1.5 py-0.5 rounded-sm border ${t.isError?"text-red-400 border-red-400/30 bg-red-400/5":"text-emerald-400 border-emerald-400/30 bg-emerald-400/5"}`,children:t.isError?"ERR":"OK"})})]}),r&&o&&e.jsx(y.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},className:"border-t border-neutral-border/50 bg-neutral-bg/50 relative z-20 px-3 py-2",children:e.jsxs("div",{className:`max-h-[60vh] overflow-auto prose prose-invert prose-xs selection:bg-secondary-400/20 whitespace-pre-wrap ${t.isError?"text-red-400":""}`,children:[e.jsx(te,{remarkPlugins:[se],children:l}),o&&!a&&t.tool.toLowerCase().includes("emit_interaction")&&e.jsx("div",{className:"mt-4 flex flex-wrap gap-2 border-t border-neutral-border/50 pt-3 not-prose",children:(()=>{var x,f;try{const m=JSON.parse(t.args||"{}"),p=h=>{window.dispatchEvent(new CustomEvent("chat-action-send",{detail:h}))};if(m.type==="question"){const h=[];if((x=m.question)!=null&&x.options&&m.question.options.length>0){const{options:g,recommendation:b}=m.question;b!==void 0&&g[b.optionIndex]&&h.push(e.jsxs("button",{onClick:()=>p(`Approve recommendation: ${g[b.optionIndex].label}`),className:"rounded bg-primary-500 px-3 py-1.5 text-xs font-bold text-white shadow hover:bg-primary-400 transition-colors",children:["Approve Recommendation (",String.fromCharCode(65+b.optionIndex),")"]},"approve-rec")),g.forEach((j,N)=>{if((b==null?void 0:b.optionIndex)===N)return;const v=typeof j=="string"?j:j.label;h.push(e.jsxs("button",{onClick:()=>p(`Approve option ${String.fromCharCode(65+N)}: ${v}`),className:"rounded bg-neutral-surface/60 border border-neutral-border hover:bg-white/5 px-3 py-1.5 text-[10px] font-medium text-neutral-text transition-colors",children:["Option ",String.fromCharCode(65+N)]},`opt-${N}`))})}return h.push(e.jsx("button",{onClick:()=>p("Continue"),className:"rounded bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 px-4 py-1.5 text-[10px] font-bold hover:bg-emerald-500/30 transition-colors",children:"Continue"},"continue-btn")),h}if(m.type==="confirmation")return e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>p("Yes, proceed"),className:"rounded bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 px-4 py-1.5 text-xs font-bold hover:bg-emerald-500/30 transition-colors",children:"Confirm & Proceed"}),e.jsx("button",{onClick:()=>p("No, stop"),className:"rounded bg-red-500/20 text-red-400 border border-red-500/30 px-4 py-1.5 text-xs font-bold hover:bg-red-500/30 transition-colors",children:"Cancel"})]});if(m.type==="transition"&&((f=m.transition)!=null&&f.requiresConfirmation))return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>p(`Yes, proceed to ${m.transition.suggestedNext}`),className:"rounded bg-primary-500 px-4 py-1.5 text-xs font-bold text-white shadow hover:bg-primary-400 transition-colors",children:["Proceed to ",m.transition.suggestedNext]}),e.jsxs("button",{onClick:()=>p("No, stay here"),className:"rounded bg-neutral-surface/60 border border-neutral-border hover:bg-white/5 px-4 py-1.5 text-[10px] font-medium text-neutral-text transition-colors",children:["Stay in ",m.transition.completedPhase]})]});if(m.type==="batch")return e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>p("Approve all decisions"),className:"rounded bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 px-4 py-1.5 text-xs font-bold hover:bg-emerald-500/30 transition-colors",children:"Approve All"}),e.jsx("button",{onClick:()=>p("Reject batch"),className:"rounded bg-red-500/20 text-red-400 border border-red-500/30 px-4 py-1.5 text-xs font-bold hover:bg-red-500/30 transition-colors",children:"Reject"})]})}catch{}return null})()})]})})]})}function At({blocks:t,startIndex:s,isStreaming:a,isLastGroup:n}){if(t.filter(r=>r.kind==="tool_use").length,t.length===0)return null;if(t.length===1){const r=t[0];if(r.kind!=="tool_use"&&r.kind!=="text"){if(r.kind==="thinking")return e.jsx(y.div,{initial:{opacity:0,y:5},animate:{opacity:1,y:0},children:e.jsx(It,{block:r})});if(r.kind==="status")return e.jsx(y.div,{initial:{opacity:0,x:-5},animate:{opacity:1,x:0},children:e.jsx($t,{block:r})})}}return e.jsx("div",{className:"relative flex flex-col gap-[2px] my-1",children:(()=>{const r=[];let i=[];const l=()=>{if(i.length!==0){if(i.length>=3){const o=i[i.length-1].block;r.push(e.jsxs("details",{className:"rounded border border-neutral-border/50 bg-neutral-bg/30 my-1",children:[e.jsxs("summary",{className:"cursor-pointer px-3 py-2 text-xs text-neutral-muted select-none flex items-center gap-2",children:[e.jsxs("div",{className:"flex -space-x-1 shrink-0",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-secondary-400/50"}),e.jsx("div",{className:"h-2 w-2 rounded-full bg-secondary-400/70"}),e.jsx("div",{className:"h-2 w-2 rounded-full bg-secondary-400"})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0 overflow-hidden",children:[e.jsxs("span",{className:"shrink-0",children:["Used ",i.length," tools"]}),e.jsx("span",{className:"shrink-0 opacity-30 text-lg leading-none mt-[-2px]",children:"·"}),e.jsxs("span",{className:"truncate opacity-75 capitalize tracking-widest text-[9px] font-black text-neutral-text",children:[o.tool.replace(/_/g," "),o.args&&e.jsx("span",{className:"font-mono text-[9px] font-normal normal-case tracking-normal ml-2 text-neutral-muted/80",children:ys(o.tool,o.args)})]})]})]}),e.jsx("div",{className:"flex flex-col gap-[2px] border-t border-neutral-border/50 p-2",children:i.map(({block:d,localIndex:u})=>{const x=n&&u===t.length-1;return e.jsx(Le,{block:d,isPending:x&&a},s+u)})})]},`cluster-${r.length}`))}else i.forEach(({block:o,localIndex:d})=>{const u=n&&d===t.length-1;r.push(e.jsx(Le,{block:o,isPending:u&&a},s+d))});i=[]}};for(let o=0;o<t.length;o++){const d=t[o];if(d.kind==="tool_use")i.push({block:d,localIndex:o});else switch(l(),d.kind){case"thinking":r.push(e.jsx(y.div,{initial:{opacity:0,y:5},animate:{opacity:1,y:0},children:e.jsx(It,{block:d})},s+o));break;case"status":r.push(e.jsx(y.div,{initial:{opacity:0,x:-5},animate:{opacity:1,x:0},children:e.jsx($t,{block:d})},s+o));break;case"text":r.push(e.jsx(y.div,{initial:{opacity:0},animate:{opacity:1},children:e.jsx(bs,{block:d})},s+o));break}}return l(),r})()})}function Bn(t){const s=t.replace(/^\s*<!--\s*packed:[^>]*-->\s*/,"").trim(),a=s.indexOf("{");if(a===-1)return null;try{const n=JSON.parse(s.slice(a));if(typeof n.featureName!="string")return null;const r=i=>{var l,o;return Array.isArray(i)&&(i.length===0||typeof((l=i[0])==null?void 0:l.skill)=="string"&&typeof((o=i[0])==null?void 0:o.score)=="number")};return!r(n.apply)&&!r(n.reference)&&!r(n.consider)?null:n}catch{return null}}function Hn(t){return t>=.7?"bg-emerald-500":t>=.5?"bg-primary-500":t>=.3?"bg-secondary-400":"bg-neutral-muted"}function Et({match:t,dim:s}){const a=Math.round(t.score*100);return e.jsxs(y.div,{initial:{opacity:0,y:4},animate:{opacity:s?.7:1,y:0},className:"rounded border border-neutral-border/60 bg-neutral-surface/40 px-3 py-2 hover:bg-neutral-surface/60 transition-colors",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"font-mono text-[12px] font-bold text-neutral-text truncate",children:t.skill}),e.jsxs("span",{className:"ml-auto shrink-0 font-mono text-[10px] text-neutral-muted tabular-nums",children:[a,"%"]})]}),e.jsx("div",{className:"mt-1 h-1 w-full overflow-hidden rounded-full bg-neutral-bg/60",children:e.jsx("div",{className:`h-full rounded-full ${Hn(t.score)} transition-all`,style:{width:`${a}%`}})}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"rounded bg-primary-500/10 border border-primary-500/20 px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wider text-primary-300",children:t.when}),t.reasons.map((n,r)=>e.jsx("span",{className:"rounded bg-neutral-bg/60 border border-neutral-border/40 px-1.5 py-0.5 text-[9px] text-neutral-muted",title:n,children:n.length>40?n.slice(0,38)+"…":n},r))]})]})}function Xe({label:t,matches:s,dim:a}){return s.length===0?null:e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-[10px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:t}),e.jsx("span",{className:"text-[10px] font-mono text-neutral-muted/60",children:s.length}),e.jsx("div",{className:"flex-1 h-px bg-neutral-border/40"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-1.5",children:s.map(n=>a?e.jsx(Et,{match:n,dim:!0},n.skill):e.jsx(Et,{match:n},n.skill))})]})}function Wn({payload:t}){const s=t.apply??[],a=t.reference??[],n=t.consider??[],r=s.length+a.length+n.length;return e.jsxs("div",{className:"flex flex-col gap-3 not-prose",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[e.jsx("span",{className:"text-sm font-bold text-neutral-text",children:t.featureName}),t.totalScanned!=null&&e.jsxs("span",{className:"font-mono text-[10px] text-neutral-muted",children:[t.totalScanned," scanned"]}),t.scanDuration!=null&&e.jsxs("span",{className:"font-mono text-[10px] text-neutral-muted",children:[t.scanDuration,"ms"]}),e.jsxs("span",{className:"font-mono text-[10px] text-neutral-muted",children:[r," matched"]}),t.skillsPath&&e.jsx("span",{className:"ml-auto font-mono text-[10px] text-neutral-muted/60 truncate",children:t.skillsPath})]}),e.jsx(Xe,{label:"Apply",matches:s}),e.jsx(Xe,{label:"Reference",matches:a,dim:!0}),e.jsx(Xe,{label:"Consider",matches:n,dim:!0})]})}const Rt={error:0,warning:1,info:2};function Gn(t){return t==="error"||t==="fail"||t==="critical"||t==="high"?"error":t==="warning"||t==="warn"||t==="medium"?"warning":"info"}function Un(t){const s=t.replace(/^\s*<!--\s*packed:[^>]*-->\s*/,"").trim(),a=s.indexOf("{");if(a===-1)return null;try{const n=JSON.parse(s.slice(a)),r=n.findings;if(!Array.isArray(r)||r.length===0)return null;const i=r[0];if(typeof(i==null?void 0:i.severity)!="string")return null;const l=r.map(d=>{const u=d,x={severity:Gn(u.severity)};return typeof u.file=="string"&&(x.file=u.file),typeof u.line=="number"&&(x.line=u.line),typeof u.column=="number"&&(x.column=u.column),typeof u.ruleId=="string"&&(x.ruleId=u.ruleId),typeof u.ruleName=="string"&&(x.ruleName=u.ruleName),typeof u.category=="string"&&(x.category=u.category),typeof u.message=="string"&&(x.message=u.message),typeof u.match=="string"&&(x.match=u.match),typeof u.context=="string"&&(x.context=u.context),x}),o=n.summary&&typeof n.summary=="object"?n.summary:void 0;return o?{findings:l,summary:o}:{findings:l}}catch{return null}}const at={error:{pill:"bg-red-500/15 text-red-300 border-red-500/30",bar:"bg-red-500",text:"text-red-300"},warning:{pill:"bg-yellow-500/15 text-yellow-300 border-yellow-500/30",bar:"bg-yellow-500",text:"text-yellow-300"},info:{pill:"bg-primary-500/15 text-primary-300 border-primary-500/30",bar:"bg-primary-500",text:"text-primary-300"}};function qn({finding:t}){const[s,a]=c.useState(!1),n=at[t.severity],r=t.ruleName||t.message||t.ruleId||"Finding",i=t.file?`${t.file}${t.line!=null?`:${t.line}`:""}`:null,l=t.match||t.context||t.message;return e.jsxs("div",{className:"rounded border border-neutral-border/50 bg-neutral-surface/40 overflow-hidden",children:[e.jsxs("div",{className:`flex items-start gap-2 px-3 py-2 ${l?"cursor-pointer hover:bg-white/5":""} transition-colors`,onClick:l?()=>a(o=>!o):void 0,children:[e.jsx("span",{className:`shrink-0 mt-0.5 rounded border px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wider ${n.pill}`,children:t.severity}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-2 gap-y-0.5",children:[e.jsx("span",{className:"text-[12px] font-bold text-neutral-text truncate",children:r}),t.category&&e.jsx("span",{className:"text-[10px] font-mono text-neutral-muted/70",children:t.category})]}),i&&e.jsx("div",{className:"mt-0.5 font-mono text-[10px] text-neutral-muted/80 truncate",children:i})]}),l&&e.jsx(y.span,{animate:{rotate:s?90:0},className:"shrink-0 mt-0.5 text-[9px] text-neutral-muted",children:"▶"})]}),e.jsx(W,{children:s&&l&&e.jsx(y.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},className:"border-t border-neutral-border/50 bg-neutral-bg/40 overflow-hidden",children:e.jsxs("div",{className:"px-3 py-2 flex flex-col gap-2",children:[t.message&&t.ruleName&&t.message!==t.ruleName&&e.jsx("p",{className:"text-xs text-neutral-text/80",children:t.message}),t.match&&e.jsx("pre",{className:"rounded bg-neutral-bg/60 border border-neutral-border/40 px-2 py-1 font-mono text-[11px] text-secondary-300 overflow-x-auto whitespace-pre-wrap",children:t.match}),t.context&&t.context!==t.match&&e.jsx("pre",{className:"rounded bg-neutral-bg/30 px-2 py-1 font-mono text-[10px] text-neutral-muted overflow-x-auto whitespace-pre-wrap",children:t.context})]})})})]})}function Yn({payload:t}){const s=[...t.findings].sort((n,r)=>Rt[n.severity]-Rt[r.severity]),a=s.reduce((n,r)=>(n[r.severity]++,n),{error:0,warning:0,info:0});return e.jsxs("div",{className:"flex flex-col gap-2 not-prose",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.title&&e.jsx("span",{className:"text-sm font-bold text-neutral-text",children:t.title}),["error","warning","info"].map(n=>a[n]>0?e.jsxs("span",{className:`inline-flex items-center gap-1 rounded border px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider ${at[n].pill}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${at[n].bar}`}),a[n]," ",n,a[n]===1?"":"s"]},n):null),e.jsxs("span",{className:"ml-auto font-mono text-[10px] text-neutral-muted/60",children:[s.length," total"]})]}),e.jsx("div",{className:"flex flex-col gap-1",children:s.map((n,r)=>e.jsx(qn,{finding:n},r))})]})}function Vn(t){const s=t.replace(/^\s*<!--\s*packed:[^>]*-->\s*/,"").trim(),a=s.indexOf("{");if(a===-1)return null;try{const n=JSON.parse(s.slice(a));return typeof n.targetNodeId=="string"&&(typeof n.impact=="object"||typeof n.impactCounts=="object")?{kind:"impact",...n}:typeof n.sourceNodeId=="string"&&(Array.isArray(n.topRisks)||Array.isArray(n.flatSummary))?{kind:"blast",...n}:null}catch{return null}}const Jn={tests:{color:"text-emerald-400 border-emerald-400/30 bg-emerald-400/5",label:"Tests"},code:{color:"text-primary-400 border-primary-400/30 bg-primary-400/5",label:"Code"},docs:{color:"text-secondary-400 border-secondary-400/30 bg-secondary-400/5",label:"Docs"},other:{color:"text-neutral-muted border-neutral-border bg-neutral-bg/30",label:"Other"}};function js({node:t}){const s=t.name||t.path||t.id||"?";return e.jsxs("span",{className:"inline-flex items-center gap-1 rounded border border-neutral-border/60 bg-neutral-bg/40 px-1.5 py-0.5 font-mono text-[10px] text-neutral-text/90 truncate max-w-full",title:t.path||t.id,children:[t.type&&e.jsx("span",{className:"text-neutral-muted/60",children:t.type}),e.jsx("span",{className:"truncate",children:s})]})}function Lt({category:t,items:s,count:a}){const[n,r]=c.useState(t==="tests"||t==="code");if(a===0)return null;const i=Jn[t],l=s&&s.length>0;return e.jsxs("div",{className:"rounded border border-neutral-border/40 overflow-hidden",children:[e.jsxs("div",{className:`flex items-center gap-2 px-3 py-1.5 ${l?"cursor-pointer hover:bg-white/5":""} transition-colors`,onClick:l?()=>r(o=>!o):void 0,children:[l&&e.jsx(y.span,{animate:{rotate:n?90:0},className:"text-[9px] text-neutral-muted",children:"▶"}),e.jsx("span",{className:`rounded border px-1.5 py-0.5 text-[9px] font-bold uppercase tracking-wider ${i.color}`,children:i.label}),e.jsx("span",{className:"font-mono text-[11px] text-neutral-muted",children:a})]}),n&&l&&e.jsx("div",{className:"border-t border-neutral-border/40 bg-neutral-bg/30 p-2 flex flex-wrap gap-1",children:s.map((o,d)=>e.jsx(js,{node:o},o.id??d))})]})}function Xn(t){var n,r,i,l,o,d,u,x,f;const s=t.impactCounts??{tests:((r=(n=t.impact)==null?void 0:n.tests)==null?void 0:r.length)??0,code:((l=(i=t.impact)==null?void 0:i.code)==null?void 0:l.length)??0,docs:((d=(o=t.impact)==null?void 0:o.docs)==null?void 0:d.length)??0,other:((x=(u=t.impact)==null?void 0:u.other)==null?void 0:x.length)??0},a=(s.tests??0)+(s.code??0)+(s.docs??0)+(s.other??0);return e.jsxs("div",{className:"flex flex-col gap-2 not-prose",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[e.jsx("span",{className:"text-[10px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:"Impact"}),t.targetNodeId&&e.jsx("span",{className:"font-mono text-[11px] text-neutral-text/90 truncate",children:t.targetNodeId}),e.jsxs("span",{className:"ml-auto font-mono text-[10px] text-neutral-muted/70",children:[a," affected"]}),((f=t.stats)==null?void 0:f.maxDepthReached)!=null&&e.jsxs("span",{className:"font-mono text-[10px] text-neutral-muted/70",children:["depth ",t.stats.maxDepthReached]})]}),e.jsx("div",{className:"flex flex-col gap-1",children:["tests","code","docs","other"].map(m=>{var h;const p=(h=t.impact)==null?void 0:h[m];return p?e.jsx(Lt,{category:m,items:p,count:s[m]??0},m):e.jsx(Lt,{category:m,count:s[m]??0},m)})}),t.highestRiskItems&&t.highestRiskItems.length>0&&e.jsxs("div",{className:"mt-1 flex flex-col gap-1",children:[e.jsx("span",{className:"text-[10px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:"Highest Risk"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:t.highestRiskItems.map((m,p)=>e.jsx(js,{node:m},m.id??p))})]})]})}function Kn({p:t}){const s=Math.round(t*100),a=t>=.7?"bg-red-500":t>=.4?"bg-yellow-500":"bg-primary-500";return e.jsxs("div",{className:"flex items-center gap-2 w-full",children:[e.jsx("div",{className:"flex-1 h-1.5 rounded-full bg-neutral-bg/60 overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${a} transition-all`,style:{width:`${s}%`}})}),e.jsxs("span",{className:"shrink-0 font-mono text-[10px] tabular-nums text-neutral-muted",children:[s,"%"]})]})}function Qn(t){var a,n;const s=t.topRisks??t.flatSummary??[];return e.jsxs("div",{className:"flex flex-col gap-2 not-prose",children:[e.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-3 gap-y-1",children:[e.jsx("span",{className:"text-[10px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:"Blast Radius"}),t.sourceName&&e.jsx("span",{className:"font-mono text-[11px] text-neutral-text/90 truncate",children:t.sourceName}),((a=t.summary)==null?void 0:a.totalAffected)!=null&&e.jsxs("span",{className:"ml-auto font-mono text-[10px] text-neutral-muted/70",children:[t.summary.totalAffected," affected"]}),((n=t.summary)==null?void 0:n.maxDepth)!=null&&e.jsxs("span",{className:"font-mono text-[10px] text-neutral-muted/70",children:["depth ",t.summary.maxDepth]})]}),e.jsx("div",{className:"flex flex-col gap-1",children:s.map((r,i)=>{const l=r.cumulativeProbability??r.probability??0;return e.jsx("div",{className:"rounded border border-neutral-border/40 bg-neutral-surface/30 px-3 py-1.5 flex items-center gap-3",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"font-mono text-[11px] font-bold text-neutral-text truncate",children:r.name||r.path||r.id}),r.type&&e.jsx("span",{className:"text-[9px] text-neutral-muted/70",children:r.type}),r.depth!=null&&e.jsxs("span",{className:"ml-auto shrink-0 font-mono text-[9px] text-neutral-muted/60",children:["d",r.depth]})]}),e.jsx("div",{className:"mt-1",children:e.jsx(Kn,{p:l})})]})},r.id??i)})})]})}function Zn({payload:t}){return t.kind==="impact"?e.jsx(Xn,{...t}):e.jsx(Qn,{...t})}function er({block:t,children:s}){let a={};if(t.args)try{a=JSON.parse(t.args)}catch{}const n=t.tool.toLowerCase(),r=n==="skill"||n.startsWith("harness:"),i=r?"border-emerald-400/20 bg-emerald-400/5":"border-secondary-400/20 bg-secondary-400/5",l=r?"border-emerald-400/10 bg-emerald-400/10":"border-secondary-400/10 bg-secondary-400/10",o=r?"text-emerald-400":"text-secondary-400",d=r?"text-emerald-300":"text-secondary-300",u=r?"text-emerald-400":"text-secondary-400",x=r?"border-emerald-400/10":"border-secondary-400/10",f=r?`Skill: ${a.skill||(n.startsWith("harness:")?t.tool.split(":")[1]:"Execution")}`:`Subagent: ${a.subagent_type||a.type||"Execution"}`,m=r?void 0:a.description,p=r?a.args:a.prompt;return e.jsxs("div",{className:`my-3 rounded border ${i} overflow-hidden`,children:[e.jsxs("div",{className:`flex items-center gap-2 px-3 py-2 border-b ${l}`,children:[e.jsx("svg",{className:`w-3 h-3 ${o}`,fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:r?e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"}):e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z"})}),e.jsx("span",{className:`font-bold tracking-widest uppercase text-[10px] ${d}`,children:f}),!t.result&&!t.isError&&e.jsx("span",{className:`ml-auto text-[10px] ${u} animate-pulse`,children:"Running..."}),t.isError&&e.jsx("span",{className:"ml-auto text-[10px] text-red-400",children:"Error"})]}),e.jsxs("div",{className:"flex flex-col p-3 gap-2",children:[m&&e.jsx("div",{className:"text-[13px] font-bold text-neutral-text",children:m}),p&&e.jsx("div",{className:"text-xs text-neutral-muted bg-neutral-surface/40 p-2 rounded border border-neutral-border/50 whitespace-pre-wrap font-mono leading-relaxed mt-1 overflow-x-auto",children:p}),t.result&&(()=>{const h=Bn(t.result);if(h)return e.jsx("div",{className:`mt-2 pt-2 border-t ${x} max-h-[60vh] overflow-auto`,children:e.jsx(Wn,{payload:h})});const g=Un(t.result);if(g)return e.jsx("div",{className:`mt-2 pt-2 border-t ${x} max-h-[60vh] overflow-auto`,children:e.jsx(Yn,{payload:g})});const b=Vn(t.result);return b?e.jsx("div",{className:`mt-2 pt-2 border-t ${x} max-h-[60vh] overflow-auto`,children:e.jsx(Zn,{payload:b})}):e.jsx("div",{className:`mt-2 pt-2 border-t ${x} text-xs text-neutral-muted prose prose-invert prose-xs max-h-[40vh] overflow-auto whitespace-pre-wrap`,children:e.jsx(te,{remarkPlugins:[se],children:t.result})})})(),s&&(Array.isArray(s)?s.length>0:!0)&&e.jsxs("div",{className:`mt-2 pt-2 border-t ${x} flex flex-col gap-1`,children:[e.jsx("div",{className:"text-[10px] uppercase tracking-widest font-black text-neutral-muted/50 mb-1",children:"Activity Trace"}),s]})]})]})}function tr({block:t}){let s=null;if(t.args)try{const a=JSON.parse(t.args);a.todos&&Array.isArray(a.todos)&&(s=a.todos)}catch{}return s?e.jsxs("div",{className:"my-3 rounded border border-primary-500/20 bg-primary-500/5 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-primary-500/10 bg-primary-500/10",children:[e.jsx("svg",{className:"w-3 h-3 text-primary-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"})}),e.jsx("span",{className:"font-bold tracking-widest uppercase text-[10px] text-primary-300",children:"Todo Plan"}),t.isError&&e.jsx("span",{className:"ml-auto text-[10px] text-red-400",children:"Error Parsing"})]}),e.jsxs("div",{className:"flex flex-col p-3 gap-2",children:[s.map((a,n)=>{const r=a.status==="completed"||a.status==="done",i=a.status==="in_progress";return e.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[e.jsx("div",{className:"pt-1 shrink-0",children:r?e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-emerald-500/20 border border-emerald-500 flex items-center justify-center",children:e.jsx("svg",{className:"w-2.5 h-2.5 text-emerald-400",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M5 13l4 4L19 7"})})}):i?e.jsx("div",{className:"h-3.5 w-3.5 rounded bg-secondary-400/20 border border-secondary-400 flex items-center justify-center",children:e.jsx("div",{className:"w-1.5 h-1.5 rounded-full bg-secondary-400 animate-pulse"})}):e.jsx("div",{className:"h-3.5 w-3.5 rounded border border-neutral-border bg-neutral-surface/50"})}),e.jsxs("div",{className:"flex flex-col leading-snug pt-[1px]",children:[e.jsx("span",{className:`text-neutral-text text-[13px] ${r?"line-through text-neutral-muted":""}`,children:a.content}),a.activeForm&&i&&e.jsxs("span",{className:"text-xs text-secondary-400 mt-1 font-mono",children:["▶ ",a.activeForm]})]})]},n)}),t.result&&e.jsx("div",{className:"mt-2 pt-2 border-t border-primary-500/10 text-xs text-neutral-muted prose prose-invert prose-xs whitespace-pre-wrap",children:e.jsx(te,{remarkPlugins:[se],children:t.result})})]})]}):e.jsx(Le,{block:t,isPending:!1})}function sr({segment:t,isStreaming:s}){switch(t.kind){case"agent":return e.jsx(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},children:e.jsx(er,{block:t.block,children:t.childBlocks.length>0&&e.jsx(At,{blocks:t.childBlocks,startIndex:t.childStartIndex,isStreaming:s,isLastGroup:t.childIsLastGroup})})});case"todo":return e.jsx(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},children:e.jsx(tr,{block:t.block})});case"interaction":return e.jsx(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},children:e.jsx(Le,{block:t.block,isPending:t.isPending})});case"activity":return e.jsx(At,{blocks:t.blocks,startIndex:t.startIndex,isStreaming:s,isLastGroup:t.isLastGroup});case"text":return e.jsx(y.div,{initial:{opacity:0},animate:{opacity:1},children:e.jsx(bs,{block:t.block})});case"streaming":return e.jsx(y.div,{initial:{opacity:0,y:5},animate:{opacity:1,y:0},className:"mt-2 border-t border-white/5",children:e.jsx(gs,{})})}}function Ns({blocks:t,isStreaming:s}){if(t.length===0&&s)return e.jsx(gs,{});const a=c.useMemo(()=>Pn(t,s),[t,s]);return a.length===0?null:e.jsx("div",{className:"flex flex-col gap-2",children:a.map(n=>e.jsx(sr,{segment:n,isStreaming:s},Fn(n)))})}const ar=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","TodoWrite"]);function nr(t){return!(t.kind==="status"||t.kind==="tool_use"&&ar.has(t.tool))}function rr(t){return t.filter(nr)}function ir(t){const s=[],a=new Map;for(const n of t){if(n.kind!=="tool_use")continue;const r=n;if(r.tool==="TaskCreate"&&r.args)try{const i=JSON.parse(r.args),l=`task-${s.length+a.size+1}`;i.subject&&a.set(l,{id:l,text:i.subject,completed:!1})}catch{}if(r.tool==="TaskUpdate"&&r.args)try{const i=JSON.parse(r.args);if(i.taskId&&i.status==="completed"){const l=`task-${i.taskId}`,o=a.get(l);o&&a.set(l,{...o,completed:!0})}}catch{}if(r.tool==="TodoWrite"&&r.args)try{const i=JSON.parse(r.args);if(i.todos)for(const l of i.todos)a.set(l.id,{id:l.id,text:l.content,completed:l.status==="completed"})}catch{}}return[...a.values()]}function ut({messages:t,streaming:s,className:a}){const n=c.useRef(null),[r,i]=c.useState(!0),[l,o]=c.useState(!0),d=c.useRef(0);c.useEffect(()=>(s&&r&&t.length>0&&(cancelAnimationFrame(d.current),d.current=requestAnimationFrame(()=>{var f;(f=n.current)==null||f.scrollToIndex({index:t.length-1,align:"end",behavior:"smooth"})})),()=>cancelAnimationFrame(d.current)),[s,r,t]);const u=c.useCallback(()=>{var f;(f=n.current)==null||f.scrollToIndex({index:0,align:"start",behavior:"smooth"})},[]),x=c.useCallback(()=>{var f;(f=n.current)==null||f.scrollToIndex({index:t.length-1,align:"end",behavior:"smooth"})},[t.length]);return e.jsxs("div",{className:`h-full overflow-hidden rounded-2xl border border-neutral-border bg-neutral-bg/40 backdrop-blur-sm shadow-inner relative ${a}`,children:[e.jsxs(W,{children:[!l&&e.jsx(y.button,{initial:{opacity:0,y:-10},animate:{opacity:1,y:0},exit:{opacity:0,y:-10},onClick:u,className:"absolute top-4 right-4 z-30 flex h-10 w-10 items-center justify-center rounded-full bg-white/10 backdrop-blur-xl border border-white/20 text-white hover:bg-white/20 transition-all shadow-2xl shadow-black/50",title:"Jump to top",children:e.jsx(oa,{size:20})}),!r&&e.jsx(y.button,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0,y:10},onClick:x,className:"absolute bottom-4 right-4 z-30 flex h-12 w-12 items-center justify-center rounded-full bg-primary-500 hover:bg-primary-400 text-white transition-all shadow-2xl shadow-primary-500/40 border border-white/20",title:"Jump to bottom",children:e.jsx(He,{size:24})})]}),t.length===0&&e.jsxs(y.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2,ease:"easeOut"},className:"absolute inset-0 flex flex-col items-center justify-center text-center p-6",children:[e.jsxs("div",{className:"relative mb-6",children:[e.jsx(y.div,{className:"absolute inset-0 -m-16 rounded-full",animate:{opacity:[.04,.08,.05,.07,.04],scale:[1,1.15,1.05,1.1,1]},transition:{duration:12,repeat:1/0,ease:"easeInOut"},style:{background:"radial-gradient(circle, rgba(139,92,246,0.3) 0%, rgba(79,70,229,0.1) 40%, transparent 70%)",filter:"blur(20px)"}}),e.jsx(y.div,{className:"absolute inset-0 -m-10 rounded-full",animate:{opacity:[.06,.12,.08,.1,.06],scale:[1,1.08,1.02,1.06,1]},transition:{duration:8,repeat:1/0,ease:"easeInOut",delay:.5},style:{background:"radial-gradient(circle, rgba(34,211,238,0.15) 0%, transparent 60%)",filter:"blur(12px)"}}),e.jsx(y.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},transition:{duration:1.5,ease:[.16,1,.3,1],delay:.2},children:e.jsx(J,{size:120})})]}),e.jsx(y.h2,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{delay:.6,duration:.8},className:"mb-2 text-base font-bold tracking-tight text-neutral-text",children:"Neural Engine Ready"}),e.jsx(y.p,{initial:{opacity:0,y:6},animate:{opacity:1,y:0},transition:{delay:.8,duration:.8},className:"max-w-[280px] text-[11px] leading-relaxed text-neutral-muted",children:"Awaiting prompt sequence. Issue context is pre-loaded into working memory."})]}),e.jsx(ns,{ref:n,style:{height:"100%"},data:t,followOutput:f=>f?"smooth":!1,atBottomStateChange:i,atTopStateChange:o,atBottomThreshold:200,initialTopMostItemIndex:t.length-1,itemContent:(f,m)=>e.jsx("div",{className:"px-6 py-3",children:m.role==="user"?e.jsx(y.div,{initial:{opacity:0,y:10,scale:.98},animate:{opacity:1,y:0,scale:1},className:"flex justify-end",children:e.jsxs("div",{className:"max-w-[85%] text-right",children:[e.jsxs("div",{className:"mb-1.5 flex items-center justify-end gap-2 text-[9px] font-bold uppercase tracking-widest text-neutral-muted",children:[e.jsx("span",{children:"Operator"}),e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-neutral-muted/60"})]}),e.jsx("div",{className:"rounded-2xl px-5 py-3 text-sm leading-relaxed bg-primary-500 text-white shadow-[0_4px_24px_-4px_rgba(79,70,229,0.4)]",children:e.jsx("pre",{className:"whitespace-pre-wrap font-sans",children:m.content})})]})}):e.jsx(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},children:e.jsx("div",{className:"px-1 py-1",children:e.jsx(Ns,{blocks:rr(m.blocks),isStreaming:s&&f===t.length-1})})})})})]})}const lr={health:es,security:Zt,performance:we,architecture:Qt,"code-quality":Kt,workflow:oe},or={health:"text-emerald-400",security:"text-red-400",performance:"text-amber-400",architecture:"text-blue-400","code-quality":"text-purple-400",workflow:"text-secondary-400"};function cr({filter:t,onSelect:s,onClose:a}){const[n,r]=c.useState(0),i=c.useMemo(()=>{const l=t.toLowerCase().replace(/^\//,"");return l?le.filter(o=>o.name.toLowerCase().includes(l)||o.id.toLowerCase().includes(l)||o.slashCommand.toLowerCase().includes(l)):le},[t]);return c.useEffect(()=>{r(0)},[i]),c.useEffect(()=>{const l=o=>{o.key==="ArrowDown"?(o.preventDefault(),r(d=>(d+1)%i.length)):o.key==="ArrowUp"?(o.preventDefault(),r(d=>(d-1+i.length)%i.length)):o.key==="Enter"?i[n]&&(o.preventDefault(),s(i[n])):o.key==="Escape"&&(o.preventDefault(),a())};return window.addEventListener("keydown",l),()=>window.removeEventListener("keydown",l)},[i,n,s,a]),i.length===0?null:e.jsxs(y.div,{initial:{opacity:0,y:10,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:10,scale:.95},className:"absolute bottom-full left-0 right-0 mb-2 overflow-hidden rounded-xl border border-white/10 bg-neutral-bg/80 backdrop-blur-2xl shadow-2xl z-[70]",children:[e.jsx("div",{className:"max-h-60 overflow-y-auto p-1 custom-scrollbar",children:i.map((l,o)=>{const d=lr[l.category],u=or[l.category],x=o===n;return e.jsxs("button",{onClick:()=>s(l),onMouseEnter:()=>r(o),className:`flex w-full items-center gap-3 rounded-lg px-3 py-2 text-left transition-all ${x?"bg-white/10":"hover:bg-white/5"}`,children:[e.jsx("div",{className:`shrink-0 ${u}`,children:e.jsx(d,{size:14})}),e.jsxs("div",{className:"flex-1 overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-bold text-white truncate",children:l.name}),e.jsx("span",{className:"text-[9px] font-mono text-neutral-muted uppercase tracking-tighter shrink-0 ml-2",children:l.category})]}),e.jsx("div",{className:"text-[10px] text-neutral-muted truncate font-mono",children:l.slashCommand})]}),x&&e.jsx("div",{className:"text-[10px] font-mono text-primary-400 animate-pulse",children:"↵"})]},l.id)})}),e.jsxs("div",{className:"border-t border-white/5 bg-white/5 px-3 py-1.5 flex items-center justify-between",children:[e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-widest text-neutral-muted/50",children:"Command Registry"}),e.jsxs("div",{className:"flex gap-2 text-[9px] font-mono text-neutral-muted/30",children:[e.jsx("span",{children:"↑↓ to navigate"}),e.jsx("span",{children:"↵ to select"})]})]})]})}function nt({value:t,onChange:s,onSend:a,disabled:n,placeholder:r}){const[i,l]=c.useState(!1),o=u=>{if(s(u),u.startsWith("/")){const x=u.toLowerCase().replace(/^\//,""),f=le.some(m=>m.name.toLowerCase().includes(x)||m.id.toLowerCase().includes(x)||m.slashCommand.toLowerCase().includes(x));l(f)}else l(!1)},d=u=>{s(u.slashCommand+" "),l(!1)};return e.jsxs("div",{className:"relative",children:[i&&e.jsx(cr,{filter:t,onSelect:d,onClose:()=>l(!1)}),e.jsx("textarea",{rows:1,value:t,onChange:u=>o(u.target.value),onKeyDown:u=>{i&&(u.key==="ArrowUp"||u.key==="ArrowDown"||u.key==="Enter"&&t.startsWith("/"))||u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),a())},placeholder:r??"Execute command or query neural link...",disabled:n,className:"w-full resize-none rounded-2xl border border-neutral-border bg-neutral-surface/60 px-5 py-4 pr-14 text-sm text-neutral-text placeholder-neutral-muted/50 backdrop-blur-xl transition-all focus:border-primary-500 focus:outline-none focus:ring-4 focus:ring-primary-500/10 disabled:opacity-50 shadow-lg"}),e.jsx("button",{onClick:a,disabled:n||!t.trim(),className:"absolute right-3 top-1/2 -translate-y-1/2 rounded-xl bg-primary-500 p-2.5 text-white transition-all hover:scale-105 active:scale-95 disabled:cursor-not-allowed disabled:opacity-30 shadow-[0_0_15px_rgba(79,70,229,0.3)]",children:n?e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-white border-t-transparent"}):e.jsx(dt,{size:18})})]})}function dr(t,s){var n;const a=(n=s["/api/checks"])==null?void 0:n.data;if(!a)return"No specific context data found for this skill.";switch(t.category){case"security":return ur(a.security);case"performance":return hr(a.perf);case"architecture":return fr(a.arch);case"health":return"Analyzing overall project health and implementation artifacts.";default:return t.description}}function xr(t,s){var r;const a=(r=s["/api/checks"])==null?void 0:r.data,n=[`You are launching the harness skill: ${t.name} (${t.id}).`,`Goal: ${t.description}`,""];return a&&(t.category==="security"?n.push("## Security Context",mr(a.security)):t.category==="performance"?n.push("## Performance Context",pr(a.perf)):t.category==="architecture"&&n.push("## Architecture Context",gr(a.arch))),n.push("","## Instructions",`Please proceed with the ${t.name} task. Use the provided context to prioritize your analysis and remediation efforts.`,"If specific files are mentioned in the context, start by examining those files."),n.join(`
13
+ `)}function ur(t){return"error"in t?`Security scan error: ${t.error}`:t.stats.errorCount===0&&t.stats.warningCount===0?"No security issues found in the latest scan.":`Found ${t.stats.errorCount} errors and ${t.stats.warningCount} warnings across ${t.stats.filesScanned} files.`}function mr(t){return"error"in t?`Error: ${t.error}`:t.findings.map(s=>`- [${s.severity}] ${s.ruleId} in ${s.file}:${s.line}: ${s.message}`).join(`
14
+ `)}function hr(t){return"error"in t?`Performance audit error: ${t.error}`:t.stats.violationCount===0?"No performance violations detected.":`Found ${t.stats.violationCount} performance violations in ${t.stats.filesAnalyzed} files.`}function pr(t){return"error"in t?`Error: ${t.error}`:t.violations.map(s=>`- [${s.severity}] ${s.metric} in ${s.file}: ${s.value} (threshold: ${s.threshold})`).join(`
15
+ `)}function fr(t){return"error"in t?`Architecture check error: ${t.error}`:t.totalViolations===0?"No architectural violations found.":`Found ${t.totalViolations} architectural violations across the codebase.`}function gr(t){return"error"in t?`Error: ${t.error}`:t.newViolations.map(s=>`- [${s.severity}] ${s.file}: ${s.detail}`).join(`
16
+ `)}function yr({skill:t,context:s,onExecute:a,onCancel:n}){const r=dr(t,s.data);return e.jsxs(y.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},exit:{opacity:0,scale:.95},className:"flex flex-col gap-6 p-6 h-full overflow-y-auto custom-scrollbar",children:[e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary-400",children:[e.jsx(Ee,{size:16}),e.jsx("span",{className:"text-[10px] font-black uppercase tracking-[0.2em]",children:"Strategy Briefing"})]}),e.jsx("h2",{className:"text-2xl font-bold text-white",children:t.name}),e.jsx("p",{className:"text-sm text-neutral-muted leading-relaxed",children:t.description})]}),e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/5 p-5 backdrop-blur-xl flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-[10px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:"Telemetry Findings"}),s.isLoading&&e.jsx(Be,{size:14,className:"animate-spin text-primary-500"})]}),s.error?e.jsxs("div",{className:"flex gap-3 text-red-400 bg-red-400/10 p-3 rounded-lg border border-red-400/20",children:[e.jsx(ts,{size:16,className:"shrink-0"}),e.jsx("p",{className:"text-xs leading-tight",children:s.error})]}):s.isLoading?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("div",{className:"h-4 w-3/4 bg-white/5 animate-pulse rounded"}),e.jsx("div",{className:"h-4 w-1/2 bg-white/5 animate-pulse rounded"})]}):e.jsxs("div",{className:"flex flex-col gap-3",children:[e.jsx("p",{className:"text-sm text-white leading-relaxed font-medium",children:r}),e.jsxs("div",{className:"flex items-center gap-2 text-[10px] font-mono text-neutral-muted",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500"}),e.jsx("span",{children:"Context automatically extracted from latest dashboard telemetry"})]})]})]}),e.jsxs("div",{className:"mt-auto pt-6 flex flex-col gap-3",children:[e.jsxs(y.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:a,disabled:s.isLoading,className:"w-full flex items-center justify-center gap-3 rounded-2xl bg-primary-500 py-4 text-sm font-bold text-white shadow-[0_0_20px_rgba(79,70,229,0.4)] transition-all hover:shadow-[0_0_30px_rgba(79,70,229,0.6)] disabled:opacity-50 disabled:cursor-not-allowed",children:[e.jsx(ca,{size:18,fill:"currentColor"}),"Execute ",t.name]}),n&&e.jsx("button",{onClick:n,className:"w-full py-2 text-[10px] font-bold uppercase tracking-widest text-neutral-muted hover:text-white transition-colors",children:"Change Command"})]}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-[9px] font-mono text-neutral-muted/30 uppercase tracking-tighter",children:"Verification loop: pre-launch strategy pass active"})})]})}async function vs(t,s,a,n,r){try{const i=await fetch("/api/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:t,system:s,sessionId:a}),signal:r});if(!i.ok||!i.body){n.onError(`Chat request failed: HTTP ${i.status}`);return}const l=i.body.getReader(),o=new TextDecoder;let d="";for(;;){const{done:u,value:x}=await l.read();if(u)break;d+=o.decode(x,{stream:!0});const f=d.split(`
17
+ `);d=f.pop()??"";for(const m of f){if(!m.startsWith("data: "))continue;const p=m.slice(6).trim();if(p==="[DONE]"){n.onDone();return}try{const h=JSON.parse(p);if(typeof h!="object"||h===null||!("type"in h))continue;const g=h;if(g.type==="session")n.onSession(g.sessionId);else if(g.type==="error"){n.onError(g.error);return}else n.onChunk(g)}catch{}}}n.onDone()}catch(i){i.name!=="AbortError"&&n.onError(i.message??"Stream failed")}}function ws(t,s){if(s.type==="session"||s.type==="error")return;const a=t[t.length-1];switch(s.type){case"text":br(t,a,s.text);break;case"thinking":jr(t,a,s.text);break;case"tool_use":t.push({kind:"tool_use",tool:s.tool,...s.args!=null?{args:s.args}:{}});break;case"tool_args_delta":Nr(t,s.text);break;case"tool_result":vr(t,s.content,s.isError);break;case"status":wr(t,a,s.text);break}}function br(t,s,a){(s==null?void 0:s.kind)==="text"?t[t.length-1]={kind:"text",text:s.text+a}:((s==null?void 0:s.kind)==="status"&&t.pop(),t.push({kind:"text",text:a}))}function jr(t,s,a){(s==null?void 0:s.kind)==="thinking"?t[t.length-1]={kind:"thinking",text:s.text+a}:t.push({kind:"thinking",text:a})}function Nr(t,s){for(let a=t.length-1;a>=0;a--){const n=t[a];if(n.kind==="tool_use"&&n.result===void 0){t[a]={...n,args:(n.args??"")+s};break}}}function vr(t,s,a){for(let n=t.length-1;n>=0;n--){const r=t[n];if(r.kind==="tool_use"&&r.result===void 0){t[n]={...r,result:s,...a!=null?{isError:a}:{}};break}}}function wr(t,s,a){(s==null?void 0:s.kind)==="status"?t[t.length-1]={kind:"status",text:a}:t.push({kind:"status",text:a})}async function kr(t){const s=await fetch(t);if(!s.ok)throw new Error(`Failed to fetch context from ${t}: ${s.statusText}`);const a=await s.json();return{source:t,data:a}}function Sr(t){const s={};for(const{source:a,data:n}of t)s[a]=n;return s}function Cr(t){return t instanceof Error?t.message:"Unknown error fetching chat context"}function Mr(t){return t?t.split("|"):[]}function Tr(t,s,a){t({}),s(!1),a(null)}function Ir(t){const[s,a]=c.useState({}),[n,r]=c.useState(!1),[i,l]=c.useState(null),o=c.useMemo(()=>(t??[]).join("|"),[t]);return c.useEffect(()=>{const d=Mr(o);if(d.length===0){Tr(a,r,l);return}let u=!0;return r(!0),l(null),Promise.all(d.map(kr)).then(x=>{u&&a(Sr(x))}).catch(x=>{u&&l(Cr(x))}).finally(()=>{u&&r(!1)}),()=>{u=!1}},[o]),{data:s,isLoading:n,error:i}}const $r=[];function Ar(t){fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}).catch(s=>console.error("Failed to persist session:",s))}function Er({thread:t}){const s=t.meta,a=E(k=>k.messages.get(t.id)??$r),n=E;c.useEffect(()=>{const k=[];for(const M of a)M.role==="assistant"&&k.push(...M.blocks);const $=ir(k);$.length>0&&E.getState().updatePanelState(t.id,{todos:$})},[a,t.id]);const[r,i]=c.useState(""),[l,o]=c.useState(!1),[d,u]=c.useState(null),[x,f]=c.useState(),[m,p]=c.useState(null),[h,g]=c.useState(!1),b=c.useRef(new Set),j=c.useRef(null);c.useEffect(()=>{const k=n.getState().messages.get(t.id);k&&k.length>0||fetch(`/api/sessions/${s.sessionId}`).then($=>$.ok?$.json():null).then($=>{$&&Array.isArray($.messages)&&(n.getState().setMessages(t.id,$.messages),$.orchestratorSessionId&&f($.orchestratorSessionId))}).catch(()=>{})},[s.sessionId,t.id,n]),c.useEffect(()=>{if(s.command&&!m){const k=le.find($=>$.id===s.command||$.slashCommand===s.command);k&&(p(k),g(!0))}},[s.command,m]);const N=c.useMemo(()=>m||(s.command?le.find(k=>k.id===s.command)??null:null),[m,s.command]),v=Ir(N==null?void 0:N.contextSources),S=c.useCallback(async(k,$)=>{const M=(k??r).trim();if(!M||l)return;const L=a.length===0,O={role:"user",content:M},R={role:"assistant",blocks:[]};n.getState().appendMessage(t.id,O),n.getState().appendMessage(t.id,R),i(""),o(!0),u(null);const G={sessionId:s.sessionId,...x?{orchestratorSessionId:x}:{},command:s.command,interactionId:null,label:t.title,createdAt:new Date(t.createdAt).toISOString(),lastActiveAt:new Date().toISOString(),artifacts:[],status:"active",messages:[...a,O,R],input:""};Ar(G);const Y=L?void 0:x,Q=new AbortController;await vs(M,$,Y,{onSession:U=>{f(U)},onChunk:U=>{n.getState().updateLastMessage(t.id,A=>{if(A.role!=="assistant")return A;const P=[...A.blocks];return ws(P,U),{...A,blocks:P}})},onDone:()=>{if(o(!1),t.title==="New Chat"&&M.length>0){const U=M.length>50?M.slice(0,47)+"...":M;n.getState().updateThread(t.id,{title:U})}},onError:U=>{u(U),n.getState().updateLastMessage(t.id,A=>A.role!=="assistant"?A:{...A,blocks:[...A.blocks,{kind:"text",text:`**Error:** ${U}`}]}),o(!1)}},Q.signal)},[r,l,a,s,x,t]);c.useEffect(()=>{const k=$=>{const M=$.detail;typeof M=="string"&&M.length>0&&!l&&S(M)};return window.addEventListener("chat-action-send",k),()=>window.removeEventListener("chat-action-send",k)},[S,l]);const T=c.useCallback(()=>{if(!m)return;const k=xr(m,v.data),$=j.current,M=$?`${m.slashCommand} ${$}`:m.slashCommand;j.current=null,g(!1),S(M,k),p(null)},[m,v.data,S]);c.useEffect(()=>{m&&!h&&a.length===0&&!l&&!v.isLoading&&!b.current.has(s.sessionId)&&(b.current.add(s.sessionId),T())},[m,h,a.length,l,v.isLoading,T,s.sessionId]);const w=c.useCallback(k=>{p(k),g(!0),a.length===0&&n.getState().updateThread(t.id,{title:k.id.split(":").pop()||"New Chat"})},[a.length,t.id]);return a.length===0&&!m&&!s.command?e.jsxs("div",{className:"flex flex-1 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-3 border-b border-white/[0.06] px-6 py-4",children:[e.jsx(J,{size:36,growthDuration:5}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-bold text-white",children:t.title}),e.jsx("p",{className:"text-[10px] text-neutral-muted",children:"Start a conversation or select a skill"})]})]}),e.jsxs("div",{className:"flex-1 flex flex-col overflow-y-auto",children:[e.jsx("div",{className:"px-4 pt-4",children:e.jsx(nt,{value:r,onChange:i,onSend:()=>void S(),disabled:l,placeholder:"Type a message or select a skill below..."})}),e.jsx("div",{className:"flex-1 px-4 py-4",children:e.jsx(xs,{onSelect:w})})]})]}):h&&m&&a.length===0?e.jsxs("div",{className:"flex flex-1 flex-col",children:[e.jsxs("div",{className:"flex items-center gap-3 border-b border-white/[0.06] px-6 py-4",children:[e.jsx(J,{size:36,growthDuration:5}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-sm font-bold text-white",children:m.name}),e.jsx("p",{className:"text-[10px] text-neutral-muted",children:m.description})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:e.jsx(yr,{skill:m,context:v,onExecute:T,onCancel:()=>{p(null),g(!1)}})})]}):e.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-center gap-3 border-b border-white/[0.06] px-6 py-3 flex-shrink-0",children:[e.jsx(J,{size:28,growthDuration:5}),e.jsx("h2",{className:"text-sm font-bold text-white truncate",children:t.title}),l&&e.jsx(y.div,{animate:{opacity:[.4,1,.4]},transition:{duration:1.5,repeat:1/0},className:"text-[9px] font-bold uppercase tracking-widest text-primary-500",children:"Streaming"}),d&&e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-widest text-semantic-error",children:"Error"})]}),e.jsx("div",{className:"flex-1 min-h-0 p-4",children:e.jsx(ut,{messages:a,streaming:l})}),e.jsx("div",{className:"flex-shrink-0 border-t border-white/[0.06] px-4 py-3",children:e.jsx(nt,{value:r,onChange:i,onSend:()=>void S(),disabled:l,placeholder:"Type a message..."})})]})}const Dt={low:"bg-emerald-500/10 text-emerald-400 border-emerald-500/20",medium:"bg-yellow-500/10 text-yellow-400 border-yellow-500/20",high:"bg-orange-500/10 text-orange-400 border-orange-500/20",critical:"bg-red-500/10 text-red-400 border-red-500/20"};function Rr({spec:t}){return e.jsxs("div",{className:"space-y-3 rounded-lg border border-primary-500/20 bg-primary-500/5 p-3",children:[e.jsx("h4",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-primary-500",children:"Enriched Spec (SEL)"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-[0.15em] text-neutral-muted",children:"Intent"}),e.jsx("p",{className:"mt-0.5 text-xs text-white",children:t.intent})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-[0.15em] text-neutral-muted",children:"Summary"}),e.jsx("p",{className:"mt-0.5 text-xs text-neutral-text/80 leading-relaxed",children:t.summary})]}),t.affectedSystems.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-[0.15em] text-neutral-muted",children:"Affected Systems"}),e.jsx("div",{className:"mt-1 flex flex-wrap gap-1",children:t.affectedSystems.map(s=>e.jsxs("span",{className:"rounded-md border border-blue-500/20 bg-blue-500/10 px-1.5 py-0.5 text-[9px] font-medium text-blue-400",title:`Confidence: ${Math.round(s.confidence*100)}% | Tests: ${s.testCoverage} | Deps: ${s.transitiveDeps.length}`,children:[s.name,s.graphNodeId&&e.jsxs("span",{className:"ml-1 text-blue-500/50",children:[Math.round(s.confidence*100),"%"]})]},s.name))})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-2 md:grid-cols-3",children:[t.unknowns.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[9px] font-bold uppercase tracking-[0.15em] text-amber-400",children:["Unknowns (",t.unknowns.length,")"]}),e.jsx("ul",{className:"mt-0.5 space-y-0.5",children:t.unknowns.map((s,a)=>e.jsx("li",{className:"text-[11px] text-neutral-text/70",children:s},a))})]}),t.ambiguities.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[9px] font-bold uppercase tracking-[0.15em] text-orange-400",children:["Ambiguities (",t.ambiguities.length,")"]}),e.jsx("ul",{className:"mt-0.5 space-y-0.5",children:t.ambiguities.map((s,a)=>e.jsx("li",{className:"text-[11px] text-neutral-text/70",children:s},a))})]}),t.riskSignals.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[9px] font-bold uppercase tracking-[0.15em] text-red-400",children:["Risk Signals (",t.riskSignals.length,")"]}),e.jsx("ul",{className:"mt-0.5 space-y-0.5",children:t.riskSignals.map((s,a)=>e.jsx("li",{className:"text-[11px] text-neutral-text/70",children:s},a))})]})]})]})}const Lr={local:"text-emerald-400",human:"text-amber-400","simulation-required":"text-purple-400"};function ye({value:t,label:s,color:a}){const n=Math.round(t*100);return e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs("div",{className:"flex justify-between text-[10px]",children:[e.jsx("span",{className:"text-neutral-muted",children:s}),e.jsxs("span",{className:a,children:[n,"%"]})]}),e.jsx("div",{className:"h-1 w-full rounded-full bg-white/[0.06]",children:e.jsx("div",{className:`h-full rounded-full ${a.replace("text-","bg-")}`,style:{width:`${n}%`}})})]})}function Dr({score:t}){return e.jsxs("div",{className:"space-y-3 rounded-lg border border-secondary-400/20 bg-secondary-400/5 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-secondary-400",children:"Complexity (CML)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`inline-block rounded-md border px-1.5 py-0.5 text-[9px] font-bold uppercase ${Dt[t.riskLevel]??Dt.medium}`,children:t.riskLevel}),e.jsx("span",{className:`text-[10px] font-mono font-bold ${Lr[t.recommendedRoute]??"text-neutral-muted"}`,children:t.recommendedRoute})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ye,{value:t.overall,label:"Overall",color:"text-primary-500"}),e.jsx(ye,{value:t.dimensions.structural,label:"Structural",color:"text-blue-400"}),e.jsx(ye,{value:t.dimensions.semantic,label:"Semantic",color:"text-purple-400"}),e.jsx(ye,{value:t.dimensions.historical,label:"Historical",color:"text-yellow-400"}),e.jsx(ye,{value:t.confidence,label:"Confidence",color:"text-emerald-400"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 border-t border-white/[0.06] pt-2 md:grid-cols-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-sm font-bold text-white",children:t.blastRadius.services}),e.jsx("span",{className:"text-[9px] uppercase tracking-widest text-neutral-muted",children:"Services"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-sm font-bold text-white",children:t.blastRadius.modules}),e.jsx("span",{className:"text-[9px] uppercase tracking-widest text-neutral-muted",children:"Modules"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-sm font-bold text-white",children:t.blastRadius.filesEstimated}),e.jsx("span",{className:"text-[9px] uppercase tracking-widest text-neutral-muted",children:"Files"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-sm font-bold text-white",children:t.blastRadius.testFilesAffected}),e.jsx("span",{className:"text-[9px] uppercase tracking-widest text-neutral-muted",children:"Test Files"})]})]}),t.reasoning.length>0&&e.jsxs("div",{className:"border-t border-white/[0.06] pt-2",children:[e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-[0.15em] text-neutral-muted",children:"Reasoning"}),e.jsx("ul",{className:"mt-0.5 space-y-0.5",children:t.reasoning.map((s,a)=>e.jsx("li",{className:"text-[11px] text-neutral-text/70",children:s},a))})]})]})}function Or({interaction:t,collapsed:s,onClaim:a,onDismiss:n}){const[r,i]=c.useState(!s),{context:l,reasons:o}=t;return e.jsxs("div",{className:"border-b border-white/[0.06] bg-neutral-surface/20 backdrop-blur-sm",children:[e.jsxs("button",{onClick:()=>i(!r),className:"flex w-full items-center gap-3 px-6 py-3 text-left hover:bg-white/[0.02] transition-colors",children:[e.jsx(Xt,{size:16,className:"text-semantic-warning flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"text-sm font-bold text-white truncate",children:l.issueTitle}),s&&e.jsx("p",{className:"text-[10px] text-neutral-muted truncate",children:o[0]||"Needs attention"})]}),!s&&e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[e.jsxs("button",{onClick:d=>{d.stopPropagation(),a()},className:"flex items-center gap-1 rounded-lg bg-primary-500/10 border border-primary-500/20 px-3 py-1 text-[9px] font-bold uppercase tracking-widest text-primary-500 hover:bg-primary-500/20 transition-colors",children:[e.jsx(xt,{size:10}),"Claim"]}),e.jsxs("button",{onClick:d=>{d.stopPropagation(),n()},className:"flex items-center gap-1 rounded-lg bg-white/[0.04] border border-white/[0.08] px-3 py-1 text-[9px] font-bold uppercase tracking-widest text-neutral-muted hover:text-white hover:bg-white/[0.08] transition-colors",children:[e.jsx(lt,{size:10}),"Dismiss"]})]}),e.jsx(y.div,{animate:{rotate:r?0:-90},transition:{duration:.2},children:e.jsx(He,{size:14,className:"text-neutral-muted"})})]}),e.jsx(W,{initial:!1,children:r&&e.jsx(y.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:"easeInOut"},className:"overflow-hidden",children:e.jsxs("div",{className:"px-6 pb-4 space-y-3",children:[l.issueDescription&&e.jsx("div",{className:"text-xs text-neutral-text/80 leading-relaxed prose prose-invert prose-xs max-w-none",children:e.jsx(te,{remarkPlugins:[se],children:l.issueDescription})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h4",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted",children:"Escalation Reasons"}),o.map((d,u)=>e.jsx("div",{className:"text-xs text-neutral-text/80 leading-relaxed prose prose-invert prose-xs max-w-none",children:e.jsx(te,{remarkPlugins:[se],children:d})},u))]}),l.enrichedSpec&&e.jsx(Rr,{spec:l.enrichedSpec}),l.complexityScore&&e.jsx(Dr,{score:l.complexityScore}),l.relatedFiles.length>0&&e.jsxs("div",{children:[e.jsx("h4",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted mb-1",children:"Related Files"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:l.relatedFiles.map(d=>e.jsx("span",{className:"rounded bg-white/[0.04] px-1.5 py-0.5 text-[10px] font-mono text-neutral-muted",children:d.split("/").pop()},d))})]})]})})})]})}const Pr=[];function Ot(t){const{context:s,reasons:a}=t,n=["You are helping a human engineer reason through a complex issue that was escalated from the orchestrator.","",`## Issue: ${s.issueTitle}`];return s.issueDescription&&n.push("","## Description",s.issueDescription),a.length>0&&n.push("","## Escalation Reasons",...a.map(r=>`- ${r}`)),s.specPath&&n.push("","## Spec",`Available at: ${s.specPath}`),s.relatedFiles.length>0&&n.push("","## Related Files",...s.relatedFiles.map(r=>`- ${r}`)),n.push("","## Instructions",'Help the human brainstorm and produce a plan. When the human is satisfied with the plan, they will save it using the "Save Plan" button.'),n.join(`
18
+ `)}function Fr({thread:t}){const s=t.meta,a=E,n=a(N=>N.messages.get(t.id)??Pr),[r,i]=c.useState(""),[l,o]=c.useState(!1),[d,u]=c.useState(),[x,f]=c.useState(null),[m,p]=c.useState(t.status==="active"),h=c.useRef(!1);c.useEffect(()=>{fetch("/api/interactions").then(N=>N.json()).then(N=>{const v=N.find(S=>S.id===s.interactionId);v&&(f(v),v.context.issueTitle&&t.title.startsWith("Attention:")&&a.getState().updateThread(t.id,{title:v.context.issueTitle}))}).catch(()=>{})},[s.interactionId,t.id,t.title]);const g=c.useCallback(()=>{a.getState().claimThread(t.id),p(!0),s.interactionId&&fetch(`/api/interactions/${s.interactionId}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:"claimed"})}).catch(()=>{})},[t.id,s.interactionId]),b=c.useCallback(()=>{a.getState().dismissThread(t.id),s.interactionId&&fetch(`/api/interactions/${s.interactionId}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:"resolved"})}).catch(()=>{})},[t.id,s.interactionId]),j=c.useCallback(async(N,v)=>{const S=(N??r).trim();if(!S||l)return;m||g();const T=n.length===0,w={role:"user",content:S},k={role:"assistant",blocks:[]};a.getState().appendMessage(t.id,w),a.getState().appendMessage(t.id,k),i(""),o(!0);let $=v;T&&!$&&x&&($=Ot(x));const M=T?void 0:d,L=new AbortController;await vs(S,$,M,{onSession:O=>u(O),onChunk:O=>{a.getState().updateLastMessage(t.id,R=>{if(R.role!=="assistant")return R;const G=[...R.blocks];return ws(G,O),{...R,blocks:G}})},onDone:()=>o(!1),onError:O=>{a.getState().updateLastMessage(t.id,R=>R.role!=="assistant"?R:{...R,blocks:[...R.blocks,{kind:"text",text:`**Error:** ${O}`}]}),o(!1)}},L.signal)},[r,l,m,n.length,x,d,g,t.id]);return c.useEffect(()=>{m&&x&&n.length===0&&!l&&!h.current&&(h.current=!0,j("Analyze this escalated issue and help me brainstorm an implementation approach.",Ot(x)))},[m,x,n.length,l,j]),x?e.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[e.jsx(Or,{interaction:x,collapsed:m,onClaim:g,onDismiss:b}),n.length>0&&e.jsx("div",{className:"flex-1 min-h-0 p-4",children:e.jsx(ut,{messages:n,streaming:l})}),m&&e.jsx("div",{className:"flex-shrink-0 border-t border-white/[0.06] px-4 py-3",children:e.jsx(nt,{value:r,onChange:i,onSend:()=>void j(),disabled:l,placeholder:"Discuss the escalation..."})})]}):e.jsx("div",{className:"flex flex-1 items-center justify-center",children:e.jsx(y.div,{animate:{opacity:[.3,1,.3]},transition:{duration:1.5,repeat:1/0},className:"text-xs text-neutral-muted",children:"Loading interaction..."})})}function _r(t){const s=[],a=t.trim().split(`
19
+ `).filter(Boolean);for(const n of a)try{const r=JSON.parse(n);if(r.type==="session_start"||r.type==="session_end")continue;const i=zr(r);ls(s,i)}catch{}return s}function zr(t){const s={type:typeof t.type=="string"?t.type:"",timestamp:typeof t.timestamp=="string"?t.timestamp:""};return typeof t.content=="string"?s.content=t.content:t.content!=null&&(s.content=JSON.stringify(t.content)),typeof t.subtype=="string"&&(s.subtype=t.subtype),typeof t.sessionId=="string"&&(s.sessionId=t.sessionId),s}function Br(t,s){const[a,n]=c.useState(null),[r,i]=c.useState([]),[l,o]=c.useState(!1),[d,u]=c.useState(null),x=c.useRef(null);return c.useEffect(()=>{if(!t){n(null),i([]),u(null),x.current=null;return}const f=`${t}:latest`;if(x.current===f)return;let m=!1;async function p(){o(!0),u(null);try{const h=await Hr(t);if(m)return;if(!h){n(null),i([]),o(!1);return}n(h);const g=await Wr(t,s);if(m)return;i(g),x.current=f}catch(h){m||u(h instanceof Error?h.message:"Failed to load stream")}finally{m||o(!1)}}return p(),()=>{m=!0}},[t,s]),{manifest:a,recordedBlocks:r,loading:l,error:d}}async function Hr(t){const s=await fetch(`/api/streams/${t}/manifest`);if(s.status===404)return null;if(!s.ok)throw new Error(`Manifest fetch failed: ${s.status}`);return await s.json()}async function Wr(t,s){const a=`/api/streams/${t}`,n=await fetch(a);if(!n.ok)throw new Error(`Stream fetch failed: ${n.status}`);const r=await n.text();return _r(r)}function Gr({thread:t}){const s=t.meta,n=c.useContext(ds)[s.issueId]??[],{recordedBlocks:r,manifest:i,loading:l}=Br(s.issueId),{snapshot:o}=ke(),d=c.useMemo(()=>{if(!o)return null;const h=o.running.find(([g])=>g===s.issueId);return h?h[1]:null},[o,s.issueId]),u=(d==null?void 0:d.session)??null,x=(i==null?void 0:i.attempts.at(-1))??null,f=c.useMemo(()=>r.length>0&&n.length>0?[...r,...n]:r.length>0?r:n,[r,n]),m=c.useMemo(()=>f.length===0?[]:[{role:"assistant",blocks:f}],[f]),p=t.status==="active";return c.useEffect(()=>{var b,j,N,v;const h=((b=x==null?void 0:x.stats)==null?void 0:b.durationMs)??null,g={identifier:s.identifier,phase:s.phase,backendName:(u==null?void 0:u.backendName)??s.backendName,description:s.issueDescription??null,turnCount:(u==null?void 0:u.turnCount)??((j=x==null?void 0:x.stats)==null?void 0:j.turnCount)??0,inputTokens:(u==null?void 0:u.inputTokens)??((N=x==null?void 0:x.stats)==null?void 0:N.inputTokens)??0,outputTokens:(u==null?void 0:u.outputTokens)??((v=x==null?void 0:x.stats)==null?void 0:v.outputTokens)??0,totalTokens:(u==null?void 0:u.totalTokens)??(x!=null&&x.stats?x.stats.inputTokens+x.stats.outputTokens:0),startedAt:s.startedAt?new Date(s.startedAt).getTime():null,durationMs:h,isRunning:p,pr:i!=null&&i.pr?{number:i.pr.number,status:i.pr.status}:null};E.getState().updatePanelState(t.id,{phase:s.phase,skill:s.backendName,startedAt:s.startedAt?new Date(s.startedAt).getTime():null,agentStats:g})},[s,u,x,i,t.id,p]),e.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[e.jsxs("div",{className:"flex items-center gap-3 border-b border-white/[0.06] px-6 py-3 flex-shrink-0",children:[e.jsx(J,{size:32,growthDuration:5}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h2",{className:"text-sm font-bold text-white truncate",children:t.title}),e.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-neutral-muted",children:[e.jsx("span",{className:"font-mono truncate",children:s.identifier}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(it,{size:10}),s.phase]})]})]}),p?e.jsxs(y.div,{animate:{opacity:[.4,1,.4]},transition:{duration:1.5,repeat:1/0},className:"flex items-center gap-1 text-[9px] font-bold uppercase tracking-widest text-semantic-success",children:[e.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-semantic-success"}),"Running"]}):e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-widest text-neutral-muted",children:"Completed"})]}),s.issueDescription&&e.jsx("div",{className:"border-b border-white/[0.06] px-6 py-3 flex-shrink-0",children:e.jsx("p",{className:"text-xs text-neutral-muted leading-relaxed line-clamp-3",children:s.issueDescription})}),e.jsx("div",{className:"flex-1 min-h-0 p-4",children:l?e.jsx("div",{className:"flex flex-1 items-center justify-center h-full",children:e.jsx(y.div,{animate:{opacity:[.3,1,.3]},transition:{duration:1.5,repeat:1/0},className:"text-xs text-neutral-muted",children:"Loading stream history..."})}):m.length>0?e.jsx(ut,{messages:m,streaming:p}):e.jsx("div",{className:"flex flex-1 items-center justify-center h-full",children:e.jsxs("div",{className:"text-center",children:[e.jsx(J,{size:60,growthDuration:10}),e.jsx("p",{className:"mt-4 text-xs text-neutral-muted",children:p?"Agent is working...":"No activity recorded for this session."})]})})})]})}function Ur({initialTitle:t,initialDescription:s,initialLabels:a,collapsed:n,onSubmit:r}){const[i,l]=c.useState(!n),[o,d]=c.useState(t),[u,x]=c.useState(s),[f,m]=c.useState(a.join(", ")),p=()=>{if(!o.trim())return;const h=f.split(",").map(g=>g.trim()).filter(Boolean);r({title:o.trim(),description:u.trim(),labels:h})};return e.jsxs("div",{className:"border-b border-white/[0.06] bg-neutral-surface/20 backdrop-blur-sm",children:[e.jsxs("button",{onClick:()=>l(!i),className:"flex w-full items-center gap-3 px-6 py-3 text-left hover:bg-white/[0.02] transition-colors",children:[e.jsx(ct,{size:16,className:"text-accent-500 flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"text-sm font-bold text-white truncate",children:o||"New Analysis"}),n&&e.jsx("p",{className:"text-[10px] text-neutral-muted truncate",children:"Analysis complete — expand to see inputs"})]}),e.jsx(y.div,{animate:{rotate:i?0:-90},transition:{duration:.2},children:e.jsx(He,{size:14,className:"text-neutral-muted"})})]}),e.jsx(W,{initial:!1,children:i&&e.jsx(y.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:"easeInOut"},className:"overflow-hidden",children:e.jsxs("div",{className:"px-6 pb-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted block mb-1",children:"Title *"}),e.jsx("input",{type:"text",value:o,onChange:h=>d(h.target.value),disabled:n,placeholder:"Feature or issue title...",className:"w-full rounded-lg border border-white/[0.08] bg-white/[0.04] px-3 py-2 text-sm text-white placeholder:text-neutral-muted/40 focus:border-primary-500/40 focus:outline-none focus:ring-2 focus:ring-primary-500/10 disabled:opacity-50"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted block mb-1",children:"Description"}),e.jsx("textarea",{value:u,onChange:h=>x(h.target.value),disabled:n,rows:3,placeholder:"Optional context...",className:"w-full rounded-lg border border-white/[0.08] bg-white/[0.04] px-3 py-2 text-sm text-white placeholder:text-neutral-muted/40 focus:border-primary-500/40 focus:outline-none focus:ring-2 focus:ring-primary-500/10 resize-none disabled:opacity-50"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-neutral-muted block mb-1",children:"Labels"}),e.jsx("input",{type:"text",value:f,onChange:h=>m(h.target.value),disabled:n,placeholder:"Comma-separated labels...",className:"w-full rounded-lg border border-white/[0.08] bg-white/[0.04] px-3 py-2 text-sm text-white placeholder:text-neutral-muted/40 focus:border-primary-500/40 focus:outline-none focus:ring-2 focus:ring-primary-500/10 disabled:opacity-50"})]}),!n&&e.jsxs("button",{onClick:p,disabled:!o.trim(),className:"flex items-center gap-2 rounded-lg bg-accent-500/10 border border-accent-500/20 px-4 py-2 text-xs font-bold text-accent-500 hover:bg-accent-500/20 transition-colors disabled:opacity-30 disabled:cursor-not-allowed",children:[e.jsx(dt,{size:12}),"Run Analysis"]})]})})})]})}const qr={low:"text-semantic-success border-semantic-success/20 bg-semantic-success/10",medium:"text-semantic-warning border-semantic-warning/20 bg-semantic-warning/10",high:"text-orange-400 border-orange-500/20 bg-orange-500/10",critical:"text-semantic-error border-semantic-error/20 bg-semantic-error/10"};function Yr({thread:t}){const s=t.meta,[a,n]=c.useState(!1),[r,i]=c.useState(!1),[l,o]=c.useState(null),[d,u]=c.useState(null),[x,f]=c.useState(null),[m,p]=c.useState(null),[h,g]=c.useState(null),b=c.useRef(null),j=c.useCallback(async N=>{n(!0),i(!0),o("Starting analysis..."),g(null),u(null),f(null),p(null),E.getState().updateThread(t.id,{title:N.title}),b.current=new AbortController;try{const v=await fetch("/api/analyze",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(N),signal:b.current.signal});if(!v.ok||!v.body){g(`HTTP ${v.status}`),i(!1);return}const S=v.body.getReader(),T=new TextDecoder;let w="";for(;;){const{done:k,value:$}=await S.read();if(k)break;w+=T.decode($,{stream:!0});const M=w.split(`
20
+ `);w=M.pop()??"";for(const L of M){if(!L.startsWith("data: "))continue;const O=L.slice(6).trim();if(O==="[DONE]"){i(!1),o(null);return}try{const R=JSON.parse(O);switch(R.type){case"status":o(R.text);break;case"sel_result":u(R.data);break;case"cml_result":f(R.data);break;case"pesl_result":p(R.data);break;case"error":g(R.error),i(!1);return}}catch{}}}i(!1),o(null)}catch(v){v.name!=="AbortError"&&g(v.message),i(!1)}},[t.id]);return e.jsxs("div",{className:"flex flex-1 flex-col min-h-0",children:[e.jsx(Ur,{initialTitle:s.analysisTitle,initialDescription:s.description,initialLabels:s.labels,collapsed:a,onSubmit:N=>void j(N)}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[r&&l&&e.jsxs(y.div,{animate:{opacity:[.5,1,.5]},transition:{duration:1.5,repeat:1/0},className:"flex items-center gap-2 text-xs text-primary-500",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-primary-500 animate-pulse"}),l]}),d&&e.jsxs(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"rounded-xl border border-primary-500/20 bg-primary-500/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ee,{size:14,className:"text-primary-500"}),e.jsx("h4",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-primary-500",children:"Spec Enrichment (SEL)"})]}),e.jsx("p",{className:"text-sm text-white font-medium",children:d.intent}),e.jsx("p",{className:"text-xs text-neutral-text/80 leading-relaxed",children:d.summary}),d.affectedSystems.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:d.affectedSystems.map(N=>e.jsxs("span",{className:"rounded-md border border-blue-500/20 bg-blue-500/10 px-2 py-0.5 text-[10px] text-blue-400",children:[N.name," (",Math.round(N.confidence*100),"%)"]},N.name))})]}),x&&e.jsxs(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"rounded-xl border border-secondary-400/20 bg-secondary-400/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{size:14,className:"text-secondary-400"}),e.jsx("h4",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-secondary-400",children:"Complexity Model (CML)"})]}),e.jsx("span",{className:`rounded-md border px-2 py-0.5 text-[9px] font-bold uppercase ${qr[x.riskLevel]??""}`,children:x.riskLevel})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-3",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("span",{className:"block text-lg font-bold text-white",children:[Math.round(x.overall*100),"%"]}),e.jsx("span",{className:"text-[9px] text-neutral-muted uppercase",children:"Overall"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-lg font-bold text-white",children:x.blastRadius.filesEstimated}),e.jsx("span",{className:"text-[9px] text-neutral-muted uppercase",children:"Files"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-lg font-bold text-white",children:x.blastRadius.modules}),e.jsx("span",{className:"text-[9px] text-neutral-muted uppercase",children:"Modules"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-lg font-bold text-white",children:x.recommendedRoute}),e.jsx("span",{className:"text-[9px] text-neutral-muted uppercase",children:"Route"})]})]})]}),m&&e.jsxs(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"rounded-xl border border-accent-500/20 bg-accent-500/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ss,{size:14,className:"text-accent-500"}),e.jsx("h4",{className:"text-[9px] font-black uppercase tracking-[0.2em] text-accent-500",children:"Simulation (PESL)"}),e.jsxs("span",{className:"text-xs text-neutral-muted ml-auto",children:["Confidence: ",Math.round(m.executionConfidence*100),"%"]})]}),m.predictedFailures.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[9px] font-bold uppercase text-red-400",children:"Predicted Failures"}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:m.predictedFailures.map((N,v)=>e.jsxs("li",{className:"text-xs text-neutral-text/80",children:["- ",N]},v))})]}),m.recommendedChanges.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[9px] font-bold uppercase text-accent-400",children:"Recommended Changes"}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:m.recommendedChanges.map((N,v)=>e.jsxs("li",{className:"text-xs text-neutral-text/80",children:["- ",N]},v))})]})]}),h&&e.jsx("div",{className:"rounded-xl border border-semantic-error/20 bg-semantic-error/5 p-4",children:e.jsxs("p",{className:"text-xs text-semantic-error",children:["Error: ",h]})}),a&&!r&&(d||x||m)&&e.jsxs(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"flex items-center gap-2 pt-2",children:[e.jsxs("button",{className:"flex items-center gap-1.5 rounded-lg bg-primary-500/10 border border-primary-500/20 px-3 py-1.5 text-[10px] font-bold text-primary-500 hover:bg-primary-500/20 transition-colors",children:[e.jsx(ot,{size:10}),"Add to Roadmap"]}),e.jsxs("button",{className:"flex items-center gap-1.5 rounded-lg bg-white/[0.04] border border-white/[0.08] px-3 py-1.5 text-[10px] font-bold text-neutral-muted hover:text-white hover:bg-white/[0.08] transition-colors",children:[e.jsx(as,{size:10}),"Export Spec"]}),e.jsxs("button",{onClick:()=>{n(!1),u(null),f(null),p(null),g(null)},className:"flex items-center gap-1.5 rounded-lg bg-white/[0.04] border border-white/[0.08] px-3 py-1.5 text-[10px] font-bold text-neutral-muted hover:text-white hover:bg-white/[0.08] transition-colors",children:[e.jsx(da,{size:10}),"Refine"]})]})]})]})}const Vr=3e3;function De(t,s){const[a,n]=c.useState({data:null,lastUpdated:null,stale:!1,error:null}),r=c.useRef(null);return c.useEffect(()=>{let i=null,l=!0;function o(){i=new EventSource(t),i.addEventListener(s,d=>{if(!l)return;const u=d;try{const x=JSON.parse(u.data);n({data:x.data,lastUpdated:x.timestamp,stale:!1,error:null})}catch{}}),i.onerror=()=>{l&&(i==null||i.close(),n(d=>({...d,stale:!0,error:"Connection lost. Reconnecting…"})),r.current=setTimeout(o,Vr))}}return o(),()=>{l=!1,i==null||i.close(),r.current&&clearTimeout(r.current)}},[t,s]),a}const Jr={default:"text-white",green:"text-emerald-400",yellow:"text-yellow-400",red:"text-red-400"};function D({label:t,value:s,sub:a,accent:n="default"}){return e.jsxs("div",{className:"rounded-lg border border-neutral-border bg-neutral-surface p-5",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-widest text-neutral-muted",children:t}),e.jsx("p",{className:["mt-2 text-3xl font-bold tabular-nums",Jr[n]].join(" "),children:s}),a&&e.jsx("p",{className:"mt-1 text-xs text-neutral-muted",children:a})]})}function mt({lastUpdated:t,stale:s,error:a}){const n=t?new Date(t).toLocaleTimeString():null;return s||a?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-secondary-400",children:[e.jsx("span",{className:"inline-block h-2 w-2 animate-pulse rounded-full bg-secondary-400"}),e.jsx("span",{children:a??"Stale data"}),n&&e.jsxs("span",{className:"text-neutral-muted",children:["· last updated ",n]})]}):e.jsxs("div",{className:"flex items-center gap-2 text-xs text-neutral-muted",children:[e.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-secondary-400"}),e.jsxs("span",{children:["Live",n?` · updated ${n}`:""]})]})}function ks(t){const[s,a]=c.useState("idle"),[n,r]=c.useState(null),[i,l]=c.useState(null),o=c.useCallback(async d=>{a("loading"),l(null);try{const u=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},...d!==void 0?{body:JSON.stringify(d)}:{}}),x=await u.json();!u.ok||x&&typeof x=="object"&&"error"in x&&x.error?(a("error"),l(x.error??`HTTP ${u.status}`)):(a("success"),r(x))}catch(u){a("error"),l(u instanceof Error?u.message:"Network error")}},[t]);return{state:s,data:n,error:i,run:o}}function Xr({url:t,label:s,body:a,loadingLabel:n,onSuccess:r,className:i=""}){const{state:l,error:o,run:d}=ks(t),u=c.useRef(null),x=bt(0),f=bt(0),m={damping:15,stiffness:150},p=Re(x,m),h=Re(f,m);c.useEffect(()=>{l==="success"&&(r==null||r())},[l,r]);const g=S=>{if(!u.current)return;const{left:T,top:w,width:k,height:$}=u.current.getBoundingClientRect(),M=S.clientX-(T+k/2),L=S.clientY-(w+$/2);x.set(M*.3),f.set(L*.3)},b=()=>{x.set(0),f.set(0)},j=l==="loading",N=l==="success",v=l==="error";return e.jsxs("div",{className:`inline-flex flex-col items-center gap-2 ${i}`,children:[e.jsxs(y.button,{ref:u,style:{x:p,y:h},onMouseMove:g,onMouseLeave:b,whileTap:{scale:.95},onClick:()=>void d(a),disabled:j,className:["group relative flex items-center gap-2 overflow-hidden rounded-xl border px-5 py-2.5 text-xs font-bold uppercase tracking-wider transition-all duration-300 shadow-lg",j?"cursor-not-allowed border-neutral-border bg-neutral-surface/50 text-neutral-muted":"",N?"border-emerald-500/50 bg-emerald-500/10 text-emerald-400 shadow-emerald-500/20":"",v?"border-red-500/50 bg-red-500/10 text-red-400 shadow-red-500/20":"",!j&&!N&&!v?"border-primary-500/50 bg-primary-500/10 text-primary-500 hover:bg-primary-500 hover:text-white shadow-primary-500/20":""].filter(Boolean).join(" "),children:[!j&&!N&&e.jsx(y.div,{initial:{left:"-100%"},animate:{left:"100%"},transition:{duration:3,repeat:1/0,ease:"linear"},className:"absolute top-0 bottom-0 w-1/2 bg-gradient-to-r from-transparent via-white/5 to-transparent pointer-events-none"}),e.jsxs(W,{mode:"wait",children:[j&&e.jsx(y.div,{initial:{scale:0},animate:{scale:1},exit:{scale:0},children:e.jsx(Be,{className:"h-3.5 w-3.5 animate-spin"})},"loading"),N&&e.jsx(y.div,{initial:{scale:0},animate:{scale:1},exit:{scale:0},children:e.jsx(xt,{className:"h-3.5 w-3.5"})},"success"),v&&e.jsx(y.div,{initial:{scale:0},animate:{scale:1},exit:{scale:0},children:e.jsx(ts,{className:"h-3.5 w-3.5"})},"error")]}),e.jsx("span",{className:"relative z-10",children:j?n??"Syncing...":N?"Verified":s}),e.jsx("div",{className:"absolute inset-0 z-0 bg-gradient-to-r from-transparent via-white/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity"})]}),v&&o&&e.jsx(y.p,{initial:{opacity:0,y:-5},animate:{opacity:1,y:0},className:"text-[10px] font-mono font-bold text-red-400 uppercase tracking-tighter",children:o})]})}const Oe="/api/sse";function Kr(t){return typeof t=="object"&&t!==null&&"totalFeatures"in t}function Qr(t){return typeof t=="object"&&t!==null&&"totalIssues"in t}function Zr(t){return typeof t=="object"&&t!==null&&"available"in t&&t.available===!0}function ei(t){return typeof t=="object"&&t!==null&&"findings"in t&&"stats"in t}function ti(t){return typeof t=="object"&&t!==null&&"violations"in t&&"stats"in t}function si(t){return typeof t=="object"&&t!==null&&"passed"in t&&"totalViolations"in t}function ai(t){return typeof t=="object"&&t!==null&&"sourceNodeId"in t&&"layers"in t}const ht=c.memo(function({title:s,count:a,children:n}){const[r,i]=c.useState(!1);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("button",{onClick:()=>i(!r),className:"flex items-center gap-2 text-left transition-opacity hover:opacity-80","aria-expanded":r,children:[e.jsx("span",{className:"text-[10px] text-gray-600",children:r?"▼":"▶"}),e.jsxs("p",{className:"text-[10px] font-bold uppercase tracking-[0.2em] text-gray-500",children:[s," (",a,")"]})]}),r&&n]})});function Ss({command:t}){const s=X();return e.jsx("button",{onClick:()=>{const a=E.getState().createThread("chat",{sessionId:crypto.randomUUID(),command:t});s(`/t/${a.id}`)},className:"rounded bg-primary-500/10 px-2 py-1 text-[10px] font-bold uppercase tracking-widest text-primary-400 border border-primary-500/20 hover:bg-primary-500 hover:text-white transition-all",children:"Fix It"})}const ni=c.memo(function({data:s}){return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[e.jsx(D,{label:"Errors",value:s.stats.errorCount,accent:s.stats.errorCount>0?"red":"green"}),e.jsx(D,{label:"Warnings",value:s.stats.warningCount,accent:s.stats.warningCount>0?"yellow":"default"}),e.jsx(D,{label:"Info",value:s.stats.infoCount}),e.jsx(D,{label:"Files Scanned",value:s.stats.filesScanned})]}),s.findings.length>0&&e.jsx(ht,{title:"Top Findings",count:s.findings.length,children:e.jsx("div",{className:"space-y-2 rounded-lg border border-gray-800 bg-gray-900 p-4",children:s.findings.slice(0,10).map((a,n)=>e.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[e.jsxs("span",{className:a.severity==="error"?"text-red-400":a.severity==="warning"?"text-yellow-400":"text-gray-400",children:["[",a.severity,"]"]}),e.jsxs("span",{className:"text-gray-300",children:[a.file,":",a.line]}),e.jsx("span",{className:"text-gray-500",children:a.message})]},n))})})]})}),ri=c.memo(function({data:s}){return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3",children:[e.jsx(D,{label:"Violations",value:s.stats.violationCount,accent:s.stats.violationCount>0?"red":"green"}),e.jsx(D,{label:"Files Analyzed",value:s.stats.filesAnalyzed}),e.jsx(D,{label:"Status",value:s.valid?"OK":"Failing",accent:s.valid?"green":"red"})]}),s.violations.length>0&&e.jsx(ht,{title:"Violations",count:s.violations.length,children:e.jsx("div",{className:"space-y-2 rounded-lg border border-gray-800 bg-gray-900 p-4",children:s.violations.map((a,n)=>e.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[e.jsxs("span",{className:a.severity==="error"?"text-red-400":"text-yellow-400",children:["[",a.severity,"]"]}),e.jsx("span",{className:"text-gray-300",children:a.file}),e.jsxs("span",{className:"text-gray-500",children:[a.metric,": ",a.value," (threshold: ",a.threshold,")"]})]},n))})})]})}),ii=c.memo(function({data:s}){return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3",children:[e.jsx(D,{label:"Status",value:s.passed?"Passed":"Failed",accent:s.passed?"green":"red"}),e.jsx(D,{label:"Violations",value:s.totalViolations,accent:s.totalViolations>0?"red":"default"}),e.jsx(D,{label:"Regressions",value:s.regressions.length,accent:s.regressions.length>0?"yellow":"default"})]}),s.newViolations.length>0&&e.jsx(ht,{title:"New Violations",count:s.newViolations.length,children:e.jsx("div",{className:"space-y-2 rounded-lg border border-gray-800 bg-gray-900 p-4",children:s.newViolations.map((a,n)=>e.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[e.jsxs("span",{className:a.severity==="error"?"text-red-400":"text-yellow-400",children:["[",a.severity,"]"]}),e.jsx("span",{className:"text-gray-300",children:a.file}),e.jsx("span",{className:"text-gray-500",children:a.detail})]},n))})})]})});function li({healthData:t}){return e.jsxs("section",{children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Entropy Analysis"}),t.totalIssues>0&&e.jsx(Ss,{command:"harness:validate"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[e.jsx(D,{label:"Total Issues",value:t.totalIssues,accent:t.totalIssues>0?"yellow":"green"}),e.jsx(D,{label:"Errors",value:t.errors,accent:t.errors>0?"red":"default"}),e.jsx(D,{label:"Warnings",value:t.warnings,accent:t.warnings>0?"yellow":"default"}),e.jsx(D,{label:"Auto-fixable",value:t.fixableCount,accent:"default"})]})]})}function oi({healthData:t}){return e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Scan Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3",children:[e.jsx(D,{label:"Suggestions",value:t.suggestionCount}),e.jsx(D,{label:"Scan Duration",value:`${t.durationMs} ms`}),e.jsx(D,{label:"Analysis Errors",value:t.analysisErrors.length,accent:t.analysisErrors.length>0?"red":"default"})]})]})}function ci({healthData:t}){return t.analysisErrors.length===0?null:e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Analysis Errors"}),e.jsx("div",{className:"space-y-2 rounded-lg border border-red-900 bg-gray-900 p-4",children:t.analysisErrors.map((s,a)=>e.jsx("p",{className:"text-xs text-red-400",children:s},a))})]})}function Ke({title:t,raw:s,guard:a,Section:n,fixCommand:r}){const i=s,l=typeof i=="object"&&i!==null&&"stats"in i?i.stats:void 0,d=a(s)&&(l!=null&&(l.errorCount??0)+(l.warningCount??0)>0||i!=null&&"totalViolations"in i&&i.totalViolations>0||l!=null&&(l.violationCount??0)>0)&&r?e.jsx(Ss,{command:r}):void 0;return e.jsxs("section",{children:[e.jsxs("div",{className:"mb-3 flex w-full items-center justify-between",children:[e.jsx("h2",{className:"text-xs font-semibold uppercase tracking-widest text-gray-500",children:t}),d]}),s==null?e.jsx("p",{className:"text-sm text-gray-500",children:"Awaiting first scan..."}):a(s)?e.jsx(n,{data:s}):e.jsx("p",{className:"text-sm text-red-400",children:"error"in s?String(s.error):"Unavailable"})]})}function di({health:t}){const s="error"in t?String(t.error):"Unavailable";return e.jsx("p",{className:"text-sm text-red-400",children:s})}function xi({healthData:t,security:s,perf:a,arch:n}){return e.jsxs("div",{className:"space-y-8",children:[e.jsx(li,{healthData:t}),e.jsx(oi,{healthData:t}),e.jsx(ci,{healthData:t}),e.jsx(Ke,{title:"Security",raw:s,guard:ei,Section:ni,fixCommand:"harness:security-scan"}),e.jsx(Ke,{title:"Performance",raw:a,guard:ti,Section:ri,fixCommand:"harness:perf"}),e.jsx(Ke,{title:"Architecture",raw:n,guard:si,Section:ii,fixCommand:"harness:enforce-architecture"})]})}function ui(t){const s=t?t.health:null,a=s&&Qr(s)?s:null;return{health:s,healthData:a}}function mi(t){return{security:(t==null?void 0:t.security)??null,perf:(t==null?void 0:t.perf)??null,arch:(t==null?void 0:t.arch)??null}}const hi=["validate","check-deps","check-arch","check-perf","check-security","check-docs","phase-gate"];function pi(t){const s=Date.now()-new Date(t).getTime(),a=Math.floor(s/1e3);if(a<60)return`${a}s ago`;const n=Math.floor(a/60);return n<60?`${n}m ago`:`${Math.floor(n/60)}h ago`}const fi=c.memo(function({name:s,result:a,expanded:n,onToggle:r}){if(!a)return e.jsxs("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-3 w-3 rounded-full bg-gray-600"}),e.jsx("span",{className:"text-sm font-medium text-gray-400",children:s})]}),e.jsx("p",{className:"mt-1 text-xs text-gray-600",children:"Not yet run"})]});const i=a.passed?"border-emerald-800":"border-red-800",l=a.passed?"bg-emerald-400":"bg-red-400",o=a.passed?"text-emerald-400":"text-red-400";return e.jsxs("div",{className:`rounded-lg border ${i} bg-gray-900`,children:[e.jsxs("button",{onClick:r,className:"w-full p-4 text-left","aria-expanded":n,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`inline-block h-3 w-3 rounded-full ${l}`}),e.jsx("span",{className:"text-sm font-medium text-gray-200",children:s})]}),e.jsx("span",{className:`text-xs font-medium ${o}`,children:a.passed?"PASS":"FAIL"})]}),!n&&(a.errorCount>0||a.warningCount>0)&&e.jsxs("p",{className:"mt-1 text-xs text-gray-500",children:[a.errorCount>0&&`${a.errorCount} errors`,a.errorCount>0&&a.warningCount>0&&", ",a.warningCount>0&&`${a.warningCount} warnings`]})]}),n&&e.jsx("div",{className:"border-t border-gray-800 px-4 py-3",children:e.jsxs("div",{className:"space-y-1 text-xs",children:[e.jsxs("p",{className:"text-gray-400",children:["Errors:"," ",e.jsx("span",{className:a.errorCount>0?"text-red-400":"text-gray-300",children:a.errorCount})," | ","Warnings:"," ",e.jsx("span",{className:a.warningCount>0?"text-yellow-400":"text-gray-300",children:a.warningCount})]}),a.details&&e.jsx("p",{className:"text-gray-500",children:a.details})]})})]})});function gi(t){const s=new Map;if(!t)return s;for(const a of t.checks)s.set(a.name,a);return s}async function yi(t,s,a){try{const n=await fetch("/api/ci");if(!n.ok){s(`HTTP ${n.status}`);return}const r=await n.json();t(r.data),s(null)}catch(n){s(n instanceof Error?n.message:"Network error")}finally{a(!1)}}function bi(){const[t,s]=c.useState(null),[a,n]=c.useState(!0),[r,i]=c.useState(null),[l,o]=c.useState(new Set),d=c.useCallback(()=>{yi(s,i,n)},[]);c.useEffect(()=>{d()},[d]);const u=f=>{o(m=>{const p=new Set(m);return p.has(f)?p.delete(f):p.add(f),p})},x=c.useMemo(()=>gi(t),[t]);return e.jsxs("section",{children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsx("h2",{className:"text-xs font-semibold uppercase tracking-widest text-gray-500",children:"CI Checks"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Xr,{url:"/api/actions/refresh-checks",label:"Run All Checks",loadingLabel:"Running checks...",onSuccess:d}),(t==null?void 0:t.lastRun)&&e.jsxs("span",{className:"text-xs text-gray-500",children:["Last checked ",pi(t.lastRun)]})]})]}),a&&!t&&e.jsx("p",{className:"text-sm text-gray-500",children:"Loading check results..."}),r&&e.jsx("p",{className:"text-sm text-red-400",children:r}),e.jsx("div",{className:"grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:hi.map(f=>e.jsx(fi,{name:f,result:x.get(f),expanded:l.has(f),onToggle:()=>u(f)},f))})]})}function ji(){const{data:t,lastUpdated:s,stale:a,error:n}=De(Oe,"overview"),{data:r}=De(Oe,"checks"),{health:i,healthData:l}=ui(t),{security:o,perf:d,arch:u}=mi(r);return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Health"}),e.jsx(mt,{lastUpdated:s,stale:a,error:n})]}),e.jsxs("div",{className:"space-y-8",children:[e.jsx(bi,{}),!t&&!n&&e.jsx("p",{className:"text-sm text-gray-500",children:"Connecting to data stream..."}),i&&!l&&e.jsx(di,{health:i}),l&&e.jsx(xi,{healthData:l,security:o,perf:d,arch:u})]})]})}function Ni({reason:t}){return e.jsxs("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-6",children:[e.jsx("p",{className:"text-base font-medium text-gray-300",children:"Graph not connected"}),t&&e.jsx("p",{className:"mt-2 text-sm text-gray-500",children:t}),e.jsxs("div",{className:"mt-4 rounded border border-gray-700 bg-gray-950 p-4",children:[e.jsx("p",{className:"text-xs font-semibold text-gray-400",children:"To connect the graph:"}),e.jsxs("ol",{className:"mt-2 list-decimal list-inside space-y-1 text-xs text-gray-500",children:[e.jsxs("li",{children:["Run ",e.jsx("code",{className:"text-gray-300",children:"harness ingest"})," to build the knowledge graph"]}),e.jsx("li",{children:"Ensure the graph database is available in your project"}),e.jsx("li",{children:"Restart the dashboard to reconnect"})]})]})]})}const vi=c.memo(function({type:s,count:a,pct:n}){return e.jsxs("tr",{className:"hover:bg-gray-900",children:[e.jsx("td",{className:"px-4 py-2.5 text-gray-300",children:s}),e.jsx("td",{className:"px-4 py-2.5 text-right tabular-nums text-gray-400",children:a}),e.jsxs("td",{className:"px-4 py-2.5 text-right tabular-nums text-gray-500",children:[n,"%"]})]})}),wi=c.memo(function({nodesByType:s,nodeCount:a}){const n=c.useMemo(()=>[...s].sort((r,i)=>i.count-r.count),[s]);return s.length===0?null:e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Node Type Breakdown"}),e.jsx("div",{className:"overflow-hidden rounded-lg border border-gray-800",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-gray-900 text-xs uppercase tracking-wider text-gray-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 text-left",children:"Type"}),e.jsx("th",{className:"px-4 py-3 text-right",children:"Count"}),e.jsx("th",{className:"px-4 py-3 text-right",children:"%"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-800 bg-gray-950",children:n.map(r=>{const i=a>0?(r.count/a*100).toFixed(1):"0";return e.jsx(vi,{type:r.type,count:r.count,pct:i},r.type)})})]})})]})}),ki=c.memo(function({graphData:s}){return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Graph Metrics"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3",children:[e.jsx(D,{label:"Nodes",value:s.nodeCount}),e.jsx(D,{label:"Edges",value:s.edgeCount}),e.jsx(D,{label:"Node Types",value:s.nodesByType.length})]})]}),e.jsx(wi,{nodesByType:s.nodesByType,nodeCount:s.nodeCount})]})});function Si(){const{data:t,lastUpdated:s,stale:a,error:n}=De(Oe,"overview"),r=t?t.graph:null,i=r&&Zr(r)?r:null;return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Knowledge Graph"}),e.jsx(mt,{lastUpdated:s,stale:a,error:n})]}),!t&&!n&&e.jsx("p",{className:"text-sm text-gray-500",children:"Connecting to data stream…"}),r&&!i&&e.jsx(Ni,{reason:r.available?void 0:r.reason}),i&&e.jsx(ki,{graphData:i})]})}const Z=130,ae=30,Cs=180,Ci=44,re={top:40,right:24,bottom:24,left:24},Pe=re.left,Ae={high:"#ef4444",medium:"#f59e0b",low:"#71717a"};function Mi(t){return t>.7?"high":t>=.3?"medium":"low"}function Pt(t){return Math.max(.15,Math.min(1,t))}function Ti(t){if(t.layers.length===0)return null;const s=[],a=[],n={nodeId:t.sourceNodeId,name:t.sourceName,type:"source",probability:1,parentId:"",risk:"high",x:Pe,y:re.top};s.push(n);for(const l of t.layers){const o=Pe+l.depth*Cs;l.nodes.forEach((d,u)=>{const x={nodeId:d.nodeId,name:d.name,type:d.type,probability:d.probability,parentId:d.parentId,risk:Mi(d.probability),x:o,y:re.top+u*Ci};s.push(x),a.push({fromId:d.parentId,toId:d.nodeId})})}const r=Math.max(...s.map(l=>l.x+Z))+re.right,i=Math.max(...s.map(l=>l.y+ae))+re.bottom;return{nodes:s,sourceNode:n,edges:a,width:r,height:i}}function Ii({data:t}){const{summary:s}=t,a=[{label:"Total Affected",count:s.totalAffected,color:"#fafafa"},{label:"High Risk",count:s.highRisk,color:Ae.high},{label:"Medium Risk",count:s.mediumRisk,color:Ae.medium},{label:"Low Risk",count:s.lowRisk,color:Ae.low}];return e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-4",children:[a.map(n=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-full",style:{background:n.color}}),e.jsx("span",{className:"text-sm tabular-nums text-neutral-text",children:n.count}),e.jsx("span",{className:"text-xs text-neutral-muted",children:n.label})]},n.label)),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-xs text-neutral-muted",children:"Max Depth:"}),e.jsx("span",{className:"text-sm tabular-nums text-neutral-text",children:s.maxDepth})]})]})}function $i({data:t}){const s=Ti(t),[a,n]=c.useState(null);if(!s)return e.jsx(y.div,{initial:{opacity:0},animate:{opacity:1},className:"flex h-32 items-center justify-center rounded-2xl border border-neutral-border bg-neutral-bg/50 backdrop-blur-sm",children:e.jsx("p",{className:"text-sm text-neutral-muted",children:"No affected nodes detected"})});const r=new Map(s.nodes.map(l=>[l.nodeId,l])),i=t.layers.map(l=>l.depth);return e.jsxs("div",{className:"relative group",children:[e.jsx(Ii,{data:t}),e.jsx("div",{className:"overflow-x-auto rounded-2xl border border-neutral-border bg-neutral-bg/30 p-6 backdrop-blur-md",children:e.jsxs("svg",{width:s.width,height:s.height,className:"overflow-visible",children:[e.jsxs("defs",{children:[e.jsxs("filter",{id:"neon-glow",x:"-20%",y:"-20%",width:"140%",height:"140%",children:[e.jsx("feGaussianBlur",{stdDeviation:"2",result:"blur"}),e.jsx("feComposite",{in:"SourceGraphic",in2:"blur",operator:"over"})]}),e.jsx("marker",{id:"blast-arrow",markerWidth:"8",markerHeight:"8",refX:"6",refY:"3",orient:"auto",children:e.jsx("path",{d:"M0,0 L0,6 L8,3 z",fill:"#4f46e5"})})]}),e.jsx(y.text,{initial:{opacity:0},animate:{opacity:1},x:Pe+Z/2,y:re.top-14,textAnchor:"middle",className:"text-[10px] font-bold uppercase tracking-widest fill-neutral-muted",children:"Origin"}),i.map(l=>{const o=Pe+l*Cs;return e.jsxs(y.text,{initial:{opacity:0},animate:{opacity:1},transition:{delay:l*.1},x:o+Z/2,y:re.top-14,textAnchor:"middle",className:"text-[10px] font-bold uppercase tracking-widest fill-neutral-muted",children:["Layer ",l]},l)}),s.edges.map((l,o)=>{const d=r.get(l.fromId),u=r.get(l.toId);if(!d||!u)return null;const x=d.x+Z,f=d.y+ae/2,m=u.x,p=u.y+ae/2,h=a===l.fromId||a===l.toId;return e.jsx(y.line,{initial:{pathLength:0,opacity:0},animate:{pathLength:1,opacity:h?1:Pt(u.probability),stroke:h?"var(--color-primary-500)":"rgba(79, 70, 229, 0.2)",strokeWidth:h?2:1.5},transition:{duration:.4},x1:x,y1:f,x2:m-4,y2:p,markerEnd:"url(#blast-arrow)"},`${l.fromId}-${l.toId}`)}),s.nodes.map((l,o)=>e.jsxs(y.g,{initial:{opacity:0,scale:.9,x:l.x-10},animate:{opacity:a&&a!==l.nodeId?.3:Pt(l.probability),scale:a===l.nodeId?1.05:1,x:l.x},onMouseEnter:()=>n(l.nodeId),onMouseLeave:()=>n(null),transition:{duration:.2},className:"cursor-pointer",children:[e.jsx("rect",{x:0,y:l.y,width:Z,height:ae,rx:8,className:"fill-neutral-surface/80 stroke-neutral-border",strokeWidth:1}),e.jsx(y.rect,{x:0,y:l.y,width:Z,height:ae,rx:8,className:"fill-none",stroke:Ae[l.risk],strokeWidth:1.5,initial:{pathLength:0},animate:{pathLength:1},transition:{duration:1,delay:o*.05}}),e.jsx("text",{x:Z/2,y:l.y+ae/2,dominantBaseline:"middle",textAnchor:"middle",className:"text-[10px] font-bold tracking-tight fill-neutral-text pointer-events-none",children:l.name.length>16?l.name.slice(0,15)+"…":l.name}),e.jsx("text",{x:Z-6,y:l.y+ae-6,textAnchor:"end",className:"text-[8px] font-mono fill-neutral-muted pointer-events-none",children:l.type==="source"?"SRC":`${(l.probability*100).toFixed(0)}%`})]},l.nodeId))]})})]})}const Ai=[1,2,3,4,5],Ei=3,Ri=c.memo(function({loading:s,fetchError:a,anomalies:n,sortedAPs:r,sortedOutliers:i,selectedNodeId:l,onAnomalyClick:o}){return e.jsxs("div",{className:"lg:col-span-1",children:[s&&!n&&e.jsx("p",{className:"text-sm text-gray-500",children:"Loading anomalies..."}),a&&e.jsx("p",{className:"text-sm text-red-400",children:a}),n&&r.length===0&&i.length===0&&e.jsxs("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-6",children:[e.jsx("p",{className:"text-base font-medium text-gray-300",children:"No anomalies detected"}),e.jsx("p",{className:"mt-2 text-sm text-gray-500",children:'Run "harness scan" to build the knowledge graph, then restart the dashboard.'})]}),r.length>0&&e.jsxs("section",{className:"mb-6",children:[e.jsx("h2",{className:"mb-2 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Articulation Points"}),e.jsx("div",{className:"space-y-1",children:r.map(d=>e.jsxs("button",{onClick:()=>o(d.nodeId),className:["w-full rounded border px-3 py-2 text-left text-sm transition-colors",l===d.nodeId?"border-blue-700 bg-blue-950":"border-gray-800 bg-gray-900 hover:bg-gray-800"].join(" "),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"truncate font-medium text-gray-200",children:d.name}),e.jsxs("span",{className:"ml-2 text-xs tabular-nums text-gray-500",children:[d.dependentCount," deps"]})]}),e.jsxs("p",{className:"mt-0.5 text-xs text-gray-500",children:[d.componentsIfRemoved," components if removed"]})]},d.nodeId))})]}),i.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"mb-2 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Statistical Outliers"}),e.jsx("div",{className:"space-y-1",children:i.map(d=>e.jsxs("button",{onClick:()=>o(d.nodeId),className:["w-full rounded border px-3 py-2 text-left text-sm transition-colors",l===d.nodeId?"border-blue-700 bg-blue-950":"border-gray-800 bg-gray-900 hover:bg-gray-800"].join(" "),children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"truncate font-medium text-gray-200",children:d.name}),e.jsxs("span",{className:"ml-2 text-xs tabular-nums text-gray-500",children:["z=",d.zScore.toFixed(1)]})]}),e.jsxs("p",{className:"mt-0.5 text-xs text-gray-500",children:[d.metric,": ",d.value," (",d.type,")"]})]},d.nodeId))})]})]})}),Li=c.memo(function({selectedNodeId:s,blastRadiusState:a,blastRadiusError:n,brData:r,brIsData:i}){const l=i?r:null;return e.jsxs("div",{className:"lg:col-span-2",children:[!s&&a==="idle"&&e.jsx("div",{className:"flex h-64 items-center justify-center rounded-lg border border-gray-800 bg-gray-900",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Select a node or search to view blast radius"})}),a==="loading"&&e.jsx("div",{className:"flex h-64 items-center justify-center rounded-lg border border-gray-800 bg-gray-900",children:e.jsx("p",{className:"text-sm text-gray-500",children:"Computing blast radius..."})}),a==="error"&&n&&e.jsx("div",{className:"rounded-lg border border-red-800 bg-gray-900 p-6",children:e.jsx("p",{className:"text-sm text-red-400",children:n})}),a==="success"&&r&&!i&&e.jsx("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-6",children:e.jsx("p",{className:"text-sm text-gray-400",children:"error"in r?r.error:"No blast radius data"})}),a==="success"&&l&&e.jsxs("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-6",children:[e.jsxs("h3",{className:"mb-3 text-sm font-semibold text-gray-200",children:["Blast Radius: ",l.sourceName]}),e.jsx($i,{data:l})]})]})}),Di=c.memo(function({searchText:s,depth:a,onSearchTextChange:n,onDepthChange:r,onSubmit:i}){return e.jsxs("div",{className:"mb-6 flex items-center gap-4",children:[e.jsxs("form",{onSubmit:i,className:"flex flex-1 gap-2",children:[e.jsx("input",{type:"text",value:s,onChange:l=>n(l.target.value),placeholder:"Search node by name or path...",className:"flex-1 rounded border border-gray-700 bg-gray-900 px-3 py-1.5 text-sm text-gray-200 placeholder-gray-500 focus:border-gray-500 focus:outline-none"}),e.jsx("button",{type:"submit",className:"rounded bg-gray-800 px-3 py-1.5 text-xs font-medium text-gray-200 hover:bg-gray-700",children:"Search"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm text-gray-400",children:["Depth",e.jsx("select",{value:a,onChange:l=>r(Number(l.target.value)),className:"rounded border border-gray-700 bg-gray-900 px-2 py-1.5 text-sm text-gray-200",children:Ai.map(l=>e.jsx("option",{value:l,children:l},l))})]})]})});function Oi(){const[t,s]=c.useState(null),[a,n]=c.useState(!0),[r,i]=c.useState(null),l=c.useCallback(async()=>{try{const o=await fetch("/api/impact/anomalies");if(!o.ok){i(`HTTP ${o.status}`);return}const d=await o.json();s(d.data),i(null)}catch(o){i(o instanceof Error?o.message:"Network error")}finally{n(!1)}},[]);return c.useEffect(()=>{l()},[l]),{anomalies:t,loading:a,fetchError:r}}function Pi(t){const s=t?[...t.articulationPoints].sort((n,r)=>r.dependentCount-n.dependentCount):[],a=t?[...t.outliers].sort((n,r)=>r.zScore-n.zScore):[];return{sortedAPs:s,sortedOutliers:a}}function Fi(){var j;const{anomalies:t,loading:s,fetchError:a}=Oi(),[n,r]=c.useState(null),[i,l]=c.useState(""),[o,d]=c.useState(Ei),u=ks("/api/impact/blast-radius"),x=c.useCallback(N=>{r(N),u.run({nodeId:N,maxDepth:o})},[u,o]),f=c.useCallback(N=>{N.preventDefault();const v=i.trim();v&&x(v)},[i,x]),m=c.useCallback(N=>{l(""),x(N)},[x]),{sortedAPs:p,sortedOutliers:h}=c.useMemo(()=>Pi(t),[t]),g=(j=u.data)==null?void 0:j.data,b=!!g&&ai(g);return{anomalies:t,loading:s,fetchError:a,selectedNodeId:n,searchText:i,depth:o,setSearchText:l,setDepth:d,handleSearch:f,handleAnomalyClick:m,sortedAPs:p,sortedOutliers:h,blastRadius:u,brData:g,brIsData:b}}function _i(){const{anomalies:t,loading:s,fetchError:a,selectedNodeId:n,searchText:r,depth:i,setSearchText:l,setDepth:o,handleSearch:d,handleAnomalyClick:u,sortedAPs:x,sortedOutliers:f,blastRadius:m,brData:p,brIsData:h}=Fi();return e.jsxs("div",{children:[e.jsx("h1",{className:"mb-6 text-2xl font-bold",children:"Impact Explorer"}),e.jsx(Di,{searchText:r,depth:i,onSearchTextChange:l,onDepthChange:o,onSubmit:d}),e.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-3",children:[e.jsx(Ri,{loading:s,fetchError:a,anomalies:t,sortedAPs:x,sortedOutliers:f,selectedNodeId:n,onAnomalyClick:u}),e.jsx(Li,{selectedNodeId:n,blastRadiusState:m.state,blastRadiusError:m.error,brData:p,brIsData:h})]})]})}function Ms(t){return t==="improving"?"Improving":t==="declining"?"Degrading":"Stable"}function Qe(t){return t==="improving"?"green":t==="declining"?"red":"yellow"}function zi(t){return t==="improving"?"text-emerald-400":t==="declining"?"text-red-400":"text-yellow-400"}function Bi(t){return t==="improving"?"↓":t==="declining"?"↑":"→"}function Ts(t){return t===0?"0":`${t>0?"+":""}${t.toFixed(1)}`}function Hi(t){return t.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1)).join(" ")}const Wi=c.memo(function({name:s,trend:a}){return e.jsxs("tr",{className:"border-b border-gray-800 hover:bg-gray-800/40",children:[e.jsx("td",{className:"py-2 px-3 font-mono text-xs text-gray-200",children:Hi(s)}),e.jsx("td",{className:"py-2 px-3 text-right tabular-nums text-gray-200",children:a.current.toFixed(1)}),e.jsxs("td",{className:`py-2 px-3 text-right tabular-nums ${zi(a.direction)}`,children:[Bi(a.direction)," ",Ms(a.direction)]}),e.jsx("td",{className:"py-2 px-3 text-right tabular-nums text-gray-400",children:Ts(a.delta)}),e.jsx("td",{className:"py-2 px-3 text-right tabular-nums text-gray-500",children:a.previous.toFixed(1)})]})});function Gi({categories:t}){const s=c.useMemo(()=>Object.entries(t).sort((a,n)=>Math.abs(n[1].delta)-Math.abs(a[1].delta)),[t]);return s.length===0?e.jsx("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-6 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No category data yet. Capture architecture snapshots to see trends."})}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-gray-800 bg-gray-900",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-800 bg-gray-900/60",children:[e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Category"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Current"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Trend"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Delta"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Previous"})]})}),e.jsx("tbody",{children:s.map(([a,n])=>e.jsx(Wi,{name:a,trend:n},a))})]})})}async function Ui(){const t=await fetch("/api/decay-trends");if(!t.ok)throw new Error(`HTTP ${t.status}`);return(await t.json()).data}function qi(){const[t,s]=c.useState(null),[a,n]=c.useState(null),[r,i]=c.useState(!0),l=c.useCallback(async()=>{try{const d=await Ui();s(d),n(null)}catch(d){n(d instanceof Error?d.message:"Network error")}finally{i(!1)}},[]);c.useEffect(()=>{l()},[l]);const o=t&&t.snapshotCount===0;return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Decay Trends"}),t&&t.to&&e.jsxs("span",{className:"text-xs text-gray-500",children:[t.snapshotCount," snapshot",t.snapshotCount!==1?"s":""," analyzed",t.from&&` from ${t.from.slice(0,10)} to ${t.to.slice(0,10)}`]})]}),r&&!t&&e.jsx("p",{className:"text-sm text-gray-500",children:"Loading decay trends..."}),a&&e.jsx("p",{className:"text-sm text-red-400",children:a}),o&&e.jsx("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-6 text-center",children:e.jsxs("p",{className:"text-sm text-gray-500",children:["No architecture snapshots found. Run"," ",e.jsx("code",{className:"text-gray-400",children:"harness snapshot capture"})," to create the first snapshot."]})}),t&&!o&&e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Overview"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[e.jsx(D,{label:"Stability Score",value:t.stability.current,sub:"0-100 (higher is healthier)",accent:Qe(t.stability.direction)}),e.jsx(D,{label:"Trend Direction",value:Ms(t.stability.direction),accent:Qe(t.stability.direction)}),e.jsx(D,{label:"Score Delta",value:Ts(t.stability.delta),sub:`Previous: ${t.stability.previous}`,accent:Qe(t.stability.direction)}),e.jsx(D,{label:"Snapshots",value:t.snapshotCount})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Category Breakdown"}),e.jsx(Gi,{categories:t.categories})]})]})]})}function Yi(t){switch(t){case"full":return"Covered";case"code-only":return"Partial (code)";case"test-only":return"Partial (test)";case"none":return"Uncovered"}}function Vi(t){switch(t){case"full":return"text-emerald-400";case"code-only":case"test-only":return"text-yellow-400";case"none":return"text-red-400"}}function Ji(t){switch(t){case"full":return"bg-emerald-400";case"code-only":case"test-only":return"bg-yellow-400";case"none":return"bg-red-400"}}function Te(t){return t>=80?"green":t>=50?"yellow":"red"}const Xi=c.memo(function({req:s}){return e.jsxs("tr",{className:"border-b border-gray-800 hover:bg-gray-800/40",children:[e.jsxs("td",{className:"py-2 px-3",children:[e.jsx("div",{className:"font-mono text-xs text-gray-200",children:s.requirementName||s.requirementId}),s.featureName&&e.jsx("div",{className:"text-[10px] text-gray-500 mt-0.5",children:s.featureName})]}),e.jsx("td",{className:"py-2 px-3",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:`inline-block h-1.5 w-1.5 rounded-full ${Ji(s.status)}`}),e.jsx("span",{className:`text-xs font-medium ${Vi(s.status)}`,children:Yi(s.status)})]})}),e.jsx("td",{className:"py-2 px-3 text-right tabular-nums text-gray-200 text-sm",children:s.codeFileCount}),e.jsx("td",{className:"py-2 px-3 text-right tabular-nums text-gray-200 text-sm",children:s.testFileCount})]})});function Ki({requirements:t}){return t.length===0?e.jsx("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-6 text-center",children:e.jsxs("p",{className:"text-sm text-gray-500",children:["No requirements found in graph. Run"," ",e.jsx("code",{className:"rounded bg-gray-800 px-1 py-0.5 text-xs font-mono text-gray-300",children:"harness scan"})," ","to ingest spec requirements."]})}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-gray-800 bg-gray-900",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-800 bg-gray-900/60",children:[e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Requirement"}),e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Status"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Implementations"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Tests"})]})}),e.jsx("tbody",{children:t.map(s=>e.jsx(Xi,{req:s},s.requirementId))})]})})}async function Qi(){const t=await fetch("/api/traceability");if(!t.ok)throw new Error(`HTTP ${t.status}`);return(await t.json()).data}function Zi(){const[t,s]=c.useState(null),[a,n]=c.useState(null),[r,i]=c.useState(!0),[l,o]=c.useState(!1),d=c.useCallback(async()=>{try{const m=await Qi();m===null?o(!0):s(m),n(null)}catch(m){n(m instanceof Error?m.message:"Network error")}finally{i(!1)}},[]);c.useEffect(()=>{d()},[d]);const u=t?t.totals.fullyTraced:0,x=t?t.totals.withCode+t.totals.withTests-2*t.totals.fullyTraced:0,f=t?t.totals.untraceable:0;return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Traceability"}),t&&e.jsxs("span",{className:"text-xs text-gray-500",children:["Generated ",new Date(t.generatedAt).toLocaleString()]})]}),r&&!t&&e.jsx("p",{className:"text-sm text-gray-500",children:"Loading traceability data..."}),a&&e.jsx("p",{className:"text-sm text-red-400",children:a}),l&&!r&&e.jsx("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-8 text-center",children:e.jsxs("p",{className:"text-sm text-gray-400",children:["No traceability data available. Run"," ",e.jsx("code",{className:"rounded bg-gray-800 px-1.5 py-0.5 text-xs font-mono text-gray-300",children:"harness scan"})," ","to build the knowledge graph with requirement nodes from spec files."]})}),t&&e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Coverage Summary"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[e.jsx(D,{label:"Total Requirements",value:t.totals.total}),e.jsx(D,{label:"Covered",value:u,accent:"green",sub:`${t.overallCoverage}% coverage`}),e.jsx(D,{label:"Partial",value:x>0?x:t.totals.total-u-f,accent:"yellow"}),e.jsx(D,{label:"Uncovered",value:f,accent:f>0?"red":"green"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Overall Coverage"}),e.jsxs("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm text-gray-400",children:"Fully traced"}),e.jsxs("span",{className:`text-sm font-bold ${Te(t.overallCoverage)==="green"?"text-emerald-400":Te(t.overallCoverage)==="yellow"?"text-yellow-400":"text-red-400"}`,children:[t.overallCoverage,"%"]})]}),e.jsx("div",{className:"h-2 rounded-full bg-gray-800 overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full transition-all duration-500 ${Te(t.overallCoverage)==="green"?"bg-emerald-500":Te(t.overallCoverage)==="yellow"?"bg-yellow-500":"bg-red-500"}`,style:{width:`${t.overallCoverage}%`}})})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Requirements"}),e.jsx(Ki,{requirements:t.requirements})]})]})]})}function el(){const[t,s]=c.useState([]),[a,n]=c.useState(!0),[r,i]=c.useState(null);return c.useEffect(()=>{let l=!1;async function o(){try{const u=await fetch("/api/streams");if(!u.ok)throw new Error(`Failed to fetch sessions: ${u.status}`);const x=await u.json();l||(s(x),i(null))}catch(u){l||i(u instanceof Error?u.message:"Failed to load sessions")}finally{l||n(!1)}}o();const d=setInterval(()=>void o(),3e4);return()=>{l=!0,clearInterval(d)}},[]),{sessions:t,loading:a,error:r}}function tl(t){if(!t)return"never";const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString()}function Ft({status:t}){const s=t.detected.length>0?t.detected.join(", "):"none detected";return e.jsx("div",{role:"alert",className:"mb-6 rounded-lg border border-red-900/60 bg-red-950/40 px-4 py-3 text-sm",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"mt-0.5 inline-block h-2.5 w-2.5 flex-shrink-0 rounded-full bg-red-500"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-semibold text-red-300",children:"Local model unavailable"}),e.jsxs("p",{className:"mt-1 font-mono text-xs text-red-300/80",children:[t.backendName," — ",t.endpoint]}),e.jsx("p",{className:"mt-1 text-red-200",children:"No configured candidate is currently loaded on the local server. The intelligence pipeline and local agent dispatch are disabled until a candidate is loaded."}),e.jsxs("dl",{className:"mt-2 grid grid-cols-1 gap-x-6 gap-y-1 text-xs text-red-200 sm:grid-cols-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-red-400",children:"Configured:"}),e.jsx("dd",{className:"font-mono",children:t.configured.join(", ")||"(none)"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-red-400",children:"Detected:"}),e.jsx("dd",{className:"font-mono",children:s})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-red-400",children:"Last probe:"}),e.jsx("dd",{className:"font-mono",children:tl(t.lastProbeAt)})]}),t.lastError&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("dt",{className:"text-red-400",children:"Last error:"}),e.jsx("dd",{className:"font-mono",children:t.lastError})]})]})]})]})})}function K({title:t}){return e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:t})}function V(t){return t.toLocaleString()}function sl(t){const s=Is(),a=Math.max(0,Math.floor((s-new Date(t).getTime())/1e3));if(a<60)return`${a}s`;const n=Math.floor(a/60),r=a%60;return n<60?`${n}m ${r}s`:`${Math.floor(n/60)}h ${n%60}m`}function Is(){const[t,s]=c.useState(Date.now());return c.useEffect(()=>{const a=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(a)},[]),t}function al({phase:t}){const a={PreparingWorkspace:"bg-yellow-900/50 text-yellow-400",BuildingPrompt:"bg-yellow-900/50 text-yellow-400",LaunchingAgent:"bg-blue-900/50 text-blue-400",InitializingSession:"bg-blue-900/50 text-blue-400",StreamingTurn:"bg-emerald-900/50 text-emerald-400",Finishing:"bg-purple-900/50 text-purple-400",Succeeded:"bg-emerald-900/50 text-emerald-300",Failed:"bg-red-900/50 text-red-400",TimedOut:"bg-red-900/50 text-red-400",Stalled:"bg-orange-900/50 text-orange-400",CanceledByReconciliation:"bg-gray-800 text-gray-400"}[t]??"bg-gray-800 text-gray-400";return e.jsx("span",{className:`inline-block rounded px-2 py-0.5 text-xs font-medium ${a}`,children:t})}function nl({startedAt:t}){const s=sl(t);return e.jsx("span",{className:"tabular-nums text-gray-400",children:s})}function rl({snapshot:t}){const s=t.globalCooldownUntilMs!==null&&Date.now()<t.globalCooldownUntilMs,a=Date.now(),n=t.recentRequestTimestamps.filter(l=>a-l<6e4).length,r=t.recentInputTokens.filter(l=>a-l.timestamp<6e4).reduce((l,o)=>l+o.tokens,0),i=t.recentOutputTokens.filter(l=>a-l.timestamp<6e4).reduce((l,o)=>l+o.tokens,0);return e.jsxs("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-5",children:[e.jsx(K,{title:"Rate Limits"}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-400",children:"Status"}),e.jsx("span",{className:s?"font-semibold text-red-400":"text-emerald-400",children:s?"COOLDOWN":"OK"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-400",children:"Req/Min"}),e.jsxs("span",{className:"text-blue-400",children:[n," / ",t.maxRequestsPerMinute]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-400",children:"Req/Sec"}),e.jsxs("span",{className:"text-blue-400",children:[t.maxRequestsPerSecond," max"]})]}),t.maxInputTokensPerMinute>0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-400",children:"ITPM"}),e.jsxs("span",{className:"text-yellow-400",children:[V(r)," / ",V(t.maxInputTokensPerMinute)]})]}),t.maxOutputTokensPerMinute>0&&e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-400",children:"OTPM"}),e.jsxs("span",{className:"text-yellow-400",children:[V(i)," / ",V(t.maxOutputTokensPerMinute)]})]})]})]})}function il({snapshot:t}){return e.jsxs("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-5",children:[e.jsx(K,{title:"Concurrency"}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-400",children:"Active"}),e.jsxs("span",{className:t.running.length>0?"text-emerald-400":"text-gray-500",children:[t.running.length," / ",t.maxConcurrentAgents]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-400",children:"Claimed"}),e.jsx("span",{className:"text-cyan-400",children:t.claimed.length})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-400",children:"Retry Queue"}),e.jsx("span",{className:"text-gray-300",children:t.retryAttempts.length})]})]})]})}function ll({snapshot:t}){return e.jsxs("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-5",children:[e.jsx(K,{title:"Token Usage"}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-400",children:"Input"}),e.jsx("span",{className:"text-yellow-400",children:V(t.tokenTotals.inputTokens)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-400",children:"Output"}),e.jsx("span",{className:"text-yellow-400",children:V(t.tokenTotals.outputTokens)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-400",children:"Total"}),e.jsx("span",{className:"text-yellow-400",children:V(t.tokenTotals.totalTokens)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-400",children:"Time Running"}),e.jsxs("span",{className:"text-blue-400",children:[Math.round(t.tokenTotals.secondsRunning),"s"]})]})]})]})}function ol({activity:t}){if(t.phase==="idle")return null;const s={fetching:"Fetching",analyzing:"Analyzing",dispatching:"Dispatching"},a={fetching:"text-blue-400",analyzing:"text-violet-400",dispatching:"text-emerald-400"};return e.jsxs("div",{className:"mb-6 rounded-lg border border-violet-800/50 bg-violet-950/20 px-4 py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"relative flex h-2.5 w-2.5",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-violet-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-violet-500"})]}),e.jsx("span",{className:`text-sm font-medium ${a[t.phase]??"text-gray-400"}`,children:s[t.phase]??t.phase}),t.detail&&e.jsx("span",{className:"truncate text-sm text-gray-400",children:t.detail}),t.progress&&e.jsxs("span",{className:"ml-auto text-xs tabular-nums text-gray-500",children:[t.progress.current,"/",t.progress.total]})]}),t.progress&&e.jsx("div",{className:"mt-2 h-1 overflow-hidden rounded-full bg-gray-800",children:e.jsx("div",{className:"h-full rounded-full bg-violet-500 transition-all duration-300",style:{width:`${t.progress.current/t.progress.total*100}%`}})})]})}function cl({agent:t,blocks:s,onViewStream:a}){var l,o,d,u,x,f,m,p,h;const[n,r]=c.useState(!1),i=s.slice(-5);return e.jsxs("div",{className:"rounded-lg border border-gray-800 bg-gray-900/60",children:[e.jsxs("button",{type:"button",onClick:()=>r(!n),className:"flex w-full items-start gap-3 px-4 py-3 text-left transition-colors hover:bg-gray-800/40",children:[e.jsx("div",{className:"mt-1 flex-shrink-0",children:t.phase==="StreamingTurn"?e.jsxs("span",{className:"relative flex h-2.5 w-2.5",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-emerald-500"})]}):e.jsx("span",{className:"inline-flex h-2.5 w-2.5 rounded-full bg-yellow-500"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate font-medium text-white",children:((l=t.issue)==null?void 0:l.title)??t.identifier}),e.jsx(al,{phase:t.phase})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-3 text-xs text-gray-500",children:[e.jsx("span",{className:"font-mono",children:t.identifier}),e.jsx("span",{className:"text-gray-600",children:"|"}),e.jsx("span",{className:"text-blue-400",children:((o=t.session)==null?void 0:o.backendName)??"pending"}),e.jsx("span",{className:"text-gray-600",children:"|"}),e.jsx(nl,{startedAt:t.startedAt}),t.session&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-gray-600",children:"|"}),e.jsxs("span",{children:["T",t.session.turnCount," · ",V(t.session.totalTokens)," tok"]})]})]}),((d=t.session)==null?void 0:d.lastMessage)&&e.jsx("p",{className:"mt-1.5 truncate text-xs text-gray-400",children:t.session.lastMessage})]}),e.jsx("span",{className:"mt-1 flex-shrink-0 text-gray-600",children:n?"▲":"▼"})]}),n&&e.jsxs("div",{className:"border-t border-gray-800 px-4 py-3 text-sm",children:[(u=t.issue)!=null&&u.description?e.jsxs("div",{className:"mb-3",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Description"}),e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-gray-300",children:t.issue.description})]}):e.jsx("p",{className:"mb-3 text-xs italic text-gray-600",children:"No description available."}),e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-1 text-xs",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-500",children:"Input Tokens"}),e.jsx("span",{className:"text-yellow-400",children:V(((x=t.session)==null?void 0:x.inputTokens)??0)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-500",children:"Output Tokens"}),e.jsx("span",{className:"text-yellow-400",children:V(((f=t.session)==null?void 0:f.outputTokens)??0)})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-500",children:"Backend"}),e.jsx("span",{className:"text-blue-400",children:((m=t.session)==null?void 0:m.backendName)??"-"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-gray-500",children:"Turns"}),e.jsx("span",{className:"text-gray-300",children:((p=t.session)==null?void 0:p.turnCount)??0})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-widest text-gray-500",children:i.length>0?"Live Activity":"Latest Activity"}),e.jsx("button",{type:"button",onClick:g=>{g.stopPropagation(),a()},className:"text-xs font-medium text-blue-400 transition-colors hover:text-blue-300",children:"View Full Stream"})]}),i.length>0?e.jsx("div",{className:"mt-2 max-h-48 overflow-hidden rounded-lg border border-gray-800 bg-gray-950/60 px-3 py-2 text-xs",children:e.jsx(Ns,{blocks:i,isStreaming:t.phase==="StreamingTurn"})}):(h=t.session)!=null&&h.lastMessage?e.jsx("p",{className:"mt-1 whitespace-pre-wrap text-gray-300",children:t.session.lastMessage}):e.jsx("p",{className:"mt-2 text-xs italic text-gray-600",children:"No activity yet."})]})]})]})}function dl({agents:t,agentEvents:s,onViewStream:a}){return t.length===0?e.jsx("p",{className:"text-sm italic text-gray-500",children:"No active agents."}):e.jsx("div",{className:"space-y-2",children:t.map(n=>e.jsx(cl,{agent:n,blocks:s[n.issueId]??[],onViewStream:()=>a(n)},n.issueId))})}function xl({snapshot:t}){const s=Is();if(t.retryAttempts.length===0)return null;const a=[...t.retryAttempts].sort((n,r)=>n[1].dueAtMs-r[1].dueAtMs);return e.jsxs("section",{className:"mt-6",children:[e.jsx(K,{title:"Retry Queue"}),e.jsx("div",{className:"space-y-1",children:a.map(([,n])=>{const r=Math.max(0,Math.ceil((n.dueAtMs-s)/1e3));return e.jsxs("div",{className:"flex items-center justify-between rounded border border-gray-800 bg-gray-900/40 px-3 py-2 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`inline-flex h-2 w-2 rounded-full ${r>0?"bg-orange-500":"bg-orange-400 animate-pulse"}`}),e.jsx("span",{className:"font-mono text-gray-300",children:n.identifier}),e.jsxs("span",{className:"text-gray-500",children:["attempt ",n.attempt]})]}),e.jsx("span",{className:`text-xs ${r>0?"text-gray-500":"text-orange-400 font-medium"}`,children:r>0?`retries in ${r}s`:"due now"})]},n.issueId)})})]})}function ul(t){const s=Math.floor(t/1e3);if(s<60)return`${s}s`;const a=Math.floor(s/60),n=s%60;return a<60?`${a}m ${n}s`:`${Math.floor(a/60)}h ${a%60}m`}function ml(t){const s=Date.now()-new Date(t).getTime(),a=Math.floor(s/6e4);if(a<1)return"just now";if(a<60)return`${a}m ago`;const n=Math.floor(a/60);return n<24?`${n}h ago`:`${Math.floor(n/24)}d ago`}function hl({outcome:t}){if(!t)return e.jsx("span",{className:"text-xs text-gray-600",children:"in progress"});const a={normal:"bg-emerald-900/50 text-emerald-400",error:"bg-red-900/50 text-red-400"}[t]??"bg-gray-800 text-gray-400";return e.jsx("span",{className:`inline-block rounded px-2 py-0.5 text-xs font-medium ${a}`,children:t})}function pl({session:t,onViewStream:s}){const a=t.attempts.at(-1),n=a==null?void 0:a.startedAt,r=(a==null?void 0:a.outcome)??null,i=a==null?void 0:a.stats;return e.jsxs("button",{type:"button",onClick:()=>s(t.issueId),className:"flex w-full items-center gap-3 rounded-lg border border-gray-800 bg-gray-900/60 px-4 py-3 text-left transition-colors hover:bg-gray-800/40",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"truncate font-medium text-white",children:t.title??t.identifier}),e.jsx(hl,{outcome:r}),t.pr&&e.jsxs("span",{className:"text-xs text-blue-400",children:["PR #",t.pr.number]})]}),e.jsxs("div",{className:"mt-1 flex items-center gap-3 text-xs text-gray-500",children:[n&&e.jsx("span",{children:ml(n)}),i&&i.durationMs>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-gray-600",children:"|"}),e.jsx("span",{children:ul(i.durationMs)})]}),i&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-gray-600",children:"|"}),e.jsxs("span",{children:["T",i.turnCount," · ",V(i.inputTokens+i.outputTokens)," ","tok"]})]}),t.attempts.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-gray-600",children:"|"}),e.jsxs("span",{children:[t.attempts.length," attempts"]})]})]})]}),e.jsx("span",{className:"flex-shrink-0 text-gray-600",children:"›"})]})}function _t({onViewStream:t}){const{sessions:s,loading:a,error:n}=el();return a?e.jsxs("section",{className:"mt-6",children:[e.jsx(K,{title:"Recent Sessions"}),e.jsx("p",{className:"text-sm text-gray-500",children:"Loading sessions..."})]}):n?e.jsxs("section",{className:"mt-6",children:[e.jsx(K,{title:"Recent Sessions"}),e.jsx("p",{className:"text-sm text-red-400",children:n})]}):s.length===0?e.jsxs("section",{className:"mt-6",children:[e.jsx(K,{title:"Recent Sessions"}),e.jsx("p",{className:"text-sm italic text-gray-500",children:"No recorded sessions yet."})]}):e.jsxs("section",{className:"mt-6",children:[e.jsx(K,{title:"Recent Sessions"}),e.jsx("div",{className:"space-y-2",children:s.map(r=>e.jsx(pl,{session:r,onViewStream:t},r.issueId))})]})}function fl(){const{snapshot:t,agentEvents:s,connected:a,localModelStatuses:n}=ke(),r=X(),i=c.useCallback(d=>{var f,m,p;const u=E.getState();for(const h of u.threads.values())if(h.type==="agent"&&h.meta.issueId===d.issueId){u.setActiveThread(h.id),r(`/t/${h.id}`);return}const x=u.createThread("agent",{issueId:d.issueId,identifier:d.identifier,phase:d.phase,issueTitle:((f=d.issue)==null?void 0:f.title)??d.identifier,issueDescription:((m=d.issue)==null?void 0:m.description)??null,startedAt:d.startedAt,backendName:((p=d.session)==null?void 0:p.backendName)??null});u.setActiveThread(x.id),r(`/t/${x.id}`)},[r]),l=c.useCallback(d=>{const u=E.getState();for(const f of u.threads.values())if(f.type==="agent"&&f.meta.issueId===d){u.setActiveThread(f.id),r(`/t/${f.id}`);return}const x=u.createThread("agent",{issueId:d,identifier:d,phase:"completed",issueTitle:d,issueDescription:null,startedAt:new Date().toISOString(),backendName:null});u.updateThread(x.id,{status:"completed"}),u.setActiveThread(x.id),r(`/t/${x.id}`)},[r]);if(!t)return e.jsxs("div",{children:[n.filter(d=>!d.available).map(d=>e.jsx(Ft,{status:d},d.backendName)),e.jsx("h1",{className:"mb-6 text-2xl font-bold",children:"Agent Monitor"}),e.jsx("p",{className:"text-sm text-gray-500",children:a?"Waiting for first state update...":"Connecting to orchestrator..."}),e.jsx(_t,{onViewStream:l})]});const o=t.running.map(([,d])=>d);return e.jsxs("div",{children:[n.filter(d=>!d.available).map(d=>e.jsx(Ft,{status:d},d.backendName)),e.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Agent Monitor"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:["inline-block h-2 w-2 rounded-full",a?"bg-emerald-500":"bg-yellow-400"].join(" ")}),e.jsx("span",{className:a?"text-gray-500":"text-yellow-400",children:a?"Live":"Reconnecting..."})]})]}),e.jsxs("div",{className:"mb-8 grid grid-cols-1 gap-4 md:grid-cols-3",children:[e.jsx(rl,{snapshot:t}),e.jsx(il,{snapshot:t}),e.jsx(ll,{snapshot:t})]}),t.tickActivity&&e.jsx(ol,{activity:t.tickActivity}),e.jsxs("section",{children:[e.jsx(K,{title:"Active Agents"}),e.jsx(dl,{agents:o,agentEvents:s,onViewStream:i})]}),e.jsx(xl,{snapshot:t}),e.jsx(_t,{onViewStream:l})]})}function gl(t){return t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${(t/6e4).toFixed(1)}m`}function yl(t){return t==="success"||t==="no-issues"?"text-emerald-400":t==="failed"?"text-red-400":"text-yellow-400"}function ve(t){return t?new Date(t).toLocaleString():"—"}const bl=c.memo(function({entry:s}){const a=s.task==="compound-candidates"&&(s.findings??0)>0;return e.jsxs("tr",{className:"border-b border-gray-800 hover:bg-gray-800/40",children:[e.jsxs("td",{className:"py-2 px-3 font-mono text-xs text-gray-200",children:[s.task,a&&e.jsxs("span",{className:"ml-2 inline-block rounded bg-amber-500/20 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-amber-300",title:"Undocumented learnings detected this run",children:[s.findings," candidates"]})]}),e.jsx("td",{className:`py-2 px-3 text-xs font-semibold uppercase ${yl(s.status)}`,children:s.status}),e.jsx("td",{className:"py-2 px-3 text-xs text-gray-400",children:ve(s.startedAt)}),e.jsx("td",{className:"py-2 px-3 text-right tabular-nums text-gray-400",children:gl(s.durationMs)})]})});function jl({entries:t}){return t.length===0?e.jsx("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-6 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No maintenance history yet. Runs will appear here after the first execution."})}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-gray-800 bg-gray-900",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-800 bg-gray-900/60",children:[e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Task"}),e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Status"}),e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Started At"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Duration"})]})}),e.jsx("tbody",{children:t.map((s,a)=>e.jsx(bl,{entry:s},`${s.task}-${s.startedAt}-${a}`))})]})})}function Nl({rows:t,inFlight:s,onRunNow:a}){return t.length===0?e.jsx("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-6 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No scheduled tasks."})}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-gray-800 bg-gray-900",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-800 bg-gray-900/60",children:[e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Task ID"}),e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Type"}),e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Next Run"}),e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Last Run"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Action"})]})}),e.jsx("tbody",{children:t.map(n=>{const r=s.has(n.taskId);return e.jsxs("tr",{className:"border-b border-gray-800 hover:bg-gray-800/40",children:[e.jsx("td",{className:"py-2 px-3 font-mono text-xs text-gray-200",children:n.taskId}),e.jsx("td",{className:"py-2 px-3 text-xs text-gray-400",children:n.type??"—"}),e.jsx("td",{className:"py-2 px-3 text-xs text-gray-400",children:ve(n.nextRun)}),e.jsx("td",{className:"py-2 px-3 text-xs text-gray-400",children:n.lastRun?ve(n.lastRun.startedAt):"—"}),e.jsx("td",{className:"py-2 px-3 text-right",children:e.jsx("button",{"data-task-id":n.taskId,onClick:()=>a(n.taskId),disabled:r,className:"rounded-lg border border-white/10 bg-white/5 px-3 py-1 text-xs font-semibold uppercase tracking-wider text-gray-200 transition-all hover:bg-white/10 hover:text-white disabled:opacity-50 disabled:cursor-not-allowed",children:r?"Running...":"Run Now"})})]},n.taskId)})})]})})}async function vl(){const t=await fetch("/api/maintenance/status");if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.json()}async function wl(){const t=await fetch("/api/maintenance/history");if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.json()}class $s extends Error{constructor(){super("Schedule endpoint not implemented (404)"),this.name="ScheduleNotImplementedError"}}async function kl(){const t=await fetch("/api/maintenance/schedule");if(!t.ok)throw t.status===404?new $s:new Error(`HTTP ${t.status}`);return await t.json()}async function Sl(t){const s=await fetch("/api/maintenance/trigger",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({taskId:t})});if(!s.ok)throw new Error(`HTTP ${s.status}`)}function Cl(){const[t,s]=c.useState(null),[a,n]=c.useState(null),[r,i]=c.useState(null),[l,o]=c.useState(null),[d,u]=c.useState(new Set),[x,f]=c.useState(null),[m,p]=c.useState(!0),[h,g]=c.useState(null),{maintenanceEvent:b,connected:j}=ke(),N=c.useCallback(async()=>{try{const[T,w]=await Promise.all([vl(),wl()]);s(T),n(w),f(null)}catch(T){const w=T instanceof Error?T.message:"Network error";w.includes("404")||w.includes("502")?f("Orchestrator not running. Start with: harness orchestrator run"):f(w)}finally{p(!1)}try{const T=await kl();i(T),o(null)}catch(T){if(T instanceof $s)i([]),o(null);else{const w=T instanceof Error?T.message:"Network error";o(`Failed to load schedule: ${w}`)}}},[]);c.useEffect(()=>{N()},[N]),c.useEffect(()=>{b&&N()},[b,N]),c.useEffect(()=>{if(!b)return;const T=b;T.type==="maintenance:started"?u(w=>{const k=new Set(w);return k.add(T.data.taskId),k}):(T.type==="maintenance:completed"||T.type==="maintenance:error")&&u(w=>{const k=new Set(w);return k.delete(T.data.taskId),k})},[b]),c.useEffect(()=>{if(j)return;let T=!1;const w=()=>{(async()=>{var $;try{const M=await fetch("/api/maintenance/status");if(!M.ok)return;const L=await M.json();if(T)return;const O=(($=L==null?void 0:L.activeRun)==null?void 0:$.taskId)??null;u(R=>{const G=new Set;return O&&G.add(O),R.size===G.size&&[...R].every(Y=>G.has(Y))?R:G})}catch{}})()},k=setInterval(w,5e3);return w(),()=>{T=!0,clearInterval(k)}},[j]);const v=c.useCallback(T=>{u(w=>{const k=new Set(w);return k.add(T),k}),Sl(T).catch(w=>{f(w instanceof Error?w.message:`Failed to trigger ${T}`),u(k=>{const $=new Set(k);return $.delete(T),$})})},[]),S=[...d];return e.jsxs("div",{children:[e.jsx("div",{className:"mb-6 flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Maintenance"}),e.jsx("span",{className:`inline-block h-2 w-2 rounded-full ${j?"bg-emerald-400":"bg-gray-600"}`,title:j?"WebSocket connected":"WebSocket disconnected"})]})}),S.length>0&&e.jsxs("div",{className:"mb-4 flex items-center gap-2 rounded-lg border border-blue-500/30 bg-blue-500/10 px-4 py-2",children:[e.jsx("span",{className:"inline-block h-2 w-2 animate-pulse rounded-full bg-blue-400"}),e.jsx("span",{className:"text-sm text-blue-300",children:S.length===1?e.jsxs(e.Fragment,{children:["Running: ",e.jsx("span",{className:"font-mono font-semibold",children:S[0]})]}):e.jsxs(e.Fragment,{children:["Running ",S.length," tasks:"," ",e.jsx("span",{className:"font-mono font-semibold",children:S.join(", ")})]})})]}),(b==null?void 0:b.type)==="maintenance:error"&&e.jsx("div",{className:"mb-4 rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-2",children:e.jsxs("span",{className:"text-sm text-red-300",children:["Task ",e.jsx("span",{className:"font-mono font-semibold",children:b.data.taskId})," ","failed",b.data.error?`: ${b.data.error}`:""]})}),(b==null?void 0:b.type)==="maintenance:baseref_fallback"&&!((h==null?void 0:h.ref)===b.data.ref&&(h==null?void 0:h.repoRoot)===b.data.repoRoot)&&e.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3 rounded-lg border border-amber-500/30 bg-amber-500/10 px-4 py-2",children:[e.jsxs("span",{className:"text-sm text-amber-300",children:["Worktree base-ref fell back to local"," ",e.jsx("span",{className:"font-mono font-semibold",children:b.data.ref})," (repo:"," ",e.jsx("span",{className:"font-mono",children:b.data.repoRoot}),"). Origin may be misconfigured or unreachable."]}),e.jsx("button",{type:"button","aria-label":"Dismiss baseref fallback warning",onClick:()=>{g({ref:b.data.ref,repoRoot:b.data.repoRoot})},className:"shrink-0 rounded p-0.5 text-amber-300/80 transition-colors hover:bg-amber-500/20 hover:text-amber-200",children:e.jsx("span",{"aria-hidden":"true",className:"text-base leading-none",children:"×"})})]}),m&&!t&&e.jsx("p",{className:"text-sm text-gray-500",children:"Loading maintenance status..."}),x&&e.jsx("p",{className:"text-sm text-red-400",children:x}),t&&a&&e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Scheduler Status"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3",children:[e.jsx(D,{label:"Scheduled Tasks",value:t.scheduledTasks}),e.jsx(D,{label:"Last Run",value:ve(t.lastRunAt)}),e.jsx(D,{label:"Next Run",value:ve(t.nextRunAt)})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Schedule"}),l&&e.jsx("div",{className:"mb-3 rounded-lg border border-red-500/30 bg-red-500/10 px-4 py-2",children:e.jsx("span",{className:"text-sm text-red-300",children:l})}),r?e.jsx(Nl,{rows:r,inFlight:d,onRunNow:v}):l?null:e.jsx("p",{className:"text-sm text-gray-500",children:"Loading schedule..."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Run History"}),e.jsx(jl,{entries:a})]})]})]})}function Ml(t){if(t<1e3)return`${Math.round(t)}ms`;const s=Math.floor(t/1e3);if(s<60)return`${s}s`;const a=Math.floor(s/60),n=s%60;return a<60?`${a}m ${n}s`:`${Math.floor(a/60)}h ${a%60}m`}function Tl(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function Il(t){const s=Date.now()-new Date(t).getTime(),a=Math.floor(s/6e4);if(a<1)return"just now";if(a<60)return`${a}m ago`;const n=Math.floor(a/60);return n<24?`${n}h ago`:`${Math.floor(n/24)}d ago`}function $l(t){return new Date(t).toLocaleString()}async function Al(){const t=await fetch("/api/streams");if(!t.ok)throw new Error(`HTTP ${t.status}`);return await t.json()}const El=c.memo(function({outcome:s}){if(!s)return e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded px-2 py-0.5 text-xs font-medium bg-blue-900/50 text-blue-400",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full bg-blue-400 animate-pulse"}),"running"]});const n={normal:"bg-emerald-900/50 text-emerald-400",error:"bg-red-900/50 text-red-400",timeout:"bg-orange-900/50 text-orange-400"}[s]??"bg-gray-800 text-gray-400";return e.jsx("span",{className:`inline-block rounded px-2 py-0.5 text-xs font-medium ${n}`,children:s})});function Rl({title:t}){return e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:t})}const Ll=c.memo(function({session:s,onSelect:a}){const n=s.attempts.at(-1),r=n==null?void 0:n.startedAt,i=(n==null?void 0:n.outcome)??null,l=n==null?void 0:n.stats,o=l?l.turnCount:0,d=l?l.inputTokens+l.outputTokens:0;return e.jsxs("tr",{onClick:a,className:"border-b border-gray-800 cursor-pointer transition-colors hover:bg-gray-800/40",children:[e.jsx("td",{className:"py-3 px-3 text-sm text-white truncate max-w-[260px]",children:s.title??s.identifier}),e.jsx("td",{className:"py-3 px-3 font-mono text-xs text-gray-400 max-w-[180px] truncate",children:s.identifier}),e.jsx("td",{className:"py-3 px-3",children:e.jsx(El,{outcome:i})}),e.jsx("td",{className:"py-3 px-3 text-xs text-gray-400",children:r?$l(r):"-"}),e.jsx("td",{className:"py-3 px-3 text-right tabular-nums text-gray-400 text-xs",children:r?Il(r):"-"}),e.jsxs("td",{className:"py-3 px-3 text-right tabular-nums text-gray-300 text-xs",children:[o," turns"]}),e.jsx("td",{className:"py-3 px-3 text-right tabular-nums text-yellow-400 text-xs",children:Tl(d)}),e.jsx("td",{className:"py-3 px-3 text-right tabular-nums text-gray-400 text-xs",children:l&&l.durationMs>0?Ml(l.durationMs):"-"}),e.jsxs("td",{className:"py-3 px-3 text-right text-gray-500 text-xs",children:[s.attempts.length>1?`${s.attempts.length} attempts`:"",s.pr?e.jsxs("span",{className:"ml-2 text-blue-400",children:["PR #",s.pr.number]}):null]})]})});function Dl(t){const s=E.getState();for(const i of s.threads.values())if(i.type==="agent"&&i.meta.issueId===t.issueId)return i.id;const a=t.attempts.at(-1),n=a!=null&&!a.endedAt,r=s.createThread("agent",{issueId:t.issueId,identifier:t.identifier,phase:n?"running":"completed",issueTitle:t.title??t.identifier,issueDescription:null,startedAt:(a==null?void 0:a.startedAt)??new Date().toISOString(),backendName:null});return n||s.updateThread(r.id,{status:"completed"}),r.id}function Ol(){const t=X(),[s,a]=c.useState([]),[n,r]=c.useState(null),[i,l]=c.useState(!0),o=c.useCallback(async()=>{try{const u=await Al();a(u),r(null)}catch(u){const x=u instanceof Error?u.message:"Network error";x.includes("404")||x.includes("502")?r("Orchestrator not running. Start with: harness orchestrator run"):r(x)}finally{l(!1)}},[]);c.useEffect(()=>{o();const u=setInterval(()=>void o(),3e4);return()=>clearInterval(u)},[o]);const d=c.useCallback(u=>{const x=Dl(u);E.getState().setActiveThread(x),t(`/t/${x}`)},[t]);return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Streams"}),e.jsxs("div",{className:"flex items-center gap-4",children:[s.length>0&&e.jsxs("span",{className:"text-xs text-gray-500",children:[s.length," recorded session",s.length!==1?"s":""]}),e.jsx("button",{type:"button",onClick:()=>{l(!0),o()},className:"rounded-lg border border-gray-700 bg-gray-800/60 px-3 py-1.5 text-xs font-medium text-gray-300 transition-colors hover:bg-gray-700 hover:text-white",children:"Refresh"})]})]}),i&&s.length===0&&e.jsx("p",{className:"text-sm text-gray-500",children:"Loading streams..."}),n&&e.jsx("p",{className:"text-sm text-red-400",children:n}),!i&&!n&&s.length===0&&e.jsx("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-6 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No recorded streams yet. Sessions will appear here after agents run."})}),s.length>0&&e.jsxs("section",{children:[e.jsx(Rl,{title:"Recorded Sessions"}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-gray-800 bg-gray-900",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-800 bg-gray-900/60",children:[e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Title"}),e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Identifier"}),e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Status"}),e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Started At"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Age"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Turns"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Tokens"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Duration"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Info"})]})}),e.jsx("tbody",{children:s.map(u=>e.jsx(Ll,{session:u,onSelect:()=>d(u)},u.issueId))})]})})]})]})}const ee={done:"#10b981","in-progress":"#3b82f6",planned:"#6b7280",blocked:"#ef4444",backlog:"#374151","needs-human":"#f59e0b"},xe=20,Ze=8,Ie=140,ue={top:12,right:24,bottom:12,left:8};function Pl({milestones:t}){const s=t.filter(d=>!d.isBacklog);if(s.length===0)return null;const a=Math.max(...s.map(d=>d.total),1),n=480,r=n-Ie,i=ue.top+s.length*(xe+Ze)-Ze+ue.bottom;function l(d){return Ie+d/a*r}function o(d,u){const x=[{value:d.done,color:ee.done},{value:d.inProgress,color:ee["in-progress"]},{value:d.blocked,color:ee.blocked},{value:d.needsHuman,color:ee["needs-human"]},{value:d.planned+d.backlog,color:ee.planned}];let f=0;return x.map(({value:m,color:p},h)=>{if(m===0)return null;const g=l(f),b=m/a*r;return f+=m,e.jsx("rect",{x:g,y:u,width:b,height:xe,fill:p},h)})}return e.jsxs("div",{children:[e.jsx("p",{className:"mb-2 text-xs text-neutral-muted",children:"Per-milestone progress (done / in-progress / blocked / remaining)"}),e.jsx("svg",{width:n+ue.left+ue.right,height:i,className:"overflow-visible",children:e.jsx("g",{transform:`translate(${ue.left},${ue.top})`,children:s.map((d,u)=>{const x=u*(xe+Ze);return e.jsxs("g",{children:[e.jsx("text",{x:Ie-8,y:x+xe/2,dominantBaseline:"middle",textAnchor:"end",fontSize:11,fill:"#71717a",children:d.name.length>18?d.name.slice(0,17)+"…":d.name}),e.jsx("rect",{x:Ie,y:x,width:r,height:xe,fill:"#18181b",rx:3}),o(d,x),e.jsxs("text",{x:l(d.total)+4,y:x+xe/2,dominantBaseline:"middle",fontSize:10,fill:"#71717a",children:[d.done,"/",d.total]})]},d.name)})})}),e.jsx("div",{className:"mt-2 flex flex-wrap gap-4",children:Object.entries(ee).map(([d,u])=>e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"inline-block h-2.5 w-2.5 rounded-sm",style:{background:u}}),e.jsx("span",{className:"text-xs capitalize text-neutral-muted",children:d.replace("-"," ")})]},d))})]})}const be=140,me=32,Fl=180,_l=56,Fe=24;function zl(t){const s=[],a=new Set(t.map(m=>m.name)),n=new Map;for(const m of t)n.set(m.name,[]);for(const m of t)for(const p of m.blockedBy)a.has(p)&&(s.push([p,m.name]),n.get(p).push(m.name));const r=new Map;for(const m of t)r.set(m.name,0);for(const[,m]of s)r.set(m,(r.get(m)??0)+1);const i=new Map,l=[];for(const m of t)(r.get(m.name)??0)===0&&(l.push(m.name),i.set(m.name,0));let o=0;for(;o<l.length;){const m=l[o++],p=i.get(m)??0;for(const h of n.get(m)){const g=(r.get(h)??1)-1;r.set(h,g),i.set(h,Math.max(i.get(h)??0,p+1)),g===0&&l.push(h)}}const d=new Set(l),u=t.filter(m=>!d.has(m.name)).map(m=>m.name);if(u.length>0){const m=Math.max(0,...Array.from(i.values()));for(const p of u)i.set(p,m+1)}const x=new Map;return{nodes:t.map(m=>{const p=i.get(m.name)??0,h=x.get(p)??0;return x.set(p,h+1),{id:m.name,x:Fe+p*Fl,y:Fe+h*_l,status:m.status}}),edges:s,cycleNodes:u}}function Bl({features:t}){const s=new Set,a=new Set;for(const x of t)for(const f of x.blockedBy)s.add(f),a.add(x.name);const n=t.filter(x=>s.has(x.name)||a.has(x.name));if(n.length===0)return null;const{nodes:r,edges:i,cycleNodes:l}=zl(n),o=new Map(r.map(x=>[x.id,x])),d=Math.max(...r.map(x=>x.x+be))+Fe,u=Math.max(...r.map(x=>x.y+me))+Fe;return e.jsxs("div",{className:"relative group",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-widest text-neutral-muted",children:"Relationship Topology"}),l.length>0&&e.jsxs("span",{className:"rounded bg-red-500/10 px-2 py-0.5 text-[10px] font-bold text-red-400 border border-red-500/20 animate-pulse",children:["Cycles Detected: ",l.length]})]}),e.jsx("div",{className:"overflow-x-auto rounded-2xl border border-neutral-border bg-neutral-bg/30 p-6 backdrop-blur-md",children:e.jsxs("svg",{width:d,height:u,className:"overflow-visible",children:[e.jsxs("defs",{children:[e.jsxs("filter",{id:"neon-glow-small",x:"-20%",y:"-20%",width:"140%",height:"140%",children:[e.jsx("feGaussianBlur",{stdDeviation:"1.5",result:"blur"}),e.jsx("feComposite",{in:"SourceGraphic",in2:"blur",operator:"over"})]}),e.jsx("marker",{id:"arrow",markerWidth:"8",markerHeight:"8",refX:"6",refY:"3",orient:"auto",children:e.jsx("path",{d:"M0,0 L0,6 L8,3 z",fill:"#4f46e5"})})]}),i.map(([x,f],m)=>{const p=o.get(x),h=o.get(f);if(!p||!h)return null;const g=p.x+be,b=p.y+me/2,j=h.x,N=h.y+me/2;return e.jsx(y.line,{initial:{pathLength:0,opacity:0},animate:{pathLength:1,opacity:1},transition:{duration:1,delay:m*.05},x1:g,y1:b,x2:j-4,y2:N,className:"stroke-primary-500/20",strokeWidth:1.5,markerEnd:"url(#arrow)"},`${x}-${f}`)}),r.map((x,f)=>e.jsxs(y.g,{initial:{opacity:0,scale:.9,y:x.y+10},animate:{opacity:1,scale:1,y:x.y},transition:{duration:.4,delay:f*.03},whileHover:{scale:1.05,filter:"url(#neon-glow-small)"},className:"cursor-pointer",children:[e.jsx("rect",{x:x.x,y:0,width:be,height:me,rx:8,className:"fill-neutral-surface/80 stroke-neutral-border",strokeWidth:1}),e.jsx(y.rect,{x:x.x,y:0,width:be,height:me,rx:8,className:"fill-none",stroke:ee[x.status]??"#27272a",strokeWidth:1.5,initial:{pathLength:0},animate:{pathLength:1},transition:{duration:1,delay:f*.05}}),e.jsx("text",{x:x.x+be/2,y:me/2,dominantBaseline:"middle",textAnchor:"middle",className:"text-[10px] font-bold tracking-tight fill-neutral-text pointer-events-none",children:x.id.length>18?x.id.slice(0,17)+"…":x.id})]},x.id))]})})]})}const Hl=[{key:"totalFeatures",label:"Total",color:"text-white"},{key:"totalDone",label:"Done",color:"text-emerald-400"},{key:"totalInProgress",label:"In Progress",color:"text-blue-400"},{key:"totalPlanned",label:"Planned",color:"text-gray-400"},{key:"totalBlocked",label:"Blocked",color:"text-red-400"},{key:"totalNeedsHuman",label:"Needs Human",color:"text-amber-400"},{key:"totalBacklog",label:"Backlog",color:"text-gray-500"}];function Wl({data:t}){return e.jsx("div",{className:"flex flex-wrap gap-6 rounded-lg border border-gray-800 bg-gray-900/50 px-5 py-3",children:Hl.map(({key:s,label:a,color:n})=>e.jsxs("div",{className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:`text-lg font-bold tabular-nums ${n}`,children:t[s]}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-gray-500",children:a})]},s))})}const ie="—";function As(t){return(t.status==="planned"||t.status==="backlog")&&(!t.assignee||t.assignee===ie)}function Gl(t){return!t.spec||t.spec==="none"||t.spec===ie?"brainstorming":!t.plans||t.plans.length===0||t.plans.length===1&&t.plans[0]===ie?"planning":"execution"}function Ul(t){const s=t.match(/^github:(.+?)#(\d+)$/);return s?`https://github.com/${s[1]}/issues/${s[2]}`:null}function ql({status:t}){const s=ee[t]??"#71717a";return e.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wider",style:{backgroundColor:`${s}20`,color:s},children:t.replace("-"," ")})}function Yl({priority:t}){const s={P0:"text-red-400 bg-red-400/10",P1:"text-orange-400 bg-orange-400/10",P2:"text-yellow-400 bg-yellow-400/10",P3:"text-gray-400 bg-gray-400/10"};return e.jsx("span",{className:`inline-flex rounded px-1.5 py-0.5 text-[10px] font-bold ${s[t]??"text-gray-400 bg-gray-400/10"}`,children:t})}function Vl({feature:t,identity:s,onClaim:a}){const[n,r]=c.useState(!1),i=As(t);return e.jsxs("div",{className:"border-t border-gray-800 first:border-t-0 outline-none focus:ring-2 focus:ring-amber-400 data-[conflict-highlight=true]:ring-2 data-[conflict-highlight=true]:ring-amber-400 data-[conflict-highlight=true]:ring-offset-2 data-[conflict-highlight=true]:ring-offset-gray-900",...t.externalId?{"data-external-id":t.externalId}:{},tabIndex:t.externalId?-1:void 0,children:[e.jsxs("div",{className:"group flex cursor-pointer items-center gap-3 px-4 py-2.5 hover:bg-gray-800/40 transition-colors",onClick:()=>r(!n),children:[e.jsx("span",{className:"text-[10px] text-gray-600 transition-transform",style:{transform:n?"rotate(90deg)":void 0},children:"▶"}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-gray-200",title:t.name,children:t.name}),e.jsx(ql,{status:t.status}),t.priority&&e.jsx(Yl,{priority:t.priority}),t.assignee&&t.assignee!==ie&&e.jsx("span",{className:"text-xs text-gray-500",title:t.assignee,children:t.assignee}),e.jsx("span",{className:"hidden max-w-[200px] truncate text-xs text-gray-600 lg:inline",title:t.summary,children:t.summary}),i&&e.jsx("button",{onClick:l=>{l.stopPropagation(),s&&a(t)},disabled:!s,title:s?void 0:"Could not resolve your identity",className:`ml-auto rounded px-2 py-1 text-[10px] font-bold uppercase tracking-widest border transition-all whitespace-nowrap ${s?"bg-primary-500/10 text-primary-400 border-primary-500/20 hover:bg-primary-500 hover:text-white":"bg-gray-800 text-gray-600 border-gray-700 cursor-not-allowed"}`,children:"Start Working"})]}),n&&e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-1.5 bg-gray-900/30 px-10 py-3 text-xs",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Summary: "}),e.jsx("span",{className:"text-gray-300",children:t.summary})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Spec: "}),e.jsx("span",{className:"text-gray-400",children:t.spec??ie})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Plans: "}),e.jsx("span",{className:"text-gray-400",children:t.plans.length>0?t.plans.join(", "):ie})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"External ID: "}),t.externalId?(()=>{const l=Ul(t.externalId);return l?e.jsx("a",{href:l,target:"_blank",rel:"noopener noreferrer",className:"text-primary-400 hover:underline",onClick:o=>o.stopPropagation(),children:t.externalId}):e.jsx("span",{className:"text-gray-400",children:t.externalId})})():e.jsx("span",{className:"text-gray-400",children:ie})]}),t.blockedBy.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Blocked by: "}),e.jsx("span",{className:"text-red-400",children:t.blockedBy.join(", ")})]}),t.updatedAt&&e.jsxs("div",{children:[e.jsx("span",{className:"text-gray-500",children:"Updated: "}),e.jsx("span",{className:"text-gray-400",children:new Date(t.updatedAt).toLocaleDateString()})]})]})]})}function Jl({name:t,features:s,progress:a,identity:n,onClaim:r}){const[i,l]=c.useState(!1),o=(a==null?void 0:a.done)??0,d=(a==null?void 0:a.total)??s.length;return e.jsxs("div",{className:"rounded-lg border border-gray-800 bg-gray-900 overflow-hidden",children:[e.jsxs("button",{className:"flex w-full items-center gap-3 px-4 py-3 text-left hover:bg-gray-800/40 transition-colors",onClick:()=>l(!i),children:[e.jsx("span",{className:"text-xs text-gray-500 transition-transform",style:{transform:i?void 0:"rotate(90deg)"},children:"▶"}),e.jsx("span",{className:"text-sm font-semibold text-gray-200",children:t}),e.jsxs("span",{className:"text-xs text-gray-500",children:[o,"/",d]}),e.jsx("div",{className:"ml-auto h-1.5 w-24 overflow-hidden rounded-full bg-gray-800",children:e.jsx("div",{className:"h-full rounded-full bg-emerald-500 transition-all",style:{width:d>0?`${o/d*100}%`:"0%"}})})]}),!i&&e.jsx("div",{children:s.map(u=>e.jsx(Vl,{feature:u,identity:n,onClaim:r},u.name))})]})}function Xl({features:t,milestones:s,filterMilestone:a,filterStatus:n,workableOnly:r,identity:i,onClaim:l}){const o=t.filter(x=>{if(a&&x.milestone!==a)return!1;if(n){if(x.status!==n)return!1}else if(x.status==="done")return!1;return!(r&&!As(x))});if(o.length===0)return e.jsx("p",{className:"text-sm text-neutral-muted",children:"No features match the current filters."});const d=new Map;for(const x of o){const f=d.get(x.milestone)??[];f.push(x),d.set(x.milestone,f)}const u=new Map(s.map(x=>[x.name,x]));return e.jsx("div",{className:"space-y-3",children:Array.from(d).map(([x,f])=>e.jsx(Jl,{name:x,features:f,progress:u.get(x),identity:i,onClaim:l},x))})}function Kl(t){return typeof t=="object"&&t!==null&&t.code==="TRACKER_CONFLICT"&&typeof t.externalId=="string"}const Ql=t=>`Claimed by ${t??"another session"} — refresh`;async function pt(t,s){let a;try{a=await fetch(t,s)}catch(i){return{ok:!1,status:0,error:i.message??"Network error"}}let n=null;try{n=await a.json()}catch{}if(a.ok)return{ok:!0,status:a.status,data:n};if(a.status===409&&Kl(n))return{ok:!1,status:409,conflict:n};const r=(n==null?void 0:n.error)??`HTTP ${a.status}`;return{ok:!1,status:a.status,error:r}}const _e=Yt((t,s)=>({current:null,pushConflict:({externalId:a,conflictedWith:n})=>{var i;const r=((i=s().current)==null?void 0:i.seq)??0;t({current:{kind:"conflict",externalId:a,conflictedWith:n,seq:r+1}})},clear:()=>t({current:null})})),Zl={brainstorming:{label:"Brainstorming",description:"No spec found. You’ll start by exploring the problem space."},planning:{label:"Planning",description:"Spec exists but no plan. You’ll create an implementation plan."},execution:{label:"Execution",description:"Spec and plan exist. You’ll start implementing."}};function eo({feature:t,identity:s,onConfirm:a,onCancel:n}){const[r,i]=c.useState(!1),[l,o]=c.useState(null),d=Gl(t),u=Zl[d];async function x(){i(!0),o(null);const f=await pt("/api/actions/roadmap/claim",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({feature:t.name,assignee:s})});if(f.ok){a(f.data);return}if(f.conflict){_e.getState().pushConflict({externalId:f.conflict.externalId,conflictedWith:typeof f.conflict.conflictedWith=="string"?f.conflict.conflictedWith:null}),n();return}o(f.error??"Claim failed"),i(!1)}return e.jsxs("div",{className:"absolute right-0 top-full z-50 mt-2 w-80 rounded-lg border border-gray-700 bg-gray-900 p-4 shadow-xl",children:[e.jsx("h3",{className:"mb-1 text-sm font-semibold text-gray-200",children:"Claim Feature"}),e.jsx("p",{className:"mb-3 text-xs text-gray-400 truncate",title:t.name,children:t.name}),e.jsxs("div",{className:"mb-3 rounded border border-gray-800 bg-gray-800/50 px-3 py-2",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-primary-400",children:u.label})}),e.jsx("p",{className:"mt-1 text-xs text-gray-400",children:u.description})]}),e.jsxs("p",{className:"mb-3 text-xs text-gray-500",children:["Claiming as ",e.jsx("span",{className:"font-medium text-gray-300",children:s})]}),l&&e.jsx("p",{className:"mb-2 text-xs text-red-400",children:l}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{onClick:n,disabled:r,className:"rounded px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest text-gray-500 hover:text-gray-300 transition-colors",children:"Cancel"}),e.jsx("button",{onClick:()=>void x(),disabled:r,className:"rounded bg-primary-500 px-3 py-1.5 text-[10px] font-bold uppercase tracking-widest text-white disabled:opacity-40 hover:bg-primary-400 transition-colors",children:r?"Claiming…":"Confirm"})]})]})}const to={assigned:"text-blue-400",completed:"text-emerald-400",unassigned:"text-gray-400"};function so({records:t}){return t.length===0?null:e.jsx("div",{className:"overflow-x-auto rounded-lg border border-gray-800 bg-gray-900",children:e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-800 text-[10px] font-semibold uppercase tracking-widest text-gray-500",children:[e.jsx("th",{className:"px-4 py-2.5",children:"Feature"}),e.jsx("th",{className:"px-4 py-2.5",children:"Assignee"}),e.jsx("th",{className:"px-4 py-2.5",children:"Action"}),e.jsx("th",{className:"px-4 py-2.5",children:"Date"})]})}),e.jsx("tbody",{children:t.map((s,a)=>e.jsxs("tr",{className:"border-t border-gray-800/50 hover:bg-gray-800/30 transition-colors",children:[e.jsx("td",{className:"px-4 py-2 text-gray-300",children:s.feature}),e.jsx("td",{className:"px-4 py-2 text-gray-400",children:s.assignee}),e.jsx("td",{className:`px-4 py-2 capitalize ${to[s.action]??"text-gray-400"}`,children:s.action}),e.jsx("td",{className:"px-4 py-2 text-gray-500",children:s.date})]},a))})]})})}function ao({onRefresh:t}){const s=_e(n=>n.current),a=_e(n=>n.clear);return c.useEffect(()=>{s&&s.kind==="conflict"&&t(s.externalId)},[s==null?void 0:s.seq,s==null?void 0:s.externalId,t,s]),e.jsx("div",{role:"status","aria-live":"polite","aria-atomic":"true",className:"pointer-events-none fixed bottom-6 right-6 z-50 max-w-sm",children:s&&s.kind==="conflict"&&e.jsxs("div",{"data-testid":"conflict-toast-body",className:"pointer-events-auto flex items-start gap-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm text-amber-200 shadow-xl backdrop-blur",children:[e.jsx("span",{className:"flex-1",children:Ql(s.conflictedWith)}),e.jsx("button",{type:"button","aria-label":"Dismiss conflict notice",onClick:a,className:"rounded px-2 py-0.5 text-[10px] font-bold uppercase tracking-widest text-amber-300 hover:text-amber-100",children:"Dismiss"})]})})}const no=2e3;function zt(t){if(typeof document>"u")return!1;const s=`[data-external-id="${t.replace(/"/g,'\\"')}"]`,a=document.querySelector(s);if(!a)return!1;a.scrollIntoView({behavior:"smooth",block:"center"});try{a.focus({preventScroll:!0})}catch{a.focus()}return a.setAttribute("data-conflict-highlight","true"),setTimeout(()=>{a.removeAttribute("data-conflict-highlight")},no),!0}function ro({milestoneOptions:t,filterMilestone:s,setFilterMilestone:a,filterStatus:n,setFilterStatus:r,workableOnly:i,setWorkableOnly:l}){return e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("select",{value:s,onChange:o=>a(o.target.value),className:"rounded border border-gray-700 bg-gray-900 px-2 py-1 text-xs text-gray-300 focus:outline-none",children:[e.jsx("option",{value:"",children:"All Milestones"}),t.map(o=>e.jsx("option",{value:o,children:o},o))]}),e.jsxs("select",{value:n,onChange:o=>r(o.target.value),className:"rounded border border-gray-700 bg-gray-900 px-2 py-1 text-xs text-gray-300 focus:outline-none",children:[e.jsx("option",{value:"",children:"Non-done"}),e.jsx("option",{value:"in-progress",children:"In Progress"}),e.jsx("option",{value:"planned",children:"Planned"}),e.jsx("option",{value:"blocked",children:"Blocked"}),e.jsx("option",{value:"done",children:"Done"}),e.jsx("option",{value:"backlog",children:"Backlog"}),e.jsx("option",{value:"needs-human",children:"Needs Human"})]}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-gray-400 cursor-pointer select-none",children:[e.jsx("input",{type:"checkbox",checked:i,onChange:o=>l(o.target.checked),className:"rounded border-gray-600 bg-gray-800 text-primary-500 focus:ring-primary-500/30"}),"Workable only"]})]})}const Es="rounded bg-primary-500/10 px-2 py-1 text-[10px] font-bold uppercase tracking-widest text-primary-400 border border-primary-500/20 hover:bg-primary-500 hover:text-white transition-all";function Bt({command:t,label:s}){const a=X();return e.jsx("button",{onClick:()=>{const n=E.getState().createThread("chat",{sessionId:crypto.randomUUID(),command:t});a(`/t/${n.id}`)},className:Es,children:s})}function io(){const t=X(),[s,a]=c.useState(!1),[n,r]=c.useState(""),i=c.useRef(null);c.useEffect(()=>{var o;s&&((o=i.current)==null||o.focus())},[s]);const l=()=>{if(!n.trim())return;const d=E.getState().createThread("chat",{sessionId:crypto.randomUUID(),command:"harness:roadmap-add"});t(`/t/${d.id}`),a(!1),r("")};return e.jsxs("div",{className:"relative",children:[e.jsx("button",{onClick:()=>a(!s),className:Es,children:"Add"}),s&&e.jsxs("div",{className:"absolute right-0 top-full z-50 mt-2 w-72 rounded-lg border border-gray-700 bg-gray-900 p-3 shadow-xl",children:[e.jsx("label",{className:"mb-1.5 block text-[10px] font-semibold uppercase tracking-widest text-gray-400",children:"What should be added?"}),e.jsx("input",{ref:i,value:n,onChange:o=>r(o.target.value),onKeyDown:o=>{o.key==="Enter"&&l(),o.key==="Escape"&&(a(!1),r(""))},placeholder:"e.g. Dark mode support",className:"mb-2 w-full rounded border border-gray-700 bg-gray-800 px-2 py-1.5 text-xs text-gray-200 placeholder-gray-600 focus:border-primary-500 focus:outline-none"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx("button",{onClick:()=>{a(!1),r("")},className:"rounded px-2 py-1 text-[10px] font-bold uppercase tracking-widest text-gray-500 hover:text-gray-300 transition-colors",children:"Cancel"}),e.jsx("button",{onClick:l,disabled:!n.trim(),className:"rounded bg-primary-500 px-2 py-1 text-[10px] font-bold uppercase tracking-widest text-white disabled:opacity-40 hover:bg-primary-400 transition-colors",children:"Go"})]})]})]})}const lo={brainstorming:"harness:brainstorming",planning:"harness:planning",execution:"harness:execution"};function oo({milestones:t,features:s,data:a}){const n=X(),[r,i]=c.useState(""),[l,o]=c.useState(""),[d,u]=c.useState(!1),[x,f]=c.useState(null),[m,p]=c.useState(null),[h,g]=c.useState(!0),b=t.map(S=>S.name),j=s.some(S=>S.blockedBy.length>0);c.useEffect(()=>{fetch("/api/identity").then(S=>S.ok?S.json():null).then(S=>{S!=null&&S.username&&p(S.username)}).catch(()=>{}).finally(()=>g(!1))},[]);const N=c.useCallback(S=>{f(S)},[]),v=c.useCallback(S=>{f(null);const T=lo[S.workflow]??"harness:execution",w=E.getState().createThread("chat",{sessionId:crypto.randomUUID(),command:T});n(`/t/${w.id}`)},[n]);return e.jsxs("div",{className:"space-y-8",children:[e.jsx(Wl,{data:a}),e.jsxs("section",{children:[e.jsx("h2",{className:"mb-4 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Progress by Milestone"}),e.jsx(Pl,{milestones:t})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-3 flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h2",{className:"text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Features"}),e.jsx(ro,{milestoneOptions:b,filterMilestone:r,setFilterMilestone:i,filterStatus:l,setFilterStatus:o,workableOnly:d,setWorkableOnly:u})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Xl,{features:s,milestones:t,filterMilestone:r,filterStatus:l,workableOnly:d,identity:h?null:m,onClaim:N}),x&&m&&e.jsx(eo,{feature:x,identity:m,onConfirm:v,onCancel:()=>f(null)})]})]}),j&&e.jsxs("section",{children:[e.jsx("h2",{className:"mb-4 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Blocker Dependencies"}),e.jsx("div",{className:"overflow-x-auto rounded-lg border border-gray-800 bg-gray-900 p-4",children:e.jsx(Bl,{features:s})})]}),a.assignmentHistory.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"mb-4 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Assignment History"}),e.jsx(so,{records:a.assignmentHistory})]})]})}const co=500;function xo(){const{data:t,lastUpdated:s,stale:a,error:n}=De(Oe,"overview"),[r,i]=c.useState(null),l=c.useRef(0),o=c.useRef(null);c.useEffect(()=>{i(null),o.current=null},[s]);const d=c.useCallback(async m=>{const p=Date.now();if(p-l.current<co&&o.current!==null){requestAnimationFrame(()=>{zt(m)});return}l.current=p;const h=await pt("/api/roadmap",{cache:"no-store"});h.ok&&(o.current=h.data,i(h.data),requestAnimationFrame(()=>{zt(m)}))},[]),u=t?t.roadmap:null,x=u&&Kr(u)?u:null,f=r??x;return e.jsxs("div",{children:[e.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Roadmap"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Bt,{command:"harness:roadmap-pilot",label:"Pilot"}),e.jsx(Bt,{command:"harness:roadmap-sync",label:"Sync"}),e.jsx(io,{}),e.jsx(mt,{lastUpdated:s,stale:a,error:n})]})]}),!t&&!n&&e.jsx("p",{className:"text-sm text-gray-500",children:"Connecting to data stream…"}),u&&!x&&e.jsx("p",{className:"text-sm text-red-400",children:"error"in u?u.error:"Unavailable"}),f&&e.jsx(oo,{milestones:f.milestones,features:f.features,data:f}),e.jsx(ao,{onRefresh:d})]})}function uo(t){return t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${(t/6e4).toFixed(1)}m`}function mo(t){return`${Math.round(t*100)}%`}function ho(t){return t>=.8?"text-emerald-400":t>=.5?"text-yellow-400":"text-red-400"}const po=c.memo(function({skill:s}){return e.jsxs("tr",{className:"border-b border-gray-800 hover:bg-gray-800/40",children:[e.jsx("td",{className:"py-2 px-3 font-mono text-xs text-gray-200",children:s.skill}),e.jsx("td",{className:"py-2 px-3 text-right tabular-nums text-gray-200",children:s.invocations}),e.jsx("td",{className:`py-2 px-3 text-right tabular-nums ${ho(s.successRate)}`,children:mo(s.successRate)}),e.jsx("td",{className:"py-2 px-3 text-right tabular-nums text-gray-400",children:uo(s.avgDuration)}),e.jsx("td",{className:"py-2 px-3 text-right text-xs text-gray-500",children:s.lastUsed.slice(0,10)})]})});function fo({skills:t}){return t.length===0?e.jsx("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-6 text-center",children:e.jsx("p",{className:"text-sm text-gray-500",children:"No adoption data yet. Skills will appear here after your next session."})}):e.jsx("div",{className:"overflow-x-auto rounded-lg border border-gray-800 bg-gray-900",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b border-gray-800 bg-gray-900/60",children:[e.jsx("th",{className:"py-2 px-3 text-left text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Skill"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Invocations"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Success"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Avg Duration"}),e.jsx("th",{className:"py-2 px-3 text-right text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Last Used"})]})}),e.jsx("tbody",{children:t.map(s=>e.jsx(po,{skill:s},s.skill))})]})})}async function go(){const t=await fetch("/api/adoption");if(!t.ok)throw new Error(`HTTP ${t.status}`);return(await t.json()).data}function yo(){const[t,s]=c.useState(null),[a,n]=c.useState(null),[r,i]=c.useState(!0),l=c.useCallback(async()=>{try{const o=await go();s(o),n(null)}catch(o){n(o instanceof Error?o.message:"Network error")}finally{i(!1)}},[]);return c.useEffect(()=>{l()},[l]),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-6 flex items-center justify-between",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Adoption"}),t&&e.jsxs("span",{className:"text-xs text-gray-500",children:["Generated ",new Date(t.generatedAt).toLocaleString()]})]}),r&&!t&&e.jsx("p",{className:"text-sm text-gray-500",children:"Loading adoption telemetry..."}),a&&e.jsx("p",{className:"text-sm text-red-400",children:a}),t&&e.jsxs("div",{className:"space-y-8",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Summary"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-3",children:[e.jsx(D,{label:"Total Invocations",value:t.totalInvocations}),e.jsx(D,{label:"Unique Skills",value:t.uniqueSkills}),e.jsx(D,{label:"Period",value:t.period})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"mb-3 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Top Skills"}),e.jsx(fo,{skills:t.topSkills})]})]})]})}function bo(t){const s=c.useRef(new Set),a=c.useRef(!1);c.useEffect(()=>{typeof Notification<"u"&&Notification.permission==="default"&&Notification.requestPermission()},[]),c.useEffect(()=>{if(!a.current){for(const n of t)s.current.add(n.id);a.current=!0;return}if(!(typeof Notification>"u"||Notification.permission!=="granted")&&document.hidden)for(const n of t)s.current.has(n.id)||(s.current.add(n.id),new Notification("Needs Attention",{body:`${n.context.issueTitle}
21
+ ${n.reasons.join(", ")}`,tag:n.id}))},[t])}function jo({spec:t}){return e.jsxs("div",{className:"space-y-3 rounded-md border border-primary-500/20 bg-primary-500/5 p-4",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-widest text-primary-500",children:"Enriched Spec (SEL)"}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-gray-500",children:"Intent"}),e.jsx("p",{className:"mt-1 text-sm text-white",children:t.intent})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-gray-500",children:"Summary"}),e.jsx("p",{className:"mt-1 text-sm leading-relaxed text-gray-300",children:t.summary})]}),t.affectedSystems.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-gray-500",children:"Affected Systems"}),e.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:t.affectedSystems.map(s=>e.jsxs("span",{className:"rounded-md border border-blue-500/20 bg-blue-500/10 px-2 py-0.5 text-[10px] font-medium text-blue-400",title:`Confidence: ${Math.round(s.confidence*100)}% | Tests: ${s.testCoverage} | Deps: ${s.transitiveDeps.length}`,children:[s.name,s.graphNodeId&&e.jsxs("span",{className:"ml-1 text-blue-500/50",children:[Math.round(s.confidence*100),"%"]})]},s.name))})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-3",children:[t.unknowns.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] font-bold uppercase tracking-widest text-amber-500",children:["Unknowns (",t.unknowns.length,")"]}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.unknowns.map((s,a)=>e.jsx("li",{className:"text-xs text-gray-400",children:s},a))})]}),t.ambiguities.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] font-bold uppercase tracking-widest text-orange-500",children:["Ambiguities (",t.ambiguities.length,")"]}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.ambiguities.map((s,a)=>e.jsx("li",{className:"text-xs text-gray-400",children:s},a))})]}),t.riskSignals.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] font-bold uppercase tracking-widest text-red-500",children:["Risk Signals (",t.riskSignals.length,")"]}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.riskSignals.map((s,a)=>e.jsx("li",{className:"text-xs text-gray-400",children:s},a))})]})]})]})}const ze={low:"bg-emerald-500/10 text-emerald-400 border-emerald-500/20",medium:"bg-yellow-500/10 text-yellow-400 border-yellow-500/20",high:"bg-orange-500/10 text-orange-400 border-orange-500/20",critical:"bg-red-500/10 text-red-400 border-red-500/20"},No={local:"text-emerald-400",human:"text-amber-400","simulation-required":"text-purple-400"};function je({value:t,label:s,color:a}){const n=Math.round(t*100);return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-400",children:s}),e.jsxs("span",{className:a,children:[n,"%"]})]}),e.jsx("div",{className:"h-1.5 w-full rounded-full bg-gray-800",children:e.jsx("div",{className:`h-full rounded-full ${a.replace("text-","bg-")}`,style:{width:`${n}%`}})})]})}function vo({score:t}){return e.jsxs("div",{className:"space-y-3 rounded-md border border-secondary-400/20 bg-secondary-400/5 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-widest text-secondary-400",children:"Complexity Model (CML)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`inline-block rounded-md border px-2 py-0.5 text-[10px] font-bold uppercase tracking-widest ${ze[t.riskLevel]??ze.medium}`,children:t.riskLevel}),e.jsx("span",{className:`text-xs font-mono font-bold ${No[t.recommendedRoute]??"text-gray-400"}`,children:t.recommendedRoute})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(je,{value:t.overall,label:"Overall",color:"text-primary-500"}),e.jsx(je,{value:t.dimensions.structural,label:"Structural",color:"text-blue-400"}),e.jsx(je,{value:t.dimensions.semantic,label:"Semantic",color:"text-purple-400"}),e.jsx(je,{value:t.dimensions.historical,label:"Historical",color:"text-yellow-400"}),e.jsx(je,{value:t.confidence,label:"Confidence",color:"text-emerald-400"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 border-t border-gray-800 pt-2 md:grid-cols-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-lg font-bold text-white",children:t.blastRadius.services}),e.jsx("span",{className:"text-[10px] uppercase tracking-widest text-gray-500",children:"Services"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-lg font-bold text-white",children:t.blastRadius.modules}),e.jsx("span",{className:"text-[10px] uppercase tracking-widest text-gray-500",children:"Modules"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-lg font-bold text-white",children:t.blastRadius.filesEstimated}),e.jsx("span",{className:"text-[10px] uppercase tracking-widest text-gray-500",children:"Files"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-lg font-bold text-white",children:t.blastRadius.testFilesAffected}),e.jsx("span",{className:"text-[10px] uppercase tracking-widest text-gray-500",children:"Test Files"})]})]}),t.reasoning.length>0&&e.jsxs("div",{className:"border-t border-gray-800 pt-2",children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-gray-500",children:"Reasoning"}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.reasoning.map((s,a)=>e.jsx("li",{className:"text-xs text-gray-400",children:s},a))})]})]})}function wo({interaction:t,onDismiss:s,onClaim:a}){const{context:n,reasons:r,status:i,createdAt:l}=t,o=i==="pending",d=i==="claimed",u=!!n.enrichedSpec,x=!!n.complexityScore,f=u||x,[m,p]=c.useState(!1);return e.jsxs("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-5",children:[e.jsxs("div",{className:"mb-3 flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-base font-semibold text-white",children:n.issueTitle}),f&&e.jsx("span",{className:"rounded-md border border-primary-500/20 bg-primary-500/10 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-widest text-primary-500",children:"Analyzed"})]}),e.jsxs("p",{className:"mt-1 text-xs text-gray-500",children:[new Date(l).toLocaleString()," · ",t.issueId]})]}),e.jsx("span",{className:["rounded px-2 py-0.5 text-xs font-medium",o?"bg-yellow-900 text-yellow-300":"",d?"bg-blue-900 text-blue-300":"",i==="resolved"?"bg-gray-700 text-gray-400":""].filter(Boolean).join(" "),children:i})]}),n.issueDescription&&e.jsx("p",{className:"mb-3 text-sm text-gray-300",children:n.issueDescription}),e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"mb-1 text-xs font-medium uppercase tracking-widest text-gray-500",children:"Escalation Reasons"}),e.jsx("div",{className:"space-y-1",children:r.map((h,g)=>e.jsx("div",{className:"text-sm text-yellow-400 [&_p]:m-0 [&_strong]:font-bold [&_strong]:text-yellow-200",children:e.jsx(te,{remarkPlugins:[se],children:h})},g))})]}),f&&e.jsxs("div",{className:"mb-3",children:[e.jsxs("button",{onClick:()=>p(h=>!h),className:["flex w-full items-center justify-between rounded-md border px-3 py-2 text-left text-xs transition-colors",m?"border-primary-500/30 bg-primary-500/10":"border-gray-700 bg-gray-800/50 hover:border-gray-600 hover:bg-gray-800"].join(" "),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block text-[10px] text-gray-500 transition-transform",style:{transform:m?"rotate(90deg)":"rotate(0deg)"},children:"▶"}),e.jsxs("span",{className:"font-medium text-gray-300",children:[m?"Hide":"View"," Analysis"]}),u&&e.jsxs("span",{className:"text-gray-500",children:[n.enrichedSpec.affectedSystems.length," system",n.enrichedSpec.affectedSystems.length!==1?"s":""]})]}),x&&e.jsxs("span",{className:`rounded-md border px-2 py-0.5 text-[10px] font-bold uppercase tracking-widest ${ze[n.complexityScore.riskLevel]??ze.medium}`,children:[n.complexityScore.riskLevel," risk"]})]}),m&&e.jsxs("div",{className:"mt-2 space-y-3",children:[u&&e.jsx(jo,{spec:n.enrichedSpec}),x&&e.jsx(vo,{score:n.complexityScore})]})]}),n.relatedFiles.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"mb-1 text-xs font-medium uppercase tracking-widest text-gray-500",children:"Related Files"}),e.jsx("ul",{className:"space-y-0.5",children:n.relatedFiles.map(h=>e.jsx("li",{className:"font-mono text-xs text-gray-400",children:h},h))})]}),n.specPath&&e.jsxs("p",{className:"mb-3 text-xs text-gray-500",children:["Spec: ",e.jsx("span",{className:"font-mono text-gray-400",children:n.specPath})]}),(o||d)&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>a(t.id),className:"rounded bg-blue-700 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-600",children:"Claim"}),e.jsx("button",{onClick:()=>s(t.id),className:"rounded bg-gray-700 px-3 py-1.5 text-xs font-medium text-gray-300 hover:bg-gray-600",children:"Dismiss"})]})]})}function ko(){const{interactions:t,removeInteraction:s,setInteractions:a}=ke(),[n,r]=c.useState(!1),[i,l]=c.useState([]),[o,d]=c.useState(""),u=X();bo(i),c.useEffect(()=>{const h=new AbortController;return(async()=>{try{const g=await fetch("/api/interactions",{signal:h.signal});if(g.ok){const b=await g.json();a(b),l(b)}}catch(g){if(g.name==="AbortError")return}finally{r(!0)}})(),()=>h.abort()},[a]),c.useEffect(()=>{t.length>0&&l(h=>{const g=new Set(h.map(j=>j.id)),b=t.filter(j=>!g.has(j.id));return b.length>0?[...h,...b]:h})},[t]);const x=c.useCallback(async h=>{(await fetch(`/api/interactions/${h}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({status:"resolved"})})).ok&&(s(h),l(b=>b.filter(j=>j.id!==h)))},[s]),f=c.useCallback(h=>{const g=E.getState();let b;for(const j of g.threads.values())if(j.type==="attention"&&"interactionId"in j.meta&&j.meta.interactionId===h){b=j.id;break}b&&u(`/t/${b}`)},[u]),p=i.filter(h=>{var S,T;if(h.status==="resolved")return!1;if(!o.trim())return!0;const g=o.toLowerCase(),b=(S=h.context.issueTitle)==null?void 0:S.toLowerCase().includes(g),j=(T=h.context.issueDescription)==null?void 0:T.toLowerCase().includes(g),N=h.reasons.some(w=>w.toLowerCase().includes(g)),v=h.id.toLowerCase().includes(g)||h.issueId.toLowerCase().includes(g);return b||j||N||v}).sort((h,g)=>new Date(g.createdAt).getTime()-new Date(h.createdAt).getTime());return e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsxs("div",{className:"mb-6 flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Needs Attention"}),e.jsxs("div",{className:"relative w-full max-w-sm",children:[e.jsx("div",{className:"pointer-events-none absolute inset-y-0 left-0 flex items-center pl-3",children:e.jsx(et,{className:"h-4 w-4 text-gray-500"})}),e.jsx("input",{type:"text",className:"block w-full rounded-lg border border-gray-800 bg-gray-900 py-2 pl-10 pr-10 text-sm text-white placeholder-gray-500 transition-all focus:border-primary-500 focus:outline-none focus:ring-1 focus:ring-primary-500",placeholder:"Search escalations...",value:o,onChange:h=>d(h.target.value)}),o&&e.jsx("button",{className:"absolute inset-y-0 right-0 flex items-center pr-3 text-gray-500 hover:text-gray-300",onClick:()=>d(""),children:e.jsx(lt,{className:"h-4 w-4"})})]})]}),!n&&e.jsx("div",{className:"flex flex-1 items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-2 text-gray-500",children:[e.jsx(Be,{className:"h-8 w-8 animate-spin"}),e.jsx("p",{className:"text-sm",children:"Loading interactions..."})]})}),n&&p.length===0&&e.jsx("div",{className:"flex flex-1 items-center justify-center rounded-xl border border-dashed border-gray-800 bg-gray-900/20 p-12 text-center",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-gray-500",children:o?"No interactions match your search.":"No interactions require attention."}),o&&e.jsx("button",{onClick:()=>d(""),className:"mt-2 text-xs font-semibold text-primary-500 hover:text-primary-400",children:"Clear search"})]})}),n&&p.length>0&&e.jsx("div",{className:"flex-1 overflow-hidden",children:e.jsx(ns,{style:{height:"100%"},data:p,itemContent:(h,g)=>e.jsx("div",{className:"pb-4 pr-4",children:e.jsx(wo,{interaction:g,onDismiss:b=>void x(b),onClaim:f})})})})]})}async function So(t){const s=await pt("/api/roadmap/append",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});return s.ok?{ok:!0,featureName:s.data.featureName,externalId:s.data.externalId}:s.conflict?(_e.getState().pushConflict({externalId:s.conflict.externalId,conflictedWith:typeof s.conflict.conflictedWith=="string"?s.conflict.conflictedWith:null}),{ok:!1,error:"A conflicting feature was just added — see toast"}):{ok:!1,error:s.error??"Append failed"}}async function Co(t,s,a){var n;try{const r=await fetch("/api/analyze",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),signal:a});if(!r.ok){if((n=r.headers.get("content-type"))!=null&&n.includes("application/json")){const d=await r.json();s.onError(d.error??`HTTP ${r.status}`)}else s.onError(`HTTP ${r.status}`);return}if(!r.body){s.onError("No response stream");return}const i=r.body.getReader(),l=new TextDecoder;let o="";for(;;){const{done:d,value:u}=await i.read();if(d)break;o+=l.decode(u,{stream:!0});const x=o.split(`
22
+ `);o=x.pop()??"";for(const f of x){if(!f.startsWith("data: "))continue;const m=f.slice(6).trim();if(m==="[DONE]"){s.onDone();return}try{const p=JSON.parse(m);if(typeof p!="object"||p===null||!("type"in p))continue;const h=p;switch(h.type){case"status":s.onStatus(h.text);break;case"sel_result":s.onSEL(h.data);break;case"cml_result":s.onCML(h.data);break;case"pesl_result":s.onPESL(h.data);break;case"signals":s.onSignals(h.data);break;case"error":s.onError(h.error);return}}catch{}}}s.onDone()}catch(r){r.name!=="AbortError"&&s.onError(r.message??"Stream failed")}}function Ne({value:t,label:s,color:a}){const n=Math.round(t*100),i={"text-primary-500":"bg-primary-500","text-secondary-400":"bg-secondary-400","text-accent-500":"bg-accent-500","text-blue-400":"bg-blue-400","text-purple-400":"bg-purple-400","text-yellow-400":"bg-yellow-400","text-emerald-400":"bg-emerald-400"}[a]||"bg-gray-600";return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{className:"text-gray-400",children:s}),e.jsxs("span",{className:a,children:[n,"%"]})]}),e.jsx("div",{className:"h-1.5 w-full rounded-full bg-gray-800",children:e.jsx(y.div,{initial:{width:0},animate:{width:`${n}%`},transition:{duration:.6,ease:"easeOut"},className:`h-full rounded-full ${i}`})})]})}const Ht={low:"bg-emerald-500/10 text-emerald-400 border-emerald-500/20",medium:"bg-yellow-500/10 text-yellow-400 border-yellow-500/20",high:"bg-orange-500/10 text-orange-400 border-orange-500/20",critical:"bg-red-500/10 text-red-400 border-red-500/20"};function Mo({level:t}){return e.jsx("span",{className:`inline-block rounded-md border px-2 py-0.5 text-[10px] font-bold uppercase tracking-widest ${Ht[t]??Ht.medium}`,children:t})}const To={local:"text-emerald-400",human:"text-amber-400","simulation-required":"text-purple-400"};function Io({data:t}){return e.jsxs(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"rounded-lg border border-gray-800 bg-gray-900 p-5 space-y-4",children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-widest text-primary-500",children:"Spec Enrichment (SEL)"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-gray-500",children:"Intent"}),e.jsx("p",{className:"mt-1 text-sm text-white",children:t.intent})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-gray-500",children:"Summary"}),e.jsx("p",{className:"mt-1 text-sm text-gray-300 leading-relaxed",children:t.summary})]}),t.affectedSystems.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-gray-500",children:"Affected Systems"}),e.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:t.affectedSystems.map(s=>e.jsxs("span",{className:"rounded-md bg-blue-500/10 border border-blue-500/20 px-2 py-0.5 text-[10px] font-medium text-blue-400",title:`Confidence: ${Math.round(s.confidence*100)}% | Tests: ${s.testCoverage} | Deps: ${s.transitiveDeps.length}`,children:[s.name,s.graphNodeId&&e.jsxs("span",{className:"ml-1 text-blue-500/50",children:[Math.round(s.confidence*100),"%"]})]},s.name))})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[t.unknowns.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] font-bold uppercase tracking-widest text-amber-500",children:["Unknowns (",t.unknowns.length,")"]}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.unknowns.map((s,a)=>e.jsx("li",{className:"text-xs text-gray-400",children:s},a))})]}),t.ambiguities.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] font-bold uppercase tracking-widest text-orange-500",children:["Ambiguities (",t.ambiguities.length,")"]}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.ambiguities.map((s,a)=>e.jsx("li",{className:"text-xs text-gray-400",children:s},a))})]}),t.riskSignals.length>0&&e.jsxs("div",{children:[e.jsxs("span",{className:"text-[10px] font-bold uppercase tracking-widest text-red-500",children:["Risk Signals (",t.riskSignals.length,")"]}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.riskSignals.map((s,a)=>e.jsx("li",{className:"text-xs text-gray-400",children:s},a))})]})]})]})]})}function $o({data:t}){return e.jsxs(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"rounded-lg border border-gray-800 bg-gray-900 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-widest text-secondary-400",children:"Complexity Model (CML)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Mo,{level:t.riskLevel}),e.jsx("span",{className:`text-xs font-mono font-bold ${To[t.recommendedRoute]??"text-gray-400"}`,children:t.recommendedRoute})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ne,{value:t.overall,label:"Overall",color:"text-primary-500"}),e.jsx(Ne,{value:t.dimensions.structural,label:"Structural",color:"text-secondary-400"}),e.jsx(Ne,{value:t.dimensions.semantic,label:"Semantic",color:"text-accent-500"}),e.jsx(Ne,{value:t.dimensions.historical,label:"Historical",color:"text-yellow-400"}),e.jsx(Ne,{value:t.confidence,label:"Confidence",color:"text-emerald-400"})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 pt-2 border-t border-gray-800",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-lg font-bold text-white",children:t.blastRadius.services}),e.jsx("span",{className:"text-[10px] text-gray-500 uppercase tracking-widest",children:"Services"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-lg font-bold text-white",children:t.blastRadius.modules}),e.jsx("span",{className:"text-[10px] text-gray-500 uppercase tracking-widest",children:"Modules"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-lg font-bold text-white",children:t.blastRadius.filesEstimated}),e.jsx("span",{className:"text-[10px] text-gray-500 uppercase tracking-widest",children:"Files"})]}),e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"block text-lg font-bold text-white",children:t.blastRadius.testFilesAffected}),e.jsx("span",{className:"text-[10px] text-gray-500 uppercase tracking-widest",children:"Test Files"})]})]}),t.reasoning.length>0&&e.jsxs("div",{className:"pt-2 border-t border-gray-800",children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-gray-500",children:"Reasoning"}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.reasoning.map((s,a)=>e.jsx("li",{className:"text-xs text-gray-400",children:s},a))})]})]})}function Ao({data:t}){return e.jsxs(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"rounded-lg border border-gray-800 bg-gray-900 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-xs font-semibold uppercase tracking-widest text-amber-400",children:"Simulation (PESL)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono text-[10px] text-gray-500 uppercase",children:t.tier}),t.abort&&e.jsx("span",{className:"rounded-md bg-red-500/10 border border-red-500/20 px-2 py-0.5 text-[10px] font-bold uppercase text-red-400",children:"Abort Recommended"}),e.jsxs("span",{className:`text-sm font-bold ${t.executionConfidence>=.7?"text-emerald-400":t.executionConfidence>=.4?"text-yellow-400":"text-red-400"}`,children:[Math.round(t.executionConfidence*100),"% confidence"]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[t.simulatedPlan.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-gray-500",children:"Simulated Plan"}),e.jsx("ol",{className:"mt-1 space-y-0.5 list-decimal list-inside",children:t.simulatedPlan.map((s,a)=>e.jsx("li",{className:"text-xs text-gray-300",children:s},a))})]}),t.predictedFailures.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-red-500",children:"Predicted Failures"}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.predictedFailures.map((s,a)=>e.jsx("li",{className:"text-xs text-gray-400",children:s},a))})]}),t.riskHotspots.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-orange-500",children:"Risk Hotspots"}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.riskHotspots.map((s,a)=>e.jsx("li",{className:"text-xs text-gray-400",children:s},a))})]}),t.testGaps.length>0&&e.jsxs("div",{children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-amber-500",children:"Test Gaps"}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.testGaps.map((s,a)=>e.jsx("li",{className:"text-xs text-gray-400",children:s},a))})]})]}),t.recommendedChanges.length>0&&e.jsxs("div",{className:"pt-2 border-t border-gray-800",children:[e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-widest text-gray-500",children:"Recommended Changes"}),e.jsx("ul",{className:"mt-1 space-y-0.5",children:t.recommendedChanges.map((s,a)=>e.jsx("li",{className:"text-xs text-gray-400",children:s},a))})]})]})}function Eo({signals:t}){return e.jsx(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"flex flex-wrap gap-2",children:t.map((s,a)=>e.jsx("span",{className:"rounded-md bg-red-500/10 border border-red-500/20 px-3 py-1 text-xs font-medium text-red-400",title:s.reason,children:s.name},a))})}function Ro(t,s,a,n){const r=[`# Spec: ${t}`,""];if(r.push(`**Generated:** ${new Date().toISOString()}`),a&&(r.push(`**Route Recommendation:** ${a.recommendedRoute}`),r.push(`**Risk Level:** ${a.riskLevel}`)),r.push(""),s&&(r.push("## Intent","",s.intent,""),r.push("## Summary","",s.summary,""),s.affectedSystems.length>0)){r.push("## Affected Systems","");for(const i of s.affectedSystems)r.push(`- ${i.name}`);r.push("")}if(a&&(r.push("## Complexity Score",""),r.push(`- **Overall:** ${Math.round(a.overall*100)}%`),r.push(`- **Structural:** ${Math.round(a.dimensions.structural*100)}%`),r.push(`- **Semantic:** ${Math.round(a.dimensions.semantic*100)}%`),r.push(`- **Historical:** ${Math.round(a.dimensions.historical*100)}%`),r.push(`- **Blast Radius:** ${a.blastRadius.services} services, ${a.blastRadius.modules} modules, ~${a.blastRadius.filesEstimated} files`),r.push("")),s){if(s.unknowns.length>0){r.push("## Unknowns","");for(const i of s.unknowns)r.push(`- ${i}`);r.push("")}if(s.ambiguities.length>0){r.push("## Ambiguities","");for(const i of s.ambiguities)r.push(`- ${i}`);r.push("")}if(s.riskSignals.length>0){r.push("## Risk Signals","");for(const i of s.riskSignals)r.push(`- ${i}`);r.push("")}}if(n){if(r.push("## Simulation (PESL)",""),r.push(`**Execution Confidence:** ${Math.round(n.executionConfidence*100)}%`),r.push(""),n.simulatedPlan.length>0&&(r.push("### Simulated Plan",""),n.simulatedPlan.forEach((i,l)=>r.push(`${l+1}. ${i}`)),r.push("")),n.predictedFailures.length>0){r.push("### Predicted Failures","");for(const i of n.predictedFailures)r.push(`- ${i}`);r.push("")}if(n.recommendedChanges.length>0){r.push("### Recommended Changes","");for(const i of n.recommendedChanges)r.push(`- ${i}`);r.push("")}}return r.join(`
23
+ `)}function $e({icon:t,label:s,doneLabel:a,onClick:n,disabled:r,pending:i,done:l,title:o,color:d="border-gray-700 text-gray-400 hover:border-primary-500/50 hover:text-primary-400"}){return e.jsxs(y.button,{...r?{}:{whileHover:{scale:1.02},whileTap:{scale:.98}},onClick:n,disabled:r||i||l,...o!=null?{title:o}:{},className:`flex items-center gap-2 rounded-lg border px-4 py-2.5 text-xs font-bold uppercase tracking-wider transition-all disabled:cursor-not-allowed disabled:opacity-30 ${l?"border-emerald-500/30 text-emerald-400":d}`,children:[i?e.jsx("div",{className:"h-3.5 w-3.5 animate-spin rounded-full border-2 border-current border-t-transparent"}):l?e.jsx(xt,{size:14}):t,l?a:s]})}function Lo(){const[t,s]=c.useState(""),[a,n]=c.useState(""),[r,i]=c.useState(""),[l,o]=c.useState(!1),[d,u]=c.useState(null),[x,f]=c.useState(null),[m,p]=c.useState(null),[h,g]=c.useState(null),[b,j]=c.useState(null),[N,v]=c.useState(null),[S,T]=c.useState("idle"),[w,k]=c.useState(null),$=c.useRef(null),M=m||h||b||N,L=!l&&M;c.useEffect(()=>{if(S==="roadmap-done"||S==="dispatch-done"){const A=setTimeout(()=>T("idle"),3e3);return()=>clearTimeout(A)}},[S]);const O=c.useCallback(async()=>{if(!t.trim()||l)return;f(null),p(null),g(null),j(null),v(null),u(null),o(!0);const A=new AbortController;$.current=A;const P=r.split(",").map(_=>_.trim()).filter(Boolean),H={title:t.trim()};a.trim()&&(H.description=a.trim()),P.length>0&&(H.labels=P),await Co(H,{onStatus:u,onSEL:_=>{p(_),u(null)},onCML:_=>{g(_),u(null)},onPESL:_=>{j(_),u(null)},onSignals:_=>{v(_),u(null)},onError:_=>{f(_),o(!1),u(null)},onDone:()=>{o(!1),u(null)}},A.signal)},[t,a,r,l]),R=c.useCallback(()=>{var A;(A=$.current)==null||A.abort(),o(!1),u(null)},[]),G=c.useCallback(async()=>{T("roadmap-pending"),k(null);const A=await So({title:t.trim(),summary:m==null?void 0:m.summary,enrichedSpec:m?{intent:m.intent,unknowns:m.unknowns,ambiguities:m.ambiguities,riskSignals:m.riskSignals,affectedSystems:m.affectedSystems.map(P=>({name:P.name}))}:void 0,cmlRecommendedRoute:h==null?void 0:h.recommendedRoute});if(A.ok){T("roadmap-done");return}k(A.error??"Append failed"),T("idle")},[t,m,h]),Y=c.useCallback(async()=>{T("dispatch-pending"),k(null);try{const A=r.split(",").map(H=>H.trim()).filter(Boolean),P=await fetch("/api/dispatch/adhoc",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({title:t.trim(),description:a.trim()||void 0,labels:A.length>0?A:void 0})});if(!P.ok){const H=await P.json();throw new Error(H.error??`HTTP ${P.status}`)}T("dispatch-done")}catch(A){k(A.message),T("idle")}},[t,a,r]),Q=c.useCallback(()=>{var H;if(!m)return;const A=[];a.trim()&&A.push(a.trim());const P=[];for(const _ of m.unknowns)P.push(`- Unknown: ${_}`);for(const _ of m.ambiguities)P.push(`- Ambiguity: ${_}`);P.length>0&&A.push("","---","Suggested clarifications from analysis:",...P),n(A.join(`
24
+ `)),p(null),g(null),j(null),v(null),T("idle"),k(null),(H=document.getElementById("analyze-description"))==null||H.focus()},[m,a]),U=c.useCallback(()=>{const A=Ro(t.trim(),m,h,b),P=t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").slice(0,40),H=new Date().toISOString().slice(0,10),_=new Blob([A],{type:"text/markdown"}),I=URL.createObjectURL(_),F=document.createElement("a");F.href=I,F.download=`spec-${P}-${H}.md`,F.click(),URL.revokeObjectURL(I)},[t,m,h,b]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-primary-500/10 p-2 text-primary-500",children:e.jsx(Ee,{size:20,className:"drop-shadow-[0_0_10px_var(--color-primary-500)]"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Analyze"}),e.jsx("p",{className:"text-xs text-gray-500 font-mono uppercase tracking-widest",children:"Intelligence Pipeline"})]})]}),e.jsxs("div",{className:"rounded-lg border border-gray-800 bg-gray-900 p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsxs("label",{htmlFor:"analyze-title",className:"block text-xs font-semibold uppercase tracking-widest text-gray-500 mb-1.5",children:["Title ",e.jsx("span",{className:"text-red-400",children:"*"})]}),e.jsx("input",{id:"analyze-title",type:"text",value:t,onChange:A=>s(A.target.value),onKeyDown:A=>{A.key==="Enter"&&!A.shiftKey&&(A.preventDefault(),O())},placeholder:"Describe the work item...",disabled:l,className:"w-full rounded-lg border border-gray-700 bg-gray-800 px-4 py-2.5 text-sm text-white placeholder-gray-500 transition-all focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20 disabled:opacity-50"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"analyze-description",className:"block text-xs font-semibold uppercase tracking-widest text-gray-500 mb-1.5",children:"Description"}),e.jsx("textarea",{id:"analyze-description",rows:8,value:a,onChange:A=>n(A.target.value),placeholder:"Additional context, requirements, constraints...",disabled:l,className:"w-full rounded-lg border border-gray-700 bg-gray-800 px-4 py-2.5 text-sm text-white placeholder-gray-500 transition-all focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20 disabled:opacity-50"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"analyze-labels",className:"block text-xs font-semibold uppercase tracking-widest text-gray-500 mb-1.5",children:"Labels"}),e.jsx("input",{id:"analyze-labels",type:"text",value:r,onChange:A=>i(A.target.value),placeholder:"Comma-separated labels (e.g. frontend, auth, urgent)",disabled:l,className:"w-full rounded-lg border border-gray-700 bg-gray-800 px-4 py-2.5 text-sm text-white placeholder-gray-500 transition-all focus:border-primary-500 focus:outline-none focus:ring-2 focus:ring-primary-500/20 disabled:opacity-50"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(y.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>void O(),disabled:l||!t.trim(),className:"flex items-center gap-2 rounded-lg bg-primary-500 px-5 py-2.5 text-xs font-bold uppercase tracking-wider text-white shadow-[0_0_15px_rgba(79,70,229,0.3)] transition-all hover:shadow-[0_0_20px_rgba(79,70,229,0.5)] disabled:cursor-not-allowed disabled:opacity-30",children:[l?e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}):e.jsx(dt,{size:14}),l?"Analyzing...":"Analyze"]}),l&&e.jsx("button",{onClick:R,className:"rounded-lg border border-gray-700 px-4 py-2.5 text-xs font-bold uppercase tracking-wider text-gray-400 transition-colors hover:border-red-500/50 hover:text-red-400",children:"Cancel"})]})]}),e.jsx(W,{children:d&&e.jsxs(y.div,{initial:{opacity:0,height:0},animate:{opacity:1,height:"auto"},exit:{opacity:0,height:0},className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block h-2 w-2 animate-pulse rounded-full bg-primary-500 shadow-[0_0_10px_var(--color-primary-500)]"}),e.jsx("span",{className:"font-mono text-xs uppercase tracking-widest text-gray-400",children:d})]})}),x&&e.jsx(y.div,{initial:{opacity:0,y:5},animate:{opacity:1,y:0},className:"rounded-lg border border-red-500/20 bg-red-500/5 p-4 text-sm text-red-400",children:x}),M&&e.jsxs("div",{className:"space-y-4",children:[m&&e.jsx(Io,{data:m}),h&&e.jsx($o,{data:h}),N&&N.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"mb-2 text-xs font-semibold uppercase tracking-widest text-gray-500",children:"Concern Signals"}),e.jsx(Eo,{signals:N})]}),b&&e.jsx(Ao,{data:b}),L&&e.jsxs(y.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:"flex flex-wrap items-center gap-3 rounded-lg border border-gray-800 bg-gray-900 p-4",children:[e.jsx($e,{icon:e.jsx(ss,{size:14}),label:"Add to Roadmap",doneLabel:"Added",onClick:()=>void G(),disabled:S!=="idle"&&S!=="roadmap-done"&&S!=="dispatch-done",pending:S==="roadmap-pending",done:S==="roadmap-done"}),e.jsx($e,{icon:e.jsx(oe,{size:14}),label:"Dispatch Now",doneLabel:"Dispatched",onClick:()=>void Y(),disabled:(h==null?void 0:h.recommendedRoute)!=="local"||S!=="idle"&&S!=="roadmap-done"&&S!=="dispatch-done",pending:S==="dispatch-pending",done:S==="dispatch-done",...(h==null?void 0:h.recommendedRoute)!=="local"?{title:"Only available for local-route items"}:{},color:"border-gray-700 text-gray-400 hover:border-emerald-500/50 hover:text-emerald-400"}),e.jsx($e,{icon:e.jsx(xa,{size:14}),label:"Refine",doneLabel:"Refine",onClick:Q,disabled:!m||m.unknowns.length===0&&m.ambiguities.length===0,pending:!1,done:!1,title:"Pre-populate description with unknowns and ambiguities for re-analysis",color:"border-gray-700 text-gray-400 hover:border-amber-500/50 hover:text-amber-400"}),e.jsx($e,{icon:e.jsx(as,{size:14}),label:"Export Spec",doneLabel:"Export Spec",onClick:U,disabled:!m,pending:!1,done:!1,color:"border-gray-700 text-gray-400 hover:border-blue-500/50 hover:text-blue-400"}),w&&e.jsx("span",{className:"text-xs text-red-400",children:w})]})]}),!M&&!l&&!x&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"mb-4 rounded-full bg-primary-500/10 p-4 text-primary-500",children:e.jsx(Ee,{size:32,className:"drop-shadow-[0_0_10px_var(--color-primary-500)]"})}),e.jsx("h2",{className:"mb-1 text-lg font-bold",children:"Intelligence Pipeline"}),e.jsx("p",{className:"max-w-sm text-xs text-gray-500",children:"Submit a work item description to run it through the SEL, CML, and PESL analysis layers. Results stream in real-time."})]})]})}function Do(){const[t,s]=c.useState([]),[a,n]=c.useState(""),[r,i]=c.useState("read-status"),[l,o]=c.useState(null),[d,u]=c.useState(null),x=c.useCallback(async()=>{const p=await fetch("/api/v1/auth/tokens");p.ok&&s(await p.json()??[])},[]);c.useEffect(()=>{x()},[x]);async function f(p){p.preventDefault(),u(null);const h=await fetch("/api/v1/auth/token",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:a,scopes:r.split(",").map(b=>b.trim())})});if(!h.ok){const b=await h.json();u(b.error??"Failed");return}const g=await h.json();o(g),n(""),await x()}async function m(p){window.confirm(`Revoke ${p}?`)&&(await fetch(`/api/v1/auth/tokens/${encodeURIComponent(p)}`,{method:"DELETE"}),await x())}return e.jsxs("div",{className:"space-y-6",children:[e.jsx("h1",{className:"text-xl font-bold",children:"Gateway API Tokens"}),e.jsxs("form",{onSubmit:p=>void f(p),className:"space-y-2 rounded-lg border border-white/10 p-4",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Create token"}),e.jsx("input",{className:"block w-full rounded bg-white/5 px-3 py-2 text-sm",placeholder:"Name (e.g. slack-bot)",value:a,onChange:p=>n(p.target.value),required:!0}),e.jsx("input",{className:"block w-full rounded bg-white/5 px-3 py-2 text-sm",placeholder:"Scopes (comma-separated)",value:r,onChange:p=>i(p.target.value),required:!0}),e.jsx("button",{type:"submit",className:"rounded bg-blue-600 px-4 py-2 text-sm",children:"Create"}),d&&e.jsx("p",{className:"text-sm text-red-400",children:d})]}),l&&e.jsxs("div",{className:"rounded-lg border border-yellow-500/40 bg-yellow-500/10 p-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider",children:"Save this token — shown once."}),e.jsx("code",{className:"mt-2 block break-all text-xs",children:l.token}),e.jsx("button",{onClick:()=>o(null),className:"mt-2 text-xs underline",children:"Dismiss"})]}),e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-left text-xs uppercase tracking-wider text-neutral-muted",children:[e.jsx("th",{className:"py-2",children:"Name"}),e.jsx("th",{children:"Scopes"}),e.jsx("th",{children:"Created"}),e.jsx("th",{children:"Last used"}),e.jsx("th",{})]})}),e.jsx("tbody",{children:t.map(p=>e.jsxs("tr",{className:"border-t border-white/5",children:[e.jsx("td",{className:"py-2",children:p.name}),e.jsx("td",{children:p.scopes.join(", ")}),e.jsx("td",{children:new Date(p.createdAt).toLocaleString()}),e.jsx("td",{children:p.lastUsedAt?new Date(p.lastUsedAt).toLocaleString():"—"}),e.jsx("td",{children:e.jsx("button",{onClick:()=>void m(p.id),className:"text-xs text-red-400 underline",children:"Revoke"})})]},p.id))})]})]})}function Oo(){const[t,s]=c.useState([]),[a,n]=c.useState(""),[r,i]=c.useState("maintenance.completed,interaction.*"),[l,o]=c.useState(null),[d,u]=c.useState(null),[x,f]=c.useState(null),m=c.useCallback(async()=>{const g=await fetch("/api/v1/webhooks");g.ok&&s(await g.json()??[])},[]);c.useEffect(()=>{m()},[m]),c.useEffect(()=>{let g=!0;async function b(){try{const N=await fetch("/api/v1/webhooks/queue/stats");N.ok&&g&&f(await N.json())}catch{}}b();const j=setInterval(()=>void b(),1e3);return()=>{g=!1,clearInterval(j)}},[]);async function p(g){g.preventDefault(),u(null);const b=await fetch("/api/v1/webhooks",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:a,events:r.split(",").map(N=>N.trim())})});if(!b.ok){const N=await b.json();u(N.error??"Failed");return}const j=await b.json();o({id:j.id,secret:j.secret}),n(""),await m()}async function h(g){window.confirm(`Delete subscription ${g}?`)&&(await fetch(`/api/v1/webhooks/${encodeURIComponent(g)}`,{method:"DELETE"}),await m())}return e.jsxs("div",{className:"space-y-6",children:[e.jsx("h1",{className:"text-xl font-bold",children:"Webhook Subscriptions"}),e.jsxs("form",{onSubmit:g=>void p(g),className:"space-y-2 rounded-lg border border-white/10 p-4",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Create subscription"}),e.jsx("input",{className:"block w-full rounded bg-white/5 px-3 py-2 text-sm",placeholder:"URL (https://…)",value:a,onChange:g=>n(g.target.value),required:!0}),e.jsx("input",{className:"block w-full rounded bg-white/5 px-3 py-2 text-sm",placeholder:"Events (comma-separated globs)",value:r,onChange:g=>i(g.target.value),required:!0}),e.jsx("button",{type:"submit",className:"rounded bg-blue-600 px-4 py-2 text-sm",children:"Subscribe"}),d&&e.jsx("p",{className:"text-sm text-red-400",children:d})]}),l&&e.jsxs("div",{className:"rounded-lg border border-yellow-500/30 bg-yellow-900/20 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-yellow-200",children:"Save this secret now — it is never shown again:"}),e.jsx("pre",{className:"mt-2 break-all rounded bg-black/40 p-2 text-xs",children:l.secret}),e.jsxs("p",{className:"mt-2 text-xs text-yellow-200/70",children:["Subscription ID: ",l.id]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h2",{className:"text-sm font-semibold",children:"Active subscriptions"}),t.length===0?e.jsx("p",{className:"text-sm text-neutral-muted",children:"No subscriptions yet."}):e.jsx("ul",{className:"space-y-1",children:t.map(g=>e.jsxs("li",{className:"flex items-center justify-between rounded border border-white/10 px-3 py-2 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-mono text-xs text-neutral-muted",children:g.id}),e.jsx("p",{children:g.url}),e.jsxs("p",{className:"text-xs text-neutral-muted",children:["events: ",g.events.join(", ")]})]}),e.jsx("button",{onClick:()=>void h(g.id),className:"rounded bg-red-600/40 px-3 py-1 text-xs",children:"Delete"})]},g.id))})]}),x!==null&&e.jsxs("div",{className:"rounded-lg border border-white/10 p-4",children:[e.jsx("h2",{className:"mb-2 text-sm font-semibold",children:"Delivery Queue"}),e.jsxs("div",{className:"grid grid-cols-5 gap-2 text-center text-xs",children:[e.jsxs("div",{className:"rounded bg-white/5 p-2",children:[e.jsx("div",{className:"text-lg font-bold",children:x.pending}),e.jsx("div",{className:"text-neutral-muted",children:"Pending"})]}),e.jsxs("div",{className:"rounded bg-white/5 p-2",children:[e.jsx("div",{className:"text-lg font-bold",children:x.failed}),e.jsx("div",{className:"text-neutral-muted",children:"Retrying"})]}),e.jsxs("div",{className:"rounded bg-white/5 p-2",children:[e.jsx("div",{className:"text-lg font-bold",children:x.inFlight}),e.jsx("div",{className:"text-neutral-muted",children:"In flight"})]}),e.jsxs("div",{className:`rounded p-2 ${x.dead>0?"bg-red-900/30":"bg-white/5"}`,children:[e.jsx("div",{className:`text-lg font-bold ${x.dead>0?"text-red-400":""}`,children:x.dead}),e.jsx("div",{className:"text-neutral-muted",children:"Dead"})]}),e.jsxs("div",{className:"rounded bg-white/5 p-2",children:[e.jsx("div",{className:"text-lg font-bold",children:x.delivered}),e.jsx("div",{className:"text-neutral-muted",children:"Delivered"})]})]})]})]})}const Po=5e3,Wt=60;function Fo({values:t,width:s=240,height:a=36}){if(t.length===0)return e.jsx("svg",{width:s,height:a,"aria-label":"empty sparkline"});const n=t.length>1?s/(t.length-1):0,r=t.map((i,l)=>{const o=l*n,d=a-Math.max(0,Math.min(1,i))*a;return`${o.toFixed(2)},${d.toFixed(2)}`}).join(" ");return e.jsx("svg",{width:s,height:a,role:"img","aria-label":`hit-rate trend over last ${t.length} samples`,children:e.jsx("polyline",{points:r,fill:"none",stroke:"currentColor",strokeWidth:1.5})})}function _o(){const[t,s]=c.useState(null),[a,n]=c.useState(null),[r,i]=c.useState([]);if(c.useEffect(()=>{let o=!0;async function d(){try{const x=await fetch("/api/v1/telemetry/cache/stats");if(!o)return;if(!x.ok){x.status===503?(s(null),n(null)):n(`Failed to load (${x.status})`);return}const f=await x.json();if(!o)return;s(f),n(null),i(m=>{const p=[...m,f.hitRate];return p.length>Wt?p.slice(p.length-Wt):p})}catch(x){if(!o)return;n(x instanceof Error?x.message:"Network error")}}d();const u=setInterval(()=>void d(),Po);return()=>{o=!1,clearInterval(u)}},[]),a)return e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:"Prompt Cache"}),e.jsx("p",{className:"text-sm text-red-400",children:a})]});if(t===null||t.totalRequests===0)return e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:"Prompt Cache"}),e.jsx("p",{className:"text-sm text-neutral-muted",children:"No prompt-cache activity recorded yet"})]});const l=(t.hitRate*100).toFixed(1);return e.jsxs("div",{className:"space-y-6",children:[e.jsx("h1",{className:"text-xl font-bold",children:"Prompt Cache"}),e.jsxs("div",{className:"rounded-lg border border-white/10 p-4","data-testid":"cache-hitrate-card",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-neutral-muted",children:"Hit rate"}),e.jsxs("div",{className:"mt-1 flex items-baseline gap-4",children:[e.jsxs("div",{className:"text-5xl font-bold","data-testid":"cache-hitrate-value",children:[l,"%"]}),e.jsxs("div",{className:"text-xs text-neutral-muted",children:[t.hits," hits / ",t.misses," misses / ",t.totalRequests," total"]})]}),e.jsx("div",{className:"mt-3 text-blue-400",children:e.jsx(Fo,{values:r})})]}),e.jsxs("div",{className:"rounded-lg border border-white/10 p-4",children:[e.jsx("h2",{className:"mb-2 text-sm font-semibold",children:"By backend"}),e.jsxs("table",{className:"w-full text-sm","data-testid":"cache-backend-table",children:[e.jsx("thead",{className:"text-xs uppercase text-neutral-muted",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-2 py-1 text-left",children:"Backend"}),e.jsx("th",{className:"px-2 py-1 text-right",children:"Hits"}),e.jsx("th",{className:"px-2 py-1 text-right",children:"Misses"}),e.jsx("th",{className:"px-2 py-1 text-right",children:"Hit rate"})]})}),e.jsx("tbody",{children:Object.entries(t.byBackend).map(([o,d])=>{const u=d.hits+d.misses,x=u===0?0:d.hits/u;return e.jsxs("tr",{className:"border-t border-white/5",children:[e.jsx("td",{className:"px-2 py-1 font-mono text-xs",children:o}),e.jsx("td",{className:"px-2 py-1 text-right",children:d.hits}),e.jsx("td",{className:"px-2 py-1 text-right",children:d.misses}),e.jsxs("td",{className:"px-2 py-1 text-right",children:[(x*100).toFixed(1),"%"]})]},o)})})]})]})]})}const zo=["open","gate-running","gate-failed","approved","rejected","all"];function Bo({status:t}){const s={open:"bg-blue-500/20 text-blue-200","gate-running":"bg-yellow-500/20 text-yellow-200","gate-failed":"bg-red-500/20 text-red-200",approved:"bg-green-500/20 text-green-200",rejected:"bg-neutral-500/20 text-neutral-300"};return e.jsx("span",{className:`inline-block rounded px-2 py-0.5 text-[10px] uppercase ${s[t]}`,children:t})}function Ho({finding:t}){const s=t.severity==="error"?"text-red-300":"text-yellow-300";return e.jsxs("li",{className:"text-xs",children:[e.jsxs("span",{className:`font-semibold ${s}`,children:["[",t.severity,"]"]})," ",e.jsx("span",{className:"font-medium",children:t.title}),e.jsx("p",{className:"text-neutral-muted",children:t.detail})]})}function Wo({proposal:t,onChanged:s}){var S,T;const[a,n]=c.useState(!1),[r,i]=c.useState(null),[l,o]=c.useState(""),[d,u]=c.useState(!1),[x,f]=c.useState(()=>t.kind==="new-skill"?t.content.skillMd??"":t.content.diff??""),m=((S=t.gate)==null?void 0:S.findings)??[],p=!!((T=t.gate)!=null&&T.lastRunAt),h=m.some(w=>w.severity==="error"),g=t.status==="approved"||t.status==="rejected",b=p&&!h&&t.status==="gate-running",j=c.useCallback(async(w,k)=>{n(!0),i(null);try{const $={method:"POST",headers:{"Content-Type":"application/json"}};k&&($.body=JSON.stringify(k));const M=await fetch(`/api/v1/proposals/${t.id}${w}`,$);if(!M.ok){const L=await M.text();throw new Error(`HTTP ${M.status}: ${L}`)}s()}catch($){i($ instanceof Error?$.message:String($))}finally{n(!1)}},[t.id,s]),N=c.useCallback(async w=>{n(!0),i(null);try{const k=await fetch(`/api/v1/proposals/${t.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!k.ok){const $=await k.text();throw new Error(`HTTP ${k.status}: ${$}`)}s()}catch(k){i(k instanceof Error?k.message:String(k))}finally{n(!1)}},[t.id,s]),v=c.useCallback(()=>{const w=t.kind==="new-skill"?{skillMd:x}:{diff:x};return N({content:w})},[t.kind,x,N]);return e.jsxs("div",{className:"rounded-lg border border-white/10 p-4",children:[e.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("h3",{className:"text-base font-semibold",children:[t.kind==="refinement"?"↻ ":"+ ",t.content.name]}),e.jsx(Bo,{status:t.status})]}),e.jsxs("p",{className:"mt-0.5 text-xs text-neutral-muted",children:[t.kind==="refinement"&&t.targetSkill?`Refines ${t.targetSkill} — `:"","proposed by ",e.jsx("span",{className:"font-mono",children:t.proposedBy})," at"," ",new Date(t.createdAt).toLocaleString()]})]}),e.jsx("span",{className:"font-mono text-[10px] text-neutral-muted",children:t.id})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"md:col-span-2 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"mb-1 text-xs font-semibold text-neutral-muted",children:"Justification"}),e.jsx("p",{className:"text-sm",children:t.source.justification})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between",children:[e.jsx("h4",{className:"text-xs font-semibold text-neutral-muted",children:t.kind==="new-skill"?"SKILL.md":"Unified diff"}),!g&&e.jsx("button",{className:"rounded bg-white/10 px-2 py-0.5 text-[11px]",onClick:()=>u(w=>!w),type:"button",children:d?"Cancel":"Edit"})]}),d?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{className:"block h-48 w-full rounded bg-black/40 p-2 font-mono text-[11px]",value:x,onChange:w=>f(w.target.value)}),e.jsx("button",{type:"button",className:"rounded bg-blue-600 px-3 py-1 text-xs",disabled:a,onClick:()=>void v().then(()=>u(!1)),children:"Save (resets gate)"})]}):e.jsx("pre",{className:"max-h-64 overflow-y-auto rounded bg-black/40 p-2 font-mono text-[11px] whitespace-pre-wrap",children:t.kind==="new-skill"?t.content.skillMd??"(no markdown)":t.content.diff??"(no diff)"})]}),t.kind==="new-skill"&&e.jsxs("div",{children:[e.jsx("h4",{className:"mb-1 text-xs font-semibold text-neutral-muted",children:"skill.yaml"}),e.jsx("pre",{className:"max-h-48 overflow-y-auto rounded bg-black/40 p-2 font-mono text-[11px]",children:t.content.skillYaml??"(no yaml)"})]})]}),e.jsxs("aside",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded border border-white/10 p-3",children:[e.jsx("h4",{className:"mb-2 text-xs font-semibold uppercase text-neutral-muted",children:"Soundness gate"}),p?e.jsxs("div",{className:"space-y-2 text-xs",children:[e.jsxs("p",{className:"text-neutral-muted",children:["Ran ",new Date(t.gate.lastRunAt).toLocaleString()]}),m.length===0?e.jsx("p",{className:"text-green-300",children:"No findings."}):e.jsx("ul",{className:"space-y-2",children:m.map((w,k)=>e.jsx(Ho,{finding:w},k))})]}):e.jsx("p",{className:"text-xs text-neutral-muted",children:"Not yet run."}),!g&&e.jsx("button",{type:"button",disabled:a,onClick:()=>void j("/run-gate"),className:"mt-3 w-full rounded bg-blue-600 px-3 py-1 text-xs",children:"Run gate"})]}),!g&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("button",{type:"button",disabled:a||!b,onClick:()=>void j("/approve",{decidedBy:"dashboard-reviewer"}),className:`w-full rounded px-3 py-1 text-xs ${b?"bg-green-600":"bg-green-900/40 text-neutral-muted"}`,title:b?"":"Run gate with no errors before approving",children:"Approve"}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("input",{className:"block w-full rounded bg-white/5 px-2 py-1 text-xs",placeholder:"Rejection reason",value:l,onChange:w=>o(w.target.value)}),e.jsx("button",{type:"button",disabled:a||!l.trim(),onClick:()=>void j("/reject",{reason:l.trim()}),className:`w-full rounded px-3 py-1 text-xs ${l.trim()?"bg-red-600":"bg-red-900/40 text-neutral-muted"}`,children:"Reject"})]})]}),g&&t.decision&&e.jsxs("div",{className:"rounded border border-white/10 p-3 text-xs",children:[e.jsx("p",{className:"font-semibold capitalize",children:t.decision.action}),e.jsxs("p",{className:"text-neutral-muted",children:["by ",t.decision.decidedBy," at"," ",new Date(t.decision.decidedAt).toLocaleString()]}),t.decision.reason&&e.jsxs("p",{className:"mt-1",children:["Reason: ",t.decision.reason]})]}),r&&e.jsx("p",{className:"text-xs text-red-300",children:r})]})]})]})}function Go(){const[t,s]=c.useState([]),[a,n]=c.useState("open"),[r,i]=c.useState(!0),[l,o]=c.useState(null),d=c.useCallback(async()=>{i(!0),o(null);try{const u=await fetch(`/api/v1/proposals?status=${encodeURIComponent(a)}`);if(!u.ok)throw new Error(`HTTP ${u.status}`);s(await u.json())}catch(u){o(u instanceof Error?u.message:String(u)),s([])}finally{i(!1)}},[a]);return c.useEffect(()=>{d()},[d]),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("header",{className:"flex items-center justify-between",children:[e.jsx("h1",{className:"text-xl font-bold",children:"Skill proposals"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{htmlFor:"proposal-status",className:"text-xs text-neutral-muted",children:"Status"}),e.jsx("select",{id:"proposal-status",className:"rounded bg-white/5 px-2 py-1 text-xs",value:a,onChange:u=>n(u.target.value),children:zo.map(u=>e.jsx("option",{value:u,children:u},u))}),e.jsx("button",{type:"button",onClick:()=>void d(),className:"rounded bg-white/10 px-2 py-1 text-xs",children:"Refresh"})]})]}),l&&e.jsx("p",{className:"text-sm text-red-300",children:l}),r?e.jsx("p",{className:"text-sm text-neutral-muted",children:"Loading…"}):t.length===0?e.jsx("p",{className:"text-sm text-neutral-muted",children:"No proposals match the current filter."}):e.jsx("div",{className:"space-y-3",children:t.map(u=>e.jsx(Wo,{proposal:u,onChanged:()=>void d()},u.id))})]})}function Uo(){const[t,s]=c.useState(null),[a,n]=c.useState(!0),[r,i]=c.useState(null);return c.useEffect(()=>{const l=new AbortController;return(async()=>{try{const o=await fetch("/api/v1/routing/config",{signal:l.signal});if(!o.ok){i(`HTTP ${o.status}`),n(!1);return}const d=await o.json();s(d),n(!1)}catch(o){if(l.signal.aborted)return;i(o instanceof Error?o.message:"Network error"),n(!1)}})(),()=>l.abort()},[]),{config:t,loading:a,error:r}}const qo=1e3,Yo=3e4,Vo=5e3,rt=500;function Jo(){return`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws`}async function Gt(t){const s=t?{signal:t}:{},a=await fetch(`/api/v1/routing/decisions?limit=${rt}`,s);if(!a.ok)throw new Error(`HTTP ${a.status}`);return(await a.json()).decisions}function Xo(){const[t,s]=c.useState([]),[a,n]=c.useState("connecting"),[r,i]=c.useState(null),l=c.useRef(null),o=c.useRef(null),d=c.useRef(0),u=c.useRef(null);return c.useEffect(()=>{const x=new AbortController;return Gt(x.signal).then(f=>s(f)).catch(f=>{x.signal.aborted||i(f instanceof Error?f.message:String(f))}),()=>x.abort()},[]),c.useEffect(()=>{const x={current:!0};function f(){u.current||(u.current=setInterval(()=>{Gt().then(h=>{x.current&&s(h)}).catch(()=>{})},Vo))}function m(){u.current&&(clearInterval(u.current),u.current=null)}function p(){const h=new WebSocket(Jo());l.current=h,h.onopen=()=>{x.current&&(d.current=0,m(),n("live"))},h.onmessage=g=>{if(x.current)try{const b=JSON.parse(g.data);if(typeof b!="object"||b===null||!("type"in b))return;const j=b;j.type==="routing:decision"&&s(N=>{const v=[j.data,...N];return v.length>rt?v.slice(0,rt):v})}catch{}},h.onclose=()=>{if(!x.current)return;n("polling"),f();const g=Math.min(qo*2**d.current,Yo);d.current+=1,o.current=setTimeout(p,g)},h.onerror=()=>{}}return p(),()=>{var h;x.current=!1,(h=l.current)==null||h.close(),o.current&&clearTimeout(o.current),m()}},[]),{decisions:t,status:a,error:r}}function Ko(t){switch(t.kind){case"skill":return`skill:${t.skillName}`;case"mode":return`mode:${t.cognitiveMode}`;case"tier":return`tier:${t.tier}`;case"intelligence":return`intelligence:${t.layer}`;case"isolation":return`isolation:${t.tier}`;case"maintenance":return"maintenance";case"chat":return"default";default:return"default"}}function Qo({resolvedChains:t,decisions:s}){const a=new Map;for(const n of s){const r=Ko(n.useCase);a.has(r)||a.set(r,n.backendName)}return e.jsxs("section",{"data-testid":"routing-card-chains",className:"rounded-xl border border-white/[0.06] bg-neutral-surface/30 p-4 backdrop-blur-sm",children:[e.jsx("header",{className:"mb-3 text-sm font-bold uppercase tracking-wide text-neutral-muted",children:"Resolved Chains"}),e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-neutral-muted",children:[e.jsx("th",{className:"py-1 pr-3",children:"Use case"}),e.jsx("th",{className:"py-1 pr-3",children:"Chain"}),e.jsx("th",{className:"py-1",children:"Currently chosen"})]})}),e.jsx("tbody",{children:Object.entries(t).map(([n,r])=>{const i=a.get(n);return e.jsxs("tr",{"data-testid":`chain-row-${n}`,className:"border-t border-white/[0.04]",children:[e.jsx("td",{className:"py-1 pr-3 font-mono",children:n}),e.jsx("td",{className:"py-1 pr-3",children:r.map((l,o)=>e.jsxs("span",{"data-testid":l.exists?"chain-step-chosen":"chain-step-unknown",className:l.exists?"text-emerald-300":"text-rose-400 line-through opacity-70",children:[l.candidate,o<r.length-1?" → ":""]},`${l.candidate}-${o}`))}),e.jsx("td",{className:"py-1 font-mono","data-testid":`currently-chosen-${n}`,children:i??"—"})]},n)})})]})]})}function Zo(t){return t.kind==="skill"?t.skillName:null}function ec(t){return t.kind==="mode"||t.kind==="skill"&&t.cognitiveMode?t.cognitiveMode:null}function tc(t){switch(t.kind){case"skill":return`skill:${t.skillName}${t.cognitiveMode?`@${t.cognitiveMode}`:""}`;case"mode":return`mode:${t.cognitiveMode}`;case"tier":return`tier:${t.tier}`;case"intelligence":return`intelligence:${t.layer}`;case"isolation":return`isolation:${t.tier}`;case"maintenance":return"maintenance";case"chat":return"chat";default:return"unknown"}}function sc({decisions:t,status:s,error:a}){const[n,r]=c.useState(""),[i,l]=c.useState(""),[o,d]=c.useState(""),[u,x]=c.useState(null),f=c.useMemo(()=>t.filter(m=>{if(n){const p=Zo(m.useCase);if(!p||!p.includes(n))return!1}if(i){const p=ec(m.useCase);if(!p||!p.includes(i))return!1}return!(o&&!m.backendName.includes(o))}),[t,n,i,o]);return e.jsxs("section",{"data-testid":"routing-card-decisions",className:"rounded-xl border border-white/[0.06] bg-neutral-surface/30 p-4 backdrop-blur-sm",children:[e.jsxs("header",{className:"mb-3 flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-bold uppercase tracking-wide text-neutral-muted",children:"Recent Decisions"}),e.jsx("span",{"data-testid":"routing-ws-status",className:s==="live"?"text-xs text-emerald-300":s==="polling"?"text-xs text-amber-300":"text-xs text-neutral-muted",children:s})]}),e.jsxs("div",{className:"mb-3 flex gap-2 text-xs",children:[e.jsx("input",{"data-testid":"decision-filter-skill",placeholder:"filter skill…",value:n,onChange:m=>r(m.target.value),className:"rounded border border-white/[0.08] bg-neutral-bg/50 px-2 py-1"}),e.jsx("input",{"data-testid":"decision-filter-mode",placeholder:"filter mode…",value:i,onChange:m=>l(m.target.value),className:"rounded border border-white/[0.08] bg-neutral-bg/50 px-2 py-1"}),e.jsx("input",{"data-testid":"decision-filter-backend",placeholder:"filter backend…",value:o,onChange:m=>d(m.target.value),className:"rounded border border-white/[0.08] bg-neutral-bg/50 px-2 py-1"})]}),a?e.jsx("p",{"data-testid":"decisions-error",className:"text-xs text-rose-400",children:a}):null,f.length===0?e.jsx("p",{"data-testid":"decisions-empty",className:"text-xs text-neutral-muted",children:"No routing decisions recorded yet."}):e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-neutral-muted",children:[e.jsx("th",{className:"py-1 pr-3",children:"Time"}),e.jsx("th",{className:"py-1 pr-3",children:"Use case"}),e.jsx("th",{className:"py-1 pr-3",children:"Backend"}),e.jsx("th",{className:"py-1",children:"ms"})]})}),e.jsx("tbody",{children:f.map((m,p)=>e.jsx(ac,{decision:m,index:p,expanded:u===p,onToggle:()=>x(h=>h===p?null:p)},`${m.timestamp}-${p}`))})]})]})}function ac({decision:t,index:s,expanded:a,onToggle:n}){return e.jsxs(e.Fragment,{children:[e.jsxs("tr",{"data-testid":`decision-row-${s}`,onClick:n,className:"cursor-pointer border-t border-white/[0.04] hover:bg-white/[0.04]",children:[e.jsx("td",{className:"py-1 pr-3 font-mono text-[10px] text-neutral-muted",children:new Date(t.timestamp).toLocaleTimeString()}),e.jsx("td",{className:"py-1 pr-3 font-mono",children:tc(t.useCase)}),e.jsx("td",{className:"py-1 pr-3 font-mono",children:t.backendName}),e.jsx("td",{className:"py-1",children:t.durationMs})]}),a?e.jsx("tr",{children:e.jsx("td",{colSpan:4,"data-testid":`decision-row-${s}-expanded`,className:"bg-black/30 p-2",children:e.jsx("ol",{className:"ml-4 list-decimal text-[11px]",children:t.resolutionPath.map((r,i)=>e.jsxs("li",{className:"font-mono",children:[e.jsx("span",{className:"text-neutral-muted",children:r.source})," → ",e.jsx("span",{children:r.candidate})," (",e.jsx("span",{className:r.outcome==="chosen"?"text-emerald-300":r.outcome==="unknown-backend"?"text-rose-400":"text-neutral-muted",children:r.outcome}),")"]},i))})})}):null]})}const nc=1440*60*1e3;function rc({decisions:t,backends:s}){const a=c.useMemo(()=>{const r=Date.now()-nc,i=Object.fromEntries(s.map(l=>[l,0]));for(const l of t){const o=new Date(l.timestamp).getTime();Number.isNaN(o)||o<r||(l.backendName in i||(i[l.backendName]=0),i[l.backendName]=(i[l.backendName]??0)+1)}return i},[t,s]),n=Object.entries(a).sort(([r],[i])=>r.localeCompare(i));return e.jsxs("section",{"data-testid":"routing-card-volume",className:"rounded-xl border border-white/[0.06] bg-neutral-surface/30 p-4 backdrop-blur-sm",children:[e.jsx("header",{className:"mb-3 text-sm font-bold uppercase tracking-wide text-neutral-muted",children:"Per-Backend Volume (24h)"}),e.jsxs("table",{className:"w-full text-left text-xs",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-neutral-muted",children:[e.jsx("th",{className:"py-1 pr-3",children:"Backend"}),e.jsx("th",{className:"py-1 pr-3",children:"Count"}),e.jsx("th",{className:"py-1",children:"Success rate"})]})}),e.jsx("tbody",{children:n.map(([r,i])=>e.jsxs("tr",{className:"border-t border-white/[0.04]",children:[e.jsx("td",{className:"py-1 pr-3 font-mono",children:r}),e.jsx("td",{className:"py-1 pr-3 font-mono","data-testid":`volume-count-${r}`,children:i}),e.jsx("td",{className:"py-1 font-mono","data-testid":`volume-rate-${r}`,children:i>0?"100%":"—"})]},r))})]})]})}function ic(){const[t,s]=c.useState(""),[a,n]=c.useState(""),[r,i]=c.useState(null),[l,o]=c.useState(null),[d,u]=c.useState(null),[x,f]=c.useState(!1);function m(){const h=t.trim(),g=a.trim();return h&&g?{kind:"skill",skillName:h,cognitiveMode:g}:h?{kind:"skill",skillName:h}:g?{kind:"mode",cognitiveMode:g}:null}function p(h){h.preventDefault(),o(null),u(null),i(null);const g=m();if(!g){u("Provide a skill or a mode.");return}f(!0),(async()=>{try{const b=await fetch("/api/v1/routing/trace",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({useCase:g})});if(!b.ok){const N=await b.text();o(N||`HTTP ${b.status}`);return}const j=await b.json();i(j)}catch(b){o(b instanceof Error?b.message:String(b))}finally{f(!1)}})()}return e.jsxs("section",{"data-testid":"routing-card-trace",className:"rounded-xl border border-white/[0.06] bg-neutral-surface/30 p-4 backdrop-blur-sm",children:[e.jsx("header",{className:"mb-3 text-sm font-bold uppercase tracking-wide text-neutral-muted",children:"Trace"}),e.jsxs("form",{onSubmit:p,className:"space-y-2 text-xs",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"block text-neutral-muted",children:"Skill"}),e.jsx("input",{type:"text",name:"skill","aria-label":"skill",value:t,onChange:h=>s(h.target.value),className:"mt-1 w-full rounded border border-white/[0.08] bg-neutral-bg/50 px-2 py-1"})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"block text-neutral-muted",children:"Mode"}),e.jsx("input",{type:"text",name:"mode","aria-label":"mode",value:a,onChange:h=>n(h.target.value),className:"mt-1 w-full rounded border border-white/[0.08] bg-neutral-bg/50 px-2 py-1"})]}),e.jsx("button",{type:"submit",disabled:x,className:"rounded bg-emerald-500/20 px-3 py-1 text-emerald-200 hover:bg-emerald-500/30 disabled:opacity-50",children:x?"Tracing…":"Trace"}),d?e.jsx("p",{className:"text-rose-400",children:d}):null]}),l?e.jsx("p",{"data-testid":"trace-error",className:"mt-3 text-xs text-rose-400",children:l}):null,r?e.jsxs("div",{className:"mt-3 space-y-1 text-xs",children:[e.jsxs("p",{children:[e.jsx("span",{className:"text-neutral-muted",children:"Backend: "}),e.jsx("span",{"data-testid":"trace-backend",className:"font-mono",children:r.decision.backendName})]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-neutral-muted",children:"Type: "}),e.jsx("span",{"data-testid":"trace-backend-type",className:"font-mono",children:r.def.type})]}),e.jsx("ol",{"data-testid":"trace-resolution-path",className:"ml-4 list-decimal text-[11px] font-mono",children:r.decision.resolutionPath.map((h,g)=>e.jsxs("li",{children:[e.jsx("span",{className:"text-neutral-muted",children:h.source})," → ",e.jsx("span",{children:h.candidate})," (",e.jsx("span",{className:h.outcome==="chosen"?"text-emerald-300":h.outcome==="unknown-backend"?"text-rose-400":"text-neutral-muted",children:h.outcome}),")"]},g))})]}):null]})}function lc(){const{config:t,loading:s,error:a}=Uo(),{decisions:n,status:r,error:i}=Xo();return s?e.jsx("p",{"data-testid":"routing-loading",className:"text-xs text-neutral-muted",children:"Loading routing configuration…"}):a||!t?e.jsxs("p",{"data-testid":"routing-error",className:"text-xs text-rose-400",children:["Failed to load routing config: ",a??"unknown error"]}):e.jsxs("div",{className:"grid grid-cols-1 gap-6 lg:grid-cols-2",children:[e.jsx(Qo,{resolvedChains:t.resolvedChains,decisions:n}),e.jsx(sc,{decisions:n,status:r,error:i}),e.jsx(rc,{decisions:n,backends:t.backends}),e.jsx(ic,{})]})}const oc={health:ji,graph:Si,impact:_i,decay:qi,traceability:Zi,orchestrator:fl,maintenance:Cl,streams:Ol,roadmap:xo,adoption:yo,tokens:Do,webhooks:Oo,"insights-cache":_o,proposals:Go,routing:lc,attention:ko,analyze:Lo};function cc({type:t,title:s}){return e.jsx("div",{className:"flex flex-1 flex-col items-center justify-center text-center",children:e.jsxs("div",{className:"rounded-xl border border-white/[0.06] bg-neutral-surface/30 px-8 py-6 backdrop-blur-sm",children:[e.jsxs("p",{className:"text-[10px] font-black uppercase tracking-[0.2em] text-neutral-muted mb-2",children:[t," thread"]}),e.jsx("h3",{className:"text-lg font-bold text-white",children:s}),e.jsx("p",{className:"text-xs text-neutral-muted mt-2",children:"Thread view will be implemented in upcoming phases."})]})})}function dc(){const{threadId:t}=qt(),s=E(n=>t?n.threads.get(t):void 0),a=E(n=>n.hydrated);if(c.useEffect(()=>{t&&E.getState().setActiveThread(t)},[t]),!s&&!a)return e.jsx("div",{className:"flex flex-1 flex-col items-center justify-center text-center text-neutral-muted",children:e.jsx("p",{className:"text-xs animate-pulse",children:"Loading thread…"})});if(!s)return e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center text-center text-neutral-muted",children:[e.jsx("p",{className:"text-sm",children:"Thread not found."}),e.jsx("p",{className:"text-xs mt-1",children:"It may have been closed or does not exist yet."})]});switch(s.type){case"chat":return e.jsx(Er,{thread:s});case"attention":return e.jsx(Fr,{thread:s});case"agent":return e.jsx(Gr,{thread:s});case"analysis":return e.jsx(Yr,{thread:s});default:return e.jsx(cc,{type:s.type,title:s.title})}}function xc(){const{systemPage:t}=qt();if(!t)return e.jsx(us,{});const s=oc[t];return s?e.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:e.jsx("div",{className:"mx-auto max-w-7xl",children:e.jsx(s,{})})}):e.jsx("div",{className:"flex flex-1 flex-col items-center justify-center text-center text-neutral-muted",children:e.jsxs("p",{className:"text-sm",children:["Unknown system page: ",t]})})}function uc(){const t=E(n=>n.lastThreadId),s=E(n=>t?n.threads.get(t):void 0),a=X();return c.useEffect(()=>{s&&t&&a(`/t/${t}`,{replace:!0})},[s,t,a]),s?null:e.jsx(us,{})}const mc=[{from:"/intelligence/health",to:"/s/health"},{from:"/intelligence/graph",to:"/s/graph"},{from:"/intelligence/impact",to:"/s/impact"},{from:"/intelligence/decay",to:"/s/decay"},{from:"/intelligence/traceability",to:"/s/traceability"},{from:"/agents",to:"/s/orchestrator"},{from:"/agents/attention",to:"/s/attention"},{from:"/agents/analyze",to:"/s/analyze"},{from:"/agents/maintenance",to:"/s/maintenance"},{from:"/agents/streams",to:"/s/streams"},{from:"/roadmap",to:"/s/roadmap"},{from:"/roadmap/adoption",to:"/s/adoption"},{from:"/health",to:"/s/health"},{from:"/graph",to:"/s/graph"},{from:"/impact",to:"/s/impact"},{from:"/decay-trends",to:"/s/decay"},{from:"/traceability",to:"/s/traceability"},{from:"/orchestrator",to:"/s/orchestrator"},{from:"/orchestrator/attention",to:"/s/attention"},{from:"/orchestrator/analyze",to:"/s/analyze"},{from:"/orchestrator/chat",to:"/"},{from:"/orchestrator/maintenance",to:"/s/maintenance"},{from:"/orchestrator/streams",to:"/s/streams"},{from:"/adoption",to:"/s/adoption"},{from:"/insights/cache",to:"/s/insights-cache"},{from:"/proposals",to:"/s/proposals"},{from:"/routing",to:"/s/routing"}],Ut=document.getElementById("root");Ut&&Ls.createRoot(Ut).render(e.jsx(c.StrictMode,{children:e.jsx(Wa,{children:e.jsx(Ps,{children:e.jsx(vn,{children:e.jsxs(Fs,{children:[e.jsx(Se,{path:"/",element:e.jsx(uc,{})}),e.jsx(Se,{path:"/t/:threadId",element:e.jsx(dc,{})}),e.jsx(Se,{path:"/s/:systemPage",element:e.jsx(xc,{})}),mc.map(({from:t,to:s})=>e.jsx(Se,{path:t,element:e.jsx(_s,{to:s,replace:!0})},t))]})})})})}));