nlm-memory 0.5.5 → 0.5.7

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.
Files changed (41) hide show
  1. package/README.md +1 -0
  2. package/dist/cli/nlm.js +10 -27
  3. package/dist/cli/nlm.js.map +1 -1
  4. package/dist/core/adapters/codex.d.ts +40 -0
  5. package/dist/core/adapters/codex.js +223 -0
  6. package/dist/core/adapters/codex.js.map +1 -0
  7. package/dist/core/adapters/from-source.js +5 -0
  8. package/dist/core/adapters/from-source.js.map +1 -1
  9. package/dist/core/digest/hook-liveness.d.ts +1 -2
  10. package/dist/core/digest/hook-liveness.js +1 -2
  11. package/dist/core/digest/hook-liveness.js.map +1 -1
  12. package/dist/core/hook/claude-settings.d.ts +0 -13
  13. package/dist/core/hook/claude-settings.js +1 -37
  14. package/dist/core/hook/claude-settings.js.map +1 -1
  15. package/dist/core/sources/source-registry.d.ts +1 -1
  16. package/dist/core/sources/source-registry.js +9 -0
  17. package/dist/core/sources/source-registry.js.map +1 -1
  18. package/dist/core/storage/sqlite-session-store.d.ts +1 -0
  19. package/dist/core/storage/sqlite-session-store.js +24 -0
  20. package/dist/core/storage/sqlite-session-store.js.map +1 -1
  21. package/dist/core/storage/supersedence-log.d.ts +16 -0
  22. package/dist/core/storage/supersedence-log.js +33 -0
  23. package/dist/core/storage/supersedence-log.js.map +1 -0
  24. package/dist/hook/stop-hook.d.ts +1 -3
  25. package/dist/hook/stop-hook.js +1 -3
  26. package/dist/hook/stop-hook.js.map +1 -1
  27. package/dist/http/app.js +1 -1
  28. package/dist/http/app.js.map +1 -1
  29. package/dist/install/claude-code.d.ts +0 -6
  30. package/dist/install/claude-code.js +2 -7
  31. package/dist/install/claude-code.js.map +1 -1
  32. package/dist/install/setup.d.ts +0 -5
  33. package/dist/install/setup.js +0 -3
  34. package/dist/install/setup.js.map +1 -1
  35. package/dist/mcp/server.d.ts +6 -0
  36. package/dist/mcp/server.js +66 -1
  37. package/dist/mcp/server.js.map +1 -1
  38. package/dist/ports/session-store.d.ts +10 -0
  39. package/dist/ui/assets/{index-DGiHGtWC.js → index-DlxeCktE.js} +1 -1
  40. package/dist/ui/index.html +1 -1
  41. package/package.json +1 -1
@@ -66,4 +66,4 @@ Error generating stack: `+a.message+`
66
66
  * @license MIT
67
67
  */function zl(){return zl=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},zl.apply(this,arguments)}function kd(e,t){if(e==null)return{};var n={},r=Object.keys(e),l,a;for(a=0;a<r.length;a++)l=r[a],!(t.indexOf(l)>=0)&&(n[l]=e[l]);return n}function Jh(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Zh(e,t){return e.button===0&&(!t||t==="_self")&&!Jh(e)}function La(e){return e===void 0&&(e=""),new URLSearchParams(typeof e=="string"||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(l=>[n,l]):[[n,r]])},[]))}function qh(e,t){let n=La(e);return t&&t.forEach((r,l)=>{n.has(l)||t.getAll(l).forEach(a=>{n.append(l,a)})}),n}const em=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],tm=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],nm="6";try{window.__reactRouterVersion=nm}catch{}const rm=x.createContext({isTransitioning:!1}),lm="startTransition",Ko=Qd[lm];function sm(e){let{basename:t,children:n,future:r,window:l}=e,a=x.useRef();a.current==null&&(a.current=ah({window:l,v5Compat:!0}));let i=a.current,[o,u]=x.useState({action:i.action,location:i.location}),{v7_startTransition:d}=r||{},h=x.useCallback(f=>{d&&Ko?Ko(()=>u(f)):u(f)},[u,d]);return x.useLayoutEffect(()=>i.listen(h),[i,h]),x.useEffect(()=>Qh(r),[r]),x.createElement(Xh,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:i,future:r})}const am=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",im=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,Pr=x.forwardRef(function(t,n){let{onClick:r,relative:l,reloadDocument:a,replace:i,state:o,target:u,to:d,preventScrollReset:h,viewTransition:f}=t,m=kd(t,em),{basename:k}=x.useContext(ct),y,N=!1;if(typeof d=="string"&&im.test(d)&&(y=d,am))try{let v=new URL(window.location.href),g=d.startsWith("//")?new URL(v.protocol+d):new URL(d),j=En(g.pathname,k);g.origin===v.origin&&j!=null?d=j+g.search+g.hash:N=!0}catch{}let S=Mh(d,{relative:l}),p=um(d,{replace:i,state:o,target:u,preventScrollReset:h,relative:l,viewTransition:f});function c(v){r&&r(v),v.defaultPrevented||p(v)}return x.createElement("a",zl({},m,{href:y||S,onClick:N||a?r:c,ref:n,target:u}))}),Ta=x.forwardRef(function(t,n){let{"aria-current":r="page",caseSensitive:l=!1,className:a="",end:i=!1,style:o,to:u,viewTransition:d,children:h}=t,f=kd(t,tm),m=ql(u,{relative:f.relative}),k=$t(),y=x.useContext(gd),{navigator:N,basename:S}=x.useContext(ct),p=y!=null&&cm(m)&&d===!0,c=N.encodeLocation?N.encodeLocation(m).pathname:m.pathname,v=k.pathname,g=y&&y.navigation&&y.navigation.location?y.navigation.location.pathname:null;l||(v=v.toLowerCase(),g=g?g.toLowerCase():null,c=c.toLowerCase()),g&&S&&(g=En(g,S)||g);const j=c!=="/"&&c.endsWith("/")?c.length-1:c.length;let w=v===c||!i&&v.startsWith(c)&&v.charAt(j)==="/",C=g!=null&&(g===c||!i&&g.startsWith(c)&&g.charAt(c.length)==="/"),_={isActive:w,isPending:C,isTransitioning:p},$=w?r:void 0,T;typeof a=="function"?T=a(_):T=[a,w?"active":null,C?"pending":null,p?"transitioning":null].filter(Boolean).join(" ");let D=typeof o=="function"?o(_):o;return x.createElement(Pr,zl({},f,{"aria-current":$,className:T,ref:n,style:D,to:u,viewTransition:d}),typeof h=="function"?h(_):h)});var Ra;(function(e){e.UseScrollRestoration="useScrollRestoration",e.UseSubmit="useSubmit",e.UseSubmitFetcher="useSubmitFetcher",e.UseFetcher="useFetcher",e.useViewTransitionState="useViewTransitionState"})(Ra||(Ra={}));var Qo;(function(e){e.UseFetcher="useFetcher",e.UseFetchers="useFetchers",e.UseScrollRestoration="useScrollRestoration"})(Qo||(Qo={}));function om(e){let t=x.useContext(Jl);return t||ee(!1),t}function um(e,t){let{target:n,replace:r,state:l,preventScrollReset:a,relative:i,viewTransition:o}=t===void 0?{}:t,u=_r(),d=$t(),h=ql(e,{relative:i});return x.useCallback(f=>{if(Zh(f,n)){f.preventDefault();let m=r!==void 0?r:Ol(d)===Ol(h);u(e,{replace:m,state:l,preventScrollReset:a,relative:i,viewTransition:o})}},[d,u,h,r,l,n,e,a,i,o])}function Sd(e){let t=x.useRef(La(e)),n=x.useRef(!1),r=$t(),l=x.useMemo(()=>qh(r.search,n.current?null:t.current),[r.search]),a=_r(),i=x.useCallback((o,u)=>{const d=La(typeof o=="function"?o(l):o);n.current=!0,a("?"+d,u)},[a,l]);return[l,i]}function cm(e,t){t===void 0&&(t={});let n=x.useContext(rm);n==null&&ee(!1);let{basename:r}=om(Ra.useViewTransitionState),l=ql(e,{relative:t.relative});if(!n.isTransitioning)return!1;let a=En(n.currentLocation.pathname,r)||n.currentLocation.pathname,i=En(n.nextLocation.pathname,r)||n.nextLocation.pathname;return _a(l.pathname,i)!=null||_a(l.pathname,a)!=null}const Yo="nlm.sidenav.collapsed",dm=[{to:"/live",label:"Live",icon:pm()},{to:"/pulse",label:"Pulse",icon:hm()},{to:"/river",label:"River",icon:mm()},{to:"/thread",label:"Thread",icon:vm()},{to:"/search",label:"Search",icon:gm()},{to:"/recall",label:"Recall",icon:ym()},{to:"/settings",label:"Settings",icon:xm()}];function fm(){const[e,t]=x.useState(()=>typeof window>"u"?!1:window.localStorage.getItem(Yo)==="1");return x.useEffect(()=>{document.body.style.setProperty("--sidenav-w",e?"52px":"180px"),window.localStorage.setItem(Yo,e?"1":"0")},[e]),s.jsxs("nav",{className:`sidenav${e?" collapsed":""}`,"aria-label":"Primary navigation",children:[s.jsxs("div",{className:"sidenav-header",children:[s.jsx("span",{className:"sidenav-wordmark",children:"NLM"}),s.jsx("button",{className:"sidenav-toggle","aria-label":"Toggle sidebar",onClick:()=>t(n=>!n),children:e?Nm():wm()})]}),s.jsx("div",{className:"sidenav-items",children:dm.map(n=>s.jsxs(Ta,{to:n.to,className:({isActive:r})=>`sidenav-item${r?" active":""}`,"data-label":n.label,children:[s.jsx("span",{className:"item-icon",children:n.icon}),s.jsx("span",{className:"item-label",children:n.label})]},n.to))}),s.jsx("div",{className:"sidenav-footer",children:s.jsxs(Ta,{to:"/settings/data",className:"sidenav-item sidenav-data","data-label":"Data",children:[s.jsx("span",{className:"item-icon",children:jm()}),s.jsx("span",{className:"item-label",children:"Data"})]})})]})}function Gt(e,t=16){return s.jsx("svg",{width:t,height:t,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.75,strokeLinecap:"round",strokeLinejoin:"round",children:e})}function pm(){return Gt(s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19 12a7 7 0 00-14 0M22 12a10 10 0 00-20 0"})]}))}function hm(){return Gt(s.jsx("polyline",{points:"22 12 18 12 15 21 9 3 6 12 2 12"}))}function mm(){return Gt(s.jsx("path",{d:"M2 12c1.5-3 3-4.5 4.5-4.5S9 9 10.5 12s3 4.5 4.5 4.5S18 15 19.5 12 21 7.5 22 7.5"}))}function vm(){return Gt(s.jsxs(s.Fragment,{children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 01-9 9"})]}))}function gm(){return Gt(s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]}))}function ym(){return Gt(s.jsxs(s.Fragment,{children:[s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"13"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"9"})]}))}function xm(){return Gt(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]}))}function jm(){return s.jsxs("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:1.75,strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("ellipse",{cx:"12",cy:"5",rx:"9",ry:"3"}),s.jsx("path",{d:"M21 12c0 1.657-4.03 3-9 3S3 13.657 3 12"}),s.jsx("path",{d:"M3 5v14c0 1.657 4.03 3 9 3s9-1.343 9-3V5"})]})}function wm(){return s.jsx("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Nm(){return s.jsx("svg",{width:14,height:14,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("polyline",{points:"9 18 15 12 9 6"})})}async function km(e){const t=await fetch(e);if(!t.ok)throw new Error(`${e} → ${t.status}`);return t.json()}function er(e,t,n){const[r,l]=x.useState({data:n,error:null,lastUpdated:null,loading:!0});return x.useEffect(()=>{let a=!1;const i=async()=>{try{const u=await km(e);a||l({data:u,error:null,lastUpdated:Date.now(),loading:!1})}catch(u){a||l(d=>({...d,error:u instanceof Error?u.message:String(u),loading:!1}))}};i();const o=setInterval(i,t);return()=>{a=!0,clearInterval(o)}},[e,t]),r}function ol(e){if(!e)return"";const t=Date.parse(e);if(!Number.isFinite(t))return"";const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s ago`;const r=Math.floor(n/60);if(r<60)return`${r}m ago`;const l=Math.floor(r/60);return l<24?`${l}h ago`:`${Math.floor(l/24)}d ago`}function ie({w:e,h:t=12,radius:n=4,className:r}){const l={width:typeof e=="number"?`${e}px`:e??"100%",height:typeof t=="number"?`${t}px`:t,borderRadius:n};return s.jsx("span",{className:`skeleton${r?` ${r}`:""}`,style:l,"aria-hidden":"true"})}function Sm(){return s.jsxs("div",{className:"page-pad",children:[s.jsxs("div",{className:"kpi-row",children:[Array.from({length:4}).map((e,t)=>s.jsxs("div",{className:"kpi",children:[s.jsx(ie,{h:10,w:70}),s.jsx(ie,{h:28,w:90}),s.jsx(ie,{h:10,w:60})]},t)),s.jsx("div",{className:"kpi",children:s.jsx(ie,{h:56})})]}),s.jsx("div",{className:"pulse-grid",children:Array.from({length:4}).map((e,t)=>s.jsxs("section",{className:"card",children:[s.jsx("header",{className:"card-head",children:s.jsx(ie,{h:14,w:140})}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:10,padding:"12px 0"},children:Array.from({length:5}).map((n,r)=>s.jsx(ie,{h:12,w:`${65+r*7%30}%`},r))})]},t))})]})}function Cm({rows:e=6}){return s.jsx("ul",{className:"session-list",children:Array.from({length:e}).map((t,n)=>s.jsxs("li",{className:"session-row session-row-detail",children:[s.jsx(ie,{h:18,w:56,radius:10}),s.jsxs("div",{className:"session-row-main",children:[s.jsx(ie,{h:13,w:`${50+n*11%35}%`}),s.jsx(ie,{h:11,w:`${30+n*13%50}%`})]}),s.jsx(ie,{h:10,w:48})]},n))})}function Em({rows:e=8,cols:t=6}){return s.jsx("tbody",{children:Array.from({length:e}).map((n,r)=>s.jsx("tr",{children:Array.from({length:t}).map((l,a)=>s.jsx("td",{children:s.jsx(ie,{h:12,w:a===0?"70%":a===t-1?"60%":"50%"})},a))},r))})}function _m(){return s.jsxs("div",{className:"drawer-body",children:[s.jsx("dl",{className:"kv-list",children:Array.from({length:5}).map((e,t)=>s.jsxs("div",{style:{display:"contents"},children:[s.jsx("dt",{className:"kv-label",children:s.jsx(ie,{h:10,w:70})}),s.jsx("dd",{className:"kv-value",children:s.jsx(ie,{h:12,w:`${40+t*13%50}%`})})]},t))}),s.jsx("h4",{className:"drawer-section",children:s.jsx(ie,{h:12,w:100})}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:Array.from({length:4}).map((e,t)=>s.jsx(ie,{h:12,w:`${55+t*7%35}%`},t))})]})}function Lr({sessionId:e,onClose:t,entityColor:n,onNavigate:r,prevSessionId:l,nextSessionId:a}){const[i,o]=x.useState(null),[u,d]=x.useState(null);return x.useEffect(()=>{o(null),d(null),fetch(`/api/session/${encodeURIComponent(e)}`).then(async h=>{if(!h.ok)throw new Error(`HTTP ${h.status}`);const f=await h.json();o({id:String(f.id??e),label:String(f.label??""),summary:String(f.summary??""),body:String(f.body??""),status:String(f.status??"closed"),startedAt:typeof f.startedAt=="string"?f.startedAt:null,endedAt:typeof f.endedAt=="string"?f.endedAt:null,durationMin:typeof f.durationMin=="number"?f.durationMin:null,runtime:String(f.runtime??""),entities:Array.isArray(f.entities)?f.entities:[],decisions:Array.isArray(f.decisions)?f.decisions:[],open:Array.isArray(f.open)?f.open:[],supersededBy:typeof f.supersededBy=="string"?f.supersededBy:null,supersedes:Array.isArray(f.supersedes)?f.supersedes:[]})}).catch(h=>d(h instanceof Error?h.message:String(h)))},[e]),x.useEffect(()=>{const h=f=>{if(f.key==="Escape"){t();return}f.key==="ArrowLeft"&&l!=null&&r&&r(l),f.key==="ArrowRight"&&a!=null&&r&&r(a)};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[t,r,l,a]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"drawer-backdrop",onClick:t}),s.jsxs("aside",{className:"session-drawer",role:"dialog","aria-modal":"true",children:[s.jsxs("header",{className:"drawer-head",children:[n&&s.jsx("span",{className:"dot",style:{background:n}}),s.jsx("h3",{className:"drawer-title",children:(i==null?void 0:i.label)??e}),(l!=null||a!=null)&&r&&s.jsxs("div",{className:"drawer-nav",children:[s.jsx("button",{type:"button",className:"drawer-nav-btn",disabled:l==null,onClick:()=>l&&r(l),"aria-label":"Previous session",children:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M15 18l-6-6 6-6"})})}),s.jsx("button",{type:"button",className:"drawer-nav-btn",disabled:a==null,onClick:()=>a&&r(a),"aria-label":"Next session",children:s.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:s.jsx("path",{d:"M9 18l6-6-6-6"})})})]}),s.jsx("button",{type:"button",className:"drawer-close",onClick:t,"aria-label":"Close",children:"×"})]}),u&&s.jsx("div",{className:"muted error drawer-body",children:u}),!i&&!u&&s.jsx(_m,{}),i&&s.jsxs("div",{className:"drawer-body",children:[i.supersededBy&&s.jsxs("div",{className:"supersedence-banner supersedence-banner--superseded",children:[s.jsx("span",{className:"supersedence-label",children:"Superseded by"}),r?s.jsx("button",{type:"button",className:"supersedence-link",onClick:()=>r(i.supersededBy),children:i.supersededBy}):s.jsx("span",{className:"supersedence-id mono small",children:i.supersededBy})]}),i.supersedes.length>0&&s.jsxs("div",{className:"supersedence-banner supersedence-banner--supersedes",children:[s.jsx("span",{className:"supersedence-label",children:"Supersedes"}),s.jsx("span",{className:"supersedence-ids",children:i.supersedes.map(h=>r?s.jsx("button",{type:"button",className:"supersedence-link",onClick:()=>r(h),children:h},h):s.jsx("span",{className:"supersedence-id mono small",children:h},h))})]}),i.summary&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{className:"drawer-section",children:"Summary"}),s.jsx("p",{className:"drawer-paragraph",children:i.summary})]}),i.decisions.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{className:"drawer-section",children:"Decisions"}),s.jsx("ul",{className:"drawer-list",children:i.decisions.map((h,f)=>s.jsxs("li",{children:[s.jsx("span",{className:"live-tag","data-kind":"decision",children:"decision"})," ",h]},f))})]}),i.open.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{className:"drawer-section",children:"Open questions"}),s.jsx("ul",{className:"drawer-list",children:i.open.map((h,f)=>s.jsxs("li",{children:[s.jsx("span",{className:"live-tag","data-kind":"open",children:"open"})," ",h]},f))})]}),i.entities.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{className:"drawer-section",children:"Entities"}),s.jsx("div",{className:"entity-chips",children:i.entities.map(h=>s.jsx(Pr,{to:`/thread?entity=${encodeURIComponent(h)}`,className:"chip",onClick:t,children:h},h))})]}),s.jsxs("dl",{className:"kv-list",children:[s.jsx("dt",{className:"kv-label",children:"Status"}),s.jsx("dd",{className:"kv-value",children:s.jsx("span",{className:`chip-inline status-${i.status}`,children:i.status})}),s.jsx("dt",{className:"kv-label",children:"Started"}),s.jsx("dd",{className:"kv-value mono small",children:i.startedAt??"—"}),s.jsx("dt",{className:"kv-label",children:"Duration"}),s.jsxs("dd",{className:"kv-value",children:[i.durationMin??"—"," min"]}),s.jsx("dt",{className:"kv-label",children:"Runtime"}),s.jsx("dd",{className:"kv-value mono small",children:i.runtime}),s.jsx("dt",{className:"kv-label",children:"Session ID"}),s.jsx("dd",{className:"kv-value mono small",children:i.id})]}),i.body&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{className:"drawer-section",children:"Transcript excerpt"}),s.jsxs("pre",{className:"drawer-body-text",children:[i.body.slice(0,3e3),i.body.length>3e3?`
68
68
 
69
- […truncated]`:""]})]})]})]})]})}const tr=3e3,Pm=tr*3;function Ps(e){const t=x.useRef(null),[n,r]=x.useState(new Set),l=e.join("|");return x.useEffect(()=>{if(e.length===0)return;if(t.current===null){t.current=new Set(e);return}const a=e.filter(o=>!t.current.has(o));for(const o of e)t.current.add(o);if(a.length===0)return;r(o=>new Set([...o,...a]));const i=setTimeout(()=>{r(o=>{const u=new Set(o);for(const d of a)u.delete(d);return u})},1200);return()=>clearTimeout(i)},[l]),n}function Lm(){const e=er("/api/recall/recent?limit=50",tr,{entries:[]}),t=er("/api/live/recent-writes?limit=50",tr,{writes:[]}),n=er("/api/live/recent-markers?limit=50",tr,{markers:[]}),[r,l]=x.useState(null),a=e.data.entries.map(f=>`${f.ts}|${f.source}|${f.query??""}`),i=t.data.writes.map(f=>f.id),o=n.data.markers.map(f=>`${f.sessionId}|${f.kind}|${f.text}`),u=Ps(a),d=Ps(i),h=Ps(o);return s.jsxs("div",{className:"live-page",children:[s.jsx(Tm,{reads:e,writes:t,markers:n}),s.jsxs("div",{className:"live-board",children:[s.jsx(Ls,{title:"Reads",count:e.data.entries.length,loading:e.loading,emptyLabel:"no recent recall",children:e.data.entries.map((f,m)=>{const k=a[m];return s.jsxs("div",{className:`live-row${u.has(k)?" is-new":""}`,children:[s.jsx("span",{className:"live-tag",children:f.source}),s.jsx("span",{className:"label",children:f.query??"(no query)"}),s.jsxs("div",{className:"body",children:[f.mode," · ",f.nResults," hit",f.nResults===1?"":"s"]}),s.jsx("div",{className:"meta",children:ol(f.ts)})]},k)})}),s.jsx(Ls,{title:"Writes",count:t.data.writes.length,loading:t.loading,emptyLabel:"no recent writes",children:t.data.writes.map(f=>s.jsxs(Xo,{fresh:d.has(f.id),onOpen:()=>l(f.id),children:[s.jsx("span",{className:"live-tag",children:f.runtime.split("/")[0]}),s.jsx("span",{className:"label",children:f.label}),s.jsx("div",{className:"body",children:f.summary}),s.jsxs("div",{className:"meta",children:[ol(f.createdAt)," · ",f.id]})]},f.id))}),s.jsx(Ls,{title:"Markers",count:n.data.markers.length,loading:n.loading,emptyLabel:"no recent markers",children:n.data.markers.map((f,m)=>{const k=o[m];return s.jsxs(Xo,{fresh:h.has(k),onOpen:()=>l(f.sessionId),children:[s.jsx("span",{className:"live-tag","data-kind":f.kind,children:f.kind}),s.jsx("span",{className:"label",children:f.text}),s.jsx("div",{className:"body",children:f.label}),s.jsx("div",{className:"meta",children:ol(f.createdAt)})]},k)})})]}),r&&s.jsx(Lr,{sessionId:r,onClose:()=>l(null)})]})}function Tm({reads:e,writes:t,markers:n}){const r=[e,t,n],l=r.every(f=>f.loading),a=r.map(f=>f.lastUpdated).filter(f=>f!==null),i=a.length>0?Math.max(...a):null,o=r.some(f=>f.error!==null),u=i!==null&&Date.now()-i>Pm;let d;l?d="connecting":u||o?d="reconnecting":d="live";const h=d==="connecting"?"Connecting…":d==="reconnecting"?"Reconnecting…":"Live";return s.jsxs("div",{className:"live-status",children:[s.jsx("span",{className:`live-status-dot live-status-${d}`,"aria-hidden":"true"}),s.jsx("span",{className:"live-status-label",children:h}),i!==null&&s.jsxs("span",{className:"muted small",children:["updated ",ol(new Date(i).toISOString())]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small mono",children:["polling every ",tr/1e3,"s"]})]})}function Ls({title:e,count:t,loading:n,emptyLabel:r,children:l}){const a=t===0;return s.jsxs("section",{className:"live-col",children:[s.jsxs("header",{className:"live-col-head",children:[s.jsx("span",{className:"live-col-title",children:e}),s.jsx("span",{className:"live-col-count",children:t})]}),s.jsx("div",{className:"live-col-body",children:a?s.jsx("div",{className:"live-empty",children:n?"loading…":r}):l})]})}function Xo({fresh:e,onOpen:t,children:n}){return s.jsx("div",{className:`live-row clickable${e?" is-new":""}`,onClick:t,role:"button",tabIndex:0,onKeyDown:r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),t())},children:n})}function Mn(e){const[t,n]=x.useState({data:null,loading:!0,error:null}),r=x.useRef(!1),l=x.useCallback(async()=>{try{const a=await fetch("/api/dataset");if(!a.ok)throw new Error(`HTTP ${a.status}`);const i=await a.json();r.current||n({data:i,loading:!1,error:null})}catch(a){if(!r.current){const i=a instanceof Error?a.message:String(a);n(o=>({data:o.data,loading:!1,error:i}))}}},[]);return x.useEffect(()=>(r.current=!1,l(),()=>{r.current=!0}),[e,l]),{...t,refetch:l}}function qe(e){if(!e)return"—";const t=Date.parse(e);if(!Number.isFinite(t))return"—";const n=Math.floor((Date.now()-t)/864e5);if(n<=0)return"today";if(n===1)return"1d";if(n<30)return`${n}d`;const r=Math.floor(n/30);return r<12?`${r}mo`:`${Math.floor(n/365)}y`}async function yn(e){const t=await fetch("/api/action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,runtime:e.runtime??"web-ui"})});if(!t.ok)throw new Error(`POST /api/action → ${t.status}`);return(await t.json()).id}function Cd({openId:e,defaultText:t,onPromoted:n}){const[r,l]=x.useState(!1),[a,i]=x.useState(!1),[o,u]=x.useState(t),d=async()=>{const h=o.trim();if(h){i(!0);try{await yn({kind:"promote_open",subject_type:"open_question",subject_id:e,payload:{resolution:h,original_text:t}}),await n(),l(!1)}catch{i(!1)}}};return r?s.jsxs("div",{className:"promote-editor",onClick:h=>h.stopPropagation(),children:[s.jsx("input",{className:"form-input form-input-inline promote-input",value:o,onChange:h=>u(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),d()),h.key==="Escape"&&(h.preventDefault(),l(!1))},disabled:a,autoFocus:!0}),s.jsx("button",{type:"button",className:"chip",onClick:()=>void d(),disabled:a||!o.trim(),children:"save"}),s.jsx("button",{type:"button",className:"chip",onClick:()=>l(!1),disabled:a,children:"cancel"})]}):s.jsx("button",{type:"button",className:"chip promote-chip",onClick:()=>{u(t),l(!0)},children:"→ decision"})}function Rm(){const{data:e,loading:t,error:n,refetch:r}=Mn(),[l,a]=x.useState("all"),[i,o]=x.useState("oldest"),[u,d]=x.useState(null),[h,f]=x.useState(null),m=x.useMemo(()=>e?[...l==="all"?e.alerts:e.alerts.filter(c=>c.severity===l)].sort((c,v)=>i==="oldest"?v.age_days-c.age_days:c.age_days-v.age_days):[],[e,l,i]),k=async p=>{await yn({kind:"dismiss",subject_type:"alert",subject_id:p}),await r()},y=async(p,c)=>{const v=new Date(Date.now()+c*864e5).toISOString();await yn({kind:"snooze",subject_type:"alert",subject_id:p,payload:{snoozed_until:v}}),await r()},N=x.useMemo(()=>e?[...e.sessions].sort((p,c)=>(c.started_at??"").localeCompare(p.started_at??"")).slice(0,20):[],[e]);if(t&&!e)return s.jsx(Sm,{});if(n&&!e)return s.jsx("div",{className:"page-pad",children:s.jsx("div",{className:"muted error",children:n})});if(!e)return null;const S=u?e.alerts.find(p=>p.id===u)??null:null;return s.jsxs("div",{className:"page-pad",children:[s.jsxs("div",{className:"kpi-row",children:[s.jsx(Yr,{label:"This week",value:e.metrics.this_week,hint:`${e.metrics.last_week} last week`}),s.jsx(Yr,{label:"Sessions",value:e.meta.sessions_total,hint:"total"}),s.jsx(Yr,{label:"Entities",value:e.meta.entities_total,hint:"catalogued"}),s.jsx(Yr,{label:"Decisions",value:e.metrics.closed_decisions,hint:"non-superseded"}),s.jsx(zm,{values:e.metrics.sparkline})]}),s.jsxs("div",{className:"pulse-grid",children:[s.jsxs("section",{className:"card pulse-area-coherence",children:[s.jsx("header",{className:"card-head",children:s.jsx("h3",{children:"Coherence"})}),s.jsx($m,{metrics:e.metrics})]}),s.jsxs("section",{className:"card pulse-area-runtimes",children:[s.jsx("header",{className:"card-head",children:s.jsx("h3",{children:"Runtimes"})}),s.jsx(Im,{runtimes:e.runtimes})]}),s.jsxs("section",{className:"card pulse-scroll-card pulse-area-recent",children:[s.jsx("header",{className:"card-head",children:s.jsx("h3",{children:"Recent sessions"})}),s.jsx("div",{className:"pulse-scroll-body",children:s.jsx("ul",{className:"session-list",children:N.map(p=>s.jsxs("li",{className:"session-row clickable",onClick:()=>f(p.id),role:"button",tabIndex:0,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),f(p.id))},children:[s.jsx("span",{className:`chip-inline status-${p.status}`,children:p.status}),s.jsx("span",{className:"session-label",children:p.label}),s.jsxs("span",{className:"session-meta",children:[qe(p.started_at)," · ",p.entities.slice(0,3).join(", "),p.entities.length>3?` +${p.entities.length-3}`:""]})]},p.id))})})]}),s.jsxs("section",{className:"card pulse-scroll-card pulse-area-stale",children:[s.jsxs("header",{className:"card-head card-head-stack",children:[s.jsxs("div",{className:"card-head-row",children:[s.jsx("h3",{children:"Stale alerts"}),s.jsxs("span",{className:"muted small",children:[m.length,m.length!==e.alerts.length?` / ${e.alerts.length}`:""]})]}),s.jsxs("div",{className:"card-filters",children:[s.jsx("div",{className:"filter-group",role:"group","aria-label":"Severity",children:["all","high","medium"].map(p=>s.jsx("button",{type:"button",className:`chip${l===p?" active":""}`,"data-severity":p==="all"?void 0:p,onClick:()=>a(p),children:p},p))}),s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Sort",children:[s.jsx("button",{type:"button",className:`chip${i==="oldest"?" active":""}`,onClick:()=>o("oldest"),children:"oldest"}),s.jsx("button",{type:"button",className:`chip${i==="recent"?" active":""}`,onClick:()=>o("recent"),children:"recent"})]})]})]}),s.jsx("div",{className:"pulse-scroll-body",children:s.jsxs("ul",{className:"alert-list",children:[m.map(p=>s.jsxs("li",{className:"alert-row clickable",onClick:()=>d(p.id),role:"button",tabIndex:0,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),d(p.id))},children:[s.jsx("span",{className:`chip-inline severity-${p.severity}`,children:p.severity}),s.jsx("span",{className:"alert-entity",children:p.entity}),s.jsx("span",{className:"alert-summary",children:p.summary}),s.jsxs("div",{className:"alert-actions",onClick:c=>c.stopPropagation(),children:[s.jsx("button",{type:"button",className:"chip",onClick:()=>void y(p.id,7),children:"snooze 7d"}),s.jsx("button",{type:"button",className:"chip",onClick:()=>void k(p.id),children:"dismiss"})]})]},p.id)),m.length===0&&s.jsx("li",{className:"muted alert-row-empty",children:e.alerts.length===0?"No stale alerts.":"No alerts match the current filters."})]})})]})]}),S&&s.jsx(Om,{alert:S,entity:e.entities.find(p=>p.canonical===S.entity)??null,entityColor:e.entity_colors[S.entity]??"#666",sessions:e.sessions,onClose:()=>d(null),onDismiss:async()=>{await k(S.id),d(null)},onSnooze:async p=>{await y(S.id,p),d(null)},onPromoted:r}),h&&s.jsx(Lr,{sessionId:h,onClose:()=>f(null),entityColor:(()=>{const p=e.sessions.find(v=>v.id===h),c=p==null?void 0:p.entities[0];return c?e.entity_colors[c]:void 0})()})]})}const Mm=[10,25,50];function Om({alert:e,entity:t,entityColor:n,sessions:r,onClose:l,onDismiss:a,onSnooze:i,onPromoted:o}){const u=_r(),[d,h]=x.useState(10),[f,m]=x.useState(0),k=x.useMemo(()=>r.filter(g=>g.entities.includes(e.entity)).sort((g,j)=>(j.started_at??"").localeCompare(g.started_at??"")),[r,e.entity]);x.useEffect(()=>{m(0)},[e.id,d]);const y=Math.max(1,Math.ceil(k.length/d)),N=Math.min(f,y-1),S=N*d,p=k.slice(S,S+d),c=x.useMemo(()=>k.flatMap(g=>g.open_questions.map(j=>({id:j.id,text:j.text,sid:g.id,when:g.started_at}))),[k]),v=x.useMemo(()=>k.flatMap(g=>g.decisions.map(j=>({text:j,sid:g.id,when:g.started_at}))),[k]);return x.useEffect(()=>{const g=j=>{j.key==="Escape"&&l()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[l]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"drawer-backdrop",onClick:l}),s.jsxs("aside",{className:"session-drawer",role:"dialog","aria-modal":"true","aria-label":`Alert detail: ${e.entity}`,children:[s.jsxs("header",{className:"drawer-head",children:[s.jsx("span",{className:"dot lg",style:{background:n}}),s.jsx("h3",{className:"drawer-title",children:e.entity}),s.jsx("span",{className:`chip-inline severity-${e.severity}`,children:e.severity}),s.jsx("button",{type:"button",className:"drawer-close",onClick:l,"aria-label":"Close",children:"×"})]}),s.jsxs("div",{className:"drawer-body",children:[s.jsx("p",{className:"drawer-paragraph",children:e.summary}),s.jsxs("dl",{className:"kv-list",children:[s.jsx("dt",{className:"kv-label",children:"Last touch"}),s.jsxs("dd",{className:"kv-value",children:[e.age_days," day",e.age_days===1?"":"s"," ago"]}),s.jsx("dt",{className:"kv-label",children:"Last session"}),s.jsx("dd",{className:"kv-value mono small",children:e.last_touch_at??"—"}),t&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{className:"kv-label",children:"Entity type"}),s.jsx("dd",{className:"kv-value",children:t.type}),s.jsx("dt",{className:"kv-label",children:"Total sessions"}),s.jsx("dd",{className:"kv-value mono",children:t.session_count})]})]}),s.jsxs("div",{className:"drawer-actions",children:[s.jsx("button",{type:"button",className:"btn btn-accent",onClick:()=>u(`/thread?entity=${encodeURIComponent(e.entity)}`),children:"Open thread"}),s.jsx("button",{type:"button",className:"btn",onClick:()=>void i(7),children:"Snooze 7d"}),s.jsx("button",{type:"button",className:"btn",onClick:()=>void i(30),children:"Snooze 30d"}),s.jsx("button",{type:"button",className:"btn btn-danger",onClick:()=>void a(),children:"Dismiss"})]}),c.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs("h4",{className:"drawer-section",children:["Open questions (",c.length,")"]}),s.jsx("ul",{className:"drawer-list",children:c.slice(0,12).map((g,j)=>s.jsxs("li",{className:"marker-row-promotable",children:[s.jsx("span",{className:"live-tag","data-kind":"open",children:"open"}),s.jsx("span",{className:"marker-text",children:g.text}),s.jsx(Cd,{openId:g.id,defaultText:g.text,onPromoted:o}),s.jsx("span",{className:"muted small",children:qe(g.when)})]},`${g.id}-${j}`))}),c.length>12&&s.jsxs("p",{className:"muted small",children:["Showing first 12 of ",c.length,"."]})]}),v.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs("h4",{className:"drawer-section",children:["Decisions (",v.length,")"]}),s.jsx("ul",{className:"drawer-list",children:v.slice(0,8).map((g,j)=>s.jsxs("li",{children:[s.jsx("span",{className:"live-tag","data-kind":"decision",children:"decision"}),s.jsx("span",{className:"marker-text",children:g.text}),s.jsx("span",{className:"muted small",children:qe(g.when)})]},`${g.sid}-${j}`))}),v.length>8&&s.jsxs("p",{className:"muted small",children:["Showing first 8 of ",v.length,"."]})]}),s.jsxs("h4",{className:"drawer-section",children:["Recent sessions (",k.length,")"]}),s.jsx("ul",{className:"session-list",children:p.map(g=>s.jsxs("li",{className:"session-row",children:[s.jsx("span",{className:`chip-inline status-${g.status}`,children:g.status}),s.jsxs("div",{className:"session-row-main",children:[s.jsx(Pr,{to:`/thread?entity=${encodeURIComponent(e.entity)}&session=${encodeURIComponent(g.id)}`,className:"session-label",children:g.label}),s.jsx("span",{className:"session-meta",children:g.summary})]}),s.jsx("span",{className:"muted small mono",children:qe(g.started_at)})]},g.id))}),k.length>0&&s.jsxs("div",{className:"pagination pagination-compact",children:[s.jsxs("div",{className:"page-size",children:[s.jsx("label",{className:"form-label",children:"Per page"}),s.jsx("select",{className:"form-input form-input-inline",value:d,onChange:g=>h(Number.parseInt(g.target.value,10)),children:Mm.map(g=>s.jsx("option",{value:g,children:g},g))})]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[S+1,"–",Math.min(S+d,k.length)," of ",k.length]}),s.jsxs("div",{className:"page-nav",children:[s.jsx("button",{type:"button",className:"chip",disabled:N===0,onClick:()=>m(0),children:"«"}),s.jsx("button",{type:"button",className:"chip",disabled:N===0,onClick:()=>m(g=>Math.max(0,g-1)),children:"‹"}),s.jsxs("span",{className:"page-indicator mono",children:[N+1," / ",y]}),s.jsx("button",{type:"button",className:"chip",disabled:N>=y-1,onClick:()=>m(g=>Math.min(y-1,g+1)),children:"›"}),s.jsx("button",{type:"button",className:"chip",disabled:N>=y-1,onClick:()=>m(y-1),children:"»"})]})]})]})]})]})}function Yr({label:e,value:t,hint:n}){return s.jsxs("div",{className:"kpi",children:[s.jsx("span",{className:"kpi-label",children:e}),s.jsx("span",{className:"kpi-value",children:t.toLocaleString()}),n&&s.jsx("span",{className:"kpi-hint",children:n})]})}function zm({values:e}){const t=Math.max(1,...e);return s.jsxs("div",{className:"kpi kpi-sparkline",children:[s.jsx("span",{className:"kpi-label",children:"Last 7 days"}),s.jsx("div",{className:"sparkline",children:e.map((n,r)=>s.jsx("span",{className:"spark-bar",style:{height:`${n/t*100}%`},title:`${n} sessions`},r))})]})}function $m({metrics:e}){const t=e.healthy+e.sparse+e.stale,n=r=>t>0?r/t*100:0;return s.jsxs("div",{className:"bar-stack",children:[s.jsx(Ts,{tone:"active",label:"Healthy",value:e.healthy,pct:n(e.healthy)}),s.jsx(Ts,{tone:"warn",label:"Sparse",value:e.sparse,pct:n(e.sparse)}),s.jsx(Ts,{tone:"danger",label:"Stale",value:e.stale,pct:n(e.stale)})]})}function Im({runtimes:e}){return e.length===0?s.jsx("div",{className:"muted small",style:{padding:"8px 12px"},children:"No runtime activity yet."}):s.jsx("ul",{className:"runtime-list",children:e.map(t=>s.jsxs("li",{className:"runtime-row",children:[s.jsx("span",{className:`runtime-dot runtime-${t.status}`,title:t.status}),s.jsx("span",{className:"runtime-name mono",children:t.name}),s.jsxs("span",{className:"runtime-counts muted small",children:[t.this_week,s.jsx("span",{className:"runtime-counts-sep",children:"·"}),s.jsxs("span",{className:"runtime-counts-prev",children:[t.last_week," prev"]})]}),s.jsx("span",{className:"muted small mono runtime-age",children:qe(t.last_session_at)})]},t.name))})}function Ts({tone:e,label:t,value:n,pct:r}){const l=Math.round(r);return s.jsxs("div",{className:"bar-item",children:[s.jsx("span",{className:"bar-label",children:t}),s.jsx("div",{className:"bar-track",title:`${n.toLocaleString()} entit${n===1?"y":"ies"} · ${l}% of total`,children:s.jsx("div",{className:`bar-fill tone-${e}`,style:{width:`${r}%`}})}),s.jsxs("span",{className:"bar-value mono",children:[n.toLocaleString(),s.jsxs("span",{className:"bar-pct muted small",children:[" · ",l,"%"]})]})]})}const Ed="nlm.settings.views",xt={landing:"live",riverDensity:"comfortable",threadSort:"recent"};function es(){if(typeof window>"u")return xt;try{const e=window.localStorage.getItem(Ed);return e?{...xt,...JSON.parse(e)}:xt}catch{return xt}}function bm(e){typeof window>"u"||window.localStorage.setItem(Ed,JSON.stringify(e))}const Go={"7d":7,"30d":30,"90d":90,all:null};function Dm(){const{data:e,loading:t,error:n}=Mn(),[r,l]=x.useState("30d"),[a,i]=x.useState(null),[o,u]=x.useState(null),[d,h]=x.useState(null),f=_r(),[m]=x.useState(()=>es().riverDensity),k=x.useRef(null),y=x.useRef(null),[N,S]=x.useState(null),p=x.useMemo(()=>{if(!e)return null;const w=Go[r],C=e.sessions.filter(I=>I.started_at!==null),_=Date.now(),$=w?C.filter(I=>(_-Date.parse(I.started_at))/864e5<=w):C,T=new Map,D=new Map,W=new Set;for(const I of $){const H=(I.started_at??"").slice(0,10);if(!H)continue;W.add(H);const M=I.status==="superseded";for(const z of I.entities)if(M){const b=D.get(z)??new Map;b.set(H,(b.get(H)??0)+1),D.set(z,b)}else{const b=T.get(z)??new Map;b.set(H,(b.get(H)??0)+1),T.set(z,b)}}for(const[I]of D)T.has(I)||T.set(I,new Map);const L=[...W].sort(),R=[...T.entries()].map(([I,H])=>({entity:I,total:[...H.values()].reduce((M,z)=>M+z,0),perDate:H,supersededPerDate:D.get(I)??new Map})).sort((I,H)=>H.total-I.total).slice(0,24),F=new Set($.filter(I=>I.started_at&&_-Date.parse(I.started_at)<864e5).flatMap(I=>I.entities));return{dates:L,laneRows:R,total:$.length,recentEntities:F}},[e,r]),c=(w,C)=>{if(!e)return;const _=e.sessions.filter($=>($.started_at??"").slice(0,10)===C&&$.entities.includes(w)).sort(($,T)=>(T.started_at??"").localeCompare($.started_at??""));if(_.length!==0){if(_.length===1){h(_[0].id);return}u({entity:w,date:C,sessions:_})}},v=w=>{if(!k.current)return;const C=k.current.getBoundingClientRect();y.current={startX:w.clientX,rect:C}},g=w=>{if(!y.current)return;const{startX:C,rect:_}=y.current,$=Math.min(C,w.clientX)-_.left,T=Math.max(C,w.clientX)-_.left;if(T-$<6){S(null);return}S({from:$,to:T})},j=()=>{if(!y.current||!N||!p){y.current=null,S(null);return}const w=k.current,C=w==null?void 0:w.querySelector(".river-lane-label"),_=(C==null?void 0:C.offsetWidth)??0,$=(w==null?void 0:w.offsetWidth)??0,D=Math.max(1,$-_)/p.dates.length,W=_+12,L=Math.max(0,Math.floor((N.from-W)/D)),R=Math.min(p.dates.length-1,Math.floor((N.to-W)/D));if(R<=L){y.current=null,S(null);return}const F=p.dates[L],I=p.dates[R];if(F&&I){const H=Math.max(1,Math.ceil((Date.parse(I)-Date.parse(F))/864e5));l(H<=7?"7d":H<=30?"30d":H<=90?"90d":"all")}y.current=null,S(null)};return t&&!e?s.jsxs("div",{className:"page-pad",children:[s.jsx("div",{className:"river-toolbar",children:s.jsx(ie,{h:22,w:80})}),s.jsx("div",{className:"card",style:{padding:12},children:Array.from({length:8}).map((w,C)=>s.jsxs("div",{className:"river-row",style:{marginBottom:3},children:[s.jsx(ie,{h:14,w:160}),s.jsx(ie,{h:20})]},C))})]}):n&&!e?s.jsx("div",{className:"page-pad",children:s.jsx("div",{className:"muted error",children:n})}):!e||!p?null:s.jsxs("div",{className:"page-pad",children:[s.jsxs("div",{className:"river-toolbar",children:[s.jsx("span",{className:"page-title",children:"River"}),s.jsxs("span",{className:"muted small",children:[p.total," sessions · ",p.laneRows.length," lanes · ",p.dates.length," days"]}),s.jsx("span",{className:"header-spacer"}),Object.keys(Go).map(w=>s.jsx("button",{type:"button",className:`ctrl-btn${w===r?" active":""}`,onClick:()=>l(w),children:w},w)),s.jsxs("div",{className:"river-legend","aria-label":"Activity scale",children:[s.jsx("span",{className:"muted small",children:"less"}),[0,1,2,3,4].map(w=>s.jsx("span",{className:`river-legend-cell tier-${w}`},w)),s.jsx("span",{className:"muted small",children:"more"})]})]}),s.jsxs("div",{className:`river-grid card river-density-${m}`,ref:k,onMouseDown:v,onMouseMove:g,onMouseUp:j,onMouseLeave:()=>{y.current=null,S(null),i(null)},style:{"--cells":p.dates.length},children:[N&&s.jsx("div",{className:"river-drag-rect",style:{left:`${N.from}px`,width:`${N.to-N.from}px`}}),s.jsxs("div",{className:"river-row river-row-dates",children:[s.jsx("div",{className:"river-lane-label river-lane-label--header","aria-hidden":"true"}),s.jsx("div",{className:"river-cells",children:(()=>{const w=p.dates.length,C=w<=60?1:w<=120?2:w<=250?7:14;return p.dates.map((_,$)=>{const D=["river-date-cell",_.slice(8,10)==="01"?"river-date-cell--month-start":""].filter(Boolean).join(" ");return s.jsx("div",{className:D,title:_,children:$%C===0?_.slice(5):""},_)})})()})]}),p.laneRows.map(({entity:w,perDate:C,supersededPerDate:_,total:$})=>{const T=p.recentEntities.has(w);return s.jsxs("div",{className:"river-row",children:[s.jsxs("button",{type:"button",className:"river-lane-label",onClick:()=>f(`/thread?entity=${encodeURIComponent(w)}`),children:[s.jsx("span",{className:`dot${T?" dot-pulse":""}`,style:{background:e.entity_colors[w]??"#666"}}),s.jsx("span",{className:"river-lane-name",children:w}),s.jsx("span",{className:"muted small",children:$})]}),s.jsx("div",{className:"river-cells",children:p.dates.map(D=>{const W=C.get(D)??0,L=_.get(D)??0,R=W>0||L>0,F=["river-cell",`tier-${Um(W)}`,L>0?"has-corrections":""].filter(Boolean).join(" ");return s.jsx("div",{className:F,onMouseEnter:I=>i({entity:w,date:D,count:W,superseded:L,x:I.clientX,y:I.clientY}),onMouseLeave:()=>i(null),onClick:()=>R&&c(w,D),style:R?{cursor:"pointer"}:{}},D)})})]},w)})]}),p.laneRows.length===0&&s.jsx("div",{className:"muted",children:"No entities in this window."}),a&&(a.count>0||a.superseded>0)&&s.jsxs("div",{className:"river-hover",style:{left:a.x+12,top:a.y+12},children:[s.jsx("span",{className:"dot",style:{background:e.entity_colors[a.entity]??"#666"}}),s.jsx("span",{className:"river-hover-name",children:a.entity}),s.jsxs("span",{className:"muted small",children:[a.date,a.count>0&&` · ${a.count} session${a.count===1?"":"s"}`,a.superseded>0&&` · ${a.superseded} corrected`]})]}),o&&s.jsx(Fm,{state:o,entityColor:e.entity_colors[o.entity]??"#666",onClose:()=>u(null),onPick:w=>{u(null),h(w)},onOpenThread:()=>f(`/thread?entity=${encodeURIComponent(o.entity)}`)}),d&&(()=>{const w=o?o.sessions:[...e.sessions].filter(W=>W.started_at!==null).sort((W,L)=>(L.started_at??"").localeCompare(W.started_at??"")),C=w.findIndex(W=>W.id===d),_=C<w.length-1?w[C+1].id:null,$=C>0?w[C-1].id:null,T=e.sessions.find(W=>W.id===d),D=T==null?void 0:T.entities[0];return s.jsx(Lr,{sessionId:d,onClose:()=>h(null),onNavigate:h,prevSessionId:_,nextSessionId:$,entityColor:D?e.entity_colors[D]:void 0})})()]})}function Fm({state:e,entityColor:t,onClose:n,onPick:r,onOpenThread:l}){return x.useEffect(()=>{const a=i=>{i.key==="Escape"&&n()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[n]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"drawer-backdrop",onClick:n}),s.jsxs("aside",{className:"session-drawer",role:"dialog","aria-modal":"true","aria-label":`Sessions on ${e.date}`,children:[s.jsxs("header",{className:"drawer-head",children:[s.jsx("span",{className:"dot lg",style:{background:t}}),s.jsx("h3",{className:"drawer-title",children:e.entity}),s.jsx("span",{className:"muted small",children:e.date}),s.jsx("button",{type:"button",className:"drawer-close",onClick:n,"aria-label":"Close",children:"×"})]}),s.jsxs("div",{className:"drawer-body",children:[s.jsxs("p",{className:"muted small",children:[e.sessions.length," sessions on this day. Pick one to inspect."]}),s.jsx("div",{className:"drawer-actions",children:s.jsx("button",{type:"button",className:"btn btn-accent",onClick:l,children:"Open thread"})}),s.jsx("ul",{className:"session-list",children:e.sessions.map(a=>s.jsxs("li",{className:"session-row session-row-detail clickable",onClick:()=>r(a.id),role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r(a.id))},children:[s.jsx("span",{className:`chip-inline status-${a.status}`,children:a.status}),s.jsxs("div",{className:"session-row-main",children:[s.jsx("span",{className:"session-label",children:a.label}),s.jsx("span",{className:"session-meta",children:a.summary})]}),s.jsx("span",{className:"muted small mono",children:qe(a.started_at)})]},a.id))})]})]})]})}function Um(e){return e===0?0:e===1?1:e<=3?2:e<=6?3:4}const Am=[10,25,50,100];function Bm(e,t,n){const r=e.label.toLowerCase(),l=e.summary.toLowerCase(),a=e.decisions.join(" ").toLowerCase(),i=e.open.join(" ").toLowerCase(),o={label:0,entity:0,decision:0,open:0,summary:0};for(const m of t){r.includes(m)&&(o.label+=3);for(const k of e.entities){const y=k.toLowerCase();if(y===m){o.entity+=4;break}else if(y.includes(m)){o.entity+=2;break}}a.includes(m)&&(o.decision+=2),i.includes(m)&&(o.open+=2),l.includes(m)&&(o.summary+=1)}if(n&&(r.includes(n)||a.includes(n)||i.includes(n))){const m=Object.keys(o).reduce((k,y)=>o[k]>=o[y]?k:y);o[m]+=5}const u=Object.values(o).reduce((m,k)=>m+k,0),d=["label","entity","decision","open","summary"];let h="summary",f=-1;for(const m of d)o[m]>f&&(f=o[m],h=m);return{score:u,matchedField:h}}function Wm(e,t,n=60){const r=e.toLowerCase();let l=-1;for(const o of t){const u=r.indexOf(o);u!==-1&&(l===-1||u<l)&&(l=u)}if(l===-1)return e.slice(0,n*2);const a=Math.max(0,l-n),i=Math.min(e.length,l+n);return(a>0?"…":"")+e.slice(a,i)+(i<e.length?"…":"")}function Vm(e,t){let n=e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");for(const r of t)n=n.replace(new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),l=>`<mark>${l}</mark>`);return n}function Hm(){const{data:e,loading:t,error:n}=Mn(),[r,l]=Sd(),a=r.get("q")??"",[i,o]=x.useState(a),[u,d]=x.useState(r.get("entity")??""),[h,f]=x.useState("all"),[m,k]=x.useState("all"),[y,N]=x.useState("recent"),[S,p]=x.useState(25),[c,v]=x.useState(0),[g,j]=x.useState(r.get("session")),w=E=>{const U=new URLSearchParams(r);U.set("session",E),l(U),j(E)},C=()=>{const E=new URLSearchParams(r);E.delete("session"),l(E),j(null)};x.useEffect(()=>{const E=setTimeout(()=>{const U=new URLSearchParams(r);i?U.set("q",i):U.delete("q"),l(U)},200);return()=>clearTimeout(E)},[i]),x.useEffect(()=>{const E=new URLSearchParams(r);u?E.set("entity",u):E.delete("entity"),l(E)},[u]);const _=x.useMemo(()=>a.toLowerCase().split(/\s+/).filter(Boolean),[a]),$=_.join(" "),T=x.useMemo(()=>{if(!e)return[];const E=e.sessions.filter(B=>!(u&&!B.entities.includes(u)||h!=="all"&&B.runtime!==h||m!=="all"&&B.status!==m));if(_.length===0)return[...E].sort((le,xe)=>(xe.started_at??"").localeCompare(le.started_at??"")).map(le=>({session:le,score:0,matchedField:"summary"}));const U=E.map(B=>{const{score:le,matchedField:xe}=Bm(B,_,$);return{session:B,score:le,matchedField:xe}}).filter(B=>B.score>0);return y==="recent"?U.sort((B,le)=>(le.session.started_at??"").localeCompare(B.session.started_at??"")):U.sort((B,le)=>le.score-B.score),U},[e,_,$,u,h,m,y]);x.useEffect(()=>{v(0)},[T,h,m,u]);const D=Math.max(1,Math.ceil(T.length/S)),W=Math.min(c,D-1),L=W*S,R=T.slice(L,L+S),F=x.useMemo(()=>{if(!e)return[];const E=new Map;for(const U of e.sessions)E.set(U.runtime,(E.get(U.runtime)??0)+1);return[...E.entries()].sort((U,B)=>B[1]-U[1]).map(([U])=>U)},[e]),I=x.useMemo(()=>{const E=new Map;for(const{session:U}of T)for(const B of U.entities)E.set(B,(E.get(B)??0)+1);return[...E.entries()].sort((U,B)=>B[1]-U[1]).map(([U])=>U)},[T]),H=a!==""||u!==""||h!=="all"||m!=="all",M=()=>{o(""),d(""),f("all"),k("all"),N("recent");const E=new URLSearchParams;g&&E.set("session",g),l(E)},z=R.findIndex(E=>E.session.id===g),b=z<R.length-1?R[z+1].session.id:null,J=z>0?R[z-1].session.id:null;return s.jsxs("div",{className:"page-pad",children:[s.jsxs("div",{className:"search-header",children:[s.jsx("form",{onSubmit:E=>E.preventDefault(),className:"search-bar",children:s.jsxs("div",{className:"search-wrap",style:{flex:1},children:[s.jsx("input",{className:"search-input search-big",placeholder:"search sessions, decisions, open questions…",value:i,onChange:E=>o(E.target.value),autoFocus:!0}),i.length>0&&s.jsx("button",{type:"button",className:"search-clear",onClick:()=>o(""),"aria-label":"Clear search",children:s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})}),s.jsxs("div",{className:"thread-filters",children:[F.length>1&&s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Agent filter",children:[s.jsx("button",{type:"button",className:`chip${h==="all"?" active":""}`,onClick:()=>f("all"),children:"all"}),F.map(E=>{const U=T.filter(B=>B.session.runtime===E).length;return s.jsxs("button",{type:"button",className:`chip${h===E?" active":""}`,onClick:()=>f(E),children:[E," · ",U]},E)})]}),s.jsx("div",{className:"filter-group",role:"group","aria-label":"Status filter",children:["all","active","idle","closed","superseded"].map(E=>{const U=E==="all"?T.length:T.filter(B=>B.session.status===E).length;return s.jsxs("button",{type:"button",className:`chip${m===E?" active":""}`,"data-status":E==="all"?void 0:E,onClick:()=>k(E),children:[E," · ",U]},E)})}),a!==""&&s.jsx("div",{className:"filter-group",role:"group","aria-label":"Sort order",children:["relevance","recent"].map(E=>s.jsx("button",{type:"button",className:`chip${y===E?" active":""}`,onClick:()=>N(E),children:E},E))}),I.length>0&&s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Entity filter",style:{flexWrap:"wrap"},children:[s.jsx("button",{type:"button",className:`chip${u===""?" active":""}`,onClick:()=>d(""),children:"all entities"}),I.slice(0,12).map(E=>s.jsx("button",{type:"button",className:`chip${u===E?" active":""}`,onClick:()=>d(u===E?"":E),children:E},E)),I.length>12&&s.jsxs("select",{className:"form-input form-input-inline",value:u,onChange:E=>d(E.target.value),children:[s.jsx("option",{value:"",children:"more entities…"}),I.slice(12).map(E=>s.jsx("option",{value:E,children:E},E))]})]})]})]}),t&&!e&&s.jsx("div",{className:"muted",children:"Loading…"}),n&&s.jsx("div",{className:"muted error",children:n}),!H&&s.jsx("p",{className:"muted small search-hint",children:"Showing recent sessions. Type to search across labels, decisions, open questions, and summaries."}),s.jsxs("div",{className:"muted small search-meta",children:[T.length," result",T.length===1?"":"s",H&&s.jsx("button",{type:"button",className:"link-button",style:{marginLeft:8},onClick:M,children:"clear filters"})]}),s.jsxs("ul",{className:"session-list",children:[R.map(({session:E,matchedField:U})=>{let B=E.summary;return _.length>0&&(U==="decision"?B=E.decisions.find(le=>_.some(xe=>le.toLowerCase().includes(xe)))??E.summary:U==="open"&&(B=E.open.find(le=>_.some(xe=>le.toLowerCase().includes(xe)))??E.summary)),s.jsxs("li",{className:`session-row session-row-detail clickable${g===E.id?" is-active":""}`,onClick:()=>w(E.id),children:[s.jsx("span",{className:`chip-inline status-${E.status}`,children:E.status}),s.jsxs("div",{className:"session-row-main",children:[s.jsx("span",{className:"session-label",children:E.label}),s.jsx("span",{className:"session-meta",children:E.entities.slice(0,4).map(le=>s.jsx("span",{className:"chip-inline",style:{marginRight:4},children:le},le))}),_.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"live-tag","data-kind":U,children:U}),s.jsx("div",{className:"match-snippet",dangerouslySetInnerHTML:{__html:Vm(Wm(B,_),_)}})]})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:4},children:[s.jsx("span",{className:"muted small mono",children:qe(E.started_at)}),s.jsx("span",{className:"chip-inline",children:E.runtime})]})]},E.id)}),R.length===0&&e&&s.jsx("li",{className:"muted empty-row",children:T.length===0?"No sessions match the current filters.":"No sessions on this page."})]}),T.length>0&&s.jsxs("div",{className:"pagination",children:[s.jsxs("div",{className:"page-size",children:[s.jsx("label",{className:"form-label",children:"Per page"}),s.jsx("select",{className:"form-input form-input-inline",value:S,onChange:E=>p(Number.parseInt(E.target.value,10)),children:Am.map(E=>s.jsx("option",{value:E,children:E},E))})]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[L+1,"–",Math.min(L+S,T.length)," of ",T.length]}),s.jsxs("div",{className:"page-nav",children:[s.jsx("button",{type:"button",className:"chip",disabled:W===0,onClick:()=>v(0),children:"« first"}),s.jsx("button",{type:"button",className:"chip",disabled:W===0,onClick:()=>v(E=>Math.max(0,E-1)),children:"‹ prev"}),s.jsxs("span",{className:"page-indicator mono",children:[W+1," / ",D]}),s.jsx("button",{type:"button",className:"chip",disabled:W>=D-1,onClick:()=>v(E=>Math.min(D-1,E+1)),children:"next ›"}),s.jsx("button",{type:"button",className:"chip",disabled:W>=D-1,onClick:()=>v(D-1),children:"last »"})]})]}),g&&s.jsx(Lr,{sessionId:g,onClose:C,onNavigate:w,prevSessionId:b,nextSessionId:J})]})}function Km(){const{data:e,loading:t,error:n,refetch:r}=Mn(),[l,a]=Sd(),i=l.get("entity")??"",o=l.get("session"),[u,d]=x.useState(()=>es().threadSort),[h,f]=x.useState(!1),[m,k]=x.useState(!1),y=x.useMemo(()=>{if(!e||!i)return[];const g=e.sessions.filter(j=>j.entities.includes(i));return g.sort((j,w)=>{const C=j.started_at??"",_=w.started_at??"";return u==="recent"?_.localeCompare(C):C.localeCompare(_)}),g},[e,i,u]),N=i&&e?e.entity_colors[i]??"#666":"#666";x.useEffect(()=>{i&&e&&(document.title=`${i} — Thread`)},[i,e]);const S=g=>{const j=new URLSearchParams(l);j.set("session",g),a(j)},p=()=>{const g=new URLSearchParams(l);g.delete("session"),a(g)};if(t&&!e)return s.jsxs("div",{className:"page-pad",children:[s.jsx(ie,{h:22,w:220}),s.jsx("div",{style:{marginTop:16},children:s.jsx(Cm,{rows:8})})]});if(n&&!e)return s.jsx("div",{className:"page-pad",children:s.jsx("div",{className:"muted error",children:n})});if(!e)return null;if(!i)return s.jsx(Gm,{data:e});const c=y.flatMap(g=>g.decisions.map(j=>({d:j,sid:g.id,when:g.started_at}))),v=y.flatMap(g=>g.open_questions.map(j=>({id:j.id,q:j.text,sid:g.id,when:g.started_at})));return s.jsxs("div",{className:"page-pad",children:[s.jsxs("div",{className:"thread-header",children:[s.jsx("span",{className:"dot lg",style:{background:N}}),s.jsx("h2",{className:"page-title",children:i}),s.jsxs("span",{className:"muted",children:[y.length," session",y.length===1?"":"s"]}),s.jsx("span",{className:"header-spacer"}),s.jsx("div",{className:"filter-group",role:"group","aria-label":"Sort order",children:["recent","oldest"].map(g=>s.jsx("button",{type:"button",className:`chip${u===g?" active":""}`,onClick:()=>d(g),children:g==="recent"?"recent first":"oldest first"},g))})]}),s.jsxs("div",{className:"thread-grid",children:[s.jsxs("section",{className:"card",children:[s.jsxs("header",{className:"card-head",children:[s.jsx("h3",{children:"Decisions"}),s.jsx("span",{className:"muted small",children:c.length})]}),s.jsxs("ul",{className:"marker-list",children:[(h?c:c.slice(0,30)).map((g,j)=>s.jsxs("li",{className:"marker-row",children:[s.jsx("span",{className:"live-tag","data-kind":"decision",children:"decision"}),s.jsx("span",{className:"marker-text",children:g.d}),s.jsx("button",{type:"button",className:"link-button",onClick:()=>S(g.sid),children:qe(g.when)})]},j)),c.length===0&&s.jsx("li",{className:"muted empty-row",children:"No decisions captured yet."}),c.length>30&&s.jsx("li",{style:{padding:"8px 14px"},children:s.jsx("button",{type:"button",className:"link-button",onClick:()=>f(g=>!g),children:h?"Show less":`Showing 30 of ${c.length} — show all`})})]})]}),s.jsxs("section",{className:"card",children:[s.jsxs("header",{className:"card-head",children:[s.jsx("h3",{children:"Open questions"}),s.jsx("span",{className:"muted small",children:v.length})]}),s.jsxs("ul",{className:"marker-list",children:[(m?v:v.slice(0,30)).map((g,j)=>s.jsxs("li",{className:"marker-row marker-row-promotable",children:[s.jsx("span",{className:"live-tag","data-kind":"open",children:"open"}),s.jsx("span",{className:"marker-text",children:g.q}),s.jsxs("div",{className:"marker-actions",children:[s.jsx(Cd,{openId:g.id,defaultText:g.q,onPromoted:r}),s.jsx("button",{type:"button",className:"link-button",onClick:()=>S(g.sid),children:qe(g.when)})]})]},`${g.id}-${j}`)),v.length===0&&s.jsx("li",{className:"muted empty-row",children:"No open questions captured yet."}),v.length>30&&s.jsx("li",{style:{padding:"8px 14px"},children:s.jsx("button",{type:"button",className:"link-button",onClick:()=>k(g=>!g),children:m?"Show less":`Showing 30 of ${v.length} — show all`})})]})]})]}),s.jsx(Ym,{thread:y,entity:i,onOpenSession:S}),o&&(()=>{const g=y.findIndex(C=>C.id===o),j=g<y.length-1?y[g+1].id:null,w=g>0?y[g-1].id:null;return s.jsx(Lr,{sessionId:o,onClose:p,onNavigate:S,prevSessionId:j,nextSessionId:w,entityColor:N})})()]})}const Qm=[10,25,50,100];function Ym({thread:e,entity:t,onOpenSession:n}){const[r,l]=x.useState("all"),[a,i]=x.useState(""),[o,u]=x.useState("all"),[d,h]=x.useState("all"),[f,m]=x.useState(25),[k,y]=x.useState(0),N=x.useMemo(()=>{const j=new Map;for(const w of e)j.set(w.runtime,(j.get(w.runtime)??0)+1);return[...j.entries()].sort((w,C)=>C[1]-w[1]).map(([w])=>w)},[e]),S=x.useMemo(()=>{const j=a.toLowerCase().trim();return e.filter(w=>r!=="all"&&w.runtime!==r||o!=="all"&&w.status!==o||d==="decisions"&&w.decisions.length===0||d==="open"&&w.open_questions.length===0?!1:j?w.label.toLowerCase().includes(j)||w.summary.toLowerCase().includes(j)||w.decisions.some(C=>C.toLowerCase().includes(j))||w.open.some(C=>C.toLowerCase().includes(j)):!0)},[e,a,o,d,r]);x.useEffect(()=>{y(0)},[a,o,d,f,r]),x.useEffect(()=>{l("all")},[t]);const p=Math.max(1,Math.ceil(S.length/f)),c=Math.min(k,p-1),v=c*f,g=S.slice(v,v+f);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"thread-sessions-head",children:[s.jsx("h3",{className:"section-title thread-sessions-title",children:"Sessions"}),s.jsxs("div",{className:"search-wrap",children:[s.jsx("input",{className:"search-input",placeholder:"search label, summary, decisions, open…",value:a,onChange:j=>i(j.target.value),onKeyDown:j=>{j.key==="Escape"&&i("")}}),a&&s.jsx("button",{type:"button",className:"search-clear",onClick:()=>i(""),"aria-label":"Clear search",children:s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),s.jsxs("div",{className:"thread-filters",children:[N.length>1&&s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Agent filter",children:[s.jsx("button",{type:"button",className:`chip${r==="all"?" active":""}`,onClick:()=>l("all"),children:"all"}),N.map(j=>{const w=e.filter(C=>C.runtime===j).length;return s.jsxs("button",{type:"button",className:`chip${r===j?" active":""}`,onClick:()=>l(j),children:[j," · ",w]},j)})]}),s.jsx("div",{className:"filter-group",role:"group","aria-label":"Status filter",children:["all","active","idle","closed","superseded"].map(j=>{const w=j==="all"?e.length:e.filter(C=>C.status===j).length;return s.jsxs("button",{type:"button",className:`chip${o===j?" active":""}`,"data-status":j==="all"?void 0:j,onClick:()=>u(j),children:[j," · ",w]},j)})}),s.jsx("div",{className:"filter-group",role:"group","aria-label":"Marker filter",children:["all","decisions","open"].map(j=>{const w=j==="decisions"?e.filter(C=>C.decisions.length>0).length:e.filter(C=>C.open_questions.length>0).length;return s.jsx("button",{type:"button",className:`chip${d===j?" active":""}`,"data-marker":j==="all"?void 0:j,onClick:()=>h(j),children:j==="all"?"all":`${j} · ${w}`},j)})}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[S.length," match",S.length===1?"":"es"]})]}),s.jsxs("ul",{className:"session-list",children:[g.map(j=>s.jsxs("li",{className:"session-row session-row-detail clickable",onClick:()=>n(j.id),children:[s.jsx("span",{className:`chip-inline status-${j.status}`,children:j.status}),s.jsxs("div",{className:"session-row-main",children:[s.jsx("span",{className:"session-label",children:j.label}),s.jsx("span",{className:"session-meta",children:j.summary})]}),s.jsx("span",{className:"muted small mono",children:qe(j.started_at)})]},j.id)),g.length===0&&s.jsx("li",{className:"muted empty-row",children:e.length===0?"No sessions yet.":"No sessions match the current filters."})]}),S.length>0&&s.jsxs("div",{className:"pagination",children:[s.jsxs("div",{className:"page-size",children:[s.jsx("label",{className:"form-label",children:"Per page"}),s.jsx("select",{className:"form-input form-input-inline",value:f,onChange:j=>m(Number.parseInt(j.target.value,10)),children:Qm.map(j=>s.jsx("option",{value:j,children:j},j))})]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[v+1,"–",Math.min(v+f,S.length)," of ",S.length]}),s.jsxs("div",{className:"page-nav",children:[s.jsx("button",{type:"button",className:"chip",disabled:c===0,onClick:()=>y(0),children:"« first"}),s.jsx("button",{type:"button",className:"chip",disabled:c===0,onClick:()=>y(j=>Math.max(0,j-1)),children:"‹ prev"}),s.jsxs("span",{className:"page-indicator mono",children:[c+1," / ",p]}),s.jsx("button",{type:"button",className:"chip",disabled:c>=p-1,onClick:()=>y(j=>Math.min(p-1,j+1)),children:"next ›"}),s.jsx("button",{type:"button",className:"chip",disabled:c>=p-1,onClick:()=>y(p-1),children:"last »"})]})]})]})}const Xm=[24,48,96];function Gm({data:e}){const[t,n]=x.useState("all"),[r,l]=x.useState(""),[a,i]=x.useState("most-active"),[o,u]=x.useState(48),[d,h]=x.useState(0),f=x.useMemo(()=>{const c=new Map;for(const v of e.sessions)for(const g of v.entities){let j=c.get(g);j||(j=new Set,c.set(g,j)),j.add(v.runtime)}return c},[e.sessions]),m=x.useMemo(()=>[...e.runtimes].sort((c,v)=>v.sessions_total-c.sessions_total),[e.runtimes]),k=x.useMemo(()=>{const c=r.toLowerCase().trim(),v=c?e.entities.filter(j=>j.canonical.toLowerCase().includes(c)):[...e.entities],g=t==="all"?v:v.filter(j=>{var w;return((w=f.get(j.canonical))==null?void 0:w.has(t))??!1});return g.sort((j,w)=>a==="most-active"?w.session_count-j.session_count:a==="least-active"?j.session_count-w.session_count:a==="a-z"?j.canonical.localeCompare(w.canonical):w.canonical.localeCompare(j.canonical)),g},[e.entities,r,a,t,f]);x.useEffect(()=>{h(0)},[r,a,o,t]);const y=Math.max(1,Math.ceil(k.length/o)),N=Math.min(d,y-1),S=N*o,p=k.slice(S,S+o);return s.jsxs("div",{className:"page-pad",children:[s.jsx("h2",{className:"page-title",children:"Thread"}),s.jsx("p",{className:"muted",children:"Pick an entity to view its reasoning history."}),s.jsxs("div",{className:"thread-sessions-head",style:{marginTop:16},children:[s.jsxs("div",{className:"search-wrap",style:{maxWidth:320},children:[s.jsx("input",{className:"search-input",placeholder:"search entities…",value:r,onChange:c=>l(c.target.value),onKeyDown:c=>{c.key==="Escape"&&l("")}}),r&&s.jsx("button",{type:"button",className:"search-clear",onClick:()=>l(""),"aria-label":"Clear search",children:s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),s.jsx("span",{className:"header-spacer"}),s.jsx("span",{className:"muted small",children:r?`${k.length} of ${e.entities.length} entities`:`${e.entities.length} entities`})]}),s.jsxs("div",{className:"thread-filters",children:[s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Agent filter",children:[s.jsx("button",{type:"button",className:`chip${t==="all"?" active":""}`,onClick:()=>n("all"),children:"all"}),m.map(c=>s.jsxs("button",{type:"button",className:`chip${t===c.name?" active":""}`,onClick:()=>n(c.name),children:[c.name," · ",c.sessions_total]},c.name))]}),s.jsx("div",{className:"filter-group",role:"group","aria-label":"Sort order",children:["most-active","least-active","a-z","z-a"].map(c=>s.jsx("button",{type:"button",className:`chip${a===c?" active":""}`,onClick:()=>i(c),children:c==="most-active"?"most active":c==="least-active"?"least active":c},c))})]}),s.jsxs("ul",{className:"entity-grid",children:[p.map(c=>s.jsx("li",{children:s.jsxs(Pr,{to:`/thread?entity=${encodeURIComponent(c.canonical)}`,className:"card card-lift entity-card",children:[s.jsx("span",{className:"dot",style:{background:e.entity_colors[c.canonical]??"#666"}}),s.jsx("span",{className:"entity-name",children:c.canonical}),s.jsx("span",{className:"muted small",children:c.session_count})]})},c.canonical)),p.length===0&&s.jsx("li",{style:{gridColumn:"1 / -1"},className:"muted empty-row",children:"No entities match."})]}),k.length>o&&s.jsxs("div",{className:"pagination",children:[s.jsxs("div",{className:"page-size",children:[s.jsx("label",{className:"form-label",children:"Per page"}),s.jsx("select",{className:"form-input form-input-inline",value:o,onChange:c=>u(Number.parseInt(c.target.value,10)),children:Xm.map(c=>s.jsx("option",{value:c,children:c},c))})]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[S+1,"–",Math.min(S+o,k.length)," of ",k.length]}),s.jsxs("div",{className:"page-nav",children:[s.jsx("button",{type:"button",className:"chip",disabled:N===0,onClick:()=>h(0),children:"« first"}),s.jsx("button",{type:"button",className:"chip",disabled:N===0,onClick:()=>h(c=>Math.max(0,c-1)),children:"‹ prev"}),s.jsxs("span",{className:"page-indicator mono",children:[N+1," / ",y]}),s.jsx("button",{type:"button",className:"chip",disabled:N>=y-1,onClick:()=>h(c=>Math.min(y-1,c+1)),children:"next ›"}),s.jsx("button",{type:"button",className:"chip",disabled:N>=y-1,onClick:()=>h(y-1),children:"last »"})]})]})]})}const Jm={days:7,total:0,with_results:0,hit_rate:0,by_source:{},top_queries:[],log_present:!1},Zm={days:7,total:0,with_results:0,hit_rate:0,by_source:{},top_subjects:[],top_predicates:[],log_present:!1},qm=[7,30,90];function ev(){const[e,t]=x.useState(7),n=er(`/api/recall/stats?days=${e}`,3e4,Jm),r=er(`/api/recall/facts/stats?days=${e}`,3e4,Zm);return s.jsxs("div",{className:"page-pad",children:[s.jsxs("div",{className:"recall-head",children:[s.jsxs("p",{className:"muted small recall-note",children:["Hit rate measures whether recall returned something — not whether the agent used it. Watch ",s.jsx("strong",{children:"by source"})," for adoption and ",s.jsx("strong",{children:"hit rate"})," for whether the corpus covers what's being asked."]}),s.jsx("div",{className:"filter-group",role:"group","aria-label":"Time window",children:qm.map(l=>s.jsxs("button",{type:"button",className:`chip${e===l?" active":""}`,onClick:()=>t(l),children:[l,"d"]},l))})]}),s.jsx(Jo,{title:"Session recall",subtitle:"What the orchestrator pulls when answering questions about past work — the human-operator surface.",stats:n.data,error:n.error,topLabel:"Top queries",topRows:n.data.top_queries.map(l=>({label:l.query,count:l.count}))}),s.jsx(Jo,{title:"Fact recall",subtitle:"Structured facts agents pull mid-task — the orchestrator surface.",stats:r.data,error:r.error,topLabel:"Top subjects",topRows:r.data.top_subjects.map(l=>({label:l.subject,count:l.count})),extraLabel:"Top predicates",extraRows:r.data.top_predicates.map(l=>({label:l.predicate,count:l.count}))})]})}function Jo({title:e,subtitle:t,stats:n,error:r,topLabel:l,topRows:a,extraLabel:i,extraRows:o}){const u=n.total-n.with_results,d=Object.entries(n.by_source).map(([h,f])=>({label:h,count:f})).sort((h,f)=>f.count-h.count);return s.jsxs("section",{className:"recall-block",children:[s.jsxs("header",{className:"recall-block-head",children:[s.jsx("h2",{className:"page-title",children:e}),s.jsx("p",{className:"muted small",children:t})]}),r&&s.jsx("div",{className:"muted error small",children:r}),n.log_present?n.total===0?s.jsxs("div",{className:"card recall-empty muted",children:["No queries in the last ",n.days," days. The log exists but this window is empty."]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"kpi-row",children:[s.jsx(Xr,{label:"Queries",value:n.total,hint:`last ${n.days}d`}),s.jsx(Xr,{label:"Hit rate",value:`${Math.round(n.hit_rate*100)}%`,hint:`${n.with_results.toLocaleString()} returned ≥1`}),s.jsx(Xr,{label:"Zero-result",value:u,hint:u>0?"corpus gaps":"full coverage"}),s.jsx(Xr,{label:"Sources",value:d.length,hint:"distinct callers"})]}),s.jsxs("div",{className:"recall-cards",children:[s.jsx(Rs,{title:"By source",rows:d,emptyText:"No sources recorded."}),s.jsx(Rs,{title:l,rows:a,emptyText:"None recorded."}),i&&o&&s.jsx(Rs,{title:i,rows:o,emptyText:"None recorded."})]})]}):s.jsx("div",{className:"card recall-empty muted",children:"No query log on disk yet — nothing has called this recall surface."})]})}function Xr({label:e,value:t,hint:n}){return s.jsxs("div",{className:"kpi",children:[s.jsx("span",{className:"kpi-label",children:e}),s.jsx("span",{className:"kpi-value",children:typeof t=="number"?t.toLocaleString():t}),n&&s.jsx("span",{className:"kpi-hint",children:n})]})}function Rs({title:e,rows:t,emptyText:n}){const r=Math.max(1,...t.map(l=>l.count));return s.jsxs("section",{className:"card",children:[s.jsx("header",{className:"card-head",children:s.jsx("h3",{children:e})}),s.jsxs("div",{className:"bar-stack recall-bars",children:[t.length===0&&s.jsx("div",{className:"muted small recall-bars-empty",children:n}),t.map(l=>s.jsxs("div",{className:"bar-item",children:[s.jsx("span",{className:"bar-label recall-bar-label",title:l.label,children:l.label}),s.jsx("div",{className:"bar-track",children:s.jsx("div",{className:"bar-fill tone-active",style:{width:`${l.count/r*100}%`}})}),s.jsx("span",{className:"bar-value mono",children:l.count.toLocaleString()})]},l.label))]})]})}const tv=[{to:"/settings",label:"Overview"},{to:"/settings/sources",label:"Sources"},{to:"/settings/providers",label:"Providers"},{to:"/settings/classifier",label:"Classifier"},{to:"/settings/labels",label:"Labels"},{to:"/settings/data",label:"Data"},{to:"/settings/views",label:"Views"}];function Jt(){return s.jsx("div",{className:"subnav",children:tv.map(e=>s.jsx(Ta,{to:e.to,end:e.to==="/settings",className:({isActive:t})=>`subnav-link${t?" active":""}`,children:e.label},e.to))})}const nv=[{to:"/settings/sources",title:"Sources",body:()=>"Transcript origins the daemon scans. Add Claude Code, Hermes, pi.dev, custom JSONL directories, or webhook ingest."},{to:"/settings/providers",title:"Providers",body:()=>"LLM endpoints (DeepSeek, Ollama, OpenAI, Anthropic, OpenRouter, custom). Manage keys and test connections."},{to:"/settings/labels",title:"Labels",body:({entities:e})=>`${e} entities catalogued. Promote candidates and edit types.`},{to:"/settings/classifier",title:"Classifier",body:({classifierProvider:e})=>e?`Active provider: ${e}.`:"Classifier provider unknown."},{to:"/settings/data",title:"Data",body:({sessions:e})=>`${e} sessions in the canonical store. Inspect path and backup posture.`},{to:"/settings/views",title:"Views",body:()=>"Default landing page, density, sort, density tier."}];function rv(){const{data:e}=Mn(),t={sessions:(e==null?void 0:e.meta.sessions_total)??0,entities:(e==null?void 0:e.meta.entities_total)??0,classifierProvider:null};return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsx("div",{className:"settings-grid",children:nv.map(n=>s.jsxs(Pr,{to:n.to,className:"card card-lift settings-card",children:[s.jsx("h3",{className:"settings-card-title",children:n.title}),s.jsx("p",{className:"settings-card-body",children:n.body(t)})]},n.to))})]})}function lv(e){if(e<1024)return`${e} B`;const t=["KB","MB","GB"];let n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n.toFixed(n>=100?0:1)} ${t[r]}`}function sv(){var f;const[e,t]=x.useState(null),[n,r]=x.useState(null),[l,a]=x.useState(null),[i,o]=x.useState(!1),u=x.useRef(null),d=x.useCallback(async()=>{try{const m=await fetch("/api/data/stats");if(!m.ok)throw new Error(`HTTP ${m.status}`);t(await m.json()),r(null)}catch(m){r(m instanceof Error?m.message:String(m))}},[]);x.useEffect(()=>{d()},[d]);const h=async()=>{var k,y;const m=(y=(k=u.current)==null?void 0:k.files)==null?void 0:y[0];if(m&&confirm(`Restore from "${m.name}"? Your current database is archived (not deleted), and the new one takes effect after the daemon restarts.`)){o(!0),a(null);try{const N=new FormData;N.append("file",m);const p=await(await fetch("/api/data/restore",{method:"POST",body:N})).json();a(p),p.staged&&u.current&&(u.current.value="")}catch(N){a({error:N instanceof Error?N.message:String(N)})}finally{o(!1)}}};return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsx("h2",{className:"page-title",children:"Data"}),!e&&!n&&s.jsx("div",{className:"muted",children:"Loading…"}),n&&s.jsx("div",{className:"muted error",children:n}),e&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-title",children:"Storage"}),s.jsxs("dl",{className:"kv-list",children:[s.jsx("dt",{className:"kv-label",children:"Canonical SQLite"}),s.jsx("dd",{className:"kv-value mono",children:e.dbPath}),s.jsx("dt",{className:"kv-label",children:"On disk"}),s.jsxs("dd",{className:"kv-value mono",children:[lv(e.dbBytes),!e.dbPresent&&s.jsx("span",{className:"muted small",children:" · file missing"})]}),s.jsx("dt",{className:"kv-label",children:"Schema version"}),s.jsxs("dd",{className:"kv-value mono",children:[e.schemaVersion??"—",e.migrations.length>0&&s.jsxs("span",{className:"muted small",children:[" · ",e.migrations.length," migrations applied"]})]})]}),s.jsx("h3",{className:"section-title",children:"Tables"}),s.jsxs("table",{className:"data-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Table"}),s.jsx("th",{children:"Rows"})]})}),s.jsx("tbody",{children:e.tables.map(m=>s.jsxs("tr",{children:[s.jsx("td",{className:"mono small",children:m.name}),s.jsx("td",{className:"mono",children:m.rows.toLocaleString()})]},m.name))})]}),e.runtimes.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-title",children:"Sessions by runtime"}),s.jsxs("table",{className:"data-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Runtime"}),s.jsx("th",{children:"Sessions"})]})}),s.jsx("tbody",{children:e.runtimes.map(m=>s.jsxs("tr",{children:[s.jsx("td",{className:"mono small",children:m.runtime}),s.jsx("td",{className:"mono",children:m.n.toLocaleString()})]},m.runtime))})]})]}),s.jsx("h3",{className:"section-title",children:"Backup"}),s.jsx("p",{className:"muted small",children:"Downloads a clean, defragmented snapshot of the canonical store. Safe to run while the daemon is ingesting."}),s.jsx("div",{className:"form-row",children:s.jsx("a",{className:"btn btn-accent",href:"/api/data/backup",download:!0,children:"Download backup"})}),s.jsx("h3",{className:"section-title",children:"Restore"}),s.jsxs("p",{className:"muted small",children:["Replace the canonical store with an ",s.jsx("code",{children:".sqlite"})," backup. The current database is archived alongside it (",s.jsx("code",{children:".pre-restore-<timestamp>"}),"), never deleted. Takes effect on the next daemon restart."]}),s.jsxs("div",{className:"form-row",children:[s.jsx("input",{ref:u,type:"file",accept:".sqlite,application/x-sqlite3",className:"file-input",disabled:i}),s.jsx("button",{type:"button",className:"btn",onClick:()=>void h(),disabled:i,children:i?"Validating…":"Restore from backup"})]}),(l==null?void 0:l.staged)&&s.jsx("div",{className:"card",style:{borderColor:"var(--accent)",padding:"0.75rem 1rem",marginTop:"0.75rem"},children:s.jsxs("p",{className:"small",style:{margin:0},children:["Backup validated and staged (",(f=l.sessions)==null?void 0:f.toLocaleString()," sessions, schema v",l.schemaVersion,").",s.jsx("strong",{children:" Restart the daemon"})," to apply it. Your current database will be archived automatically."]})}),(l==null?void 0:l.error)&&s.jsx("p",{className:"muted error small",children:l.error})]})]})}function av(){const[e,t]=x.useState(()=>es()),[n,r]=x.useState(!1),l=x.useRef(!0);x.useEffect(()=>{if(l.current){l.current=!1;return}bm(e),r(!0);const i=setTimeout(()=>r(!1),1800);return()=>clearTimeout(i)},[e]);const a=e.landing===xt.landing&&e.riverDensity===xt.riverDensity&&e.threadSort===xt.threadSort;return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsxs("div",{className:"form-row",style:{justifyContent:"space-between"},children:[s.jsx("h2",{className:"page-title",style:{margin:0},children:"Views"}),n&&s.jsx("span",{className:"muted small",children:"Saved"})]}),s.jsxs("div",{className:"form-grid",children:[s.jsx(Ms,{label:"Default landing",children:s.jsxs("select",{className:"form-input",value:e.landing,onChange:i=>t({...e,landing:i.target.value}),children:[s.jsx("option",{value:"live",children:"Live"}),s.jsx("option",{value:"pulse",children:"Pulse"}),s.jsx("option",{value:"river",children:"River"}),s.jsx("option",{value:"thread",children:"Thread"}),s.jsx("option",{value:"search",children:"Search"})]})}),s.jsx(Ms,{label:"River density",children:s.jsxs("select",{className:"form-input",value:e.riverDensity,onChange:i=>t({...e,riverDensity:i.target.value}),children:[s.jsx("option",{value:"compact",children:"Compact"}),s.jsx("option",{value:"comfortable",children:"Comfortable"}),s.jsx("option",{value:"spacious",children:"Spacious"})]})}),s.jsx(Ms,{label:"Thread sort",children:s.jsxs("select",{className:"form-input",value:e.threadSort,onChange:i=>t({...e,threadSort:i.target.value}),children:[s.jsx("option",{value:"recent",children:"Most recent first"}),s.jsx("option",{value:"oldest",children:"Oldest first"})]})})]}),s.jsx("div",{className:"form-row",children:s.jsx("button",{type:"button",className:"btn",onClick:()=>t(xt),disabled:a,children:"Reset to defaults"})}),s.jsx("p",{className:"muted small",children:"Preferences are stored per-device in localStorage. Landing applies on next load; River density and Thread sort apply when you open those pages."})]})}function Ms({label:e,children:t}){return s.jsxs("label",{className:"form-field",children:[s.jsx("span",{className:"form-label",children:e}),t]})}const Os=["candidate","project","tool","contact","service","concept"],iv=["all","active","snoozed","retired"],ov=[{value:"sessions-desc",label:"Sessions (high → low)"},{value:"sessions-asc",label:"Sessions (low → high)"},{value:"name-asc",label:"Name (A → Z)"},{value:"name-desc",label:"Name (Z → A)"},{value:"recent",label:"Most recently seen"},{value:"oldest",label:"Least recently seen"}],uv=[25,50,100,200];function cv(){const{data:e,loading:t,error:n,refetch:r}=Mn(),[l,a]=x.useState(""),[i,o]=x.useState("all"),[u,d]=x.useState("all"),[h,f]=x.useState("sessions-desc"),[m,k]=x.useState(50),[y,N]=x.useState(0),[S,p]=x.useState(null),c=(e==null?void 0:e.entities)??[],v=x.useMemo(()=>{const L=new Set(Os);for(const R of c)L.add(R.type);return["all",...[...L].sort()]},[c]),g=x.useMemo(()=>{const L=l.toLowerCase().trim(),F=[...c.filter(I=>i!=="all"&&I.type!==i||u!=="all"&&I.status!==u?!1:L?I.canonical.toLowerCase().includes(L)||I.type.toLowerCase().includes(L):!0)];return F.sort((I,H)=>{switch(h){case"sessions-desc":return H.session_count-I.session_count;case"sessions-asc":return I.session_count-H.session_count;case"name-asc":return I.canonical.localeCompare(H.canonical);case"name-desc":return H.canonical.localeCompare(I.canonical);case"recent":return(H.last_seen_session??"").localeCompare(I.last_seen_session??"");case"oldest":return(I.last_seen_session??"").localeCompare(H.last_seen_session??"")}}),F},[c,l,i,u,h]);x.useEffect(()=>{N(0)},[l,i,u,h,m]);const j=Math.max(1,Math.ceil(g.length/m)),w=Math.min(y,j-1),C=w*m,_=g.slice(C,C+m),$=async(L,R)=>{p(L);try{await R(),await r()}finally{p(null)}},T=(L,R)=>$(L,()=>yn({kind:"label_entity",subject_type:"entity",subject_id:L,payload:{new_type:R}}).then(()=>{})),D=L=>$(L,()=>yn({kind:"retire_entity",subject_type:"entity",subject_id:L}).then(()=>{})),W=L=>{const R=new Date(Date.now()+2592e6).toISOString();return $(L,()=>yn({kind:"snooze",subject_type:"entity",subject_id:L,payload:{snoozed_until:R}}).then(()=>{}))};return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsxs("div",{className:"page-header",children:[s.jsx("h2",{className:"page-title",children:"Labels"}),s.jsx("input",{className:"search-input",placeholder:"search canonical or type…",value:l,onChange:L=>a(L.target.value)})]}),s.jsxs("div",{className:"thread-filters",children:[s.jsx("div",{className:"filter-group",role:"group","aria-label":"Status filter",children:iv.map(L=>s.jsx("button",{type:"button",className:`chip${u===L?" active":""}`,onClick:()=>d(L),children:L},L))}),s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Type filter",children:[s.jsx("label",{className:"form-label",children:"Type"}),s.jsx("select",{className:"form-input form-input-inline",value:i,onChange:L=>o(L.target.value),children:v.map(L=>s.jsx("option",{value:L,children:L},L))})]}),s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Sort",children:[s.jsx("label",{className:"form-label",children:"Sort"}),s.jsx("select",{className:"form-input form-input-inline",value:h,onChange:L=>f(L.target.value),children:ov.map(L=>s.jsx("option",{value:L.value,children:L.label},L.value))})]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[g.length," match",g.length===1?"":"es"]})]}),n&&s.jsx("div",{className:"muted error",children:n}),s.jsxs("table",{className:"data-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Canonical"}),s.jsx("th",{children:"Type"}),s.jsx("th",{children:"Status"}),s.jsx("th",{className:"right",children:"Sessions"}),s.jsx("th",{children:"Last seen"}),s.jsx("th",{children:"Actions"})]})}),t&&!e&&s.jsx(Em,{rows:8,cols:6}),s.jsxs("tbody",{children:[_.map(L=>{const R=S===L.canonical;return s.jsxs("tr",{className:R?"row-busy":"",children:[s.jsxs("td",{className:"canonical",children:[s.jsx("span",{className:"dot",style:{background:(e==null?void 0:e.entity_colors[L.canonical])??"#666"}}),L.canonical]}),s.jsx("td",{children:s.jsx("select",{className:"form-input form-input-inline",value:Os.includes(L.type)?L.type:"candidate",onChange:F=>void T(L.canonical,F.target.value),disabled:R,children:Os.map(F=>s.jsx("option",{value:F,children:F},F))})}),s.jsx("td",{children:s.jsx("span",{className:`chip-inline status-${L.status}`,children:L.status})}),s.jsx("td",{className:"right mono",children:L.session_count}),s.jsx("td",{className:"mono small",children:L.last_seen_session??"—"}),s.jsxs("td",{className:"row-actions",children:[s.jsx("button",{type:"button",className:"chip",disabled:R,onClick:()=>void W(L.canonical),children:"snooze 30d"}),s.jsx("button",{type:"button",className:"chip",disabled:R,onClick:()=>void D(L.canonical),children:"retire"})]})]},L.canonical)}),_.length===0&&s.jsx("tr",{children:s.jsx("td",{colSpan:6,className:"muted small empty-row",children:c.length===0?"No entities yet.":"No entities match the current filters."})})]})]}),g.length>0&&s.jsxs("div",{className:"pagination",children:[s.jsxs("div",{className:"page-size",children:[s.jsx("label",{className:"form-label",children:"Per page"}),s.jsx("select",{className:"form-input form-input-inline",value:m,onChange:L=>k(Number.parseInt(L.target.value,10)),children:uv.map(L=>s.jsx("option",{value:L,children:L},L))})]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[C+1,"–",Math.min(C+m,g.length)," of ",g.length]}),s.jsxs("div",{className:"page-nav",children:[s.jsx("button",{type:"button",className:"chip",disabled:w===0,onClick:()=>N(0),children:"« first"}),s.jsx("button",{type:"button",className:"chip",disabled:w===0,onClick:()=>N(L=>Math.max(0,L-1)),children:"‹ prev"}),s.jsxs("span",{className:"page-indicator mono",children:[w+1," / ",j]}),s.jsx("button",{type:"button",className:"chip",disabled:w>=j-1,onClick:()=>N(L=>Math.min(j-1,L+1)),children:"next ›"}),s.jsx("button",{type:"button",className:"chip",disabled:w>=j-1,onClick:()=>N(j-1),children:"last »"})]})]}),s.jsx("p",{className:"muted small",children:"Changes are append-only actions; refresh re-applies the overlay over the persisted store."})]})}const dv=["claude-code","hermes","pi","jsonl-generic","webhook"],fv=["deepseek","ollama","openai","anthropic","openrouter","openai-compatible"],nr={deepseek:"DeepSeek",ollama:"Ollama",openai:"OpenAI",anthropic:"Anthropic",openrouter:"OpenRouter","openai-compatible":"OpenAI-compatible"},_d={"claude-code":"Claude Code",hermes:"Hermes",pi:"pi.dev","jsonl-generic":"Custom JSONL",webhook:"Webhook"},Zo={"claude-code":{name:"Claude Code",runtimeLabel:"claude-code",pathOrUrl:"~/.claude/projects",parseConfig:{}},hermes:{name:"Hermes",runtimeLabel:"hermes",pathOrUrl:"~/.hermes/sessions",parseConfig:{}},pi:{name:"pi.dev",runtimeLabel:"pi",pathOrUrl:"~/.pi/transcripts",parseConfig:{}},"jsonl-generic":{name:"",runtimeLabel:"",pathOrUrl:"",parseConfig:{idField:"session_id",textField:"text",startedAtField:"started_at",endedAtField:"ended_at"}},webhook:{name:"",runtimeLabel:"",pathOrUrl:null,parseConfig:{}}},qo={deepseek:{baseUrl:"https://api.deepseek.com",defaultModel:"deepseek-v4-flash"},ollama:{baseUrl:"http://localhost:11434",defaultModel:"phi4-mini:latest"},openai:{baseUrl:"https://api.openai.com/v1",defaultModel:"gpt-4o-mini"},anthropic:{baseUrl:"https://api.anthropic.com",defaultModel:"claude-haiku-4-5-20251001"},openrouter:{baseUrl:"https://openrouter.ai/api/v1",defaultModel:"anthropic/claude-haiku-4-5"},"openai-compatible":{baseUrl:"",defaultModel:null}};async function pv(){const e=await fetch("/api/sources");if(!e.ok)throw new Error(`HTTP ${e.status}`);return(await e.json()).sources}async function Pd(){const e=await fetch("/api/providers");if(!e.ok)throw new Error(`HTTP ${e.status}`);return(await e.json()).providers}async function hv(e){const t=await fetch(`/api/providers/${e}/models`),n=await t.json();if(!t.ok||n.error)throw new Error(n.error??`HTTP ${t.status}`);return n.models??[]}async function Li(e){return await(await fetch(`/api/providers/${e}/test`,{method:"POST"})).json()}function mv(){const[e,t]=x.useState(null),[n,r]=x.useState([]),[l,a]=x.useState([]),[i,o]=x.useState(null),[u,d]=x.useState(null),[h,f]=x.useState(""),[m,k]=x.useState(null),[y,N]=x.useState(null),[S,p]=x.useState(!1),[c,v]=x.useState(null),[g,j]=x.useState(null),w=x.useCallback(async()=>{try{const[R,F]=await Promise.all([fetch("/api/classifier/info").then(z=>z.json()),Pd()]);t(R),r(F);const I=F.find(z=>z.kind===R.provider&&z.enabled),H=F.find(z=>z.enabled)??F[0]??null,M=I??H;d(M?M.id:null),f(R.model),j(null)}catch(R){j(R instanceof Error?R.message:String(R))}},[]);x.useEffect(()=>{w()},[w]);const C=x.useMemo(()=>n.find(R=>R.id===u)??null,[n,u]);x.useEffect(()=>{if(!C){a([]);return}let R=!1;return o(null),a([]),hv(C.id).then(F=>{R||(a(F),(!h||!F.includes(h))&&f(C.defaultModel??F[0]??""))}).catch(F=>{R||o(F instanceof Error?F.message:String(F))}),()=>{R=!0}},[C==null?void 0:C.id]);const _=C?`${C.id}|${h}`:"",$=(m==null?void 0:m.ok)===!0&&y===_,D=(e&&C?C.kind!==e.provider||h!==e.model:!1)&&h.length>0&&!S&&$,W=async()=>{if(C){p(!0),k(null),N(null);try{const R=await Li(C.id);k(R),R.ok&&N(_)}catch(R){k({ok:!1,latencyMs:0,error:R instanceof Error?R.message:String(R)})}finally{p(!1)}}},L=async()=>{if(C){p(!0),v(null);try{const R=await fetch("/api/classifier",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:C.kind,model:h})}),F=await R.json();!R.ok||F.error?v(`Error: ${F.error??R.statusText}`):(v(`Active: ${F.provider} · ${F.model}`),await w())}catch(R){v(`Error: ${R instanceof Error?R.message:String(R)}`)}finally{p(!1)}}};return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsx("h2",{className:"page-title",children:"Classifier"}),!e&&!g&&s.jsx("div",{className:"muted",children:"Loading…"}),g&&s.jsx("div",{className:"muted error",children:g}),e&&s.jsxs(s.Fragment,{children:[s.jsxs("dl",{className:"kv-list",children:[s.jsx("dt",{className:"kv-label",children:"Active provider"}),s.jsx("dd",{className:"kv-value mono",children:e.provider}),s.jsx("dt",{className:"kv-label",children:"Active model"}),s.jsx("dd",{className:"kv-value mono",children:e.model})]}),s.jsx("h3",{className:"section-title",children:"Switch model"}),n.length===0?s.jsxs("p",{className:"muted small",children:["No providers configured. Add one on the ",s.jsx("a",{href:"/settings/providers",children:"Providers"})," page first."]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:"Provider"}),s.jsx("select",{className:"form-input form-input-inline",value:u??"",onChange:R=>{d(Number.parseInt(R.target.value,10)),k(null),N(null)},disabled:S,children:n.map(R=>s.jsxs("option",{value:R.id,disabled:!R.enabled,children:[R.name," (",nr[R.kind],")",R.enabled?"":" — disabled",R.kind!=="ollama"&&!R.hasApiKey?" — no key":""]},R.id))}),s.jsx("label",{className:"form-label",children:"Model"}),s.jsxs("select",{className:"form-input form-input-inline",value:h,onChange:R=>{f(R.target.value),N(null)},disabled:S||l.length===0,children:[l.map(R=>s.jsx("option",{value:R,children:R},R)),!l.includes(h)&&h&&s.jsx("option",{value:h,children:h})]}),s.jsx("button",{type:"button",className:"btn",onClick:()=>void W(),disabled:S||!C,children:S&&!m?"Testing…":"Test connection"}),s.jsx("button",{type:"button",className:"btn btn-accent",onClick:()=>void L(),disabled:!D,title:$?void 0:"Run a successful test before saving",children:S&&(m!=null&&m.ok)?"Saving…":"Save"})]}),i&&s.jsxs("p",{className:"muted error small",children:["Model list failed: ",i]}),m&&s.jsx("p",{className:`small ${m.ok?"muted":"muted error"}`,children:m.ok?`Connection OK · ${m.modelCount??"?"} models · ${m.latencyMs}ms`:`Connection failed: ${m.error??"unknown"} (${m.latencyMs}ms)`}),c&&s.jsx("p",{className:"muted small",children:c}),s.jsx("p",{className:"muted small",children:"Save is gated on a passing connection test for the selected provider + model."})]}),s.jsx("h3",{className:"section-title",children:"Embedder"}),s.jsxs("dl",{className:"kv-list",children:[s.jsx("dt",{className:"kv-label",children:"Provider"}),s.jsx("dd",{className:"kv-value mono",children:e.embedder.provider}),s.jsx("dt",{className:"kv-label",children:"Model"}),s.jsx("dd",{className:"kv-value mono",children:e.embedder.model}),s.jsx("dt",{className:"kv-label",children:"Dimensions"}),s.jsx("dd",{className:"kv-value mono",children:e.embedder.dims})]}),s.jsx("p",{className:"muted small",children:"Embedder is fixed at build time. Recall vectors must match the index dims, so it isn't hot-swappable. DeepSeek has no embeddings endpoint; Ollama serves both classification (optional) and embedding (always)."})]})]})}function vv(){const[e,t]=x.useState([]),[n,r]=x.useState(null),[l,a]=x.useState(!0),[i,o]=x.useState(!1),[u,d]=x.useState(null),h=x.useCallback(async()=>{a(!0);try{t(await pv()),r(null)}catch(y){r(y instanceof Error?y.message:String(y))}finally{a(!1)}},[]);x.useEffect(()=>{h()},[h]);const f=async y=>{await fetch(`/api/sources/${y.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!y.enabled})}),await h()},m=async y=>{confirm(`Delete source "${y.name}"? This stops scanning but leaves ingested sessions in place.`)&&(await fetch(`/api/sources/${y.id}`,{method:"DELETE"}),await h())},k=async y=>{if(!confirm(`Regenerate token for "${y.name}"? Any client using the current token will stop working.`))return;const N=await fetch(`/api/sources/${y.id}/regenerate-token`,{method:"POST"}),S=await N.json();S.token?(d({name:y.name,token:S.token}),await h()):alert(`Failed: ${S.error??N.statusText}`)};return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsxs("div",{className:"form-row",style:{justifyContent:"space-between"},children:[s.jsx("h2",{className:"page-title",style:{margin:0},children:"Sources"}),s.jsx("button",{type:"button",className:"btn btn-accent",onClick:()=>o(!0),children:"Add source"})]}),u&&s.jsx(gv,{name:u.name,token:u.token,onDismiss:()=>d(null)}),l&&e.length===0&&s.jsx("div",{className:"muted",children:"Loading…"}),n&&s.jsx("div",{className:"muted error",children:n}),e.length>0&&s.jsxs("table",{className:"data-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Kind"}),s.jsx("th",{children:"Runtime"}),s.jsx("th",{children:"Path / URL"}),s.jsx("th",{children:"Status"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:e.map(y=>s.jsxs("tr",{children:[s.jsx("td",{className:"mono",children:y.name}),s.jsx("td",{children:_d[y.kind]}),s.jsx("td",{className:"mono small",children:y.runtimeLabel}),s.jsx("td",{className:"mono small",children:y.pathOrUrl??(y.kind==="webhook"?"—":"")}),s.jsx("td",{children:s.jsx("span",{className:`chip-inline ${y.enabled?"status-active":"status-stale"}`,children:y.enabled?"enabled":"disabled"})}),s.jsx("td",{children:s.jsxs("div",{className:"form-row",style:{gap:"0.5rem"},children:[s.jsx("button",{type:"button",className:"btn small",onClick:()=>void f(y),children:y.enabled?"Disable":"Enable"}),y.kind==="webhook"&&s.jsx("button",{type:"button",className:"btn small",onClick:()=>void k(y),children:"Regenerate token"}),s.jsx("button",{type:"button",className:"btn small",onClick:()=>void m(y),children:"Delete"})]})})]},y.id))})]}),!l&&e.length===0&&s.jsx("p",{className:"muted small",children:'No sources yet. Click "Add source" to scan your first transcript directory.'}),i&&s.jsx(yv,{onClose:()=>o(!1),onCreated:y=>{o(!1),y.kind==="webhook"&&y.token&&d({name:y.name,token:y.token}),h()}})]})}function gv({name:e,token:t,onDismiss:n}){return s.jsxs("div",{className:"card",style:{borderColor:"var(--accent)",padding:"1rem",marginTop:"1rem"},children:[s.jsxs("h3",{className:"section-title",style:{marginTop:0},children:['One-time token for "',e,'"']}),s.jsxs("p",{className:"muted small",children:["Copy this now. It's stored hashed on the daemon and won't be shown again. Send sessions with"," ",s.jsx("code",{children:"Authorization: Bearer <token>"})," to ",s.jsx("code",{children:"POST /api/ingest"}),"."]}),s.jsx("pre",{className:"mono",style:{padding:"0.5rem",overflow:"auto"},children:t}),s.jsxs("div",{className:"form-row",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>void navigator.clipboard.writeText(t),children:"Copy"}),s.jsx("button",{type:"button",className:"btn btn-accent",onClick:n,children:"I've stored it"})]})]})}function yv({onClose:e,onCreated:t}){const[n,r]=x.useState("claude-code"),l=Zo[n],[a,i]=x.useState(l.name),[o,u]=x.useState(l.runtimeLabel),[d,h]=x.useState(l.pathOrUrl??""),[f,m]=x.useState({idField:"session_id",textField:"text",startedAtField:"started_at",endedAtField:"ended_at"}),[k,y]=x.useState(!1),[N,S]=x.useState(null);x.useEffect(()=>{const j=Zo[n];i(j.name),u(j.runtimeLabel),h(j.pathOrUrl??""),S(null)},[n]);const p=n!=="webhook",c=n==="jsonl-generic",v=async()=>{y(!0),S(null);try{const j={kind:n,name:a,runtimeLabel:o};p&&(j.pathOrUrl=d),c&&(j.parseConfig=f);const w=await fetch("/api/sources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(j)}),C=await w.json();if(!w.ok||C.error){S(C.error??w.statusText);return}t(C)}catch(j){S(j instanceof Error?j.message:String(j))}finally{y(!1)}},g=!k&&a.length>0&&o.length>0&&(!p||d.length>0);return s.jsxs("div",{className:"card",style:{padding:"1rem",marginTop:"1rem"},children:[s.jsx("h3",{className:"section-title",style:{marginTop:0},children:"Add source"}),s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:"Kind"}),s.jsx("select",{className:"form-input form-input-inline",value:n,onChange:j=>r(j.target.value),disabled:k,children:dv.map(j=>s.jsx("option",{value:j,children:_d[j]},j))})]}),s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:"Name"}),s.jsx("input",{className:"form-input form-input-inline",value:a,onChange:j=>i(j.target.value),placeholder:c||n==="webhook"?"e.g. my-agent":"",disabled:k}),s.jsx("label",{className:"form-label",children:"Runtime label"}),s.jsx("input",{className:"form-input form-input-inline",value:o,onChange:j=>u(j.target.value),placeholder:"appears on Pulse Runtimes card",disabled:k})]}),p&&s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:n==="jsonl-generic"?"Directory":"Path"}),s.jsx("input",{className:"form-input form-input-inline",style:{minWidth:"32rem"},value:d,onChange:j=>h(j.target.value),placeholder:"absolute or ~/ path to JSONL directory",disabled:k})]}),c&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{className:"section-title",style:{fontSize:"0.875rem"},children:"JSONL field mapping"}),s.jsx("p",{className:"muted small",children:"How to read your JSONL files. Each row should be one session. Use dot.notation for nested fields."}),["idField","textField","startedAtField","endedAtField"].map(j=>s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:j}),s.jsx("input",{className:"form-input form-input-inline",value:f[j],onChange:w=>m({...f,[j]:w.target.value}),disabled:k})]},j))]}),n==="webhook"&&s.jsxs("p",{className:"muted small",children:["A bearer token will be generated and shown ",s.jsx("strong",{children:"once"})," when you create this source. Use it to ",s.jsx("code",{children:"POST /api/ingest"})," from any agent or script."]}),N&&s.jsx("p",{className:"muted error small",children:N}),s.jsxs("div",{className:"form-row",children:[s.jsx("button",{type:"button",className:"btn btn-accent",onClick:()=>void v(),disabled:!g,children:k?"Creating…":"Create"}),s.jsx("button",{type:"button",className:"btn",onClick:e,disabled:k,children:"Cancel"})]})]})}function xv(){const[e,t]=x.useState([]),[n,r]=x.useState(null),[l,a]=x.useState(!0),[i,o]=x.useState(!1),[u,d]=x.useState({}),h=x.useCallback(async()=>{a(!0);try{t(await Pd()),r(null)}catch(y){r(y instanceof Error?y.message:String(y))}finally{a(!1)}},[]);x.useEffect(()=>{h()},[h]);const f=async y=>{await fetch(`/api/providers/${y.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!y.enabled})}),await h()},m=async y=>{confirm(`Delete provider "${y.name}"? The Classifier will fall back to another provider if this one was active.`)&&(await fetch(`/api/providers/${y.id}`,{method:"DELETE"}),await h())},k=async y=>{d(N=>({...N,[y.id]:"running"}));try{const N=await Li(y.id);d(S=>({...S,[y.id]:N}))}catch(N){d(S=>({...S,[y.id]:{ok:!1,latencyMs:0,error:N instanceof Error?N.message:String(N)}}))}};return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsxs("div",{className:"form-row",style:{justifyContent:"space-between"},children:[s.jsx("h2",{className:"page-title",style:{margin:0},children:"Providers"}),s.jsx("button",{type:"button",className:"btn btn-accent",onClick:()=>o(!0),children:"Add provider"})]}),l&&e.length===0&&s.jsx("div",{className:"muted",children:"Loading…"}),n&&s.jsx("div",{className:"muted error",children:n}),e.length>0&&s.jsxs("table",{className:"data-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Kind"}),s.jsx("th",{children:"Base URL"}),s.jsx("th",{children:"Default model"}),s.jsx("th",{children:"API key"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Last test"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:e.map(y=>{const N=u[y.id];return s.jsxs("tr",{children:[s.jsx("td",{className:"mono",children:y.name}),s.jsx("td",{children:nr[y.kind]}),s.jsx("td",{className:"mono small",children:y.baseUrl??"—"}),s.jsx("td",{className:"mono small",children:y.defaultModel??"—"}),s.jsx("td",{children:y.kind==="ollama"||y.kind==="openai-compatible"?s.jsx("span",{className:"muted small",children:y.hasApiKey?"set":"n/a"}):s.jsx("span",{className:`chip-inline ${y.hasApiKey?"status-active":"status-stale"}`,children:y.hasApiKey?"set":"missing"})}),s.jsx("td",{children:s.jsx("span",{className:`chip-inline ${y.enabled?"status-active":"status-stale"}`,children:y.enabled?"enabled":"disabled"})}),s.jsxs("td",{className:"small",children:[N==="running"&&s.jsx("span",{className:"muted",children:"testing…"}),N&&N!=="running"&&N.ok&&s.jsxs("span",{className:"muted",children:["OK · ",N.modelCount," models · ",N.latencyMs,"ms"]}),N&&N!=="running"&&!N.ok&&s.jsxs("span",{className:"muted error",children:["fail: ",N.error]})]}),s.jsx("td",{children:s.jsxs("div",{className:"form-row",style:{gap:"0.5rem"},children:[s.jsx("button",{type:"button",className:"btn small",onClick:()=>void k(y),children:"Test"}),s.jsx("button",{type:"button",className:"btn small",onClick:()=>void f(y),children:y.enabled?"Disable":"Enable"}),s.jsx("button",{type:"button",className:"btn small",onClick:()=>void m(y),children:"Delete"})]})})]},y.id)})})]}),!l&&e.length===0&&s.jsx("p",{className:"muted small",children:'No providers yet. Click "Add provider" to wire up DeepSeek, Ollama, or any OpenAI-compatible endpoint.'}),i&&s.jsx(jv,{onClose:()=>o(!1),onCreated:()=>{o(!1),h()}})]})}function jv({onClose:e,onCreated:t}){const[n,r]=x.useState("deepseek"),l=qo[n],[a,i]=x.useState(nr[n]),[o,u]=x.useState(l.baseUrl??""),[d,h]=x.useState(""),[f,m]=x.useState(l.defaultModel??""),[k,y]=x.useState(!1),[N,S]=x.useState(null),[p,c]=x.useState(null);x.useEffect(()=>{const w=qo[n];i(nr[n]),u(w.baseUrl??""),m(w.defaultModel??""),c(null),S(null)},[n]);const v=n!=="ollama"&&n!=="openai-compatible",g=async w=>{y(!0),S(null);try{const C={kind:n,name:a};o&&(C.baseUrl=o),d&&(C.apiKey=d),f&&(C.defaultModel=f);const _=await fetch("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)}),$=await _.json();if(!_.ok||$.error){S($.error??_.statusText);return}if(w){const T=await Li($.id);if(c(T),!T.ok)return}t()}catch(C){S(C instanceof Error?C.message:String(C))}finally{y(!1)}},j=!k&&a.length>0&&(!v||d.length>0);return s.jsxs("div",{className:"card",style:{padding:"1rem",marginTop:"1rem"},children:[s.jsx("h3",{className:"section-title",style:{marginTop:0},children:"Add provider"}),s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:"Kind"}),s.jsx("select",{className:"form-input form-input-inline",value:n,onChange:w=>r(w.target.value),disabled:k,children:fv.map(w=>s.jsx("option",{value:w,children:nr[w]},w))}),s.jsx("label",{className:"form-label",children:"Name"}),s.jsx("input",{className:"form-input form-input-inline",value:a,onChange:w=>i(w.target.value),placeholder:"Display name (must be unique)",disabled:k})]}),s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:"Base URL"}),s.jsx("input",{className:"form-input form-input-inline",style:{minWidth:"28rem"},value:o,onChange:w=>u(w.target.value),placeholder:n==="openai-compatible"?"https://your-endpoint/v1":"",disabled:k})]}),s.jsxs("div",{className:"form-row",children:[s.jsxs("label",{className:"form-label",children:["API key",v?"":" (optional)"]}),s.jsx("input",{type:"password",className:"form-input form-input-inline",style:{minWidth:"28rem"},value:d,onChange:w=>h(w.target.value),autoComplete:"off",disabled:k})]}),s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:"Default model"}),s.jsx("input",{className:"form-input form-input-inline",value:f,onChange:w=>m(w.target.value),placeholder:"optional",disabled:k})]}),p&&!p.ok&&s.jsxs("p",{className:"muted error small",children:["Saved, but test failed: ",p.error," (",p.latencyMs,"ms). You can edit or delete from the list."]}),N&&s.jsx("p",{className:"muted error small",children:N}),s.jsxs("div",{className:"form-row",children:[s.jsx("button",{type:"button",className:"btn btn-accent",onClick:()=>void g(!0),disabled:!j,children:k?"Saving…":"Save & test"}),s.jsx("button",{type:"button",className:"btn",onClick:()=>void g(!1),disabled:!j,children:"Save without testing"}),s.jsx("button",{type:"button",className:"btn",onClick:e,disabled:k,children:"Cancel"})]})]})}function wv({page:e}){return s.jsxs("div",{className:"stub-shell",children:[s.jsxs("span",{className:"stub-name",children:["/",e]}),s.jsx("p",{children:"not yet ported from the Astro UI."}),s.jsx("p",{className:"stub-hint",children:"Tracked in NocoDB #95 (Vite + React SPA port)."})]})}function Nv(){return s.jsxs("div",{className:"page-shell",children:[s.jsx(fm,{}),s.jsxs("div",{className:"page-main",children:[s.jsx(kv,{}),s.jsxs(Gh,{children:[s.jsx(ve,{path:"/",element:s.jsx(Yh,{to:`/${es().landing}`,replace:!0})}),s.jsx(ve,{path:"/live",element:s.jsx(Lm,{})}),s.jsx(ve,{path:"/pulse",element:s.jsx(Rm,{})}),s.jsx(ve,{path:"/river",element:s.jsx(Dm,{})}),s.jsx(ve,{path:"/thread",element:s.jsx(Km,{})}),s.jsx(ve,{path:"/search",element:s.jsx(Hm,{})}),s.jsx(ve,{path:"/recall",element:s.jsx(ev,{})}),s.jsx(ve,{path:"/settings",element:s.jsx(rv,{})}),s.jsx(ve,{path:"/settings/sources",element:s.jsx(vv,{})}),s.jsx(ve,{path:"/settings/providers",element:s.jsx(xv,{})}),s.jsx(ve,{path:"/settings/labels",element:s.jsx(cv,{})}),s.jsx(ve,{path:"/settings/classifier",element:s.jsx(mv,{})}),s.jsx(ve,{path:"/settings/data",element:s.jsx(sv,{})}),s.jsx(ve,{path:"/settings/views",element:s.jsx(av,{})}),s.jsx(ve,{path:"*",element:s.jsx(wv,{page:"not found"})})]})]})]})}function kv(){const{pathname:e}=$t(),t=e.replace(/^\//,"").replace(/\/+$/,"")||"live";return s.jsxs("header",{className:"app-header",children:[s.jsx("span",{className:"wordmark-page",children:t}),s.jsx("span",{className:"header-spacer"}),s.jsx("span",{className:"status-dot","aria-hidden":"true"}),s.jsx("span",{className:"header-info",children:"nlm-memory · :3940"})]})}const Ld=document.getElementById("root");if(!Ld)throw new Error("missing #root");pd(Ld).render(s.jsx(cu.StrictMode,{children:s.jsx(sm,{basename:"/ui",children:s.jsx(Nv,{})})}));
69
+ […truncated]`:""]})]})]})]})]})}const tr=3e3,Pm=tr*3;function Ps(e){const t=x.useRef(null),[n,r]=x.useState(new Set),l=e.join("|");return x.useEffect(()=>{if(e.length===0)return;if(t.current===null){t.current=new Set(e);return}const a=e.filter(o=>!t.current.has(o));for(const o of e)t.current.add(o);if(a.length===0)return;r(o=>new Set([...o,...a]));const i=setTimeout(()=>{r(o=>{const u=new Set(o);for(const d of a)u.delete(d);return u})},1200);return()=>clearTimeout(i)},[l]),n}function Lm(){const e=er("/api/recall/recent?limit=50",tr,{entries:[]}),t=er("/api/live/recent-writes?limit=50",tr,{writes:[]}),n=er("/api/live/recent-markers?limit=50",tr,{markers:[]}),[r,l]=x.useState(null),a=e.data.entries.map(f=>`${f.ts}|${f.source}|${f.query??""}`),i=t.data.writes.map(f=>f.id),o=n.data.markers.map(f=>`${f.sessionId}|${f.kind}|${f.text}`),u=Ps(a),d=Ps(i),h=Ps(o);return s.jsxs("div",{className:"live-page",children:[s.jsx(Tm,{reads:e,writes:t,markers:n}),s.jsxs("div",{className:"live-board",children:[s.jsx(Ls,{title:"Reads",count:e.data.entries.length,loading:e.loading,emptyLabel:"no recent recall",children:e.data.entries.map((f,m)=>{const k=a[m];return s.jsxs("div",{className:`live-row${u.has(k)?" is-new":""}`,children:[s.jsx("span",{className:"live-tag",children:f.source}),s.jsx("span",{className:"label",children:f.query??"(no query)"}),s.jsxs("div",{className:"body",children:[f.mode," · ",f.nResults," hit",f.nResults===1?"":"s"]}),s.jsx("div",{className:"meta",children:ol(f.ts)})]},k)})}),s.jsx(Ls,{title:"Writes",count:t.data.writes.length,loading:t.loading,emptyLabel:"no recent writes",children:t.data.writes.map(f=>s.jsxs(Xo,{fresh:d.has(f.id),onOpen:()=>l(f.id),children:[s.jsx("span",{className:"live-tag",children:f.runtime.split("/")[0]}),s.jsx("span",{className:"label",children:f.label}),s.jsx("div",{className:"body",children:f.summary}),s.jsxs("div",{className:"meta",children:[ol(f.createdAt)," · ",f.id]})]},f.id))}),s.jsx(Ls,{title:"Markers",count:n.data.markers.length,loading:n.loading,emptyLabel:"no recent markers",children:n.data.markers.map((f,m)=>{const k=o[m];return s.jsxs(Xo,{fresh:h.has(k),onOpen:()=>l(f.sessionId),children:[s.jsx("span",{className:"live-tag","data-kind":f.kind,children:f.kind}),s.jsx("span",{className:"label",children:f.text}),s.jsx("div",{className:"body",children:f.label}),s.jsx("div",{className:"meta",children:ol(f.createdAt)})]},k)})})]}),r&&s.jsx(Lr,{sessionId:r,onClose:()=>l(null)})]})}function Tm({reads:e,writes:t,markers:n}){const r=[e,t,n],l=r.every(f=>f.loading),a=r.map(f=>f.lastUpdated).filter(f=>f!==null),i=a.length>0?Math.max(...a):null,o=r.some(f=>f.error!==null),u=i!==null&&Date.now()-i>Pm;let d;l?d="connecting":u||o?d="reconnecting":d="live";const h=d==="connecting"?"Connecting…":d==="reconnecting"?"Reconnecting…":"Live";return s.jsxs("div",{className:"live-status",children:[s.jsx("span",{className:`live-status-dot live-status-${d}`,"aria-hidden":"true"}),s.jsx("span",{className:"live-status-label",children:h}),i!==null&&s.jsxs("span",{className:"muted small",children:["updated ",ol(new Date(i).toISOString())]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small mono",children:["polling every ",tr/1e3,"s"]})]})}function Ls({title:e,count:t,loading:n,emptyLabel:r,children:l}){const a=t===0;return s.jsxs("section",{className:"live-col",children:[s.jsxs("header",{className:"live-col-head",children:[s.jsx("span",{className:"live-col-title",children:e}),s.jsx("span",{className:"live-col-count",children:t})]}),s.jsx("div",{className:"live-col-body",children:a?s.jsx("div",{className:"live-empty",children:n?"loading…":r}):l})]})}function Xo({fresh:e,onOpen:t,children:n}){return s.jsx("div",{className:`live-row clickable${e?" is-new":""}`,onClick:t,role:"button",tabIndex:0,onKeyDown:r=>{(r.key==="Enter"||r.key===" ")&&(r.preventDefault(),t())},children:n})}function Mn(e){const[t,n]=x.useState({data:null,loading:!0,error:null}),r=x.useRef(!1),l=x.useCallback(async()=>{try{const a=await fetch("/api/dataset");if(!a.ok)throw new Error(`HTTP ${a.status}`);const i=await a.json();r.current||n({data:i,loading:!1,error:null})}catch(a){if(!r.current){const i=a instanceof Error?a.message:String(a);n(o=>({data:o.data,loading:!1,error:i}))}}},[]);return x.useEffect(()=>(r.current=!1,l(),()=>{r.current=!0}),[e,l]),{...t,refetch:l}}function qe(e){if(!e)return"—";const t=Date.parse(e);if(!Number.isFinite(t))return"—";const n=Math.floor((Date.now()-t)/864e5);if(n<=0)return"today";if(n===1)return"1d";if(n<30)return`${n}d`;const r=Math.floor(n/30);return r<12?`${r}mo`:`${Math.floor(n/365)}y`}async function yn(e){const t=await fetch("/api/action",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,runtime:e.runtime??"web-ui"})});if(!t.ok)throw new Error(`POST /api/action → ${t.status}`);return(await t.json()).id}function Cd({openId:e,defaultText:t,onPromoted:n}){const[r,l]=x.useState(!1),[a,i]=x.useState(!1),[o,u]=x.useState(t),d=async()=>{const h=o.trim();if(h){i(!0);try{await yn({kind:"promote_open",subject_type:"open_question",subject_id:e,payload:{resolution:h,original_text:t}}),await n(),l(!1)}catch{i(!1)}}};return r?s.jsxs("div",{className:"promote-editor",onClick:h=>h.stopPropagation(),children:[s.jsx("input",{className:"form-input form-input-inline promote-input",value:o,onChange:h=>u(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),d()),h.key==="Escape"&&(h.preventDefault(),l(!1))},disabled:a,autoFocus:!0}),s.jsx("button",{type:"button",className:"chip",onClick:()=>void d(),disabled:a||!o.trim(),children:"save"}),s.jsx("button",{type:"button",className:"chip",onClick:()=>l(!1),disabled:a,children:"cancel"})]}):s.jsx("button",{type:"button",className:"chip promote-chip",onClick:()=>{u(t),l(!0)},children:"→ decision"})}function Rm(){const{data:e,loading:t,error:n,refetch:r}=Mn(),[l,a]=x.useState("all"),[i,o]=x.useState("oldest"),[u,d]=x.useState(null),[h,f]=x.useState(null),m=x.useMemo(()=>e?[...l==="all"?e.alerts:e.alerts.filter(c=>c.severity===l)].sort((c,v)=>i==="oldest"?v.age_days-c.age_days:c.age_days-v.age_days):[],[e,l,i]),k=async p=>{await yn({kind:"dismiss",subject_type:"alert",subject_id:p}),await r()},y=async(p,c)=>{const v=new Date(Date.now()+c*864e5).toISOString();await yn({kind:"snooze",subject_type:"alert",subject_id:p,payload:{snoozed_until:v}}),await r()},N=x.useMemo(()=>e?[...e.sessions].sort((p,c)=>(c.started_at??"").localeCompare(p.started_at??"")).slice(0,20):[],[e]);if(t&&!e)return s.jsx(Sm,{});if(n&&!e)return s.jsx("div",{className:"page-pad",children:s.jsx("div",{className:"muted error",children:n})});if(!e)return null;const S=u?e.alerts.find(p=>p.id===u)??null:null;return s.jsxs("div",{className:"page-pad",children:[s.jsxs("div",{className:"kpi-row",children:[s.jsx(Yr,{label:"This week",value:e.metrics.this_week,hint:`${e.metrics.last_week} last week`}),s.jsx(Yr,{label:"Sessions",value:e.meta.sessions_total,hint:"total"}),s.jsx(Yr,{label:"Entities",value:e.meta.entities_total,hint:"catalogued"}),s.jsx(Yr,{label:"Decisions",value:e.metrics.closed_decisions,hint:"non-superseded"}),s.jsx(zm,{values:e.metrics.sparkline})]}),s.jsxs("div",{className:"pulse-grid",children:[s.jsxs("section",{className:"card pulse-area-coherence",children:[s.jsx("header",{className:"card-head",children:s.jsx("h3",{children:"Coherence"})}),s.jsx($m,{metrics:e.metrics})]}),s.jsxs("section",{className:"card pulse-area-runtimes",children:[s.jsx("header",{className:"card-head",children:s.jsx("h3",{children:"Runtimes"})}),s.jsx(Im,{runtimes:e.runtimes})]}),s.jsxs("section",{className:"card pulse-scroll-card pulse-area-recent",children:[s.jsx("header",{className:"card-head",children:s.jsx("h3",{children:"Recent sessions"})}),s.jsx("div",{className:"pulse-scroll-body",children:s.jsx("ul",{className:"session-list",children:N.map(p=>s.jsxs("li",{className:"session-row clickable",onClick:()=>f(p.id),role:"button",tabIndex:0,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),f(p.id))},children:[s.jsx("span",{className:`chip-inline status-${p.status}`,children:p.status}),s.jsx("span",{className:"session-label",children:p.label}),s.jsxs("span",{className:"session-meta",children:[qe(p.started_at)," · ",p.entities.slice(0,3).join(", "),p.entities.length>3?` +${p.entities.length-3}`:""]})]},p.id))})})]}),s.jsxs("section",{className:"card pulse-scroll-card pulse-area-stale",children:[s.jsxs("header",{className:"card-head card-head-stack",children:[s.jsxs("div",{className:"card-head-row",children:[s.jsx("h3",{children:"Stale alerts"}),s.jsxs("span",{className:"muted small",children:[m.length,m.length!==e.alerts.length?` / ${e.alerts.length}`:""]})]}),s.jsxs("div",{className:"card-filters",children:[s.jsx("div",{className:"filter-group",role:"group","aria-label":"Severity",children:["all","high","medium"].map(p=>s.jsx("button",{type:"button",className:`chip${l===p?" active":""}`,"data-severity":p==="all"?void 0:p,onClick:()=>a(p),children:p},p))}),s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Sort",children:[s.jsx("button",{type:"button",className:`chip${i==="oldest"?" active":""}`,onClick:()=>o("oldest"),children:"oldest"}),s.jsx("button",{type:"button",className:`chip${i==="recent"?" active":""}`,onClick:()=>o("recent"),children:"recent"})]})]})]}),s.jsx("div",{className:"pulse-scroll-body",children:s.jsxs("ul",{className:"alert-list",children:[m.map(p=>s.jsxs("li",{className:"alert-row clickable",onClick:()=>d(p.id),role:"button",tabIndex:0,onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),d(p.id))},children:[s.jsx("span",{className:`chip-inline severity-${p.severity}`,children:p.severity}),s.jsx("span",{className:"alert-entity",children:p.entity}),s.jsx("span",{className:"alert-summary",children:p.summary}),s.jsxs("div",{className:"alert-actions",onClick:c=>c.stopPropagation(),children:[s.jsx("button",{type:"button",className:"chip",onClick:()=>void y(p.id,7),children:"snooze 7d"}),s.jsx("button",{type:"button",className:"chip",onClick:()=>void k(p.id),children:"dismiss"})]})]},p.id)),m.length===0&&s.jsx("li",{className:"muted alert-row-empty",children:e.alerts.length===0?"No stale alerts.":"No alerts match the current filters."})]})})]})]}),S&&s.jsx(Om,{alert:S,entity:e.entities.find(p=>p.canonical===S.entity)??null,entityColor:e.entity_colors[S.entity]??"#666",sessions:e.sessions,onClose:()=>d(null),onDismiss:async()=>{await k(S.id),d(null)},onSnooze:async p=>{await y(S.id,p),d(null)},onPromoted:r}),h&&s.jsx(Lr,{sessionId:h,onClose:()=>f(null),entityColor:(()=>{const p=e.sessions.find(v=>v.id===h),c=p==null?void 0:p.entities[0];return c?e.entity_colors[c]:void 0})()})]})}const Mm=[10,25,50];function Om({alert:e,entity:t,entityColor:n,sessions:r,onClose:l,onDismiss:a,onSnooze:i,onPromoted:o}){const u=_r(),[d,h]=x.useState(10),[f,m]=x.useState(0),k=x.useMemo(()=>r.filter(g=>g.entities.includes(e.entity)).sort((g,j)=>(j.started_at??"").localeCompare(g.started_at??"")),[r,e.entity]);x.useEffect(()=>{m(0)},[e.id,d]);const y=Math.max(1,Math.ceil(k.length/d)),N=Math.min(f,y-1),S=N*d,p=k.slice(S,S+d),c=x.useMemo(()=>k.flatMap(g=>g.open_questions.map(j=>({id:j.id,text:j.text,sid:g.id,when:g.started_at}))),[k]),v=x.useMemo(()=>k.flatMap(g=>g.decisions.map(j=>({text:j,sid:g.id,when:g.started_at}))),[k]);return x.useEffect(()=>{const g=j=>{j.key==="Escape"&&l()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[l]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"drawer-backdrop",onClick:l}),s.jsxs("aside",{className:"session-drawer",role:"dialog","aria-modal":"true","aria-label":`Alert detail: ${e.entity}`,children:[s.jsxs("header",{className:"drawer-head",children:[s.jsx("span",{className:"dot lg",style:{background:n}}),s.jsx("h3",{className:"drawer-title",children:e.entity}),s.jsx("span",{className:`chip-inline severity-${e.severity}`,children:e.severity}),s.jsx("button",{type:"button",className:"drawer-close",onClick:l,"aria-label":"Close",children:"×"})]}),s.jsxs("div",{className:"drawer-body",children:[s.jsx("p",{className:"drawer-paragraph",children:e.summary}),s.jsxs("dl",{className:"kv-list",children:[s.jsx("dt",{className:"kv-label",children:"Last touch"}),s.jsxs("dd",{className:"kv-value",children:[e.age_days," day",e.age_days===1?"":"s"," ago"]}),s.jsx("dt",{className:"kv-label",children:"Last session"}),s.jsx("dd",{className:"kv-value mono small",children:e.last_touch_at??"—"}),t&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{className:"kv-label",children:"Entity type"}),s.jsx("dd",{className:"kv-value",children:t.type}),s.jsx("dt",{className:"kv-label",children:"Total sessions"}),s.jsx("dd",{className:"kv-value mono",children:t.session_count})]})]}),s.jsxs("div",{className:"drawer-actions",children:[s.jsx("button",{type:"button",className:"btn btn-accent",onClick:()=>u(`/thread?entity=${encodeURIComponent(e.entity)}`),children:"Open thread"}),s.jsx("button",{type:"button",className:"btn",onClick:()=>void i(7),children:"Snooze 7d"}),s.jsx("button",{type:"button",className:"btn",onClick:()=>void i(30),children:"Snooze 30d"}),s.jsx("button",{type:"button",className:"btn btn-danger",onClick:()=>void a(),children:"Dismiss"})]}),c.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs("h4",{className:"drawer-section",children:["Open questions (",c.length,")"]}),s.jsx("ul",{className:"drawer-list",children:c.slice(0,12).map((g,j)=>s.jsxs("li",{className:"marker-row-promotable",children:[s.jsx("span",{className:"live-tag","data-kind":"open",children:"open"}),s.jsx("span",{className:"marker-text",children:g.text}),s.jsx(Cd,{openId:g.id,defaultText:g.text,onPromoted:o}),s.jsx("span",{className:"muted small",children:qe(g.when)})]},`${g.id}-${j}`))}),c.length>12&&s.jsxs("p",{className:"muted small",children:["Showing first 12 of ",c.length,"."]})]}),v.length>0&&s.jsxs(s.Fragment,{children:[s.jsxs("h4",{className:"drawer-section",children:["Decisions (",v.length,")"]}),s.jsx("ul",{className:"drawer-list",children:v.slice(0,8).map((g,j)=>s.jsxs("li",{children:[s.jsx("span",{className:"live-tag","data-kind":"decision",children:"decision"}),s.jsx("span",{className:"marker-text",children:g.text}),s.jsx("span",{className:"muted small",children:qe(g.when)})]},`${g.sid}-${j}`))}),v.length>8&&s.jsxs("p",{className:"muted small",children:["Showing first 8 of ",v.length,"."]})]}),s.jsxs("h4",{className:"drawer-section",children:["Recent sessions (",k.length,")"]}),s.jsx("ul",{className:"session-list",children:p.map(g=>s.jsxs("li",{className:"session-row",children:[s.jsx("span",{className:`chip-inline status-${g.status}`,children:g.status}),s.jsxs("div",{className:"session-row-main",children:[s.jsx(Pr,{to:`/thread?entity=${encodeURIComponent(e.entity)}&session=${encodeURIComponent(g.id)}`,className:"session-label",children:g.label}),s.jsx("span",{className:"session-meta",children:g.summary})]}),s.jsx("span",{className:"muted small mono",children:qe(g.started_at)})]},g.id))}),k.length>0&&s.jsxs("div",{className:"pagination pagination-compact",children:[s.jsxs("div",{className:"page-size",children:[s.jsx("label",{className:"form-label",children:"Per page"}),s.jsx("select",{className:"form-input form-input-inline",value:d,onChange:g=>h(Number.parseInt(g.target.value,10)),children:Mm.map(g=>s.jsx("option",{value:g,children:g},g))})]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[S+1,"–",Math.min(S+d,k.length)," of ",k.length]}),s.jsxs("div",{className:"page-nav",children:[s.jsx("button",{type:"button",className:"chip",disabled:N===0,onClick:()=>m(0),children:"«"}),s.jsx("button",{type:"button",className:"chip",disabled:N===0,onClick:()=>m(g=>Math.max(0,g-1)),children:"‹"}),s.jsxs("span",{className:"page-indicator mono",children:[N+1," / ",y]}),s.jsx("button",{type:"button",className:"chip",disabled:N>=y-1,onClick:()=>m(g=>Math.min(y-1,g+1)),children:"›"}),s.jsx("button",{type:"button",className:"chip",disabled:N>=y-1,onClick:()=>m(y-1),children:"»"})]})]})]})]})]})}function Yr({label:e,value:t,hint:n}){return s.jsxs("div",{className:"kpi",children:[s.jsx("span",{className:"kpi-label",children:e}),s.jsx("span",{className:"kpi-value",children:t.toLocaleString()}),n&&s.jsx("span",{className:"kpi-hint",children:n})]})}function zm({values:e}){const t=Math.max(1,...e);return s.jsxs("div",{className:"kpi kpi-sparkline",children:[s.jsx("span",{className:"kpi-label",children:"Last 7 days"}),s.jsx("div",{className:"sparkline",children:e.map((n,r)=>s.jsx("span",{className:"spark-bar",style:{height:`${n/t*100}%`},title:`${n} sessions`},r))})]})}function $m({metrics:e}){const t=e.healthy+e.sparse+e.stale,n=r=>t>0?r/t*100:0;return s.jsxs("div",{className:"bar-stack",children:[s.jsx(Ts,{tone:"active",label:"Healthy",value:e.healthy,pct:n(e.healthy)}),s.jsx(Ts,{tone:"warn",label:"Sparse",value:e.sparse,pct:n(e.sparse)}),s.jsx(Ts,{tone:"danger",label:"Stale",value:e.stale,pct:n(e.stale)})]})}function Im({runtimes:e}){return e.length===0?s.jsx("div",{className:"muted small",style:{padding:"8px 12px"},children:"No runtime activity yet."}):s.jsx("ul",{className:"runtime-list",children:e.map(t=>s.jsxs("li",{className:"runtime-row",children:[s.jsx("span",{className:`runtime-dot runtime-${t.status}`,title:t.status}),s.jsx("span",{className:"runtime-name mono",children:t.name}),s.jsxs("span",{className:"runtime-counts muted small",children:[t.this_week,s.jsx("span",{className:"runtime-counts-sep",children:"·"}),s.jsxs("span",{className:"runtime-counts-prev",children:[t.last_week," prev"]})]}),s.jsx("span",{className:"muted small mono runtime-age",children:qe(t.last_session_at)})]},t.name))})}function Ts({tone:e,label:t,value:n,pct:r}){const l=Math.round(r);return s.jsxs("div",{className:"bar-item",children:[s.jsx("span",{className:"bar-label",children:t}),s.jsx("div",{className:"bar-track",title:`${n.toLocaleString()} entit${n===1?"y":"ies"} · ${l}% of total`,children:s.jsx("div",{className:`bar-fill tone-${e}`,style:{width:`${r}%`}})}),s.jsxs("span",{className:"bar-value mono",children:[n.toLocaleString(),s.jsxs("span",{className:"bar-pct muted small",children:[" · ",l,"%"]})]})]})}const Ed="nlm.settings.views",xt={landing:"live",riverDensity:"comfortable",threadSort:"recent"};function es(){if(typeof window>"u")return xt;try{const e=window.localStorage.getItem(Ed);return e?{...xt,...JSON.parse(e)}:xt}catch{return xt}}function bm(e){typeof window>"u"||window.localStorage.setItem(Ed,JSON.stringify(e))}const Go={"7d":7,"30d":30,"90d":90,all:null};function Dm(){const{data:e,loading:t,error:n}=Mn(),[r,l]=x.useState("30d"),[a,i]=x.useState(null),[o,u]=x.useState(null),[d,h]=x.useState(null),f=_r(),[m]=x.useState(()=>es().riverDensity),k=x.useRef(null),y=x.useRef(null),[N,S]=x.useState(null),p=x.useMemo(()=>{if(!e)return null;const w=Go[r],C=e.sessions.filter(I=>I.started_at!==null),_=Date.now(),$=w?C.filter(I=>(_-Date.parse(I.started_at))/864e5<=w):C,T=new Map,D=new Map,W=new Set;for(const I of $){const H=(I.started_at??"").slice(0,10);if(!H)continue;W.add(H);const M=I.status==="superseded";for(const z of I.entities)if(M){const b=D.get(z)??new Map;b.set(H,(b.get(H)??0)+1),D.set(z,b)}else{const b=T.get(z)??new Map;b.set(H,(b.get(H)??0)+1),T.set(z,b)}}for(const[I]of D)T.has(I)||T.set(I,new Map);const L=[...W].sort(),R=[...T.entries()].map(([I,H])=>({entity:I,total:[...H.values()].reduce((M,z)=>M+z,0),perDate:H,supersededPerDate:D.get(I)??new Map})).sort((I,H)=>H.total-I.total).slice(0,24),F=new Set($.filter(I=>I.started_at&&_-Date.parse(I.started_at)<864e5).flatMap(I=>I.entities));return{dates:L,laneRows:R,total:$.length,recentEntities:F}},[e,r]),c=(w,C)=>{if(!e)return;const _=e.sessions.filter($=>($.started_at??"").slice(0,10)===C&&$.entities.includes(w)).sort(($,T)=>(T.started_at??"").localeCompare($.started_at??""));if(_.length!==0){if(_.length===1){h(_[0].id);return}u({entity:w,date:C,sessions:_})}},v=w=>{if(!k.current)return;const C=k.current.getBoundingClientRect();y.current={startX:w.clientX,rect:C}},g=w=>{if(!y.current)return;const{startX:C,rect:_}=y.current,$=Math.min(C,w.clientX)-_.left,T=Math.max(C,w.clientX)-_.left;if(T-$<6){S(null);return}S({from:$,to:T})},j=()=>{if(!y.current||!N||!p){y.current=null,S(null);return}const w=k.current,C=w==null?void 0:w.querySelector(".river-lane-label"),_=(C==null?void 0:C.offsetWidth)??0,$=(w==null?void 0:w.offsetWidth)??0,D=Math.max(1,$-_)/p.dates.length,W=_+12,L=Math.max(0,Math.floor((N.from-W)/D)),R=Math.min(p.dates.length-1,Math.floor((N.to-W)/D));if(R<=L){y.current=null,S(null);return}const F=p.dates[L],I=p.dates[R];if(F&&I){const H=Math.max(1,Math.ceil((Date.parse(I)-Date.parse(F))/864e5));l(H<=7?"7d":H<=30?"30d":H<=90?"90d":"all")}y.current=null,S(null)};return t&&!e?s.jsxs("div",{className:"page-pad",children:[s.jsx("div",{className:"river-toolbar",children:s.jsx(ie,{h:22,w:80})}),s.jsx("div",{className:"card",style:{padding:12},children:Array.from({length:8}).map((w,C)=>s.jsxs("div",{className:"river-row",style:{marginBottom:3},children:[s.jsx(ie,{h:14,w:160}),s.jsx(ie,{h:20})]},C))})]}):n&&!e?s.jsx("div",{className:"page-pad",children:s.jsx("div",{className:"muted error",children:n})}):!e||!p?null:s.jsxs("div",{className:"page-pad",children:[s.jsxs("div",{className:"river-toolbar",children:[s.jsx("span",{className:"page-title",children:"River"}),s.jsxs("span",{className:"muted small",children:[p.total," sessions · ",p.laneRows.length," lanes · ",p.dates.length," days"]}),s.jsx("span",{className:"header-spacer"}),Object.keys(Go).map(w=>s.jsx("button",{type:"button",className:`ctrl-btn${w===r?" active":""}`,onClick:()=>l(w),children:w},w)),s.jsxs("div",{className:"river-legend","aria-label":"Activity scale",children:[s.jsx("span",{className:"muted small",children:"less"}),[0,1,2,3,4].map(w=>s.jsx("span",{className:`river-legend-cell tier-${w}`},w)),s.jsx("span",{className:"muted small",children:"more"})]})]}),s.jsxs("div",{className:`river-grid card river-density-${m}`,ref:k,onMouseDown:v,onMouseMove:g,onMouseUp:j,onMouseLeave:()=>{y.current=null,S(null),i(null)},style:{"--cells":p.dates.length},children:[N&&s.jsx("div",{className:"river-drag-rect",style:{left:`${N.from}px`,width:`${N.to-N.from}px`}}),s.jsxs("div",{className:"river-row river-row-dates",children:[s.jsx("div",{className:"river-lane-label river-lane-label--header","aria-hidden":"true"}),s.jsx("div",{className:"river-cells",children:(()=>{const w=p.dates.length,C=w<=60?1:w<=120?2:w<=250?7:14;return p.dates.map((_,$)=>{const D=["river-date-cell",_.slice(8,10)==="01"?"river-date-cell--month-start":""].filter(Boolean).join(" ");return s.jsx("div",{className:D,title:_,children:$%C===0?_.slice(5):""},_)})})()})]}),p.laneRows.map(({entity:w,perDate:C,supersededPerDate:_,total:$})=>{const T=p.recentEntities.has(w);return s.jsxs("div",{className:"river-row",children:[s.jsxs("button",{type:"button",className:"river-lane-label",onClick:()=>f(`/thread?entity=${encodeURIComponent(w)}`),children:[s.jsx("span",{className:`dot${T?" dot-pulse":""}`,style:{background:e.entity_colors[w]??"#666"}}),s.jsx("span",{className:"river-lane-name",children:w}),s.jsx("span",{className:"muted small",children:$})]}),s.jsx("div",{className:"river-cells",children:p.dates.map(D=>{const W=C.get(D)??0,L=_.get(D)??0,R=W>0||L>0,F=["river-cell",`tier-${Um(W)}`,L>0?"has-corrections":""].filter(Boolean).join(" ");return s.jsx("div",{className:F,onMouseEnter:I=>i({entity:w,date:D,count:W,superseded:L,x:I.clientX,y:I.clientY}),onMouseLeave:()=>i(null),onClick:()=>R&&c(w,D),style:R?{cursor:"pointer"}:{}},D)})})]},w)})]}),p.laneRows.length===0&&s.jsx("div",{className:"muted",children:"No entities in this window."}),a&&(a.count>0||a.superseded>0)&&s.jsxs("div",{className:"river-hover",style:{left:a.x+12,top:a.y+12},children:[s.jsx("span",{className:"dot",style:{background:e.entity_colors[a.entity]??"#666"}}),s.jsx("span",{className:"river-hover-name",children:a.entity}),s.jsxs("span",{className:"muted small",children:[a.date,a.count>0&&` · ${a.count} session${a.count===1?"":"s"}`,a.superseded>0&&` · ${a.superseded} corrected`]})]}),o&&s.jsx(Fm,{state:o,entityColor:e.entity_colors[o.entity]??"#666",onClose:()=>u(null),onPick:w=>{u(null),h(w)},onOpenThread:()=>f(`/thread?entity=${encodeURIComponent(o.entity)}`)}),d&&(()=>{const w=o?o.sessions:[...e.sessions].filter(W=>W.started_at!==null).sort((W,L)=>(L.started_at??"").localeCompare(W.started_at??"")),C=w.findIndex(W=>W.id===d),_=C<w.length-1?w[C+1].id:null,$=C>0?w[C-1].id:null,T=e.sessions.find(W=>W.id===d),D=T==null?void 0:T.entities[0];return s.jsx(Lr,{sessionId:d,onClose:()=>h(null),onNavigate:h,prevSessionId:_,nextSessionId:$,entityColor:D?e.entity_colors[D]:void 0})})()]})}function Fm({state:e,entityColor:t,onClose:n,onPick:r,onOpenThread:l}){return x.useEffect(()=>{const a=i=>{i.key==="Escape"&&n()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[n]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"drawer-backdrop",onClick:n}),s.jsxs("aside",{className:"session-drawer",role:"dialog","aria-modal":"true","aria-label":`Sessions on ${e.date}`,children:[s.jsxs("header",{className:"drawer-head",children:[s.jsx("span",{className:"dot lg",style:{background:t}}),s.jsx("h3",{className:"drawer-title",children:e.entity}),s.jsx("span",{className:"muted small",children:e.date}),s.jsx("button",{type:"button",className:"drawer-close",onClick:n,"aria-label":"Close",children:"×"})]}),s.jsxs("div",{className:"drawer-body",children:[s.jsxs("p",{className:"muted small",children:[e.sessions.length," sessions on this day. Pick one to inspect."]}),s.jsx("div",{className:"drawer-actions",children:s.jsx("button",{type:"button",className:"btn btn-accent",onClick:l,children:"Open thread"})}),s.jsx("ul",{className:"session-list",children:e.sessions.map(a=>s.jsxs("li",{className:"session-row session-row-detail clickable",onClick:()=>r(a.id),role:"button",tabIndex:0,onKeyDown:i=>{(i.key==="Enter"||i.key===" ")&&(i.preventDefault(),r(a.id))},children:[s.jsx("span",{className:`chip-inline status-${a.status}`,children:a.status}),s.jsxs("div",{className:"session-row-main",children:[s.jsx("span",{className:"session-label",children:a.label}),s.jsx("span",{className:"session-meta",children:a.summary})]}),s.jsx("span",{className:"muted small mono",children:qe(a.started_at)})]},a.id))})]})]})]})}function Um(e){return e===0?0:e===1?1:e<=3?2:e<=6?3:4}const Am=[10,25,50,100];function Bm(e,t,n){const r=e.label.toLowerCase(),l=e.summary.toLowerCase(),a=e.decisions.join(" ").toLowerCase(),i=e.open.join(" ").toLowerCase(),o={label:0,entity:0,decision:0,open:0,summary:0};for(const m of t){r.includes(m)&&(o.label+=3);for(const k of e.entities){const y=k.toLowerCase();if(y===m){o.entity+=4;break}else if(y.includes(m)){o.entity+=2;break}}a.includes(m)&&(o.decision+=2),i.includes(m)&&(o.open+=2),l.includes(m)&&(o.summary+=1)}if(n&&(r.includes(n)||a.includes(n)||i.includes(n))){const m=Object.keys(o).reduce((k,y)=>o[k]>=o[y]?k:y);o[m]+=5}const u=Object.values(o).reduce((m,k)=>m+k,0),d=["label","entity","decision","open","summary"];let h="summary",f=-1;for(const m of d)o[m]>f&&(f=o[m],h=m);return{score:u,matchedField:h}}function Wm(e,t,n=60){const r=e.toLowerCase();let l=-1;for(const o of t){const u=r.indexOf(o);u!==-1&&(l===-1||u<l)&&(l=u)}if(l===-1)return e.slice(0,n*2);const a=Math.max(0,l-n),i=Math.min(e.length,l+n);return(a>0?"…":"")+e.slice(a,i)+(i<e.length?"…":"")}function Vm(e,t){let n=e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");for(const r of t)n=n.replace(new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),l=>`<mark>${l}</mark>`);return n}function Hm(){const{data:e,loading:t,error:n}=Mn(),[r,l]=Sd(),a=r.get("q")??"",[i,o]=x.useState(a),[u,d]=x.useState(r.get("entity")??""),[h,f]=x.useState("all"),[m,k]=x.useState("all"),[y,N]=x.useState("recent"),[S,p]=x.useState(25),[c,v]=x.useState(0),[g,j]=x.useState(r.get("session")),w=E=>{const U=new URLSearchParams(r);U.set("session",E),l(U),j(E)},C=()=>{const E=new URLSearchParams(r);E.delete("session"),l(E),j(null)};x.useEffect(()=>{const E=setTimeout(()=>{const U=new URLSearchParams(r);i?U.set("q",i):U.delete("q"),l(U)},200);return()=>clearTimeout(E)},[i]),x.useEffect(()=>{const E=new URLSearchParams(r);u?E.set("entity",u):E.delete("entity"),l(E)},[u]);const _=x.useMemo(()=>a.toLowerCase().split(/\s+/).filter(Boolean),[a]),$=_.join(" "),T=x.useMemo(()=>{if(!e)return[];const E=e.sessions.filter(B=>!(u&&!B.entities.includes(u)||h!=="all"&&B.runtime!==h||m!=="all"&&B.status!==m));if(_.length===0)return[...E].sort((le,xe)=>(xe.started_at??"").localeCompare(le.started_at??"")).map(le=>({session:le,score:0,matchedField:"summary"}));const U=E.map(B=>{const{score:le,matchedField:xe}=Bm(B,_,$);return{session:B,score:le,matchedField:xe}}).filter(B=>B.score>0);return y==="recent"?U.sort((B,le)=>(le.session.started_at??"").localeCompare(B.session.started_at??"")):U.sort((B,le)=>le.score-B.score),U},[e,_,$,u,h,m,y]);x.useEffect(()=>{v(0)},[T,h,m,u]);const D=Math.max(1,Math.ceil(T.length/S)),W=Math.min(c,D-1),L=W*S,R=T.slice(L,L+S),F=x.useMemo(()=>{if(!e)return[];const E=new Map;for(const U of e.sessions)E.set(U.runtime,(E.get(U.runtime)??0)+1);return[...E.entries()].sort((U,B)=>B[1]-U[1]).map(([U])=>U)},[e]),I=x.useMemo(()=>{const E=new Map;for(const{session:U}of T)for(const B of U.entities)E.set(B,(E.get(B)??0)+1);return[...E.entries()].sort((U,B)=>B[1]-U[1]).map(([U])=>U)},[T]),H=a!==""||u!==""||h!=="all"||m!=="all",M=()=>{o(""),d(""),f("all"),k("all"),N("recent");const E=new URLSearchParams;g&&E.set("session",g),l(E)},z=R.findIndex(E=>E.session.id===g),b=z<R.length-1?R[z+1].session.id:null,J=z>0?R[z-1].session.id:null;return s.jsxs("div",{className:"page-pad",children:[s.jsxs("div",{className:"search-header",children:[s.jsx("form",{onSubmit:E=>E.preventDefault(),className:"search-bar",children:s.jsxs("div",{className:"search-wrap",style:{flex:1},children:[s.jsx("input",{className:"search-input search-big",placeholder:"search sessions, decisions, open questions…",value:i,onChange:E=>o(E.target.value),autoFocus:!0}),i.length>0&&s.jsx("button",{type:"button",className:"search-clear",onClick:()=>o(""),"aria-label":"Clear search",children:s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})}),s.jsxs("div",{className:"thread-filters",children:[F.length>1&&s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Agent filter",children:[s.jsx("button",{type:"button",className:`chip${h==="all"?" active":""}`,onClick:()=>f("all"),children:"all"}),F.map(E=>{const U=T.filter(B=>B.session.runtime===E).length;return s.jsxs("button",{type:"button",className:`chip${h===E?" active":""}`,onClick:()=>f(E),children:[E," · ",U]},E)})]}),s.jsx("div",{className:"filter-group",role:"group","aria-label":"Status filter",children:["all","active","idle","closed","superseded"].map(E=>{const U=E==="all"?T.length:T.filter(B=>B.session.status===E).length;return s.jsxs("button",{type:"button",className:`chip${m===E?" active":""}`,"data-status":E==="all"?void 0:E,onClick:()=>k(E),children:[E," · ",U]},E)})}),a!==""&&s.jsx("div",{className:"filter-group",role:"group","aria-label":"Sort order",children:["relevance","recent"].map(E=>s.jsx("button",{type:"button",className:`chip${y===E?" active":""}`,onClick:()=>N(E),children:E},E))}),I.length>0&&s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Entity filter",style:{flexWrap:"wrap"},children:[s.jsx("button",{type:"button",className:`chip${u===""?" active":""}`,onClick:()=>d(""),children:"all entities"}),I.slice(0,12).map(E=>s.jsx("button",{type:"button",className:`chip${u===E?" active":""}`,onClick:()=>d(u===E?"":E),children:E},E)),I.length>12&&s.jsxs("select",{className:"form-input form-input-inline",value:u,onChange:E=>d(E.target.value),children:[s.jsx("option",{value:"",children:"more entities…"}),I.slice(12).map(E=>s.jsx("option",{value:E,children:E},E))]})]})]})]}),t&&!e&&s.jsx("div",{className:"muted",children:"Loading…"}),n&&s.jsx("div",{className:"muted error",children:n}),!H&&s.jsx("p",{className:"muted small search-hint",children:"Showing recent sessions. Type to search across labels, decisions, open questions, and summaries."}),s.jsxs("div",{className:"muted small search-meta",children:[T.length," result",T.length===1?"":"s",H&&s.jsx("button",{type:"button",className:"link-button",style:{marginLeft:8},onClick:M,children:"clear filters"})]}),s.jsxs("ul",{className:"session-list",children:[R.map(({session:E,matchedField:U})=>{let B=E.summary;return _.length>0&&(U==="decision"?B=E.decisions.find(le=>_.some(xe=>le.toLowerCase().includes(xe)))??E.summary:U==="open"&&(B=E.open.find(le=>_.some(xe=>le.toLowerCase().includes(xe)))??E.summary)),s.jsxs("li",{className:`session-row session-row-detail clickable${g===E.id?" is-active":""}`,onClick:()=>w(E.id),children:[s.jsx("span",{className:`chip-inline status-${E.status}`,children:E.status}),s.jsxs("div",{className:"session-row-main",children:[s.jsx("span",{className:"session-label",children:E.label}),s.jsx("span",{className:"session-meta",children:E.entities.slice(0,4).map(le=>s.jsx("span",{className:"chip-inline",style:{marginRight:4},children:le},le))}),_.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"live-tag","data-kind":U,children:U}),s.jsx("div",{className:"match-snippet",dangerouslySetInnerHTML:{__html:Vm(Wm(B,_),_)}})]})]}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",alignItems:"flex-end",gap:4},children:[s.jsx("span",{className:"muted small mono",children:qe(E.started_at)}),s.jsx("span",{className:"chip-inline",children:E.runtime})]})]},E.id)}),R.length===0&&e&&s.jsx("li",{className:"muted empty-row",children:T.length===0?"No sessions match the current filters.":"No sessions on this page."})]}),T.length>0&&s.jsxs("div",{className:"pagination",children:[s.jsxs("div",{className:"page-size",children:[s.jsx("label",{className:"form-label",children:"Per page"}),s.jsx("select",{className:"form-input form-input-inline",value:S,onChange:E=>p(Number.parseInt(E.target.value,10)),children:Am.map(E=>s.jsx("option",{value:E,children:E},E))})]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[L+1,"–",Math.min(L+S,T.length)," of ",T.length]}),s.jsxs("div",{className:"page-nav",children:[s.jsx("button",{type:"button",className:"chip",disabled:W===0,onClick:()=>v(0),children:"« first"}),s.jsx("button",{type:"button",className:"chip",disabled:W===0,onClick:()=>v(E=>Math.max(0,E-1)),children:"‹ prev"}),s.jsxs("span",{className:"page-indicator mono",children:[W+1," / ",D]}),s.jsx("button",{type:"button",className:"chip",disabled:W>=D-1,onClick:()=>v(E=>Math.min(D-1,E+1)),children:"next ›"}),s.jsx("button",{type:"button",className:"chip",disabled:W>=D-1,onClick:()=>v(D-1),children:"last »"})]})]}),g&&s.jsx(Lr,{sessionId:g,onClose:C,onNavigate:w,prevSessionId:b,nextSessionId:J})]})}function Km(){const{data:e,loading:t,error:n,refetch:r}=Mn(),[l,a]=Sd(),i=l.get("entity")??"",o=l.get("session"),[u,d]=x.useState(()=>es().threadSort),[h,f]=x.useState(!1),[m,k]=x.useState(!1),y=x.useMemo(()=>{if(!e||!i)return[];const g=e.sessions.filter(j=>j.entities.includes(i));return g.sort((j,w)=>{const C=j.started_at??"",_=w.started_at??"";return u==="recent"?_.localeCompare(C):C.localeCompare(_)}),g},[e,i,u]),N=i&&e?e.entity_colors[i]??"#666":"#666";x.useEffect(()=>{i&&e&&(document.title=`${i} — Thread`)},[i,e]);const S=g=>{const j=new URLSearchParams(l);j.set("session",g),a(j)},p=()=>{const g=new URLSearchParams(l);g.delete("session"),a(g)};if(t&&!e)return s.jsxs("div",{className:"page-pad",children:[s.jsx(ie,{h:22,w:220}),s.jsx("div",{style:{marginTop:16},children:s.jsx(Cm,{rows:8})})]});if(n&&!e)return s.jsx("div",{className:"page-pad",children:s.jsx("div",{className:"muted error",children:n})});if(!e)return null;if(!i)return s.jsx(Gm,{data:e});const c=y.flatMap(g=>g.decisions.map(j=>({d:j,sid:g.id,when:g.started_at}))),v=y.flatMap(g=>g.open_questions.map(j=>({id:j.id,q:j.text,sid:g.id,when:g.started_at})));return s.jsxs("div",{className:"page-pad",children:[s.jsxs("div",{className:"thread-header",children:[s.jsx("span",{className:"dot lg",style:{background:N}}),s.jsx("h2",{className:"page-title",children:i}),s.jsxs("span",{className:"muted",children:[y.length," session",y.length===1?"":"s"]}),s.jsx("span",{className:"header-spacer"}),s.jsx("div",{className:"filter-group",role:"group","aria-label":"Sort order",children:["recent","oldest"].map(g=>s.jsx("button",{type:"button",className:`chip${u===g?" active":""}`,onClick:()=>d(g),children:g==="recent"?"recent first":"oldest first"},g))})]}),s.jsxs("div",{className:"thread-grid",children:[s.jsxs("section",{className:"card",children:[s.jsxs("header",{className:"card-head",children:[s.jsx("h3",{children:"Decisions"}),s.jsx("span",{className:"muted small",children:c.length})]}),s.jsxs("ul",{className:"marker-list",children:[(h?c:c.slice(0,30)).map((g,j)=>s.jsxs("li",{className:"marker-row",children:[s.jsx("span",{className:"live-tag","data-kind":"decision",children:"decision"}),s.jsx("span",{className:"marker-text",children:g.d}),s.jsx("button",{type:"button",className:"link-button",onClick:()=>S(g.sid),children:qe(g.when)})]},j)),c.length===0&&s.jsx("li",{className:"muted empty-row",children:"No decisions captured yet."}),c.length>30&&s.jsx("li",{style:{padding:"8px 14px"},children:s.jsx("button",{type:"button",className:"link-button",onClick:()=>f(g=>!g),children:h?"Show less":`Showing 30 of ${c.length} — show all`})})]})]}),s.jsxs("section",{className:"card",children:[s.jsxs("header",{className:"card-head",children:[s.jsx("h3",{children:"Open questions"}),s.jsx("span",{className:"muted small",children:v.length})]}),s.jsxs("ul",{className:"marker-list",children:[(m?v:v.slice(0,30)).map((g,j)=>s.jsxs("li",{className:"marker-row marker-row-promotable",children:[s.jsx("span",{className:"live-tag","data-kind":"open",children:"open"}),s.jsx("span",{className:"marker-text",children:g.q}),s.jsxs("div",{className:"marker-actions",children:[s.jsx(Cd,{openId:g.id,defaultText:g.q,onPromoted:r}),s.jsx("button",{type:"button",className:"link-button",onClick:()=>S(g.sid),children:qe(g.when)})]})]},`${g.id}-${j}`)),v.length===0&&s.jsx("li",{className:"muted empty-row",children:"No open questions captured yet."}),v.length>30&&s.jsx("li",{style:{padding:"8px 14px"},children:s.jsx("button",{type:"button",className:"link-button",onClick:()=>k(g=>!g),children:m?"Show less":`Showing 30 of ${v.length} — show all`})})]})]})]}),s.jsx(Ym,{thread:y,entity:i,onOpenSession:S}),o&&(()=>{const g=y.findIndex(C=>C.id===o),j=g<y.length-1?y[g+1].id:null,w=g>0?y[g-1].id:null;return s.jsx(Lr,{sessionId:o,onClose:p,onNavigate:S,prevSessionId:j,nextSessionId:w,entityColor:N})})()]})}const Qm=[10,25,50,100];function Ym({thread:e,entity:t,onOpenSession:n}){const[r,l]=x.useState("all"),[a,i]=x.useState(""),[o,u]=x.useState("all"),[d,h]=x.useState("all"),[f,m]=x.useState(25),[k,y]=x.useState(0),N=x.useMemo(()=>{const j=new Map;for(const w of e)j.set(w.runtime,(j.get(w.runtime)??0)+1);return[...j.entries()].sort((w,C)=>C[1]-w[1]).map(([w])=>w)},[e]),S=x.useMemo(()=>{const j=a.toLowerCase().trim();return e.filter(w=>r!=="all"&&w.runtime!==r||o!=="all"&&w.status!==o||d==="decisions"&&w.decisions.length===0||d==="open"&&w.open_questions.length===0?!1:j?w.label.toLowerCase().includes(j)||w.summary.toLowerCase().includes(j)||w.decisions.some(C=>C.toLowerCase().includes(j))||w.open.some(C=>C.toLowerCase().includes(j)):!0)},[e,a,o,d,r]);x.useEffect(()=>{y(0)},[a,o,d,f,r]),x.useEffect(()=>{l("all")},[t]);const p=Math.max(1,Math.ceil(S.length/f)),c=Math.min(k,p-1),v=c*f,g=S.slice(v,v+f);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"thread-sessions-head",children:[s.jsx("h3",{className:"section-title thread-sessions-title",children:"Sessions"}),s.jsxs("div",{className:"search-wrap",children:[s.jsx("input",{className:"search-input",placeholder:"search label, summary, decisions, open…",value:a,onChange:j=>i(j.target.value),onKeyDown:j=>{j.key==="Escape"&&i("")}}),a&&s.jsx("button",{type:"button",className:"search-clear",onClick:()=>i(""),"aria-label":"Clear search",children:s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),s.jsxs("div",{className:"thread-filters",children:[N.length>1&&s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Agent filter",children:[s.jsx("button",{type:"button",className:`chip${r==="all"?" active":""}`,onClick:()=>l("all"),children:"all"}),N.map(j=>{const w=e.filter(C=>C.runtime===j).length;return s.jsxs("button",{type:"button",className:`chip${r===j?" active":""}`,onClick:()=>l(j),children:[j," · ",w]},j)})]}),s.jsx("div",{className:"filter-group",role:"group","aria-label":"Status filter",children:["all","active","idle","closed","superseded"].map(j=>{const w=j==="all"?e.length:e.filter(C=>C.status===j).length;return s.jsxs("button",{type:"button",className:`chip${o===j?" active":""}`,"data-status":j==="all"?void 0:j,onClick:()=>u(j),children:[j," · ",w]},j)})}),s.jsx("div",{className:"filter-group",role:"group","aria-label":"Marker filter",children:["all","decisions","open"].map(j=>{const w=j==="decisions"?e.filter(C=>C.decisions.length>0).length:e.filter(C=>C.open_questions.length>0).length;return s.jsx("button",{type:"button",className:`chip${d===j?" active":""}`,"data-marker":j==="all"?void 0:j,onClick:()=>h(j),children:j==="all"?"all":`${j} · ${w}`},j)})}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[S.length," match",S.length===1?"":"es"]})]}),s.jsxs("ul",{className:"session-list",children:[g.map(j=>s.jsxs("li",{className:"session-row session-row-detail clickable",onClick:()=>n(j.id),children:[s.jsx("span",{className:`chip-inline status-${j.status}`,children:j.status}),s.jsxs("div",{className:"session-row-main",children:[s.jsx("span",{className:"session-label",children:j.label}),s.jsx("span",{className:"session-meta",children:j.summary})]}),s.jsx("span",{className:"muted small mono",children:qe(j.started_at)})]},j.id)),g.length===0&&s.jsx("li",{className:"muted empty-row",children:e.length===0?"No sessions yet.":"No sessions match the current filters."})]}),S.length>0&&s.jsxs("div",{className:"pagination",children:[s.jsxs("div",{className:"page-size",children:[s.jsx("label",{className:"form-label",children:"Per page"}),s.jsx("select",{className:"form-input form-input-inline",value:f,onChange:j=>m(Number.parseInt(j.target.value,10)),children:Qm.map(j=>s.jsx("option",{value:j,children:j},j))})]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[v+1,"–",Math.min(v+f,S.length)," of ",S.length]}),s.jsxs("div",{className:"page-nav",children:[s.jsx("button",{type:"button",className:"chip",disabled:c===0,onClick:()=>y(0),children:"« first"}),s.jsx("button",{type:"button",className:"chip",disabled:c===0,onClick:()=>y(j=>Math.max(0,j-1)),children:"‹ prev"}),s.jsxs("span",{className:"page-indicator mono",children:[c+1," / ",p]}),s.jsx("button",{type:"button",className:"chip",disabled:c>=p-1,onClick:()=>y(j=>Math.min(p-1,j+1)),children:"next ›"}),s.jsx("button",{type:"button",className:"chip",disabled:c>=p-1,onClick:()=>y(p-1),children:"last »"})]})]})]})}const Xm=[24,48,96];function Gm({data:e}){const[t,n]=x.useState("all"),[r,l]=x.useState(""),[a,i]=x.useState("most-active"),[o,u]=x.useState(48),[d,h]=x.useState(0),f=x.useMemo(()=>{const c=new Map;for(const v of e.sessions)for(const g of v.entities){let j=c.get(g);j||(j=new Set,c.set(g,j)),j.add(v.runtime)}return c},[e.sessions]),m=x.useMemo(()=>[...e.runtimes].sort((c,v)=>v.sessions_total-c.sessions_total),[e.runtimes]),k=x.useMemo(()=>{const c=r.toLowerCase().trim(),v=c?e.entities.filter(j=>j.canonical.toLowerCase().includes(c)):[...e.entities],g=t==="all"?v:v.filter(j=>{var w;return((w=f.get(j.canonical))==null?void 0:w.has(t))??!1});return g.sort((j,w)=>a==="most-active"?w.session_count-j.session_count:a==="least-active"?j.session_count-w.session_count:a==="a-z"?j.canonical.localeCompare(w.canonical):w.canonical.localeCompare(j.canonical)),g},[e.entities,r,a,t,f]);x.useEffect(()=>{h(0)},[r,a,o,t]);const y=Math.max(1,Math.ceil(k.length/o)),N=Math.min(d,y-1),S=N*o,p=k.slice(S,S+o);return s.jsxs("div",{className:"page-pad",children:[s.jsx("h2",{className:"page-title",children:"Thread"}),s.jsx("p",{className:"muted",children:"Pick an entity to view its reasoning history."}),s.jsxs("div",{className:"thread-sessions-head",style:{marginTop:16},children:[s.jsxs("div",{className:"search-wrap",style:{maxWidth:320},children:[s.jsx("input",{className:"search-input",placeholder:"search entities…",value:r,onChange:c=>l(c.target.value),onKeyDown:c=>{c.key==="Escape"&&l("")}}),r&&s.jsx("button",{type:"button",className:"search-clear",onClick:()=>l(""),"aria-label":"Clear search",children:s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),s.jsx("span",{className:"header-spacer"}),s.jsx("span",{className:"muted small",children:r?`${k.length} of ${e.entities.length} entities`:`${e.entities.length} entities`})]}),s.jsxs("div",{className:"thread-filters",children:[s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Agent filter",children:[s.jsx("button",{type:"button",className:`chip${t==="all"?" active":""}`,onClick:()=>n("all"),children:"all"}),m.map(c=>s.jsxs("button",{type:"button",className:`chip${t===c.name?" active":""}`,onClick:()=>n(c.name),children:[c.name," · ",c.sessions_total]},c.name))]}),s.jsx("div",{className:"filter-group",role:"group","aria-label":"Sort order",children:["most-active","least-active","a-z","z-a"].map(c=>s.jsx("button",{type:"button",className:`chip${a===c?" active":""}`,onClick:()=>i(c),children:c==="most-active"?"most active":c==="least-active"?"least active":c},c))})]}),s.jsxs("ul",{className:"entity-grid",children:[p.map(c=>s.jsx("li",{children:s.jsxs(Pr,{to:`/thread?entity=${encodeURIComponent(c.canonical)}`,className:"card card-lift entity-card",children:[s.jsx("span",{className:"dot",style:{background:e.entity_colors[c.canonical]??"#666"}}),s.jsx("span",{className:"entity-name",children:c.canonical}),s.jsx("span",{className:"muted small",children:c.session_count})]})},c.canonical)),p.length===0&&s.jsx("li",{style:{gridColumn:"1 / -1"},className:"muted empty-row",children:"No entities match."})]}),k.length>o&&s.jsxs("div",{className:"pagination",children:[s.jsxs("div",{className:"page-size",children:[s.jsx("label",{className:"form-label",children:"Per page"}),s.jsx("select",{className:"form-input form-input-inline",value:o,onChange:c=>u(Number.parseInt(c.target.value,10)),children:Xm.map(c=>s.jsx("option",{value:c,children:c},c))})]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[S+1,"–",Math.min(S+o,k.length)," of ",k.length]}),s.jsxs("div",{className:"page-nav",children:[s.jsx("button",{type:"button",className:"chip",disabled:N===0,onClick:()=>h(0),children:"« first"}),s.jsx("button",{type:"button",className:"chip",disabled:N===0,onClick:()=>h(c=>Math.max(0,c-1)),children:"‹ prev"}),s.jsxs("span",{className:"page-indicator mono",children:[N+1," / ",y]}),s.jsx("button",{type:"button",className:"chip",disabled:N>=y-1,onClick:()=>h(c=>Math.min(y-1,c+1)),children:"next ›"}),s.jsx("button",{type:"button",className:"chip",disabled:N>=y-1,onClick:()=>h(y-1),children:"last »"})]})]})]})}const Jm={days:7,total:0,with_results:0,hit_rate:0,by_source:{},top_queries:[],log_present:!1},Zm={days:7,total:0,with_results:0,hit_rate:0,by_source:{},top_subjects:[],top_predicates:[],log_present:!1},qm=[7,30,90];function ev(){const[e,t]=x.useState(7),n=er(`/api/recall/stats?days=${e}`,3e4,Jm),r=er(`/api/recall/facts/stats?days=${e}`,3e4,Zm);return s.jsxs("div",{className:"page-pad",children:[s.jsxs("div",{className:"recall-head",children:[s.jsxs("p",{className:"muted small recall-note",children:["Hit rate measures whether recall returned something — not whether the agent used it. Watch ",s.jsx("strong",{children:"by source"})," for adoption and ",s.jsx("strong",{children:"hit rate"})," for whether the corpus covers what's being asked."]}),s.jsx("div",{className:"filter-group",role:"group","aria-label":"Time window",children:qm.map(l=>s.jsxs("button",{type:"button",className:`chip${e===l?" active":""}`,onClick:()=>t(l),children:[l,"d"]},l))})]}),s.jsx(Jo,{title:"Session recall",subtitle:"What the orchestrator pulls when answering questions about past work — the human-operator surface.",stats:n.data,error:n.error,topLabel:"Top queries",topRows:n.data.top_queries.map(l=>({label:l.query,count:l.count}))}),s.jsx(Jo,{title:"Fact recall",subtitle:"Structured facts agents pull mid-task — the orchestrator surface.",stats:r.data,error:r.error,topLabel:"Top subjects",topRows:r.data.top_subjects.map(l=>({label:l.subject,count:l.count})),extraLabel:"Top predicates",extraRows:r.data.top_predicates.map(l=>({label:l.predicate,count:l.count}))})]})}function Jo({title:e,subtitle:t,stats:n,error:r,topLabel:l,topRows:a,extraLabel:i,extraRows:o}){const u=n.total-n.with_results,d=Object.entries(n.by_source).map(([h,f])=>({label:h,count:f})).sort((h,f)=>f.count-h.count);return s.jsxs("section",{className:"recall-block",children:[s.jsxs("header",{className:"recall-block-head",children:[s.jsx("h2",{className:"page-title",children:e}),s.jsx("p",{className:"muted small",children:t})]}),r&&s.jsx("div",{className:"muted error small",children:r}),n.log_present?n.total===0?s.jsxs("div",{className:"card recall-empty muted",children:["No queries in the last ",n.days," days. The log exists but this window is empty."]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"kpi-row",children:[s.jsx(Xr,{label:"Queries",value:n.total,hint:`last ${n.days}d`}),s.jsx(Xr,{label:"Hit rate",value:`${Math.round(n.hit_rate*100)}%`,hint:`${n.with_results.toLocaleString()} returned ≥1`}),s.jsx(Xr,{label:"Zero-result",value:u,hint:u>0?"corpus gaps":"full coverage"}),s.jsx(Xr,{label:"Sources",value:d.length,hint:"distinct callers"})]}),s.jsxs("div",{className:"recall-cards",children:[s.jsx(Rs,{title:"By source",rows:d,emptyText:"No sources recorded."}),s.jsx(Rs,{title:l,rows:a,emptyText:"None recorded."}),i&&o&&s.jsx(Rs,{title:i,rows:o,emptyText:"None recorded."})]})]}):s.jsx("div",{className:"card recall-empty muted",children:"No query log on disk yet — nothing has called this recall surface."})]})}function Xr({label:e,value:t,hint:n}){return s.jsxs("div",{className:"kpi",children:[s.jsx("span",{className:"kpi-label",children:e}),s.jsx("span",{className:"kpi-value",children:typeof t=="number"?t.toLocaleString():t}),n&&s.jsx("span",{className:"kpi-hint",children:n})]})}function Rs({title:e,rows:t,emptyText:n}){const r=Math.max(1,...t.map(l=>l.count));return s.jsxs("section",{className:"card",children:[s.jsx("header",{className:"card-head",children:s.jsx("h3",{children:e})}),s.jsxs("div",{className:"bar-stack recall-bars",children:[t.length===0&&s.jsx("div",{className:"muted small recall-bars-empty",children:n}),t.map(l=>s.jsxs("div",{className:"bar-item",children:[s.jsx("span",{className:"bar-label recall-bar-label",title:l.label,children:l.label}),s.jsx("div",{className:"bar-track",children:s.jsx("div",{className:"bar-fill tone-active",style:{width:`${l.count/r*100}%`}})}),s.jsx("span",{className:"bar-value mono",children:l.count.toLocaleString()})]},l.label))]})]})}const tv=[{to:"/settings",label:"Overview"},{to:"/settings/sources",label:"Sources"},{to:"/settings/providers",label:"Providers"},{to:"/settings/classifier",label:"Classifier"},{to:"/settings/labels",label:"Labels"},{to:"/settings/data",label:"Data"},{to:"/settings/views",label:"Views"}];function Jt(){return s.jsx("div",{className:"subnav",children:tv.map(e=>s.jsx(Ta,{to:e.to,end:e.to==="/settings",className:({isActive:t})=>`subnav-link${t?" active":""}`,children:e.label},e.to))})}const nv=[{to:"/settings/sources",title:"Sources",body:()=>"Transcript origins the daemon scans. Add Claude Code, Hermes, pi.dev, custom JSONL directories, or webhook ingest."},{to:"/settings/providers",title:"Providers",body:()=>"LLM endpoints (DeepSeek, Ollama, OpenAI, Anthropic, OpenRouter, custom). Manage keys and test connections."},{to:"/settings/labels",title:"Labels",body:({entities:e})=>`${e} entities catalogued. Promote candidates and edit types.`},{to:"/settings/classifier",title:"Classifier",body:({classifierProvider:e})=>e?`Active provider: ${e}.`:"Classifier provider unknown."},{to:"/settings/data",title:"Data",body:({sessions:e})=>`${e} sessions in the canonical store. Inspect path and backup posture.`},{to:"/settings/views",title:"Views",body:()=>"Default landing page, density, sort, density tier."}];function rv(){const{data:e}=Mn(),t={sessions:(e==null?void 0:e.meta.sessions_total)??0,entities:(e==null?void 0:e.meta.entities_total)??0,classifierProvider:null};return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsx("div",{className:"settings-grid",children:nv.map(n=>s.jsxs(Pr,{to:n.to,className:"card card-lift settings-card",children:[s.jsx("h3",{className:"settings-card-title",children:n.title}),s.jsx("p",{className:"settings-card-body",children:n.body(t)})]},n.to))})]})}function lv(e){if(e<1024)return`${e} B`;const t=["KB","MB","GB"];let n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r++;return`${n.toFixed(n>=100?0:1)} ${t[r]}`}function sv(){var f;const[e,t]=x.useState(null),[n,r]=x.useState(null),[l,a]=x.useState(null),[i,o]=x.useState(!1),u=x.useRef(null),d=x.useCallback(async()=>{try{const m=await fetch("/api/data/stats");if(!m.ok)throw new Error(`HTTP ${m.status}`);t(await m.json()),r(null)}catch(m){r(m instanceof Error?m.message:String(m))}},[]);x.useEffect(()=>{d()},[d]);const h=async()=>{var k,y;const m=(y=(k=u.current)==null?void 0:k.files)==null?void 0:y[0];if(m&&confirm(`Restore from "${m.name}"? Your current database is archived (not deleted), and the new one takes effect after the daemon restarts.`)){o(!0),a(null);try{const N=new FormData;N.append("file",m);const p=await(await fetch("/api/data/restore",{method:"POST",body:N})).json();a(p),p.staged&&u.current&&(u.current.value="")}catch(N){a({error:N instanceof Error?N.message:String(N)})}finally{o(!1)}}};return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsx("h2",{className:"page-title",children:"Data"}),!e&&!n&&s.jsx("div",{className:"muted",children:"Loading…"}),n&&s.jsx("div",{className:"muted error",children:n}),e&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-title",children:"Storage"}),s.jsxs("dl",{className:"kv-list",children:[s.jsx("dt",{className:"kv-label",children:"Canonical SQLite"}),s.jsx("dd",{className:"kv-value mono",children:e.dbPath}),s.jsx("dt",{className:"kv-label",children:"On disk"}),s.jsxs("dd",{className:"kv-value mono",children:[lv(e.dbBytes),!e.dbPresent&&s.jsx("span",{className:"muted small",children:" · file missing"})]}),s.jsx("dt",{className:"kv-label",children:"Schema version"}),s.jsxs("dd",{className:"kv-value mono",children:[e.schemaVersion??"—",e.migrations.length>0&&s.jsxs("span",{className:"muted small",children:[" · ",e.migrations.length," migrations applied"]})]})]}),s.jsx("h3",{className:"section-title",children:"Tables"}),s.jsxs("table",{className:"data-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Table"}),s.jsx("th",{children:"Rows"})]})}),s.jsx("tbody",{children:e.tables.map(m=>s.jsxs("tr",{children:[s.jsx("td",{className:"mono small",children:m.name}),s.jsx("td",{className:"mono",children:m.rows.toLocaleString()})]},m.name))})]}),e.runtimes.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("h3",{className:"section-title",children:"Sessions by runtime"}),s.jsxs("table",{className:"data-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Runtime"}),s.jsx("th",{children:"Sessions"})]})}),s.jsx("tbody",{children:e.runtimes.map(m=>s.jsxs("tr",{children:[s.jsx("td",{className:"mono small",children:m.runtime}),s.jsx("td",{className:"mono",children:m.n.toLocaleString()})]},m.runtime))})]})]}),s.jsx("h3",{className:"section-title",children:"Backup"}),s.jsx("p",{className:"muted small",children:"Downloads a clean, defragmented snapshot of the canonical store. Safe to run while the daemon is ingesting."}),s.jsx("div",{className:"form-row",children:s.jsx("a",{className:"btn btn-accent",href:"/api/data/backup",download:!0,children:"Download backup"})}),s.jsx("h3",{className:"section-title",children:"Restore"}),s.jsxs("p",{className:"muted small",children:["Replace the canonical store with an ",s.jsx("code",{children:".sqlite"})," backup. The current database is archived alongside it (",s.jsx("code",{children:".pre-restore-<timestamp>"}),"), never deleted. Takes effect on the next daemon restart."]}),s.jsxs("div",{className:"form-row",children:[s.jsx("input",{ref:u,type:"file",accept:".sqlite,application/x-sqlite3",className:"file-input",disabled:i}),s.jsx("button",{type:"button",className:"btn",onClick:()=>void h(),disabled:i,children:i?"Validating…":"Restore from backup"})]}),(l==null?void 0:l.staged)&&s.jsx("div",{className:"card",style:{borderColor:"var(--accent)",padding:"0.75rem 1rem",marginTop:"0.75rem"},children:s.jsxs("p",{className:"small",style:{margin:0},children:["Backup validated and staged (",(f=l.sessions)==null?void 0:f.toLocaleString()," sessions, schema v",l.schemaVersion,").",s.jsx("strong",{children:" Restart the daemon"})," to apply it. Your current database will be archived automatically."]})}),(l==null?void 0:l.error)&&s.jsx("p",{className:"muted error small",children:l.error})]})]})}function av(){const[e,t]=x.useState(()=>es()),[n,r]=x.useState(!1),l=x.useRef(!0);x.useEffect(()=>{if(l.current){l.current=!1;return}bm(e),r(!0);const i=setTimeout(()=>r(!1),1800);return()=>clearTimeout(i)},[e]);const a=e.landing===xt.landing&&e.riverDensity===xt.riverDensity&&e.threadSort===xt.threadSort;return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsxs("div",{className:"form-row",style:{justifyContent:"space-between"},children:[s.jsx("h2",{className:"page-title",style:{margin:0},children:"Views"}),n&&s.jsx("span",{className:"muted small",children:"Saved"})]}),s.jsxs("div",{className:"form-grid",children:[s.jsx(Ms,{label:"Default landing",children:s.jsxs("select",{className:"form-input",value:e.landing,onChange:i=>t({...e,landing:i.target.value}),children:[s.jsx("option",{value:"live",children:"Live"}),s.jsx("option",{value:"pulse",children:"Pulse"}),s.jsx("option",{value:"river",children:"River"}),s.jsx("option",{value:"thread",children:"Thread"}),s.jsx("option",{value:"search",children:"Search"})]})}),s.jsx(Ms,{label:"River density",children:s.jsxs("select",{className:"form-input",value:e.riverDensity,onChange:i=>t({...e,riverDensity:i.target.value}),children:[s.jsx("option",{value:"compact",children:"Compact"}),s.jsx("option",{value:"comfortable",children:"Comfortable"}),s.jsx("option",{value:"spacious",children:"Spacious"})]})}),s.jsx(Ms,{label:"Thread sort",children:s.jsxs("select",{className:"form-input",value:e.threadSort,onChange:i=>t({...e,threadSort:i.target.value}),children:[s.jsx("option",{value:"recent",children:"Most recent first"}),s.jsx("option",{value:"oldest",children:"Oldest first"})]})})]}),s.jsx("div",{className:"form-row",children:s.jsx("button",{type:"button",className:"btn",onClick:()=>t(xt),disabled:a,children:"Reset to defaults"})}),s.jsx("p",{className:"muted small",children:"Preferences are stored per-device in localStorage. Landing applies on next load; River density and Thread sort apply when you open those pages."})]})}function Ms({label:e,children:t}){return s.jsxs("label",{className:"form-field",children:[s.jsx("span",{className:"form-label",children:e}),t]})}const Os=["candidate","project","tool","contact","service","concept"],iv=["all","active","snoozed","retired"],ov=[{value:"sessions-desc",label:"Sessions (high → low)"},{value:"sessions-asc",label:"Sessions (low → high)"},{value:"name-asc",label:"Name (A → Z)"},{value:"name-desc",label:"Name (Z → A)"},{value:"recent",label:"Most recently seen"},{value:"oldest",label:"Least recently seen"}],uv=[25,50,100,200];function cv(){const{data:e,loading:t,error:n,refetch:r}=Mn(),[l,a]=x.useState(""),[i,o]=x.useState("all"),[u,d]=x.useState("all"),[h,f]=x.useState("sessions-desc"),[m,k]=x.useState(50),[y,N]=x.useState(0),[S,p]=x.useState(null),c=(e==null?void 0:e.entities)??[],v=x.useMemo(()=>{const L=new Set(Os);for(const R of c)L.add(R.type);return["all",...[...L].sort()]},[c]),g=x.useMemo(()=>{const L=l.toLowerCase().trim(),F=[...c.filter(I=>i!=="all"&&I.type!==i||u!=="all"&&I.status!==u?!1:L?I.canonical.toLowerCase().includes(L)||I.type.toLowerCase().includes(L):!0)];return F.sort((I,H)=>{switch(h){case"sessions-desc":return H.session_count-I.session_count;case"sessions-asc":return I.session_count-H.session_count;case"name-asc":return I.canonical.localeCompare(H.canonical);case"name-desc":return H.canonical.localeCompare(I.canonical);case"recent":return(H.last_seen_session??"").localeCompare(I.last_seen_session??"");case"oldest":return(I.last_seen_session??"").localeCompare(H.last_seen_session??"")}}),F},[c,l,i,u,h]);x.useEffect(()=>{N(0)},[l,i,u,h,m]);const j=Math.max(1,Math.ceil(g.length/m)),w=Math.min(y,j-1),C=w*m,_=g.slice(C,C+m),$=async(L,R)=>{p(L);try{await R(),await r()}finally{p(null)}},T=(L,R)=>$(L,()=>yn({kind:"label_entity",subject_type:"entity",subject_id:L,payload:{new_type:R}}).then(()=>{})),D=L=>$(L,()=>yn({kind:"retire_entity",subject_type:"entity",subject_id:L}).then(()=>{})),W=L=>{const R=new Date(Date.now()+2592e6).toISOString();return $(L,()=>yn({kind:"snooze",subject_type:"entity",subject_id:L,payload:{snoozed_until:R}}).then(()=>{}))};return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsxs("div",{className:"page-header",children:[s.jsx("h2",{className:"page-title",children:"Labels"}),s.jsx("input",{className:"search-input",placeholder:"search canonical or type…",value:l,onChange:L=>a(L.target.value)})]}),s.jsxs("div",{className:"thread-filters",children:[s.jsx("div",{className:"filter-group",role:"group","aria-label":"Status filter",children:iv.map(L=>s.jsx("button",{type:"button",className:`chip${u===L?" active":""}`,onClick:()=>d(L),children:L},L))}),s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Type filter",children:[s.jsx("label",{className:"form-label",children:"Type"}),s.jsx("select",{className:"form-input form-input-inline",value:i,onChange:L=>o(L.target.value),children:v.map(L=>s.jsx("option",{value:L,children:L},L))})]}),s.jsxs("div",{className:"filter-group",role:"group","aria-label":"Sort",children:[s.jsx("label",{className:"form-label",children:"Sort"}),s.jsx("select",{className:"form-input form-input-inline",value:h,onChange:L=>f(L.target.value),children:ov.map(L=>s.jsx("option",{value:L.value,children:L.label},L.value))})]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[g.length," match",g.length===1?"":"es"]})]}),n&&s.jsx("div",{className:"muted error",children:n}),s.jsxs("table",{className:"data-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Canonical"}),s.jsx("th",{children:"Type"}),s.jsx("th",{children:"Status"}),s.jsx("th",{className:"right",children:"Sessions"}),s.jsx("th",{children:"Last seen"}),s.jsx("th",{children:"Actions"})]})}),t&&!e&&s.jsx(Em,{rows:8,cols:6}),s.jsxs("tbody",{children:[_.map(L=>{const R=S===L.canonical;return s.jsxs("tr",{className:R?"row-busy":"",children:[s.jsxs("td",{className:"canonical",children:[s.jsx("span",{className:"dot",style:{background:(e==null?void 0:e.entity_colors[L.canonical])??"#666"}}),L.canonical]}),s.jsx("td",{children:s.jsx("select",{className:"form-input form-input-inline",value:Os.includes(L.type)?L.type:"candidate",onChange:F=>void T(L.canonical,F.target.value),disabled:R,children:Os.map(F=>s.jsx("option",{value:F,children:F},F))})}),s.jsx("td",{children:s.jsx("span",{className:`chip-inline status-${L.status}`,children:L.status})}),s.jsx("td",{className:"right mono",children:L.session_count}),s.jsx("td",{className:"mono small",children:L.last_seen_session??"—"}),s.jsxs("td",{className:"row-actions",children:[s.jsx("button",{type:"button",className:"chip",disabled:R,onClick:()=>void W(L.canonical),children:"snooze 30d"}),s.jsx("button",{type:"button",className:"chip",disabled:R,onClick:()=>void D(L.canonical),children:"retire"})]})]},L.canonical)}),_.length===0&&s.jsx("tr",{children:s.jsx("td",{colSpan:6,className:"muted small empty-row",children:c.length===0?"No entities yet.":"No entities match the current filters."})})]})]}),g.length>0&&s.jsxs("div",{className:"pagination",children:[s.jsxs("div",{className:"page-size",children:[s.jsx("label",{className:"form-label",children:"Per page"}),s.jsx("select",{className:"form-input form-input-inline",value:m,onChange:L=>k(Number.parseInt(L.target.value,10)),children:uv.map(L=>s.jsx("option",{value:L,children:L},L))})]}),s.jsx("span",{className:"header-spacer"}),s.jsxs("span",{className:"muted small",children:[C+1,"–",Math.min(C+m,g.length)," of ",g.length]}),s.jsxs("div",{className:"page-nav",children:[s.jsx("button",{type:"button",className:"chip",disabled:w===0,onClick:()=>N(0),children:"« first"}),s.jsx("button",{type:"button",className:"chip",disabled:w===0,onClick:()=>N(L=>Math.max(0,L-1)),children:"‹ prev"}),s.jsxs("span",{className:"page-indicator mono",children:[w+1," / ",j]}),s.jsx("button",{type:"button",className:"chip",disabled:w>=j-1,onClick:()=>N(L=>Math.min(j-1,L+1)),children:"next ›"}),s.jsx("button",{type:"button",className:"chip",disabled:w>=j-1,onClick:()=>N(j-1),children:"last »"})]})]}),s.jsx("p",{className:"muted small",children:"Changes are append-only actions; refresh re-applies the overlay over the persisted store."})]})}const dv=["claude-code","codex","hermes","pi","jsonl-generic","webhook"],fv=["deepseek","ollama","openai","anthropic","openrouter","openai-compatible"],nr={deepseek:"DeepSeek",ollama:"Ollama",openai:"OpenAI",anthropic:"Anthropic",openrouter:"OpenRouter","openai-compatible":"OpenAI-compatible"},_d={"claude-code":"Claude Code",codex:"Codex",hermes:"Hermes",pi:"pi.dev","jsonl-generic":"Custom JSONL",webhook:"Webhook"},Zo={"claude-code":{name:"Claude Code",runtimeLabel:"claude-code",pathOrUrl:"~/.claude/projects",parseConfig:{}},codex:{name:"Codex",runtimeLabel:"codex",pathOrUrl:"~/.codex/sessions",parseConfig:{}},hermes:{name:"Hermes",runtimeLabel:"hermes",pathOrUrl:"~/.hermes/sessions",parseConfig:{}},pi:{name:"pi.dev",runtimeLabel:"pi",pathOrUrl:"~/.pi/transcripts",parseConfig:{}},"jsonl-generic":{name:"",runtimeLabel:"",pathOrUrl:"",parseConfig:{idField:"session_id",textField:"text",startedAtField:"started_at",endedAtField:"ended_at"}},webhook:{name:"",runtimeLabel:"",pathOrUrl:null,parseConfig:{}}},qo={deepseek:{baseUrl:"https://api.deepseek.com",defaultModel:"deepseek-v4-flash"},ollama:{baseUrl:"http://localhost:11434",defaultModel:"phi4-mini:latest"},openai:{baseUrl:"https://api.openai.com/v1",defaultModel:"gpt-4o-mini"},anthropic:{baseUrl:"https://api.anthropic.com",defaultModel:"claude-haiku-4-5-20251001"},openrouter:{baseUrl:"https://openrouter.ai/api/v1",defaultModel:"anthropic/claude-haiku-4-5"},"openai-compatible":{baseUrl:"",defaultModel:null}};async function pv(){const e=await fetch("/api/sources");if(!e.ok)throw new Error(`HTTP ${e.status}`);return(await e.json()).sources}async function Pd(){const e=await fetch("/api/providers");if(!e.ok)throw new Error(`HTTP ${e.status}`);return(await e.json()).providers}async function hv(e){const t=await fetch(`/api/providers/${e}/models`),n=await t.json();if(!t.ok||n.error)throw new Error(n.error??`HTTP ${t.status}`);return n.models??[]}async function Li(e){return await(await fetch(`/api/providers/${e}/test`,{method:"POST"})).json()}function mv(){const[e,t]=x.useState(null),[n,r]=x.useState([]),[l,a]=x.useState([]),[i,o]=x.useState(null),[u,d]=x.useState(null),[h,f]=x.useState(""),[m,k]=x.useState(null),[y,N]=x.useState(null),[S,p]=x.useState(!1),[c,v]=x.useState(null),[g,j]=x.useState(null),w=x.useCallback(async()=>{try{const[R,F]=await Promise.all([fetch("/api/classifier/info").then(z=>z.json()),Pd()]);t(R),r(F);const I=F.find(z=>z.kind===R.provider&&z.enabled),H=F.find(z=>z.enabled)??F[0]??null,M=I??H;d(M?M.id:null),f(R.model),j(null)}catch(R){j(R instanceof Error?R.message:String(R))}},[]);x.useEffect(()=>{w()},[w]);const C=x.useMemo(()=>n.find(R=>R.id===u)??null,[n,u]);x.useEffect(()=>{if(!C){a([]);return}let R=!1;return o(null),a([]),hv(C.id).then(F=>{R||(a(F),(!h||!F.includes(h))&&f(C.defaultModel??F[0]??""))}).catch(F=>{R||o(F instanceof Error?F.message:String(F))}),()=>{R=!0}},[C==null?void 0:C.id]);const _=C?`${C.id}|${h}`:"",$=(m==null?void 0:m.ok)===!0&&y===_,D=(e&&C?C.kind!==e.provider||h!==e.model:!1)&&h.length>0&&!S&&$,W=async()=>{if(C){p(!0),k(null),N(null);try{const R=await Li(C.id);k(R),R.ok&&N(_)}catch(R){k({ok:!1,latencyMs:0,error:R instanceof Error?R.message:String(R)})}finally{p(!1)}}},L=async()=>{if(C){p(!0),v(null);try{const R=await fetch("/api/classifier",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:C.kind,model:h})}),F=await R.json();!R.ok||F.error?v(`Error: ${F.error??R.statusText}`):(v(`Active: ${F.provider} · ${F.model}`),await w())}catch(R){v(`Error: ${R instanceof Error?R.message:String(R)}`)}finally{p(!1)}}};return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsx("h2",{className:"page-title",children:"Classifier"}),!e&&!g&&s.jsx("div",{className:"muted",children:"Loading…"}),g&&s.jsx("div",{className:"muted error",children:g}),e&&s.jsxs(s.Fragment,{children:[s.jsxs("dl",{className:"kv-list",children:[s.jsx("dt",{className:"kv-label",children:"Active provider"}),s.jsx("dd",{className:"kv-value mono",children:e.provider}),s.jsx("dt",{className:"kv-label",children:"Active model"}),s.jsx("dd",{className:"kv-value mono",children:e.model})]}),s.jsx("h3",{className:"section-title",children:"Switch model"}),n.length===0?s.jsxs("p",{className:"muted small",children:["No providers configured. Add one on the ",s.jsx("a",{href:"/settings/providers",children:"Providers"})," page first."]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:"Provider"}),s.jsx("select",{className:"form-input form-input-inline",value:u??"",onChange:R=>{d(Number.parseInt(R.target.value,10)),k(null),N(null)},disabled:S,children:n.map(R=>s.jsxs("option",{value:R.id,disabled:!R.enabled,children:[R.name," (",nr[R.kind],")",R.enabled?"":" — disabled",R.kind!=="ollama"&&!R.hasApiKey?" — no key":""]},R.id))}),s.jsx("label",{className:"form-label",children:"Model"}),s.jsxs("select",{className:"form-input form-input-inline",value:h,onChange:R=>{f(R.target.value),N(null)},disabled:S||l.length===0,children:[l.map(R=>s.jsx("option",{value:R,children:R},R)),!l.includes(h)&&h&&s.jsx("option",{value:h,children:h})]}),s.jsx("button",{type:"button",className:"btn",onClick:()=>void W(),disabled:S||!C,children:S&&!m?"Testing…":"Test connection"}),s.jsx("button",{type:"button",className:"btn btn-accent",onClick:()=>void L(),disabled:!D,title:$?void 0:"Run a successful test before saving",children:S&&(m!=null&&m.ok)?"Saving…":"Save"})]}),i&&s.jsxs("p",{className:"muted error small",children:["Model list failed: ",i]}),m&&s.jsx("p",{className:`small ${m.ok?"muted":"muted error"}`,children:m.ok?`Connection OK · ${m.modelCount??"?"} models · ${m.latencyMs}ms`:`Connection failed: ${m.error??"unknown"} (${m.latencyMs}ms)`}),c&&s.jsx("p",{className:"muted small",children:c}),s.jsx("p",{className:"muted small",children:"Save is gated on a passing connection test for the selected provider + model."})]}),s.jsx("h3",{className:"section-title",children:"Embedder"}),s.jsxs("dl",{className:"kv-list",children:[s.jsx("dt",{className:"kv-label",children:"Provider"}),s.jsx("dd",{className:"kv-value mono",children:e.embedder.provider}),s.jsx("dt",{className:"kv-label",children:"Model"}),s.jsx("dd",{className:"kv-value mono",children:e.embedder.model}),s.jsx("dt",{className:"kv-label",children:"Dimensions"}),s.jsx("dd",{className:"kv-value mono",children:e.embedder.dims})]}),s.jsx("p",{className:"muted small",children:"Embedder is fixed at build time. Recall vectors must match the index dims, so it isn't hot-swappable. DeepSeek has no embeddings endpoint; Ollama serves both classification (optional) and embedding (always)."})]})]})}function vv(){const[e,t]=x.useState([]),[n,r]=x.useState(null),[l,a]=x.useState(!0),[i,o]=x.useState(!1),[u,d]=x.useState(null),h=x.useCallback(async()=>{a(!0);try{t(await pv()),r(null)}catch(y){r(y instanceof Error?y.message:String(y))}finally{a(!1)}},[]);x.useEffect(()=>{h()},[h]);const f=async y=>{await fetch(`/api/sources/${y.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!y.enabled})}),await h()},m=async y=>{confirm(`Delete source "${y.name}"? This stops scanning but leaves ingested sessions in place.`)&&(await fetch(`/api/sources/${y.id}`,{method:"DELETE"}),await h())},k=async y=>{if(!confirm(`Regenerate token for "${y.name}"? Any client using the current token will stop working.`))return;const N=await fetch(`/api/sources/${y.id}/regenerate-token`,{method:"POST"}),S=await N.json();S.token?(d({name:y.name,token:S.token}),await h()):alert(`Failed: ${S.error??N.statusText}`)};return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsxs("div",{className:"form-row",style:{justifyContent:"space-between"},children:[s.jsx("h2",{className:"page-title",style:{margin:0},children:"Sources"}),s.jsx("button",{type:"button",className:"btn btn-accent",onClick:()=>o(!0),children:"Add source"})]}),u&&s.jsx(gv,{name:u.name,token:u.token,onDismiss:()=>d(null)}),l&&e.length===0&&s.jsx("div",{className:"muted",children:"Loading…"}),n&&s.jsx("div",{className:"muted error",children:n}),e.length>0&&s.jsxs("table",{className:"data-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Kind"}),s.jsx("th",{children:"Runtime"}),s.jsx("th",{children:"Path / URL"}),s.jsx("th",{children:"Status"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:e.map(y=>s.jsxs("tr",{children:[s.jsx("td",{className:"mono",children:y.name}),s.jsx("td",{children:_d[y.kind]}),s.jsx("td",{className:"mono small",children:y.runtimeLabel}),s.jsx("td",{className:"mono small",children:y.pathOrUrl??(y.kind==="webhook"?"—":"")}),s.jsx("td",{children:s.jsx("span",{className:`chip-inline ${y.enabled?"status-active":"status-stale"}`,children:y.enabled?"enabled":"disabled"})}),s.jsx("td",{children:s.jsxs("div",{className:"form-row",style:{gap:"0.5rem"},children:[s.jsx("button",{type:"button",className:"btn small",onClick:()=>void f(y),children:y.enabled?"Disable":"Enable"}),y.kind==="webhook"&&s.jsx("button",{type:"button",className:"btn small",onClick:()=>void k(y),children:"Regenerate token"}),s.jsx("button",{type:"button",className:"btn small",onClick:()=>void m(y),children:"Delete"})]})})]},y.id))})]}),!l&&e.length===0&&s.jsx("p",{className:"muted small",children:'No sources yet. Click "Add source" to scan your first transcript directory.'}),i&&s.jsx(yv,{onClose:()=>o(!1),onCreated:y=>{o(!1),y.kind==="webhook"&&y.token&&d({name:y.name,token:y.token}),h()}})]})}function gv({name:e,token:t,onDismiss:n}){return s.jsxs("div",{className:"card",style:{borderColor:"var(--accent)",padding:"1rem",marginTop:"1rem"},children:[s.jsxs("h3",{className:"section-title",style:{marginTop:0},children:['One-time token for "',e,'"']}),s.jsxs("p",{className:"muted small",children:["Copy this now. It's stored hashed on the daemon and won't be shown again. Send sessions with"," ",s.jsx("code",{children:"Authorization: Bearer <token>"})," to ",s.jsx("code",{children:"POST /api/ingest"}),"."]}),s.jsx("pre",{className:"mono",style:{padding:"0.5rem",overflow:"auto"},children:t}),s.jsxs("div",{className:"form-row",children:[s.jsx("button",{type:"button",className:"btn",onClick:()=>void navigator.clipboard.writeText(t),children:"Copy"}),s.jsx("button",{type:"button",className:"btn btn-accent",onClick:n,children:"I've stored it"})]})]})}function yv({onClose:e,onCreated:t}){const[n,r]=x.useState("claude-code"),l=Zo[n],[a,i]=x.useState(l.name),[o,u]=x.useState(l.runtimeLabel),[d,h]=x.useState(l.pathOrUrl??""),[f,m]=x.useState({idField:"session_id",textField:"text",startedAtField:"started_at",endedAtField:"ended_at"}),[k,y]=x.useState(!1),[N,S]=x.useState(null);x.useEffect(()=>{const j=Zo[n];i(j.name),u(j.runtimeLabel),h(j.pathOrUrl??""),S(null)},[n]);const p=n!=="webhook",c=n==="jsonl-generic",v=async()=>{y(!0),S(null);try{const j={kind:n,name:a,runtimeLabel:o};p&&(j.pathOrUrl=d),c&&(j.parseConfig=f);const w=await fetch("/api/sources",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(j)}),C=await w.json();if(!w.ok||C.error){S(C.error??w.statusText);return}t(C)}catch(j){S(j instanceof Error?j.message:String(j))}finally{y(!1)}},g=!k&&a.length>0&&o.length>0&&(!p||d.length>0);return s.jsxs("div",{className:"card",style:{padding:"1rem",marginTop:"1rem"},children:[s.jsx("h3",{className:"section-title",style:{marginTop:0},children:"Add source"}),s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:"Kind"}),s.jsx("select",{className:"form-input form-input-inline",value:n,onChange:j=>r(j.target.value),disabled:k,children:dv.map(j=>s.jsx("option",{value:j,children:_d[j]},j))})]}),s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:"Name"}),s.jsx("input",{className:"form-input form-input-inline",value:a,onChange:j=>i(j.target.value),placeholder:c||n==="webhook"?"e.g. my-agent":"",disabled:k}),s.jsx("label",{className:"form-label",children:"Runtime label"}),s.jsx("input",{className:"form-input form-input-inline",value:o,onChange:j=>u(j.target.value),placeholder:"appears on Pulse Runtimes card",disabled:k})]}),p&&s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:n==="jsonl-generic"?"Directory":"Path"}),s.jsx("input",{className:"form-input form-input-inline",style:{minWidth:"32rem"},value:d,onChange:j=>h(j.target.value),placeholder:"absolute or ~/ path to JSONL directory",disabled:k})]}),c&&s.jsxs(s.Fragment,{children:[s.jsx("h4",{className:"section-title",style:{fontSize:"0.875rem"},children:"JSONL field mapping"}),s.jsx("p",{className:"muted small",children:"How to read your JSONL files. Each row should be one session. Use dot.notation for nested fields."}),["idField","textField","startedAtField","endedAtField"].map(j=>s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:j}),s.jsx("input",{className:"form-input form-input-inline",value:f[j],onChange:w=>m({...f,[j]:w.target.value}),disabled:k})]},j))]}),n==="webhook"&&s.jsxs("p",{className:"muted small",children:["A bearer token will be generated and shown ",s.jsx("strong",{children:"once"})," when you create this source. Use it to ",s.jsx("code",{children:"POST /api/ingest"})," from any agent or script."]}),N&&s.jsx("p",{className:"muted error small",children:N}),s.jsxs("div",{className:"form-row",children:[s.jsx("button",{type:"button",className:"btn btn-accent",onClick:()=>void v(),disabled:!g,children:k?"Creating…":"Create"}),s.jsx("button",{type:"button",className:"btn",onClick:e,disabled:k,children:"Cancel"})]})]})}function xv(){const[e,t]=x.useState([]),[n,r]=x.useState(null),[l,a]=x.useState(!0),[i,o]=x.useState(!1),[u,d]=x.useState({}),h=x.useCallback(async()=>{a(!0);try{t(await Pd()),r(null)}catch(y){r(y instanceof Error?y.message:String(y))}finally{a(!1)}},[]);x.useEffect(()=>{h()},[h]);const f=async y=>{await fetch(`/api/providers/${y.id}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({enabled:!y.enabled})}),await h()},m=async y=>{confirm(`Delete provider "${y.name}"? The Classifier will fall back to another provider if this one was active.`)&&(await fetch(`/api/providers/${y.id}`,{method:"DELETE"}),await h())},k=async y=>{d(N=>({...N,[y.id]:"running"}));try{const N=await Li(y.id);d(S=>({...S,[y.id]:N}))}catch(N){d(S=>({...S,[y.id]:{ok:!1,latencyMs:0,error:N instanceof Error?N.message:String(N)}}))}};return s.jsxs("div",{className:"page-pad",children:[s.jsx(Jt,{}),s.jsxs("div",{className:"form-row",style:{justifyContent:"space-between"},children:[s.jsx("h2",{className:"page-title",style:{margin:0},children:"Providers"}),s.jsx("button",{type:"button",className:"btn btn-accent",onClick:()=>o(!0),children:"Add provider"})]}),l&&e.length===0&&s.jsx("div",{className:"muted",children:"Loading…"}),n&&s.jsx("div",{className:"muted error",children:n}),e.length>0&&s.jsxs("table",{className:"data-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:"Name"}),s.jsx("th",{children:"Kind"}),s.jsx("th",{children:"Base URL"}),s.jsx("th",{children:"Default model"}),s.jsx("th",{children:"API key"}),s.jsx("th",{children:"Status"}),s.jsx("th",{children:"Last test"}),s.jsx("th",{})]})}),s.jsx("tbody",{children:e.map(y=>{const N=u[y.id];return s.jsxs("tr",{children:[s.jsx("td",{className:"mono",children:y.name}),s.jsx("td",{children:nr[y.kind]}),s.jsx("td",{className:"mono small",children:y.baseUrl??"—"}),s.jsx("td",{className:"mono small",children:y.defaultModel??"—"}),s.jsx("td",{children:y.kind==="ollama"||y.kind==="openai-compatible"?s.jsx("span",{className:"muted small",children:y.hasApiKey?"set":"n/a"}):s.jsx("span",{className:`chip-inline ${y.hasApiKey?"status-active":"status-stale"}`,children:y.hasApiKey?"set":"missing"})}),s.jsx("td",{children:s.jsx("span",{className:`chip-inline ${y.enabled?"status-active":"status-stale"}`,children:y.enabled?"enabled":"disabled"})}),s.jsxs("td",{className:"small",children:[N==="running"&&s.jsx("span",{className:"muted",children:"testing…"}),N&&N!=="running"&&N.ok&&s.jsxs("span",{className:"muted",children:["OK · ",N.modelCount," models · ",N.latencyMs,"ms"]}),N&&N!=="running"&&!N.ok&&s.jsxs("span",{className:"muted error",children:["fail: ",N.error]})]}),s.jsx("td",{children:s.jsxs("div",{className:"form-row",style:{gap:"0.5rem"},children:[s.jsx("button",{type:"button",className:"btn small",onClick:()=>void k(y),children:"Test"}),s.jsx("button",{type:"button",className:"btn small",onClick:()=>void f(y),children:y.enabled?"Disable":"Enable"}),s.jsx("button",{type:"button",className:"btn small",onClick:()=>void m(y),children:"Delete"})]})})]},y.id)})})]}),!l&&e.length===0&&s.jsx("p",{className:"muted small",children:'No providers yet. Click "Add provider" to wire up DeepSeek, Ollama, or any OpenAI-compatible endpoint.'}),i&&s.jsx(jv,{onClose:()=>o(!1),onCreated:()=>{o(!1),h()}})]})}function jv({onClose:e,onCreated:t}){const[n,r]=x.useState("deepseek"),l=qo[n],[a,i]=x.useState(nr[n]),[o,u]=x.useState(l.baseUrl??""),[d,h]=x.useState(""),[f,m]=x.useState(l.defaultModel??""),[k,y]=x.useState(!1),[N,S]=x.useState(null),[p,c]=x.useState(null);x.useEffect(()=>{const w=qo[n];i(nr[n]),u(w.baseUrl??""),m(w.defaultModel??""),c(null),S(null)},[n]);const v=n!=="ollama"&&n!=="openai-compatible",g=async w=>{y(!0),S(null);try{const C={kind:n,name:a};o&&(C.baseUrl=o),d&&(C.apiKey=d),f&&(C.defaultModel=f);const _=await fetch("/api/providers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C)}),$=await _.json();if(!_.ok||$.error){S($.error??_.statusText);return}if(w){const T=await Li($.id);if(c(T),!T.ok)return}t()}catch(C){S(C instanceof Error?C.message:String(C))}finally{y(!1)}},j=!k&&a.length>0&&(!v||d.length>0);return s.jsxs("div",{className:"card",style:{padding:"1rem",marginTop:"1rem"},children:[s.jsx("h3",{className:"section-title",style:{marginTop:0},children:"Add provider"}),s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:"Kind"}),s.jsx("select",{className:"form-input form-input-inline",value:n,onChange:w=>r(w.target.value),disabled:k,children:fv.map(w=>s.jsx("option",{value:w,children:nr[w]},w))}),s.jsx("label",{className:"form-label",children:"Name"}),s.jsx("input",{className:"form-input form-input-inline",value:a,onChange:w=>i(w.target.value),placeholder:"Display name (must be unique)",disabled:k})]}),s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:"Base URL"}),s.jsx("input",{className:"form-input form-input-inline",style:{minWidth:"28rem"},value:o,onChange:w=>u(w.target.value),placeholder:n==="openai-compatible"?"https://your-endpoint/v1":"",disabled:k})]}),s.jsxs("div",{className:"form-row",children:[s.jsxs("label",{className:"form-label",children:["API key",v?"":" (optional)"]}),s.jsx("input",{type:"password",className:"form-input form-input-inline",style:{minWidth:"28rem"},value:d,onChange:w=>h(w.target.value),autoComplete:"off",disabled:k})]}),s.jsxs("div",{className:"form-row",children:[s.jsx("label",{className:"form-label",children:"Default model"}),s.jsx("input",{className:"form-input form-input-inline",value:f,onChange:w=>m(w.target.value),placeholder:"optional",disabled:k})]}),p&&!p.ok&&s.jsxs("p",{className:"muted error small",children:["Saved, but test failed: ",p.error," (",p.latencyMs,"ms). You can edit or delete from the list."]}),N&&s.jsx("p",{className:"muted error small",children:N}),s.jsxs("div",{className:"form-row",children:[s.jsx("button",{type:"button",className:"btn btn-accent",onClick:()=>void g(!0),disabled:!j,children:k?"Saving…":"Save & test"}),s.jsx("button",{type:"button",className:"btn",onClick:()=>void g(!1),disabled:!j,children:"Save without testing"}),s.jsx("button",{type:"button",className:"btn",onClick:e,disabled:k,children:"Cancel"})]})]})}function wv({page:e}){return s.jsxs("div",{className:"stub-shell",children:[s.jsxs("span",{className:"stub-name",children:["/",e]}),s.jsx("p",{children:"not yet ported from the Astro UI."}),s.jsx("p",{className:"stub-hint",children:"Tracked in NocoDB #95 (Vite + React SPA port)."})]})}function Nv(){return s.jsxs("div",{className:"page-shell",children:[s.jsx(fm,{}),s.jsxs("div",{className:"page-main",children:[s.jsx(kv,{}),s.jsxs(Gh,{children:[s.jsx(ve,{path:"/",element:s.jsx(Yh,{to:`/${es().landing}`,replace:!0})}),s.jsx(ve,{path:"/live",element:s.jsx(Lm,{})}),s.jsx(ve,{path:"/pulse",element:s.jsx(Rm,{})}),s.jsx(ve,{path:"/river",element:s.jsx(Dm,{})}),s.jsx(ve,{path:"/thread",element:s.jsx(Km,{})}),s.jsx(ve,{path:"/search",element:s.jsx(Hm,{})}),s.jsx(ve,{path:"/recall",element:s.jsx(ev,{})}),s.jsx(ve,{path:"/settings",element:s.jsx(rv,{})}),s.jsx(ve,{path:"/settings/sources",element:s.jsx(vv,{})}),s.jsx(ve,{path:"/settings/providers",element:s.jsx(xv,{})}),s.jsx(ve,{path:"/settings/labels",element:s.jsx(cv,{})}),s.jsx(ve,{path:"/settings/classifier",element:s.jsx(mv,{})}),s.jsx(ve,{path:"/settings/data",element:s.jsx(sv,{})}),s.jsx(ve,{path:"/settings/views",element:s.jsx(av,{})}),s.jsx(ve,{path:"*",element:s.jsx(wv,{page:"not found"})})]})]})]})}function kv(){const{pathname:e}=$t(),t=e.replace(/^\//,"").replace(/\/+$/,"")||"live";return s.jsxs("header",{className:"app-header",children:[s.jsx("span",{className:"wordmark-page",children:t}),s.jsx("span",{className:"header-spacer"}),s.jsx("span",{className:"status-dot","aria-hidden":"true"}),s.jsx("span",{className:"header-info",children:"nlm-memory · :3940"})]})}const Ld=document.getElementById("root");if(!Ld)throw new Error("missing #root");pd(Ld).render(s.jsx(cu.StrictMode,{children:s.jsx(sm,{basename:"/ui",children:s.jsx(Nv,{})})}));