@rulemetric/local 0.14.2 → 0.15.0
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.
|
@@ -139,8 +139,8 @@ Then, for each step in order (install, auth, hooks, worker):
|
|
|
139
139
|
|
|
140
140
|
Finish by running \`rulemetric setup --json\` and report the final green/red
|
|
141
141
|
status. If any step fails, diagnose it from its output before continuing.`,CORE_ORDER=["install","auth","hooks","worker"];function stateBadge(es){switch(es){case"detected":return jsxRuntimeExports.jsx(Badge,{className:"bg-teal-500/15 text-teal-400 border-teal-500/30",children:"Detected"});case"loading":return jsxRuntimeExports.jsx(Badge,{variant:"outline",children:"Checking…"});case"attention":return jsxRuntimeExports.jsx(Badge,{className:"bg-amber-500/15 text-amber-400 border-amber-500/30",children:"Action needed"});default:return jsxRuntimeExports.jsx(Badge,{variant:"outline",children:"Waiting"})}}function CoreSteps(){const{progress:es}=useSetupWalkthrough(),$=useQueryClient(),[ts,is]=reactExports.useState(!1),cs=es.currentStepId,Qr=CORE_ORDER.slice(1).find(Fa=>es.steps[Fa].state!=="detected")??cs,ja=ts&&cs==="install"?Qr:cs;reactExports.useEffect(()=>{cs!=="install"&&ts&&is(!1)},[cs,ts]);const Na=reactExports.useRef(ja),[Aa,Oa]=reactExports.useState(null);reactExports.useEffect(()=>{const Fa=Na.current;if(Na.current=ja,Fa==null||Fa===ja)return;const Ha=es.steps[Fa];if(Ha.state!=="detected")return;Oa({label:Ha.label});const Ka=setTimeout(()=>Oa(null),800);return()=>clearTimeout(Ka)},[ja,es.steps]);function Ia(){$.invalidateQueries({queryKey:["worker-status"]}),$.invalidateQueries({queryKey:["sessions"]}),$.invalidateQueries({queryKey:["terminal-targets"]})}if(es.coreComplete||ja==null)return null;const La=es.steps[ja],Ba=CORE_ORDER.indexOf(ja)+1,Ma=La.state==="attention",qa=La.state==="loading";return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3 space-y-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"Set me up with Claude Code"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste into Claude Code — it installs step by step, showing exactly what it writes and asking before each change."})]}),jsxRuntimeExports.jsx(CopyButton$3,{text:CC_SETUP_PROMPT})]})}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"h-px flex-1 bg-border"}),"or do it yourself",jsxRuntimeExports.jsx("span",{className:"h-px flex-1 bg-border"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("div",{className:"flex items-center gap-1.5",children:CORE_ORDER.map(Fa=>{const Ha=es.steps[Fa],Ka=Ha.state==="detected",Ga=Fa===ja;return jsxRuntimeExports.jsx("span",{className:cn$1("h-2 w-2 rounded-full transition-colors",Ka?"bg-teal-500":Ga?"bg-primary ring-2 ring-primary/30":"bg-muted"),"aria-label":`${Ha.label}: ${Ha.state}`},Fa)})}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["Step ",Ba," of ",CORE_ORDER.length]})]}),Aa&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-teal-500/30 bg-teal-500/10 px-3 py-2 text-sm text-teal-400",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0"}),jsxRuntimeExports.jsxs("span",{className:"font-medium",children:[Aa.label," done"]})]}),jsxRuntimeExports.jsxs("div",{className:cn$1("rounded-lg border bg-background p-4 space-y-3",Ma?"border-amber-500/40":"border-border"),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[qa?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 shrink-0 animate-spin text-muted-foreground"}):Ma?jsxRuntimeExports.jsx(CircleAlert,{className:"h-4 w-4 shrink-0 text-amber-400"}):jsxRuntimeExports.jsx(Hourglass,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium truncate",children:La.label})]}),stateBadge(La.state)]}),qa?jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Checking current state…"]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[La.command&&jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"Run this"}),jsxRuntimeExports.jsx(CopyButton$3,{text:La.command})]}),jsxRuntimeExports.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-[#0B1120] p-3 text-xs font-mono whitespace-pre-wrap",children:La.command})]}),La.waitingFor&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}),"Waiting for ",La.waitingFor,"…"]}),La.hint&&jsxRuntimeExports.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground/80",children:La.hint}),Ma&&!La.command&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-400",children:"Sign in to continue capturing sessions."})]}),jsxRuntimeExports.jsx("div",{className:"flex items-center justify-end pt-1",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[ja==="install"&&jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:()=>is(!0),className:"cursor-pointer text-muted-foreground",children:"I've installed it →"}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",onClick:Ia,className:"cursor-pointer",children:[jsxRuntimeExports.jsx(RefreshCw,{className:"mr-1 h-3 w-3"}),"Check again"]})]})})]})]})}const CURRENT_LIMITS_POLL_MS=15e3;function useCurrentLimits(es="anthropic"){return useQuery({queryKey:["usage","current-limits",es],queryFn:()=>apiGet(`/api/usage/current-limits?provider=${encodeURIComponent(es)}`),staleTime:0,refetchOnMount:"always",refetchOnWindowFocus:"always",refetchOnReconnect:"always",refetchInterval:CURRENT_LIMITS_POLL_MS})}function useInferredCaps(){return useQuery({queryKey:["usage","inferred-caps"],queryFn:()=>apiGet("/api/usage/inferred-caps"),staleTime:5*6e4})}function assessLimitWindow(es){const{usedPercentage:$,resetsAt:ts,now:is}=es;if($==null||!Number.isFinite($))return{kind:"never-observed"};if(ts==null)return{kind:"current",usedPercentage:$};const cs=Date.parse(ts);if(!Number.isFinite(cs))return{kind:"current",usedPercentage:$};const Qr=is.getTime()-cs;return Qr>=0?{kind:"expired",lastPercentage:$,endedMsAgo:Qr}:{kind:"current",usedPercentage:$}}function formatElapsed(es){const $=Math.floor(Math.max(0,es)/6e4);if($<60)return`${$}m`;const ts=Math.floor($/60);return ts<48?`${ts}h`:`${Math.floor(ts/24)}d`}const PLAN_OPTIONS=[{code:"free",label:"Free"},{code:"pro",label:"Pro"},{code:"max_5x",label:"Max 5x"},{code:"max_20x",label:"Max 20x"}],PLAN_LABEL=Object.fromEntries(PLAN_OPTIONS.map(es=>[es.code,es.label]));function planLabel$1(es){return PLAN_LABEL[es]??es}function startOfMonthIso$1(){const es=new Date;return new Date(es.getFullYear(),es.getMonth(),1).toISOString()}function formatUsd$1(es){return es>=1e3?`$${(es/1e3).toFixed(2)}K`:es>=1?`$${es.toFixed(2)}`:es>0?`$${es.toFixed(3)}`:"$0.00"}function Payoff(){const{goTo:es}=useSetupWalkthrough(),$=useCurrentLimits(),ts=useInferredCaps(),is=useComputedInsights(void 0,void 0,{since:startOfMonthIso$1(),refetchIntervalMs:3e4});return jsxRuntimeExports.jsxs("div",{className:"space-y-5",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("h3",{className:"flex items-center gap-2 text-base font-semibold",children:[jsxRuntimeExports.jsx(PartyPopper,{className:"h-5 w-5 text-primary"}),"You're capturing! 🎉"]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"RuleMetric is now watching your Claude Code sessions. Here's your usage so far."})]}),jsxRuntimeExports.jsx(UsageSummary,{limits:$,insights:is}),jsxRuntimeExports.jsx(PlanDetection,{caps:ts}),jsxRuntimeExports.jsx("div",{className:"flex justify-end pt-1",children:jsxRuntimeExports.jsx(Button,{onClick:()=>es("livesend"),children:"Continue"})})]})}function UsageSummary({limits:es,insights:$}){var Ma,qa,Fa,Ha,Ka,Ga,Va;if(es.isLoading&&!es.data||$.isLoading&&!$.data)return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 rounded-lg border border-border bg-muted/30 px-4 py-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin"}),"Checking your usage…"]});const is=((Ma=es.data)==null?void 0:Ma.five_hour)??null,cs=((qa=es.data)==null?void 0:qa.seven_day)??null,Qr=((Fa=es.data)==null?void 0:Fa.seven_day_opus)??null,ja=is!=null||cs!=null||Qr!=null,Na=(Ha=$.data)==null?void 0:Ha.estimated_cost_usd,Aa=((Ka=$.data)==null?void 0:Ka.total_input_tokens)??0,Oa=((Ga=$.data)==null?void 0:Ga.total_output_tokens)??0,Ia=(Va=$.data)==null?void 0:Va.estimated_cost_by_model,La=typeof Na=="number"&&Na>0||Aa>0||Oa>0;if(!ja&&!La)return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 rounded-lg border border-dashed border-primary/40 bg-primary/5 px-4 py-6 text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"relative flex h-3 w-3 shrink-0",children:[jsxRuntimeExports.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-primary/60"}),jsxRuntimeExports.jsx("span",{className:"relative inline-flex h-3 w-3 rounded-full bg-primary"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-0.5",children:[jsxRuntimeExports.jsx("p",{className:"font-medium",children:"Watching for your first session…"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Run Claude Code and this fills in automatically."})]})]});const Ba=Ia?Object.entries(Ia).sort(([,Ja],[,Ya])=>Ya.cost_usd-Ja.cost_usd):[];return jsxRuntimeExports.jsxs("div",{className:"space-y-3 rounded-lg border border-border bg-background p-4",children:[ja&&jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Rate limits"}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs font-mono",children:[jsxRuntimeExports.jsx(LimitChip,{label:"5h",obs:is}),jsxRuntimeExports.jsx(LimitChip,{label:"7d",obs:cs}),jsxRuntimeExports.jsx(LimitChip,{label:"7d Opus",obs:Qr})]})]}),La&&jsxRuntimeExports.jsxs("div",{className:cn$1("space-y-1.5",ja&&"border-t border-border pt-3"),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-baseline justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Cost this month"}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-lg",children:[jsxRuntimeExports.jsx("span",{className:"mr-1 text-muted-foreground",children:"≈"}),formatUsd$1(Na??0)]})]}),Ba.length>0&&jsxRuntimeExports.jsx("div",{className:"space-y-1",children:Ba.slice(0,3).map(([Ja,Ya])=>{const el=Na&&Na>0?Math.round(Ya.cost_usd/Na*100):0;return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"truncate max-w-[60%] font-mono text-muted-foreground",children:Ja}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd$1(Ya.cost_usd)}),jsxRuntimeExports.jsxs("span",{className:"w-8 text-right text-muted-foreground",children:[el,"%"]})]})]},Ja)})})]})]})}function LimitChip({label:es,obs:$}){const ts=assessLimitWindow({usedPercentage:($==null?void 0:$.used_percentage)??null,resetsAt:($==null?void 0:$.resets_at)??null,now:new Date});return ts.kind!=="current"?jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[es," ",jsxRuntimeExports.jsx("span",{className:"opacity-60",children:"—"})]}):jsxRuntimeExports.jsxs("span",{children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:es})," ",jsxRuntimeExports.jsxs("span",{className:"font-semibold",children:[Math.round(ts.usedPercentage),"%"]})]})}function PlanDetection({caps:es}){var Oa,Ia;const $=useQueryClient(),[ts,is]=reactExports.useState(!1),[cs,Qr]=reactExports.useState(null),ja=useMutation({mutationFn:La=>apiPatch("/api/profile",{claudeCodePlan:La}),onError:()=>{Qr(null)},onSuccess:()=>{$.invalidateQueries({queryKey:["usage","inferred-caps"]}),$.invalidateQueries({queryKey:["profile"]}),is(!1)}});if(es.isLoading&&!es.data)return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin"}),"Detecting your plan…"]});const Na=((Oa=es.data)==null?void 0:Oa.plan)??"max_20x",Aa=((Ia=es.data)==null?void 0:Ia.assumed)??!0;return!Aa&&!ts?jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-lg border border-teal-500/30 bg-teal-500/5 px-4 py-3 text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Check,{className:"h-4 w-4 text-teal-400"}),"Detected your plan:"," ",jsxRuntimeExports.jsx("span",{className:"font-semibold",children:planLabel$1(Na)})]}),jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>is(!0),className:"text-xs text-primary underline-offset-2 hover:underline",children:"not right? change"})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-2 rounded-lg border border-border bg-background p-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[jsxRuntimeExports.jsx(Radar,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-medium",children:"Which Claude Code plan are you on?"})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Pick yours so your limits are accurate."}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-2 pt-1",role:"radiogroup","aria-label":"Claude Code plan",children:PLAN_OPTIONS.map(La=>{const Ba=cs===La.code||!Aa&&La.code===Na,Ma=ja.isPending&&ja.variables===La.code;return jsxRuntimeExports.jsxs(Button,{role:"radio","aria-checked":Ba,variant:Ba?"default":"outline",size:"sm",disabled:Ma,onClick:()=>{Qr(La.code),ja.mutate(La.code)},children:[Ma&&jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-1 h-3 w-3 animate-spin"}),Ba&&!Ma&&jsxRuntimeExports.jsx(Check,{className:"mr-1 h-3 w-3"}),La.label]},La.code)})}),ja.isError&&jsxRuntimeExports.jsx("p",{className:"text-xs text-destructive",role:"alert",children:"Couldn't save your plan — please try again."})]})}function LivesendEpilogue(){const{progress:es,goTo:$}=useSetupWalkthrough(),ts=useQueryClient(),is=es.steps.tmux,cs=es.steps.target,Qr=is.state==="detected"&&cs.state==="detected",ja=useMutation({mutationFn:()=>apiPatch("/api/profile",{liveSendSkipped:!0}),onSettled:()=>{ts.invalidateQueries({queryKey:["profile"]}),$("labeling")}});return jsxRuntimeExports.jsxs("div",{className:"space-y-5",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("h3",{className:"flex items-center gap-2 text-base font-semibold",children:[jsxRuntimeExports.jsx(Send,{className:"h-5 w-5 text-primary"}),"Control sessions from the browser?"]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Want to control sessions from the browser? This needs tmux. With it, RuleMetric can detect your running Claude Code sessions as live targets and send prompts to them straight from the dashboard — no terminal switching."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2 rounded-lg border border-border bg-background p-4",children:[jsxRuntimeExports.jsx(OptionalStepRow,{step:is}),jsxRuntimeExports.jsx(OptionalStepRow,{step:cs})]}),Qr?jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-2 text-sm text-teal-400",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0"}),"Live-send is ready — you can drive sessions from the dashboard."]}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsx(Button,{onClick:()=>$("labeling"),children:"Continue"})})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("div",{className:"flex items-center justify-end gap-2",children:jsxRuntimeExports.jsxs(Button,{onClick:()=>ja.mutate(),disabled:ja.isPending,children:[ja.isPending&&jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-1 h-3 w-3 animate-spin"}),"Skip for now"]})}),jsxRuntimeExports.jsxs("p",{className:"text-right text-xs text-muted-foreground",children:["You can enable this anytime from"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:"/connect"}),"."]})]})]})}function optionalIcon(es){switch(es){case"detected":return jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-teal-400"});case"loading":return jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 shrink-0 animate-spin text-muted-foreground"});default:return jsxRuntimeExports.jsx(Hourglass,{className:"h-4 w-4 shrink-0 text-muted-foreground"})}}function OptionalStepRow({step:es}){const $=es.state==="detected";return jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[optionalIcon(es.state),jsxRuntimeExports.jsx("span",{className:cn$1("text-sm font-medium truncate",$?"text-foreground":"text-muted-foreground"),children:es.label})]}),$?jsxRuntimeExports.jsx("span",{className:"shrink-0 text-xs text-teal-400",children:"Detected"}):jsxRuntimeExports.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:es.state==="loading"?"Checking…":`Waiting for ${es.waitingFor}`})]})}function LabelingEpilogue(){const{progress:es,goTo:$,dismiss:ts}=useSetupWalkthrough(),is=useNavigate(),cs=es.steps.judge;function Qr(){ts(),is("/eval-targets")}return jsxRuntimeExports.jsxs("div",{className:"space-y-5",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("h3",{className:"flex items-center gap-2 text-base font-semibold",children:[jsxRuntimeExports.jsx(ClipboardCheck,{className:"h-5 w-5 text-primary"}),'Teach the judge what "good" means']}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["RuleMetric grades your agent's outputs with an LLM judge — but only ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"your hand labels"})," can prove the judge is trustworthy. Review a few graded outputs (approve/reject, keyboard-fast) on any eval target's Review tab and you unlock calibrated verdicts. We'll notify you whenever outputs are waiting for review."]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2 rounded-lg border border-border bg-background p-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[stateIcon(cs.state),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium truncate",children:cs.label})]}),cs.state==="detected"?jsxRuntimeExports.jsx("span",{className:"shrink-0 text-xs text-teal-400",children:"Detected"}):jsxRuntimeExports.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:cs.state==="loading"?"Checking…":`Waiting for ${cs.waitingFor}`})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:cs.hint}),cs.state!=="detected"&&cs.command&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Recommended:"," ",jsxRuntimeExports.jsx("span",{className:"font-mono text-foreground",children:cs.command})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-end gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",onClick:()=>$("done"),children:"Skip for now"}),jsxRuntimeExports.jsx(Button,{onClick:Qr,children:"Show me labeling"})]}),jsxRuntimeExports.jsx("p",{className:"text-right text-xs text-muted-foreground",children:"The bell will remind you when graded outputs need review."})]})]})}function stateIcon(es){switch(es){case"detected":return jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-teal-400"});case"loading":return jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 shrink-0 animate-spin text-muted-foreground"});default:return jsxRuntimeExports.jsx(Hourglass,{className:"h-4 w-4 shrink-0 text-muted-foreground"})}}function SetupWalkthroughModal(){const{open:es,stage:$,authenticated:ts,dismiss:is,goTo:cs}=useSetupWalkthrough();return!ts||!es?null:jsxRuntimeExports.jsx(Dialog,{open:!0,onOpenChange:Qr=>{Qr||is()},children:jsxRuntimeExports.jsxs(DialogContent,{className:"sm:max-w-lg",children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsxs(DialogTitle,{className:"flex items-center gap-2 pr-6",children:[jsxRuntimeExports.jsx(Sparkles,{className:"h-4 w-4 text-primary"}),"Get set up with RuleMetric"]}),jsxRuntimeExports.jsx(DialogDescription,{children:"A quick walkthrough to connect Claude Code and start seeing your usage and cost."})]}),jsxRuntimeExports.jsx("div",{className:"py-2",children:jsxRuntimeExports.jsx(StageBody,{stage:$,onStart:()=>cs("core"),dismiss:is})}),$!=="done"&&jsxRuntimeExports.jsx(DialogFooter,{className:"sm:justify-between",children:jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:is,className:"text-muted-foreground",children:"I'll finish later"})})]})})}function StageBody({stage:es,onStart:$,dismiss:ts}){switch(es){case"welcome":return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"In a couple of minutes you'll have RuleMetric watching your Claude Code sessions — tracking real token usage, cost, and which instructions actually help."}),jsxRuntimeExports.jsx(Button,{onClick:$,className:"w-full sm:w-auto",children:"Let's get set up"})]});case"core":return jsxRuntimeExports.jsx(CoreSteps,{});case"payoff":return jsxRuntimeExports.jsx(Payoff,{});case"livesend":return jsxRuntimeExports.jsx(LivesendEpilogue,{});case"labeling":return jsxRuntimeExports.jsx(LabelingEpilogue,{});case"done":return jsxRuntimeExports.jsx(Done,{dismiss:ts})}}function Done({dismiss:es}){const $=useNavigate();function ts(){es(),$("/usage")}return jsxRuntimeExports.jsxs("div",{className:"space-y-5",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("h3",{className:"flex items-center gap-2 text-base font-semibold",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-5 w-5 text-teal-400"}),"You're all set ✓"]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"RuleMetric is capturing your Claude Code sessions — head to the usage page to watch your real token spend and cost roll in."})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-end gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",onClick:es,children:"Done"}),jsxRuntimeExports.jsx(Button,{onClick:ts,children:"View usage"})]})]})}function RootLayout({children:es}={}){return jsxRuntimeExports.jsx(SetupWalkthroughProvider,{children:jsxRuntimeExports.jsxs("div",{className:"flex h-screen",children:[jsxRuntimeExports.jsx(NotificationsListener,{}),jsxRuntimeExports.jsx(InsightsJobsListener,{}),jsxRuntimeExports.jsx(Sidebar,{className:"hidden md:flex"}),jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 flex-1 flex-col overflow-hidden",children:[jsxRuntimeExports.jsx(Header$1,{}),jsxRuntimeExports.jsx(AlertBanner,{}),jsxRuntimeExports.jsx(WorkerHealthBanner,{}),jsxRuntimeExports.jsx(CliUpdateBanner,{}),jsxRuntimeExports.jsx("main",{className:"min-w-0 flex-1 overflow-y-auto p-4 md:p-6",children:es??jsxRuntimeExports.jsx(Outlet,{})})]}),jsxRuntimeExports.jsx(SetupWalkthroughModal,{})]})})}const steps=[{icon:CircleDot,title:"Observe the baseline",text:"Session trends show where to investigate. They are observational signals, not proof that an instruction caused an outcome."},{icon:FlaskConical,title:"Hold the setup fixed",text:"Compare a prepared change using the same harness, model, tasks, and grading approach."},{icon:Gauge,title:"Inspect the tradeoffs",text:"Read quality alongside actor and grader cost, latency, sample size, uncertainty, and missing prices."},{icon:GitCompareArrows,title:"Keep what earns trust",text:"A small positive result is a reason to gather more evidence—not a guarantee that the change generalizes."}];function LandingPage(){return reactExports.useEffect(()=>{var es;document.title="Measure agent instruction changes | RuleMetric",(es=document.querySelector('meta[name="description"]'))==null||es.setAttribute("content","Compare prompt, rule, and memory changes inside the harnesses and models you already use.")},[]),jsxRuntimeExports.jsxs("div",{className:"min-h-screen bg-background text-foreground",children:[jsxRuntimeExports.jsx("nav",{className:"sticky top-0 z-50 border-b border-border bg-background/90 backdrop-blur",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto flex h-14 max-w-6xl items-center justify-between px-4",children:[jsxRuntimeExports.jsxs(Link,{to:"/",className:"font-mono text-sm font-semibold",children:[jsxRuntimeExports.jsx("span",{className:"mr-2 text-primary",children:"●"}),"RuleMetric"]}),jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-1 sm:gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",className:"hidden sm:inline-flex",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/login",children:"Sign in"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/signup",children:[jsxRuntimeExports.jsx("span",{className:"sm:hidden",children:"Start measuring"}),jsxRuntimeExports.jsx("span",{className:"hidden sm:inline",children:"Measure your first change"})]})})]})]})}),jsxRuntimeExports.jsxs("main",{children:[jsxRuntimeExports.jsx("section",{className:"px-4 py-24",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto grid max-w-6xl items-center gap-12 lg:grid-cols-[1.1fr_.9fr]",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h1",{className:"max-w-3xl text-4xl font-bold leading-tight lg:text-6xl",children:"Your agent instructions changed. Did your results improve?"}),jsxRuntimeExports.jsx("p",{className:"mt-6 max-w-2xl text-lg leading-8 text-muted-foreground",children:"RuleMetric measures prompt, rule, and memory changes inside the harnesses and models you already use. Compare quality, cost, and latency before deciding what to keep."}),jsxRuntimeExports.jsxs("div",{className:"mt-8 flex flex-wrap gap-3",children:[jsxRuntimeExports.jsx(Button,{size:"lg",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/signup",children:["Measure your first change",jsxRuntimeExports.jsx(ArrowRight,{className:"ml-2 h-4 w-4"})]})}),jsxRuntimeExports.jsx(Button,{size:"lg",variant:"outline",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/play/token-triage",children:"Play the instruction challenge"})})]})]}),jsxRuntimeExports.jsxs("aside",{className:"rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between border-b border-border pb-3 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"font-mono",children:"Evidence example"}),jsxRuntimeExports.jsx("span",{className:"rounded-full border border-primary/30 px-2 py-1 text-xs text-primary",children:"Illustrative"})]}),jsxRuntimeExports.jsxs("div",{className:"py-7",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Prepared variant versus baseline"}),jsxRuntimeExports.jsx("p",{className:"mt-2 font-mono text-3xl",children:"+4.2 quality points"}),jsxRuntimeExports.jsx("div",{className:"mt-5 h-2 rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-full w-[58%] rounded-full bg-primary"})})]}),jsxRuntimeExports.jsxs("dl",{className:"mt-5 grid grid-cols-2 gap-4 border-t border-border pt-4 text-sm",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{className:"text-muted-foreground",children:"Tasks"}),jsxRuntimeExports.jsx("dd",{className:"font-mono",children:"24 per variant"})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{className:"text-muted-foreground",children:"95% interval"}),jsxRuntimeExports.jsx("dd",{className:"font-mono",children:"−1.1 to +9.5"})]})]}),jsxRuntimeExports.jsx("p",{className:"mt-5 text-xs leading-5 text-muted-foreground",children:"Illustrative data, not a customer result. The interval crosses zero, so this example is insufficient evidence to call the change an improvement."})]})]})}),jsxRuntimeExports.jsx("section",{className:"border-y border-border bg-card/50 px-4 py-20",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl",children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-bold",children:"Instructions accumulate. Evidence should too."}),jsxRuntimeExports.jsx("p",{className:"mt-4 max-w-2xl text-muted-foreground",children:"Separate clues in normal sessions from controlled comparisons designed to answer whether a particular change helped."}),jsxRuntimeExports.jsx("div",{className:"mt-10 grid gap-px overflow-hidden rounded-lg border border-border bg-border md:grid-cols-2",children:steps.map(({icon:es,title:$,text:ts})=>jsxRuntimeExports.jsxs("article",{className:"bg-background p-7",children:[jsxRuntimeExports.jsx(es,{className:"h-5 w-5 text-primary"}),jsxRuntimeExports.jsx("h3",{className:"mt-5 text-lg font-semibold",children:$}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm leading-6 text-muted-foreground",children:ts})]},$))})]})}),jsxRuntimeExports.jsx("section",{className:"px-4 py-20",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto flex max-w-6xl flex-col justify-between gap-8 rounded-lg border border-border bg-card p-8 md:flex-row md:items-center",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold",children:"Does your agent memory actually help?"}),jsxRuntimeExports.jsx("p",{className:"mt-2 max-w-xl text-muted-foreground",children:"Presence, absence, and formatting are different questions. Learn how to frame a useful comparison."})]}),jsxRuntimeExports.jsx(Button,{variant:"outline",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/agent-memory",children:"Explore memory measurement"})})]})}),jsxRuntimeExports.jsx("section",{className:"border-t border-border px-4 py-20",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto grid max-w-6xl gap-10 md:grid-cols-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold",children:"Works with the harness you already run"}),jsxRuntimeExports.jsx("p",{className:"mt-4 leading-7 text-muted-foreground",children:"RuleMetric captures sessions from supported Claude Code, Cursor, and Copilot integrations. Controlled eval work can run through configured Claude, Codex, or Pi-compatible paths; support depends on the selected worker, provider, and workload."})]}),jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-semibold",children:"Start with the setup you can verify"}),jsxRuntimeExports.jsx("p",{className:"mt-3 text-sm leading-6 text-muted-foreground",children:"The setup guide documents hooks, proxy capture, workers, local mode, measurement costs, and current limitations."}),jsxRuntimeExports.jsxs("div",{className:"mt-5 flex flex-wrap gap-4 text-sm",children:[jsxRuntimeExports.jsx(Link,{className:"text-primary underline-offset-4 hover:underline",to:"/docs",children:"Read setup and support docs"}),jsxRuntimeExports.jsx(Link,{className:"text-primary underline-offset-4 hover:underline",to:"/login",children:"Sign in"})]})]})]})})]}),jsxRuntimeExports.jsx("footer",{className:"border-t border-border px-4 py-8",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto flex max-w-6xl justify-between text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{children:"RuleMetric"}),jsxRuntimeExports.jsx("span",{children:"Measure changes before you trust them."})]})})]})}function AgentMemoryPage(){return reactExports.useEffect(()=>{var es;document.title="Does your agent memory actually help? | RuleMetric",(es=document.querySelector('meta[name="description"]'))==null||es.setAttribute("content","Measure agent memory presence, absence, and prepared formatting variants with controlled comparisons.")},[]),jsxRuntimeExports.jsxs("div",{className:"min-h-screen bg-background text-foreground",children:[jsxRuntimeExports.jsx("header",{className:"border-b border-border",children:jsxRuntimeExports.jsxs("nav",{className:"mx-auto flex h-14 max-w-5xl items-center justify-between px-4",children:[jsxRuntimeExports.jsxs(Link,{to:"/",className:"font-mono font-semibold",children:[jsxRuntimeExports.jsx("span",{className:"mr-2 text-primary",children:"●"}),"RuleMetric"]}),jsxRuntimeExports.jsx(Link,{to:"/play/token-triage",className:"text-sm text-primary",children:"Play Token Triage"})]})}),jsxRuntimeExports.jsxs("main",{className:"mx-auto max-w-5xl px-4 py-16",children:[jsxRuntimeExports.jsx("h1",{className:"max-w-3xl text-4xl font-bold lg:text-5xl",children:"Does your agent memory actually help?"}),jsxRuntimeExports.jsx("p",{className:"mt-6 max-w-3xl text-lg leading-8 text-muted-foreground",children:"Memory being present is not the same as memory improving a task. Compare outcomes with the harness and model held fixed, then inspect quality, actor and grader cost, latency, and uncertainty together."}),jsxRuntimeExports.jsxs("div",{className:"mt-12 grid gap-5 md:grid-cols-3",children:[jsxRuntimeExports.jsxs("article",{className:"rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsx("h2",{className:"text-lg font-semibold",children:"Presence versus absence"}),jsxRuntimeExports.jsx("p",{className:"mt-3 text-sm leading-6 text-muted-foreground",children:"Prepare tasks that reveal whether memory adds useful context. Session trends can suggest a question, but controlled trials provide stronger evidence."})]}),jsxRuntimeExports.jsxs("article",{className:"rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsx("h2",{className:"text-lg font-semibold",children:"Formatting experiments"}),jsxRuntimeExports.jsx("p",{className:"mt-3 text-sm leading-6 text-muted-foreground",children:"Prepare each formatting variant yourself, then compare it under the same setup. RuleMetric does not automatically invent arbitrary A/B formats."})]}),jsxRuntimeExports.jsxs("article",{className:"rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsx("h2",{className:"text-lg font-semibold",children:"Insufficient evidence"}),jsxRuntimeExports.jsx("p",{className:"mt-3 text-sm leading-6 text-muted-foreground",children:"Missing prices, wide intervals, few tasks, or conflicting metrics should stay visible. A small positive result is not proof."})]})]}),jsxRuntimeExports.jsxs("section",{className:"mt-12 rounded-lg border border-primary/30 bg-primary/5 p-7",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-semibold",children:"Optimize instructions and harnesses—not model weights."}),jsxRuntimeExports.jsx("p",{className:"mt-3 max-w-3xl text-muted-foreground",children:"Background trials are bounded and require configured eval targets, compatible workers, and enablement. They are not free and do not guarantee an improvement."}),jsxRuntimeExports.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/signup",children:"Measure your first change"})}),jsxRuntimeExports.jsx(Button,{variant:"outline",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/docs",children:"Read measurement documentation"})})]})]})]})]})}function ChecklistCapture(){const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(!1),[cs,Qr]=reactExports.useState("idle"),[ja,Na]=reactExports.useState("");async function Aa(Oa){Oa==null||Oa.preventDefault(),Qr("loading"),Na("");try{const Ia=await fetch("/api/marketing/leads",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({email:es,marketingConsent:ts,source:"token-triage"})}),La=await Ia.json();if(!Ia.ok)throw new Error(La.error||"The request could not be saved. Try again.");Qr("success")}catch(Ia){Na(Ia instanceof Error?Ia.message:"The request could not be saved. Try again."),Qr("error")}}return cs==="success"?jsxRuntimeExports.jsxs("section",{className:"min-w-0 rounded-lg border border-primary/30 bg-primary/5 p-6","aria-live":"polite",children:[jsxRuntimeExports.jsx("h2",{className:"text-xl font-semibold",children:"Your checklist is ready"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Open it now and use it with any instruction file."}),jsxRuntimeExports.jsx(Button,{asChild:!0,className:"mt-4",children:jsxRuntimeExports.jsx(Link,{to:"/instruction-audit",children:"Open the checklist"})})]}):jsxRuntimeExports.jsxs("section",{className:"min-w-0 rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsx("h2",{className:"text-xl font-semibold",children:"Get the instruction-audit checklist"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"The checklist is available immediately. Email is used to record this request."}),jsxRuntimeExports.jsxs("form",{className:"mt-5 space-y-4",onSubmit:Aa,children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("label",{htmlFor:"checklist-email",className:"mb-1 block text-sm",children:"Email"}),jsxRuntimeExports.jsx("input",{id:"checklist-email",required:!0,type:"email",value:es,onChange:Oa=>$(Oa.target.value),className:"w-full rounded-md border border-input bg-background px-3 py-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),jsxRuntimeExports.jsxs("label",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("input",{type:"checkbox",className:"mt-1",checked:ts,onChange:Oa=>is(Oa.target.checked)}),jsxRuntimeExports.jsx("span",{children:"Send me occasional RuleMetric product updates. Optional."})]}),cs==="error"&&jsxRuntimeExports.jsx("div",{role:"alert",className:"text-sm text-destructive",children:ja}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:cs==="loading",children:cs==="loading"?"Requesting…":cs==="error"?"Retry":"Get the checklist"})]}),jsxRuntimeExports.jsx(Link,{className:"mt-4 inline-block text-sm text-primary underline-offset-4 hover:underline",to:"/instruction-audit",children:"Skip the form and open the checklist"})]})}const GAME_VERSION=1,STORAGE_KEY="rulemetric:token-triage:v1",scenarios=[{task:"Return a JSON object with the answer and cite the source line.",budget:200,cards:[{id:"tone",title:"Friendly voice",text:"Use a warm, conversational tone.",tokens:44,compressedTokens:18,compressedText:"Be friendly."},{id:"format",title:"Output contract",text:"Return valid JSON with answer and source_line keys.",tokens:32,compressedTokens:13,compressedText:"Return JSON with the answer.",required:!0,compressionLoses:!0},{id:"scope",title:"Evidence boundary",text:"Use only the supplied file and cite its exact line.",tokens:40,compressedTokens:17,compressedText:"Use supplied evidence; cite line.",required:!0}]},{task:"Fix the defect without changing the public API.",budget:82,cards:[{id:"tone",title:"Narrate first",text:"Explain your entire thought process before editing.",tokens:38,compressedTokens:14,compressedText:"Explain first."},{id:"format",title:"Compatibility",text:"Preserve exported names and argument shapes.",tokens:42,compressedTokens:17,compressedText:"Keep the public API.",required:!0},{id:"scope",title:"Verification",text:"Run the focused regression test after the edit.",tokens:35,compressedTokens:15,compressedText:"Run focused test.",required:!0}]},{task:"Summarize a customer incident without exposing personal data.",budget:74,cards:[{id:"tone",title:"Decorative opener",text:"Begin with an imaginative metaphor.",tokens:31,compressedTokens:12,compressedText:"Use a metaphor."},{id:"format",title:"Privacy rule",text:"Remove names, emails, tokens, and account identifiers.",tokens:39,compressedTokens:16,compressedText:"Remove names and emails.",required:!0,compressionLoses:!0},{id:"scope",title:"Incident shape",text:"State impact, timeline, cause, and follow-up.",tokens:34,compressedTokens:14,compressedText:"Give incident essentials.",required:!0}]},{task:"Review a migration and report only release-blocking risks.",budget:66,cards:[{id:"tone",title:"Praise the author",text:"Open with two sentences of encouragement.",tokens:29,compressedTokens:10,compressedText:"Be encouraging."},{id:"format",title:"Severity filter",text:"Report only data-loss, outage, or rollback blockers.",tokens:36,compressedTokens:15,compressedText:"Only release blockers.",required:!0},{id:"scope",title:"Evidence",text:"Give the affected statement and concrete failure mode.",tokens:37,compressedTokens:16,compressedText:"Cite statement and failure.",required:!0}]},{task:"Prepare a safe deployment decision from incomplete evidence.",budget:58,cards:[{id:"tone",title:"Sound confident",text:"Avoid uncertain language and make a firm claim.",tokens:27,compressedTokens:9,compressedText:"Be confident."},{id:"format",title:"Decision gate",text:"Return go only when tests and rollback checks pass.",tokens:34,compressedTokens:14,compressedText:"Return go when checks pass.",required:!0,compressionLoses:!0},{id:"scope",title:"Unknowns",text:"List missing evidence and return no-go when unresolved.",tokens:33,compressedTokens:13,compressedText:"Unknowns mean no-go.",required:!0}]}];function utcDailySeed(es=new Date){return es.toISOString().slice(0,10)}function getChallengeId(es=utcDailySeed()){return`v${GAME_VERSION}-${es}`}function scenarioForRound(es,$){const ts=Math.max(0,Math.min(scenarios.length-1,$)),is=[...es].reduce((ja,Na)=>ja*31+Na.charCodeAt(0)>>>0,0),cs=scenarios[ts].cards.map(ja=>({...ja})),Qr=is%cs.length;return{...scenarios[ts],id:`${es}-r${$+1}`,cards:[...cs.slice(Qr),...cs.slice(0,Qr)]}}function createGame(es=utcDailySeed()){return{version:GAME_VERSION,challengeId:getChallengeId(es),round:0,completedRounds:0,failures:0,score:0,status:"playing",lastResult:null}}function restartGame(es){const $=es.challengeId.replace(/^v\d+-/,"");return createGame($)}function applyRound(es,$){if(es.status!=="playing")return es;const ts=scenarioForRound(es.challengeId,es.round),is=ts.cards.reduce((Ha,Ka)=>{const Ga=$[Ka.id]??"discard";return Ha+(Ga==="keep"?Ka.tokens:Ga==="compress"?Ka.compressedTokens:0)},0),cs=ts.cards.filter(Ha=>Ha.required),Qr=cs.filter(Ha=>{const Ka=$[Ha.id]??"discard";return Ka==="discard"||Ka==="compress"&&Ha.compressionLoses}),ja=Qr.length===0,Na=is<=ts.budget,Aa=ja&&Na,Oa=Aa?Math.max(1,Math.min(200,ts.budget-is)):0,Ia=es.failures+(Aa?0:1),La=es.completedRounds+1,Ba=Ia>=2?"failed":La>=5?"complete":"playing",Ma=cs.map(Ha=>Ha.title).join(" and "),qa=Qr.map(Ha=>($[Ha.id]??"discard")==="compress"?`${Ha.title} became “${Ha.compressedText}” and lost the required detail “${Ha.text}”`:`${Ha.title} was discarded, removing “${Ha.text}”`).join("; "),Fa=Aa?`${Ma} protected the task with ${ts.budget-is} tokens to spare.`:ja?`${Ma} protected the requirements, but the context used ${is} tokens—${is-ts.budget} above the ${ts.budget}-token budget.`:`${qa}.`;return{...es,round:Math.min(4,es.round+1),completedRounds:La,failures:Ia,score:es.score+Oa,status:Ba,lastResult:{passed:Aa,score:Oa,usedTokens:is,explanation:Fa}}}function loadGame(es,$=utcDailySeed()){var is,cs,Qr,ja,Na,Aa,Oa;const ts=createGame($);if(!es)return ts;try{const Ia=JSON.parse(es),La=Ia.lastResult===null||typeof Ia.lastResult=="object"&&typeof Ia.lastResult.passed=="boolean"&&Number.isInteger(Ia.lastResult.score)&&Ia.lastResult.score>=0&&Ia.lastResult.score<=200&&Number.isInteger(Ia.lastResult.usedTokens)&&Ia.lastResult.usedTokens>=0&&Ia.lastResult.usedTokens<=1e3&&typeof Ia.lastResult.explanation=="string"&&Ia.lastResult.explanation.length>0&&Ia.lastResult.explanation.length<=1e3&&(Ia.lastResult.passed?Ia.lastResult.score>0:Ia.lastResult.score===0);if(Ia.version!==GAME_VERSION||Ia.challengeId!==ts.challengeId||!Number.isInteger(Ia.round)||!Number.isInteger(Ia.failures)||!Number.isInteger(Ia.completedRounds)||typeof Ia.score!="number"||!Number.isInteger(Ia.score)||Ia.score<0||Ia.score>1e3||!["playing","failed","complete"].includes(Ia.status??"")||!La)return ts;const Ba=Ia.completedRounds-Ia.failures,Ma=scenarioForRound(ts.challengeId,Math.max(0,Ia.completedRounds-1)),qa=(is=Ia.lastResult)!=null&&is.passed?Math.max(1,Math.min(200,Ma.budget-Ia.lastResult.usedTokens)):0;return(Ia.round??-1)<0||(Ia.round??6)>4||(Ia.failures??-1)<0||(Ia.failures??3)>2||(Ia.completedRounds??-1)<0||(Ia.completedRounds??6)>5||Ia.round!==Math.min(Ia.completedRounds??-1,4)||(Ia.failures??3)>(Ia.completedRounds??-1)||Ia.score>(Ia.completedRounds??0)*200||Ia.score>Ba*200||Ia.score<(((cs=Ia.lastResult)==null?void 0:cs.score)??0)||Ia.completedRounds===1&&Ia.score!==((Qr=Ia.lastResult)==null?void 0:Qr.score)||((ja=Ia.lastResult)==null?void 0:ja.passed)===!1&&Ia.failures===0||Ia.failures===0&&Ia.completedRounds>0&&((Na=Ia.lastResult)==null?void 0:Na.passed)!==!0||((Aa=Ia.lastResult)==null?void 0:Aa.passed)===!0&&Ia.lastResult.usedTokens>Ma.budget||Ia.lastResult!==null&&((Oa=Ia.lastResult)==null?void 0:Oa.score)!==qa||(Ia.completedRounds===0?Ia.lastResult!==null:Ia.lastResult==null)||Ia.status!==((Ia.failures??0)>=2?"failed":(Ia.completedRounds??0)>=5?"complete":"playing")?ts:{...ts,...Ia}}catch{return ts}}function Header(){return jsxRuntimeExports.jsx("header",{className:"border-b border-border",children:jsxRuntimeExports.jsxs("nav",{"aria-label":"Public",className:"mx-auto flex h-14 max-w-6xl items-center justify-between px-4",children:[jsxRuntimeExports.jsxs(Link,{to:"/",className:"font-mono font-semibold",children:[jsxRuntimeExports.jsx("span",{className:"mr-2 text-primary",children:"●"}),"RuleMetric"]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-4 text-sm",children:[jsxRuntimeExports.jsx(Link,{to:"/agent-memory",children:"Agent memory"}),jsxRuntimeExports.jsx(Link,{to:"/signup",className:"text-primary",children:"Sign up"})]})]})})}function TokenTriagePage(){const[es,$]=reactExports.useState(()=>{const Ka=typeof location>"u"?null:new URLSearchParams(location.search).get("challenge"),Ga=Ka==null?void 0:Ka.match(/^v1-(\d{4}-\d{2}-\d{2})$/);if(Ga)return createGame(Ga[1]);try{return typeof localStorage>"u"?createGame():loadGame(localStorage.getItem(STORAGE_KEY))}catch{return createGame()}}),[ts,is]=reactExports.useState({}),[cs,Qr]=reactExports.useState(!1),[ja,Na]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(""),Ia=reactExports.useMemo(()=>scenarioForRound(es.challengeId,es.round),[es.challengeId,es.round]),La=Ia.cards.reduce((Ka,Ga)=>Ka+(ts[Ga.id]==="keep"?Ga.tokens:ts[Ga.id]==="compress"?Ga.compressedTokens:0),0);reactExports.useEffect(()=>{var Ka;document.title="Token Triage | RuleMetric",(Ka=document.querySelector('meta[name="description"]'))==null||Ka.setAttribute("content","A simulated instruction challenge: protect task requirements while working within a context budget.")},[]),reactExports.useEffect(()=>{try{localStorage.setItem(STORAGE_KEY,JSON.stringify(es))}catch{}},[es]);function Ba(Ka,Ga){is(Va=>({...Va,[Ka]:Ga}))}function Ma(){$(Ka=>applyRound(Ka,ts)),Qr(!0)}function qa(){is({}),Qr(!1)}function Fa(){$(Ka=>restartGame(Ka)),is({}),Qr(!1)}async function Ha(){Na(""),Oa("");const Ka=`${location.origin}/play/token-triage?challenge=${encodeURIComponent(es.challengeId)}`,Ga=`I scored ${es.score} in Token Triage. Beat the same simulated challenge: ${Ka}`;try{typeof navigator.share=="function"?await navigator.share({title:"Token Triage",text:Ga,url:Ka}):await navigator.clipboard.writeText(Ga),Na(typeof navigator.share=="function"?"Challenge shared.":"Challenge copied.")}catch(Va){(Va==null?void 0:Va.name)!=="AbortError"&&(Na("Sharing is unavailable. Copy this challenge link manually:"),Oa(Ka))}}return jsxRuntimeExports.jsxs("div",{className:"min-h-screen bg-background text-foreground",children:[jsxRuntimeExports.jsx(Header,{}),jsxRuntimeExports.jsxs("main",{className:"mx-auto max-w-4xl px-4 py-12",children:[jsxRuntimeExports.jsxs("div",{className:"mb-8 flex flex-wrap items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-primary",children:"Simulated challenge · no live model calls"}),jsxRuntimeExports.jsx("h1",{className:"mt-2 text-4xl font-bold",children:"Token Triage"}),jsxRuntimeExports.jsx("p",{className:"mt-3 max-w-2xl text-muted-foreground",children:"Keep task-critical meaning while spending less of the context window. Compression is useful—until it deletes the detail that makes an instruction work."})]}),jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border bg-card px-4 py-3 font-mono text-sm",children:["Round ",Math.min(es.completedRounds+1,5)," / 5",jsxRuntimeExports.jsx("br",{}),"Score ",es.score," · Strikes ",es.failures,"/2"]})]}),cs&&es.lastResult?jsxRuntimeExports.jsxs("section",{className:`rounded-lg border p-6 ${es.lastResult.passed?"border-primary/40 bg-primary/5":"border-destructive/40 bg-destructive/5"}`,children:[jsxRuntimeExports.jsxs("p",{role:"status",className:"font-semibold",children:[es.lastResult.passed?"Task protected.":"Regression introduced."," ",es.lastResult.explanation]}),jsxRuntimeExports.jsxs("p",{className:"mt-2 text-sm text-muted-foreground",children:["Round score: ",es.lastResult.score,". Correctness is evaluated before efficiency."]}),jsxRuntimeExports.jsx(Button,{className:"mt-4",onClick:qa,children:es.status==="playing"?"Next round":"See final result"})]}):es.status!=="playing"?jsxRuntimeExports.jsxs("section",{className:"rounded-lg border border-border bg-card p-8 text-center",children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-bold",children:es.status==="failed"?"Run ended":"Five rounds complete"}),jsxRuntimeExports.jsxs("p",{className:"mt-3 text-muted-foreground",children:["Final simulated score: ",es.score,". Game results are not evidence about a real harness."]}),jsxRuntimeExports.jsxs("div",{className:"mt-6 flex justify-center gap-3",children:[jsxRuntimeExports.jsx(Button,{onClick:Fa,children:"Restart"}),jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:Ha,children:"Share challenge"})]}),jsxRuntimeExports.jsxs("p",{role:"status",className:"mt-3 text-sm",children:[ja,Aa&&jsxRuntimeExports.jsx("a",{"aria-label":"Copy this challenge link manually",className:"mt-2 block break-all text-primary underline underline-offset-4",href:Aa,children:Aa})]})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("section",{className:"rounded-lg border border-border bg-card p-6",children:[jsxRuntimeExports.jsx("h2",{className:"text-xl font-semibold",children:Ia.task}),jsxRuntimeExports.jsxs("div",{className:"mt-5",children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex justify-between font-mono text-sm",children:[jsxRuntimeExports.jsx("span",{children:"Context meter"}),jsxRuntimeExports.jsxs("span",{children:[La," / ",Ia.budget," tokens"]})]}),jsxRuntimeExports.jsx("div",{className:"h-3 overflow-hidden rounded-full bg-muted",role:"meter","aria-label":"Context used","aria-valuemin":0,"aria-valuemax":Ia.budget,"aria-valuenow":Math.min(La,Ia.budget),"aria-valuetext":`${La} of ${Ia.budget} tokens${La>Ia.budget?`, ${La-Ia.budget} over budget`:""}`,children:jsxRuntimeExports.jsx("div",{className:`h-full transition-[width] motion-reduce:transition-none ${La>Ia.budget?"bg-destructive":"bg-primary"}`,style:{width:`${Math.min(100,La/Ia.budget*100)}%`}})})]})]}),jsxRuntimeExports.jsxs("div",{className:"mt-5 space-y-4",children:[Ia.cards.map(Ka=>jsxRuntimeExports.jsxs("fieldset",{className:"rounded-lg border border-border bg-card p-5",children:[jsxRuntimeExports.jsx("legend",{className:"px-1 font-mono font-semibold",children:Ka.title}),jsxRuntimeExports.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:Ka.text}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-3 gap-2",children:["keep","compress","discard"].map(Ga=>jsxRuntimeExports.jsxs("label",{className:`rounded-md border p-3 text-center text-sm capitalize focus-within:ring-2 focus-within:ring-ring ${ts[Ka.id]===Ga?"border-primary bg-primary/10":"border-border"}`,children:[jsxRuntimeExports.jsx("input",{className:"sr-only",type:"radio",name:Ka.id,"aria-label":`${Ga} ${Ka.title}`,checked:ts[Ka.id]===Ga,onChange:()=>Ba(Ka.id,Ga)}),Ga,jsxRuntimeExports.jsxs("span",{className:"block text-xs text-muted-foreground",children:[Ga==="keep"?Ka.tokens:Ga==="compress"?Ka.compressedTokens:0," ","tokens"]}),Ga==="compress"&&jsxRuntimeExports.jsxs("span",{className:"mt-1 block text-[11px] normal-case text-muted-foreground",children:["“",Ka.compressedText,"”"]})]},Ga))})]},Ka.id)),jsxRuntimeExports.jsx(Button,{className:"w-full",disabled:Ia.cards.some(Ka=>!ts[Ka.id]),onClick:Ma,children:"Run instruction set"})]})]}),es.status!=="playing"&&!cs&&jsxRuntimeExports.jsxs("div",{className:"mt-10 grid min-w-0 gap-6 md:grid-cols-2",children:[jsxRuntimeExports.jsx("div",{className:"min-w-0",children:jsxRuntimeExports.jsx(ChecklistCapture,{})}),jsxRuntimeExports.jsxs("section",{className:"min-w-0 rounded-lg border border-border p-6",children:[jsxRuntimeExports.jsx("h2",{className:"text-xl font-semibold",children:"That was a simulation."}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"Test your real instructions with the harness and model held fixed."}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"mt-4 h-auto max-w-full whitespace-normal text-center",children:jsxRuntimeExports.jsx(Link,{to:"/signup",children:"Test real instructions with RuleMetric"})})]})]})]})]})}const checks=["Name the task outcome the instruction should change.","Record the harness, model, task set, grader, and versions.","Prepare one change at a time when practical.","Track quality, actor cost, grader cost, latency, and missing prices.","Keep observational trends separate from controlled trial evidence.","Check sample size and uncertainty before calling a winner.","Document failure modes and preserve a rollback path.","Repeat on representative tasks before generalizing."];function InstructionAuditPage(){return reactExports.useEffect(()=>{var es;document.title="Instruction-audit checklist | RuleMetric",(es=document.querySelector('meta[name="description"]'))==null||es.setAttribute("content","A practical checklist for evaluating agent instruction changes with evidence.")},[]),jsxRuntimeExports.jsx("div",{className:"min-h-screen bg-background text-foreground",children:jsxRuntimeExports.jsxs("main",{className:"mx-auto max-w-3xl px-4 py-16",children:[jsxRuntimeExports.jsx(Link,{to:"/",className:"font-mono text-sm text-primary",children:"← RuleMetric"}),jsxRuntimeExports.jsx("p",{className:"mt-12 text-sm text-primary",children:"Accessible now · no email required"}),jsxRuntimeExports.jsx("h1",{className:"mt-2 text-4xl font-bold",children:"Instruction-audit checklist"}),jsxRuntimeExports.jsx("p",{className:"mt-4 text-muted-foreground",children:"Use this before deciding that a prompt, rule, or memory change improved your agent."}),jsxRuntimeExports.jsx("ol",{className:"mt-10 space-y-3",children:checks.map((es,$)=>jsxRuntimeExports.jsxs("li",{className:"flex gap-4 rounded-lg border border-border bg-card p-4",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-primary",children:$+1}),jsxRuntimeExports.jsx("span",{children:es})]},es))}),jsxRuntimeExports.jsx("p",{className:"mt-8 text-sm text-muted-foreground",children:"This checklist structures an evaluation; it does not turn a simulated score or a small positive result into proof."})]})})}const REDIRECT_DECISION_TIMEOUT_MS=2500;async function getPostAuthRedirect(){try{return(await api("/api/sessions?summary=exists",{timeoutMs:REDIRECT_DECISION_TIMEOUT_MS})).exists?"/sessions":"/connect"}catch{return"/sessions"}}function useSocialAuthProviders(){const[es,$]=reactExports.useState([]),[ts,is]=reactExports.useState(!0);return reactExports.useEffect(()=>{const cs=new AbortController;return fetchEnabledSocialAuthProviders(cs.signal).then($).finally(()=>{cs.signal.aborted||is(!1)}),()=>cs.abort()},[]),{providers:es,loading:ts}}function GoogleIcon(){return jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24","aria-hidden":"true",className:"h-4 w-4",children:[jsxRuntimeExports.jsx("path",{fill:"currentColor",d:"M21.6 12.2c0-.7-.1-1.4-.2-2.1H12v4h5.4a4.6 4.6 0 0 1-2 3v2.6h3.3c1.9-1.8 2.9-4.4 2.9-7.5Z"}),jsxRuntimeExports.jsx("path",{fill:"currentColor",d:"M12 22c2.7 0 5-.9 6.7-2.3l-3.3-2.6c-.9.6-2.1 1-3.4 1a5.9 5.9 0 0 1-5.5-4.1H3.1v2.7A10 10 0 0 0 12 22Z",opacity:".8"}),jsxRuntimeExports.jsx("path",{fill:"currentColor",d:"M6.5 14a6 6 0 0 1 0-3.9V7.4H3.1a10 10 0 0 0 0 9.3L6.5 14Z",opacity:".6"}),jsxRuntimeExports.jsx("path",{fill:"currentColor",d:"M12 6.1c1.5 0 2.8.5 3.9 1.5l2.9-2.9A9.8 9.8 0 0 0 3.1 7.4l3.4 2.7A5.9 5.9 0 0 1 12 6.1Z",opacity:".9"})]})}function OAuthButtons({next:es}){const{signInWithProvider:$}=useAuth(),{providers:ts,loading:is}=useSocialAuthProviders(),[cs,Qr]=reactExports.useState(null),[ja,Na]=reactExports.useState(null);if(is)return jsxRuntimeExports.jsx("div",{className:"h-20 animate-pulse rounded-md bg-muted/40","aria-label":"Loading social sign-in options"});if(ts.length===0)return null;async function Aa(Oa){Na(null),Qr(Oa);try{await $(Oa,es)}catch(Ia){Na(Ia instanceof Error?Ia.message:"Social sign-in failed"),Qr(null)}}return jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"relative py-1",children:[jsxRuntimeExports.jsx("div",{className:"absolute inset-0 flex items-center","aria-hidden":"true",children:jsxRuntimeExports.jsx("div",{className:"w-full border-t border-border"})}),jsxRuntimeExports.jsx("div",{className:"relative flex justify-center",children:jsxRuntimeExports.jsx("span",{className:"bg-card px-2 text-xs text-muted-foreground",children:"or continue with"})})]}),ja&&jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm text-destructive",children:ja}),jsxRuntimeExports.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:SOCIAL_AUTH_PROVIDERS.filter(({id:Oa})=>ts.includes(Oa)).map(({id:Oa,label:Ia})=>jsxRuntimeExports.jsxs(Button,{type:"button",variant:"outline",disabled:cs!==null,onClick:()=>void Aa(Oa),"aria-label":`Continue with ${Ia}`,children:[Oa==="github"?jsxRuntimeExports.jsx(Github,{className:"h-4 w-4"}):jsxRuntimeExports.jsx(GoogleIcon,{}),cs===Oa?"Redirecting...":Ia]},Oa))})]})}function Input({className:es,type:$,...ts}){return jsxRuntimeExports.jsx("input",{type:$,"data-slot":"input",className:cn$1("file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm","focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]","aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",es),...ts})}function Label({className:es,...$}){return jsxRuntimeExports.jsx(Root$3,{"data-slot":"label",className:cn$1("flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",es),...$})}function LoginPage(){const{signIn:es}=useAuth(),$=useNavigate(),[ts]=useSearchParams(),[is,cs]=reactExports.useState(""),[Qr,ja]=reactExports.useState(""),[Na,Aa]=reactExports.useState(""),[Oa,Ia]=reactExports.useState(!1);async function La(qa){qa.preventDefault(),Aa(""),Ia(!0);try{await es(is,Qr);const Fa=safeNext(ts.get("next"));if(Fa){$(Fa,{replace:!0});return}const Ha=await getPostAuthRedirect();$(Ha)}catch(Fa){Aa(Fa instanceof Error?Fa.message:"Login failed")}finally{Ia(!1)}}const Ba=safeNext(ts.get("next")),Ma=Ba?`/signup?next=${encodeURIComponent(Ba)}`:"/signup";return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono mt-2",children:"Sign in"}),jsxRuntimeExports.jsx(CardDescription,{children:"Enter your credentials to continue"})]}),jsxRuntimeExports.jsxs("form",{onSubmit:La,children:[jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[Na&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:Na}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"email",type:"email",value:is,onChange:qa=>cs(qa.target.value),required:!0,autoComplete:"email",className:"bg-background border-border"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"password",children:"Password"}),jsxRuntimeExports.jsx(Link,{to:"/forgot-password",className:"text-sm font-medium text-muted-foreground hover:text-primary transition-colors",children:"Forgot password?"})]}),jsxRuntimeExports.jsx(Input,{id:"password",type:"password",value:Qr,onChange:qa=>ja(qa.target.value),required:!0,autoComplete:"current-password",className:"bg-background border-border"})]})]}),jsxRuntimeExports.jsxs(CardFooter,{className:"flex flex-col gap-3",children:[jsxRuntimeExports.jsx(Button,{type:"submit",className:"w-full cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90 mt-8",disabled:Oa,children:Oa?"Signing in...":"Sign in"}),jsxRuntimeExports.jsx(OAuthButtons,{next:Ba}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Don't have an account?"," ",jsxRuntimeExports.jsx(Link,{to:Ma,className:"text-primary underline",children:"Sign up"})]})]})]})]})})}function SignupPage(){const{signUp:es}=useAuth(),$=useNavigate(),[ts]=useSearchParams(),is=safeNext(ts.get("next")),cs=is?`/login?next=${encodeURIComponent(is)}`:"/login",[Qr,ja]=reactExports.useState(""),[Na,Aa]=reactExports.useState(""),[Oa,Ia]=reactExports.useState(""),[La,Ba]=reactExports.useState(""),[Ma,qa]=reactExports.useState(!1),[Fa,Ha]=reactExports.useState(!1),[Ka,Ga]=reactExports.useState(!1);async function Va(Ja){if(Ja.preventDefault(),Ba(""),qa(!1),Na!==Oa){Ba("Passwords do not match");return}if(Na.length<6){Ba("Password must be at least 6 characters");return}Ga(!0);try{const{needsConfirmation:Ya,alreadyRegistered:el}=await es(Qr,Na,is??void 0);if(el){qa(!0);return}if(Ya){Ha(!0);return}if(is){$(is,{replace:!0});return}const tl=await getPostAuthRedirect();$(tl,{replace:!0})}catch(Ya){Ba(Ya instanceof Error?Ya.message:"Signup failed")}finally{Ga(!1)}}return Fa?jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Check your email"}),jsxRuntimeExports.jsxs(CardDescription,{children:["We sent a confirmation link to ",jsxRuntimeExports.jsx("strong",{children:Qr}),". Click it to activate your account."]})]}),jsxRuntimeExports.jsx(CardFooter,{children:jsxRuntimeExports.jsx(Link,{to:cs,className:"text-primary underline text-sm",children:"Back to login"})})]})}):jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:"Sign up"}),jsxRuntimeExports.jsx(CardDescription,{children:"Create a new account"})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Va,children:[jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[La&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:La}),Ma&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border bg-muted/40 p-3 text-sm",children:[jsxRuntimeExports.jsx("p",{className:"text-foreground",children:"An account with this email already exists."}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-muted-foreground",children:[jsxRuntimeExports.jsx(Link,{to:cs,className:"text-primary underline",children:"Sign in"})," ","instead, or"," ",jsxRuntimeExports.jsx(Link,{to:"/forgot-password",className:"text-primary underline",children:"reset your password"})," ","if you've forgotten it."]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"email",type:"email",value:Qr,onChange:Ja=>ja(Ja.target.value),required:!0,autoComplete:"email",className:"bg-background border-border"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"password",children:"Password"}),jsxRuntimeExports.jsx(Input,{id:"password",type:"password",value:Na,onChange:Ja=>Aa(Ja.target.value),required:!0,minLength:6,autoComplete:"new-password",className:"bg-background border-border"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"confirm-password",children:"Confirm password"}),jsxRuntimeExports.jsx(Input,{id:"confirm-password",type:"password",value:Oa,onChange:Ja=>Ia(Ja.target.value),required:!0,autoComplete:"new-password",className:"bg-background border-border"})]})]}),jsxRuntimeExports.jsxs(CardFooter,{className:"flex flex-col gap-3",children:[jsxRuntimeExports.jsx(Button,{type:"submit",className:"w-full cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",disabled:Ka,children:Ka?"Creating account...":"Sign up"}),jsxRuntimeExports.jsx(OAuthButtons,{next:is}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Already have an account?"," ",jsxRuntimeExports.jsx(Link,{to:cs,className:"text-primary underline",children:"Sign in"})]})]})]})]})})}function ConfirmPage(){const es=useNavigate(),[$]=useSearchParams(),{session:ts,loading:is}=useAuth(),[cs,Qr]=reactExports.useState(null);return reactExports.useEffect(()=>{const ja=oauthCallbackError(window.location.hash);if(ja){Qr(ja);return}if(is)return;if(ts){const Aa=window.location.hash;if(Aa.includes("type=recovery")||Aa.includes("type=invite")){es("/reset-password",{replace:!0});return}const Oa=safeNext($.get("next"));Oa?es(Oa,{replace:!0}):getPostAuthRedirect().then(Ia=>{es(Ia,{replace:!0})});return}const Na=window.location.hash;(!Na||!Na.includes("access_token"))&&Qr("Invalid confirmation link")},[ts,is,es,$]),jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),cs?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Confirmation failed"}),jsxRuntimeExports.jsx(CardDescription,{children:cs})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Confirming..."}),jsxRuntimeExports.jsx(CardDescription,{children:"Verifying your email address"})]})]}),cs&&jsxRuntimeExports.jsxs(CardContent,{className:"flex gap-4 text-sm",children:[jsxRuntimeExports.jsx(Link,{className:"text-primary hover:underline",to:"/login",children:"Try signing in again"}),jsxRuntimeExports.jsx(Link,{className:"text-muted-foreground hover:underline",to:"/signup",children:"Create an account"})]})]})})}const ALLOWED_EDITOR_SCHEMES=new Set(["vscode","vscode-insiders","cursor","windsurf"]),ALLOWED_EXTENSION_IDS=new Set(["rulemetric.rulemetric-vscode"]),mintedNonces=new Set;function ExtensionAuthPage(){const{session:es,loading:$}=useAuth(),[ts]=useSearchParams(),is=ts.get("editor")??"",cs=ts.get("extension_id")??"",Qr=ts.get("nonce")??"",[ja,Na]=reactExports.useState(null),[Aa,Oa]=reactExports.useState(!1),[Ia,La]=reactExports.useState(null),Ba=ALLOWED_EDITOR_SCHEMES.has(is)&&ALLOWED_EXTENSION_IDS.has(cs)&&/^[A-Za-z0-9_-]{8,128}$/.test(Qr);if(reactExports.useEffect(()=>{var Ma;if(!$&&es){if(!Ba){Na("Invalid sign-in request — missing or malformed editor/extension/nonce parameters.");return}mintedNonces.has(Qr)||(mintedNonces.add(Qr),apiPost("/api/auth/extension/code",{email:((Ma=es.user)==null?void 0:Ma.email)??null,editor:is}).then(({code:qa})=>{const Fa=`${is}://${cs}/auth?nonce=${encodeURIComponent(Qr)}&code=${encodeURIComponent(qa)}`;La(Fa),window.location.href=Fa,Oa(!0)}).catch(qa=>{mintedNonces.delete(Qr),Na(qa instanceof Error?qa.message:"Failed to mint auth code")}))}},[$,es,is,cs,Qr,Ba]),$)return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center",children:jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Loading…"})});if(!es){const Ma=ts.toString(),qa=`/auth/extension${Ma?`?${Ma}`:""}`;return jsxRuntimeExports.jsx(Navigate,{to:`/login?next=${encodeURIComponent(qa)}`,replace:!0})}return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-md border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{children:"Connecting to your editor…"}),jsxRuntimeExports.jsx(CardDescription,{children:ja?"Something went wrong":Aa?"We've handed off to your editor. You can close this tab.":"Generating a one-time sign-in code."})]}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:ja?jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:ja}):Aa&&Ia?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"If your editor didn't open automatically, click below."}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"default",children:jsxRuntimeExports.jsx("a",{href:Ia,children:"Open in editor"})})]}):null})]})})}function ForgotPasswordPage(){const{resetPassword:es}=useAuth(),[$,ts]=reactExports.useState(""),[is,cs]=reactExports.useState(""),[Qr,ja]=reactExports.useState(!1),[Na,Aa]=reactExports.useState(!1);async function Oa(Ia){Ia.preventDefault(),cs(""),Aa(!0);try{await es($),ja(!0)}catch(La){cs(La instanceof Error?La.message:"Failed to send reset email")}finally{Aa(!1)}}return Qr?jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Check your email"}),jsxRuntimeExports.jsxs(CardDescription,{children:["We sent a password reset link to ",jsxRuntimeExports.jsx("strong",{children:$}),"."]})]}),jsxRuntimeExports.jsx(CardFooter,{children:jsxRuntimeExports.jsx(Link,{to:"/login",className:"text-primary underline text-sm",children:"Back to login"})})]})}):jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:"Reset password"}),jsxRuntimeExports.jsx(CardDescription,{children:"Enter your email and we'll send you a reset link"})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Oa,children:[jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[is&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:is}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"email",type:"email",value:$,onChange:Ia=>ts(Ia.target.value),required:!0,autoComplete:"email",className:"bg-background border-border"})]})]}),jsxRuntimeExports.jsxs(CardFooter,{className:"flex flex-col gap-3",children:[jsxRuntimeExports.jsx(Button,{type:"submit",className:"w-full cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",disabled:Na,children:Na?"Sending...":"Send reset link"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Remember your password?"," ",jsxRuntimeExports.jsx(Link,{to:"/login",className:"text-primary underline",children:"Sign in"})]})]})]})]})})}const verifyPromises=new Map;function ResetPasswordPage(){const{updatePassword:es,session:$,loading:ts}=useAuth(),is=useNavigate(),[cs,Qr]=reactExports.useState(""),[ja,Na]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(""),[Ia,La]=reactExports.useState(!1),[Ba,Ma]=reactExports.useState(()=>{const Ka=new URLSearchParams(window.location.search);return!!(Ka.get("token_hash")&&Ka.get("type"))}),[qa,Fa]=reactExports.useState(null);if(reactExports.useEffect(()=>{const Ka=new URLSearchParams(window.location.search),Ga=Ka.get("token_hash"),Va=Ka.get("type");if(!Ga||!Va)return;let Ja=!1,Ya=verifyPromises.get(Ga);return Ya||(Ya=supabase.auth.verifyOtp({token_hash:Ga,type:Va}),verifyPromises.set(Ga,Ya)),Ya.then(({error:el})=>{Ja||(el&&Fa(el.message||"This reset link is invalid or has expired."),window.history.replaceState({},"","/reset-password"),Ma(!1))}),()=>{Ja=!0}},[]),Ba||ts)return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsx(Card,{className:"w-full max-w-sm border-border bg-card",children:jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Verifying..."}),jsxRuntimeExports.jsx(CardDescription,{children:"Checking your reset link"})]})})});if(qa||!$)return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Invalid or expired link"}),jsxRuntimeExports.jsx(CardDescription,{children:qa??"This password reset link is no longer valid. Please request a new one."})]}),jsxRuntimeExports.jsx(CardFooter,{children:jsxRuntimeExports.jsx(Link,{to:"/forgot-password",className:"text-primary underline text-sm",children:"Request new reset link"})})]})});async function Ha(Ka){if(Ka.preventDefault(),Oa(""),cs!==ja){Oa("Passwords do not match");return}if(cs.length<6){Oa("Password must be at least 6 characters");return}La(!0);try{await es(cs),is("/sessions",{replace:!0})}catch(Ga){Oa(Ga instanceof Error?Ga.message:"Failed to update password")}finally{La(!1)}}return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 bg-background",children:jsxRuntimeExports.jsxs(Card,{className:"w-full max-w-sm border-border bg-card",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:"Set password"}),jsxRuntimeExports.jsx(CardDescription,{children:"Secure your account with a strong password"})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Ha,children:[jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[Aa&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:Aa}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"password",children:"Password"}),jsxRuntimeExports.jsx(Input,{id:"password",type:"password",value:cs,onChange:Ka=>Qr(Ka.target.value),required:!0,minLength:6,autoComplete:"new-password",className:"bg-background border-border"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"confirm-password",children:"Confirm password"}),jsxRuntimeExports.jsx(Input,{id:"confirm-password",type:"password",value:ja,onChange:Ka=>Na(Ka.target.value),required:!0,autoComplete:"new-password",className:"bg-background border-border"})]})]}),jsxRuntimeExports.jsx(CardFooter,{children:jsxRuntimeExports.jsx(Button,{type:"submit",className:"w-full cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",disabled:Ia,children:Ia?"Saving...":"Save password"})})]})]})})}function useInstructions(){return useQuery({queryKey:["instructions"],queryFn:()=>apiGet("/api/instructions")})}function useSessions(es={}){const $=new URLSearchParams;es.tool&&$.set("tool",es.tool),es.outcome&&$.set("outcome",es.outcome),es.friction&&$.set("friction",es.friction),es.instructionId&&$.set("instructionId",es.instructionId),es.hasAnalysis&&$.set("hasAnalysis","true"),es.projectPath&&$.set("projectPath",es.projectPath),es.projectId&&$.set("projectId",es.projectId),es.limit&&$.set("limit",String(es.limit)),es.hideEmpty===!1&&$.set("hideEmpty","false");const ts=$.toString();return useQuery({queryKey:["sessions",es],queryFn:()=>apiGet(`/api/sessions${ts?`?${ts}`:""}`),refetchInterval:POLL.LIVE})}function useSessionCount(es={}){const $=new URLSearchParams({summary:"count"});return es.tool&&$.set("tool",es.tool),es.projectPath&&$.set("projectPath",es.projectPath),es.projectId&&$.set("projectId",es.projectId),es.hideEmpty===!1&&$.set("hideEmpty","false"),useQuery({queryKey:["sessions","count",es],queryFn:()=>apiGet(`/api/sessions?${$.toString()}`),refetchInterval:POLL.LIVE})}function useSession(es){return useQuery({queryKey:["sessions",es],queryFn:()=>apiGet(`/api/sessions/${es}`),enabled:!!es,refetchInterval:POLL.LIVE})}const PAGE_SIZE$2=100;function useSessionEventsInfinite(es){return useInfiniteQuery({queryKey:["sessions",es,"events-infinite"],queryFn:({pageParam:$=0})=>apiGet(`/api/sessions/${es}/events?limit=${PAGE_SIZE$2}&offset=${$}&sort=desc`),initialPageParam:0,getNextPageParam:($,ts,is)=>$.length===PAGE_SIZE$2?is+PAGE_SIZE$2:void 0,enabled:!!es,refetchInterval:POLL.LIVE})}function useAnalyzeSession(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/sessions/${$}/analyze`,{}),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["sessions",ts]})}})}function useInsightsJob(es){const $=useQueryClient();return useQuery({queryKey:["insights-job",es],queryFn:()=>apiGet(`/api/insights-jobs/${es}`),enabled:!!es,refetchInterval:ts=>{var cs;const is=(cs=ts.state.data)==null?void 0:cs.status;return is==="completed"||is==="failed"||is==="cancelled"?(is==="completed"&&$.invalidateQueries({queryKey:["sessions"]}),!1):2e3}})}function useDeleteSession(){const es=useQueryClient();return useMutation({mutationFn:$=>apiDelete(`/api/sessions/${$}`),onSuccess:()=>{es.invalidateQueries({queryKey:["sessions"]})}})}function useSkillsRegistry(){return useQuery({queryKey:["skills-registry"],queryFn:()=>apiGet("/api/skills"),staleTime:300*1e3})}function useSkill(es){return useQuery({queryKey:["skills-registry",es],queryFn:()=>apiGet(`/api/skills/${es}`),enabled:!!es})}function CopyButton$2({text:es}){const{copied:$,copy:ts}=useCopyToClipboard();return jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"cursor-pointer h-7 text-xs",onClick:async is=>{is.stopPropagation(),await ts(es)||ue$1.error("Couldn't copy to clipboard",{description:"Select the text and copy it manually."})},children:$?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"})})}function RunCommandButton({prompt:es,label:$="Copy"}){const{copied:ts,copy:is}=useCopyToClipboard(),Qr=/^(claude|rulemetric|pnpm|npm|npx|git)\s/.test(es.trim())?es.trim():`claude -p '${es.replace(/'/g,"'\\''")}'`;return jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5 border-teal-500/30 text-teal-600 hover:bg-teal-500/10 hover:text-teal-600",onClick:async ja=>{ja.stopPropagation(),await is(Qr)||ue$1.error("Couldn't copy to clipboard",{description:"Select the text and copy it manually."})},title:`Copy command: ${Qr.slice(0,80)}...`,children:[ts?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),ts?"Copied!":$]})}function TooltipProvider({delayDuration:es=0,...$}){return jsxRuntimeExports.jsx(Provider,{"data-slot":"tooltip-provider",delayDuration:es,...$})}function Tooltip({...es}){return jsxRuntimeExports.jsx(Root3,{"data-slot":"tooltip",...es})}function TooltipTrigger({...es}){return jsxRuntimeExports.jsx(Trigger$2,{"data-slot":"tooltip-trigger",...es})}function TooltipContent({className:es,sideOffset:$=0,children:ts,...is}){return jsxRuntimeExports.jsx(Portal$1,{children:jsxRuntimeExports.jsxs(Content2$1,{"data-slot":"tooltip-content",sideOffset:$,className:cn$1("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",es),...is,children:[ts,jsxRuntimeExports.jsx(Arrow2,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}function canonicalToolKey(es){return es.toLowerCase().replace(/-/g,"_")}const TOOL_LABELS={claude_code:"Claude Code",cursor:"Cursor",vscode_copilot:"VS Code Copilot",copilot:"Copilot",copilot_cli:"Copilot CLI",copilot_agent:"Copilot Agent",github_copilot_chat:"GitHub Copilot Chat",github_copilot_fim:"GitHub Copilot FIM",codex:"Codex",aider:"Aider",gemini:"Gemini",windsurf:"Windsurf",cline:"Cline",openclaw:"OpenClaw",opencode:"OpenCode",antigravity:"Antigravity",rulemetric_mcp:"RuleMetric MCP"},TOOLS_WITHOUT_WORKING_ANALYSIS=new Set(["cursor"]);function canAnalyzeWithToolCli(es){return es?!TOOLS_WITHOUT_WORKING_ANALYSIS.has(canonicalToolKey(es)):!0}function displayTool(es){const $=canonicalToolKey(es);return TOOL_LABELS[$]?TOOL_LABELS[$]:$.split("_").filter(Boolean).map(ts=>ts.charAt(0).toUpperCase()+ts.slice(1)).join(" ")}function captureToolKey(es){return canonicalToolKey(es)}function formatUsd(es){return es>=1e3?`$${(es/1e3).toFixed(2)}K`:es>=1?`$${es.toFixed(2)}`:es>0?`$${es.toFixed(3)}`:"$0.00"}function formatTokens$1(es){return es?es>=1e6?`${(es/1e6).toFixed(1)}M`:es>=1e3?`${(es/1e3).toFixed(0)}K`:String(es):"0"}function Row$1({label:es,usd:$,detail:ts}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:es}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd($)}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground w-20 text-right",children:ts})]})]})}function CostBreakdownCard({totalUsd:es,breakdown:$,inputTokens:ts=0,outputTokens:is=0,cacheReadTokens:cs=0,cacheWriteTokens:Qr=0,byModel:ja,byTool:Na}){const Aa=$??{inputUsd:0,outputUsd:0,cacheReadUsd:0,cacheWriteUsd:0},Oa=ja?Object.entries(ja).sort(([,La],[,Ba])=>Ba.cost_usd-La.cost_usd):[],Ia=Na?Object.entries(Na).sort(([,La],[,Ba])=>Ba.cost_usd-La.cost_usd):[];return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Zap,{className:"h-4 w-4 text-primary"}),jsxRuntimeExports.jsx("span",{children:"Estimated cost"}),jsxRuntimeExports.jsxs("span",{className:"ml-auto font-mono text-base",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground mr-1",children:"≈"}),formatUsd(es)]})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Row$1,{label:"Input",usd:Aa.inputUsd,detail:`${formatTokens$1(ts)} tok`}),jsxRuntimeExports.jsx(Row$1,{label:"Output",usd:Aa.outputUsd,detail:`${formatTokens$1(is)} tok`}),jsxRuntimeExports.jsx(Row$1,{label:"Cache read",usd:Aa.cacheReadUsd,detail:cs>0?`${formatTokens$1(cs)} tok`:"no cache"}),jsxRuntimeExports.jsx(Row$1,{label:"Cache write",usd:Aa.cacheWriteUsd,detail:Qr>0?`${formatTokens$1(Qr)} tok`:"no cache"})]}),Ia.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"border-t border-border"}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"By tool"}),Ia.map(([La,Ba])=>{const Ma=es>0?Math.round(Ba.cost_usd/es*100):0;return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate max-w-[55%]",children:displayTool(La)}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd(Ba.cost_usd)}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground w-8 text-right",children:[Ma,"%"]})]})]},La)})]})]}),Oa.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"border-t border-border"}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide",children:"By model"}),Oa.map(([La,Ba])=>{const Ma=es>0?Math.round(Ba.cost_usd/es*100):0;return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate max-w-[55%]",children:La}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd(Ba.cost_usd)}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground w-8 text-right",children:[Ma,"%"]})]})]},La)})]})]}),jsxRuntimeExports.jsx("div",{className:"border-t border-border"}),jsxRuntimeExports.jsx(TooltipProvider,{children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground cursor-help",children:[jsxRuntimeExports.jsx("span",{className:"mr-1",children:"≈"}),"estimated · derived from token usage × current published rates"]})}),jsxRuntimeExports.jsx(TooltipContent,{className:"max-w-xs",children:jsxRuntimeExports.jsx("p",{className:"text-xs",children:"Computed from each model's token usage × its provider's published pricing (Anthropic, OpenAI, Google, and others). May differ from actual billing by ±5% due to per-request rounding; unrecognised models fall back to a Sonnet-equivalent estimate."})})]})})]})]})}const GLOSSARY={anchorSet:"A set of runs a human has reviewed — for each, you said whether the AI judge graded it correctly. These 'anchors' measure how trustworthy the judge is; no calibrated verdict is shown until you've collected enough.",humanLabeledRuns:"Runs where you've reviewed the AI judge's grade (approve = judge was right, reject = judge was wrong). Each review is one anchor. Only you can add these — an AI can't grade its own grader.",pilotTarget:"How many human-labeled runs are needed before a bias-corrected verdict is claimed (default 50), with a minimum in each of the with/without groups.",cohort:"The two groups being compared: runs WITH the instruction applied vs WITHOUT it. Each group needs enough labeled runs on its own for the comparison to hold.",mde:"Minimum Detectable Effect — the smallest with-vs-without difference this sample size could reliably detect. Lower is better; once MDE ≤ your target effect the result is 'powered'.",targetEffect:"The size of with-vs-without difference you care about detecting (default ±20 percentage points). The result is 'powered' once the MDE drops to this or below.",powered:"The sample is now precise enough to detect your target effect (MDE ≤ target). This is about PRECISION only — it does NOT mean the effect is real, nor that the AI judge has been calibrated yet.",adequate:"Enough human labels have been collected — across both groups and above the pilot floor — that a bias-corrected verdict can be published at the required precision.",judge:"The LLM that grades each eval output against its expectations. Fast and cheap, but it can be biased — which is exactly what your human labels measure and correct.",rectifier:"The AI judge's measured bias: the average gap between your human labels and the judge's own grades. It's subtracted back out to correct the judge's scores across every unlabeled run.",ppi:"Prediction-Powered Inference — grade everything cheaply with the AI judge, then correct its bias using a small RANDOM set of human labels. Gives tighter results than human-labels-alone.",discrimination:"Whether each test case actually responds to the instruction. A case 'discriminates' if its pass rate MOVES between the with- and without-instruction runs; one that always passes or always fails measures nothing.",discriminate:"This case's pass rate moves between with- and without-instruction runs, so it carries real signal about whether the instruction helps.",flat:"This case passes (or fails) at the same rate with and without the instruction — it measures nothing, and adding more runs of it will never help. Replace it.",unpaired:"This case has runs in only one group (e.g. every baseline run failed), so no with-vs-without comparison can be made for it.",separation:"The 'Δ' — with% minus without% for a case. The larger it is, the more sensitive the case is to the instruction.",significance:"Whether the measured effect is statistically distinguishable from zero — i.e. its confidence interval excludes 0. Without this, an apparent difference could just be noise.",confidenceInterval:"The range the true value most likely falls within. A wider interval means more uncertainty; it narrows as you collect more data.",delta:"The difference between the two conditions being compared (e.g. with-instruction pass rate minus without-instruction pass rate). Positive = the instruction helped.",verdict:"The overall read on whether an instruction helps, hurts, or shows no measurable effect — shown only once there's enough data to say honestly (otherwise 'insufficient data').",outcome:"An AI-graded score for how a real captured session went (from clean success to abandoned). It's the signal the observational effect estimate is built from.",totalSessionHours:"Every session's own length, added together. One session's length is the time from its first captured event to its last, so waiting and thinking inside a session count — it is elapsed time, not billed or active time. Sessions you ran side by side are each counted in full, so this total can exceed the hours on the clock: two sessions running the same hour contribute two hours, not one.",sessionSpan:"One session's length: last captured event minus the first. Idle stretches inside the session are included, so a session you left open and came back to counts the whole gap.",burnRate:"How fast you're consuming a rate-limit window relative to time elapsed — >100% means you're on track to hit the cap before the window resets.",rateLimitWindow:"A rolling period (e.g. 5-hour or weekly) over which a usage cap applies. Usage resets when the window rolls over."};function InfoTip({term:es,content:$,children:ts,className:is,size:cs=13,plain:Qr=!1}){const ja=$??(es?GLOSSARY[es]:null);if(!ja)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:ts});const Na=ts!=null?jsxRuntimeExports.jsx("span",{tabIndex:0,className:cn$1("cursor-help rounded-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",!Qr&&"underline decoration-dotted decoration-muted-foreground/50 underline-offset-2",is),children:ts}):jsxRuntimeExports.jsx("span",{tabIndex:0,"aria-label":"More information",className:cn$1("inline-flex shrink-0 items-center justify-center align-middle text-muted-foreground/60 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:text-foreground cursor-help",is),children:jsxRuntimeExports.jsx(Info,{style:{width:cs,height:cs},"aria-hidden":!0})});return jsxRuntimeExports.jsx(TooltipProvider,{delayDuration:150,children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:Na}),jsxRuntimeExports.jsx(TooltipContent,{className:"max-w-[19rem] whitespace-normal text-xs font-normal leading-relaxed",children:ja})]})})}function activatable(es){return{role:"button",tabIndex:0,onClick:es,onKeyDown:$=>{($.key==="Enter"||$.key===" ")&&($.preventDefault(),es())}}}const FRIENDLY_LABELS={debug_investigate:"Debug/Investigate",implement_feature:"Implement Feature",fix_bug:"Fix Bug",write_script_tool:"Write Script/Tool",refactor_code:"Refactor Code",configure_system:"Configure System",create_pr_commit:"Create PR/Commit",understand_codebase:"Understand Codebase",write_tests:"Write Tests",write_docs:"Write Docs",analyze_data:"Analyze Data",deploy_infra:"Deploy/Infra",warmup_minimal:"Cache Warmup",fully_achieved:"Fully Achieved",mostly_achieved:"Mostly Achieved",partially_achieved:"Partially Achieved",not_achieved:"Not Achieved",unclear_from_transcript:"Unclear",frustrated:"Frustrated",dissatisfied:"Dissatisfied",likely_satisfied:"Likely Satisfied",satisfied:"Satisfied",happy:"Happy",unsure:"Unsure",single_task:"Single Task",multi_task:"Multi Task",iterative_refinement:"Iterative Refinement",exploration:"Exploration",quick_question:"Quick Question",unhelpful:"Unhelpful",slightly_helpful:"Slightly Helpful",very_helpful:"Very Helpful",essential:"Essential",moderately_helpful:"Moderately Helpful",misunderstood_request:"Misunderstood Request",wrong_approach:"Wrong Approach",buggy_code:"Buggy Code",user_rejected_action:"User Rejected Action",excessive_changes:"Excessive Changes",wrong_file_or_location:"Wrong File/Location",slow_or_verbose:"Slow/Verbose",tool_failed:"Tool Failed",claude_code:"Claude Code",cursor:"Cursor",vscode_copilot:"VS Code Copilot",copilot_cli:"Copilot CLI",antigravity:"Antigravity",github_copilot_chat:"GitHub Copilot Chat",github_copilot_fim:"GitHub Copilot FIM"};function friendlyLabel(es){return FRIENDLY_LABELS[es]||es.replace(/_/g," ").replace(/\b\w/g,$=>$.toUpperCase())}function StatCard$2({icon:es,label:$,value:ts,sub:is,info:cs}){return jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[jsxRuntimeExports.jsx("div",{className:"shrink-0 rounded-lg bg-primary/10 p-2",children:jsxRuntimeExports.jsx(es,{className:"h-4 w-4 text-primary"})}),jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("p",{className:"break-words text-2xl font-bold font-mono",children:ts}),jsxRuntimeExports.jsxs("p",{className:"flex min-w-0 flex-wrap items-center gap-1 text-xs text-muted-foreground",children:[$,cs&&jsxRuntimeExports.jsx(InfoTip,{term:cs,size:12})]}),is&&jsxRuntimeExports.jsx("p",{className:"break-words text-xs text-muted-foreground mt-0.5",children:is})]})]})})})}function HorizontalBar({items:es,maxItems:$=8,onItemClick:ts}){const is=Object.entries(es).sort(([,Qr],[,ja])=>ja-Qr).slice(0,$);if(is.length===0)return jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No data"});const cs=is[0][1];return jsxRuntimeExports.jsx("div",{className:"space-y-2",children:is.map(([Qr,ja])=>jsxRuntimeExports.jsxs("div",{className:`space-y-1 ${ts?"cursor-pointer hover:bg-muted/50 rounded px-1 -mx-1 py-0.5":""}`,...ts?activatable(()=>ts(Qr)):{},children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate max-w-[200px]",children:friendlyLabel(Qr)}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono",children:(ja??0).toLocaleString()})]}),jsxRuntimeExports.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full rounded-full bg-primary transition-all",style:{width:`${ja/cs*100}%`}})})]},Qr))})}function HourChart({hours:es}){const $=new Array(24).fill(0);for(const is of es)$[is]++;const ts=Math.max(...$,1);return jsxRuntimeExports.jsx("div",{className:"flex items-end gap-0.5 h-20",children:$.map((is,cs)=>jsxRuntimeExports.jsx("div",{className:"flex-1 bg-primary/60 rounded-t hover:bg-primary transition-colors cursor-default",style:{height:`${is/ts*100}%`,minHeight:is>0?2:0},title:`${cs}:00 — ${is} messages`},cs))})}function formatDurationSec(es){return es<60?`${Math.round(es)}s`:es<3600?`${Math.round(es/60)}m`:`${(es/3600).toFixed(1)}h`}function ResponseTimeChart({histogram:es}){const $=Object.entries(es),ts=Math.max(...$.map(([,is])=>is),1);return jsxRuntimeExports.jsx("div",{className:"space-y-1.5",children:$.map(([is,cs])=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground w-14 text-right shrink-0",children:is}),jsxRuntimeExports.jsx("div",{className:"flex-1 h-4 bg-muted rounded overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary/70 rounded transition-all",style:{width:`${cs/ts*100}%`}})}),jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground w-8 text-right",children:cs})]},is))})}function OverviewTab({data:es}){const $=es.estimated_cost_usd??0,ts=es.truncated??!1,is=es.response_time,cs=es.parallel_sessions,Qr=es.tools_used,ja=es.tool_error_categories??{},Na=es.total_interruptions??0,Aa=es.sessions_with_meta??es.total_sessions,Oa=es.sessions_using_task_agent??0,Ia=es.sessions_using_mcp??0;return jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-5",children:[jsxRuntimeExports.jsx(StatCard$2,{icon:MessageSquare,label:"Messages",value:(es.total_messages??0).toLocaleString(),sub:`${es.messages_per_day??0}/day avg`}),jsxRuntimeExports.jsx(StatCard$2,{icon:CodeXml,label:"Lines Changed",value:`+${(es.total_lines_added??0).toLocaleString()}`,sub:`-${(es.total_lines_removed??0).toLocaleString()} removed`}),jsxRuntimeExports.jsx(StatCard$2,{icon:CodeXml,label:"Files Modified",value:(es.total_files_modified??0).toLocaleString()}),jsxRuntimeExports.jsx(StatCard$2,{icon:ChartColumn,label:"Days Active",value:es.days_active,sub:`${es.total_sessions} sessions`}),jsxRuntimeExports.jsx(StatCard$2,{icon:GitCommitHorizontal,label:"Git Commits",value:es.git_commits,sub:`${es.git_pushes} pushes`})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[$>0&&jsxRuntimeExports.jsxs("div",{className:"md:col-span-2 space-y-2",children:[jsxRuntimeExports.jsx(CostBreakdownCard,{totalUsd:$,breakdown:es.estimated_cost_breakdown,inputTokens:es.total_input_tokens,outputTokens:es.total_output_tokens,cacheReadTokens:es.total_cache_read_tokens,cacheWriteTokens:es.total_cache_write_tokens,byModel:es.estimated_cost_by_model}),ts&&jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3 shrink-0"}),"Computed from your 500 most-recent sessions — spend and token totals are a floor, not a complete sum."]})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4",children:[jsxRuntimeExports.jsx(StatCard$2,{icon:Clock,label:"Total Session Hours",info:"totalSessionHours",value:Math.round(es.total_duration_hours).toLocaleString(),sub:[`summed over ${Aa.toLocaleString()} sessions`,Na>0?`${Na} interruptions`:null].filter(Boolean).join(" · ")}),Oa>0&&jsxRuntimeExports.jsx(StatCard$2,{icon:Zap,label:"Task Agents",value:Oa,sub:"sessions"}),Ia>0&&jsxRuntimeExports.jsx(StatCard$2,{icon:Zap,label:"MCP Sessions",value:Ia,sub:"sessions"})]})]}),cs&&cs.events>0&&jsxRuntimeExports.jsxs(Card,{className:"min-w-0",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Parallel Sessions"})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-3 sm:gap-8",children:[jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-2xl font-bold font-mono",children:cs.events}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"overlap events"})]}),jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-2xl font-bold font-mono",children:cs.sessions_involved}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"sessions involved"})]}),jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsxs("p",{className:"text-2xl font-bold font-mono",children:[es.total_sessions>0?Math.round(cs.sessions_involved/es.total_sessions*100):0,"%"]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"of sessions"})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Detected when messages from different sessions overlap within 30-minute windows."})]})]}),Qr&&Object.keys(Qr).length>1&&jsxRuntimeExports.jsxs(Card,{className:"min-w-0",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"AI Tools Used"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:Qr})})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[is&&is.total_samples>0&&jsxRuntimeExports.jsxs(Card,{className:"min-w-0",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"User Response Time Distribution"}),jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Median: ",formatDurationSec(is.median_seconds)," · Avg: ",formatDurationSec(is.avg_seconds)," · ",is.total_samples," samples"]})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(ResponseTimeChart,{histogram:is.histogram})})]}),es.message_hours.length>0&&jsxRuntimeExports.jsxs(Card,{className:"min-w-0",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Messages by Time of Day (UTC)"})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsx(HourChart,{hours:es.message_hours}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-1 font-mono",children:[jsxRuntimeExports.jsx("span",{children:"0:00"}),jsxRuntimeExports.jsx("span",{children:"6:00"}),jsxRuntimeExports.jsx("span",{children:"12:00"}),jsxRuntimeExports.jsx("span",{children:"18:00"}),jsxRuntimeExports.jsx("span",{children:"23:00"})]})]})]})]}),Object.keys(ja).length>0&&jsxRuntimeExports.jsxs(Card,{className:"min-w-0",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 text-red-500"}),"Tool Error Encounters"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:ja})})]})]})}function ToolsTab({data:es}){return jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Tool Usage"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:es.tool_counts,maxItems:12})})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Languages"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:es.languages})})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Feature Usage"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[{label:"Task Agents",value:es.sessions_using_task_agent},{label:"MCP Servers",value:es.sessions_using_mcp}].map($=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("span",{className:"text-sm",children:$.label}),jsxRuntimeExports.jsxs(Badge,{variant:$.value>0?"default":"outline",children:[$.value," sessions"]})]},$.label))})})]})]})}function QualityTab({data:es,emptyAction:$}){const ts=useNavigate(),is=[{key:"goal_categories",title:"Goal Categories",items:es.goal_categories??{}},{key:"outcomes",title:"Outcomes",items:es.outcomes??{},onClick:cs=>ts(`/sessions?outcome=${cs}`)},{key:"satisfaction",title:"User Satisfaction",items:es.satisfaction??{}},{key:"session_types",title:"Session Types",items:es.session_types??{}},{key:"friction",title:"Friction Points",items:es.friction??{},icon:TriangleAlert,onClick:cs=>ts(`/sessions?friction=${cs}`)}].filter(cs=>Object.keys(cs.items).length>0);return is.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-6 space-y-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["No quality data yet. Session analysis runs automatically on your local worker — make sure ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"rulemetric evals agent"})," is running, then use Generate Recommendations to analyze recent sessions."]}),$]})}):jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:is.map(cs=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:cs.title})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:cs.items,onItemClick:cs.onClick})})]},cs.key))})}function GenerateInsightsButton({idleLabel:es="Generate Insights",successLabel:$="Insights queued!",className:ts}={}){const is=useMutation({mutationFn:()=>apiPost("/api/insights-jobs/regenerate-all",{})});return jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",className:cn$1("cursor-pointer",ts),onClick:()=>is.mutate(),disabled:is.isPending||is.isSuccess,children:is.isPending?"Queuing...":is.isSuccess?$:es})}function SkillDownloadButton({skillId:es,content:$}){return jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5 border-primary/30 text-primary hover:bg-primary/10",onClick:ts=>{ts.stopPropagation();const is=new Blob([$],{type:"text/markdown"}),cs=URL.createObjectURL(is),Qr=document.createElement("a");Qr.href=cs,Qr.download=`${es}.md`,Qr.click(),URL.revokeObjectURL(cs)},children:[jsxRuntimeExports.jsx(Download,{className:"h-3 w-3"}),"Download"]})}function SuggestionsTab({rec:es,isAuto:$}){var Aa,Oa,Ia;const{data:ts}=useSkillsRegistry(),cs=es.recommended_skills??[],Qr=((Aa=es.suggestions)==null?void 0:Aa.features_to_try)??[],ja=((Oa=es.suggestions)==null?void 0:Oa.usage_patterns)??[],Na=((Ia=es.on_the_horizon)==null?void 0:Ia.opportunities)??[];return Qr.length===0&&ja.length===0&&Na.length===0&&cs.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-6 space-y-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No suggestions yet. Generate insights to get recommendations from your sessions."}),jsxRuntimeExports.jsx(GenerateInsightsButton,{})]})}):jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[$&&jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border bg-muted/30 px-4 py-2",children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Auto-generated from your session data. Generate full AI-powered recommendations for deeper insights."}),jsxRuntimeExports.jsx(GenerateInsightsButton,{idleLabel:"Generate Full Insights",successLabel:"Queued!",className:"text-xs ml-4 shrink-0"})]}),Qr.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"h-4 w-4 text-blue-500"}),"Features to Try"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:Qr.map((La,Ba)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:La.feature}),La.example_code&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:La.example_code,label:"Run"}),jsxRuntimeExports.jsx(CopyButton$2,{text:La.example_code})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:La.why_for_you}),La.example_code&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto text-muted-foreground",children:La.example_code})]},Ba))})]}),ja.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"h-4 w-4 text-cyan-500"}),"Usage Patterns"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:ja.map((La,Ba)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:La.title}),La.copyable_prompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:La.copyable_prompt,label:"Run"}),jsxRuntimeExports.jsx(CopyButton$2,{text:La.copyable_prompt})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:La.suggestion}),La.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto text-muted-foreground",children:La.copyable_prompt})]},Ba))})]}),Na.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-4 w-4 text-pink-500"}),"On the Horizon"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:Na.map((La,Ba)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:La.title}),La.copyable_prompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:La.copyable_prompt,label:"Run"}),jsxRuntimeExports.jsx(CopyButton$2,{text:La.copyable_prompt})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:La.whats_possible}),La.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto text-muted-foreground",children:La.copyable_prompt})]},Ba))})]}),cs.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Zap,{className:"h-4 w-4 text-amber-500"}),"Recommended Skills"]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[cs.map(La=>{var qa;const Ba=(qa=ts==null?void 0:ts.skills)==null?void 0:qa.find(Fa=>Fa.id===La.skillId),Ma=`rulemetric skills install ${La.skillId}`;return jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:(Ba==null?void 0:Ba.name)??La.skillId}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[(Ba==null?void 0:Ba.content)&&jsxRuntimeExports.jsx(SkillDownloadButton,{skillId:La.skillId,content:Ba.content}),jsxRuntimeExports.jsx(RunCommandButton,{prompt:Ma,label:"Install"})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:La.reason}),(Ba==null?void 0:Ba.description)&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:Ba.description})]},La.skillId)}),jsxRuntimeExports.jsx("div",{className:"pt-1",children:jsxRuntimeExports.jsx(Link,{to:"/skills",className:"text-xs text-primary hover:underline font-mono",children:"Browse all skills →"})})]})]})]})}function InsightsSection(){var Qr;const[es,$]=useTabParam(["overview","tools","quality","suggestions"],"overview"),{data:ts,isLoading:is,error:cs}=useComputedInsights();return is?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[...Array(4)].map((ja,Na)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},Na))}):cs||!ts||ts.total_sessions===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"text-center space-y-3 py-6",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-10 w-10 mx-auto text-muted-foreground/50"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"No insights yet"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Start capturing sessions to see insights here"})]})]})})}):jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-mono text-muted-foreground",children:"Session Insights"}),jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[ts.total_sessions," sessions · ",ts.days_active," days"]})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsx(TabsTrigger,{value:"overview",className:"cursor-pointer",children:"Overview"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"tools",className:"cursor-pointer",children:"Tools"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"quality",className:"cursor-pointer",children:"Quality"}),ts.recommendations&&jsxRuntimeExports.jsx(TabsTrigger,{value:"suggestions",className:"cursor-pointer",children:"Suggestions"})]}),jsxRuntimeExports.jsx(TabsContent,{value:"overview",className:"mt-4",children:jsxRuntimeExports.jsx(OverviewTab,{data:ts})}),jsxRuntimeExports.jsx(TabsContent,{value:"tools",className:"mt-4",children:jsxRuntimeExports.jsx(ToolsTab,{data:ts})}),jsxRuntimeExports.jsx(TabsContent,{value:"quality",className:"mt-4",children:jsxRuntimeExports.jsx(QualityTab,{data:ts,emptyAction:jsxRuntimeExports.jsx(GenerateInsightsButton,{})})}),ts.recommendations&&jsxRuntimeExports.jsx(TabsContent,{value:"suggestions",className:"mt-4",children:jsxRuntimeExports.jsx(SuggestionsTab,{rec:ts.recommendations,isAuto:!!((Qr=ts.recommendations)!=null&&Qr._auto_generated)})})]})]})}function PendingSuggestionsCallout(){const{data:es}=usePendingSuggestionCount();if(!es||es.total===0)return null;const $=es.byProject.slice(0,3);return jsxRuntimeExports.jsx(Link,{to:"/suggestions",className:"block no-underline","data-testid":"pending-suggestions-callout",children:jsxRuntimeExports.jsxs("div",{className:"group flex flex-wrap items-center gap-3 rounded-lg border border-primary/40 bg-primary/[0.06] px-4 py-3 transition-colors hover:bg-primary/[0.1]",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"h-4 w-4 shrink-0 text-primary"}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 basis-56",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm font-medium",children:[es.total," instruction suggestion",es.total===1?"":"s"," await your review"]}),jsxRuntimeExports.jsxs("p",{className:"mt-0.5 truncate text-xs text-muted-foreground",children:[$.map(ts=>`${ts.projectPath.split("/").pop()} (${ts.count})`).join(" · "),es.byProject.length>3&&" · …"]})]}),jsxRuntimeExports.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-sm font-medium text-primary",children:["Review",jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]})})}function DashboardPage(){const{user:es}=useAuth(),{data:$,isLoading:ts}=useInstructions(),{data:is,isLoading:cs}=useSessionCount();return jsxRuntimeExports.jsxs("div",{className:"space-y-8",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 basis-56",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Dashboard"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground break-words",children:["Welcome back, ",es==null?void 0:es.email]})]}),jsxRuntimeExports.jsx("div",{className:"flex gap-2"})]}),jsxRuntimeExports.jsx(PendingSuggestionsCallout,{}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{className:"flex flex-row items-center justify-between pb-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium text-muted-foreground",children:"Instructions"}),jsxRuntimeExports.jsx(FileText,{className:"h-4 w-4 text-muted-foreground"})]}),jsxRuntimeExports.jsx(CardContent,{children:ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-16"}):jsxRuntimeExports.jsx("div",{className:"text-3xl font-mono font-bold text-primary",children:($==null?void 0:$.length)??0})})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"flex flex-row items-center justify-between pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium text-muted-foreground",children:"Formats"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("div",{className:"text-3xl font-mono font-bold text-primary",children:"25+"})})]}),jsxRuntimeExports.jsx(Link,{to:"/sessions",className:"no-underline",children:jsxRuntimeExports.jsxs(Card,{className:"cursor-pointer hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsxs(CardHeader,{className:"flex flex-row items-center justify-between pb-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium text-muted-foreground",children:"Sessions"}),jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4 text-muted-foreground"})]}),jsxRuntimeExports.jsx(CardContent,{children:cs?jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-16"}):jsxRuntimeExports.jsx("div",{className:"text-3xl font-mono font-bold text-primary","data-testid":"dashboard-session-count",children:((is==null?void 0:is.count)??0).toLocaleString()})})]})})]}),jsxRuntimeExports.jsx(InsightsSection,{})]})}function useApiKeys(){return useQuery({queryKey:["api-keys"],queryFn:()=>apiGet("/api/auth/api-keys")})}function useCreateApiKey(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/auth/api-keys",$),onSuccess:()=>{es.invalidateQueries({queryKey:["api-keys"]})}})}function useRevokeApiKey(){const es=useQueryClient();return useMutation({mutationFn:$=>apiDelete(`/api/auth/api-keys/${$}`),onSuccess:()=>{es.invalidateQueries({queryKey:["api-keys"]})}})}const apiUrl=window.location.origin,toolGroups=[{label:"Instructions",tools:[{name:"rulemetric_list",desc:"List your instructions"},{name:"rulemetric_summary",desc:"Get instruction metadata and preview"},{name:"rulemetric_get",desc:"Get full instruction content"},{name:"rulemetric_search",desc:"Search instructions by name or content"},{name:"rulemetric_convert",desc:"Convert to any supported format"},{name:"rulemetric_formats",desc:"List all 25+ converter formats"}]},{label:"Collaboration",tools:[{name:"rulemetric_fork",desc:"Fork an instruction to personal scope"},{name:"rulemetric_promote",desc:"Promote to team or org scope"},{name:"rulemetric_upstream",desc:"Check for upstream updates"},{name:"rulemetric_pull_upstream",desc:"Pull upstream changes via 3-way merge"}]},{label:"Catalog & Recommendations",tools:[{name:"rulemetric_catalog",desc:"Browse org/team instruction catalog"},{name:"rulemetric_recommendations",desc:"AI-powered instruction suggestions"},{name:"rulemetric_apply_suggestion",desc:"Accept a precomputed instruction suggestion mid-session"}]},{label:"Sessions & Insights",tools:[{name:"rulemetric_session_list",desc:"List captured AI sessions"},{name:"rulemetric_session_import",desc:"Import session from JSONL or JSON"},{name:"rulemetric_instruction_insights",desc:"Session-based performance insights"},{name:"rulemetric_diagnostics",desc:"Diagnose hook install, config, and API connectivity"}]}];function SetupRow({state:es,label:$,helper:ts}){const is=es==="detected"?CircleCheck:es==="loading"?LoaderCircle:es==="waiting"?Hourglass:CircleAlert,cs=es==="detected"?"text-teal-400":es==="loading"||es==="waiting"?"text-muted-foreground":"text-amber-400";return jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border bg-background px-3 py-2",children:[jsxRuntimeExports.jsx(is,{className:cn$1("h-4 w-4 mt-0.5 shrink-0",cs,es==="loading"&&"animate-spin")}),jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports.jsx("div",{className:"text-sm font-medium",children:$}),ts&&jsxRuntimeExports.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:ts})]})]})}function ConnectPage(){const[es,$]=useTabParam(["claude-code","copilot","manual"],"claude-code"),{session:ts,user:is}=useAuth();ts==null||ts.access_token;const{workers:cs,activeWorkers:Qr,isConnected:ja,isLoading:Na}=useWorkerStatus("mcp"),Aa=useSetupProgress(),{openModal:Oa,progress:Ia}=useSetupWalkthrough(),{data:La,isLoading:Ba}=useApiKeys(),Ma=useCreateApiKey(),qa=useRevokeApiKey(),[Fa,Ha]=reactExports.useState(""),[Ka,Ga]=reactExports.useState(null),[Va,Ja]=reactExports.useState(!0),[Ya,el]=reactExports.useState(null),{profile:tl}=useActiveOrg(),rl=(tl==null?void 0:tl.liveSendSkipped)??!1,cl=(La==null?void 0:La.filter(pl=>!pl.revokedAt))??[];function dl(){const pl=Fa.trim()||"default";Ma.mutate({name:pl},{onSuccess:jl=>{Ga(jl.key),Ja(!0),Ha("")}})}function fl(pl){qa.mutate(pl,{onSuccess:()=>el(null)})}const nl="<your-api-key>",ol=`claude mcp add rulemetric -e RULEMETRIC_API_KEY=${nl} -e RULEMETRIC_API_URL=${apiUrl} -e RULEMETRIC_CLIENT_NAME=claude-code -- node /path/to/apps/mcp/dist/index.js`,hl=JSON.stringify({mcpServers:{rulemetric:{command:"node",args:["/path/to/apps/mcp/dist/index.js"],env:{RULEMETRIC_API_KEY:nl,RULEMETRIC_API_URL:apiUrl,RULEMETRIC_CLIENT_NAME:"claude-code"}}}},null,2),Tl=JSON.stringify({"github.copilot.chat.mcp.servers":{rulemetric:{command:"node",args:["/path/to/apps/mcp/dist/index.js"],env:{RULEMETRIC_API_KEY:nl,RULEMETRIC_API_URL:apiUrl,RULEMETRIC_CLIENT_NAME:"vscode-copilot"}}}},null,2),ul=JSON.stringify({servers:{rulemetric:{command:"node",args:["/path/to/apps/mcp/dist/index.js"],env:{RULEMETRIC_API_KEY:nl,RULEMETRIC_API_URL:apiUrl,RULEMETRIC_CLIENT_NAME:"vscode-copilot"}}}},null,2);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Connect"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Connect RuleMetric to your AI coding tools via the MCP server"})]}),jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsxs(CardHeader,{className:"pb-2 flex flex-row items-center justify-between space-y-0",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono text-muted-foreground",children:"Setup"}),!Ia.coreComplete&&jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",onClick:Oa,className:"cursor-pointer shrink-0",children:"Resume setup"})]}),jsxRuntimeExports.jsxs(CardContent,{className:"grid gap-2 md:grid-cols-2",children:[jsxRuntimeExports.jsx(SetupRow,{state:Aa.steps.install.state,label:"Install the CLI",helper:Aa.steps.install.state==="detected"?"Detected via captured session activity.":`Run: ${INSTALL_CLI}`}),jsxRuntimeExports.jsx(SetupRow,{state:Aa.steps.auth.state,label:"Authenticated",helper:Aa.steps.auth.state==="detected"?(is==null?void 0:is.email)??"Signed in":"Sign in to capture sessions."}),jsxRuntimeExports.jsx(SetupRow,{state:Aa.steps.hooks.state,label:"Hooks installed",helper:Aa.steps.hooks.state==="detected"?"Session hooks are firing — capturing Claude Code directly, no proxy needed. Add the optional proxy for the exact system prompt, other AI tools, and live cost.":"Run: rulemetric hooks install — no CA cert or proxy required."}),jsxRuntimeExports.jsx(SetupRow,{state:Aa.steps.worker.state,label:"Worker running",helper:Aa.steps.worker.state==="detected"?"Local worker is heartbeating.":"Run: rulemetric service install --worker-only"}),jsxRuntimeExports.jsx(SetupRow,{state:Aa.steps.tmux.state,label:"Tmux available",helper:Aa.steps.tmux.state==="detected"?"Live message send is enabled for active sessions.":rl?"Skipped during setup — start a Claude Code session in tmux to enable it anytime.":"Start a Claude Code session in tmux to enable live send."}),jsxRuntimeExports.jsx(SetupRow,{state:Aa.steps.target.state,label:"First live target detected",helper:Aa.steps.target.state==="detected"?"We've seen at least one terminal target from this user.":rl?"Skipped during setup — launch a session anytime to register your first target.":"Launch a session to register your first target."})]})]}),jsxRuntimeExports.jsx(Card,{className:ja?"border-teal-500/30 bg-teal-500/5":"border-border",children:jsxRuntimeExports.jsx(CardContent,{className:"py-4",children:Na?jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(Clock,{className:"h-4 w-4 animate-pulse"}),"Checking connection status..."]}):ja?jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-teal-400",children:[jsxRuntimeExports.jsx(Wifi,{className:"h-4 w-4"}),jsxRuntimeExports.jsxs("span",{className:"font-medium",children:[Qr.length," active connection",Qr.length>1?"s":""]})]}),jsxRuntimeExports.jsx("div",{className:"grid gap-2",children:Qr.map(pl=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-teal-500/20 bg-background px-3 py-2 text-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"h-2 w-2 rounded-full bg-teal-500 animate-pulse"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:pl.clientName}),pl.workerVersion&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-xs",children:["v",pl.workerVersion]})]}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["Last seen ",formatRelativeTime(pl.lastHeartbeat)]})]},pl.id))})]}):cs&&cs.length>0?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(WifiOff,{className:"h-4 w-4"}),jsxRuntimeExports.jsxs("span",{children:["No active connections — last seen ",formatRelativeTime(cs[0].lastHeartbeat)]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Start your AI coding tool with the RuleMetric MCP server configured to reconnect."})]}):jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(WifiOff,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{children:"No MCP connections yet — follow the setup below to get started."})]})})}),jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono text-muted-foreground flex items-center gap-2",children:[jsxRuntimeExports.jsx(Key,{className:"h-4 w-4"}),"API Keys"]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"API keys authenticate your CLI, hooks, and proxy. They never expire and are more reliable than session tokens."}),Ka&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-teal-500/30 bg-teal-500/5 p-4 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-teal-400",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4"}),"Copy your API key now — it won't be shown again"]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("code",{className:"flex-1 text-xs font-mono bg-[#0B1120] rounded px-3 py-2 break-all",children:Va?Ka:"rm_"+"•".repeat(40)}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:()=>Ja(!Va),className:"cursor-pointer shrink-0",children:Va?jsxRuntimeExports.jsx(EyeOff,{className:"h-4 w-4"}):jsxRuntimeExports.jsx(Eye,{className:"h-4 w-4"})}),jsxRuntimeExports.jsx(CopyButton$3,{text:Ka})]}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:()=>Ga(null),className:"cursor-pointer text-xs text-muted-foreground",children:"Dismiss"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Input,{placeholder:"Key name (e.g. laptop, work)",value:Fa,onChange:pl=>Ha(pl.target.value),onKeyDown:pl=>{pl.key==="Enter"&&!Ma.isPending&&dl()},className:"flex-1"}),jsxRuntimeExports.jsxs(Button,{onClick:dl,disabled:Ma.isPending,className:"cursor-pointer shrink-0",size:"sm",children:[jsxRuntimeExports.jsx(Plus,{className:"mr-1 h-4 w-4"}),Ma.isPending?"Creating...":"Create Key"]})]}),Ba?jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading keys..."}):cl.length===0&&!Ka?jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground border border-dashed border-border rounded-lg p-4 text-center",children:"No API keys yet. Create one to get started."}):jsxRuntimeExports.jsx("div",{className:"space-y-2",children:cl.map(pl=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border bg-background px-3 py-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[jsxRuntimeExports.jsxs("code",{className:"text-xs font-mono text-muted-foreground shrink-0",children:[pl.keyPrefix,"..."]}),jsxRuntimeExports.jsx("span",{className:"text-sm truncate",children:pl.name})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:pl.lastUsedAt?`Used ${formatRelativeTime(pl.lastUsedAt)}`:"Never used"}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["Created ",formatRelativeTime(pl.createdAt)]}),Ya===pl.id?jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(Button,{variant:"destructive",size:"sm",onClick:()=>fl(pl.id),disabled:qa.isPending,className:"cursor-pointer text-xs h-7",children:"Confirm"}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:()=>el(null),className:"cursor-pointer text-xs h-7",children:"Cancel"})]}):jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:()=>el(pl.id),className:"cursor-pointer text-muted-foreground hover:text-destructive h-7",children:jsxRuntimeExports.jsx(Trash2,{className:"h-3 w-3"})})]})]},pl.id))})]})]}),jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono text-muted-foreground flex items-center gap-2",children:[jsxRuntimeExports.jsx(Plug,{className:"h-4 w-4"}),"MCP Server Setup"]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:["The MCP server isn't published to npm yet — clone the RuleMetric repo and run"," ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"pnpm install && pnpm build"})," first, then point the config at ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"apps/mcp/dist/index.js"})," in your checkout."]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"claude-code",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Terminal,{className:"mr-2 h-4 w-4"}),"Claude Code"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"copilot",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(CodeXml,{className:"mr-2 h-4 w-4"}),"VS Code Copilot"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"manual",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(FileJson,{className:"mr-2 h-4 w-4"}),"Manual Config"]})]}),jsxRuntimeExports.jsxs(TabsContent,{value:"claude-code",className:"mt-4 space-y-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Run this command to add RuleMetric as an MCP server in Claude Code:"}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-1",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"Terminal"}),jsxRuntimeExports.jsx(CopyButton$3,{text:ol})]}),jsxRuntimeExports.jsx("pre",{className:"overflow-auto rounded-lg border border-border bg-[#0B1120] p-4 text-sm font-mono whitespace-pre-wrap",children:ol})]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Or add this to a ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:".mcp.json"})," file in your project root (Claude Code reads MCP servers from there, not from settings.json):"]}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-1",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:".mcp.json"}),jsxRuntimeExports.jsx(CopyButton$3,{text:hl})]}),jsxRuntimeExports.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg border border-border bg-[#0B1120] p-4 text-sm font-mono whitespace-pre-wrap",children:hl})]})]})]}),jsxRuntimeExports.jsxs(TabsContent,{value:"copilot",className:"mt-4 space-y-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-2",children:"Option 1: VS Code Settings"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Add this to your VS Code settings (",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"Cmd+Shift+P"}),' → "Preferences: Open User Settings (JSON)"):']}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-1",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"settings.json"}),jsxRuntimeExports.jsx(CopyButton$3,{text:Tl})]}),jsxRuntimeExports.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg border border-border bg-[#0B1120] p-4 text-sm font-mono whitespace-pre-wrap",children:Tl})]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-2",children:"Option 2: Project-level .vscode/mcp.json"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Or create a ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:".vscode/mcp.json"})," file in your project root for per-project configuration:"]}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-1",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:".vscode/mcp.json"}),jsxRuntimeExports.jsx(CopyButton$3,{text:ul})]}),jsxRuntimeExports.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg border border-border bg-[#0B1120] p-4 text-sm font-mono whitespace-pre-wrap",children:ul})]})]}),jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-4 space-y-2",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Using RuleMetric in Copilot Chat"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Once configured, open Copilot Chat in Agent mode (",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"Cmd+Shift+I"}),") and RuleMetric tools will be available. You can ask Copilot to:"]}),jsxRuntimeExports.jsxs("ul",{className:"text-sm text-muted-foreground list-disc pl-5 space-y-1",children:[jsxRuntimeExports.jsx("li",{children:"List and search your instructions"}),jsxRuntimeExports.jsx("li",{children:"Convert instructions to any format"}),jsxRuntimeExports.jsx("li",{children:"Browse the org/team catalog"}),jsxRuntimeExports.jsx("li",{children:"Get AI-powered recommendations"}),jsxRuntimeExports.jsx("li",{children:"Import and review coding sessions"})]})]})]}),jsxRuntimeExports.jsxs(TabsContent,{value:"manual",className:"mt-4 space-y-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Use this JSON config for any MCP-compatible tool (Cursor, Windsurf, etc.):"}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-1",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"mcp.json"}),jsxRuntimeExports.jsx(CopyButton$3,{text:hl})]}),jsxRuntimeExports.jsx("pre",{className:"max-h-96 overflow-auto rounded-lg border border-border bg-[#0B1120] p-4 text-sm font-mono whitespace-pre-wrap",children:hl})]})]}),jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-4 space-y-2",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Getting an API key"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate an API key via the CLI. It never expires and is saved automatically:"}),jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono text-muted-foreground bg-[#0B1120] rounded p-3 mt-2",children:`rulemetric auth login
|
|
142
|
-
rulemetric auth create-key --name "my-setup"`})]})]})]})]})]}),jsxRuntimeExports.jsx(Card,{className:"border-blue-500/30 bg-blue-500/5",children:jsxRuntimeExports.jsxs(CardContent,{className:"py-3 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("strong",{className:"text-blue-400",children:"Tip:"})," Use an API key (",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"rm_..."}),") instead of a JWT for MCP server config. API keys never expire and work for all integrations. Create one in the API Keys section above, or via CLI:"," ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:'rulemetric auth create-key --name "my-setup"'})]})}),jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono text-muted-foreground",children:["Available Tools (",toolGroups.reduce((pl,jl)=>pl+jl.tools.length,0),")"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-6",children:toolGroups.map(pl=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-2",children:pl.label}),jsxRuntimeExports.jsx("div",{className:"grid gap-2",children:pl.tools.map(jl=>jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-lg border border-border bg-background p-3",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs shrink-0",children:jl.name}),jsxRuntimeExports.jsx("span",{className:"min-w-0 break-words text-sm text-muted-foreground",children:jl.desc})]},jl.name))})]},pl.label))})]})]})}function projectDisplayName(es){var cs;if(es.projectName)return es.projectName;const $=lastTwoSegments(es.primaryCheckoutPath);if($)return $;const ts=nameFromRemote((cs=es.metadata)==null?void 0:cs.gitRemote);if(ts)return ts;const is=lastTwoSegments(es.projectPath);return is||"—"}function lastTwoSegments(es){if(!es)return null;const $=es.split("/").filter(Boolean);return $.length===0?null:$.slice(-2).join("/")}function nameFromRemote(es){if(typeof es!="string"||!es.trim())return null;const $=es.trim().replace(/\.git$/i,"").replace(/^(https?:\/\/|ssh:\/\/(?:[^@]+@)?|git:\/\/|[^@]+@)/,"").replace(/^([^/:]+):/,"$1/"),ts=$.split("/").filter(Boolean);return ts.length>=3?ts.slice(-2).join("/"):ts.length===2?ts[1]:$||null}function ClaudeCodeIcon(es){return jsxRuntimeExports.jsx("svg",{viewBox:"0 0 24 24",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",...es,children:jsxRuntimeExports.jsx("path",{d:"M12 2.5L13.4 9.2L20 8.5L14.8 12L20 15.5L13.4 14.8L12 21.5L10.6 14.8L4 15.5L9.2 12L4 8.5L10.6 9.2L12 2.5Z"})})}function CursorIcon(es){return jsxRuntimeExports.jsx("svg",{viewBox:"0 0 24 24",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",...es,children:jsxRuntimeExports.jsx("path",{d:"M12 2L13.5 10.5L22 12L13.5 13.5L12 22L10.5 13.5L2 12L10.5 10.5L12 2Z"})})}function VSCodeCopilotIcon(es){return jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24",width:"1em",height:"1em",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinejoin:"round","aria-hidden":"true",...es,children:[jsxRuntimeExports.jsx("path",{d:"M17.5 2.5L21.5 4.5V19.5L17.5 21.5L8 13.5L4 16.5L2.5 15.5V8.5L4 7.5L8 10.5L17.5 2.5Z"}),jsxRuntimeExports.jsx("path",{d:"M17.5 2.5V21.5"})]})}const TOOL_ICON_COMPONENTS={claude_code:ClaudeCodeIcon,cursor:CursorIcon,vscode_copilot:VSCodeCopilotIcon};function ToolIcon({tool:es,...$}){const ts=TOOL_ICON_COMPONENTS[es];return ts?jsxRuntimeExports.jsx(ts,{...$}):jsxRuntimeExports.jsx(Activity,{...$})}function Table({className:es,...$}){return jsxRuntimeExports.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:jsxRuntimeExports.jsx("table",{"data-slot":"table",className:cn$1("w-full caption-bottom text-sm",es),...$})})}function TableHeader({className:es,...$}){return jsxRuntimeExports.jsx("thead",{"data-slot":"table-header",className:cn$1("[&_tr]:border-b",es),...$})}function TableBody({className:es,...$}){return jsxRuntimeExports.jsx("tbody",{"data-slot":"table-body",className:cn$1("[&_tr:last-child]:border-0",es),...$})}function TableRow({className:es,...$}){return jsxRuntimeExports.jsx("tr",{"data-slot":"table-row",className:cn$1("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",es),...$})}function TableHead({className:es,...$}){return jsxRuntimeExports.jsx("th",{"data-slot":"table-head",className:cn$1("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",es),...$})}function TableCell({className:es,...$}){return jsxRuntimeExports.jsx("td",{"data-slot":"table-cell",className:cn$1("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",es),...$})}function formatDuration(es,$){if(!$)return"—";const ts=new Date($).getTime()-new Date(es).getTime();if(!Number.isFinite(ts)||ts<0)return"—";const is=Math.floor(ts/6e4);if(is<1)return"<1m";if(is<60)return`${is}m`;const cs=Math.floor(is/60);return cs<24?`${cs}h ${is%60}m`:`${Math.floor(cs/24)}d ${cs%24}h`}function HeadlessBadge(){return jsxRuntimeExports.jsx("span",{className:"inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium bg-slate-500/10 text-slate-500 border border-slate-500/20",title:"Started via `claude -p` (non-interactive). Typically a script or pipeline invocation.",children:"headless"})}function DataTierBadge({tier:es}){return es==="full"?jsxRuntimeExports.jsx("span",{className:"inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium bg-teal-500/10 text-teal-600 border border-teal-500/20",children:"Full capture"}):es==="events"?jsxRuntimeExports.jsx("span",{className:"inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium bg-amber-500/10 text-amber-600 border border-amber-500/20",children:"Events only"}):null}function SortableHead({label:es,sortKey:$,currentKey:ts,currentDir:is,onSort:cs,className:Qr}){const ja=ts===$,Na=ja?is==="asc"?ArrowUp:ArrowDown:ArrowUpDown;return jsxRuntimeExports.jsx(TableHead,{className:`cursor-pointer select-none hover:text-foreground transition-colors ${Qr??""}`,onClick:()=>cs($),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[es,jsxRuntimeExports.jsx(Na,{className:`h-3 w-3 ${ja?"text-primary":"text-muted-foreground/50"}`})]})})}function SessionsListPage(){const es=useNavigate(),[$,ts]=useSearchParams(),is=$.get("outcome")??void 0,cs=$.get("friction")??void 0,Qr=$.get("instructionId")??void 0,ja=[is&&{key:"outcome",label:`outcome: ${is.replace(/_/g," ")}`},cs&&{key:"friction",label:`friction: ${cs.replace(/_/g," ")}`},Qr&&{key:"instructionId",label:"linked instruction"}].filter(Boolean),Na=dl=>{const fl=new URLSearchParams($);fl.delete(dl),ts(fl,{replace:!0})},{data:Aa,isLoading:Oa}=useSessions({hideEmpty:!0,outcome:is,friction:cs,instructionId:Qr}),[Ia,La]=reactExports.useState("date"),[Ba,Ma]=reactExports.useState("desc"),[qa,Fa]=reactExports.useState(new Set),[Ha,Ka]=reactExports.useState(new Set),Ga=useDeleteSession(),Va=dl=>{Ka(fl=>{const nl=new Set(fl);return nl.has(dl)?nl.delete(dl):nl.add(dl),nl})},Ja=dl=>{Fa(fl=>{const nl=new Set(fl);return nl.has(dl)?nl.delete(dl):nl.add(dl),nl})},Ya=()=>{rl&&(qa.size===rl.length?Fa(new Set):Fa(new Set(rl.map(dl=>dl.id))))},el=async()=>{const dl=[...qa];for(const fl of dl)await Ga.mutateAsync(fl);Fa(new Set)},tl=dl=>{dl===Ia?Ma(fl=>fl==="asc"?"desc":"asc"):(La(dl),Ma("desc"))},rl=Aa?[...Aa].sort((dl,fl)=>{const nl=Ba==="asc"?1:-1;switch(Ia){case"date":return nl*(new Date(dl.lastActivityAt??dl.startedAt).getTime()-new Date(fl.lastActivityAt??fl.startedAt).getTime());case"events":return nl*(dl.eventCount-fl.eventCount);case"project":return nl*projectDisplayName(dl).localeCompare(projectDisplayName(fl));default:return 0}}):void 0,cl=[];if(rl){let dl=null;for(const fl of rl){const nl=new Date(fl.startedAt).toISOString().slice(0,19),ol=`${fl.tool}|${fl.projectPath??"∅"}|${nl}`;dl&&dl.key===ol?dl.siblings.push(fl):(dl&&cl.push(dl),dl={key:ol,rep:fl,siblings:[]})}dl&&cl.push(dl)}return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx("div",{className:"flex items-start justify-between",children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Sessions"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Review AI coding sessions and analyze instruction performance"}),ja.length>0&&jsxRuntimeExports.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:ja.map(dl=>jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"cursor-pointer font-mono text-xs",onClick:()=>Na(dl.key),title:"Clear this filter",children:[dl.label,jsxRuntimeExports.jsx(X$1,{className:"ml-1 h-3 w-3"})]},dl.key))})]})}),qa.size>0&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:[qa.size," selected"]}),jsxRuntimeExports.jsxs(Button,{variant:"destructive",size:"sm",className:"h-8 text-xs cursor-pointer",onClick:el,disabled:Ga.isPending,children:[jsxRuntimeExports.jsx(Trash2,{className:"h-3 w-3 mr-1"}),Ga.isPending?"Deleting...":"Delete"]}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"h-8 text-xs cursor-pointer",onClick:()=>Fa(new Set),children:"Cancel"})]}),Oa?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:5}).map((dl,fl)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 w-full"},fl))}):rl!=null&&rl.length?jsxRuntimeExports.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"bg-card hover:bg-card",children:[jsxRuntimeExports.jsx(TableHead,{className:"w-10",children:jsxRuntimeExports.jsx("button",{role:"checkbox","aria-checked":!!rl&&qa.size===rl.length&&rl.length>0,"aria-label":"Select all sessions",className:"h-4 w-4 rounded border border-border cursor-pointer flex items-center justify-center text-xs hover:bg-secondary/50 transition-colors",onClick:Ya,children:rl&&qa.size===rl.length&&rl.length>0?"✓":""})}),jsxRuntimeExports.jsx(TableHead,{className:"w-48",children:"Tool"}),jsxRuntimeExports.jsx(SortableHead,{label:"Project",sortKey:"project",currentKey:Ia,currentDir:Ba,onSort:tl,className:"w-80"}),jsxRuntimeExports.jsx(TableHead,{className:"w-[28rem]",children:"Last message"}),jsxRuntimeExports.jsx(TableHead,{className:"w-24",children:"Branch"}),jsxRuntimeExports.jsx(SortableHead,{label:"Events",sortKey:"events",currentKey:Ia,currentDir:Ba,onSort:tl,className:"text-right"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Duration"}),jsxRuntimeExports.jsx(SortableHead,{label:"Last activity",sortKey:"date",currentKey:Ia,currentDir:Ba,onSort:tl,className:"text-right"})]})}),jsxRuntimeExports.jsx(TableBody,{children:cl.flatMap(dl=>{const fl=Ha.has(dl.key),nl=dl.siblings.length>0;return[{session:dl.rep,isSibling:!1},...fl?dl.siblings.map(hl=>({session:hl,isSibling:!0})):[]].map(({session:hl,isSibling:Tl})=>{var pl,jl;const ul=hl.analysis;return jsxRuntimeExports.jsxs(TableRow,{className:`cursor-pointer hover:bg-secondary/50 transition-colors ${qa.has(hl.id)?"bg-primary/5":""} ${Tl?"bg-muted/20":""}`,onClick:()=>es(`/sessions/${hl.id}`),children:[jsxRuntimeExports.jsx(TableCell,{onClick:Nl=>Nl.stopPropagation(),children:jsxRuntimeExports.jsx("button",{type:"button",role:"checkbox","aria-checked":qa.has(hl.id),"aria-label":"Select session",className:"h-4 w-4 rounded border border-border flex items-center justify-center text-xs hover:bg-secondary/50 transition-colors",onClick:Nl=>{Nl.stopPropagation(),Ja(hl.id)},children:qa.has(hl.id)?"✓":""})}),jsxRuntimeExports.jsxs(TableCell,{className:"w-48 align-top",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[nl&&!Tl?jsxRuntimeExports.jsx("button",{type:"button",className:"flex h-4 w-4 items-center justify-center rounded hover:bg-muted cursor-pointer shrink-0",onClick:Nl=>{Nl.stopPropagation(),Va(dl.key)},title:fl?"Collapse parallel sessions":"Expand parallel sessions",children:fl?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3"})}):Tl?jsxRuntimeExports.jsx("div",{className:"w-4 shrink-0"}):null,jsxRuntimeExports.jsx(ToolIcon,{tool:hl.tool,className:"h-4 w-4 text-muted-foreground shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm truncate",children:displayTool(hl.tool)})]}),(hl.dataTier||((pl=hl.metadata)==null?void 0:pl.headless)||nl&&!Tl)&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-1 mt-1 ml-6",children:[hl.dataTier&&jsxRuntimeExports.jsx(DataTierBadge,{tier:hl.dataTier}),((jl=hl.metadata)==null?void 0:jl.headless)&&jsxRuntimeExports.jsx(HeadlessBadge,{}),nl&&!Tl&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[9px] font-mono px-1 py-0 gap-1",children:[jsxRuntimeExports.jsx(Layers,{className:"h-2.5 w-2.5"}),"+",dl.siblings.length," parallel"]})]})]}),jsxRuntimeExports.jsxs(TableCell,{className:"font-mono text-sm text-muted-foreground w-80 max-w-80 align-top",children:[jsxRuntimeExports.jsx("div",{className:"truncate text-foreground",children:projectDisplayName(hl)}),hl.projectName&&(hl.primaryCheckoutPath||hl.projectPath)&&jsxRuntimeExports.jsx("div",{className:"truncate text-[10px] text-muted-foreground/70",children:hl.primaryCheckoutPath??hl.projectPath}),hl.linkedInstructions&&hl.linkedInstructions.length>0&&jsxRuntimeExports.jsxs("div",{className:"flex gap-1 mt-0.5 flex-wrap",children:[hl.linkedInstructions.slice(0,3).map((Nl,zl)=>{var Fl;const Zl=((Fl=Nl.contextIdentity)==null?void 0:Fl.split("::").pop())??Nl.name,Dl=Zl.split("/").pop()??Zl,Il=isGenerated(classifyProvenance({source:Nl.source},null));return jsxRuntimeExports.jsx(Badge,{variant:"outline",className:Il?"text-[9px] font-mono px-1 py-0 border-teal-400/40 text-teal-400":"text-[9px] font-mono px-1 py-0",title:Il?PROVENANCE_TOOLTIP:void 0,"data-testid":Il?"provenance-chip":void 0,children:Dl.length>20?Dl.slice(0,20)+"...":Dl},zl)}),hl.linkedInstructions.length>3&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[9px] font-mono px-1 py-0",children:["+",hl.linkedInstructions.length-3]})]})]}),jsxRuntimeExports.jsx(TableCell,{className:"text-sm text-muted-foreground w-[28rem] max-w-[28rem] align-top",children:jsxRuntimeExports.jsx("div",{className:"truncate",title:hl.lastMessagePreview??void 0,children:hl.lastMessagePreview??"—"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-sm text-muted-foreground w-24 max-w-24 truncate",title:hl.gitBranch??void 0,children:hl.gitBranch??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-right font-mono text-sm",children:hl.eventCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-sm text-muted-foreground",children:formatDuration(hl.startedAt,hl.lastActivityAt??hl.endedAt)}),jsxRuntimeExports.jsxs(TableCell,{className:"text-right text-sm text-muted-foreground whitespace-nowrap",children:[jsxRuntimeExports.jsx("div",{children:hl.lastActivityAt??hl.startedAt?new Date(hl.lastActivityAt??hl.startedAt).toLocaleString():"—"}),!!(ul!=null&&ul.outcome)&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[9px] mt-0.5",children:String(ul.outcome).replace(/_/g," ")})]})]},hl.id)})})})]})}):jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(Activity,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:"No sessions yet"}),jsxRuntimeExports.jsx("p",{className:"text-sm mt-1",children:"Import a session file or install Claude Code hooks to get started"})]})]})}function isAgentResponseEvent(es){return es.eventType==="assistant_response"||es.eventType==="assistant_message"}function eventUsage(es){var is;if(!es)return;const $=(is=es.metadata)==null?void 0:is.usage;if($&&typeof $=="object")return $;const ts=es.tokenUsage;if(ts)return{input_tokens:ts.input_tokens??ts.input,output_tokens:ts.output_tokens??ts.output,cache_read_input_tokens:ts.cache_read_input_tokens??ts.cacheRead,cache_creation_input_tokens:ts.cache_creation_input_tokens??ts.cacheWrite}}function isBlankAssistantMessage(es){return es.eventType==="assistant_message"&&(es.content==null||es.content.trim()==="")}function groupEventsIntoTurns(es){const $=[];let ts={userMessage:null,events:[],assistantResponse:null};for(const is of es)is.eventType==="user_message"?((ts.userMessage||ts.events.length>0)&&$.push(ts),ts={userMessage:is,events:[],assistantResponse:null}):(isAgentResponseEvent(is)&&(ts.assistantResponse=is),ts.events.push(is));return(ts.userMessage||ts.events.length>0)&&$.push(ts),$}function sessionEventCounts(es,$){if($)return{messages:$.messages,assistantResponses:$.assistantResponses,tools:$.toolCalls,total:$.total,partial:!1};const ts=es.filter(is=>is.eventType==="assistant_message"&&!isBlankAssistantMessage(is)).length;return{messages:es.filter(is=>is.eventType==="user_message").length+ts,assistantResponses:ts+es.filter(is=>{var cs;return is.eventType==="assistant_response"&&!!((cs=is.content)!=null&&cs.trim())}).length,tools:es.filter(is=>is.eventType==="tool_call").length,total:es.length,partial:!0}}const INJECTED_TYPES=new Set(["system_reminder","claude_md","agents_md","copilot_instructions","memory","skill_catalog","git_context","hook_output","deferred_tools"]);function getContextItems(es){const ts=(es.metadata??{}).contextItems??[];let is=0;for(const cs of ts)INJECTED_TYPES.has(cs.type)&&(cs.instruction_index==null&&(cs.instruction_index=is),is++);return ts}function useContextSnapshots(es){return useQuery({queryKey:["sessions",es,"context-snapshots"],queryFn:()=>apiGet(`/api/sessions/${es}/context-snapshots`),enabled:!!es,refetchInterval:POLL.ACTIVE})}function useContextSnapshotDetail(es){return useQuery({queryKey:["context-snapshots",es],queryFn:()=>apiGet(`/api/context-snapshots/${es}`),enabled:!!es})}function useLaunchJobs(){return useQuery({queryKey:["launch-jobs"],queryFn:()=>apiGet("/api/launch-jobs?limit=20"),refetchInterval:POLL.LIVE})}function useAvailableLaunchers(){return useQuery({queryKey:["launchers"],queryFn:()=>apiGet("/api/launchers"),staleTime:6e4})}function useCreateLaunchJob(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/launch-jobs",{tool:$.tool,config:{projectPath:$.projectPath,prompt:$.prompt,model:$.model,mode:$.mode,resumeSessionId:$.resumeSessionId}}),onSuccess:()=>{es.invalidateQueries({queryKey:["launch-jobs"]})}})}function useSessionTerminalTarget(es){return useQuery({queryKey:["terminal-target",es],queryFn:()=>apiGet(`/api/sessions/${es}/terminal-target`),enabled:!!es,refetchInterval:POLL.BACKGROUND})}function useSendMessage$1(es){const $=useQueryClient();return useMutation({mutationFn:ts=>apiPost(`/api/sessions/${es}/send`,ts),onSuccess:()=>{$.invalidateQueries({queryKey:["terminal-target",es]}),$.invalidateQueries({queryKey:["launch-jobs"]})}})}function SessionTargetSummary({target:es,capabilities:$,session:ts}){const is=(es==null?void 0:es.attachCommand)??(es!=null&&es.target?`tmux attach -t ${es.target}`:null),cs=ts.primaryCheckoutPath??ts.projectPath??null,Qr=displayTool(ts.tool);return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-md bg-card/60 px-4 py-3 text-xs space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono font-medium",children:[Qr,ts.externalSessionId&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" · ",ts.externalSessionId.slice(0,12)]})]}),cs&&jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono truncate max-w-[40ch]",children:cs}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),jsxRuntimeExports.jsxs(Badge,{variant:$.workerOnline?"default":"destructive",className:"text-[10px] font-mono",children:["worker ",$.workerOnline?"online":"offline"]}),es?jsxRuntimeExports.jsxs(Badge,{variant:es.status==="active"?"default":"outline",className:"text-[10px] font-mono",children:["tmux ",es.status]}):jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono",children:"no tmux target"})]}),es&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-muted-foreground",children:[jsxRuntimeExports.jsx(Terminal,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:es.target}),is&&jsxRuntimeExports.jsx(CopyButton$1,{text:is,label:"Copy attach"})]}),!es&&$.fallbackResume&&ts.externalSessionId&&jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground",children:["No live tmux target. Fallback resume will spawn a new terminal via"," ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"claude --resume"}),"."]})]})}function CopyButton$1({text:es,label:$}){const{copied:ts,copy:is}=useCopyToClipboard(1500);return jsxRuntimeExports.jsxs(Button,{type:"button",size:"sm",variant:"ghost",className:"h-6 px-2 text-[10px] font-mono cursor-pointer gap-1",onClick:cs=>{cs.stopPropagation(),is(es)},children:[ts?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),jsxRuntimeExports.jsx("span",{className:"truncate max-w-[28ch]",children:ts?"Copied":$})]})}function ProvenanceBadge({source:es,frontmatter:$,className:ts}){const is=es==="insights"||es==="evolution"?es:readStampedSource($),cs=provenanceLabel(is);return!is||!cs?null:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("border-teal-400/40 text-teal-400 text-[10px] font-normal shrink-0",ts),title:PROVENANCE_TOOLTIP,"data-testid":`provenance-${is}`,children:cs})}const LINK_METHOD_LABELS={project_match:"Auto-linked via project",auto_capture:"Auto-captured",manual:"Manually linked",context_file:"Context file"};function InstructionCard({instruction:es}){const[$,ts]=reactExports.useState(!1),is=es.content.slice(0,200),cs=es.content.length>200;return jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsxs("div",{className:"px-4 py-3 cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(FileText,{className:"h-4 w-4 text-primary shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium",children:es.name}),jsxRuntimeExports.jsx(ProvenanceBadge,{source:es.source}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:es.scope}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:LINK_METHOD_LABELS[es.linkMethod]??es.linkMethod}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),!$&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground mt-1 truncate",children:[is,cs&&"..."]})]}),$&&jsxRuntimeExports.jsx(CardContent,{className:"pt-0 pb-3",children:jsxRuntimeExports.jsx("pre",{className:"p-3 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-96 overflow-y-auto whitespace-pre-wrap break-words",children:es.content})})]})}const CATEGORY_ORDER=["instructions","memory","agents","commands","skills","settings"];function extractCategory(es){const $=es.frontmatter;if($&&typeof $.category=="string")return $.category;const ts=es.name.match(/\[([^\]]+)\]$/);return ts?ts[1]:"other"}function cleanName(es){return es.replace(/\s*\[[^\]]+\]$/,"")}function ContextFileRow({instruction:es}){const[$,ts]=reactExports.useState(!1);return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 cursor-pointer hover:bg-secondary/30 transition-colors rounded",...activatable(()=>ts(!$)),children:[jsxRuntimeExports.jsx(FileText,{className:"h-3 w-3 text-teal-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-xs",children:cleanName(es.name)}),jsxRuntimeExports.jsx(ProvenanceBadge,{source:es.source}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3 text-muted-foreground"})]}),$&&jsxRuntimeExports.jsx("div",{className:"ml-5 mr-3 mb-2",children:jsxRuntimeExports.jsx("pre",{className:"p-3 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-96 overflow-y-auto whitespace-pre-wrap break-words",children:es.content})})]})}function ContextBlock({instructions:es}){const[$,ts]=reactExports.useState(!1),is=reactExports.useMemo(()=>{const ja={};for(const Na of es){const Aa=extractCategory(Na);ja[Aa]||(ja[Aa]=[]),ja[Aa].push(Na)}return ja},[es]),cs=reactExports.useMemo(()=>es.filter(ja=>isGenerated(classifyProvenance({source:ja.source},null))).length,[es]),Qr=reactExports.useMemo(()=>Object.keys(is).sort((Na,Aa)=>{const Oa=CATEGORY_ORDER.indexOf(Na),Ia=CATEGORY_ORDER.indexOf(Aa);return(Oa===-1?999:Oa)-(Ia===-1?999:Ia)}),[is]);return jsxRuntimeExports.jsxs("div",{className:"mb-4",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-teal-500 rounded-lg bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[jsxRuntimeExports.jsx(FileText,{className:"h-3.5 w-3.5 text-teal-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:"Session Context"}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs font-mono",children:es.length}),cs>0&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"border-teal-400/40 text-teal-400 text-[10px] font-normal shrink-0",title:PROVENANCE_TOOLTIP,"data-testid":"provenance-insights",children:cs===1?"from insights":`${cs} from insights`}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),jsxRuntimeExports.jsx("div",{className:"flex items-center gap-1.5",children:!$&&Qr.map(ja=>jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"text-xs font-mono",children:[ja," ",is[ja].length]},ja))}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&jsxRuntimeExports.jsx("div",{className:"ml-4 mt-2 space-y-3",children:Qr.map(ja=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground font-medium uppercase tracking-wider mb-1 px-3",children:ja}),jsxRuntimeExports.jsx("div",{children:is[ja].map(Na=>jsxRuntimeExports.jsx(ContextFileRow,{instruction:Na},Na.instructionId))})]},ja))})]})}const PROVIDER_COLORS={anthropic:"bg-orange-500/10 text-orange-600 border-orange-500/20",openai:"bg-teal-500/10 text-teal-600 border-teal-500/20",azure_openai:"bg-blue-500/10 text-blue-600 border-blue-500/20",gemini:"bg-pink-500/10 text-pink-600 border-pink-500/20",bedrock:"bg-amber-500/10 text-amber-600 border-amber-500/20",ollama:"bg-gray-500/10 text-gray-600 border-gray-500/20"};function formatTokenCount(es){return es==null?"0":es>=1e3?`${(es/1e3).toFixed(1)}K`:String(es)}function formatEventTimestamp(es){const $=new Date(es),ts=new Date,is=ts.getTime()-$.getTime(),cs=Math.floor(is/6e4),Qr=$.toDateString()===ts.toDateString();return cs<1?"just now":cs<60?`${cs}m ago`:Qr?$.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):$.toLocaleDateString([],{month:"numeric",day:"numeric",year:"numeric"})+" "+$.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function UserBubble({event:es}){return jsxRuntimeExports.jsxs("div",{className:"mt-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[jsxRuntimeExports.jsx(User,{className:"h-4 w-4 text-blue-500"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:"You"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)})]}),jsxRuntimeExports.jsx("div",{className:"bg-blue-500/10 border border-blue-500/20 rounded-lg px-4 py-3 max-w-[85%]",children:jsxRuntimeExports.jsx("p",{className:"text-sm whitespace-pre-wrap break-words",children:es.content})})]})}function AssistantBubble({event:es}){const $=es.content??"",ts=/\[tool_use:\s*([^\]]+)\]/g,is=[];let cs=0,Qr;for(;(Qr=ts.exec($))!==null;)Qr.index>cs&&is.push({type:"text",value:$.slice(cs,Qr.index)}),is.push({type:"tool",value:Qr[1]}),cs=Qr.index+Qr[0].length;return cs<$.length&&is.push({type:"text",value:$.slice(cs)}),jsxRuntimeExports.jsxs("div",{className:"mt-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[jsxRuntimeExports.jsx(Brain,{className:"h-4 w-4 text-primary"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:"Assistant"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)})]}),jsxRuntimeExports.jsx("div",{className:"bg-secondary/50 border border-border rounded-lg px-4 py-3",children:jsxRuntimeExports.jsx("div",{className:"text-sm whitespace-pre-wrap break-words",children:is.length>0?is.map((ja,Na)=>ja.type==="tool"?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"mx-1 text-xs font-mono",children:ja.value},Na):jsxRuntimeExports.jsx("span",{children:ja.value},Na)):$})})]})}function ToolCallCard({event:es}){const[$,ts]=reactExports.useState(!1),is=es.metadata??{},cs=is.durationMs,Qr=is.success;return jsxRuntimeExports.jsxs("div",{className:"ml-8 mt-2",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-amber-500 rounded-lg px-3 py-2 bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Terminal,{className:"h-3.5 w-3.5 text-amber-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm",children:es.toolName}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)}),cs!=null&&jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:cs<1e3?`${cs}ms`:`${(cs/1e3).toFixed(1)}s`}),Qr!=null&&(Qr?jsxRuntimeExports.jsx(Check,{className:"h-3.5 w-3.5 text-teal-500"}):jsxRuntimeExports.jsx(X$1,{className:"h-3.5 w-3.5 text-destructive"})),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&jsxRuntimeExports.jsxs("div",{className:"ml-4 mt-1 space-y-2",children:[es.toolInput&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Input"}),jsxRuntimeExports.jsx("pre",{className:"p-2 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-64 overflow-y-auto",children:JSON.stringify(es.toolInput,null,2)})]}),es.toolOutput&&Object.keys(es.toolOutput).length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Output"}),jsxRuntimeExports.jsx("pre",{className:"p-2 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-64 overflow-y-auto",children:JSON.stringify(es.toolOutput,null,2)})]}),es.content&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Content"}),jsxRuntimeExports.jsx("pre",{className:"p-2 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-64 overflow-y-auto whitespace-pre-wrap break-words",children:es.content})]})]})]})}function ThinkingBubble({event:es}){const[$,ts]=reactExports.useState(!0),is=es.content??"",cs=is.slice(0,150);return jsxRuntimeExports.jsxs("div",{className:"ml-8 mt-2",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-rose-500 rounded-lg px-3 py-2 bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Brain,{className:"h-3.5 w-3.5 text-rose-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-sm text-muted-foreground italic",children:$?"Thinking":`${cs}${is.length>150?"...":""}`}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&jsxRuntimeExports.jsx("div",{className:"ml-4 mt-1",children:jsxRuntimeExports.jsx("p",{className:"text-sm italic text-muted-foreground whitespace-pre-wrap break-words",children:is})})]})}function ToolResultCard({event:es}){const[$,ts]=reactExports.useState(!0),is=es.content??"",cs=is.slice(0,200),ja=(es.metadata??{}).toolUseId??es.toolName;return jsxRuntimeExports.jsxs("div",{className:"ml-8 mt-2",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-teal-500 rounded-lg px-3 py-2 bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Check,{className:"h-3.5 w-3.5 text-teal-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:"Result"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)}),ja&&jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:ja}),!$&&is&&jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground truncate max-w-xs",children:[cs,is.length>200?"...":""]}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&is&&jsxRuntimeExports.jsx("div",{className:"ml-4 mt-1",children:jsxRuntimeExports.jsx("pre",{className:"p-2 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-64 overflow-y-auto whitespace-pre-wrap break-words",children:is})})]})}function GenericEvent({event:es}){return jsxRuntimeExports.jsx("div",{className:"mt-2 ml-4",children:jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg px-3 py-2 bg-card/50",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:es.eventType.replace(/_/g," ")}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)})]}),es.content&&jsxRuntimeExports.jsxs("p",{className:"text-sm mt-1 text-muted-foreground whitespace-pre-wrap break-words",children:[es.content.slice(0,300),es.content.length>300&&"..."]})]})})}function TokenUsageBar({usage:es}){const $=es.input_tokens??0,ts=es.output_tokens??0,is=es.cache_read_input_tokens??0,cs=es.cache_creation_input_tokens??0,Qr=$+ts+is+cs;if(Qr===0)return null;const ja=[{value:is,color:"bg-teal-500",label:"cache read"},{value:cs,color:"bg-amber-500",label:"cache write"},{value:$,color:"bg-blue-500",label:"input"},{value:ts,color:"bg-primary",label:"output"}].filter(Na=>Na.value>0);return jsxRuntimeExports.jsxs("div",{className:"mt-2",children:[jsxRuntimeExports.jsx("div",{className:"h-1.5 rounded-full bg-secondary overflow-hidden flex",children:ja.map(Na=>jsxRuntimeExports.jsx("div",{className:`${Na.color} h-full`,style:{width:`${Na.value/Qr*100}%`},title:`${Na.label}: ${formatTokenCount(Na.value)}`},Na.label))}),jsxRuntimeExports.jsx("div",{className:"flex gap-3 mt-1",children:ja.map(Na=>jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[jsxRuntimeExports.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${Na.color}`}),formatTokenCount(Na.value)," ",Na.label]},Na.label))})]})}function AssistantResponseCard({event:es}){const $=es.metadata??{},ts=eventUsage(es),is=$.stop_reason,cs=$.content_block_types,Qr=$.model,ja=$.response_time_ms,Na=$.streaming;return jsxRuntimeExports.jsx("div",{className:"mt-3 ml-8",children:jsxRuntimeExports.jsxs("div",{className:"bg-primary/5 border border-primary/20 rounded-lg px-4 py-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(Sparkles,{className:"h-3.5 w-3.5 text-primary shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium text-primary",children:"Response"}),Qr&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono px-1.5 py-0 border-primary/30 text-primary/80",children:Qr}),ja!=null&&jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[jsxRuntimeExports.jsx(Clock,{className:"h-3 w-3"}),ja<1e3?`${ja}ms`:`${(ja/1e3).toFixed(1)}s`]}),is&&jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-[10px] font-mono px-1.5 py-0",children:is}),Na&&jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"stream"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:formatEventTimestamp(es.timestamp)})]}),ts&&jsxRuntimeExports.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[ts.output_tokens>0&&jsxRuntimeExports.jsxs("span",{className:"text-[11px] font-mono bg-primary/10 text-primary px-2 py-0.5 rounded-full",children:[formatTokenCount(ts.output_tokens)," out"]}),ts.input_tokens>0&&jsxRuntimeExports.jsxs("span",{className:"text-[11px] font-mono bg-blue-500/10 text-blue-400 px-2 py-0.5 rounded-full",children:[formatTokenCount(ts.input_tokens)," in"]}),ts.cache_read_input_tokens>0&&jsxRuntimeExports.jsxs("span",{className:"text-[11px] font-mono bg-teal-500/10 text-teal-400 px-2 py-0.5 rounded-full",children:[formatTokenCount(ts.cache_read_input_tokens)," cache"]}),ts.cache_creation_input_tokens>0&&jsxRuntimeExports.jsxs("span",{className:"text-[11px] font-mono bg-amber-500/10 text-amber-400 px-2 py-0.5 rounded-full",children:[formatTokenCount(ts.cache_creation_input_tokens)," cached"]})]}),es.content&&jsxRuntimeExports.jsx("div",{className:"mt-2 text-sm text-foreground/90 whitespace-pre-wrap break-words leading-relaxed",children:es.content}),cs&&Object.keys(cs).length>0&&jsxRuntimeExports.jsx("div",{className:"flex gap-2 mt-2",children:Object.entries(cs).map(([Aa,Oa])=>jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[Aa,"(",Oa,")"]},Aa))}),ts&&jsxRuntimeExports.jsx(TokenUsageBar,{usage:ts})]})})}function renderEvent(es){switch(es.eventType){case"user_message":return jsxRuntimeExports.jsx(UserBubble,{event:es});case"assistant_message":return isBlankAssistantMessage(es)?jsxRuntimeExports.jsx(AssistantResponseCard,{event:es}):jsxRuntimeExports.jsx(AssistantBubble,{event:es});case"assistant_response":return jsxRuntimeExports.jsx(AssistantResponseCard,{event:es});case"tool_call":return jsxRuntimeExports.jsx(ToolCallCard,{event:es});case"thinking":return jsxRuntimeExports.jsx(ThinkingBubble,{event:es});case"tool_result":return jsxRuntimeExports.jsx(ToolResultCard,{event:es});default:return jsxRuntimeExports.jsx(GenericEvent,{event:es})}}function InlineTurnSnapshot({snapshot:es}){var Aa;const[$,ts]=reactExports.useState(!1),{data:is}=useContextSnapshotDetail($?es.id:void 0),cs=is??es,Qr=reactExports.useMemo(()=>$?getContextItems(cs):[],[$,cs]),ja=reactExports.useMemo(()=>{var Ia;return((es.metadata??{}).contextItems??[]).length||(((Ia=es.injectedInstructions)==null?void 0:Ia.length)??0)},[es]),Na=PROVIDER_COLORS[es.provider]??PROVIDER_COLORS.ollama;return jsxRuntimeExports.jsxs("div",{className:"ml-8 mt-2",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-cyan-500 rounded-lg px-3 py-2 bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(Eye,{className:"h-3.5 w-3.5 text-cyan-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-xs font-medium text-cyan-600 dark:text-cyan-400",children:"Snapshot"}),jsxRuntimeExports.jsx(Badge,{className:`text-[10px] font-mono border ${Na} px-1.5 py-0`,children:es.provider}),jsxRuntimeExports.jsx("span",{className:"text-[11px] font-mono text-muted-foreground",children:es.model}),jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["~",(es.estimatedTokens??0).toLocaleString()," tok"]}),ja>0&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[ja," context items"]}),Array.isArray(es.tools)&&es.tools.length>0&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[es.tools.length," tools"]}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&jsxRuntimeExports.jsx("div",{className:"ml-4 mt-2 space-y-2",children:is?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Qr.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Context Items"}),Object.entries(Qr.reduce((Oa,Ia)=>{var La;return(Oa[La=Ia.type]??(Oa[La]=[])).push(Ia),Oa},{})).map(([Oa,Ia])=>jsxRuntimeExports.jsxs("div",{className:"mb-1",children:[jsxRuntimeExports.jsxs("p",{className:"text-[10px] font-medium text-muted-foreground/70 capitalize mb-0.5",children:[Oa.replace(/_/g," ")," (",Ia.length,")"]}),Ia.map((La,Ba)=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 text-xs font-mono text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"truncate",children:La.name}),La.estimated_tokens!=null&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] shrink-0",children:["~",La.estimated_tokens.toLocaleString()," tok"]})]},Ba))]},Oa))]}),cs.systemPrompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:["System prompt: ",(cs.systemPrompt.length??0).toLocaleString()," chars"]}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-[10px]",children:["hash: ",((Aa=cs.systemHash)==null?void 0:Aa.slice(0,12))??"..."]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground flex-wrap",children:[cs.maxTokens!=null&&jsxRuntimeExports.jsxs("span",{children:["Max tokens: ",cs.maxTokens.toLocaleString()]}),cs.temperature!=null&&jsxRuntimeExports.jsxs("span",{children:["Temp: ",cs.temperature]}),Array.isArray(cs.tools)&&jsxRuntimeExports.jsxs("span",{children:[cs.tools.length," tools available"]})]})]}):jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 py-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin"}),"Loading snapshot..."]})})]})}function TurnContainer({turn:es,index:$,totalTurns:ts,snapshot:is,hideSnapshot:cs}){var Aa,Oa,Ia,La,Ba;const Qr=es.events.filter(Ma=>Ma.eventType==="tool_call").length,ja=eventUsage(es.assistantResponse)??((Aa=is==null?void 0:is.metadata)==null?void 0:Aa.usage),Na=ja==null?void 0:ja.output_tokens;return((Ia=(Oa=es.assistantResponse)==null?void 0:Oa.metadata)==null?void 0:Ia.response_time_ms)??((Ba=(La=is==null?void 0:is.metadata)==null?void 0:La.responseHeaders)==null||Ba["server-timing"]),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 pt-6 pb-2",children:[jsxRuntimeExports.jsxs("div",{className:"text-xs font-mono text-muted-foreground/60",children:["Turn ",ts-$]}),jsxRuntimeExports.jsx("div",{className:"h-px flex-1 bg-border/50"}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[Qr>0&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[Qr," tool",Qr!==1?"s":""]}),Na!=null&&Na>0&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[jsxRuntimeExports.jsx(Zap,{className:"h-2.5 w-2.5"}),formatTokenCount(Na)," tokens"]})]})]}),jsxRuntimeExports.jsxs("div",{className:"relative pl-6",children:[jsxRuntimeExports.jsx("div",{className:"absolute left-[11px] top-0 bottom-0 w-px bg-border/40"}),es.userMessage&&jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("div",{className:"absolute left-[-17px] top-4 w-2 h-2 rounded-full bg-blue-500 ring-2 ring-background"}),jsxRuntimeExports.jsx(UserBubble,{event:es.userMessage})]}),es.events.map(Ma=>{if(Ma.eventType==="assistant_response")return jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("div",{className:"absolute left-[-17px] top-4 w-2 h-2 rounded-full bg-primary ring-2 ring-background"}),jsxRuntimeExports.jsx(AssistantResponseCard,{event:Ma})]},Ma.id);const qa=Ma.eventType==="tool_call"?"bg-amber-500":Ma.eventType==="thinking"?"bg-rose-500":Ma.eventType==="tool_result"?"bg-teal-500":Ma.eventType==="assistant_message"?"bg-primary":"bg-muted-foreground";return jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("div",{className:`absolute left-[-17px] top-3 w-2 h-2 rounded-full ${qa} ring-2 ring-background`}),renderEvent(Ma)]},Ma.id)}),is&&!cs&&jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("div",{className:"absolute left-[-17px] top-3 w-2 h-2 rounded-full bg-cyan-500 ring-2 ring-background"}),jsxRuntimeExports.jsx(InlineTurnSnapshot,{snapshot:is})]})]})]})}function SessionDetailPage(){var ic,Iu;const{id:es}=useParams(),[$,ts]=useSearchParams(),{data:is,isLoading:cs}=useSession(es),{data:Qr,isLoading:ja,hasNextPage:Na,fetchNextPage:Aa,isFetchingNextPage:Oa}=useSessionEventsInfinite(es),Ia=useAnalyzeSession(),La=useCreateLaunchJob(),Ba=(ic=Ia.data)==null?void 0:ic.jobId,{data:Ma}=useInsightsJob(Ba),[qa,Fa]=reactExports.useState(""),{data:Ha}=useContextSnapshots(es),Ka=$.get("filter"),[Ga,Va]=reactExports.useState(Ka??"turns"),Ja=$.get("layout"),[Ya,el]=reactExports.useState(Ja??"default"),tl=reactExports.useMemo(()=>(Qr==null?void 0:Qr.pages.flat())??[],[Qr]),rl=reactExports.useMemo(()=>{switch(Ga){case"conversation":return tl.filter(Bl=>Bl.eventType==="user_message"||isAgentResponseEvent(Bl));case"tools":return tl.filter(Bl=>Bl.eventType==="tool_call");case"responses":return tl.filter(isAgentResponseEvent);default:return tl}},[tl,Ga]),cl=reactExports.useMemo(()=>groupEventsIntoTurns([...tl].sort((Bl,ru)=>Bl.sequence-ru.sequence)),[tl]),dl=reactExports.useMemo(()=>((is==null?void 0:is.linkedInstructions)??[]).filter(Bl=>Bl.linkMethod==="context_file"),[is==null?void 0:is.linkedInstructions]),fl=reactExports.useMemo(()=>((is==null?void 0:is.linkedInstructions)??[]).filter(Bl=>Bl.linkMethod!=="context_file"),[is==null?void 0:is.linkedInstructions]),nl=reactExports.useMemo(()=>sessionEventCounts(tl,is==null?void 0:is.eventCounts),[is==null?void 0:is.eventCounts,tl]);if(cs)return jsxRuntimeExports.jsx(Skeleton,{className:"h-96 w-full"});if(!is)return jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Session not found"});const ol=is.analysis,hl=ol==null?void 0:ol.adherenceScore,Tl=ol==null?void 0:ol.summary,ul=ol==null?void 0:ol.suggestions,pl=ol==null?void 0:ol.brief_summary,jl=ol==null?void 0:ol.underlying_goal,Nl=ol==null?void 0:ol.outcome,zl=ol==null?void 0:ol.session_type,Zl=ol==null?void 0:ol.goal_categories,Dl=ol==null?void 0:ol.friction_counts,Il=ol==null?void 0:ol.friction_detail,Fl=ol==null?void 0:ol.primary_success,ql=ol==null?void 0:ol.tool,nu=is.analyzedAt??(ol==null?void 0:ol.analyzed_at),Gl=is.analyzedEventCount??(ol==null?void 0:ol.analyzed_event_count),cu=is.analyzedTurnCount??(ol==null?void 0:ol.analyzed_turn_count),Al=!!pl||!!jl,Ml=Object.values(Dl??{}).reduce((Bl,ru)=>Bl+ru,0),Ql=is.endedAt?Math.max(0,Math.round((new Date(is.endedAt).getTime()-new Date(is.startedAt).getTime())/6e4)):null,eu=ol?jsxRuntimeExports.jsxs("div",{className:`mt-2 flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs ${nu?"border-border bg-muted/40 text-foreground":"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300"}`,children:[jsxRuntimeExports.jsx(Clock,{className:"h-3.5 w-3.5 shrink-0"}),jsxRuntimeExports.jsx("div",{className:"flex-1 font-mono",children:nu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:"Analyzed"})," ",formatEventTimestamp(nu),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" ","(",new Date(nu).toLocaleString(),")"]}),(cu!=null||Gl!=null)&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" · ",cu!=null&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["through turn ",cu]}),Gl!=null&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[cu!=null?" ":"","(",Gl," event",Gl===1?"":"s",")"]})]})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:"Analyzed at unknown time"})," — ","this analysis predates timestamp tracking. Re-analyze to record when it ran and which turn it covered."]})}),!nu&&canAnalyzeWithToolCli(is.tool)&&jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",className:"h-7 cursor-pointer text-xs",onClick:()=>Ia.mutate(is.id),disabled:Ia.isPending||Ia.isSuccess,children:Ia.isPending?"Submitting...":Ia.isSuccess?"Queued":"Re-analyze"})]}):null,fu=(is.metadata??{}).clientName,Ou=[{key:"turns",label:"Turns"},{key:"all",label:"All"},{key:"conversation",label:"Conversation"},{key:"tools",label:"Tools"},{key:"responses",label:"Responses"}],yu=(()=>{if(is.tool!=="claude_code"||!is.externalSessionId)return!1;if(!is.endedAt||new Date(is.endedAt).getTime()<new Date(is.startedAt).getTime())return!0;const Bl=10080*60*1e3;return Date.now()-new Date(is.endedAt).getTime()<Bl})();return jsxRuntimeExports.jsxs("div",{className:`space-y-6 ${yu?"pb-40":""}`,children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"icon",className:"cursor-pointer shrink-0",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/sessions",children:jsxRuntimeExports.jsx(ArrowLeft,{className:"h-4 w-4"})})}),jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Session Detail"}),is.gitBranch&&jsxRuntimeExports.jsxs("span",{title:`git branch: ${is.gitBranch}`,className:"inline-flex items-center gap-1.5 rounded-md border border-primary/40 bg-primary/10 px-2.5 py-1 font-mono text-sm font-semibold text-primary max-w-[11rem] sm:max-w-[18rem] truncate",children:[jsxRuntimeExports.jsx(GitBranch,{className:"h-4 w-4 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:is.gitBranch})]})]}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground font-mono text-sm flex items-center gap-1.5 flex-wrap",children:[jsxRuntimeExports.jsx(ToolIcon,{tool:is.tool,className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{children:displayTool(is.tool)}),is.harnessVersion&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/60",title:"harness version",children:["v",is.harnessVersion]}),fu&&jsxRuntimeExports.jsxs("span",{children:["(",fu,")"]}),is.model&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{children:"·"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground/80",title:"model (rolled up from the transcript)",children:is.model})]}),jsxRuntimeExports.jsx("span",{children:"·"}),jsxRuntimeExports.jsx("span",{children:projectDisplayName(is)}),jsxRuntimeExports.jsx("span",{children:"·"}),jsxRuntimeExports.jsx("span",{children:formatEventTimestamp(is.startedAt)})," ",jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/60",children:["(",is.startedAt?new Date(is.startedAt).toLocaleString():"—",")"]})]}),nl.total>0&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[nl.partial&&"Loaded events: ",nl.messages," messages, ",nl.tools," tool calls",nl.assistantResponses>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[", ",nl.assistantResponses," responses"]})]})]})]}),jsxRuntimeExports.jsx("div",{className:"flex items-center gap-2",children:!ol&&canAnalyzeWithToolCli(is.tool)&&jsxRuntimeExports.jsx(Button,{onClick:()=>Ia.mutate(is.id),disabled:Ia.isPending||Ia.isSuccess,className:"cursor-pointer bg-primary text-primary-foreground",children:Ia.isPending?"Submitting...":Ia.isSuccess?"Analysis queued...":`Analyze via ${displayTool(is.tool)}`})})]}),jsxRuntimeExports.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[jsxRuntimeExports.jsx(Card,{className:"bg-card",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Outcome"}),jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[Nl==="achieved"||Nl==="mostly_achieved"?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 text-teal-500"}):jsxRuntimeExports.jsx(CircleHelp,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-lg font-semibold capitalize",children:(Nl==null?void 0:Nl.replace(/_/g," "))??"Not analyzed"})]})]})}),jsxRuntimeExports.jsx(Card,{className:"bg-card",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Activity"}),jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"h-4 w-4 text-blue-500"}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-lg font-semibold",children:[nl.messages," messages",nl.partial&&" (loaded)"]})]}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[nl.tools," tool calls · ",nl.total," events"]})]})}),jsxRuntimeExports.jsx(Card,{className:"bg-card",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Elapsed time"}),jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(Clock,{className:"h-4 w-4 text-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-lg font-semibold",children:Ql==null?"In progress":Ql<60?`${Ql}m`:`${Math.floor(Ql/60)}h ${Ql%60}m`})]})]})}),jsxRuntimeExports.jsx(Card,{className:Ml>0?"border-amber-500/30 bg-amber-500/5":"bg-card",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Friction"}),jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:`h-4 w-4 ${Ml?"text-amber-500":"text-muted-foreground"}`}),jsxRuntimeExports.jsx("span",{className:"font-mono text-lg font-semibold",children:ol?`${Ml} signal${Ml===1?"":"s"}`:"Unknown"})]})]})})]}),(jl||pl)&&jsxRuntimeExports.jsx(Card,{className:"border-primary/20 bg-primary/[0.03]",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-5",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Session goal"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-base font-medium",children:jl??pl}),jl&&pl&&jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:pl})]})}),Ma&&Ma.status!=="completed"&&jsxRuntimeExports.jsx(Card,{className:"bg-card border-border border-l-2 border-l-primary",children:jsxRuntimeExports.jsx(CardContent,{className:"pt-4 pb-4",children:jsxRuntimeExports.jsx("div",{className:"flex items-center gap-3",children:Ma.status==="failed"?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4 text-destructive"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium text-destructive",children:"Analysis failed"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:Ma.error})]})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin text-primary"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("p",{className:"text-sm font-medium",children:[Ma.status==="pending"&&"Waiting for worker...",Ma.status==="claimed"&&"Worker picked up job...",Ma.status==="running"&&"Analyzing session..."]}),!!((Iu=Ma.progress)!=null&&Iu.step)&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:[String(Ma.progress.step).replace(/_/g," "),!!Ma.progress.tool&&` via ${displayTool(String(Ma.progress.tool))}`]})]})]})})})}),ol&&Al?jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs(CardTitle,{className:"font-mono text-lg flex items-center gap-2",children:["Analysis",Nl&&jsxRuntimeExports.jsx(Badge,{variant:Nl==="achieved"||Nl==="mostly_achieved"?"default":Nl==="partially_achieved"?"secondary":"destructive",className:"font-mono",children:Nl.replace(/_/g," ")}),zl&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs",children:zl.replace(/_/g," ")}),ql&&jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:["via ",displayTool(ql)]})]}),eu]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[pl&&jsxRuntimeExports.jsx("p",{className:"text-sm",children:pl}),jl&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Goal"}),jsxRuntimeExports.jsx("p",{className:"text-sm",children:jl})]}),Fl&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Primary Success"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-teal-600 dark:text-teal-400",children:Fl})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[Zl&&Object.keys(Zl).length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Goal Categories"}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1.5",children:Object.entries(Zl).filter(([,Bl])=>Bl>0).sort(([,Bl],[,ru])=>ru-Bl).map(([Bl,ru])=>jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"text-xs font-mono",children:[Bl.replace(/_/g," ")," ",ru>1?`(${ru})`:""]},Bl))})]}),Dl&&Object.values(Dl).some(Bl=>Bl>0)&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Friction Points"}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1.5",children:Object.entries(Dl).filter(([,Bl])=>Bl>0).sort(([,Bl],[,ru])=>ru-Bl).map(([Bl,ru])=>jsxRuntimeExports.jsxs(Badge,{variant:"destructive",className:"text-xs font-mono",children:[Bl.replace(/_/g," ")," (",ru,")"]},Bl))}),Il&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:Il})]})]})]})]}):ol&&jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs(CardTitle,{className:"font-mono text-lg flex items-center gap-2",children:["Analysis",hl!=null&&jsxRuntimeExports.jsxs(Badge,{variant:hl>=80?"default":hl>=50?"secondary":"destructive",className:"font-mono",children:[hl,"% adherence"]})]}),eu]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:Tl}),ul&&ul.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-2",children:"Suggestions"}),ul.map((Bl,ru)=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded p-3 mb-2 bg-background",children:[jsxRuntimeExports.jsx("p",{className:"text-sm",children:Bl.rationale}),jsxRuntimeExports.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Current"}),jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono p-2 bg-card rounded",children:Bl.currentContent})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-primary mb-1",children:"Suggested"}),jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono p-2 bg-card rounded border-primary/20 border",children:Bl.suggestedContent})]})]})]},ru))]})]})]}),jsxRuntimeExports.jsxs(TooltipProvider,{children:[(dl.length>0||fl.length>0)&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[dl.length>0&&jsxRuntimeExports.jsx(ContextBlock,{instructions:dl}),fl.length>0&&fl.map(Bl=>jsxRuntimeExports.jsx(InstructionCard,{instruction:Bl},Bl.instructionId))]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-4",children:[jsxRuntimeExports.jsxs("h3",{className:"text-sm font-medium flex items-center gap-1.5",children:["Timeline",jsxRuntimeExports.jsx(InfoTip,{content:"Conversation turns between you and the AI, including tool calls, thinking, and responses. Proxy snapshots show the exact context sent to the LLM for each turn."})]}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1 ml-auto",children:Ou.map(Bl=>jsxRuntimeExports.jsx(Badge,{asChild:!0,className:"py-1",variant:Ga===Bl.key?"default":"outline",children:jsxRuntimeExports.jsx("button",{type:"button",className:"cursor-pointer",onClick:()=>Va(Bl.key),children:Bl.label})},Bl.key))}),((Ha==null?void 0:Ha.length)??0)>0&&jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"text-xs font-mono shrink-0",children:[Ha.length," snapshots"]})]}),Ga==="turns"&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-3 text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono",children:"Layout"}),[{key:"default",label:"Inline"},{key:"split",label:"Side panel"},{key:"capped",label:"Capped + summary"}].map(Bl=>jsxRuntimeExports.jsx(Badge,{asChild:!0,className:"py-1",variant:Ya===Bl.key?"default":"outline",children:jsxRuntimeExports.jsx("button",{type:"button",className:"cursor-pointer",onClick:()=>{el(Bl.key);const ru=new URLSearchParams($);Bl.key==="default"?ru.delete("layout"):ru.set("layout",Bl.key),ts(ru,{replace:!0})},children:Bl.label})},Bl.key))]}),ja?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:10}).map((Bl,ru)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-16 w-full"},ru))}):Ga==="turns"?jsxRuntimeExports.jsxs("div",{children:[cl.length===0&&((Ha==null?void 0:Ha.length)??0)===0?jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(FileText,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:"No activity captured"}),jsxRuntimeExports.jsxs("p",{className:"text-sm mt-1",children:["Use ",jsxRuntimeExports.jsx("code",{className:"font-mono text-xs bg-secondary px-1 py-0.5 rounded",children:"rulemetric proxy start"})," to capture LLM context, or install hooks for event capture"]})]}):cl.length===0?jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground py-8 text-center",children:["No conversation turns — ",(Ha==null?void 0:Ha.length)??0," proxy snapshots captured."]}):(()=>{var Mu,lc;const Bl=((lc=(Mu=is==null?void 0:is.eventCounts)==null?void 0:Mu.byType)==null?void 0:lc.user_message)??cl.length,ru=[...cl].map((Tu,Eu)=>({turn:Tu,chronoIdx:Eu})).reverse();if(Ya==="split")return jsxRuntimeExports.jsx("div",{className:"space-y-2",children:ru.map(({turn:Tu,chronoIdx:Eu},Ua)=>{var yl;const ll=Ha==null?void 0:Ha[Eu];return jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_360px] gap-6 border-t border-border/40 first:border-t-0",children:[jsxRuntimeExports.jsx(TurnContainer,{turn:Tu,index:Ua,totalTurns:Bl,snapshot:ll,hideSnapshot:!0}),jsxRuntimeExports.jsx("div",{className:"hidden lg:block pt-6",children:ll?jsxRuntimeExports.jsx("div",{className:"sticky top-4",children:jsxRuntimeExports.jsx(InlineTurnSnapshot,{snapshot:ll})}):jsxRuntimeExports.jsx("div",{className:"sticky top-4 text-xs text-muted-foreground/60 font-mono pt-2",children:"No snapshot for this turn"})})]},((yl=Tu.userMessage)==null?void 0:yl.id)??`turn-${Eu}`)})});if(Ya==="capped"){const Tu=(Ha??[]).reduce((Ua,ll)=>Ua+(ll.estimatedTokens??0),0),Eu=nl.tools;return jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_320px] gap-8",children:[jsxRuntimeExports.jsx("div",{className:"max-w-3xl",children:ru.map(({turn:Ua,chronoIdx:ll},yl)=>{var $l;return jsxRuntimeExports.jsx(TurnContainer,{turn:Ua,index:yl,totalTurns:Bl,snapshot:Ha==null?void 0:Ha[ll]},(($l=Ua.userMessage)==null?void 0:$l.id)??`turn-${ll}`)})}),jsxRuntimeExports.jsx("aside",{className:"hidden xl:block",children:jsxRuntimeExports.jsxs("div",{className:"sticky top-4 space-y-3 border border-border rounded-lg p-4 bg-card",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Session Summary"}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Turns"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:Bl})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Tool calls"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:Eu})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Snapshots"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:(Ha==null?void 0:Ha.length)??0})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"~Total tokens"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:Tu.toLocaleString()})]})]}),jsxRuntimeExports.jsxs("div",{className:"border-t border-border/40 pt-3",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Per-turn"}),jsxRuntimeExports.jsx("div",{className:"space-y-1 max-h-96 overflow-y-auto pr-1",children:ru.map(({turn:Ua,chronoIdx:ll},yl)=>{var bl,_l;const $l=Ha==null?void 0:Ha[ll],kl=Bl-yl,Za=Ua.events.filter(Ol=>Ol.eventType==="tool_call").length,al=eventUsage(Ua.assistantResponse)??((bl=$l==null?void 0:$l.metadata)==null?void 0:bl.usage),El=al==null?void 0:al.output_tokens;return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-mono",children:[jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/60 w-10",children:["T",kl]}),Za>0&&jsxRuntimeExports.jsxs("span",{className:"text-amber-500",children:[Za,"t"]}),El!=null&&El>0&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[formatTokenCount(El),"tk"]}),($l==null?void 0:$l.estimatedTokens)!=null&&jsxRuntimeExports.jsxs("span",{className:"text-cyan-500/80 ml-auto",children:[formatTokenCount($l.estimatedTokens)," ctx"]})]},((_l=Ua.userMessage)==null?void 0:_l.id)??`meta-${ll}`)})})]})]})})]})}return ru.map(({turn:Tu,chronoIdx:Eu},Ua)=>{var ll;return jsxRuntimeExports.jsx(TurnContainer,{turn:Tu,index:Ua,totalTurns:Bl,snapshot:Ha==null?void 0:Ha[Eu]},((ll=Tu.userMessage)==null?void 0:ll.id)??`turn-${Eu}`)})})(),Na&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-6 pb-2",children:jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Aa(),disabled:Oa,className:"cursor-pointer",children:Oa?"Loading...":"Load more events"})})]}):rl.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No events match the current filter."}):jsxRuntimeExports.jsxs("div",{children:[rl.map(Bl=>jsxRuntimeExports.jsx("div",{children:renderEvent(Bl)},Bl.id)),Na&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-6 pb-2",children:jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Aa(),disabled:Oa,className:"cursor-pointer",children:Oa?"Loading...":"Load more events"})})]})]})]}),yu&&jsxRuntimeExports.jsx(ResumeBar,{sessionId:is.id,session:is,externalSessionId:is.externalSessionId,launchProjectPath:is.primaryCheckoutPath??is.projectPath??"/tmp",resumePrompt:qa,setResumePrompt:Fa,resumeMutation:La})]})}function ResumeBar({sessionId:es,session:$,externalSessionId:ts,launchProjectPath:is,resumePrompt:cs,setResumePrompt:Qr,resumeMutation:ja}){const{data:Na}=useSessionTerminalTarget(es),Aa=useSendMessage$1(es),{data:Oa}=useLaunchJobs(),Ia=(Na==null?void 0:Na.target)??null,La=(Na==null?void 0:Na.capabilities)??{liveSend:!1,fallbackResume:!0,tmuxAvailable:!1,workerOnline:!1},Ba=(()=>{const ol=!!(Ia&&Ia.status==="active");return!La.workerOnline&&ol?"worker_offline":ol&&La.liveSend?"live_ready":Ia&&Ia.status!=="active"?"target_missing":La.tmuxAvailable?"launch_ready":"tmux_missing"})(),Ma=Aa.isPending?"sending":Aa.isError?"send_failed":Aa.isSuccess?"sent":Ba,qa=Ba==="live_ready"&&(Ma==="live_ready"||Ma==="sending"||Ma==="sent"),Fa=qa?"Send to live Claude session… (Enter submits, Shift+Enter for newline)":"Resume this session… (Enter submits, Shift+Enter for newline)",Ha=(()=>{switch(Ma){case"live_ready":return"Send to live Claude";case"launch_ready":return"Resume in Terminal";case"tmux_missing":return"Resume in Terminal";case"target_missing":return"Start new live session";case"worker_offline":return"Worker offline";case"sending":return qa?"Sending…":"Resuming…";case"sent":return qa?"Sent":"Resumed";case"send_failed":return"Retry"}})(),Ka=Ma==="worker_offline"||Ma==="sending"||ja.isPending,Ga=Aa.data,Va=(Ga==null?void 0:Ga.delivery)==="live"?Ga.target.target:null,Ja=(Ia==null?void 0:Ia.attachCommand)??(Ia!=null&&Ia.target?`tmux attach -t ${Ia.target}`:null),Ya=(Oa??[]).find(ol=>{var hl;return((hl=ol.config)==null?void 0:hl.resumeSessionId)===ts}),el=Ya==null?void 0:Ya.status,tl=!!(Ya!=null&&Ya.completedAt)&&Date.now()-new Date(Ya.completedAt).getTime()<3e4,rl=(()=>{var ol;return Ma==="send_failed"?{dot:"bg-red-500",label:Aa.error instanceof Error?Aa.error.message:"Send failed"}:Ma==="sent"&&qa&&Va?{dot:"bg-teal-500",label:`Sent to ${Va}`}:el==="pending"||el==="claimed"?{dot:"bg-amber-500 animate-pulse",label:"Queued — waiting for worker"}:el==="running"?{dot:"bg-teal-500 animate-pulse",label:(ol=Ya==null?void 0:Ya.result)!=null&&ol.pid?`Running (PID ${Ya.result.pid})`:"Running"}:el==="failed"?{dot:"bg-red-500",label:(Ya==null?void 0:Ya.error)??"Failed"}:el==="completed"&&tl?{dot:"bg-teal-500",label:"Resumed — Claude is now active"}:null})(),cl=La.workerOnline?"":" Worker offline — job will queue and run when the worker connects.",dl=(()=>{switch(Ba){case"worker_offline":return"Start worker: `rulemetric service install` or `rulemetric evals agent`";case"tmux_missing":return"Install tmux to enable live send."+cl;case"target_missing":return"The previous tmux session ended. Starting a new one will spawn a fresh terminal."+cl;case"launch_ready":return"Live send needs a tmux target. Fallback will spawn a new terminal."+cl;default:return null}})(),fl=ol=>{ts&&ja.mutate({tool:"claude_code",projectPath:is,mode:"interactive",resumeSessionId:ts,...ol?{prompt:ol}:{}},{onSuccess:()=>{ue$1(ol?"Resume request sent":"Resume request sent (no prompt)"),Qr("")},onError:hl=>ue$1.error(hl instanceof Error?hl.message:"Failed to resume")})},nl=()=>{if(Ka)return;const ol=cs.trim();if(!ol){if(Ba==="live_ready"){ue$1.error("Type a message to send");return}if(!ts)return;fl("");return}if(Ba==="live_ready"){Aa.mutate({message:ol,delivery:"live",submit:!0},{onSuccess:()=>Qr("")});return}ts&&fl(ol)};return jsxRuntimeExports.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 border-t border-border bg-background shadow-[0_-4px_20px_rgba(0,0,0,0.15)]",children:[rl&&jsxRuntimeExports.jsx("div",{className:"border-b border-border/60 bg-secondary/40",children:jsxRuntimeExports.jsxs("div",{className:"max-w-screen-xl mx-auto px-6 py-1.5 sm:px-8 flex items-center gap-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:`h-2 w-2 rounded-full ${rl.dot}`}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:rl.label}),Ja&&Ma==="sent"&&qa&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/70 font-mono ml-2",children:["· ",Ja]})]})}),jsxRuntimeExports.jsxs("div",{className:"max-w-screen-xl mx-auto px-6 py-3 sm:px-8 space-y-2",children:[jsxRuntimeExports.jsx(SessionTargetSummary,{target:Ia,capabilities:La,session:$}),dl&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground font-mono",children:dl}),jsxRuntimeExports.jsxs("form",{onSubmit:ol=>{ol.preventDefault(),nl()},className:"flex items-end gap-2",children:[jsxRuntimeExports.jsx("textarea",{value:cs,onChange:ol=>Qr(ol.target.value),onKeyDown:ol=>{var hl;ol.key==="Enter"&&!ol.shiftKey&&!ol.nativeEvent.isComposing&&(ol.preventDefault(),(hl=ol.currentTarget.form)==null||hl.requestSubmit())},placeholder:Fa,rows:2,className:"flex-1 resize-none rounded-md border border-input bg-card px-3 py-2 text-sm font-mono ring-offset-background placeholder:text-muted-foreground/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",disabled:Ka}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ka,className:"cursor-pointer self-end",children:Ha})]})]})]})}function useProjects(es={}){const $=new URLSearchParams;es.limit&&$.set("limit",String(es.limit)),es.offset&&$.set("offset",String(es.offset));const ts=$.toString();return useQuery({queryKey:["projects",es],queryFn:()=>apiGet(`/api/projects${ts?`?${ts}`:""}`),refetchInterval:POLL.ACTIVE})}function useProject(es){return useQuery({queryKey:["projects",es],queryFn:()=>apiGet(`/api/projects/${es}`),enabled:!!es,refetchInterval:POLL.ACTIVE})}function Select({...es}){return jsxRuntimeExports.jsx(Root2$1,{"data-slot":"select",...es})}function SelectValue({...es}){return jsxRuntimeExports.jsx(Value,{"data-slot":"select-value",...es})}function SelectTrigger({className:es,size:$="default",children:ts,...is}){return jsxRuntimeExports.jsxs(Trigger$3,{"data-slot":"select-trigger","data-size":$,className:cn$1("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",es),...is,children:[ts,jsxRuntimeExports.jsx(Icon,{asChild:!0,children:jsxRuntimeExports.jsx(ChevronDown,{className:"size-4 opacity-50"})})]})}function SelectContent({className:es,children:$,position:ts="item-aligned",align:is="center",...cs}){return jsxRuntimeExports.jsx(Portal$2,{children:jsxRuntimeExports.jsxs(Content2$2,{"data-slot":"select-content",className:cn$1("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",ts==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",es),position:ts,align:is,...cs,children:[jsxRuntimeExports.jsx(SelectScrollUpButton,{}),jsxRuntimeExports.jsx(Viewport,{className:cn$1("p-1",ts==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:$}),jsxRuntimeExports.jsx(SelectScrollDownButton,{})]})})}function SelectItem({className:es,children:$,...ts}){return jsxRuntimeExports.jsxs(Item,{"data-slot":"select-item",className:cn$1("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",es),...ts,children:[jsxRuntimeExports.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:jsxRuntimeExports.jsx(ItemIndicator,{children:jsxRuntimeExports.jsx(Check,{className:"size-4"})})}),jsxRuntimeExports.jsx(ItemText,{children:$})]})}function SelectScrollUpButton({className:es,...$}){return jsxRuntimeExports.jsx(ScrollUpButton,{"data-slot":"select-scroll-up-button",className:cn$1("flex cursor-default items-center justify-center py-1",es),...$,children:jsxRuntimeExports.jsx(ChevronUp,{className:"size-4"})})}function SelectScrollDownButton({className:es,...$}){return jsxRuntimeExports.jsx(ScrollDownButton,{"data-slot":"select-scroll-down-button",className:cn$1("flex cursor-default items-center justify-center py-1",es),...$,children:jsxRuntimeExports.jsx(ChevronDown,{className:"size-4"})})}function Textarea({className:es,...$}){return jsxRuntimeExports.jsx("textarea",{"data-slot":"textarea",className:cn$1("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",es),...$})}function sanitizeTmuxName(es){return`rm-${es.trim().replace(/[^A-Za-z0-9_.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"session"}`}function previewTmuxTarget(es){return sanitizeTmuxName("claude-auto")}function LaunchSessionDialog({open:es,onOpenChange:$,initialProjectPath:ts}){const is=useNavigate(),{data:cs}=useAvailableLaunchers(),Qr=useCreateLaunchJob(),[ja,Na]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(ts??""),[Ia,La]=reactExports.useState(""),[Ba,Ma]=reactExports.useState(""),[qa,Fa]=reactExports.useState("interactive");reactExports.useEffect(()=>{es&&Oa(Ja=>Ja||(ts??""))},[es,ts]);const Ha=()=>{Na(""),Oa(ts??""),La(""),Ma(""),Fa("interactive")},Ka=reactExports.useMemo(()=>previewTmuxTarget(),[]),Ga=Ja=>{Ja.preventDefault(),!(!ja||!Aa)&&Qr.mutate({tool:ja,projectPath:Aa,prompt:Ia||void 0,model:Ba||void 0,mode:qa},{onSuccess:Ya=>{var cl;const el=Ya.result,tl=(cl=el==null?void 0:el.terminalTarget)==null?void 0:cl.target,rl=(el==null?void 0:el.terminalTarget)&&el.terminalTarget.live===!1;ue$1(qa==="headless"?"Starting headless Claude Code job":tl?`Starting Claude Code in tmux target ${tl}`:rl?"Starting Claude Code in Terminal fallback":`Starting Claude Code in tmux target ${Ka}`),Ya.noLiveWorker&&ue$1.error("No worker online — start `rulemetric evals agent` to process this launch"),Ya.sessionId?is(`/sessions/${Ya.sessionId}`):is("/sessions"),Ha(),$(!1)},onError:Ya=>{ue$1.error(Ya instanceof Error?Ya.message:"Failed to create launch job")}})},Va=!!(ja&&Aa);return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{className:"sm:max-w-md",children:[jsxRuntimeExports.jsx(DialogHeader,{children:jsxRuntimeExports.jsx(DialogTitle,{children:"Launch Session"})}),jsxRuntimeExports.jsxs("form",{onSubmit:Ga,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"tool",children:"Tool"}),jsxRuntimeExports.jsxs(Select,{value:ja,onValueChange:Na,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"tool",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"Select a tool"})}),jsxRuntimeExports.jsx(SelectContent,{children:cs==null?void 0:cs.map(Ja=>jsxRuntimeExports.jsx(SelectItem,{value:Ja.tool,children:Ja.tool.replace(/_/g," ")},Ja.tool))})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"projectPath",children:"Project Path"}),jsxRuntimeExports.jsx(Input,{id:"projectPath",value:Aa,onChange:Ja=>Oa(Ja.target.value),placeholder:"/path/to/project",required:!0})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"prompt",children:"Prompt"}),jsxRuntimeExports.jsx(Textarea,{id:"prompt",value:Ia,onChange:Ja=>La(Ja.target.value),placeholder:"Optional prompt for the session",rows:3})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"model",children:"Model"}),jsxRuntimeExports.jsx(Input,{id:"model",value:Ba,onChange:Ja=>Ma(Ja.target.value),placeholder:"Optional model override"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"mode",children:"Mode"}),jsxRuntimeExports.jsxs(Select,{value:qa,onValueChange:Ja=>Fa(Ja),children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"mode",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"interactive",children:"Interactive"}),jsxRuntimeExports.jsx(SelectItem,{value:"headless",children:"Headless"})]})]})]}),Va&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border bg-muted/30 p-3 text-xs font-mono space-y-1",children:[jsxRuntimeExports.jsx("div",{className:"text-muted-foreground uppercase tracking-wide text-[10px] mb-1",children:"Launch summary"}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Tool"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:ja.replace(/_/g," ")})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Mode"}),jsxRuntimeExports.jsx("span",{children:qa})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Project path"}),jsxRuntimeExports.jsx("span",{className:"truncate",title:Aa,children:Aa})]}),Ia&&jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Prompt"}),jsxRuntimeExports.jsx("span",{className:"truncate max-w-[16rem]",title:Ia,children:Ia})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Expected target"}),jsxRuntimeExports.jsx("span",{className:"truncate",title:Ka,children:Ka})]}),qa==="interactive"&&jsxRuntimeExports.jsx("div",{className:"pt-1 text-[10px] text-amber-600",children:"Live send requires tmux on the worker host."})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",onClick:()=>$(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:!ja||!Aa||Qr.isPending,children:Qr.isPending?"Launching...":"Launch"})]})]})]})})}function ProjectCard$1({p:es,onClick:$,onLaunch:ts}){return jsxRuntimeExports.jsxs(Card,{className:"cursor-pointer hover:bg-secondary/30 transition-colors",onClick:$,children:[jsxRuntimeExports.jsxs(CardHeader,{className:"flex flex-row items-start justify-between space-y-0 pb-3",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono text-base font-semibold truncate",children:es.name}),es.gitRemoteUrl&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground font-mono flex items-center gap-1 mt-1",children:[jsxRuntimeExports.jsx(GitBranch,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:es.gitRemoteUrl})]}),es.primaryCheckoutPath&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground font-mono flex items-center gap-1 mt-0.5",children:[jsxRuntimeExports.jsx(Folder,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:es.primaryCheckoutPath})]})]}),jsxRuntimeExports.jsx("div",{className:"flex flex-col items-end gap-1 shrink-0 ml-3",children:es.activeSessionCount>0?jsxRuntimeExports.jsxs(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30",children:[es.activeSessionCount," active"]}):jsxRuntimeExports.jsx(Badge,{variant:"outline",children:"idle"})})]}),jsxRuntimeExports.jsxs(CardContent,{className:"pt-0 pb-4 text-xs text-muted-foreground font-mono flex items-center justify-between",children:[jsxRuntimeExports.jsxs("span",{children:[es.sessionCount," session",es.sessionCount===1?"":"s"," total"]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsxs("span",{children:["last activity ",formatRelativeTime(es.lastActivityAt,{fallback:"never"})]}),es.primaryCheckoutPath&&jsxRuntimeExports.jsxs(Button,{type:"button",size:"sm",variant:"outline",className:"h-7 px-2 text-[11px] cursor-pointer",onClick:is=>{is.stopPropagation(),ts(es.primaryCheckoutPath)},title:`Launch a new session in ${es.primaryCheckoutPath}`,children:[jsxRuntimeExports.jsx(Rocket,{className:"h-3 w-3 mr-1"}),"Launch"]})]})]})]})}function ProjectsListPage(){const es=useNavigate(),{data:$,isLoading:ts,isError:is}=useProjects({limit:100}),[cs,Qr]=reactExports.useState("cards"),[ja,Na]=reactExports.useState(!1),[Aa,Oa]=reactExports.useState(void 0),Ia=Ba=>{Oa(Ba),Na(!0)};let La;return ts?La=jsxRuntimeExports.jsxs("div",{className:"grid gap-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-28 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-28 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-28 w-full"})]}):is?La=jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-destructive font-mono",children:"Failed to load projects."}):!$||$.projects.length===0?La=jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(Layers,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:"No projects yet"}),jsxRuntimeExports.jsx("p",{className:"text-sm mt-1",children:"Projects appear after your first captured session in this org."})]}):cs==="cards"?La=jsxRuntimeExports.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:$.projects.map(Ba=>jsxRuntimeExports.jsx(ProjectCard$1,{p:Ba,onClick:()=>es(`/projects/${Ba.id}`),onLaunch:Ma=>Ia(Ma)},Ba.id))}):La=jsxRuntimeExports.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"bg-card hover:bg-card",children:[jsxRuntimeExports.jsx(TableHead,{children:"Project"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Active"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Total"}),jsxRuntimeExports.jsx(TableHead,{className:"w-40 text-right",children:"Last activity"}),jsxRuntimeExports.jsx(TableHead,{className:"w-28 text-right",children:"Actions"})]})}),jsxRuntimeExports.jsx(TableBody,{children:$.projects.map(Ba=>jsxRuntimeExports.jsxs(TableRow,{className:"cursor-pointer hover:bg-secondary/50 transition-colors",onClick:()=>es(`/projects/${Ba.id}`),children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("div",{className:"font-mono text-sm font-semibold truncate",children:Ba.name}),Ba.gitRemoteUrl&&jsxRuntimeExports.jsx("div",{className:"text-xs text-muted-foreground font-mono truncate",children:Ba.gitRemoteUrl})]})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:Ba.activeSessionCount>0?jsxRuntimeExports.jsx(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30",children:Ba.activeSessionCount}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono text-sm",children:"—"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right font-mono text-sm",children:Ba.sessionCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-sm text-muted-foreground whitespace-nowrap",children:formatRelativeTime(Ba.lastActivityAt,{fallback:"never"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",onClick:Ma=>Ma.stopPropagation(),children:Ba.primaryCheckoutPath?jsxRuntimeExports.jsxs(Button,{type:"button",size:"sm",variant:"outline",className:"h-7 px-2 text-[11px] cursor-pointer",onClick:()=>Ia(Ba.primaryCheckoutPath),title:`Launch a new session in ${Ba.primaryCheckoutPath}`,children:[jsxRuntimeExports.jsx(Rocket,{className:"h-3 w-3 mr-1"}),"Launch"]}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})})]},Ba.id))})]})}),jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 basis-56",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Projects"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"All projects in your active org. Click one to see its sessions."})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[jsxRuntimeExports.jsxs(Button,{size:"sm",className:"h-8 cursor-pointer",onClick:()=>Ia(void 0),children:[jsxRuntimeExports.jsx(Rocket,{className:"h-3.5 w-3.5 mr-1.5"}),"Launch session"]}),jsxRuntimeExports.jsxs("div",{role:"group","aria-label":"View mode",className:"inline-flex items-center rounded-md border border-border bg-card p-0.5",children:[jsxRuntimeExports.jsx(Button,{type:"button",size:"sm",variant:cs==="cards"?"secondary":"ghost","aria-pressed":cs==="cards",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>Qr("cards"),children:"Cards"}),jsxRuntimeExports.jsx(Button,{type:"button",size:"sm",variant:cs==="list"?"secondary":"ghost","aria-pressed":cs==="list",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>Qr("list"),children:"List"})]})]})]}),La,jsxRuntimeExports.jsx(LaunchSessionDialog,{open:ja,onOpenChange:Na,initialProjectPath:Aa})]})}function useRuns(es={}){const $=new URLSearchParams;es.limit&&$.set("limit",String(es.limit)),es.offset&&$.set("offset",String(es.offset)),es.projectId&&$.set("projectId",es.projectId);const ts=$.toString();return useQuery({queryKey:["runs","list",es],queryFn:()=>apiGet(`/api/runs${ts?`?${ts}`:""}`),enabled:es.projectId===void 0||!!es.projectId,refetchInterval:POLL.ACTIVE})}function useRunsEnabled(){return"false"==="1"}function sessionGoal(es){var ts;const $=(ts=es.analysis)==null?void 0:ts.goalSummary;return $?{text:$,isFallback:!1}:es.firstUserPrompt?{text:es.firstUserPrompt,isFallback:!0}:{text:"(no goal yet)",isFallback:!0}}function isActive(es){if(es.endedAt)return!1;const $=new Date(es.lastActivityAt??es.startedAt).getTime();return Date.now()-$<1800*1e3}function duration$1(es){const ts=new Date(es.endedAt??es.lastActivityAt??es.startedAt).getTime()-new Date(es.startedAt).getTime();if(!Number.isFinite(ts)||ts<0)return"—";const is=Math.floor(ts/6e4);return is<1?"<1m":is<60?`${is}m`:`${Math.floor(is/60)}h ${is%60}m`}function SessionCard({s:es,emphasized:$,onOpen:ts}){const is=sessionGoal(es);return jsxRuntimeExports.jsx(Card,{className:`cursor-pointer transition-colors hover:bg-secondary/30 ${$?"border-teal-500/40 shadow-[0_0_12px_-4px_rgba(16,185,129,0.35)]":""}`,onClick:ts,children:jsxRuntimeExports.jsxs(CardContent,{className:"py-3 flex flex-col gap-2 h-full",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground font-mono flex-wrap",children:[jsxRuntimeExports.jsx(ToolIcon,{tool:captureToolKey(es.tool),className:"h-4 w-4 shrink-0"}),jsxRuntimeExports.jsx("span",{children:displayTool(es.tool)}),es.gitBranch&&jsxRuntimeExports.jsxs("span",{children:["· ",es.gitBranch]}),jsxRuntimeExports.jsxs("span",{children:["· ",formatRelativeTime(es.lastActivityAt??es.startedAt)]}),isActive(es)&&jsxRuntimeExports.jsx(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30 text-[10px]",children:"active"})]}),jsxRuntimeExports.jsx("p",{className:`text-sm line-clamp-2 ${is.isFallback?"italic text-muted-foreground":"text-foreground"}`,children:is.text}),es.lastMessagePreview&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground line-clamp-2 font-mono",children:["↳ ",es.lastMessagePreview]}),jsxRuntimeExports.jsxs("div",{className:"mt-auto pt-1 text-[11px] text-muted-foreground font-mono",children:[es.eventCount," events · ",duration$1(es)]})]})})}function ProjectDetailPage(){const{id:es}=useParams(),$=useNavigate(),ts=useProject(es),is=useSessions({projectId:es,hideEmpty:!1,limit:200}),cs=useRunsEnabled();useRuns({projectId:""});const[Qr,ja]=reactExports.useState("cards"),[Na,Aa]=reactExports.useState(!1);if(ts.isLoading)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"})]});if(ts.isError||!ts.data)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs(Link,{to:"/projects",className:"text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"h-3 w-3"})," Projects"]}),jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-destructive font-mono",children:"Project not found."})]});const Oa=ts.data,Ia=is.data??[],La=null,Ba=Ia;let Ma;if(is.isLoading)Ma=jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"});else if(Ia.length===0)Ma=jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground font-mono text-sm",children:"No sessions yet for this project."});else if(Qr==="cards"){const qa=Ba.filter(isActive),Fa=Ba.filter(Ha=>!isActive(Ha));Ma=jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[qa.length>0&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"relative flex h-2 w-2",children:[jsxRuntimeExports.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-teal-500 opacity-60"}),jsxRuntimeExports.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-teal-500"})]}),jsxRuntimeExports.jsxs("h4",{className:"text-sm font-mono font-semibold text-teal-600",children:["Active now · ",qa.length]})]}),jsxRuntimeExports.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:qa.map(Ha=>jsxRuntimeExports.jsx(SessionCard,{s:Ha,emphasized:!0,onOpen:()=>$(`/sessions/${Ha.id}`)},Ha.id))})]}),Fa.length>0&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[qa.length>0&&jsxRuntimeExports.jsx("h4",{className:"text-sm font-mono font-semibold text-muted-foreground",children:"Earlier"}),jsxRuntimeExports.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:Fa.map(Ha=>jsxRuntimeExports.jsx(SessionCard,{s:Ha,onOpen:()=>$(`/sessions/${Ha.id}`)},Ha.id))})]})]})}else Ma=jsxRuntimeExports.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"bg-card hover:bg-card",children:[jsxRuntimeExports.jsx(TableHead,{className:"w-40",children:"Tool"}),jsxRuntimeExports.jsx(TableHead,{className:"w-40",children:"Branch"}),jsxRuntimeExports.jsx(TableHead,{children:"Goal"}),jsxRuntimeExports.jsx(TableHead,{className:"w-24",children:"Status"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Last activity"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Ba.map(qa=>{const Fa=sessionGoal(qa);return jsxRuntimeExports.jsxs(TableRow,{className:"cursor-pointer hover:bg-secondary/50 transition-colors",onClick:()=>$(`/sessions/${qa.id}`),children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(ToolIcon,{tool:captureToolKey(qa.tool),className:"h-4 w-4 text-muted-foreground shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm truncate",children:displayTool(qa.tool)})]})}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-sm text-muted-foreground",children:qa.gitBranch??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"max-w-md",children:jsxRuntimeExports.jsx("p",{className:`text-sm line-clamp-2 ${Fa.isFallback?"italic text-muted-foreground":"text-foreground"}`,children:Fa.text})}),jsxRuntimeExports.jsx(TableCell,{children:isActive(qa)?jsxRuntimeExports.jsx(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30",children:"active"}):qa.endedAt?jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs font-mono",children:"ended"}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs font-mono",children:"idle"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-sm text-muted-foreground whitespace-nowrap",children:formatRelativeTime(qa.lastActivityAt??qa.startedAt)})]},qa.id)})})]})});return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs(Link,{to:"/projects",className:"text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"h-3 w-3"})," Projects"]}),jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight truncate",children:Oa.name}),Oa.description&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Oa.description}),jsxRuntimeExports.jsxs("div",{className:"mt-2 space-y-1",children:[Oa.gitRemoteUrl&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground font-mono flex items-center gap-1.5",children:[jsxRuntimeExports.jsx(GitBranch,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:Oa.gitRemoteUrl})]}),Oa.primaryCheckoutPath&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground font-mono flex items-center gap-1.5",children:[jsxRuntimeExports.jsx(Folder,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:Oa.primaryCheckoutPath})]})]})]}),jsxRuntimeExports.jsxs("div",{className:"text-right shrink-0 space-y-1.5 flex flex-col items-end",children:[cs,Oa.activeSessionCount>0&&jsxRuntimeExports.jsxs(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30",children:[Oa.activeSessionCount," active"]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground font-mono",children:[Oa.sessionCount," total"]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground font-mono",children:["last ",formatRelativeTime(Oa.lastActivityAt)]})]})]})})}),La,jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-mono font-semibold",children:"Sessions"}),jsxRuntimeExports.jsxs("div",{role:"group","aria-label":"View mode",className:"inline-flex items-center rounded-md border border-border bg-card p-0.5",children:[jsxRuntimeExports.jsx(Button,{type:"button",size:"sm",variant:Qr==="cards"?"secondary":"ghost","aria-pressed":Qr==="cards",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>ja("cards"),children:"Cards"}),jsxRuntimeExports.jsx(Button,{type:"button",size:"sm",variant:Qr==="list"?"secondary":"ghost","aria-pressed":Qr==="list",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>ja("list"),children:"List"})]})]}),Ma,cs]})}function useEvalTargets(es){return useQuery({queryKey:["eval-targets",es],queryFn:()=>apiGet("/api/eval-targets")})}function useEvalTarget(es){return useQuery({queryKey:["eval-targets",es],queryFn:()=>apiGet(`/api/eval-targets/${es}`),enabled:!!es})}function useEvals(es){return useQuery({queryKey:["eval-targets",es,"evals"],queryFn:()=>apiGet(`/api/eval-targets/${es}/evals`),enabled:!!es})}function useEvalRuns(es,$){return useQuery({queryKey:["eval-targets",es,"runs",$],queryFn:()=>apiGet(`/api/eval-targets/${es}/runs`),enabled:!!es})}function useBenchmarks(es){return useQuery({queryKey:["eval-targets",es,"benchmarks"],queryFn:()=>apiGet(`/api/eval-targets/${es}/benchmarks`),enabled:!!es})}function useEvalComparisons(es){return useQuery({queryKey:["eval-targets",es,"comparisons"],queryFn:()=>apiGet(`/api/eval-targets/${es}/comparisons`),enabled:!!es})}function useEvalComparison(es,$=!0){return useQuery({queryKey:["eval-comparisons",es],queryFn:()=>apiGet(`/api/eval-comparisons/${es}`),enabled:!!es&&$})}function useGradeAnnotations(es){return useQuery({queryKey:["eval-targets",es,"annotations"],queryFn:()=>apiGet(`/api/eval-targets/${es}/annotations?limit=500`),enabled:!!es})}function useAnnotateGrade(es){const $=useQueryClient();return useMutation({mutationFn:({runId:ts,expectationIndex:is,verdict:cs,flag:Qr,note:ja})=>apiPut(`/api/eval-runs/${ts}/annotations/${is}`,{verdict:cs,...Qr!==void 0?{flag:Qr}:{},...ja!==void 0?{note:ja}:{}}),onSuccess:()=>{$.invalidateQueries({queryKey:["eval-targets",es,"annotations"]}),$.invalidateQueries({queryKey:["eval-targets",es,"judge-calibration"]})}})}function useRemoveGradeAnnotation(es){const $=useQueryClient();return useMutation({mutationFn:({runId:ts,expectationIndex:is})=>apiDelete(`/api/eval-runs/${ts}/annotations/${is}`),onSuccess:()=>{$.invalidateQueries({queryKey:["eval-targets",es,"annotations"]}),$.invalidateQueries({queryKey:["eval-targets",es,"judge-calibration"]})}})}function useJudgeDisagreements(es){return useQuery({queryKey:["eval-targets",es,"judge-disagreements"],queryFn:()=>apiGet(`/api/eval-targets/${es}/judge-reviews/disagreements`),enabled:!!es})}function useResolveJudgeReview(es){const $=useQueryClient();return useMutation({mutationFn:({id:ts,resolution:is})=>apiPatch(`/api/judge-reviews/${ts}/resolve`,{resolution:is}),onSuccess:()=>{$.invalidateQueries({queryKey:["eval-targets",es,"judge-disagreements"]})}})}function useJudgeCalibration(es){return useQuery({queryKey:["eval-targets",es,"judge-calibration"],queryFn:()=>apiGet(`/api/eval-targets/${es}/judge-calibration`),enabled:!!es})}function useAnnotationQueue(es){return useQuery({queryKey:["eval-targets",es,"annotation-queue"],queryFn:()=>apiGet(`/api/eval-targets/${es}/annotation-queue`),enabled:!!es})}function EvalTargetsListPage(){const es=useNavigate(),{data:$,isLoading:ts}=useEvalTargets();return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Eval Targets"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Manage eval targets and view benchmark results"})]}),ts?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:5}).map((is,cs)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 w-full"},cs))}):$!=null&&$.length?jsxRuntimeExports.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"bg-card hover:bg-card",children:[jsxRuntimeExports.jsx(TableHead,{children:"Name"}),jsxRuntimeExports.jsx(TableHead,{children:"Type"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Version"}),jsxRuntimeExports.jsx(TableHead,{children:"Description"}),jsxRuntimeExports.jsx(TableHead,{children:"Updated"})]})}),jsxRuntimeExports.jsx(TableBody,{children:$.map(is=>jsxRuntimeExports.jsxs(TableRow,{className:"cursor-pointer hover:bg-secondary/50 transition-colors",onClick:()=>es(`/eval-targets/${is.id}`),children:[jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-sm font-medium",children:is.name}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono",children:is.type})}),jsxRuntimeExports.jsxs(TableCell,{className:"text-right font-mono text-sm",children:["v",is.version]}),jsxRuntimeExports.jsx(TableCell,{className:"text-sm text-muted-foreground max-w-64 truncate",children:is.description||"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-sm text-muted-foreground",children:new Date(is.updatedAt).toLocaleDateString()})]},is.id))})]})}):jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:"No eval targets yet"}),jsxRuntimeExports.jsxs("p",{className:"text-sm mt-1",children:["Create eval targets via the CLI with"," ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric eval-targets create"})]})]})]})}function usePromotions(es){return useQuery({queryKey:["eval-targets",es,"promotions"],queryFn:()=>apiGet(`/api/eval-targets/${es}/promotions?limit=50`),enabled:!!es})}function useEvalJobs(es){return useQuery({queryKey:["eval-jobs",es],queryFn:()=>apiGet(`/api/eval-targets/${es}/jobs`),enabled:!!es})}function useCreateEvalJob(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/eval-jobs",$),onSuccess:$=>{es.invalidateQueries({queryKey:["eval-jobs",$.evalTargetId]})}})}function useCancelEvalJob(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/eval-jobs/${$}/cancel`,{}),onSuccess:$=>{es.invalidateQueries({queryKey:["eval-jobs",$.evalTargetId]})}})}function useRealtimeEvalJobs(es,$){const ts=useQueryClient(),[is,cs]=reactExports.useState(null);return reactExports.useEffect(()=>{if(!es)return;const Qr=`user_id=eq.${es}`,ja=supabase.channel(`eval-jobs-${$??"all"}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"eval_jobs",filter:Qr},Na=>{const Aa=Na.new;$&&Aa.evalTargetId!==$||(cs(Aa),ts.invalidateQueries({queryKey:["eval-jobs",Aa.evalTargetId]}))}).on("postgres_changes",{event:"UPDATE",schema:"public",table:"eval_jobs",filter:Qr},Na=>{const Aa=Na.new;$&&Aa.evalTargetId!==$||(Aa.status==="completed"||Aa.status==="failed"||Aa.status==="cancelled"?(cs(null),ts.invalidateQueries({queryKey:["eval-runs",Aa.evalTargetId]}),ts.invalidateQueries({queryKey:["eval-jobs",Aa.evalTargetId]})):cs(Aa))}).subscribe();return()=>{supabase.removeChannel(ja)}},[es,$,ts]),is}function useEvalConversation(es){return useQuery({queryKey:["eval-conversation",es],queryFn:()=>apiGet(`/api/eval-targets/${es}/conversations`),enabled:!!es})}function useCreateConversation(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/eval-targets/${$}/conversations`,{}),onSuccess:$=>{es.invalidateQueries({queryKey:["eval-conversation",$.evalTargetId]})}})}function useSendMessage(){const es=useQueryClient();return useMutation({mutationFn:({conversationId:$,content:ts})=>apiPost(`/api/eval-conversations/${$}/messages`,{content:ts}),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["eval-conversation-messages",ts.conversationId]})}})}function useConversationMessages(es,$=2e3){return useQuery({queryKey:["eval-conversation-messages",es],queryFn:()=>apiGet(`/api/eval-conversations/${es}/messages`),enabled:!!es,refetchInterval:$})}function useApplyProposal(){const es=useQueryClient(),$=useNavigate();return useMutation({mutationFn:({conversationId:ts,messageId:is})=>apiPost(`/api/eval-conversations/${ts}/apply-proposal`,{messageId:is}),onSuccess:ts=>{es.invalidateQueries({queryKey:["eval-targets"]}),es.invalidateQueries({queryKey:["eval-conversation"]}),es.invalidateQueries({queryKey:["eval-conversation-messages"]}),$(`/eval-targets/${ts.newTarget.id}`)}})}function ChatPanel({targetId:es}){const{data:$}=useEvalConversation(es),ts=useCreateConversation(),is=useSendMessage(),cs=useApplyProposal(),Qr=$==null?void 0:$.id,{data:ja}=useConversationMessages(Qr,2e3),[Na,Aa]=reactExports.useState(""),[Oa,Ia]=reactExports.useState(!1),[La,Ba]=reactExports.useState(!1),Ma=reactExports.useRef(null);reactExports.useEffect(()=>{var Va;(Va=Ma.current)==null||Va.scrollIntoView({behavior:"smooth"})},[ja==null?void 0:ja.length]);const qa=reactExports.useCallback(async Va=>{if(!(!Va.trim()||Oa)){Ia(!0);try{let Ja=Qr;Ja||(Ja=(await ts.mutateAsync(es)).id);const Ya=await is.mutateAsync({conversationId:Ja,content:Va.trim()});Ba(Ya.noLiveWorker),Aa("")}finally{Ia(!1)}}},[Qr,ts,is,es,Oa]),Fa=async()=>{await qa(Na)},Ha=Va=>{Va.key==="Enter"&&!Va.shiftKey&&(Va.preventDefault(),Fa())},Ka=Va=>{Qr&&cs.mutate({conversationId:Qr,messageId:Va})},Ga=ja??($==null?void 0:$.messages)??[];return jsxRuntimeExports.jsxs("div",{className:"flex flex-col h-[600px]",children:[jsxRuntimeExports.jsxs("div",{className:"flex-1 overflow-y-auto space-y-3 p-4",children:[Ga.length===0&&jsxRuntimeExports.jsxs("div",{className:"text-center text-muted-foreground text-sm py-12 space-y-3",children:[jsxRuntimeExports.jsx("p",{children:"Start by running evals or generating test cases."}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 justify-center",children:[jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",disabled:Oa,onClick:()=>qa("Generate test cases for this instruction"),children:[jsxRuntimeExports.jsx(Sparkles,{className:"h-3 w-3 mr-1"}),"Generate Test Cases"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",disabled:Oa,onClick:()=>qa("Run the evals"),children:[jsxRuntimeExports.jsx(Play,{className:"h-3 w-3 mr-1"}),"Run Evals"]})]})]}),Ga.map((Va,Ja)=>Va.type==="status"&&Ga.slice(Ja+1).some(Ya=>Ya.type==="results"||Ya.type==="proposal"||Ya.type==="generated"||Ya.role==="user")?null:jsxRuntimeExports.jsx(MessageBubble,{message:Va,onApply:Ka,applyingProposal:cs.isPending,isLastStatus:Va.type==="status"},Va.id)),jsxRuntimeExports.jsx("div",{ref:Ma})]}),La&&jsxRuntimeExports.jsxs("div",{className:"border-t border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-500",children:["No CLI worker is listening — your message is queued but nothing will answer it. Start one with ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric evals agent"}),"."]}),jsxRuntimeExports.jsxs("div",{className:"border-t border-border p-3 flex gap-2",children:[jsxRuntimeExports.jsx("textarea",{value:Na,onChange:Va=>Aa(Va.target.value),onKeyDown:Ha,placeholder:"Type a message... (e.g. 'run evals', 'this output is missing X')",className:"flex-1 bg-muted rounded-lg px-3 py-2 text-sm resize-none min-h-[40px] max-h-[120px] focus:outline-none focus:ring-1 focus:ring-primary",rows:1,disabled:Oa}),jsxRuntimeExports.jsx(Button,{size:"icon",onClick:Fa,disabled:Oa||!Na.trim(),className:"shrink-0",children:Oa?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin"}):jsxRuntimeExports.jsx(Send,{className:"h-4 w-4"})})]})]})}function MessageBubble({message:es,onApply:$,applyingProposal:ts,isLastStatus:is}){if(es.role==="user")return jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsx("div",{className:"bg-primary text-primary-foreground rounded-lg px-3 py-2 max-w-[80%] text-sm",children:es.content})});switch(es.type){case"status":return jsxRuntimeExports.jsx(StatusMessage,{content:es.content,isActive:!!is});case"results":return jsxRuntimeExports.jsx(ResultsMessage,{content:es.content,data:es.data});case"proposal":return jsxRuntimeExports.jsx(ProposalMessage,{content:es.content,data:es.data,messageId:es.id,onApply:$,applying:ts});case"applied":return jsxRuntimeExports.jsx(AppliedMessage,{content:es.content});case"generated":return jsxRuntimeExports.jsx(GeneratedMessage,{content:es.content,data:es.data});default:return jsxRuntimeExports.jsx("div",{className:"flex justify-start",children:jsxRuntimeExports.jsx("div",{className:"bg-card border border-border rounded-lg px-3 py-2 max-w-[80%] text-sm",children:es.content})})}}function StatusMessage({content:es,isActive:$}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground px-3 py-1",children:[$?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}):jsxRuntimeExports.jsx(CircleCheck,{className:"h-3 w-3 text-muted-foreground/50"}),es]})}function ResultsMessage({content:es,data:$}){const[ts,is]=reactExports.useState(null);if(!$)return jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:es});const{summary:cs,results:Qr}=$,ja=cs.passRate>=.8?"text-teal-500":cs.passRate>=.5?"text-yellow-500":"text-red-500";return jsxRuntimeExports.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 space-y-3 max-w-[90%]",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsxs("span",{className:`font-mono text-lg font-bold ${ja}`,children:[cs.passed,"/",cs.total]}),jsxRuntimeExports.jsxs("span",{className:"text-sm text-muted-foreground",children:["evals passed (",Math.round(cs.passRate*100),"%)"]})]}),jsxRuntimeExports.jsx("div",{className:"space-y-1",children:Qr.map((Na,Aa)=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>is(ts===Aa?null:Aa),className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-left hover:bg-secondary/30",children:[ts===Aa?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3"}),Na.passed?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 text-teal-500"}):jsxRuntimeExports.jsx(CircleX,{className:"h-4 w-4 text-red-500"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:Na.evalName})]}),ts===Aa&&jsxRuntimeExports.jsxs("div",{className:"px-3 pb-3 space-y-2 border-t border-border pt-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Output:"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-2 rounded mt-1 overflow-x-auto max-h-40 whitespace-pre-wrap",children:Na.output})]}),Na.evidence&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Evidence:"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-2 rounded mt-1 overflow-x-auto max-h-32 whitespace-pre-wrap",children:Na.evidence})]})]})]},Aa))})]})}function ProposalMessage({content:es,data:$,messageId:ts,onApply:is,applying:cs}){const[Qr,ja]=reactExports.useState(!1);return jsxRuntimeExports.jsxs("div",{className:"bg-card border border-primary/30 rounded-lg p-4 space-y-3 max-w-[90%]",children:[jsxRuntimeExports.jsx("p",{className:"text-sm",children:es}),($==null?void 0:$.suggestions)&&$.suggestions.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("button",{onClick:()=>ja(!Qr),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[Qr?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3"}),$.suggestions.length," suggested change",$.suggestions.length>1?"s":""]}),Qr&&jsxRuntimeExports.jsx("div",{className:"space-y-2",children:$.suggestions.map((Na,Aa)=>jsxRuntimeExports.jsxs("div",{className:"bg-muted rounded p-3 text-xs space-y-1",children:[jsxRuntimeExports.jsx("div",{className:"font-mono font-medium text-primary",children:Na.section}),Na.current&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-red-400 font-medium",children:"- "}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:Na.current})]}),Na.proposed&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-teal-400 font-medium",children:"+ "}),jsxRuntimeExports.jsx("span",{children:Na.proposed})]}),jsxRuntimeExports.jsx("div",{className:"text-muted-foreground italic",children:Na.reasoning})]},Aa))})]}),jsxRuntimeExports.jsx("div",{className:"flex gap-2",children:jsxRuntimeExports.jsxs(Button,{size:"sm",onClick:()=>is(ts),disabled:cs,children:[cs?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin mr-1"}):null,"Apply Changes"]})})]})}function AppliedMessage({content:es}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-teal-500 px-3 py-1",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4"}),es]})}function GeneratedMessage({content:es,data:$}){const[ts,is]=reactExports.useState(null);return jsxRuntimeExports.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 space-y-3 max-w-[90%]",children:[jsxRuntimeExports.jsx("p",{className:"text-sm",children:es}),($==null?void 0:$.cases)&&jsxRuntimeExports.jsx("div",{className:"space-y-1",children:$.cases.map((cs,Qr)=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>is(ts===Qr?null:Qr),className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-left hover:bg-secondary/30",children:[ts===Qr?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:cs.name})]}),ts===Qr&&jsxRuntimeExports.jsxs("div",{className:"px-3 pb-3 space-y-2 border-t border-border pt-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Prompt:"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-2 rounded mt-1 whitespace-pre-wrap",children:cs.prompt})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Expectations:"}),jsxRuntimeExports.jsx("div",{className:"mt-1 space-y-1",children:cs.expectations.map((ja,Na)=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs font-normal",children:ja},Na))})]})]})]},Qr))})]})}const MIN_QUOTE_LEN=12,MIN_CODE_LEN=4,SHORT_CANDIDATE_LEN=20;function extractEvidenceQuotes(es){const $=[],ts=is=>{const cs=is==null?void 0:is.trim();cs&&$.push(cs)};for(const is of[/"([^"]+)"/g,/“([^”]+)”/g,/'([^']+)'/g,/‘([^’]+)’/g])for(const cs of es.matchAll(is))cs[1].length>=MIN_QUOTE_LEN&&ts(cs[1]);for(const is of es.matchAll(/`([^`]+)`/g))is[1].length>=MIN_CODE_LEN&&ts(is[1]);return es.trim().length>=SHORT_CANDIDATE_LEN&&ts(es),[...new Set($)]}function findEvidenceRanges(es,$){if(!es||!$)return[];const ts=[];for(const cs of extractEvidenceQuotes($))for(const[Qr,ja]of[[es,cs],[es.toLowerCase(),cs.toLowerCase()]]){let Na=0,Aa=!1;for(;;){const Oa=Qr.indexOf(ja,Na);if(Oa===-1||(ts.push([Oa,Oa+ja.length]),Aa=!0,cs.length<SHORT_CANDIDATE_LEN))break;Na=Oa+ja.length}if(Aa)break}ts.sort((cs,Qr)=>cs[0]-Qr[0]||cs[1]-Qr[1]);const is=[];for(const[cs,Qr]of ts){const ja=is[is.length-1];ja&&cs<=ja[1]?ja[1]=Math.max(ja[1],Qr):is.push([cs,Qr])}return is}function segmentByRanges(es,$){if($.length===0)return[{text:es,highlighted:!1}];const ts=[];let is=0;for(const[cs,Qr]of $)cs>is&&ts.push({text:es.slice(is,cs),highlighted:!1}),ts.push({text:es.slice(cs,Qr),highlighted:!0}),is=Qr;return is<es.length&&ts.push({text:es.slice(is),highlighted:!1}),ts}function SecondOpinions({flags:es,actions:$}){const ts=reactExports.useMemo(()=>{const Ka=new Map;for(const Ga of es){const Va=`${Ga.evalRunId}:${Ga.expectationIndex}`;Ka.set(Va,[...Ka.get(Va)??[],Ga])}return[...Ka.entries()].map(([Ga,Va])=>({key:Ga,rows:Va,first:Va[0],humanVerdict:Va[0].humanPassed===Va[0].judgePassed?"approve":"reject",consensus:new Set(Va.map(Ja=>Ja.reviewerEngine)).size>1})).sort((Ga,Va)=>Number(Va.consensus)-Number(Ga.consensus))},[es]),[is,cs]=reactExports.useState(new Set),[Qr,ja]=reactExports.useState(null),[Na,Aa]=reactExports.useState(!1),Oa=ts.length>0&&ts.every(Ka=>is.has(Ka.key)),Ia=()=>cs(Oa?new Set:new Set(ts.map(Ka=>Ka.key))),La=Ka=>cs(Ga=>{const Va=new Set(Ga);return Va.has(Ka)?Va.delete(Ka):Va.add(Ka),Va}),Ba=async(Ka,Ga,Va)=>{Aa(!0);let Ja=0,Ya=0;for(const el of Va)try{await Ga(el),Ja+=1}catch{Ya+=1}Aa(!1),cs(new Set),Ya===0?ue$1.success(`${Ka} ${Ja} label${Ja===1?"":"s"}`):ue$1.error(`${Ka} ${Ja}, ${Ya} failed — the rest are still flagged`)},Ma=Ka=>$.resolve({id:Ka.first.id,resolution:"kept"}),qa=async Ka=>{await $.annotate({runId:Ka.first.evalRunId,expectationIndex:Ka.first.expectationIndex,verdict:Ka.humanVerdict==="approve"?"reject":"approve"}),await $.resolve({id:Ka.first.id,resolution:"relabeled"})},Fa=async Ka=>{await $.removeAnnotation({runId:Ka.first.evalRunId,expectationIndex:Ka.first.expectationIndex}),await $.resolve({id:Ka.first.id,resolution:"relabeled"})};if(ts.length===0)return null;const Ha=ts.filter(Ka=>is.has(Ka.key));return jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-b border-border px-3 py-2",children:[jsxRuntimeExports.jsxs("label",{className:"flex cursor-pointer items-center gap-2",children:[jsxRuntimeExports.jsx("input",{type:"checkbox",checked:Oa,onChange:Ia,className:"h-3.5 w-3.5 accent-teal-500","aria-label":"Select all flags"}),jsxRuntimeExports.jsxs("span",{className:"text-sm font-medium",children:["Second opinions",jsxRuntimeExports.jsxs("span",{className:"ml-1.5 text-muted-foreground font-normal",children:[ts.length," label",ts.length===1?"":"s"," flagged"]})]})]}),Ha.length>0?jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"h-6 px-2 text-xs",disabled:Na,onClick:()=>Ba("Kept",Ma,Ha),children:["Keep ",Ha.length," label",Ha.length===1?"":"s"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"h-6 px-2 text-xs",disabled:Na,onClick:()=>Ba("Flipped",qa,Ha),children:["Flip ",Ha.length]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",disabled:Na,onClick:()=>Ba("Removed",Fa,Ha),children:["Remove ",Ha.length," & requeue"]})]}):jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"A second model disagrees with these labels — keep yours, or flip it if the reviewer caught a judge error."})]}),jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:ts.map(Ka=>{const Ga=Ka.first,Va=Qr===Ka.key;return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:cn$1("flex items-center gap-2 px-3 py-1.5 text-sm",is.has(Ka.key)&&"bg-primary/[0.04]"),children:[jsxRuntimeExports.jsx("input",{type:"checkbox",checked:is.has(Ka.key),onChange:()=>La(Ka.key),className:"h-3.5 w-3.5 shrink-0 accent-teal-500","aria-label":`Select ${Ga.expectationText}`}),jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>ja(Va?null:Ka.key),className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[Va?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[13px]",children:Ga.expectationText}),jsxRuntimeExports.jsxs("span",{className:"hidden shrink-0 font-mono text-[11px] text-muted-foreground sm:inline",children:[Ga.evalName??"case"," #",Ga.runNumber]}),Ka.consensus&&jsxRuntimeExports.jsx("span",{className:"shrink-0 rounded bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-500",children:"2 vendors"}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px]",children:["You: ",Ka.humanVerdict==="approve"?"right":"wrong"]}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 rounded bg-red-500/10 px-1.5 py-0.5 text-[10px] text-red-500",children:[Ka.rows.length," reviewer",Ka.rows.length===1?"":"s"," disagree"]})]}),jsxRuntimeExports.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",disabled:Na,onClick:()=>Ba("Kept",Ma,[Ka]),children:"Keep"}),jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-red-500 hover:text-red-400",disabled:Na,onClick:()=>Ba("Flipped",qa,[Ka]),children:"Flip"})]})]}),Va&&jsxRuntimeExports.jsxs("div",{className:"space-y-2 border-t border-border/50 bg-muted/20 px-9 py-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[jsxRuntimeExports.jsxs("span",{className:"rounded bg-muted px-1.5 py-0.5",children:["Judge: ",Ga.judgePassed?"PASS":"FAIL"]}),jsxRuntimeExports.jsxs("span",{className:"rounded bg-muted px-1.5 py-0.5",children:["You: judge was ",Ka.humanVerdict==="approve"?"right":"wrong"]}),Ka.rows.map(Ja=>jsxRuntimeExports.jsxs("span",{className:"rounded bg-red-500/10 px-1.5 py-0.5 text-red-500",children:[Ja.reviewerModel,": ",Ja.reviewerPassed?"PASS":"FAIL"]},Ja.id)),jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground",children:Ga.configuration})]}),Ga.outputExcerpt&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"mb-1 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Agent output (excerpt)"}),jsxRuntimeExports.jsx("pre",{className:"max-h-48 overflow-y-auto whitespace-pre-wrap rounded-md bg-muted p-2 text-xs",children:Ga.outputExcerpt})]})]})]},Ka.key)})})]})}function AnchorProgressCard({check:es,judge:$,pooling:ts}){const is=Math.min(100,Math.round(es.nAnchors/es.pilotTarget*100));return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("h3",{className:"font-mono font-medium flex items-center gap-1.5",children:["Anchor set",jsxRuntimeExports.jsx(InfoTip,{term:"anchorSet"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[($==null?void 0:$.currentModel)&&jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs text-muted-foreground flex items-center gap-1",children:[jsxRuntimeExports.jsx(InfoTip,{term:"judge",children:"judge"}),": ",$.currentModel]}),es.adequate?jsxRuntimeExports.jsx(Badge,{className:"font-mono text-xs",children:"adequate"}):jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",children:"not yet adequate"}),jsxRuntimeExports.jsx(InfoTip,{term:"adequate"})]})]}),$!=null&&$.staleAnchors>0&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-500",children:[$.staleAnchors," label",$.staleAnchors===1?"":"s"," from an older judge model no longer count toward this judge's calibration — the queue below only serves runs graded by the current judge."]}),jsxRuntimeExports.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:jsxRuntimeExports.jsx("div",{className:"bg-primary rounded-full h-2 transition-all duration-300",style:{width:`${is}%`}})}),ts&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:ts.engaged?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["rectifier: ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"pooled"})," from"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:ts.poolTargets})," same-judge targets /"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:ts.poolAnchors})," anchors (λ=",jsxRuntimeExports.jsx("span",{className:"font-mono",children:ts.withLambda.toFixed(2)}),Math.abs(ts.withLambda-ts.withoutLambda)>.01&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" / ",ts.withoutLambda.toFixed(2)]}),")"]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["rectifier: ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"target-specific"}),ts.withReason?` — ${ts.withReason}`:""]})}),(ts==null?void 0:ts.engaged)&&ts.assumedExchangeability&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-500",children:["Pool spans ",ts.poolTargets," of the 3 targets needed to MEASURE between-target variance — until then the judge is assumed to behave the same across targets rather than shown to. No calibrated verdict rests on that assumption."]}),jsxRuntimeExports.jsxs("p",{className:"text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[es.nAnchors," / ",es.pilotTarget]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(InfoTip,{term:"humanLabeledRuns",children:"human-labeled runs"})," (with"," ",es.nAnchorsWith," · without ",es.nAnchorsWithout,")",es.mde!=null&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" · ",jsxRuntimeExports.jsx(InfoTip,{term:"mde",children:"MDE"})," ±",(es.mde*100).toFixed(0),"pp vs ±",(es.targetEffect*100).toFixed(0),"pp target"]})]})]}),es.adequate?jsxRuntimeExports.jsx("p",{className:"text-xs text-teal-500",children:"Pilot target, cohort minimums, and target detectable effect all met — corrected estimates are publishable at this precision."}):jsxRuntimeExports.jsx("ul",{className:"text-xs text-muted-foreground space-y-0.5",children:es.reasons.map((cs,Qr)=>jsxRuntimeExports.jsxs("li",{children:["— ",cs]},Qr))})]})}function CaseDiscriminationCard({data:es}){const $=cs=>`${(cs*100).toFixed(0)}%`,ts=es.nonDiscriminating+es.unpaired,is=es.total>0&&ts/es.total>=.5;return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("h3",{className:"font-mono font-medium flex items-center gap-1.5",children:["Case discrimination",jsxRuntimeExports.jsx(InfoTip,{term:"discrimination"})]}),is?jsxRuntimeExports.jsxs(Badge,{variant:"destructive",className:"font-mono text-xs",children:[ts,"/",es.total," measure nothing"]}):jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"font-mono text-xs",children:[es.discriminating,"/",es.total," discriminate"]})]}),is&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-500",children:"Most cases don't separate with vs without, so the effect can't be resolved by adding runs — the variance is structural. Cull or replace the flagged cases before labeling."}),jsxRuntimeExports.jsxs("ul",{className:"text-xs space-y-1",children:[es.cases.map(cs=>jsxRuntimeExports.jsxs("li",{className:"flex items-baseline justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:cs.discriminating?"text-foreground":"text-muted-foreground line-through",children:cs.name}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-muted-foreground whitespace-nowrap",children:[$(cs.withPassRate)," vs ",$(cs.withoutPassRate),cs.discriminating?jsxRuntimeExports.jsxs("span",{className:"text-teal-500",children:[" · ",jsxRuntimeExports.jsxs(InfoTip,{term:"separation",children:["Δ",$(cs.separation)]})]}):jsxRuntimeExports.jsxs("span",{className:"text-amber-500",children:[" · ",jsxRuntimeExports.jsx(InfoTip,{term:"flat",children:"flat"})]})]})]},cs.name)),es.unpaired>0&&jsxRuntimeExports.jsxs("li",{className:"text-muted-foreground",children:["+ ",es.unpaired," case",es.unpaired===1?"":"s"," with no baseline cohort (can't be diagnosed — every baseline run missing or failed)"]})]})]})}function JudgeCalibrationCard({data:es}){const{anchors:$,calibration:ts,judge:is}=es,cs=Qr=>`${(Qr*100).toFixed(0)}%`;return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono font-medium",children:"Judge calibration"}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:[(is==null?void 0:is.currentModel)&&`judge ${is.currentModel} · `,$.llmAnchors," human label",$.llmAnchors===1?"":"s",$.flagged>0&&` · ${$.flagged} flagged`]})]}),is!=null&&(is.staleAnchors>0||is.staleRuns>0)&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-500",children:["Judge model changed — ",is.staleRuns," graded run",is.staleRuns===1?"":"s"," and ",is.staleAnchors," label",is.staleAnchors===1?"":"s"," from older judges are excluded here. Re-run evals and re-label in the Review tab to rebuild the anchor set under the current judge."]}),$.llmAnchors===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No human labels yet. Work through the Review tab (approve/reject each judge grade) — labels measure the judge's bias and correct the pass-rate estimates below (PPI)."}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[$.agreementRate!=null&&jsxRuntimeExports.jsxs("p",{className:"text-sm",children:["Judge/human agreement:"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:cs($.agreementRate)}),$.agreementCi&&jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs text-muted-foreground",children:[" ","[",cs($.agreementCi.lower),"–",cs($.agreementCi.upper),"]"]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["on ",$.llmAnchors," reviewed assertion",$.llmAnchors===1?"":"s"]})]}),ts&&(ts.sufficient?jsxRuntimeExports.jsxs("div",{className:"text-sm space-y-1",children:[jsxRuntimeExports.jsxs("p",{children:["Corrected pass rates:"," ",jsxRuntimeExports.jsxs("span",{className:"font-mono",children:["with ",cs(ts.with.estimate)," · without"," ",cs(ts.without.estimate)]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["(judge-only said ",cs(ts.with.naive)," ·"," ",cs(ts.without.naive),")"]})]}),jsxRuntimeExports.jsxs("p",{children:["Corrected delta:"," ",jsxRuntimeExports.jsxs("span",{className:`font-mono ${ts.significant?ts.delta>=0?"text-teal-500":"text-red-500":""}`,children:[ts.delta>=0?"+":"",cs(ts.delta)]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["95% CI ",cs(ts.ci.lower)," to ",cs(ts.ci.upper),ts.significant?"":" — not significant"," (unpaired, judge-bias-corrected)"]})]})]}):jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:[ts.insufficientReason??`need >= ${$.minAnchors} fully-reviewed runs per cohort for a corrected estimate`,". Fully-reviewed runs so far: ",$.labeledRuns.with," with ·"," ",$.labeledRuns.without," without."]})),es.powerCheck&&(es.powerCheck.adequate?jsxRuntimeExports.jsxs("p",{className:"text-xs text-teal-500",children:["Anchor set adequate — pilot target, cohort minimums, and ±",(es.powerCheck.targetEffect*100).toFixed(0),"pp detectable-effect target all met."]}):jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-500",children:["Anchor set not yet adequate (",es.powerCheck.nAnchors,"/",es.powerCheck.pilotTarget," pilot labels",es.powerCheck.mde!=null&&`, MDE ±${(es.powerCheck.mde*100).toFixed(0)}pp vs ±${(es.powerCheck.targetEffect*100).toFixed(0)}pp target`,") — treat corrected numbers as provisional; grow it in the Review tab."]}))]})]})}function CopyButton({text:es,what:$}){const{copy:ts}=useCopyToClipboard();return jsxRuntimeExports.jsx("button",{type:"button",onClick:async()=>await ts(es)?ue$1.success(`Copied ${$}`):ue$1.error("Copy failed — clipboard unavailable"),title:`Copy ${$}`,className:"rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground",children:jsxRuntimeExports.jsx(Copy,{className:"h-3.5 w-3.5"})})}function Kbd({children:es,className:$}){return jsxRuntimeExports.jsx("kbd",{className:cn$1("inline-flex items-center rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[10px] font-medium text-muted-foreground",$),children:es})}function ReviewerAgreementCard({reviewers:es}){const $=is=>`${(is*100).toFixed(0)}%`,ts=is=>is==null?"—":is.toFixed(2);return jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border",children:[jsxRuntimeExports.jsx("div",{className:"border-b border-border px-3 py-2",children:jsxRuntimeExports.jsxs("span",{className:"text-sm font-medium",children:["Second-opinion agreement",jsxRuntimeExports.jsx("span",{className:"ml-1.5 font-normal text-muted-foreground",children:"vs your current labels"})]})}),jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:es.filter(is=>is.pairs>0).map(is=>{const cs=is.kappa!=null&&is.snapshotKappa!=null&&Math.abs(is.kappa-is.snapshotKappa)>=.005;return jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 px-3 py-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-[13px] text-foreground",children:is.models.join(", ")}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[is.pairs," assertion",is.pairs===1?"":"s",is.orphaned>0&&` (+${is.orphaned} requeued)`]}),is.agreementRate!=null&&jsxRuntimeExports.jsxs("span",{children:["matches you ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:$(is.agreementRate)})]}),jsxRuntimeExports.jsxs("span",{children:["κ ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:ts(is.kappa)}),cs&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" ","(was ",ts(is.snapshotKappa)," before your corrections)"]})]}),is.judgeAgreementRate!=null&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:["judge matches you ",$(is.judgeAgreementRate)]}),is.suggestedAnchorWeight!=null&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:["anchor weight ",is.suggestedAnchorWeight.toFixed(2)]})]},is.engine)})})]})}function ReviewTab({targetId:es,queue:$,isFetching:ts,refetchQueue:is,annotations:cs,powerCheck:Qr,judge:ja,caseDiscrimination:Na,pooling:Aa,reviewers:Oa,targetContent:Ia,targetType:La}){var Gl,cu;const[Ba,Ma]=reactExports.useState(0),[qa,Fa]=reactExports.useState(!1),Ha=reactExports.useRef(!1);reactExports.useEffect(()=>{Aa!=null&&Aa.engaged&&!Ha.current&&(Ha.current=!0,Fa(!0))},[Aa==null?void 0:Aa.engaged]);const[Ka,Ga]=reactExports.useState(!1),[Va,Ja]=reactExports.useState({}),Ya=reactExports.useRef([]),el=useJudgeDisagreements(es),tl=useResolveJudgeReview(es),[rl,cl]=reactExports.useState({}),dl=useAnnotateGrade(es),fl=useRemoveGradeAnnotation(es),nl=new Map(cs.map(Al=>[`${Al.evalRunId}:${Al.expectationIndex}`,Al])),ol=(Al,Ml)=>{var xu,fu;const Ql=`${Al.id}:${Ml}`;if(Ql in rl)return rl[Ql];const eu=nl.get(Ql);return eu?eu.verdict:((fu=(xu=Al.expectations[Ml])==null?void 0:xu.annotation)==null?void 0:fu.verdict)??null},hl=(Al,Ml,Ql,eu)=>{const xu=`${Al}:${Ml}`;eu===Ql?(cl(fu=>{const Ou={...fu};return delete Ou[xu],Ou}),fl.mutate({runId:Al,expectationIndex:Ml},{onError:()=>ue$1.error("Couldn't remove the label — it may still be recorded. Retry in a moment.")})):(cl(fu=>({...fu,[xu]:Ql})),Ya.current.push({runId:Al,expectationIndex:Ml}),dl.mutate({runId:Al,expectationIndex:Ml,verdict:Ql},{onError:()=>{cl(fu=>{const Ou={...fu};return delete Ou[xu],Ou}),ue$1.error("Label didn't save — check your connection and mark it again.")}}))},Tl=$==null?void 0:$.runs[Ba],ul=(Tl==null?void 0:Tl.expectations.filter(Al=>Al.method==="llm"&&!Al.errored))??[],pl=Tl?ul.filter(Al=>ol(Tl,Al.index)!=null).length:0,jl=Tl!=null&&ul.length>0&&pl===ul.length,Nl=Tl?((Gl=ul.find(Al=>ol(Tl,Al.index)==null))==null?void 0:Gl.index)??null:null,[zl,Zl]=reactExports.useState(null);reactExports.useEffect(()=>{Zl(null),Ga(!1)},[Tl==null?void 0:Tl.id]);const Dl=zl??Nl,Il=reactExports.useRef(null),Fl=reactExports.useRef(null),ql=reactExports.useMemo(()=>{const Al=Tl==null?void 0:Tl.expectations.find(Ql=>Ql.method==="llm"&&Ql.index===Dl);if(!Al||!(Tl!=null&&Tl.output))return{segments:null,count:0};const Ml=findEvidenceRanges(Tl.output,Al.evidence);return Ml.length===0?{segments:null,count:0}:{segments:segmentByRanges(Tl.output,Ml),count:Ml.length}},[Tl,Dl]);reactExports.useEffect(()=>{const Al=Il.current,Ml=Fl.current;if(!Al||!Ml)return;const Ql=Ml.getBoundingClientRect().top-Al.getBoundingClientRect().top;Al.scrollTo({top:Al.scrollTop+Ql-48,behavior:"smooth"})},[Dl,Tl==null?void 0:Tl.id,ql.count]),reactExports.useEffect(()=>{const Al=Ml=>{if(Ml.metaKey||Ml.ctrlKey||Ml.altKey)return;const Ql=Ml.target;if(Ql&&(Ql.tagName==="INPUT"||Ql.tagName==="TEXTAREA"||Ql.isContentEditable)||!Tl)return;const eu=Ml.key.toLowerCase();if((eu==="1"||eu==="a")&&Nl!=null)Ml.preventDefault(),hl(Tl.id,Nl,"approve",null);else if((eu==="2"||eu==="d")&&Nl!=null)Ml.preventDefault(),hl(Tl.id,Nl,"reject",null);else if((Ml.key==="Enter"||eu==="n")&&jl)Ml.preventDefault(),Ma(xu=>xu+1);else if(eu==="s")Ml.preventDefault(),Ma(xu=>xu+1);else if(eu==="u"){const xu=Ya.current.pop();if(xu){Ml.preventDefault();const fu=`${xu.runId}:${xu.expectationIndex}`;cl(Ou=>{const yu={...Ou};return delete yu[fu],yu}),fl.mutate(xu,{onError:()=>ue$1.error("Couldn't undo — the label may still be recorded.")})}}else Ml.key==="ArrowRight"&&$&&Ba<$.runs.length-1?(Ml.preventDefault(),Ma(xu=>xu+1)):Ml.key==="ArrowLeft"&&Ba>0&&(Ml.preventDefault(),Ma(xu=>xu-1))};return window.addEventListener("keydown",Al),()=>window.removeEventListener("keydown",Al)},[Tl,Nl,jl,Ba,$]);const nu=Al=>{const Ml=Al.expectations.filter(eu=>eu.method==="llm");if(Ml.length===0)return"done";const Ql=Ml.filter(eu=>ol(Al,eu.index)!=null).length;return Ql===Ml.length?"done":Ql>0?"partial":"todo"};return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[$&&$.remaining>0&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-primary/40 bg-primary/[0.06] px-4 py-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"Review the judge's grade — not the output."}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-[13px] text-muted-foreground",children:["For each assertion below, decide whether the AI judge got the pass/fail right — mark"," ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"Judge was right"})," if it did, or"," ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"Judge was wrong"})," if it didn't. Each mark adds one"," ",jsxRuntimeExports.jsx(InfoTip,{term:"humanLabeledRuns",children:"human anchor"}),Qr&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" ","(",jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[Qr.nAnchors,"/",Qr.pilotTarget]}),")"]})," ","toward calibrating this judge — so a real verdict can be shown."]}),jsxRuntimeExports.jsxs("p",{className:"mt-2 flex flex-wrap items-center gap-x-1.5 gap-y-1 text-xs text-muted-foreground",children:["Keyboard: ",jsxRuntimeExports.jsx(Kbd,{children:"1"})," judge was right ",jsxRuntimeExports.jsx(Kbd,{children:"2"})," judge was wrong",jsxRuntimeExports.jsx(Kbd,{children:"U"})," undo last ",jsxRuntimeExports.jsx(Kbd,{children:"Enter"})," next run ",jsxRuntimeExports.jsx(Kbd,{children:"S"})," skip ",jsxRuntimeExports.jsx(Kbd,{children:"←"}),jsxRuntimeExports.jsx(Kbd,{children:"→"})," switch run"]})]}),cs.length>=10&&cs.every(Al=>Al.verdict==="approve")&&(((cu=el.data)==null?void 0:cu.length)??0)===0&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/[0.06] px-4 py-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm font-medium text-amber-500",children:["All ",cs.length," labels agree with the judge"]}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-[13px] text-muted-foreground",children:["A label set with zero rejects can't detect judge bias — don't hunt for rejects, but if the judge looks wrong, say so. To surface likely judge errors worth a second look, run"," ",jsxRuntimeExports.jsxs("span",{className:"font-mono text-foreground",children:["rulemetric evals validate-judge ",es]})," ","— assertions where a second model disagrees with the judge are the best candidates."]})]}),el.data&&el.data.length>0&&jsxRuntimeExports.jsx(SecondOpinions,{flags:el.data,actions:{annotate:Al=>dl.mutateAsync(Al),removeAnnotation:Al=>fl.mutateAsync(Al),resolve:Al=>tl.mutateAsync(Al)}}),Oa&&Oa.some(Al=>Al.pairs>0)&&jsxRuntimeExports.jsx(ReviewerAgreementCard,{reviewers:Oa}),Qr?jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>Fa(Al=>!Al),className:"flex w-full items-center gap-3 rounded-lg px-4 py-2.5 text-left transition-colors hover:bg-muted/40",children:[qa?jsxRuntimeExports.jsx(ChevronDown,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[Qr.nAnchors,"/",Qr.pilotTarget," labeled"]}),jsxRuntimeExports.jsxs("span",{className:"truncate text-xs text-muted-foreground",children:[$?`${$.remaining} to review`:"",Qr.mde!=null&&` · MDE ±${(Qr.mde*100).toFixed(0)}pp`,Na&&Na.total>0&&` · ${Na.discriminating}/${Na.total} cases discriminate`,Aa&&(Aa.engaged?jsxRuntimeExports.jsx("span",{className:"text-teal-500",children:` · pooled ✓ (${Aa.poolTargets} targets / ${Aa.poolAnchors} anchors)`}):" · rectifier: target-specific")]})]}),jsxRuntimeExports.jsx("div",{className:"mt-1.5 h-1.5 w-full rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-1.5 rounded-full bg-primary transition-all",style:{width:`${Math.min(100,Math.round(Qr.nAnchors/Qr.pilotTarget*100))}%`}})})]})]}),qa&&jsxRuntimeExports.jsxs("div",{className:"space-y-4 border-t border-border p-4",children:[jsxRuntimeExports.jsx(AnchorProgressCard,{check:Qr,judge:ja,pooling:Aa}),Na&&Na.total>0&&jsxRuntimeExports.jsx(CaseDiscriminationCard,{data:Na})]})]}):Na&&Na.total>0&&jsxRuntimeExports.jsx(CaseDiscriminationCard,{data:Na}),$?$.remaining===0?jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:"All caught up — every LLM-judged assertion of this target is reviewed."}):Tl?jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 p-3 border-b border-border",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",title:Tl.configuration==="with_target"?"This run executed WITH the content under test in the agent's context":"Baseline arm — this run executed WITHOUT the content under test",children:Tl.configuration==="with_target"?"with instruction":"baseline · no instruction"}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 break-words font-mono text-sm",children:[Tl.evalName," · run #",Tl.runNumber]})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[jsxRuntimeExports.jsx("span",{className:"mr-1 text-xs text-muted-foreground",children:"batch"}),$.runs.map((Al,Ml)=>{const Ql=nu(Al);return jsxRuntimeExports.jsx("button",{onClick:()=>Ma(Ml),title:`${Al.evalName} · ${Al.configuration}${Ql==="done"?" · reviewed":Ql==="partial"?" · partially reviewed":""}`,className:cn$1("h-6 min-w-6 rounded border px-1 font-mono text-[11px] transition-colors",Ql==="done"?"bg-teal-500/10 text-teal-500":Ql==="partial"?"bg-amber-500/10 text-amber-500":"text-muted-foreground hover:text-foreground",Ml===Ba?"border-primary/70":"border-border"),children:Ql==="done"?"✓":Ml+1},Al.id)})]})]}),jsxRuntimeExports.jsxs("div",{className:"p-4 grid gap-4 xl:grid-cols-2",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-3 xl:sticky xl:top-4 xl:self-start",children:[jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border","data-testid":"review-input-panel",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/60 bg-muted/40 px-3 py-1.5",children:[jsxRuntimeExports.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Input — what the agent was asked"}),jsxRuntimeExports.jsx(CopyButton,{text:Tl.prompt,what:"prompt"})]}),jsxRuntimeExports.jsx("p",{className:"max-h-44 overflow-y-auto whitespace-pre-wrap p-3 text-sm",children:Tl.prompt})]}),Tl.configuration==="with_target"&&Ia&&jsxRuntimeExports.jsxs("details",{className:"rounded-md border border-border","data-testid":"review-target-panel",children:[jsxRuntimeExports.jsxs("summary",{className:"cursor-pointer rounded-md bg-muted/40 px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground transition-colors hover:text-foreground",children:["Also in context — the ",La," under test"]}),jsxRuntimeExports.jsx("pre",{className:"max-h-60 overflow-y-auto whitespace-pre-wrap border-t border-border/60 p-3 text-xs",children:Ia})]}),!Tl.output&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-dashed border-border px-3 py-2.5 text-xs text-muted-foreground",children:"No output was captured for this run — the judge graded an empty transcript. Treat its passes with suspicion."}),Tl.output&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border","data-testid":"review-output-panel",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/60 bg-muted/40 px-3 py-1.5",children:[jsxRuntimeExports.jsxs("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:["Output — what the judge graded",Tl.outputTruncated?" (first 20k chars)":""]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-0.5",children:[jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>Ga(Al=>!Al),className:"rounded px-1.5 py-0.5 text-[11px] text-muted-foreground/70 transition-colors hover:text-foreground",children:Ka?"Collapse":"Show all"}),jsxRuntimeExports.jsx(CopyButton,{text:Tl.output,what:"output"})]})]}),jsxRuntimeExports.jsx("pre",{ref:Il,className:cn$1("text-xs p-3 overflow-x-auto overflow-y-auto whitespace-pre-wrap rounded-b-md bg-muted/30",Ka?"max-h-none":"max-h-[26rem]"),children:ql.segments?ql.segments.map((Al,Ml)=>{if(!Al.highlighted)return jsxRuntimeExports.jsx("span",{children:Al.text},Ml);const Ql=ql.segments.findIndex(eu=>eu.highlighted)===Ml;return jsxRuntimeExports.jsx("mark",{ref:Ql?Fl:void 0,className:"bg-teal-500/25 text-inherit rounded-sm",children:Al.text},Ml)}):Tl.output})]})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Judge grades — did the judge get each one right?"}),jsxRuntimeExports.jsx(InfoTip,{content:"You're checking the AI JUDGE, not re-grading the output. For each assertion, decide whether the judge's pass/fail verdict was correct: approve if the judge got it right, reject if it got it wrong. Each click is one human anchor that calibrates how much to trust the judge."})]}),Tl.expectations.map(Al=>{const Ml=Al.method==="llm"&&!Al.errored,Ql=Ml?ol(Tl,Al.index):null,eu=Ml&&Al.index===Nl,xu=Ml&&Al.index===Dl;return jsxRuntimeExports.jsxs("div",{onMouseEnter:Ml?()=>Zl(Al.index):void 0,onMouseLeave:Ml?()=>Zl(null):void 0,className:cn$1("rounded-md border p-3 transition-colors",eu?"border-primary/60 bg-primary/[0.04]":"border-border"),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2.5",children:[Al.errored?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"mt-0.5 shrink-0 text-[10px] text-muted-foreground",title:"The grader crashed or the assertion definition is broken — no verdict exists to review. Re-run grading.",children:"grader errored"}):Ml?jsxRuntimeExports.jsxs("span",{className:cn$1("mt-0.5 shrink-0 rounded px-1.5 py-0.5 font-mono text-[10px] font-medium",Al.passed?"bg-teal-500/10 text-teal-500":"bg-red-500/10 text-red-500"),children:["Judge: ",Al.passed?"PASS":"FAIL"]}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"mt-0.5 shrink-0 text-[10px]",children:["auto ",Al.passed?"✓":"✗"]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"font-mono text-sm",children:Al.text}),Al.evidence&&jsxRuntimeExports.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{className:"font-medium text-muted-foreground/70",children:["Judge's evidence:"," "]}),Al.evidence]}),xu&&(ql.count>0?jsxRuntimeExports.jsxs("p",{className:"mt-1 text-[11px] text-teal-500",children:[ql.count," cited span",ql.count===1?"":"s"," highlighted in the output above"]}):jsxRuntimeExports.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground/70",children:"evidence isn't quoted verbatim — nothing to highlight"}))]})]}),Ml&&jsxRuntimeExports.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center gap-2 pl-0.5",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>hl(Tl.id,Al.index,"approve",Ql),disabled:dl.isPending||fl.isPending,className:cn$1("flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs transition-colors",Ql==="approve"?"border-teal-500/60 bg-teal-500/10 text-teal-500":"border-border text-muted-foreground hover:border-teal-500/40 hover:text-teal-500"),children:[jsxRuntimeExports.jsx(ThumbsUp,{className:"h-3.5 w-3.5"})," Judge was right",eu&&jsxRuntimeExports.jsx(Kbd,{children:"1"})]}),jsxRuntimeExports.jsxs("button",{onClick:()=>hl(Tl.id,Al.index,"reject",Ql),disabled:dl.isPending||fl.isPending,className:cn$1("flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs transition-colors",Ql==="reject"?"border-red-500/60 bg-red-500/10 text-red-500":"border-border text-muted-foreground hover:border-red-500/40 hover:text-red-500"),children:[jsxRuntimeExports.jsx(ThumbsDown,{className:"h-3.5 w-3.5"})," Judge was wrong",eu&&jsxRuntimeExports.jsx(Kbd,{children:"2"})]}),Ql&&jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"✓ recorded"})]}),Ml&&Ql==="reject"&&(()=>{var Bl;const fu=`${Tl.id}:${Al.index}`,Ou=((Bl=nl.get(fu))==null?void 0:Bl.note)??"",yu=Va[fu]??Ou,ic=yu!==Ou,Iu=()=>dl.mutate({runId:Tl.id,expectationIndex:Al.index,verdict:"reject",note:yu.trim()||null},{onError:()=>ue$1.error("Note didn't save — try again.")});return jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2 pl-0.5",children:[jsxRuntimeExports.jsx("input",{type:"text",value:yu,maxLength:2e3,onChange:ru=>Ja(Mu=>({...Mu,[fu]:ru.target.value})),onKeyDown:ru=>{ru.key==="Enter"&&ic&&(ru.preventDefault(),Iu())},placeholder:"Why was the judge wrong? (optional — saved with the label)",className:"h-7 min-w-0 flex-1 rounded-md border border-border bg-background px-2 text-xs placeholder:text-muted-foreground/60 focus:border-primary/50 focus:outline-none"}),jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",disabled:!ic||dl.isPending,onClick:Iu,children:Ou&&!ic?"Saved":"Save note"})]})})()]},Al.index)})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t border-border p-3",children:[jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 basis-48 text-xs text-muted-foreground",children:[pl,"/",ul.length," assertions reviewed",jl?jsxRuntimeExports.jsx("span",{className:"text-teal-500",children:" · this run now counts toward the pilot"}):ul.length>1?jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/70",children:[" ","· label all ",ul.length," for this run to count toward the pilot"]}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[!jl&&ul.length>1&&jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",disabled:dl.isPending,onClick:()=>{for(const Al of ul)ol(Tl,Al.index)==null&&hl(Tl.id,Al.index,"approve",null)},children:["Mark all ",ul.length," right"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:jl?"default":"ghost",onClick:()=>Ma(Ba+1),children:[jl?"Next run":"Skip run",jsxRuntimeExports.jsx(Kbd,{className:"ml-1.5 border-transparent bg-transparent",children:jl?"↵":"S"}),jsxRuntimeExports.jsx(ChevronRight,{className:"ml-0.5 h-3 w-3"})]})]})]})]}):jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-6 text-center space-y-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Batch reviewed — ",$.remaining," run",$.remaining===1?"":"s"," still need",$.remaining===1?"s":""," review."]}),jsxRuntimeExports.jsxs(Button,{size:"sm",disabled:ts,onClick:()=>{Ma(0),is()},children:[ts&&jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 mr-1.5 animate-spin"}),"Load next batch"]})]}):jsxRuntimeExports.jsx(Skeleton,{className:"h-48 w-full"})]})}const FINISHED_FILTERS=["all","evolution","decided","skipped","failed"],FinishedFilterSchema=enumType(FINISHED_FILTERS),PAGE_SIZES=[20,50,100],JobOutcomeSchema=enumType(["ok","skipped","decided","failed"]),PendingKindSchema=objectType({kind:stringType(),count:numberType(),oldestMinutes:numberType()}).strict(),WorkerVerdictSchema=objectType({severity:enumType(["ok","warn","fail"]),headline:stringType(),hints:arrayType(stringType()),stuck:arrayType(PendingKindSchema),unclaimable:arrayType(PendingKindSchema),engineBlocked:arrayType(PendingKindSchema)}).strict(),WorkerSchema=objectType({present:booleanType(),active:booleanType(),ageSeconds:numberType().nullable(),clientName:stringType().nullable(),clientVersion:stringType().nullable(),lastHeartbeat:stringType().nullable()}).strict(),ReviewGateTargetSchema=objectType({id:stringType(),name:stringType(),awaitingReview:numberType(),humanLabeled:numberType(),humanLabeledWith:numberType(),humanLabeledWithout:numberType(),pilotTarget:numberType()}).strict(),ReviewGateSchema=objectType({blocking:booleanType(),totalAwaitingReview:numberType(),targets:arrayType(ReviewGateTargetSchema)}).strict(),RunningJobSchema=objectType({id:stringType(),kind:stringType(),label:stringType().nullable(),claimedAt:stringType().nullable(),elapsedSeconds:numberType().nullable(),leaseHealthy:booleanType()}).strict(),QueuedJobSchema=objectType({id:stringType(),kind:stringType(),label:stringType().nullable(),createdAt:stringType(),waitedSeconds:numberType(),attempts:numberType()}).strict(),FinishedJobSchema=objectType({id:stringType(),kind:stringType(),label:stringType().nullable(),finishedAt:stringType().nullable(),durationSeconds:numberType().nullable(),outcome:JobOutcomeSchema,reason:stringType().nullable(),detail:stringType().nullable()}).strict(),LoopProposalSchema=objectType({id:stringType(),evalTargetId:stringType().nullable(),targetName:stringType().nullable(),createdAt:stringType(),decision:stringType(),applied:booleanType(),effectClass:stringType(),proposalSource:stringType()}).strict(),LoopChangesSchema=objectType({decisions:numberType(),applied:numberType(),byDecision:objectType({promote:numberType(),revert:numberType(),refuse:numberType()}).strict(),readyToApply:numberType(),readyToApplyTargetId:stringType().nullable(),readyToApplyPromotionId:stringType().nullable(),lastAppliedAt:stringType().nullable(),lastDecidedAt:stringType().nullable(),suggestionsProposed:numberType(),suggestionsAccepted:numberType(),suggestionsPending:numberType(),lastAcceptedAt:stringType().nullable(),landedTotal:numberType(),window:objectType({hours:numberType(),landed:numberType(),decisions:numberType(),promotionsApplied:numberType(),adoptionApplied:numberType(),suggestionsSurfaced:numberType(),suggestionsAccepted:numberType(),suggestionsDeclined:numberType()}).strict()}).strict(),DeliveryProjectSchema=objectType({projectId:stringType(),name:stringType().nullable(),canonicalPath:stringType().nullable(),canonicalLastSeenAt:stringType().nullable(),stale:booleanType(),lastActivityAt:stringType().nullable(),lastAnalysedAt:stringType().nullable(),suggestionsPending:numberType(),suggestionsAccepted:numberType(),lastAcceptedAt:stringType().nullable()}).strict(),RecommendationApplicationSchema=objectType({id:stringType(),instructionId:stringType(),title:stringType(),artifact:stringType(),harness:stringType(),targetPath:stringType(),projectPath:stringType(),status:stringType(),applyMode:stringType(),verdictDetail:stringType().nullable(),updatedAt:stringType()}).strict(),PromotionPathProjectSchema=objectType({projectId:stringType(),trials:objectType({running:numberType(),orphaned:numberType(),eligible:numberType(),maxConcurrent:numberType(),maxPerRun:numberType(),blocked:enumType(["none","concurrency","per-run","no-candidates"])}).strict(),autoAccept:objectType({enabled:booleanType(),usedInWindow:numberType(),maxPerWindow:numberType(),maxPerRun:numberType(),windowDays:numberType(),eligible:numberType(),windowResetsAt:stringType().nullable()}).strict()}).strict(),LoopSummarySchema=objectType({worker:WorkerSchema,verdict:WorkerVerdictSchema,reviewGate:ReviewGateSchema,running:arrayType(RunningJobSchema),queued:arrayType(QueuedJobSchema),failedInWindow:numberType(),proposals:arrayType(LoopProposalSchema),proposalTotal:numberType(),changes:LoopChangesSchema,counts:objectType({experimentsRunning:numberType(),suggestions:recordType(stringType(),numberType())}).strict(),windowHours:numberType()}).strict(),LoopDiagnosticsSchema=objectType({recent:arrayType(FinishedJobSchema),recentTotal:numberType(),filterCounts:objectType({all:numberType(),evolution:numberType(),decided:numberType(),skipped:numberType(),failed:numberType()}).strict(),insights:objectType({entries:numberType(),distinct:numberType(),repeated:numberType(),dismissed:numberType(),maxTimesGenerated:numberType(),lastSeenAt:stringType().nullable()}).strict(),delivery:objectType({projects:arrayType(DeliveryProjectSchema),total:numberType(),staleCount:numberType()}).strict(),promotionPaths:objectType({projects:arrayType(PromotionPathProjectSchema)}).strict(),adoption:objectType({available:booleanType(),counts:recordType(stringType(),numberType()),applications:arrayType(RecommendationApplicationSchema)}).strict(),windowHours:numberType(),limit:numberType(),filter:FinishedFilterSchema}).strict();LoopSummarySchema.merge(LoopDiagnosticsSchema).strict();Object.keys(LoopSummarySchema.shape);Object.keys(LoopDiagnosticsSchema.shape);const loopQueryKeys={summary:es=>["loop","summary",es.hours,es.limit],diagnostics:es=>["loop","diagnostics",es.hours,es.limit,es.filter]};function summaryPollInterval(es){var ts,is;return(((ts=es==null?void 0:es.running)==null?void 0:ts.length)??0)>0||(((is=es==null?void 0:es.queued)==null?void 0:is.length)??0)>0?POLL.LIVE:POLL.HEARTBEAT}function assertLoopPayload(es,$){const ts=es==="summary"?["running","queued","proposals"]:["recent"],is=$;if(!(typeof is=="object"&&is!==null&&ts.every(Qr=>Array.isArray(is[Qr]))&&(es==="summary"?typeof is.changes=="object"&&is.changes!==null&&typeof is.worker=="object":typeof is.filterCounts=="object"&&is.filterCounts!==null))){const Qr=typeof $=="string"?`${$.slice(0,40).replace(/\s+/g," ")}…`:typeof $;throw new Error(`/api/loop/${es} returned something that is not a loop ${es} (got ${Qr}). An API that predates this page answers with the SPA fallback — is the API you are talking to current?`)}return $}function diagnosticsQuery(es){return{enabled:es.open,refetchInterval:es.open?POLL.HEARTBEAT:!1}}function diagnosticsPanelState(es){return es.open?es.hasData?"ready":es.isError?"error":"loading":"closed"}function headlineInputs(es){return{workerPresent:es.worker.present,leaseUnhealthy:es.running.some($=>!$.leaseHealthy),readyToApply:es.changes.readyToApply,failedRecently:es.failedInWindow,running:es.running.length,queued:es.queued.length,engineBlocked:(es.verdict.engineBlocked??[]).reduce(($,ts)=>$+ts.count,0)}}function useProvenanceImpact(){return useQuery({queryKey:["provenance-impact"],queryFn:()=>apiGet("/api/insights/provenance-impact"),refetchInterval:POLL.SLOW})}function usePromotionDetail(es,$){return useQuery({queryKey:["promotion",es],queryFn:()=>apiGet(`/api/promotions/${es}`),enabled:$&&!!es,staleTime:5*6e4})}function useApplyPromotion(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/promotions/${$}/apply`,{}),onSuccess:()=>{es.invalidateQueries({queryKey:["loop"]}),es.invalidateQueries({queryKey:["promotion"]})}})}function useRunLoopNow(){const es=useQueryClient();return useMutation({mutationFn:()=>apiPost("/api/loop/run-now",{}),onSuccess:()=>{es.invalidateQueries({queryKey:["loop"]})}})}function useLoopSummary(es){const $=new URLSearchParams({hours:String(es.hours),limit:String(es.limit)});return useQuery({queryKey:loopQueryKeys.summary(es),queryFn:async()=>assertLoopPayload("summary",await apiGet(`/api/loop/summary?${$.toString()}`)),placeholderData:ts=>ts,refetchInterval:ts=>summaryPollInterval(ts.state.data)})}function useLoopDiagnostics(es,$){const ts=new URLSearchParams({hours:String(es.hours),limit:String(es.limit),filter:es.filter}),is=diagnosticsQuery($);return useQuery({queryKey:loopQueryKeys.diagnostics(es),queryFn:async()=>assertLoopPayload("diagnostics",await apiGet(`/api/loop/diagnostics?${ts.toString()}`)),enabled:is.enabled,placeholderData:cs=>cs,refetchInterval:is.refetchInterval})}const MAX_LINES=4e3,toLines=es=>es===""?[]:es.split(`
|
|
143
|
-
`);function lineDiff(es,$){const ts=toLines(es),is=toLines($);if(ts.length>MAX_LINES||is.length>MAX_LINES)return[...ts.map((Aa,Oa)=>({op:"remove",text:Aa,oldLine:Oa+1,newLine:null})),...is.map((Aa,Oa)=>({op:"add",text:Aa,oldLine:null,newLine:Oa+1}))];const cs=Array.from({length:ts.length+1},()=>new Array(is.length+1).fill(0));for(let Aa=ts.length-1;Aa>=0;Aa--)for(let Oa=is.length-1;Oa>=0;Oa--)cs[Aa][Oa]=ts[Aa]===is[Oa]?cs[Aa+1][Oa+1]+1:Math.max(cs[Aa+1][Oa],cs[Aa][Oa+1]);const Qr=[];let ja=0,Na=0;for(;ja<ts.length&&Na<is.length;)ts[ja]===is[Na]?(Qr.push({op:"same",text:ts[ja],oldLine:ja+1,newLine:Na+1}),ja++,Na++):cs[ja+1][Na]>=cs[ja][Na+1]?(Qr.push({op:"remove",text:ts[ja],oldLine:ja+1,newLine:null}),ja++):(Qr.push({op:"add",text:is[Na],oldLine:null,newLine:Na+1}),Na++);for(;ja<ts.length;)Qr.push({op:"remove",text:ts[ja],oldLine:++ja,newLine:null});for(;Na<is.length;)Qr.push({op:"add",text:is[Na],oldLine:null,newLine:++Na});return Qr}function toHunks(es,$=3){const ts=new Set;es.forEach((Na,Aa)=>{if(Na.op!=="same")for(let Oa=Math.max(0,Aa-$);Oa<=Math.min(es.length-1,Aa+$);Oa++)ts.add(Oa)});const is=[];let cs=[],Qr=0,ja=0;return es.forEach((Na,Aa)=>{ts.has(Aa)?(cs.length===0&&(Qr=ja,ja=0),cs.push(Na)):(cs.length>0&&(is.push({lines:cs,skippedBefore:Qr}),cs=[]),ja++)}),cs.length>0&&is.push({lines:cs,skippedBefore:Qr}),is}function diffStat(es){let $=0,ts=0;for(const is of es)is.op==="add"?$++:is.op==="remove"&&ts++;return{added:$,removed:ts}}function EvidenceJson({label:es,value:$}){return Object.keys($).length===0?null:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-foreground",children:es}),jsxRuntimeExports.jsx("pre",{className:"mt-1 overflow-x-auto rounded border border-border bg-background/60 p-2 text-xs text-muted-foreground",children:JSON.stringify($,null,2)})]})}function PromotionDetailPanel({promotionId:es,open:$,allowApply:ts=!1,testId:is}){const{data:cs,isLoading:Qr,isError:ja}=usePromotionDetail(es,$),Na=useApplyPromotion();if(!$)return null;const Aa=cs?lineDiff(cs.fromContent,cs.toContent):[],Oa=cs?toHunks(Aa):[],Ia=diffStat(Aa);return jsxRuntimeExports.jsxs("div",{className:"reveal min-w-0 border-t border-border bg-muted/10 px-3 py-3","data-testid":is??`proposal-detail-${es}`,children:[Qr&&jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}),ja&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-400/90",children:"Could not load this proposed change."}),cs&&jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"grid gap-3 text-sm md:grid-cols-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Decision rationale"}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-foreground",children:cs.rationale||"No final rationale was recorded."})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Proposal rationale"}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-foreground",children:cs.proposalRationale||"No proposal rationale was recorded."})]})]}),cs.refusals.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-amber-400",children:"Refusal reasons"}),jsxRuntimeExports.jsx("ul",{className:"list-disc space-y-1 pt-1 pl-5 text-sm text-foreground",children:cs.refusals.map((La,Ba)=>jsxRuntimeExports.jsx("li",{children:La},Ba))})]}),cs.touchedSections.length>0&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"font-medium text-foreground",children:"Touched sections:"})," ",cs.touchedSections.join(" · ")]}),jsxRuntimeExports.jsxs("div",{className:"grid min-w-0 gap-3 md:grid-cols-2",children:[jsxRuntimeExports.jsx(EvidenceJson,{label:"Verdict evidence",value:cs.verdict}),jsxRuntimeExports.jsx(EvidenceJson,{label:"Decision gates",value:cs.gates})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("p",{className:"pb-1 font-mono text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{className:"text-teal-400",children:["+",Ia.added]})," ",jsxRuntimeExports.jsxs("span",{className:"text-amber-400",children:["−",Ia.removed]})," lines"]}),jsxRuntimeExports.jsx("div",{className:"max-h-96 max-w-full overflow-auto rounded border border-border bg-background/50","data-testid":"promotion-diff",children:jsxRuntimeExports.jsx("div",{className:"w-max min-w-full font-mono text-xs leading-relaxed",children:Oa.map((La,Ba)=>jsxRuntimeExports.jsxs("div",{children:[La.skippedBefore>0&&jsxRuntimeExports.jsxs("div",{className:"bg-muted/30 px-2 py-0.5 text-muted-foreground",children:["… ",La.skippedBefore," unchanged line",La.skippedBefore===1?"":"s"]}),La.lines.map((Ma,qa)=>jsxRuntimeExports.jsxs("div",{className:cn$1("px-2",Ma.op==="add"&&"bg-teal-400/10 text-teal-300",Ma.op==="remove"&&"bg-amber-400/10 text-amber-300",Ma.op==="same"&&"text-muted-foreground"),children:[jsxRuntimeExports.jsx("span",{className:"select-none pr-2 opacity-50",children:Ma.op==="add"?"+":Ma.op==="remove"?"−":" "}),Ma.text||" "]},qa))]},Ba))})})]}),ts&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:Na.isPending||Na.isSuccess,onClick:()=>Na.mutate(es),className:cn$1("rounded border px-3 py-1 text-xs transition-colors duration-150",Na.isSuccess?"border-teal-400/40 text-teal-400":"cursor-pointer border-teal-400/40 text-teal-400 hover:bg-teal-400/10",Na.isPending&&"opacity-60"),"data-testid":"apply-promotion",children:Na.isSuccess?"Applied":Na.isPending?"Applying…":"Apply this change"}),Na.isError&&jsxRuntimeExports.jsx("span",{className:"text-xs text-amber-400/90","data-testid":"apply-error",children:Na.error instanceof Error?Na.error.message:"Could not apply this change."})]})]})]})}function PromotionsTab({promotions:es,isLoading:$}){const[ts,is]=reactExports.useState(null);return $?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading promotions…"}):es.length===0?jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-border px-4 py-3",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No evolution decisions yet. The nightly loop records one row here per measured proposal — promote, revert, or refuse."})}):jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-border divide-y divide-border",children:es.map(cs=>{const Qr=ts===cs.id;return jsxRuntimeExports.jsxs("div",{"data-testid":"promotion-row",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>is(Qr?null:cs.id),"aria-expanded":Qr,"aria-controls":`proposal-detail-${cs.id}`,className:"flex min-h-11 w-full cursor-pointer items-start justify-between gap-4 px-4 py-3 text-left hover:bg-muted/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring","data-testid":`promotion-toggle-${cs.id}`,children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[Qr?jsxRuntimeExports.jsx(ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("p",{className:"font-mono text-sm",children:[cs.decision," · ",cs.effectClass," · ",new Date(cs.createdAt).toLocaleDateString()]}),jsxRuntimeExports.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["via ",cs.proposalSource]}),cs.rationale&&jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-muted-foreground",children:cs.rationale})]})]}),jsxRuntimeExports.jsx("span",{className:cn$1("shrink-0 rounded border px-2 py-0.5 text-xs",cs.applied?"border-teal-400/40 text-teal-400":"border-muted-foreground/40 text-muted-foreground"),children:cs.applied?"applied":"not applied"})]}),jsxRuntimeExports.jsx(PromotionDetailPanel,{promotionId:cs.id,open:Qr})]},cs.id)})})}function ActiveJobCard({job:es}){const $=es.progress,ts=$.total>0?Math.round($.completed/$.total*100):0;return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 bg-secondary/20 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin text-primary"}),jsxRuntimeExports.jsxs("span",{className:"text-sm font-medium",children:[es.status==="pending"&&"Waiting for CLI worker to pick up job...",es.status==="claimed"&&`Claimed by ${es.claimedBy}. Starting...`,es.status==="running"&&($.message||"Running...")]})]}),$.total>0&&jsxRuntimeExports.jsxs("span",{className:"text-sm font-mono text-muted-foreground",children:[$.completed,"/",$.total," (",ts,"%)"]})]}),$.total>0&&jsxRuntimeExports.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:jsxRuntimeExports.jsx("div",{className:"bg-primary rounded-full h-2 transition-all duration-300",style:{width:`${ts}%`}})}),$.current&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground font-mono truncate",children:$.current})]})}function BackgroundMeasurement({targetId:es}){var Na,Aa,Oa,Ia;const $=useQueryClient(),ts=["eval-targets",es,"background"],is=useQuery({queryKey:ts,queryFn:()=>apiGet(`/api/eval-targets/${es}/background`),refetchInterval:15e3}),cs=useMutation({mutationFn:La=>apiPatch(`/api/eval-targets/${es}/background`,{enabled:La}),onSuccess:()=>{$.invalidateQueries({queryKey:ts})}}),Qr=is.data,ja=is.error??cs.error;return jsxRuntimeExports.jsxs("section",{"aria-label":"Background measurement",className:"rounded-lg border border-border p-4 space-y-2 text-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[jsxRuntimeExports.jsxs("h3",{className:"font-medium",children:["Background measurement",Qr?` · ${Qr.enabled?"On":"Off"}`:""]}),Qr&&jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",disabled:cs.isPending||!Qr.enabled&&Qr.blockers.length>0,onClick:()=>cs.mutate(!Qr.enabled),children:cs.isPending?"Saving…":Qr.enabled?"Pause nightly trials":"Enable nightly trials"})]}),ja&&jsxRuntimeExports.jsx("p",{role:"alert",className:"break-words text-destructive",children:ja.message}),!Qr&&!ja&&jsxRuntimeExports.jsx("p",{role:"status",children:"Loading schedule…"}),Qr&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground",children:[Qr.schedule,"; up to ",Qr.maxRuns/2," paired cases per night, rotating through ",Qr.liveCases," cases until sufficient evidence. Uses your local worker and subscription quota. Does not rewrite files."]}),jsxRuntimeExports.jsxs("p",{className:"break-words",children:["Actor: ",Qr.measurement?`${Qr.measurement.engine} · ${Qr.measurement.model??"CLI default"}`:"Existing worker defaults","; grader: ",Qr.judge.engine," · ",Qr.judge.model??"default",". ",jsxRuntimeExports.jsx(Link,{className:"underline",to:"/settings",children:"Measurement settings"})]}),!Qr.ready&&jsxRuntimeExports.jsx("p",{role:"status",className:"text-amber-500",children:"Waiting for a compatible worker. Start or upgrade your local worker; installed engines do not guarantee account credits."}),Qr.blockers.map(La=>jsxRuntimeExports.jsx("p",{className:"text-amber-500",children:La},La)),Qr.latest?jsxRuntimeExports.jsxs("p",{className:"break-words","data-testid":"background-last-result",children:["Last batch: ",Qr.latest.status," · ",new Date(Qr.latest.createdAt).toLocaleString(),((Na=Qr.latest.result)==null?void 0:Na.ranRuns)!=null&&` · ${Qr.latest.result.ranRuns} completed, ${Qr.latest.result.failedRuns??0} failed`,` — ${Qr.latest.error??((Aa=Qr.latest.result)==null?void 0:Aa.failures)??((Oa=Qr.latest.result)==null?void 0:Oa.reason)??((Ia=Qr.latest.result)==null?void 0:Ia.skipped)??"Waiting for results"}`]}):jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"No background batch yet. Results appear in Runs and Review below."}),!Qr.enabled&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"No new nightly batches will start. A batch already executing may finish."})]})]})}const label=es=>typeof es=="string"&&es?es:"Not recorded",number=es=>typeof es=="number"&&Number.isFinite(es)&&es>=0?es:null;function RunEvidence({run:es}){const $=number(es.outputs.costUsd),ts=number(es.timing.total_tokens);return jsxRuntimeExports.jsxs("div",{className:"space-y-2 text-xs","data-testid":"run-evidence",children:[jsxRuntimeExports.jsxs("dl",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2 [&_dd]:break-words [&_dt]:text-muted-foreground",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Harness / provider"}),jsxRuntimeExports.jsxs("dd",{children:[label(es.outputs.engine)," / ",label(es.outputs.provider)]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Resolved model"}),jsxRuntimeExports.jsx("dd",{children:label(es.outputs.model)})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Tokens"}),jsxRuntimeExports.jsx("dd",{children:ts===null?"Not recorded":ts.toLocaleString()})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Estimated API-equivalent cost"}),jsxRuntimeExports.jsx("dd",{children:$===null?"Unavailable — not zero":`$${$.toFixed(5)}`})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Methodology / delivery"}),jsxRuntimeExports.jsxs("dd",{children:[label(es.outputs.methodology)," / ",label(es.outputs.delivery)]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Judge"}),jsxRuntimeExports.jsxs("dd",{children:[label(es.grading.judge_engine)," / ",label(es.grading.judge_model)]})]})]}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Compare revisions within the same harness, provider, model and methodology. Dollar estimates are not subscription charges or proven savings."}),es.outputs.isolated===!1&&jsxRuntimeExports.jsx("p",{className:"text-amber-500",children:"No repository workspace was available for this run."}),Array.isArray(es.outputs.leakedFiles)&&es.outputs.leakedFiles.length>0&&jsxRuntimeExports.jsx("p",{role:"alert",className:"text-destructive",children:"Contaminated workspace: instruction files survived baseline isolation."}),typeof es.outputs.error=="string"&&jsxRuntimeExports.jsx("p",{role:"alert",className:"break-words text-destructive",children:es.outputs.error})]})}const TAB_KEYS=["chat","evals","runs","review","benchmarks","comparisons","promotions"],RUNS_PAGE_LIMIT=50,COMPARISONS_PAGE_LIMIT=50;function EvalTargetDetailPage(){const{id:es}=useParams(),[$,ts]=useTabParam(TAB_KEYS,"chat"),{data:is,isLoading:cs}=useEvalTarget(es),{data:Qr,isLoading:ja}=useEvals(es),{data:Na,isLoading:Aa}=useEvalRuns(es),{data:Oa,isLoading:Ia}=useBenchmarks(es),{data:La,isLoading:Ba}=useEvalComparisons(es),{data:Ma}=useGradeAnnotations(es),{data:qa}=useJudgeCalibration(es),{data:Fa,isFetching:Ha,refetch:Ka}=useAnnotationQueue(es),{data:Ga,isLoading:Va}=usePromotions(es),{data:Ja}=useJudgeDisagreements(es),{user:Ya}=useAuth(),{data:el}=useEvalJobs(es),tl=useCreateEvalJob(),rl=useCancelEvalJob(),cl=useRealtimeEvalJobs(Ya==null?void 0:Ya.id,es),{isConnected:dl,workerCount:fl}=useWorkerStatus("cli-worker"),nl=cl??(el==null?void 0:el.find(pl=>["pending","claimed","running"].includes(pl.status)))??null,ol=!!nl&&["pending","claimed","running"].includes(nl.status),hl=(el==null?void 0:el[0])??null,Tl=!ol&&(hl==null?void 0:hl.status)==="failed"?hl:null;if(cs)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-96"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"})]});if(!is)return jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Eval target not found."});const ul=[{key:"chat",label:"Chat"},{key:"evals",label:"Evals",count:Qr==null?void 0:Qr.length},{key:"runs",label:"Runs",count:Na&&Na.length>=RUNS_PAGE_LIMIT?`${RUNS_PAGE_LIMIT}+`:Na==null?void 0:Na.length},{key:"review",label:"Review",count:Fa==null?void 0:Fa.remaining},{key:"benchmarks",label:"Benchmarks",count:Oa==null?void 0:Oa.length},{key:"comparisons",label:"Comparisons",count:La&&La.length>=COMPARISONS_PAGE_LIMIT?`${COMPARISONS_PAGE_LIMIT}+`:La==null?void 0:La.length},{key:"promotions",label:"Promotions",count:Ga==null?void 0:Ga.total}];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/eval-targets",children:jsxRuntimeExports.jsx(ArrowLeft,{className:"h-4 w-4"})})}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 basis-64",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight break-words",children:is.name}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground break-words",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"mr-2 font-mono",children:is.type}),"v",is.version,is.description&&` — ${is.description}`]})]}),jsxRuntimeExports.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("div",{className:`h-2 w-2 rounded-full ${dl?"bg-teal-500":"bg-red-500"}`}),dl?`${fl} worker${fl>1?"s":""} online`:"No workers"]}),ol?jsxRuntimeExports.jsxs(Button,{variant:"destructive",size:"sm",onClick:()=>nl&&rl.mutate(nl.id),disabled:rl.isPending,children:[jsxRuntimeExports.jsx(Square,{className:"h-3 w-3 mr-1.5"}),"Cancel Run"]}):jsxRuntimeExports.jsxs(Button,{size:"sm",onClick:()=>es&&tl.mutate({evalTargetId:es}),disabled:tl.isPending||!(Qr!=null&&Qr.length)||!dl,title:dl?Qr!=null&&Qr.length?void 0:"Add eval cases first — none defined for this target":"Start a CLI worker: rulemetric evals agent",children:[jsxRuntimeExports.jsx(Play,{className:"h-3 w-3 mr-1.5"}),"Run Evals"]})]})]}),jsxRuntimeExports.jsx(BackgroundMeasurement,{targetId:is.id}),!ol&&Qr&&Qr.length===0&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-amber-500 font-medium",children:"No eval cases defined"}),jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Add cases via CLI: ",jsxRuntimeExports.jsxs("code",{className:"bg-muted px-1 py-0.5 rounded text-[11px]",children:["rulemetric evals create ",es,' --name "..." --prompt "..." -e "..."']})]})]}),nl&&["pending","claimed","running"].includes(nl.status)&&jsxRuntimeExports.jsx(ActiveJobCard,{job:nl}),Tl&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-red-500/30 bg-red-500/5 px-4 py-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-red-500 font-medium",children:"Last run failed"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1 font-mono break-words",children:Tl.error??"No error recorded for this job."})]}),$!=="review"&&(((Fa==null?void 0:Fa.remaining)??0)>0||((Ja==null?void 0:Ja.length)??0)>0)&&jsxRuntimeExports.jsx("button",{type:"button","data-testid":"review-callout",onClick:()=>ts("review"),className:"group w-full rounded-lg border border-primary/40 bg-primary/[0.06] px-4 py-3 text-left transition-colors hover:bg-primary/[0.1]",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm font-medium",children:[((Fa==null?void 0:Fa.remaining)??0)>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fa.remaining," run",Fa.remaining===1?"":"s"," await your review"]}),((Fa==null?void 0:Fa.remaining)??0)>0&&((Ja==null?void 0:Ja.length)??0)>0&&" · ",((Ja==null?void 0:Ja.length)??0)>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Ja.length," label",Ja.length===1?"":"s"," flagged by a second opinion"]})]}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-[13px] text-muted-foreground",children:"For each run you'll see the prompt, the agent's output, and the judge's pass/fail on every assertion — you mark whether the judge got it right. A few minutes of labels calibrate the judge so its verdicts can be trusted."})]}),jsxRuntimeExports.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-sm font-medium text-primary",children:["Start reviewing",jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]})}),jsxRuntimeExports.jsx("div",{className:"flex gap-1 border-b border-border overflow-x-auto",children:ul.map(pl=>jsxRuntimeExports.jsxs("button",{onClick:()=>ts(pl.key),className:`shrink-0 whitespace-nowrap px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${$===pl.key?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"}`,children:[pl.label,pl.count!=null&&jsxRuntimeExports.jsxs("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",pl.count,")"]})]},pl.key))}),$==="evals"&&jsxRuntimeExports.jsx(EvalsTab,{evalCases:Qr??[],isLoading:ja}),$==="runs"&&jsxRuntimeExports.jsx(RunsTab,{targetId:es,runs:Na??[],isLoading:Aa,annotations:Ma??[]}),$==="review"&&jsxRuntimeExports.jsx(ReviewTab,{targetId:es,queue:Fa,isFetching:Ha,refetchQueue:Ka,annotations:Ma??[],powerCheck:qa==null?void 0:qa.powerCheck,judge:qa==null?void 0:qa.judge,caseDiscrimination:qa==null?void 0:qa.caseDiscrimination,pooling:qa==null?void 0:qa.pooling,reviewers:qa==null?void 0:qa.reviewers,targetContent:is.content??null,targetType:is.type}),$==="benchmarks"&&jsxRuntimeExports.jsx(BenchmarksTab,{benchmarks:Oa??[],isLoading:Ia,judgeCalibration:qa}),$==="comparisons"&&jsxRuntimeExports.jsx(ComparisonsTab,{comparisons:La??[],isLoading:Ba}),$==="promotions"&&jsxRuntimeExports.jsx(PromotionsTab,{promotions:(Ga==null?void 0:Ga.promotions)??[],isLoading:Va}),$==="chat"&&es&&jsxRuntimeExports.jsx(ChatPanel,{targetId:es})]})}function EvalsTab({evalCases:es,isLoading:$}){return $?jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"}):es.length?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:es.map(ts=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-2",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono font-medium",children:ts.name}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:ts.prompt}),ts.expectations.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:ts.expectations.map((is,cs)=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:is},cs))})]},ts.id))}):jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:"No evals defined yet."})}function RunsTab({targetId:es,runs:$,isLoading:ts,annotations:is}){const[cs,Qr]=reactExports.useState(null),ja=useAnnotateGrade(es),Na=useRemoveGradeAnnotation(es),Aa=new Map(is.map(Ia=>[`${Ia.evalRunId}:${Ia.expectationIndex}`,Ia])),Oa=(Ia,La,Ba)=>{const Ma=Aa.get(`${Ia}:${La}`);(Ma==null?void 0:Ma.verdict)===Ba?Na.mutate({runId:Ia,expectationIndex:La}):ja.mutate({runId:Ia,expectationIndex:La,verdict:Ba})};return ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"}):$.length?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[$.length>=RUNS_PAGE_LIMIT&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing the ",RUNS_PAGE_LIMIT," most recent runs — older runs are not loaded."]}),$.map(Ia=>{var Ma,qa,Fa,Ha,Ka;const La=cs===Ia.id,Ba=(qa=(Ma=Ia.grading)==null?void 0:Ma.summary)==null?void 0:qa.pass_rate;return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>Qr(La?null:Ia.id),className:"w-full flex flex-wrap items-center justify-between gap-2 p-3 text-left hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-3",children:[La?jsxRuntimeExports.jsx(ChevronDown,{className:"h-4 w-4 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Badge,{variant:Ia.status==="completed"?"default":"destructive",className:"font-mono text-xs",children:Ia.status}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm",children:[Ia.configuration," · run #",Ia.runNumber," · iter ",Ia.iteration]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[Ba!=null&&jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[(Ba*100).toFixed(0),"% pass"]}),((Fa=Ia.timing)==null?void 0:Fa.duration_ms)&&jsxRuntimeExports.jsxs("span",{children:[(Ia.timing.duration_ms/1e3).toFixed(1),"s"]}),jsxRuntimeExports.jsx("span",{children:new Date(Ia.createdAt).toLocaleDateString()})]})]}),La&&jsxRuntimeExports.jsxs("div",{className:"border-t border-border p-4 space-y-3",children:[jsxRuntimeExports.jsx(RunEvidence,{run:Ia}),((Ha=Ia.grading)==null?void 0:Ha.expectations)&&jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Expectations"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"— review each grade: your labels calibrate the judge"})]}),Ia.grading.expectations.map((Ga,Va)=>{const Ja=Aa.get(`${Ia.id}:${Va}`);return jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2 text-sm group",children:[Ga.passed?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 text-teal-500 mt-0.5 shrink-0"}):jsxRuntimeExports.jsx(CircleX,{className:"h-4 w-4 text-red-500 mt-0.5 shrink-0"}),jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports.jsx("span",{className:"font-mono",children:Ga.text}),Ga.method==="deterministic"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"ml-1.5 text-[10px] align-middle",children:"deterministic"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-xs",children:Ga.evidence})]}),Ga.method!=="deterministic"&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[jsxRuntimeExports.jsx("button",{onClick:()=>Oa(Ia.id,Va,"approve"),disabled:ja.isPending||Na.isPending,title:"Judge graded this correctly",className:`p-1 rounded transition-colors ${(Ja==null?void 0:Ja.verdict)==="approve"?"text-teal-500 bg-teal-500/10":"text-muted-foreground/50 hover:text-teal-500"}`,children:jsxRuntimeExports.jsx(ThumbsUp,{className:"h-3.5 w-3.5"})}),jsxRuntimeExports.jsx("button",{onClick:()=>Oa(Ia.id,Va,"reject"),disabled:ja.isPending||Na.isPending,title:"Judge got this grade wrong",className:`p-1 rounded transition-colors ${(Ja==null?void 0:Ja.verdict)==="reject"?"text-red-500 bg-red-500/10":"text-muted-foreground/50 hover:text-red-500"}`,children:jsxRuntimeExports.jsx(ThumbsDown,{className:"h-3.5 w-3.5"})})]})]},Va)})]}),!!((Ka=Ia.outputs)!=null&&Ka.transcript)&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:"Output"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-3 rounded-md overflow-x-auto max-h-48",children:String(Ia.outputs.transcript)})]})]})]},Ia.id)})]}):jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:"No runs yet. Execute evals via the CLI."})}function BenchmarksTab({benchmarks:es,isLoading:$,judgeCalibration:ts}){return $?jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"}):es.length?jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[ts&&jsxRuntimeExports.jsx(JudgeCalibrationCard,{data:ts}),es.map(is=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("h3",{className:"font-mono font-medium",children:["Iteration ",is.iteration]}),jsxRuntimeExports.jsx("span",{className:"text-sm text-muted-foreground",children:new Date(is.createdAt).toLocaleDateString()})]}),Object.entries(is.runSummary).map(([cs,Qr])=>cs==="delta"?jsxRuntimeExports.jsxs("div",{className:"bg-muted/50 rounded-md p-3",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:"Delta (with - without target)"}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-4 text-sm font-mono",children:Object.entries(Qr).map(([ja,Na])=>jsxRuntimeExports.jsxs("span",{children:[ja,": ",Na]},ja))}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Mean difference only — no significance test. At the default 1 run per eval this is a single-run difference and is not statistically meaningful."})]},cs):jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:cs}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:Object.entries(Qr).map(([ja,Na])=>{const Aa=Na;return jsxRuntimeExports.jsxs("div",{className:"bg-muted/30 rounded-md p-2 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs",children:ja}),jsxRuntimeExports.jsxs("div",{className:"font-mono",children:[Aa.mean.toFixed(3),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["±",Aa.stddev.toFixed(3)]})]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["[",Aa.min.toFixed(3),", ",Aa.max.toFixed(3),"]"]})]},ja)})})]},cs)),is.notes.length>0&&jsxRuntimeExports.jsx("div",{className:"text-sm space-y-1",children:is.notes.map((cs,Qr)=>jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground",children:["— ",cs]},Qr))})]},is.id))]}):jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[ts&&jsxRuntimeExports.jsx(JudgeCalibrationCard,{data:ts}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["No benchmarks yet. Run"," ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric evals benchmark"})," ","to create one."]})]})}function ComparisonsTab({comparisons:es,isLoading:$}){const[ts,is]=reactExports.useState(null);return $?jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"}):es.length?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[es.length>=COMPARISONS_PAGE_LIMIT&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing the ",COMPARISONS_PAGE_LIMIT," most recent comparisons — older ones are not loaded."]}),es.map(cs=>{var Aa,Oa;const Qr=ts===cs.id,ja=Ia=>Ia===cs.targetAId?`${cs.targetAName} v${cs.targetAVersion}`:Ia===cs.targetBId?`${cs.targetBName} v${cs.targetBVersion}`:null,Na=cs.status==="parse_failed"?"unparseable":ja(cs.winnerTargetId)??"TIE";return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>is(Qr?null:cs.id),className:"w-full flex items-center justify-between p-3 text-left hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[Qr?jsxRuntimeExports.jsx(ChevronDown,{className:"h-4 w-4 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Badge,{variant:cs.status==="parse_failed"?"destructive":cs.winnerTargetId?"default":"secondary",className:"font-mono text-xs",children:Na}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm",children:[cs.targetAName," v",cs.targetAVersion," vs ",cs.targetBName," v",cs.targetBVersion]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[cs.model&&jsxRuntimeExports.jsx("span",{className:"font-mono text-xs",children:cs.model}),jsxRuntimeExports.jsx("span",{children:new Date(cs.createdAt).toLocaleDateString()})]})]}),Qr&&jsxRuntimeExports.jsxs("div",{className:"border-t border-border p-4 space-y-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Judged blind",cs.isSwapped?" (labels swapped)":""," — winners shown unblinded."]}),cs.status==="parse_failed"?jsxRuntimeExports.jsx(ComparisonRawOutput,{id:cs.id}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[cs.overall.reasoning&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:"Overall"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:cs.overall.reasoning})]}),(Aa=cs.overall.strengthsWinner)!=null&&Aa.length||(Oa=cs.overall.weaknessesLoser)!=null&&Oa.length?jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"font-medium mb-1",children:"Winner strengths"}),jsxRuntimeExports.jsx("ul",{className:"text-muted-foreground list-disc list-inside space-y-0.5",children:(cs.overall.strengthsWinner??[]).map((Ia,La)=>jsxRuntimeExports.jsx("li",{children:Ia},La))})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"font-medium mb-1",children:"Loser weaknesses"}),jsxRuntimeExports.jsx("ul",{className:"text-muted-foreground list-disc list-inside space-y-0.5",children:(cs.overall.weaknessesLoser??[]).map((Ia,La)=>jsxRuntimeExports.jsx("li",{children:Ia},La))})]})]}):null,cs.perEval.length>0&&jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Per eval"}),cs.perEval.map((Ia,La)=>jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[jsxRuntimeExports.jsx(Badge,{variant:Ia.winnerTargetId?"default":"secondary",className:"font-mono text-xs shrink-0",children:ja(Ia.winnerTargetId)??"TIE"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"font-mono",children:Ia.evalName}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-xs",children:Ia.reasoning})]})]},La))]})]})]})]},cs.id)})]}):jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["No comparisons yet. Run"," ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric evals compare <target-a> <target-b>"})," ","to create one."]})}function ComparisonRawOutput({id:es}){const{data:$,isLoading:ts}=useEvalComparison(es);return ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-16 w-full"}):jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:"Judge output (not parseable as a structured verdict)"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-3 rounded-md overflow-x-auto max-h-48 whitespace-pre-wrap",children:($==null?void 0:$.rawOutput)??"No raw output recorded."})]})}function PublicDocsShell({children:es}){return jsxRuntimeExports.jsxs("div",{className:"min-h-screen bg-background text-foreground",children:[jsxRuntimeExports.jsx("nav",{className:"sticky top-0 z-50 border-b border-border bg-background/80 backdrop-blur-sm",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl flex items-center justify-between px-4 h-14",children:[jsxRuntimeExports.jsxs(Link,{to:"/",className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-semibold",children:"RuleMetric"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",className:"cursor-pointer",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/login",children:"Sign in"})}),jsxRuntimeExports.jsx(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/signup",children:"Get Started"})})]})]})}),jsxRuntimeExports.jsx("main",{className:"mx-auto max-w-6xl px-4 py-8",children:es})]})}function DocsRoute(){const{session:es,loading:$}=useAuth();return $?jsxRuntimeExports.jsx("div",{className:"flex h-screen items-center justify-center",children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 w-64",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-1/2"})]})}):es?jsxRuntimeExports.jsx(RootLayout,{children:jsxRuntimeExports.jsx(DocsPage,{})}):jsxRuntimeExports.jsx(PublicDocsShell,{children:jsxRuntimeExports.jsx(DocsPage,{})})}function useHarnessReleases(es,$=50){const ts=new URLSearchParams;return ts.set("harness",es),ts.set("limit",String($)),useQuery({queryKey:["harness-releases",es,$],queryFn:()=>apiGet(`/api/harness-releases?${ts}`)})}function useSyncHarnessReleases(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/harness-releases/sync",{harness:$}),onSuccess:()=>es.invalidateQueries({queryKey:["harness-releases"]})})}function AnalysisFreshnessBanner({freshness:es,totalAnalyzed:$}){if(!es||$===0)return null;const{with_timestamp:ts,pre_instrumentation:is,stale_30d:cs,oldest_analyzed_at:Qr}=es,ja=$>0?Math.round(is/$*100):0,Na=ts>0?Math.round(cs/ts*100):0;if(is===0&&cs===0)return null;const Aa=ja>=25||Na>=50?"warn":"info",Oa=Aa==="warn"?"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300":"border-border bg-muted/40 text-muted-foreground";return jsxRuntimeExports.jsxs("div",{className:`flex items-start gap-2 rounded-md border px-3 py-2 text-xs ${Oa}`,children:[Aa==="warn"?jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 shrink-0 mt-0.5"}):jsxRuntimeExports.jsx(Clock,{className:"h-4 w-4 shrink-0 mt-0.5"}),jsxRuntimeExports.jsxs("div",{className:"flex-1 font-mono space-y-0.5",children:[jsxRuntimeExports.jsx("p",{className:"font-medium",children:Aa==="warn"?"Some inputs to these stats are stale or untimestamped":"Input freshness"}),jsxRuntimeExports.jsxs("p",{children:[is>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[is," of ",$," analyzed sessions (",ja,"%) predate timestamp tracking. Re-analyze them to participate in freshness checks."]}),is>0&&cs>0&&" ",cs>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[cs," of ",ts," timestamped analyses (",Na,"%) are over 30 days old",Qr&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" ","(oldest: ",new Date(Qr).toLocaleDateString(),")"]}),"."]})]})]})]})}function jobStepLabel(es){const $=es.progress;return $!=null&&$.step&&($!=null&&$.current)&&($!=null&&$.total)?`${$.step} (${$.current}/${$.total})`:$!=null&&$.step?$.step:es.status==="claimed"?"starting...":es.status==="pending"?"queued":es.status}function JobStatusIcon({status:es}){switch(es){case"completed":return jsxRuntimeExports.jsx(CircleCheck,{className:"h-3.5 w-3.5 text-teal-500 shrink-0"});case"running":case"claimed":return jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3.5 w-3.5 text-blue-500 animate-spin shrink-0"});case"failed":return jsxRuntimeExports.jsx(CircleX,{className:"h-3.5 w-3.5 text-red-500 shrink-0"});case"pending":default:return jsxRuntimeExports.jsx(CircleDashed,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})}}function JobTracker({jobs:es}){if(es.length===0)return null;const $=es.filter(La=>La.status==="completed").length,ts=es.filter(La=>La.status==="failed").length,is=es.filter(La=>La.status==="running"||La.status==="claimed").length,cs=es.filter(La=>La.status==="pending").length,Qr=es.length,ja=$+ts,Na=ja===Qr,Aa=$/Qr*100,Oa=ts/Qr*100,Ia=is/Qr*100;return jsxRuntimeExports.jsx(Card,{className:Na?"border-teal-500/30 bg-teal-500/5":"border-blue-500/30 bg-blue-500/5",children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-4 pb-4 space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[Na?jsxRuntimeExports.jsx(Check,{className:"h-4 w-4 text-teal-500"}):jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin text-blue-500"}),jsxRuntimeExports.jsx("p",{className:"min-w-0 break-words text-sm font-medium",children:Na?Qr===1?"Recommendations ready":`All ${Qr} projects done`:Qr===1?`Generating recommendations — ${jobStepLabel(es[0])}`:`Generating recommendations — ${ja}/${Qr} complete`})]}),Qr>1&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground font-mono",children:[$>0&&jsxRuntimeExports.jsxs("span",{className:"text-teal-500",children:[$," done"]}),is>0&&jsxRuntimeExports.jsxs("span",{className:"text-blue-500",children:[is," running"]}),cs>0&&jsxRuntimeExports.jsxs("span",{children:[cs," queued"]}),ts>0&&jsxRuntimeExports.jsxs("span",{className:"text-red-500",children:[ts," failed"]})]})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden flex",children:Qr===1?(()=>{const La=es[0],Ba=La.progress,Ma=Ba!=null&&Ba.current&&(Ba!=null&&Ba.total)?Ba.current/Ba.total*100:0;return La.status==="completed"?jsxRuntimeExports.jsx("div",{className:"h-full bg-teal-500",style:{width:"100%"}}):La.status==="failed"?jsxRuntimeExports.jsx("div",{className:"h-full bg-red-500",style:{width:"100%"}}):jsxRuntimeExports.jsx("div",{className:"h-full bg-blue-500 animate-pulse transition-all duration-500",style:{width:`${Math.max(Ma,5)}%`}})})():jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Aa>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-teal-500 transition-all duration-500",style:{width:`${Aa}%`}}),Oa>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-red-500 transition-all duration-500",style:{width:`${Oa}%`}}),Ia>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-blue-500 animate-pulse transition-all duration-500",style:{width:`${Ia}%`}})]})}),Qr>1&&jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-x-6 gap-y-1",children:es.map(La=>jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-2 py-0.5 text-xs",children:[jsxRuntimeExports.jsx(JobStatusIcon,{status:La.status}),jsxRuntimeExports.jsx("span",{className:"min-w-0 flex-1 truncate font-mono",children:La.projectPath??"global"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground ml-auto shrink-0",children:La.status==="running"||La.status==="claimed"?jobStepLabel(La):La.status==="failed"?"error":La.status==="completed"?"done":"queued"})]},La.id))})]})})}function ProjectJobBadge({job:es}){return es.status==="completed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-teal-500/10 text-teal-500 border-teal-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"mr-1 h-2.5 w-2.5"})," done"]}):es.status==="failed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-red-500/10 text-red-500 border-red-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleX,{className:"mr-1 h-2.5 w-2.5"})," failed"]}):es.status==="running"||es.status==="claimed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-blue-500/10 text-blue-500 border-blue-500/20 font-mono",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-1 h-2.5 w-2.5 animate-spin"})," ",jobStepLabel(es)]}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-amber-500/10 text-amber-500 border-amber-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleDashed,{className:"mr-1 h-2.5 w-2.5"})," queued"]})}function WorkerOfflineBanner(){const{workers:es,isLoading:$}=useWorkerStatus("cli-worker");if($)return null;const ts=es.slice().sort((Qr,ja)=>new Date(ja.lastHeartbeat).getTime()-new Date(Qr.lastHeartbeat).getTime())[0];if((ts==null?void 0:ts.status)==="active")return null;const cs=ts?`${Math.round((Date.now()-new Date(ts.lastHeartbeat).getTime())/1e3)}s ago`:"never";return jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm",children:[jsxRuntimeExports.jsx("div",{className:"font-medium text-amber-500 mb-1",children:"Worker offline"}),jsxRuntimeExports.jsxs("div",{className:"text-muted-foreground",children:["No cli-worker has heartbeat'd within the last 60s (last seen: ",cs,"). Insights jobs will queue but won't run until the worker is healthy. Restart with"," ",jsxRuntimeExports.jsx("code",{className:"font-mono text-xs bg-secondary px-1 py-0.5 rounded",children:"launchctl kickstart -k gui/$UID/com.rulemetric.worker"}),"."]})]})}function formatCompact(es){return new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(es)}function parseTimestamp(es){if(!es)return null;const $=es.replace(" ","T").replace(/([+-]\d{2})$/,"$1:00"),ts=new Date($);return Number.isNaN(ts.getTime())?null:ts}function formatSessionRange(es,$){const ts=parseTimestamp(es),is=parseTimestamp($),cs={month:"short",day:"numeric",year:"numeric"};if(ts&&is){const ja=ts.getFullYear()===is.getFullYear();return`${ts.toLocaleDateString(void 0,ja?{month:"short",day:"numeric"}:cs)} – ${is.toLocaleDateString(void 0,cs)}`}const Qr=ts??is;return Qr?Qr.toLocaleDateString(void 0,cs):null}function outcomeScore(es){const $=(es.achieved??0)+(es.mostly_achieved??0),ts=Object.values(es).reduce((is,cs)=>is+cs,0);return ts?Math.round($/ts*100):null}function InsightsOverview({computed:es}){var Na;const $=outcomeScore(es.outcomes??{}),ts=es.total_sessions?Math.round(es.sessions_with_analysis/es.total_sessions*100):0,is=Object.entries(es.friction??{}).sort((Aa,Oa)=>Oa[1]-Aa[1])[0],cs=Object.entries(es.tool_counts??{}).sort((Aa,Oa)=>Oa[1]-Aa[1]).slice(0,5),Qr=((Na=cs[0])==null?void 0:Na[1])??1,ja=[{label:"Successful outcomes",value:$==null?"—":`${$}%`,detail:`${es.sessions_with_analysis} analyzed`,icon:CircleCheck},{label:"Estimated spend",value:`$${(es.estimated_cost_usd??0).toFixed(2)}`,detail:`${formatCompact(es.total_input_tokens+es.total_output_tokens)} tokens`,icon:DollarSign},{label:"Tool errors",value:es.total_tool_errors.toLocaleString(),detail:`${es.total_interruptions} interruptions`,icon:TriangleAlert},{label:"Code changed",value:`+${formatCompact(es.total_lines_added)}`,detail:`${formatCompact(es.total_lines_removed)} removed · ${es.git_commits} commits`,icon:TrendingUp}];return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:ja.map(({label:Aa,value:Oa,detail:Ia,icon:La})=>jsxRuntimeExports.jsx(Card,{className:"min-w-0",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"text-xs font-medium uppercase tracking-wide",children:Aa}),jsxRuntimeExports.jsx(La,{className:"h-4 w-4"})]}),jsxRuntimeExports.jsx("p",{className:"mt-3 text-2xl font-mono font-semibold",children:Oa}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:Ia})]})},Aa))}),es.truncated&&jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3 shrink-0"}),"Computed from your 500 most-recent sessions — spend and token totals are a floor, not a complete sum."]}),jsxRuntimeExports.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[jsxRuntimeExports.jsxs(Card,{className:"min-w-0 lg:col-span-2",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"What is slowing work down?"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[Object.entries(es.friction??{}).sort((Aa,Oa)=>Oa[1]-Aa[1]).slice(0,5).map(([Aa,Oa])=>{const Ia=Math.max(1,Object.values(es.friction).reduce((La,Ba)=>La+Ba,0));return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"mb-1 flex min-w-0 justify-between gap-2 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"min-w-0 break-words",children:Aa.replace(/_/g," ")}),jsxRuntimeExports.jsx("span",{className:"shrink-0 font-mono text-muted-foreground",children:Oa})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-full rounded-full bg-amber-500",style:{width:`${Math.max(4,Oa/Ia*100)}%`}})})]},Aa)}),!is&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No friction has been detected in analyzed sessions."})]})]}),jsxRuntimeExports.jsxs(Card,{className:"min-w-0",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-base flex items-center gap-2",children:[jsxRuntimeExports.jsx(Wrench,{className:"h-4 w-4"})," Most-used tools"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:cs.map(([Aa,Oa])=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs",children:Aa}),jsxRuntimeExports.jsx("div",{className:"h-1.5 w-20 overflow-hidden rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary",style:{width:`${Oa/Qr*100}%`}})}),jsxRuntimeExports.jsx("span",{className:"w-10 text-right font-mono text-xs text-muted-foreground",children:Oa})]},Aa))})]})]}),ts<80&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Analysis coverage is ",ts,"%. Outcome and friction metrics reflect ",es.sessions_with_analysis," of ",es.total_sessions," sessions."]})]})}function ProjectCard({project:es,hasReport:$,activeJob:ts,onClick:is}){const cs=formatSessionRange(es.firstSession,es.lastSession);return jsxRuntimeExports.jsxs(Card,{className:"min-w-0 cursor-pointer hover:border-primary/50 transition-colors",...activatable(is),children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntimeExports.jsx(CardTitle,{className:"min-w-0 break-words text-base font-mono",children:es.name}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:shrink-0",children:[ts?jsxRuntimeExports.jsx(ProjectJobBadge,{job:ts}):$?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs bg-teal-500/10 text-teal-500 border-teal-500/20",children:"Recommendations"}):null,jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-xs",children:[es.enrichedCount," enriched"]})]})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-6 gap-y-1 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:[es.sessionCount," sessions"]}),es.analyzedCount>0&&jsxRuntimeExports.jsxs("span",{children:[es.analyzedCount," analyzed"]})]}),cs&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:cs})]})]})}function ReleaseCategorySection({label:es,items:$,colorClass:ts}){const[is,cs]=reactExports.useState(!1);return $.length===0?null:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>cs(!is),className:"flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors w-full text-left cursor-pointer",children:[is?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 shrink-0"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 shrink-0"}),jsxRuntimeExports.jsx("span",{className:ts,children:es}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",$.length,")"]})]}),is&&jsxRuntimeExports.jsx("ul",{className:"mt-1.5 ml-5 space-y-1",children:$.map((Qr,ja)=>jsxRuntimeExports.jsx("li",{className:"text-xs text-muted-foreground leading-relaxed",children:Qr},ja))})]})}function ReleaseCard({release:es}){var ja,Na,Aa;const $=es.categories??{features:[],fixes:[],security:[]},ts=((ja=$.features)==null?void 0:ja.length)??0,is=((Na=$.fixes)==null?void 0:Na.length)??0,cs=((Aa=$.security)==null?void 0:Aa.length)??0,Qr=new Date(es.publishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{className:"pb-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-base font-mono",children:es.version}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:Qr})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[ts>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-teal-500/10 text-teal-500 border-teal-500/20",children:[ts," feature",ts!==1?"s":""]}),is>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-amber-500/10 text-amber-500 border-amber-500/20",children:[is," fix",is!==1?"es":""]}),cs>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-red-500/10 text-red-500 border-red-500/20",children:[cs," security"]})]})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-2",children:[jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Features",items:$.features??[],colorClass:"text-teal-500"}),jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Fixes",items:$.fixes??[],colorClass:"text-amber-500"}),jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Security",items:$.security??[],colorClass:"text-red-500"}),es.url&&jsxRuntimeExports.jsx("div",{className:"pt-1 flex justify-end",children:jsxRuntimeExports.jsxs("a",{href:es.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["View release ",jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]})})]})]})}function HarnessUpdatesTab(){const{data:es,isLoading:$}=useHarnessReleases("claude_code"),ts=useSyncHarnessReleases();return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-mono font-semibold",children:"Claude Code Releases"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Changelog from the Claude Code GitHub repository"})]}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",onClick:()=>ts.mutate("claude_code"),disabled:ts.isPending,className:"cursor-pointer",children:[ts.isPending?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-3.5 w-3.5"}),"Sync"]})]}),ts.isSuccess&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["Synced ",ts.data.synced," new release",ts.data.synced!==1?"s":""," (",ts.data.total," total checked)"]}),$?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[...Array(4)].map((is,cs)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-32"},cs))}):!es||es.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"text-center space-y-4 py-8",children:[jsxRuntimeExports.jsx(Package,{className:"h-12 w-12 mx-auto text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-semibold",children:"No releases synced yet"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Click Sync to fetch the latest releases from GitHub."})]})]})})}):jsxRuntimeExports.jsx("div",{className:"space-y-3",children:es.map(is=>jsxRuntimeExports.jsx(ReleaseCard,{release:is},is.id))})]})}function InsightsListPage(){const[es,$]=useTabParam(["overview","harness-updates"],"overview"),ts=useNavigate(),{data:is,isLoading:cs}=useComputedInsights(),{data:Qr}=useInsightsProjects(),ja=useRegenerateAllInsights(),Na=useActiveInsightsJobs(),{data:Aa}=useInsightsJobs(void 0,500),Oa=(Aa??[]).filter(Fa=>Fa.status!=="cancelled"),Ia=(()=>{if(Oa.length<2)return[];const Fa=[...Oa].sort((Ka,Ga)=>new Date(Ka.createdAt).getTime()-new Date(Ga.createdAt).getTime());let Ha=[];for(let Ka=0;Ka<Fa.length;Ka++){const Ga=new Date(Fa[Ka].createdAt).getTime(),Va=Fa.filter(Ja=>new Date(Ja.createdAt).getTime()-Ga<12e4&&new Date(Ja.createdAt).getTime()>=Ga);Va.length>Ha.length&&(Ha=Va)}return Ha.length<2?[]:Ha})(),La=Ia.length>1,Ba=new Map;for(const Fa of Ia)Fa.projectPath&&!Ba.has(Fa.projectPath)&&Ba.set(Fa.projectPath,Fa);const Ma=new Set(Oa.filter(Fa=>Fa.status==="completed"&&Fa.projectPath).map(Fa=>Fa.projectPath)),qa=Fa=>{if(Fa.errors.length>0&&ue$1.error(`${Fa.errors.length} project${Fa.errors.length===1?"":"s"} failed to enqueue`,{description:`${Fa.errors[0].projectPath}: ${Fa.errors[0].error}`}),Fa.created>0){ue$1.success(`Started ${Fa.created} regeneration job${Fa.created===1?"":"s"}`,Fa.noLiveWorker?{description:"No live worker — start `rulemetric evals agent` to run them."}:void 0);return}const Ha=Fa.skipped.filter(Ga=>Ga.reason==="fresh").length,Ka=Fa.skipped.length-Ha;Ha>0?ue$1(Ka>0?`${Ha} project${Ha===1?"":"s"} fresh (<4h), ${Ka} skipped`:`All ${Ha} project${Ha===1?" is":"s are"} fresh (regenerated <4h ago)`,{action:{label:"Force regenerate",onClick:()=>ja.mutate({force:!0},{onSuccess:qa,onError:Ga=>ue$1.error("Couldn't start the regeneration",{description:Ga instanceof Error?Ga.message:"Please try again."})})}}):Ka>0?ue$1(`${Ka} project${Ka===1?"":"s"} skipped (no checkout or too few sessions)`):Fa.errors.length===0&&ue$1("No projects eligible for regeneration")};return cs?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]}),jsxRuntimeExports.jsx("div",{className:"space-y-4",children:[...Array(3)].map((Fa,Ha)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-28"},Ha))})]}):!is||is.total_sessions===0?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Claude Code session analytics and AI-powered recommendations"})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"harness-updates",children:[jsxRuntimeExports.jsx(Package,{className:"h-4 w-4"}),"Harness Updates"]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"overview",className:"space-y-4 pt-2",children:jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"text-center space-y-4 py-8",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-12 w-12 mx-auto text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-semibold",children:"No sessions captured yet"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground max-w-md mx-auto mt-2",children:["Run ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"rulemetric hooks install"})," in a project to start capturing Claude Code sessions. Insights will appear automatically after your next session."]})]})]})})})}),jsxRuntimeExports.jsx(TabsContent,{value:"harness-updates",className:"pt-2",children:jsxRuntimeExports.jsx(HarnessUpdatesTab,{})})]})]}):jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-6",children:[jsxRuntimeExports.jsx(WorkerOfflineBanner,{}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Claude Code session analytics and AI-powered recommendations"})]}),jsxRuntimeExports.jsx("div",{className:"flex items-center gap-2 sm:shrink-0",children:jsxRuntimeExports.jsx(Button,{onClick:()=>ja.mutate(void 0,{onSuccess:qa,onError:Fa=>ue$1.error("Couldn't start the regeneration",{description:Fa instanceof Error?Fa.message:"Please try again."})}),disabled:ja.isPending||Na.length>0,className:"w-full cursor-pointer sm:w-auto",children:Na.length>0?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating (",Na.length," remaining)..."]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4"}),"Regenerate All"]})})})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"harness-updates",children:[jsxRuntimeExports.jsx(Package,{className:"h-4 w-4"}),"Harness Updates"]})]}),jsxRuntimeExports.jsxs(TabsContent,{value:"overview",className:"space-y-4 pt-2",children:[La&&jsxRuntimeExports.jsx(JobTracker,{jobs:Ia}),(is==null?void 0:is.analysis_freshness)&&jsxRuntimeExports.jsx(AnalysisFreshnessBanner,{freshness:is.analysis_freshness,totalAnalyzed:is.sessions_with_analysis}),jsxRuntimeExports.jsxs("div",{className:"space-y-5",children:[jsxRuntimeExports.jsx(InsightsOverview,{computed:is}),jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>ts("/insights/computed"),className:"text-sm font-medium text-primary hover:underline cursor-pointer",children:"Explore detailed trends and recommendations →"}),Qr&&Qr.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-mono font-semibold text-muted-foreground pt-2",children:"By Project"}),Qr.filter(Fa=>Fa.sessionCount>=3).map(Fa=>{const Ha=Ma.has(Fa.projectPath),Ka=Ba.get(Fa.projectPath),Ga=Fa.projectId??void 0,Va=Ga?`/insights/computed?projectPath=${encodeURIComponent(Fa.projectPath)}&projectId=${encodeURIComponent(Ga)}`:`/insights/computed?projectPath=${encodeURIComponent(Fa.projectPath)}`;return jsxRuntimeExports.jsx(ProjectCard,{project:Fa,hasReport:Ha,activeJob:Ka,onClick:()=>ts(Va)},Ga??Fa.projectPath)})]})]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"harness-updates",className:"pt-2",children:jsxRuntimeExports.jsx(HarnessUpdatesTab,{})})]})]})}function verdictState(es){return es.sufficient?es.significant?"significant":"no-effect":(es.strataDroppedForTimeSeparation??0)>0?"no-comparable-cohort":"insufficient"}function VerdictBadge({verdict:es}){const $=`95% CI ${(es.ci.lower*100).toFixed(0)}–${(es.ci.upper*100).toFixed(0)}%`,ts=`n=${es.nWith}`,is=es.strata!=null?` · within ${es.strata} project${es.strata===1?"":"s"}`:"",cs=es.confounded?` · observational${is}`:"",Qr=verdictState(es);if(Qr==="no-comparable-cohort"){const Oa=es.strataDroppedForTimeSeparation;return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`No comparable cohort. ${Oa} project-month${Oa===1?"":"s"} held both exposed and unexposed sessions, but they're separated in time — this treatment's sessions all ran later than the ones without it, so any difference is a calendar difference, not an effect. More sessions won't resolve it; a randomised holdout would.`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-amber-400 border-amber-400/40",children:"no comparable cohort"})})}if(Qr==="insufficient")return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Not enough sessions to measure this yet, so no number is shown (rather than a fabricated one).${es.insufficientReason?` ${es.insufficientReason}`:""}`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-muted-foreground",children:"insufficient data"})});if(Qr==="no-effect")return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`The with-vs-without difference isn't statistically distinguishable from zero, so we report no effect rather than noise. ${$}, ${ts}${cs}.`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-muted-foreground",children:"no measured effect"})});const ja=es.delta>0,Na=`${ja?"+":""}${(es.delta*100).toFixed(0)}%`,Aa=es.pValue!=null?`, p=${es.pValue.toFixed(3)}`:"";return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Sessions with this ${ja?"did measurably BETTER":"did measurably WORSE"} than sessions without it, and the difference is statistically significant. ${$}, ${ts}${Aa}${cs}. Observational — a correlation from real sessions, not a controlled experiment.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("text-[10px] font-mono shrink-0",ja?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40"),children:[Na," outcome"]})})}function SessionsTab({data:es}){return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[Object.keys(es.projects).length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono",children:["Projects (",Object.keys(es.projects).length,")"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:es.projects})})]}),es.session_summaries.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono",children:["Sessions with Analysis (",es.session_summaries.length,")"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:es.session_summaries.map($=>{const ts=$.id.length===36&&$.id.includes("-"),is=jsxRuntimeExports.jsxs("div",{className:`flex items-start gap-3 rounded-lg border border-border bg-background p-3 ${ts?"hover:border-primary/50 cursor-pointer":""}`,children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs shrink-0",children:$.date}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"text-sm truncate",children:$.summary||$.goal||"No summary"}),$.goal&&$.summary&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:$.goal}),"outcome"in $&&$.outcome&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"mt-1 text-[10px]",children:friendlyLabel($.outcome)})]})]});return ts?jsxRuntimeExports.jsx(Link,{to:`/sessions/${$.id}`,children:is},$.id):jsxRuntimeExports.jsx("div",{children:is},$.id)})})})]})]})}function RecEntryControls({item:es,projectPath:$}){const ts=useDismissRecommendation();return es.id?jsxRuntimeExports.jsxs("span",{className:"flex items-center gap-1 shrink-0",children:[(es.timesGenerated??1)>1&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-muted-foreground",title:`This exact advice has been generated by ${es.timesGenerated} separate insights runs. Dismissing it stops the repetition for 90 days.`,"data-testid":"rec-seen-count",children:["seen ×",es.timesGenerated]}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"cursor-pointer h-6 w-6 p-0 text-muted-foreground",title:"Dismiss — hidden for 90 days",disabled:ts.isPending,"data-testid":"rec-dismiss",onClick:()=>ts.mutate({contentHash:es.id,projectPath:$},{onError:is=>ue$1.error(is.message)}),children:jsxRuntimeExports.jsx(X$1,{className:"h-3 w-3"})})]}):null}function RecommendationsTab({rec:es,projectPath:$,autoAddAvailable:ts}){var ja,Na,Aa,Oa,Ia,La;const is=useAutoAddSuggestion(),[cs,Qr]=reactExports.useState(new Set);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[es.at_a_glance&&jsxRuntimeExports.jsxs(Card,{className:"border-amber-500/30 bg-amber-500/5",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Sparkles,{className:"h-4 w-4 text-amber-500"}),"At a Glance"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:Object.entries(es.at_a_glance).map(([Ba,Ma])=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1",children:Ba.replace(/_/g," ")}),jsxRuntimeExports.jsx("p",{className:"text-sm",children:Ma})]},Ba))})]}),((ja=es.what_works)==null?void 0:ja.impressive_workflows)&&es.what_works.impressive_workflows.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Impressive Things You Did"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.what_works.impressive_workflows.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.title}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.description})]},Ma))})]}),((Na=es.friction_analysis)==null?void 0:Na.categories)&&es.friction_analysis.categories.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 text-amber-500"}),"Where Things Go Wrong"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.friction_analysis.categories.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.category}),jsxRuntimeExports.jsx(RecEntryControls,{item:Ba,projectPath:$})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.description}),Ba.examples.length>0&&jsxRuntimeExports.jsx("ul",{className:"mt-2 space-y-1",children:Ba.examples.map((qa,Fa)=>jsxRuntimeExports.jsx("li",{className:"text-xs text-muted-foreground pl-3 border-l-2 border-border",children:qa},Fa))})]},Ba.id??Ma))})]}),((Aa=es.suggestions)==null?void 0:Aa.features_to_try)&&es.suggestions.features_to_try.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"h-4 w-4 text-blue-500"}),"Features to Try"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.features_to_try.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.feature}),Ba.example_code&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Ba.example_code}),jsxRuntimeExports.jsx(CopyButton$2,{text:Ba.example_code})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.why_for_you}),Ba.example_code&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Ba.example_code})]},Ma))})]}),((Oa=es.suggestions)==null?void 0:Oa.claude_md_additions)&&es.suggestions.claude_md_additions.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Suggested CLAUDE.md Additions"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.claude_md_additions.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono bg-muted px-2 py-1 rounded flex-1 overflow-x-auto",children:Ba.addition}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RecEntryControls,{item:Ba,projectPath:$}),jsxRuntimeExports.jsx(CopyButton$2,{text:Ba.addition}),$&&ts&&jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"cursor-pointer h-7 text-xs",disabled:cs.has(Ma)||is.isPending,onClick:qa=>{qa.stopPropagation(),is.mutate({projectPath:$,addition:Ba.addition,why:Ba.why},{onSuccess:Fa=>{(Fa.success||Fa.reason==="already_present")&&Qr(Ha=>new Set(Ha).add(Ma))},onError:Fa=>{const Ha=Fa instanceof ApiError&&(Fa.code==="not_local_mode"||Fa.statusCode===501);ue$1.error(Ha?"Add to CLAUDE.md only works when the API runs on your machine (local mode) — use the copy button instead.":Fa instanceof Error?Fa.message:"Failed to update CLAUDE.md")}})},children:is.isPending?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}):cs.has(Ma)?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3 text-teal-500"}):jsxRuntimeExports.jsx(Upload,{className:"h-3 w-3"})})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:Ba.why}),cs.has(Ma)&&jsxRuntimeExports.jsx("p",{className:"text-xs text-teal-500 mt-1",children:"Added to CLAUDE.md"})]},Ma))})]}),((Ia=es.suggestions)==null?void 0:Ia.usage_patterns)&&es.suggestions.usage_patterns.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"h-4 w-4 text-cyan-500"}),"Usage Patterns"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.usage_patterns.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.title}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[Ba.copyable_prompt&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Ba.copyable_prompt}),jsxRuntimeExports.jsx(CopyButton$2,{text:Ba.copyable_prompt})]}),jsxRuntimeExports.jsx(RecEntryControls,{item:Ba,projectPath:$})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.suggestion}),Ba.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Ba.copyable_prompt})]},Ba.id??Ma))})]}),((La=es.on_the_horizon)==null?void 0:La.opportunities)&&es.on_the_horizon.opportunities.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-4 w-4 text-pink-500"}),"On the Horizon"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.on_the_horizon.opportunities.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.title}),Ba.copyable_prompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Ba.copyable_prompt}),jsxRuntimeExports.jsx(CopyButton$2,{text:Ba.copyable_prompt})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.whats_possible}),Ba.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Ba.copyable_prompt})]},Ma))})]}),es.fun_ending&&jsxRuntimeExports.jsx(Card,{className:"border-pink-500/20 bg-pink-500/5",children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-6",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:es.fun_ending.headline}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:es.fun_ending.detail})]})})]})}function ScorePair({label:es,withVal:$,withoutVal:ts,delta:is,unit:cs,inverted:Qr}){const ja=Oa=>Oa!=null?`${Oa}${cs}`:"—",Na=is!=null&&is!==0?(Qr?is<0:is>0)?"text-teal-500":"text-red-500":"text-muted-foreground",Aa=is!=null&&is>0?"+":"";return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:es}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"font-mono",children:ja($)}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"vs"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:ja(ts)})]}),is!=null&&is!==0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:`text-[10px] mt-1 ${Na} ${(Qr?is<0:is>0)?"bg-teal-500/10 border-teal-500/20":"bg-red-500/10 border-red-500/20"}`,children:[Aa,is,cs]})]})}function SegmentLine({title:es,noun:$,segments:ts}){if(!ts||ts.length===0)return null;const is=ts.filter(Qr=>Qr.verdict.sufficient),cs=ts.length-is.length;return is.length===0&&cs===0?null:jsxRuntimeExports.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"text-[10px] text-muted-foreground mr-0.5",children:es}),is.map(Qr=>{const ja=Qr.verdict,Na=ja.delta>0,Aa=ja.significant?`${Na?"+":""}${(ja.delta*100).toFixed(0)}%`:"no effect",Oa=ja.significant?Na?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40":"text-muted-foreground",Ia=`95% CI ${(ja.ci.lower*100).toFixed(0)}–${(ja.ci.upper*100).toFixed(0)}%, n=${ja.nWith} exposed / ${ja.nWithout} unexposed (observational)`;return jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("text-[10px] font-mono",Oa),title:Ia,children:[Qr.label," ",Aa]},Qr.label)}),cs>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-muted-foreground",title:`Not enough exposed + unexposed sessions within a project to measure ${cs===1?`this ${$}`:`these ${$}s`} yet.`,children:[cs," ",$,cs===1?"":"s",": insufficient"]})]})}function SegmentBreakdown({impact:es}){const $=(es.segments??[]).map(is=>({label:is.model,verdict:is.verdict})),ts=(es.harnessSegments??[]).map(is=>({label:is.harness,verdict:is.verdict}));return $.length===0&&ts.length===0?null:jsxRuntimeExports.jsxs("div",{className:"mt-3 pt-3 border-t",children:[jsxRuntimeExports.jsx(SegmentLine,{title:"By model:",noun:"model",segments:$}),jsxRuntimeExports.jsx(SegmentLine,{title:"By harness:",noun:"harness",segments:ts})]})}function RandomisedBadges({randomised:es}){const $=ts=>ts.split("/").filter(Boolean).pop()??ts;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[es.verdicts.map(ts=>jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`RANDOMISED verdict on ${ts.projectPath}: sessions were assigned to receive or not receive this instruction, and the ${ts.decision==="always"?"receiving":"withheld"} arm did measurably ${ts.decision==="always"?"better":"better without it"}. ${(ts.delta>0?"+":"")+(ts.delta*100).toFixed(0)}pp, 95% CI ${(ts.ciLower*100).toFixed(0)} to ${(ts.ciUpper*100).toFixed(0)}pp, n=${ts.nTreated}/${ts.nControl}. This supersedes the observational estimate for that project — assignment, not correlation.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:ts.decision==="always"?"text-[10px] font-mono shrink-0 text-teal-400 border-teal-400/40":"text-[10px] font-mono shrink-0 text-red-400 border-red-400/40","data-testid":"randomised-verdict-badge",children:["randomised · ",ts.delta>0?"+":"",(ts.delta*100).toFixed(0),"pp on ",$(ts.projectPath)]})},ts.projectPath)),es.experiments.map(ts=>jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Under randomised measurement on ${ts.projectPath} right now — injected to some sessions and withheld from the rest until the arms decide.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-muted-foreground","data-testid":"randomised-running-badge",children:["measuring · ",$(ts.projectPath)]})},ts.id))]})}function ImpactCard({impact:es,linkedSessions:$,source:ts}){const is=es.with,cs=es.without,Qr=es.comparison;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono truncate",children:es.instructionName}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[jsxRuntimeExports.jsx(ProvenanceBadge,{source:ts}),es.autoAdded&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-teal-400 border-teal-400/40",title:`Auto-added from a recommendation${es.autoAdded.count>1?` ×${es.autoAdded.count}`:""}`+(es.autoAdded.lastAssignedAt?` (last ${new Date(es.autoAdded.lastAssignedAt).toLocaleDateString()})`:"")+" — the verdict beside this is whether it helped.",children:["auto-added",es.autoAdded.count>1?` ×${es.autoAdded.count}`:""]}),es.randomised&&jsxRuntimeExports.jsx(RandomisedBadges,{randomised:es.randomised}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.verdict}),$!=null&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono",children:[$," sessions"]})]})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-xs",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:"Sessions"}),jsxRuntimeExports.jsxs("p",{className:"font-mono",children:[is.sessionCount," with / ",cs.sessionCount," without"]}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground mt-0.5",children:[is.enrichedCount," / ",cs.enrichedCount," enriched"]})]}),jsxRuntimeExports.jsx(ScorePair,{label:"Outcome Score",withVal:is.avgOutcomeScore,withoutVal:cs.avgOutcomeScore,delta:Qr.outcomeScoreDelta,unit:""}),jsxRuntimeExports.jsx(ScorePair,{label:"Tool Errors",withVal:is.avgToolErrors,withoutVal:cs.avgToolErrors,delta:Qr.toolErrorsDelta,unit:"",inverted:!0}),jsxRuntimeExports.jsx(ScorePair,{label:"Avg Duration",withVal:is.avgDurationMinutes,withoutVal:cs.avgDurationMinutes,delta:Qr.durationDelta,unit:"m",inverted:!0})]}),jsxRuntimeExports.jsx(SegmentBreakdown,{impact:es})]})]})}function InstructionImpactLoader({instructionId:es,linkedSessions:$,source:ts}){const{data:is,isLoading:cs}=useInstructionImpact(es);return cs?jsxRuntimeExports.jsx(Skeleton,{className:"h-24"}):!is||is.with.sessionCount===0&&is.without.sessionCount===0?null:jsxRuntimeExports.jsx(ImpactCard,{impact:is,linkedSessions:$,source:ts})}function GroomingCard(){const{data:es,isLoading:$}=useGroomCandidates(),ts=useArchiveInstruction(),is=useRestoreInstruction(),[cs,Qr]=reactExports.useState(new Set);if($||!es)return null;if(!es.captureHealthy)return jsxRuntimeExports.jsxs(Card,{className:"border-amber-500/30",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Grooming paused"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:es.reason})})]});const ja=es.harmful??[],Na=es.bloated??[],Aa=es.candidates.length+ja.length;if(Aa===0&&Na.length===0)return null;const Oa=La=>jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",className:"h-6 text-[10px] shrink-0",disabled:cs.has(La)||ts.isPending,onClick:()=>ts.mutate(La,{onSuccess:()=>{Qr(Ba=>new Set(Ba).add(La)),ue$1.success("Archived",{description:"Soft delete — this can be restored.",action:{label:"Undo",onClick:()=>is.mutate(La,{onSuccess:()=>{Qr(Ba=>{const Ma=new Set(Ba);return Ma.delete(La),Ma}),ue$1.success("Restored")},onError:()=>ue$1.error("Restore failed")})}})},onError:()=>ue$1.error("Archive failed")}),children:cs.has(La)?"Archived":"Archive"}),Ia=es.safetyGuarded+(es.harmfulSafetyGuarded??0);return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{className:"pb-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm",children:["Instructions worth a second look (",Aa+Na.length,")"]}),Ia>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-muted-foreground shrink-0",title:"Safety / destructive-guardrail rules are never proposed for retirement, however rarely they fire or however they score.",children:[Ia," safety rule",Ia===1?"":"s"," protected"]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Your own instructions worth a second look. Archiving is reversible; safety rules are never listed here."})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[Na.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-amber-400/90 mb-0.5",children:"Expensive, no measurable effect"}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:"Enough exposure to detect an effect and none was found — so these are candidates to SHORTEN, not to retire. Neutral means undetected, not worthless; the rule may carry something the outcome score cannot see. No archive button here on purpose."}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-64 overflow-y-auto",children:Na.map(La=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:La.name,children:La.name}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:La.verdict}),La.containsSafetyLanguage&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-400 shrink-0",title:"Contains destructive-command or credential guardrail language. Shown anyway — a trim changes nothing on its own — but preserve those lines when shortening.",children:"has guardrails"})]}),jsxRuntimeExports.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground shrink-0",title:"Estimated from content length (chars/4), not a tokenizer count.",children:["~",La.estimatedTokens.toLocaleString()," tok/session"]})]},La.id))})]}),ja.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-red-400/90 mb-0.5",children:"Measurably worse outcomes"}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:"Present in sessions that scored significantly lower. Correlational, not proven cause — the rule may just ride along with harder tasks — so review before retiring; the verdict beside each shows the effect."}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-64 overflow-y-auto",children:ja.map(La=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:La.name,children:La.name}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:La.verdict})]}),Oa(La.id)]},La.id))})]}),es.candidates.length>0&&jsxRuntimeExports.jsxs("div",{children:[ja.length>0&&jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-muted-foreground mb-1.5",children:"No recent use"}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-80 overflow-y-auto",children:es.candidates.map(La=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:La.name,children:La.name}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] shrink-0 text-muted-foreground",children:La.reason})]}),Oa(La.id)]},La.id))})]})]})]})}function InstructionsTab({projectFilter:es}){const{data:$,isLoading:ts}=useLinkedInstructions(es);return ts?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[...Array(3)].map((is,cs)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},cs))}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx(GroomingCard,{}),!$||$.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No instructions linked to sessions yet. Instructions are auto-captured from context snapshots — the session-end hook snapshots your on-disk CLAUDE.md files, and the proxy additionally captures runtime-rendered prompts and skills."})})}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Instructions linked to sessions, ranked by usage. Comparing sessions with vs. without each instruction."}),$.map(is=>jsxRuntimeExports.jsx(InstructionImpactLoader,{instructionId:is.id,linkedSessions:is.linkedSessions,source:is.source},is.id))]})]})}function InsightsDetailPage(){const{id:es}=useParams(),[$]=useSearchParams(),ts=es==="computed",is=ts?$.get("projectPath")??$.get("project")??void 0:void 0,cs=ts?$.get("projectId")??void 0:void 0,[Qr,ja]=reactExports.useState(""),{data:Na,recommendations:Aa,isLoading:Oa,fullProjectPath:Ia,title:La,subtitle:Ba,lastCompletedJob:Ma,activeJobs:qa,createJob:Fa}=useProjectInsights(es,is,cs,Qr||void 0),[Ha,Ka]=useTabParam(["overview","tools","quality","sessions","instructions","recommendations"],"overview");if(Oa)return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-48"}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[...Array(4)].map((Ya,el)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},el))})]});if(!Na)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/insights",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Report not found."})]});const Ga=ts?Na.tools_used??{}:{},Va=Object.keys(Ga).sort((Ya,el)=>(Ga[el]??0)-(Ga[Ya]??0)),Ja=Na.autoAddAvailable!==!1;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/insights",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:La}),ts&&(Va.length>1||Qr)&&jsxRuntimeExports.jsxs("select",{value:Qr,onChange:Ya=>ja(Ya.target.value),className:"h-8 rounded-md border border-input bg-background px-2 text-xs font-mono cursor-pointer focus:outline-none focus:ring-1 focus:ring-ring",children:[jsxRuntimeExports.jsx("option",{value:"",children:"All Tools"}),Va.map(Ya=>jsxRuntimeExports.jsxs("option",{value:Ya,children:[displayTool(Ya)," (",Ga[Ya],")"]},Ya)),Qr&&!Va.includes(Qr)&&jsxRuntimeExports.jsx("option",{value:Qr,children:displayTool(Qr)})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:Ba}),ts&&Va.length>0&&!Qr&&jsxRuntimeExports.jsx("div",{className:"flex items-center gap-1.5 mt-1 flex-wrap",children:Va.map(Ya=>jsxRuntimeExports.jsx(Badge,{asChild:!0,variant:"outline",children:jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>ja(Ya),className:"text-[10px] font-mono cursor-pointer hover:bg-primary/10",children:[displayTool(Ya),": ",Ga[Ya]]})},Ya))})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[Ma&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Last generated ",new Date(Ma.completedAt).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})]}),jsxRuntimeExports.jsxs(Button,{onClick:()=>Fa.mutate(Ia??is,{onSuccess:Ya=>{Ya.noLiveWorker?ue$1.warning("Queued, but no worker is listening",{description:"Start one with `rulemetric evals agent` (or `rulemetric service install --worker-only`) and it will pick this up."}):ue$1.success("Generating recommendations…")},onError:Ya=>ue$1.error("Couldn't start the run",{description:Ya instanceof Error?Ya.message:"Please try again."})}),disabled:Fa.isPending||qa.length>0,variant:"outline",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mr-2 h-4 w-4"}),qa.length>0?`Generating — ${jobStepLabel(qa[0])}`:Aa?"Refresh Recommendations":"Generate Recommendations"]})]})]}),ts&&jsxRuntimeExports.jsx(AnalysisFreshnessBanner,{freshness:Na.analysis_freshness,totalAnalyzed:Na.sessions_with_analysis??0}),jsxRuntimeExports.jsx(WorkerOfflineBanner,{}),qa.length>0&&jsxRuntimeExports.jsx(JobTracker,{jobs:qa}),jsxRuntimeExports.jsxs(Tabs,{value:Ha,onValueChange:Ka,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"mr-2 h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"tools",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Terminal,{className:"mr-2 h-4 w-4"}),"Tools"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"quality",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"mr-2 h-4 w-4"}),"Quality"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"sessions",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"mr-2 h-4 w-4"}),"Sessions"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"instructions",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"mr-2 h-4 w-4"}),"Instructions"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"recommendations",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mr-2 h-4 w-4"}),"Recommendations"]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"overview",className:"mt-6",children:jsxRuntimeExports.jsx(OverviewTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"tools",className:"mt-6",children:jsxRuntimeExports.jsx(ToolsTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"quality",className:"mt-6",children:jsxRuntimeExports.jsx(QualityTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"sessions",className:"mt-6",children:jsxRuntimeExports.jsx(SessionsTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"instructions",className:"mt-6",children:jsxRuntimeExports.jsx(InstructionsTab,{projectFilter:is})}),jsxRuntimeExports.jsx(TabsContent,{value:"recommendations",className:"mt-6",children:Aa?jsxRuntimeExports.jsx(RecommendationsTab,{rec:Aa,projectPath:Ia,autoAddAvailable:Ja}):jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:qa.length>0?`Generating recommendations — ${jobStepLabel(qa[0])}`:'No recommendations yet. Use "Generate Recommendations" above to analyze this project’s sessions.'})})})})]})]})}const MEMORY_PAGE_SIZE=50;function useMemories(es="active",$="",ts="all"){return useInfiniteQuery({queryKey:["memories",{status:es,search:$,kind:ts}],initialPageParam:0,queryFn:({pageParam:is})=>{const cs=new URLSearchParams({status:es,limit:String(MEMORY_PAGE_SIZE),offset:String(is)});return $&&cs.set("search",$),ts&&ts!=="all"&&cs.set("kind",ts),apiGet(`/api/memories?${cs.toString()}`).then(Qr=>Qr.memories)},getNextPageParam:(is,cs)=>is.length<MEMORY_PAGE_SIZE?void 0:cs.length*MEMORY_PAGE_SIZE})}function useMemory(es){return useQuery({queryKey:["memories",es],queryFn:()=>apiGet(`/api/memories/${es}`),enabled:!!es})}function useMemoryImpact(es){return useQuery({queryKey:["insights","memory-impact",es],queryFn:()=>apiGet(`/api/insights/memory-impact?memoryId=${es}`),enabled:!!es})}function useMemoryExperiments(es){return useQuery({queryKey:["memories",es,"experiments"],queryFn:()=>apiGet(`/api/memories/${es}/experiments`),enabled:!!es,select:$=>$.experiments,refetchInterval:$=>{var is;return(((is=$.state.data)==null?void 0:is.experiments)??[]).some(cs=>cs.status==="pending"||cs.status==="running")?5e3:!1}})}function useCreateExperiment(es){const $=useQueryClient();return useMutation({mutationFn:ts=>apiPost(`/api/memories/${es}/experiments`,ts),onSuccess:()=>$.invalidateQueries({queryKey:["memories",es,"experiments"]})})}function useCreateMemory(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/memories",$),onSuccess:()=>es.invalidateQueries({queryKey:["memories"]})})}function useUpdateMemory(){const es=useQueryClient();return useMutation({mutationFn:({id:$,...ts})=>apiPatch(`/api/memories/${$}`,ts),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["memories"]}),es.invalidateQueries({queryKey:["memories",ts.id]})}})}function useArchiveMemory(){const es=useQueryClient();return useMutation({mutationFn:$=>apiDelete(`/api/memories/${$}`),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["memories"]}),es.invalidateQueries({queryKey:["memories",ts]})}})}const KINDS=["fact","decision","correction","convention"];function MemoryFormDialog({open:es,onOpenChange:$,memory:ts}){const is=!!ts,cs=useCreateMemory(),Qr=useUpdateMemory(),[ja,Na]=reactExports.useState("fact"),[Aa,Oa]=reactExports.useState(""),[Ia,La]=reactExports.useState("");reactExports.useEffect(()=>{es&&(Na((ts==null?void 0:ts.kind)??"fact"),Oa((ts==null?void 0:ts.title)??""),La((ts==null?void 0:ts.body)??""))},[es,ts==null?void 0:ts.id]);const Ba=cs.isPending||Qr.isPending,Ma=Aa.trim().length>0&&Ia.trim().length>0&&!Ba,qa=()=>{if(!Ma)return;const Fa=Ka=>()=>{ue$1.success(`Memory ${Ka}`),$(!1)},Ha=Ka=>ue$1.error(Ka instanceof Error?Ka.message:"Something went wrong");is?Qr.mutate({id:ts.id,kind:ja,title:Aa.trim(),body:Ia.trim()},{onSuccess:Fa("updated"),onError:Ha}):cs.mutate({kind:ja,title:Aa.trim(),body:Ia.trim()},{onSuccess:Fa("created"),onError:Ha})};return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:is?"Edit memory":"New memory"}),jsxRuntimeExports.jsx(DialogDescription,{children:"A durable note the session-start hook injects into future sessions as context. Its measured effect is tracked automatically."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Kind"}),jsxRuntimeExports.jsxs(Select,{value:ja,onValueChange:Fa=>Na(Fa),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsx(SelectContent,{children:KINDS.map(Fa=>jsxRuntimeExports.jsx(SelectItem,{value:Fa,className:"capitalize",children:Fa},Fa))})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Title"}),jsxRuntimeExports.jsx(Input,{value:Aa,onChange:Fa=>Oa(Fa.target.value),placeholder:"Short, memorable summary",maxLength:300})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Body"}),jsxRuntimeExports.jsx(Textarea,{value:Ia,onChange:Fa=>La(Fa.target.value),placeholder:"The fact / decision / correction / convention to remember.",rows:5})]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>$(!1),className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{onClick:qa,disabled:!Ma,className:"cursor-pointer",children:Ba?"Saving…":is?"Save changes":"Create"})]})]})})}const kindColors={fact:"bg-blue-500/15 text-blue-400 border-blue-500/30",decision:"bg-primary/15 text-primary border-primary/30",correction:"bg-red-500/15 text-red-400 border-red-500/30",convention:"bg-pink-500/15 text-pink-400 border-pink-500/30"};function useDebouncedValue(es,$){const[ts,is]=reactExports.useState(es);return reactExports.useEffect(()=>{const cs=setTimeout(()=>is(es),$);return()=>clearTimeout(cs)},[es,$]),ts}function MemoryList(){const[es,$]=reactExports.useState("active"),[ts,is]=reactExports.useState(""),[cs,Qr]=reactExports.useState("all"),[ja,Na]=reactExports.useState(!1),Aa=useNavigate(),Oa=useDebouncedValue(ts.trim(),300),{data:Ia,isLoading:La,error:Ba,hasNextPage:Ma,fetchNextPage:qa,isFetchingNextPage:Fa}=useMemories(es,Oa,cs),Ha=reactExports.useMemo(()=>(Ia==null?void 0:Ia.pages.flat())??[],[Ia]),Ka=Oa!==""||cs!=="all";if(Ba)return jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-destructive",children:["Failed to load memories: ",Ba.message]});const Ga=es!=="active";return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"relative min-w-40 flex-1",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{placeholder:"Search memories...",value:ts,onChange:Va=>is(Va.target.value),className:"pl-9 bg-background border-border"})]}),jsxRuntimeExports.jsxs(Select,{value:cs,onValueChange:Qr,children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-36 cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"all",children:"All kinds"}),jsxRuntimeExports.jsx(SelectItem,{value:"fact",children:"Fact"}),jsxRuntimeExports.jsx(SelectItem,{value:"decision",children:"Decision"}),jsxRuntimeExports.jsx(SelectItem,{value:"correction",children:"Correction"}),jsxRuntimeExports.jsx(SelectItem,{value:"convention",children:"Convention"})]})]}),jsxRuntimeExports.jsxs(Select,{value:es,onValueChange:Va=>$(Va),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-32 cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"active",children:"Active"}),jsxRuntimeExports.jsx(SelectItem,{value:"archived",children:"Archived"}),jsxRuntimeExports.jsx(SelectItem,{value:"all",children:"All"})]})]}),jsxRuntimeExports.jsxs(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"New"]})]}),La?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((Va,Ja)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 rounded-lg"},Ja))}):Ha.length===0?jsxRuntimeExports.jsxs("div",{className:"text-center py-12",children:[jsxRuntimeExports.jsx(Brain,{className:"mx-auto h-8 w-8 text-muted-foreground/40 mb-3"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-4",children:Ka?"No memories match your filters.":"No memories yet. Create one, or let the distiller extract them from your sessions."}),!Ka&&jsxRuntimeExports.jsxs(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"Create memory"]})]}):jsxRuntimeExports.jsx("div",{className:"bg-card border border-border rounded-lg",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"hover:bg-transparent",children:[jsxRuntimeExports.jsx(TableHead,{children:"Title"}),jsxRuntimeExports.jsx(TableHead,{children:"Kind"}),jsxRuntimeExports.jsx(TableHead,{className:"hidden md:table-cell",children:"Scope"}),jsxRuntimeExports.jsx(TableHead,{className:"hidden lg:table-cell",children:"Source"}),Ga&&jsxRuntimeExports.jsx(TableHead,{children:"Status"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Updated"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Ha.map(Va=>jsxRuntimeExports.jsxs(TableRow,{className:"hover:bg-secondary/50 transition-colors duration-200 cursor-pointer",onClick:()=>Aa(`/memories/${Va.id}`),children:[jsxRuntimeExports.jsx(TableCell,{className:"font-medium max-w-md truncate",children:Va.title}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:`capitalize ${kindColors[Va.kind]}`,children:Va.kind})}),jsxRuntimeExports.jsx(TableCell,{className:"hidden md:table-cell text-xs text-muted-foreground",children:Va.projectId?"Project":"Global"}),jsxRuntimeExports.jsx(TableCell,{className:"hidden lg:table-cell text-xs text-muted-foreground",children:Va.source}),Ga&&jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs capitalize text-muted-foreground",children:Va.status})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-xs text-muted-foreground",children:formatDistanceToNow(Va.updatedAt)})]},Va.id))})]})}),Ma&&jsxRuntimeExports.jsx("div",{className:"flex justify-center",children:jsxRuntimeExports.jsx(Button,{variant:"outline",className:"cursor-pointer",disabled:Fa,onClick:()=>qa(),children:Fa?"Loading…":"Load more"})}),jsxRuntimeExports.jsx(MemoryFormDialog,{open:ja,onOpenChange:Na})]})}function MemoriesListPage(){return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Memories"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Durable project facts your agent recalls — injected at session start, and measured for whether they actually help."})]}),jsxRuntimeExports.jsx(MemoryList,{})]})}function ExperimentRow({exp:es}){var $,ts,is;return jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3 py-2 border-b border-border last:border-0",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-mono truncate",title:es.taskPrompt,children:es.taskPrompt}),jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:["v",es.memoryVersion," · ",es.engine," · ",es.trials," trials · ",formatDistanceToNow(es.createdAt)]}),es.status==="failed"&&es.error&&jsxRuntimeExports.jsx("p",{className:"text-[10px] text-red-400 mt-0.5",title:es.error,children:es.error}),es.result&&jsxRuntimeExports.jsxs("details",{className:"mt-2 text-xs",children:[jsxRuntimeExports.jsxs("summary",{className:"cursor-pointer",children:["Trial evidence · ",es.result.completedTrials,"/",es.trials," usable pairs"]}),jsxRuntimeExports.jsxs("p",{className:"break-words mt-2",children:[es.result.engine," · ",es.result.model??"Model not recorded",es.result.judge&&` · configured grader ${es.result.judge.engine} ${es.result.judge.model??"(default)"}`]}),es.result.actualJudge&&jsxRuntimeExports.jsx("p",{className:"break-words",children:es.result.actualJudge.engine?`Actual grader: ${es.result.actualJudge.engine} · ${es.result.actualJudge.model??"model not recorded"}`:"Deterministic assertions · no model grader used"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"With memory / without memory. Dollar values are API-equivalent estimates, not subscription charges."}),jsxRuntimeExports.jsx("ol",{className:"space-y-1 mt-2",children:($=es.result.pairs)==null?void 0:$.map((cs,Qr)=>{var ja,Na,Aa,Oa;return jsxRuntimeExports.jsxs("li",{className:"break-words",children:["Pair ",Qr+1,": score ",cs.withScore,"/",cs.withoutScore,"; tokens ",cs.withTokens??"?","/",cs.withoutTokens??"?",";"," ","seconds ",((ja=cs.withLatency)==null?void 0:ja.toFixed(1))??"?","/",((Na=cs.withoutLatency)==null?void 0:Na.toFixed(1))??"?",";"," ","estimated $ ",((Aa=cs.withCostUsd)==null?void 0:Aa.toFixed(5))??"unknown","/",((Oa=cs.withoutCostUsd)==null?void 0:Oa.toFixed(5))??"unknown"]},Qr)})}),(ts=es.result.excluded)==null?void 0:ts.map(cs=>jsxRuntimeExports.jsxs("p",{className:"break-words text-amber-500",children:["Excluded trial ",cs.trial,": ",cs.reason]},cs.trial))]})]}),jsxRuntimeExports.jsx("div",{className:"shrink-0",children:es.status==="completed"&&((is=es.result)!=null&&is.verdict)?jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["n=",es.result.completedTrials]}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.result.verdict})]}):es.status==="failed"||es.status==="completed"?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] text-red-400 border-red-400/40",children:es.status==="failed"?"failed":"no usable verdict"}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] text-muted-foreground gap-1",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}),es.status==="running"?"running":"queued"]})})]})}function MemoryExperiments({memoryId:es}){const{data:$,isLoading:ts}=useMemoryExperiments(es),is=useCreateExperiment(es),[cs,Qr]=reactExports.useState(!1),[ja,Na]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(""),[Ia,La]=reactExports.useState(10),[Ba,Ma]=reactExports.useState("claude"),[qa,Fa]=reactExports.useState(""),[Ha,Ka]=reactExports.useState("claude"),[Ga,Va]=reactExports.useState("");function Ja(){const Ya=Aa.split(`
|
|
142
|
+
rulemetric auth create-key --name "my-setup"`})]})]})]})]})]}),jsxRuntimeExports.jsx(Card,{className:"border-blue-500/30 bg-blue-500/5",children:jsxRuntimeExports.jsxs(CardContent,{className:"py-3 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx("strong",{className:"text-blue-400",children:"Tip:"})," Use an API key (",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:"rm_..."}),") instead of a JWT for MCP server config. API keys never expire and work for all integrations. Create one in the API Keys section above, or via CLI:"," ",jsxRuntimeExports.jsx("code",{className:"text-xs bg-muted px-1 py-0.5 rounded font-mono",children:'rulemetric auth create-key --name "my-setup"'})]})}),jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono text-muted-foreground",children:["Available Tools (",toolGroups.reduce((pl,jl)=>pl+jl.tools.length,0),")"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-6",children:toolGroups.map(pl=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-2",children:pl.label}),jsxRuntimeExports.jsx("div",{className:"grid gap-2",children:pl.tools.map(jl=>jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-lg border border-border bg-background p-3",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs shrink-0",children:jl.name}),jsxRuntimeExports.jsx("span",{className:"min-w-0 break-words text-sm text-muted-foreground",children:jl.desc})]},jl.name))})]},pl.label))})]})]})}function projectDisplayName(es){var cs;if(es.projectName)return es.projectName;const $=lastTwoSegments(es.primaryCheckoutPath);if($)return $;const ts=nameFromRemote((cs=es.metadata)==null?void 0:cs.gitRemote);if(ts)return ts;const is=lastTwoSegments(es.projectPath);return is||"—"}function lastTwoSegments(es){if(!es)return null;const $=es.split("/").filter(Boolean);return $.length===0?null:$.slice(-2).join("/")}function nameFromRemote(es){if(typeof es!="string"||!es.trim())return null;const $=es.trim().replace(/\.git$/i,"").replace(/^(https?:\/\/|ssh:\/\/(?:[^@]+@)?|git:\/\/|[^@]+@)/,"").replace(/^([^/:]+):/,"$1/"),ts=$.split("/").filter(Boolean);return ts.length>=3?ts.slice(-2).join("/"):ts.length===2?ts[1]:$||null}function ClaudeCodeIcon(es){return jsxRuntimeExports.jsx("svg",{viewBox:"0 0 24 24",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",...es,children:jsxRuntimeExports.jsx("path",{d:"M12 2.5L13.4 9.2L20 8.5L14.8 12L20 15.5L13.4 14.8L12 21.5L10.6 14.8L4 15.5L9.2 12L4 8.5L10.6 9.2L12 2.5Z"})})}function CursorIcon(es){return jsxRuntimeExports.jsx("svg",{viewBox:"0 0 24 24",width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",...es,children:jsxRuntimeExports.jsx("path",{d:"M12 2L13.5 10.5L22 12L13.5 13.5L12 22L10.5 13.5L2 12L10.5 10.5L12 2Z"})})}function VSCodeCopilotIcon(es){return jsxRuntimeExports.jsxs("svg",{viewBox:"0 0 24 24",width:"1em",height:"1em",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinejoin:"round","aria-hidden":"true",...es,children:[jsxRuntimeExports.jsx("path",{d:"M17.5 2.5L21.5 4.5V19.5L17.5 21.5L8 13.5L4 16.5L2.5 15.5V8.5L4 7.5L8 10.5L17.5 2.5Z"}),jsxRuntimeExports.jsx("path",{d:"M17.5 2.5V21.5"})]})}const TOOL_ICON_COMPONENTS={claude_code:ClaudeCodeIcon,cursor:CursorIcon,vscode_copilot:VSCodeCopilotIcon};function ToolIcon({tool:es,...$}){const ts=TOOL_ICON_COMPONENTS[es];return ts?jsxRuntimeExports.jsx(ts,{...$}):jsxRuntimeExports.jsx(Activity,{...$})}function Table({className:es,...$}){return jsxRuntimeExports.jsx("div",{"data-slot":"table-container",className:"relative w-full overflow-x-auto",children:jsxRuntimeExports.jsx("table",{"data-slot":"table",className:cn$1("w-full caption-bottom text-sm",es),...$})})}function TableHeader({className:es,...$}){return jsxRuntimeExports.jsx("thead",{"data-slot":"table-header",className:cn$1("[&_tr]:border-b",es),...$})}function TableBody({className:es,...$}){return jsxRuntimeExports.jsx("tbody",{"data-slot":"table-body",className:cn$1("[&_tr:last-child]:border-0",es),...$})}function TableRow({className:es,...$}){return jsxRuntimeExports.jsx("tr",{"data-slot":"table-row",className:cn$1("hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",es),...$})}function TableHead({className:es,...$}){return jsxRuntimeExports.jsx("th",{"data-slot":"table-head",className:cn$1("text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",es),...$})}function TableCell({className:es,...$}){return jsxRuntimeExports.jsx("td",{"data-slot":"table-cell",className:cn$1("p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",es),...$})}function formatDuration(es,$){if(!$)return"—";const ts=new Date($).getTime()-new Date(es).getTime();if(!Number.isFinite(ts)||ts<0)return"—";const is=Math.floor(ts/6e4);if(is<1)return"<1m";if(is<60)return`${is}m`;const cs=Math.floor(is/60);return cs<24?`${cs}h ${is%60}m`:`${Math.floor(cs/24)}d ${cs%24}h`}function HeadlessBadge(){return jsxRuntimeExports.jsx("span",{className:"inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium bg-slate-500/10 text-slate-500 border border-slate-500/20",title:"Started via `claude -p` (non-interactive). Typically a script or pipeline invocation.",children:"headless"})}function DataTierBadge({tier:es}){return es==="full"?jsxRuntimeExports.jsx("span",{className:"inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium bg-teal-500/10 text-teal-600 border border-teal-500/20",children:"Full capture"}):es==="events"?jsxRuntimeExports.jsx("span",{className:"inline-flex items-center rounded-full px-1.5 py-0.5 text-[10px] font-medium bg-amber-500/10 text-amber-600 border border-amber-500/20",children:"Events only"}):null}function SortableHead({label:es,sortKey:$,currentKey:ts,currentDir:is,onSort:cs,className:Qr}){const ja=ts===$,Na=ja?is==="asc"?ArrowUp:ArrowDown:ArrowUpDown;return jsxRuntimeExports.jsx(TableHead,{className:`cursor-pointer select-none hover:text-foreground transition-colors ${Qr??""}`,onClick:()=>cs($),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[es,jsxRuntimeExports.jsx(Na,{className:`h-3 w-3 ${ja?"text-primary":"text-muted-foreground/50"}`})]})})}function SessionsListPage(){const es=useNavigate(),[$,ts]=useSearchParams(),is=$.get("outcome")??void 0,cs=$.get("friction")??void 0,Qr=$.get("instructionId")??void 0,ja=[is&&{key:"outcome",label:`outcome: ${is.replace(/_/g," ")}`},cs&&{key:"friction",label:`friction: ${cs.replace(/_/g," ")}`},Qr&&{key:"instructionId",label:"linked instruction"}].filter(Boolean),Na=dl=>{const fl=new URLSearchParams($);fl.delete(dl),ts(fl,{replace:!0})},{data:Aa,isLoading:Oa}=useSessions({hideEmpty:!0,outcome:is,friction:cs,instructionId:Qr}),[Ia,La]=reactExports.useState("date"),[Ba,Ma]=reactExports.useState("desc"),[qa,Fa]=reactExports.useState(new Set),[Ha,Ka]=reactExports.useState(new Set),Ga=useDeleteSession(),Va=dl=>{Ka(fl=>{const nl=new Set(fl);return nl.has(dl)?nl.delete(dl):nl.add(dl),nl})},Ja=dl=>{Fa(fl=>{const nl=new Set(fl);return nl.has(dl)?nl.delete(dl):nl.add(dl),nl})},Ya=()=>{rl&&(qa.size===rl.length?Fa(new Set):Fa(new Set(rl.map(dl=>dl.id))))},el=async()=>{const dl=[...qa];for(const fl of dl)await Ga.mutateAsync(fl);Fa(new Set)},tl=dl=>{dl===Ia?Ma(fl=>fl==="asc"?"desc":"asc"):(La(dl),Ma("desc"))},rl=Aa?[...Aa].sort((dl,fl)=>{const nl=Ba==="asc"?1:-1;switch(Ia){case"date":return nl*(new Date(dl.lastActivityAt??dl.startedAt).getTime()-new Date(fl.lastActivityAt??fl.startedAt).getTime());case"events":return nl*(dl.eventCount-fl.eventCount);case"project":return nl*projectDisplayName(dl).localeCompare(projectDisplayName(fl));default:return 0}}):void 0,cl=[];if(rl){let dl=null;for(const fl of rl){const nl=new Date(fl.startedAt).toISOString().slice(0,19),ol=`${fl.tool}|${fl.projectPath??"∅"}|${nl}`;dl&&dl.key===ol?dl.siblings.push(fl):(dl&&cl.push(dl),dl={key:ol,rep:fl,siblings:[]})}dl&&cl.push(dl)}return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx("div",{className:"flex items-start justify-between",children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Sessions"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Review AI coding sessions and analyze instruction performance"}),ja.length>0&&jsxRuntimeExports.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-2",children:ja.map(dl=>jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"cursor-pointer font-mono text-xs",onClick:()=>Na(dl.key),title:"Clear this filter",children:[dl.label,jsxRuntimeExports.jsx(X$1,{className:"ml-1 h-3 w-3"})]},dl.key))})]})}),qa.size>0&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:[qa.size," selected"]}),jsxRuntimeExports.jsxs(Button,{variant:"destructive",size:"sm",className:"h-8 text-xs cursor-pointer",onClick:el,disabled:Ga.isPending,children:[jsxRuntimeExports.jsx(Trash2,{className:"h-3 w-3 mr-1"}),Ga.isPending?"Deleting...":"Delete"]}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"h-8 text-xs cursor-pointer",onClick:()=>Fa(new Set),children:"Cancel"})]}),Oa?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:5}).map((dl,fl)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 w-full"},fl))}):rl!=null&&rl.length?jsxRuntimeExports.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"bg-card hover:bg-card",children:[jsxRuntimeExports.jsx(TableHead,{className:"w-10",children:jsxRuntimeExports.jsx("button",{role:"checkbox","aria-checked":!!rl&&qa.size===rl.length&&rl.length>0,"aria-label":"Select all sessions",className:"h-4 w-4 rounded border border-border cursor-pointer flex items-center justify-center text-xs hover:bg-secondary/50 transition-colors",onClick:Ya,children:rl&&qa.size===rl.length&&rl.length>0?"✓":""})}),jsxRuntimeExports.jsx(TableHead,{className:"w-48",children:"Tool"}),jsxRuntimeExports.jsx(SortableHead,{label:"Project",sortKey:"project",currentKey:Ia,currentDir:Ba,onSort:tl,className:"w-80"}),jsxRuntimeExports.jsx(TableHead,{className:"w-[28rem]",children:"Last message"}),jsxRuntimeExports.jsx(TableHead,{className:"w-24",children:"Branch"}),jsxRuntimeExports.jsx(SortableHead,{label:"Events",sortKey:"events",currentKey:Ia,currentDir:Ba,onSort:tl,className:"text-right"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Duration"}),jsxRuntimeExports.jsx(SortableHead,{label:"Last activity",sortKey:"date",currentKey:Ia,currentDir:Ba,onSort:tl,className:"text-right"})]})}),jsxRuntimeExports.jsx(TableBody,{children:cl.flatMap(dl=>{const fl=Ha.has(dl.key),nl=dl.siblings.length>0;return[{session:dl.rep,isSibling:!1},...fl?dl.siblings.map(hl=>({session:hl,isSibling:!0})):[]].map(({session:hl,isSibling:Tl})=>{var pl,jl;const ul=hl.analysis;return jsxRuntimeExports.jsxs(TableRow,{className:`cursor-pointer hover:bg-secondary/50 transition-colors ${qa.has(hl.id)?"bg-primary/5":""} ${Tl?"bg-muted/20":""}`,onClick:()=>es(`/sessions/${hl.id}`),children:[jsxRuntimeExports.jsx(TableCell,{onClick:Nl=>Nl.stopPropagation(),children:jsxRuntimeExports.jsx("button",{type:"button",role:"checkbox","aria-checked":qa.has(hl.id),"aria-label":"Select session",className:"h-4 w-4 rounded border border-border flex items-center justify-center text-xs hover:bg-secondary/50 transition-colors",onClick:Nl=>{Nl.stopPropagation(),Ja(hl.id)},children:qa.has(hl.id)?"✓":""})}),jsxRuntimeExports.jsxs(TableCell,{className:"w-48 align-top",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[nl&&!Tl?jsxRuntimeExports.jsx("button",{type:"button",className:"flex h-4 w-4 items-center justify-center rounded hover:bg-muted cursor-pointer shrink-0",onClick:Nl=>{Nl.stopPropagation(),Va(dl.key)},title:fl?"Collapse parallel sessions":"Expand parallel sessions",children:fl?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3"})}):Tl?jsxRuntimeExports.jsx("div",{className:"w-4 shrink-0"}):null,jsxRuntimeExports.jsx(ToolIcon,{tool:hl.tool,className:"h-4 w-4 text-muted-foreground shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm truncate",children:displayTool(hl.tool)})]}),(hl.dataTier||((pl=hl.metadata)==null?void 0:pl.headless)||nl&&!Tl)&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-1 mt-1 ml-6",children:[hl.dataTier&&jsxRuntimeExports.jsx(DataTierBadge,{tier:hl.dataTier}),((jl=hl.metadata)==null?void 0:jl.headless)&&jsxRuntimeExports.jsx(HeadlessBadge,{}),nl&&!Tl&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[9px] font-mono px-1 py-0 gap-1",children:[jsxRuntimeExports.jsx(Layers,{className:"h-2.5 w-2.5"}),"+",dl.siblings.length," parallel"]})]})]}),jsxRuntimeExports.jsxs(TableCell,{className:"font-mono text-sm text-muted-foreground w-80 max-w-80 align-top",children:[jsxRuntimeExports.jsx("div",{className:"truncate text-foreground",children:projectDisplayName(hl)}),hl.projectName&&(hl.primaryCheckoutPath||hl.projectPath)&&jsxRuntimeExports.jsx("div",{className:"truncate text-[10px] text-muted-foreground/70",children:hl.primaryCheckoutPath??hl.projectPath}),hl.linkedInstructions&&hl.linkedInstructions.length>0&&jsxRuntimeExports.jsxs("div",{className:"flex gap-1 mt-0.5 flex-wrap",children:[hl.linkedInstructions.slice(0,3).map((Nl,zl)=>{var Fl;const Zl=((Fl=Nl.contextIdentity)==null?void 0:Fl.split("::").pop())??Nl.name,Dl=Zl.split("/").pop()??Zl,Il=isGenerated(classifyProvenance({source:Nl.source},null));return jsxRuntimeExports.jsx(Badge,{variant:"outline",className:Il?"text-[9px] font-mono px-1 py-0 border-teal-400/40 text-teal-400":"text-[9px] font-mono px-1 py-0",title:Il?PROVENANCE_TOOLTIP:void 0,"data-testid":Il?"provenance-chip":void 0,children:Dl.length>20?Dl.slice(0,20)+"...":Dl},zl)}),hl.linkedInstructions.length>3&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[9px] font-mono px-1 py-0",children:["+",hl.linkedInstructions.length-3]})]})]}),jsxRuntimeExports.jsx(TableCell,{className:"text-sm text-muted-foreground w-[28rem] max-w-[28rem] align-top",children:jsxRuntimeExports.jsx("div",{className:"truncate",title:hl.lastMessagePreview??void 0,children:hl.lastMessagePreview??"—"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-sm text-muted-foreground w-24 max-w-24 truncate",title:hl.gitBranch??void 0,children:hl.gitBranch??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-right font-mono text-sm",children:hl.eventCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-sm text-muted-foreground",children:formatDuration(hl.startedAt,hl.lastActivityAt??hl.endedAt)}),jsxRuntimeExports.jsxs(TableCell,{className:"text-right text-sm text-muted-foreground whitespace-nowrap",children:[jsxRuntimeExports.jsx("div",{children:hl.lastActivityAt??hl.startedAt?new Date(hl.lastActivityAt??hl.startedAt).toLocaleString():"—"}),!!(ul!=null&&ul.outcome)&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[9px] mt-0.5",children:String(ul.outcome).replace(/_/g," ")})]})]},hl.id)})})})]})}):jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(Activity,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:"No sessions yet"}),jsxRuntimeExports.jsx("p",{className:"text-sm mt-1",children:"Import a session file or install Claude Code hooks to get started"})]})]})}function isAgentResponseEvent(es){return es.eventType==="assistant_response"||es.eventType==="assistant_message"}function eventUsage(es){var is;if(!es)return;const $=(is=es.metadata)==null?void 0:is.usage;if($&&typeof $=="object")return $;const ts=es.tokenUsage;if(ts)return{input_tokens:ts.input_tokens??ts.input,output_tokens:ts.output_tokens??ts.output,cache_read_input_tokens:ts.cache_read_input_tokens??ts.cacheRead,cache_creation_input_tokens:ts.cache_creation_input_tokens??ts.cacheWrite}}function isBlankAssistantMessage(es){return es.eventType==="assistant_message"&&(es.content==null||es.content.trim()==="")}function groupEventsIntoTurns(es){const $=[];let ts={userMessage:null,events:[],assistantResponse:null};for(const is of es)is.eventType==="user_message"?((ts.userMessage||ts.events.length>0)&&$.push(ts),ts={userMessage:is,events:[],assistantResponse:null}):(isAgentResponseEvent(is)&&(ts.assistantResponse=is),ts.events.push(is));return(ts.userMessage||ts.events.length>0)&&$.push(ts),$}function sessionEventCounts(es,$){if($)return{messages:$.messages,assistantResponses:$.assistantResponses,tools:$.toolCalls,total:$.total,partial:!1};const ts=es.filter(is=>is.eventType==="assistant_message"&&!isBlankAssistantMessage(is)).length;return{messages:es.filter(is=>is.eventType==="user_message").length+ts,assistantResponses:ts+es.filter(is=>{var cs;return is.eventType==="assistant_response"&&!!((cs=is.content)!=null&&cs.trim())}).length,tools:es.filter(is=>is.eventType==="tool_call").length,total:es.length,partial:!0}}const INJECTED_TYPES=new Set(["system_reminder","claude_md","agents_md","copilot_instructions","memory","skill_catalog","git_context","hook_output","deferred_tools"]);function getContextItems(es){const ts=(es.metadata??{}).contextItems??[];let is=0;for(const cs of ts)INJECTED_TYPES.has(cs.type)&&(cs.instruction_index==null&&(cs.instruction_index=is),is++);return ts}function useContextSnapshots(es){return useQuery({queryKey:["sessions",es,"context-snapshots"],queryFn:()=>apiGet(`/api/sessions/${es}/context-snapshots`),enabled:!!es,refetchInterval:POLL.ACTIVE})}function useContextSnapshotDetail(es){return useQuery({queryKey:["context-snapshots",es],queryFn:()=>apiGet(`/api/context-snapshots/${es}`),enabled:!!es})}function useLaunchJobs(){return useQuery({queryKey:["launch-jobs"],queryFn:()=>apiGet("/api/launch-jobs?limit=20"),refetchInterval:POLL.LIVE})}function useAvailableLaunchers(){return useQuery({queryKey:["launchers"],queryFn:()=>apiGet("/api/launchers"),staleTime:6e4})}function useCreateLaunchJob(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/launch-jobs",{tool:$.tool,config:{projectPath:$.projectPath,prompt:$.prompt,model:$.model,mode:$.mode,resumeSessionId:$.resumeSessionId}}),onSuccess:()=>{es.invalidateQueries({queryKey:["launch-jobs"]})}})}function useSessionTerminalTarget(es){return useQuery({queryKey:["terminal-target",es],queryFn:()=>apiGet(`/api/sessions/${es}/terminal-target`),enabled:!!es,refetchInterval:POLL.BACKGROUND})}function useSendMessage$1(es){const $=useQueryClient();return useMutation({mutationFn:ts=>apiPost(`/api/sessions/${es}/send`,ts),onSuccess:()=>{$.invalidateQueries({queryKey:["terminal-target",es]}),$.invalidateQueries({queryKey:["launch-jobs"]})}})}function SessionTargetSummary({target:es,capabilities:$,session:ts}){const is=(es==null?void 0:es.attachCommand)??(es!=null&&es.target?`tmux attach -t ${es.target}`:null),cs=ts.primaryCheckoutPath??ts.projectPath??null,Qr=displayTool(ts.tool);return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-md bg-card/60 px-4 py-3 text-xs space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono font-medium",children:[Qr,ts.externalSessionId&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" · ",ts.externalSessionId.slice(0,12)]})]}),cs&&jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono truncate max-w-[40ch]",children:cs}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),jsxRuntimeExports.jsxs(Badge,{variant:$.workerOnline?"default":"destructive",className:"text-[10px] font-mono",children:["worker ",$.workerOnline?"online":"offline"]}),es?jsxRuntimeExports.jsxs(Badge,{variant:es.status==="active"?"default":"outline",className:"text-[10px] font-mono",children:["tmux ",es.status]}):jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono",children:"no tmux target"})]}),es&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-muted-foreground",children:[jsxRuntimeExports.jsx(Terminal,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:es.target}),is&&jsxRuntimeExports.jsx(CopyButton$1,{text:is,label:"Copy attach"})]}),!es&&$.fallbackResume&&ts.externalSessionId&&jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground",children:["No live tmux target. Fallback resume will spawn a new terminal via"," ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"claude --resume"}),"."]})]})}function CopyButton$1({text:es,label:$}){const{copied:ts,copy:is}=useCopyToClipboard(1500);return jsxRuntimeExports.jsxs(Button,{type:"button",size:"sm",variant:"ghost",className:"h-6 px-2 text-[10px] font-mono cursor-pointer gap-1",onClick:cs=>{cs.stopPropagation(),is(es)},children:[ts?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),jsxRuntimeExports.jsx("span",{className:"truncate max-w-[28ch]",children:ts?"Copied":$})]})}function ProvenanceBadge({source:es,frontmatter:$,className:ts}){const is=es==="insights"||es==="evolution"?es:readStampedSource($),cs=provenanceLabel(is);return!is||!cs?null:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("border-teal-400/40 text-teal-400 text-[10px] font-normal shrink-0",ts),title:PROVENANCE_TOOLTIP,"data-testid":`provenance-${is}`,children:cs})}const LINK_METHOD_LABELS={project_match:"Auto-linked via project",auto_capture:"Auto-captured",manual:"Manually linked",context_file:"Context file"};function InstructionCard({instruction:es}){const[$,ts]=reactExports.useState(!1),is=es.content.slice(0,200),cs=es.content.length>200;return jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsxs("div",{className:"px-4 py-3 cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(FileText,{className:"h-4 w-4 text-primary shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium",children:es.name}),jsxRuntimeExports.jsx(ProvenanceBadge,{source:es.source}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:es.scope}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:LINK_METHOD_LABELS[es.linkMethod]??es.linkMethod}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),!$&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground mt-1 truncate",children:[is,cs&&"..."]})]}),$&&jsxRuntimeExports.jsx(CardContent,{className:"pt-0 pb-3",children:jsxRuntimeExports.jsx("pre",{className:"p-3 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-96 overflow-y-auto whitespace-pre-wrap break-words",children:es.content})})]})}const CATEGORY_ORDER=["instructions","memory","agents","commands","skills","settings"];function extractCategory(es){const $=es.frontmatter;if($&&typeof $.category=="string")return $.category;const ts=es.name.match(/\[([^\]]+)\]$/);return ts?ts[1]:"other"}function cleanName(es){return es.replace(/\s*\[[^\]]+\]$/,"")}function ContextFileRow({instruction:es}){const[$,ts]=reactExports.useState(!1);return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 cursor-pointer hover:bg-secondary/30 transition-colors rounded",...activatable(()=>ts(!$)),children:[jsxRuntimeExports.jsx(FileText,{className:"h-3 w-3 text-teal-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-xs",children:cleanName(es.name)}),jsxRuntimeExports.jsx(ProvenanceBadge,{source:es.source}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3 text-muted-foreground"})]}),$&&jsxRuntimeExports.jsx("div",{className:"ml-5 mr-3 mb-2",children:jsxRuntimeExports.jsx("pre",{className:"p-3 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-96 overflow-y-auto whitespace-pre-wrap break-words",children:es.content})})]})}function ContextBlock({instructions:es}){const[$,ts]=reactExports.useState(!1),is=reactExports.useMemo(()=>{const ja={};for(const Na of es){const Aa=extractCategory(Na);ja[Aa]||(ja[Aa]=[]),ja[Aa].push(Na)}return ja},[es]),cs=reactExports.useMemo(()=>es.filter(ja=>isGenerated(classifyProvenance({source:ja.source},null))).length,[es]),Qr=reactExports.useMemo(()=>Object.keys(is).sort((Na,Aa)=>{const Oa=CATEGORY_ORDER.indexOf(Na),Ia=CATEGORY_ORDER.indexOf(Aa);return(Oa===-1?999:Oa)-(Ia===-1?999:Ia)}),[is]);return jsxRuntimeExports.jsxs("div",{className:"mb-4",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-teal-500 rounded-lg bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[jsxRuntimeExports.jsx(FileText,{className:"h-3.5 w-3.5 text-teal-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:"Session Context"}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs font-mono",children:es.length}),cs>0&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"border-teal-400/40 text-teal-400 text-[10px] font-normal shrink-0",title:PROVENANCE_TOOLTIP,"data-testid":"provenance-insights",children:cs===1?"from insights":`${cs} from insights`}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),jsxRuntimeExports.jsx("div",{className:"flex items-center gap-1.5",children:!$&&Qr.map(ja=>jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"text-xs font-mono",children:[ja," ",is[ja].length]},ja))}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&jsxRuntimeExports.jsx("div",{className:"ml-4 mt-2 space-y-3",children:Qr.map(ja=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground font-medium uppercase tracking-wider mb-1 px-3",children:ja}),jsxRuntimeExports.jsx("div",{children:is[ja].map(Na=>jsxRuntimeExports.jsx(ContextFileRow,{instruction:Na},Na.instructionId))})]},ja))})]})}const PROVIDER_COLORS={anthropic:"bg-orange-500/10 text-orange-600 border-orange-500/20",openai:"bg-teal-500/10 text-teal-600 border-teal-500/20",azure_openai:"bg-blue-500/10 text-blue-600 border-blue-500/20",gemini:"bg-pink-500/10 text-pink-600 border-pink-500/20",bedrock:"bg-amber-500/10 text-amber-600 border-amber-500/20",ollama:"bg-gray-500/10 text-gray-600 border-gray-500/20"};function formatTokenCount(es){return es==null?"0":es>=1e3?`${(es/1e3).toFixed(1)}K`:String(es)}function formatEventTimestamp(es){const $=new Date(es),ts=new Date,is=ts.getTime()-$.getTime(),cs=Math.floor(is/6e4),Qr=$.toDateString()===ts.toDateString();return cs<1?"just now":cs<60?`${cs}m ago`:Qr?$.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"}):$.toLocaleDateString([],{month:"numeric",day:"numeric",year:"numeric"})+" "+$.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}function UserBubble({event:es}){return jsxRuntimeExports.jsxs("div",{className:"mt-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[jsxRuntimeExports.jsx(User,{className:"h-4 w-4 text-blue-500"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:"You"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)})]}),jsxRuntimeExports.jsx("div",{className:"bg-blue-500/10 border border-blue-500/20 rounded-lg px-4 py-3 max-w-[85%]",children:jsxRuntimeExports.jsx("p",{className:"text-sm whitespace-pre-wrap break-words",children:es.content})})]})}function AssistantBubble({event:es}){const $=es.content??"",ts=/\[tool_use:\s*([^\]]+)\]/g,is=[];let cs=0,Qr;for(;(Qr=ts.exec($))!==null;)Qr.index>cs&&is.push({type:"text",value:$.slice(cs,Qr.index)}),is.push({type:"tool",value:Qr[1]}),cs=Qr.index+Qr[0].length;return cs<$.length&&is.push({type:"text",value:$.slice(cs)}),jsxRuntimeExports.jsxs("div",{className:"mt-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[jsxRuntimeExports.jsx(Brain,{className:"h-4 w-4 text-primary"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:"Assistant"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)})]}),jsxRuntimeExports.jsx("div",{className:"bg-secondary/50 border border-border rounded-lg px-4 py-3",children:jsxRuntimeExports.jsx("div",{className:"text-sm whitespace-pre-wrap break-words",children:is.length>0?is.map((ja,Na)=>ja.type==="tool"?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"mx-1 text-xs font-mono",children:ja.value},Na):jsxRuntimeExports.jsx("span",{children:ja.value},Na)):$})})]})}function ToolCallCard({event:es}){const[$,ts]=reactExports.useState(!1),is=es.metadata??{},cs=is.durationMs,Qr=is.success;return jsxRuntimeExports.jsxs("div",{className:"ml-8 mt-2",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-amber-500 rounded-lg px-3 py-2 bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Terminal,{className:"h-3.5 w-3.5 text-amber-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm",children:es.toolName}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)}),cs!=null&&jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:cs<1e3?`${cs}ms`:`${(cs/1e3).toFixed(1)}s`}),Qr!=null&&(Qr?jsxRuntimeExports.jsx(Check,{className:"h-3.5 w-3.5 text-teal-500"}):jsxRuntimeExports.jsx(X$1,{className:"h-3.5 w-3.5 text-destructive"})),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&jsxRuntimeExports.jsxs("div",{className:"ml-4 mt-1 space-y-2",children:[es.toolInput&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Input"}),jsxRuntimeExports.jsx("pre",{className:"p-2 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-64 overflow-y-auto",children:JSON.stringify(es.toolInput,null,2)})]}),es.toolOutput&&Object.keys(es.toolOutput).length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Output"}),jsxRuntimeExports.jsx("pre",{className:"p-2 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-64 overflow-y-auto",children:JSON.stringify(es.toolOutput,null,2)})]}),es.content&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Content"}),jsxRuntimeExports.jsx("pre",{className:"p-2 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-64 overflow-y-auto whitespace-pre-wrap break-words",children:es.content})]})]})]})}function ThinkingBubble({event:es}){const[$,ts]=reactExports.useState(!0),is=es.content??"",cs=is.slice(0,150);return jsxRuntimeExports.jsxs("div",{className:"ml-8 mt-2",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-rose-500 rounded-lg px-3 py-2 bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Brain,{className:"h-3.5 w-3.5 text-rose-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-sm text-muted-foreground italic",children:$?"Thinking":`${cs}${is.length>150?"...":""}`}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&jsxRuntimeExports.jsx("div",{className:"ml-4 mt-1",children:jsxRuntimeExports.jsx("p",{className:"text-sm italic text-muted-foreground whitespace-pre-wrap break-words",children:is})})]})}function ToolResultCard({event:es}){const[$,ts]=reactExports.useState(!0),is=es.content??"",cs=is.slice(0,200),ja=(es.metadata??{}).toolUseId??es.toolName;return jsxRuntimeExports.jsxs("div",{className:"ml-8 mt-2",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-teal-500 rounded-lg px-3 py-2 bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Check,{className:"h-3.5 w-3.5 text-teal-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:"Result"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)}),ja&&jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:ja}),!$&&is&&jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground truncate max-w-xs",children:[cs,is.length>200?"...":""]}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&is&&jsxRuntimeExports.jsx("div",{className:"ml-4 mt-1",children:jsxRuntimeExports.jsx("pre",{className:"p-2 bg-background border border-border rounded text-xs font-mono overflow-x-auto max-h-64 overflow-y-auto whitespace-pre-wrap break-words",children:is})})]})}function GenericEvent({event:es}){return jsxRuntimeExports.jsx("div",{className:"mt-2 ml-4",children:jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg px-3 py-2 bg-card/50",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:es.eventType.replace(/_/g," ")}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:formatEventTimestamp(es.timestamp)})]}),es.content&&jsxRuntimeExports.jsxs("p",{className:"text-sm mt-1 text-muted-foreground whitespace-pre-wrap break-words",children:[es.content.slice(0,300),es.content.length>300&&"..."]})]})})}function TokenUsageBar({usage:es}){const $=es.input_tokens??0,ts=es.output_tokens??0,is=es.cache_read_input_tokens??0,cs=es.cache_creation_input_tokens??0,Qr=$+ts+is+cs;if(Qr===0)return null;const ja=[{value:is,color:"bg-teal-500",label:"cache read"},{value:cs,color:"bg-amber-500",label:"cache write"},{value:$,color:"bg-blue-500",label:"input"},{value:ts,color:"bg-primary",label:"output"}].filter(Na=>Na.value>0);return jsxRuntimeExports.jsxs("div",{className:"mt-2",children:[jsxRuntimeExports.jsx("div",{className:"h-1.5 rounded-full bg-secondary overflow-hidden flex",children:ja.map(Na=>jsxRuntimeExports.jsx("div",{className:`${Na.color} h-full`,style:{width:`${Na.value/Qr*100}%`},title:`${Na.label}: ${formatTokenCount(Na.value)}`},Na.label))}),jsxRuntimeExports.jsx("div",{className:"flex gap-3 mt-1",children:ja.map(Na=>jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[jsxRuntimeExports.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${Na.color}`}),formatTokenCount(Na.value)," ",Na.label]},Na.label))})]})}function AssistantResponseCard({event:es}){const $=es.metadata??{},ts=eventUsage(es),is=$.stop_reason,cs=$.content_block_types,Qr=$.model,ja=$.response_time_ms,Na=$.streaming;return jsxRuntimeExports.jsx("div",{className:"mt-3 ml-8",children:jsxRuntimeExports.jsxs("div",{className:"bg-primary/5 border border-primary/20 rounded-lg px-4 py-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(Sparkles,{className:"h-3.5 w-3.5 text-primary shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium text-primary",children:"Response"}),Qr&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono px-1.5 py-0 border-primary/30 text-primary/80",children:Qr}),ja!=null&&jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[jsxRuntimeExports.jsx(Clock,{className:"h-3 w-3"}),ja<1e3?`${ja}ms`:`${(ja/1e3).toFixed(1)}s`]}),is&&jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-[10px] font-mono px-1.5 py-0",children:is}),Na&&jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"stream"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:formatEventTimestamp(es.timestamp)})]}),ts&&jsxRuntimeExports.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[ts.output_tokens>0&&jsxRuntimeExports.jsxs("span",{className:"text-[11px] font-mono bg-primary/10 text-primary px-2 py-0.5 rounded-full",children:[formatTokenCount(ts.output_tokens)," out"]}),ts.input_tokens>0&&jsxRuntimeExports.jsxs("span",{className:"text-[11px] font-mono bg-blue-500/10 text-blue-400 px-2 py-0.5 rounded-full",children:[formatTokenCount(ts.input_tokens)," in"]}),ts.cache_read_input_tokens>0&&jsxRuntimeExports.jsxs("span",{className:"text-[11px] font-mono bg-teal-500/10 text-teal-400 px-2 py-0.5 rounded-full",children:[formatTokenCount(ts.cache_read_input_tokens)," cache"]}),ts.cache_creation_input_tokens>0&&jsxRuntimeExports.jsxs("span",{className:"text-[11px] font-mono bg-amber-500/10 text-amber-400 px-2 py-0.5 rounded-full",children:[formatTokenCount(ts.cache_creation_input_tokens)," cached"]})]}),es.content&&jsxRuntimeExports.jsx("div",{className:"mt-2 text-sm text-foreground/90 whitespace-pre-wrap break-words leading-relaxed",children:es.content}),cs&&Object.keys(cs).length>0&&jsxRuntimeExports.jsx("div",{className:"flex gap-2 mt-2",children:Object.entries(cs).map(([Aa,Oa])=>jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[Aa,"(",Oa,")"]},Aa))}),ts&&jsxRuntimeExports.jsx(TokenUsageBar,{usage:ts})]})})}function renderEvent(es){switch(es.eventType){case"user_message":return jsxRuntimeExports.jsx(UserBubble,{event:es});case"assistant_message":return isBlankAssistantMessage(es)?jsxRuntimeExports.jsx(AssistantResponseCard,{event:es}):jsxRuntimeExports.jsx(AssistantBubble,{event:es});case"assistant_response":return jsxRuntimeExports.jsx(AssistantResponseCard,{event:es});case"tool_call":return jsxRuntimeExports.jsx(ToolCallCard,{event:es});case"thinking":return jsxRuntimeExports.jsx(ThinkingBubble,{event:es});case"tool_result":return jsxRuntimeExports.jsx(ToolResultCard,{event:es});default:return jsxRuntimeExports.jsx(GenericEvent,{event:es})}}function InlineTurnSnapshot({snapshot:es}){var Aa;const[$,ts]=reactExports.useState(!1),{data:is}=useContextSnapshotDetail($?es.id:void 0),cs=is??es,Qr=reactExports.useMemo(()=>$?getContextItems(cs):[],[$,cs]),ja=reactExports.useMemo(()=>{var Ia;return((es.metadata??{}).contextItems??[]).length||(((Ia=es.injectedInstructions)==null?void 0:Ia.length)??0)},[es]),Na=PROVIDER_COLORS[es.provider]??PROVIDER_COLORS.ollama;return jsxRuntimeExports.jsxs("div",{className:"ml-8 mt-2",children:[jsxRuntimeExports.jsx("div",{className:"border border-border border-l-2 border-l-cyan-500 rounded-lg px-3 py-2 bg-card cursor-pointer hover:bg-secondary/30 transition-colors",...activatable(()=>ts(!$)),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(Eye,{className:"h-3.5 w-3.5 text-cyan-500 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"text-xs font-medium text-cyan-600 dark:text-cyan-400",children:"Snapshot"}),jsxRuntimeExports.jsx(Badge,{className:`text-[10px] font-mono border ${Na} px-1.5 py-0`,children:es.provider}),jsxRuntimeExports.jsx("span",{className:"text-[11px] font-mono text-muted-foreground",children:es.model}),jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["~",(es.estimatedTokens??0).toLocaleString()," tok"]}),ja>0&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[ja," context items"]}),Array.isArray(es.tools)&&es.tools.length>0&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[es.tools.length," tools"]}),jsxRuntimeExports.jsx("div",{className:"flex-1"}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 text-muted-foreground"})]})}),$&&jsxRuntimeExports.jsx("div",{className:"ml-4 mt-2 space-y-2",children:is?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Qr.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Context Items"}),Object.entries(Qr.reduce((Oa,Ia)=>{var La;return(Oa[La=Ia.type]??(Oa[La]=[])).push(Ia),Oa},{})).map(([Oa,Ia])=>jsxRuntimeExports.jsxs("div",{className:"mb-1",children:[jsxRuntimeExports.jsxs("p",{className:"text-[10px] font-medium text-muted-foreground/70 capitalize mb-0.5",children:[Oa.replace(/_/g," ")," (",Ia.length,")"]}),Ia.map((La,Ba)=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 text-xs font-mono text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"truncate",children:La.name}),La.estimated_tokens!=null&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] shrink-0",children:["~",La.estimated_tokens.toLocaleString()," tok"]})]},Ba))]},Oa))]}),cs.systemPrompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:["System prompt: ",(cs.systemPrompt.length??0).toLocaleString()," chars"]}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-[10px]",children:["hash: ",((Aa=cs.systemHash)==null?void 0:Aa.slice(0,12))??"..."]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground flex-wrap",children:[cs.maxTokens!=null&&jsxRuntimeExports.jsxs("span",{children:["Max tokens: ",cs.maxTokens.toLocaleString()]}),cs.temperature!=null&&jsxRuntimeExports.jsxs("span",{children:["Temp: ",cs.temperature]}),Array.isArray(cs.tools)&&jsxRuntimeExports.jsxs("span",{children:[cs.tools.length," tools available"]})]})]}):jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 py-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin"}),"Loading snapshot..."]})})]})}function TurnContainer({turn:es,index:$,totalTurns:ts,snapshot:is,hideSnapshot:cs}){var Aa,Oa,Ia,La,Ba;const Qr=es.events.filter(Ma=>Ma.eventType==="tool_call").length,ja=eventUsage(es.assistantResponse)??((Aa=is==null?void 0:is.metadata)==null?void 0:Aa.usage),Na=ja==null?void 0:ja.output_tokens;return((Ia=(Oa=es.assistantResponse)==null?void 0:Oa.metadata)==null?void 0:Ia.response_time_ms)??((Ba=(La=is==null?void 0:is.metadata)==null?void 0:La.responseHeaders)==null||Ba["server-timing"]),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 pt-6 pb-2",children:[jsxRuntimeExports.jsxs("div",{className:"text-xs font-mono text-muted-foreground/60",children:["Turn ",ts-$]}),jsxRuntimeExports.jsx("div",{className:"h-px flex-1 bg-border/50"}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[Qr>0&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[Qr," tool",Qr!==1?"s":""]}),Na!=null&&Na>0&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-1",children:[jsxRuntimeExports.jsx(Zap,{className:"h-2.5 w-2.5"}),formatTokenCount(Na)," tokens"]})]})]}),jsxRuntimeExports.jsxs("div",{className:"relative pl-6",children:[jsxRuntimeExports.jsx("div",{className:"absolute left-[11px] top-0 bottom-0 w-px bg-border/40"}),es.userMessage&&jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("div",{className:"absolute left-[-17px] top-4 w-2 h-2 rounded-full bg-blue-500 ring-2 ring-background"}),jsxRuntimeExports.jsx(UserBubble,{event:es.userMessage})]}),es.events.map(Ma=>{if(Ma.eventType==="assistant_response")return jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("div",{className:"absolute left-[-17px] top-4 w-2 h-2 rounded-full bg-primary ring-2 ring-background"}),jsxRuntimeExports.jsx(AssistantResponseCard,{event:Ma})]},Ma.id);const qa=Ma.eventType==="tool_call"?"bg-amber-500":Ma.eventType==="thinking"?"bg-rose-500":Ma.eventType==="tool_result"?"bg-teal-500":Ma.eventType==="assistant_message"?"bg-primary":"bg-muted-foreground";return jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("div",{className:`absolute left-[-17px] top-3 w-2 h-2 rounded-full ${qa} ring-2 ring-background`}),renderEvent(Ma)]},Ma.id)}),is&&!cs&&jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx("div",{className:"absolute left-[-17px] top-3 w-2 h-2 rounded-full bg-cyan-500 ring-2 ring-background"}),jsxRuntimeExports.jsx(InlineTurnSnapshot,{snapshot:is})]})]})]})}function SessionDetailPage(){var ic,Iu;const{id:es}=useParams(),[$,ts]=useSearchParams(),{data:is,isLoading:cs}=useSession(es),{data:Qr,isLoading:ja,hasNextPage:Na,fetchNextPage:Aa,isFetchingNextPage:Oa}=useSessionEventsInfinite(es),Ia=useAnalyzeSession(),La=useCreateLaunchJob(),Ba=(ic=Ia.data)==null?void 0:ic.jobId,{data:Ma}=useInsightsJob(Ba),[qa,Fa]=reactExports.useState(""),{data:Ha}=useContextSnapshots(es),Ka=$.get("filter"),[Ga,Va]=reactExports.useState(Ka??"turns"),Ja=$.get("layout"),[Ya,el]=reactExports.useState(Ja??"default"),tl=reactExports.useMemo(()=>(Qr==null?void 0:Qr.pages.flat())??[],[Qr]),rl=reactExports.useMemo(()=>{switch(Ga){case"conversation":return tl.filter(Bl=>Bl.eventType==="user_message"||isAgentResponseEvent(Bl));case"tools":return tl.filter(Bl=>Bl.eventType==="tool_call");case"responses":return tl.filter(isAgentResponseEvent);default:return tl}},[tl,Ga]),cl=reactExports.useMemo(()=>groupEventsIntoTurns([...tl].sort((Bl,ru)=>Bl.sequence-ru.sequence)),[tl]),dl=reactExports.useMemo(()=>((is==null?void 0:is.linkedInstructions)??[]).filter(Bl=>Bl.linkMethod==="context_file"),[is==null?void 0:is.linkedInstructions]),fl=reactExports.useMemo(()=>((is==null?void 0:is.linkedInstructions)??[]).filter(Bl=>Bl.linkMethod!=="context_file"),[is==null?void 0:is.linkedInstructions]),nl=reactExports.useMemo(()=>sessionEventCounts(tl,is==null?void 0:is.eventCounts),[is==null?void 0:is.eventCounts,tl]);if(cs)return jsxRuntimeExports.jsx(Skeleton,{className:"h-96 w-full"});if(!is)return jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Session not found"});const ol=is.analysis,hl=ol==null?void 0:ol.adherenceScore,Tl=ol==null?void 0:ol.summary,ul=ol==null?void 0:ol.suggestions,pl=ol==null?void 0:ol.brief_summary,jl=ol==null?void 0:ol.underlying_goal,Nl=ol==null?void 0:ol.outcome,zl=ol==null?void 0:ol.session_type,Zl=ol==null?void 0:ol.goal_categories,Dl=ol==null?void 0:ol.friction_counts,Il=ol==null?void 0:ol.friction_detail,Fl=ol==null?void 0:ol.primary_success,ql=ol==null?void 0:ol.tool,nu=is.analyzedAt??(ol==null?void 0:ol.analyzed_at),Gl=is.analyzedEventCount??(ol==null?void 0:ol.analyzed_event_count),cu=is.analyzedTurnCount??(ol==null?void 0:ol.analyzed_turn_count),Al=!!pl||!!jl,Ml=Object.values(Dl??{}).reduce((Bl,ru)=>Bl+ru,0),Ql=is.endedAt?Math.max(0,Math.round((new Date(is.endedAt).getTime()-new Date(is.startedAt).getTime())/6e4)):null,eu=ol?jsxRuntimeExports.jsxs("div",{className:`mt-2 flex items-center gap-2 rounded-md border px-3 py-1.5 text-xs ${nu?"border-border bg-muted/40 text-foreground":"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300"}`,children:[jsxRuntimeExports.jsx(Clock,{className:"h-3.5 w-3.5 shrink-0"}),jsxRuntimeExports.jsx("div",{className:"flex-1 font-mono",children:nu?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:"Analyzed"})," ",formatEventTimestamp(nu),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" ","(",new Date(nu).toLocaleString(),")"]}),(cu!=null||Gl!=null)&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" · ",cu!=null&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["through turn ",cu]}),Gl!=null&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[cu!=null?" ":"","(",Gl," event",Gl===1?"":"s",")"]})]})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:"Analyzed at unknown time"})," — ","this analysis predates timestamp tracking. Re-analyze to record when it ran and which turn it covered."]})}),!nu&&canAnalyzeWithToolCli(is.tool)&&jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",className:"h-7 cursor-pointer text-xs",onClick:()=>Ia.mutate(is.id),disabled:Ia.isPending||Ia.isSuccess,children:Ia.isPending?"Submitting...":Ia.isSuccess?"Queued":"Re-analyze"})]}):null,fu=(is.metadata??{}).clientName,Ou=[{key:"turns",label:"Turns"},{key:"all",label:"All"},{key:"conversation",label:"Conversation"},{key:"tools",label:"Tools"},{key:"responses",label:"Responses"}],yu=(()=>{if(is.tool!=="claude_code"||!is.externalSessionId)return!1;if(!is.endedAt||new Date(is.endedAt).getTime()<new Date(is.startedAt).getTime())return!0;const Bl=10080*60*1e3;return Date.now()-new Date(is.endedAt).getTime()<Bl})();return jsxRuntimeExports.jsxs("div",{className:`space-y-6 ${yu?"pb-40":""}`,children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"icon",className:"cursor-pointer shrink-0",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/sessions",children:jsxRuntimeExports.jsx(ArrowLeft,{className:"h-4 w-4"})})}),jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Session Detail"}),is.gitBranch&&jsxRuntimeExports.jsxs("span",{title:`git branch: ${is.gitBranch}`,className:"inline-flex items-center gap-1.5 rounded-md border border-primary/40 bg-primary/10 px-2.5 py-1 font-mono text-sm font-semibold text-primary max-w-[11rem] sm:max-w-[18rem] truncate",children:[jsxRuntimeExports.jsx(GitBranch,{className:"h-4 w-4 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:is.gitBranch})]})]}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground font-mono text-sm flex items-center gap-1.5 flex-wrap",children:[jsxRuntimeExports.jsx(ToolIcon,{tool:is.tool,className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{children:displayTool(is.tool)}),is.harnessVersion&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/60",title:"harness version",children:["v",is.harnessVersion]}),fu&&jsxRuntimeExports.jsxs("span",{children:["(",fu,")"]}),is.model&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{children:"·"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground/80",title:"model (rolled up from the transcript)",children:is.model})]}),jsxRuntimeExports.jsx("span",{children:"·"}),jsxRuntimeExports.jsx("span",{children:projectDisplayName(is)}),jsxRuntimeExports.jsx("span",{children:"·"}),jsxRuntimeExports.jsx("span",{children:formatEventTimestamp(is.startedAt)})," ",jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/60",children:["(",is.startedAt?new Date(is.startedAt).toLocaleString():"—",")"]})]}),nl.total>0&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[nl.partial&&"Loaded events: ",nl.messages," messages, ",nl.tools," tool calls",nl.assistantResponses>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[", ",nl.assistantResponses," responses"]})]})]})]}),jsxRuntimeExports.jsx("div",{className:"flex items-center gap-2",children:!ol&&canAnalyzeWithToolCli(is.tool)&&jsxRuntimeExports.jsx(Button,{onClick:()=>Ia.mutate(is.id),disabled:Ia.isPending||Ia.isSuccess,className:"cursor-pointer bg-primary text-primary-foreground",children:Ia.isPending?"Submitting...":Ia.isSuccess?"Analysis queued...":`Analyze via ${displayTool(is.tool)}`})})]}),jsxRuntimeExports.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[jsxRuntimeExports.jsx(Card,{className:"bg-card",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Outcome"}),jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[Nl==="achieved"||Nl==="mostly_achieved"?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 text-teal-500"}):jsxRuntimeExports.jsx(CircleHelp,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-lg font-semibold capitalize",children:(Nl==null?void 0:Nl.replace(/_/g," "))??"Not analyzed"})]})]})}),jsxRuntimeExports.jsx(Card,{className:"bg-card",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Activity"}),jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"h-4 w-4 text-blue-500"}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-lg font-semibold",children:[nl.messages," messages",nl.partial&&" (loaded)"]})]}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[nl.tools," tool calls · ",nl.total," events"]})]})}),jsxRuntimeExports.jsx(Card,{className:"bg-card",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Elapsed time"}),jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(Clock,{className:"h-4 w-4 text-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-lg font-semibold",children:Ql==null?"In progress":Ql<60?`${Ql}m`:`${Math.floor(Ql/60)}h ${Ql%60}m`})]})]})}),jsxRuntimeExports.jsx(Card,{className:Ml>0?"border-amber-500/30 bg-amber-500/5":"bg-card",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Friction"}),jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:`h-4 w-4 ${Ml?"text-amber-500":"text-muted-foreground"}`}),jsxRuntimeExports.jsx("span",{className:"font-mono text-lg font-semibold",children:ol?`${Ml} signal${Ml===1?"":"s"}`:"Unknown"})]})]})})]}),(jl||pl)&&jsxRuntimeExports.jsx(Card,{className:"border-primary/20 bg-primary/[0.03]",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-5",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Session goal"}),jsxRuntimeExports.jsx("p",{className:"mt-2 text-base font-medium",children:jl??pl}),jl&&pl&&jsxRuntimeExports.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:pl})]})}),Ma&&Ma.status!=="completed"&&jsxRuntimeExports.jsx(Card,{className:"bg-card border-border border-l-2 border-l-primary",children:jsxRuntimeExports.jsx(CardContent,{className:"pt-4 pb-4",children:jsxRuntimeExports.jsx("div",{className:"flex items-center gap-3",children:Ma.status==="failed"?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4 text-destructive"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium text-destructive",children:"Analysis failed"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:Ma.error})]})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin text-primary"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("p",{className:"text-sm font-medium",children:[Ma.status==="pending"&&"Waiting for worker...",Ma.status==="claimed"&&"Worker picked up job...",Ma.status==="running"&&"Analyzing session..."]}),!!((Iu=Ma.progress)!=null&&Iu.step)&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:[String(Ma.progress.step).replace(/_/g," "),!!Ma.progress.tool&&` via ${displayTool(String(Ma.progress.tool))}`]})]})]})})})}),ol&&Al?jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs(CardTitle,{className:"font-mono text-lg flex items-center gap-2",children:["Analysis",Nl&&jsxRuntimeExports.jsx(Badge,{variant:Nl==="achieved"||Nl==="mostly_achieved"?"default":Nl==="partially_achieved"?"secondary":"destructive",className:"font-mono",children:Nl.replace(/_/g," ")}),zl&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs",children:zl.replace(/_/g," ")}),ql&&jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:["via ",displayTool(ql)]})]}),eu]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[pl&&jsxRuntimeExports.jsx("p",{className:"text-sm",children:pl}),jl&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Goal"}),jsxRuntimeExports.jsx("p",{className:"text-sm",children:jl})]}),Fl&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Primary Success"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-teal-600 dark:text-teal-400",children:Fl})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[Zl&&Object.keys(Zl).length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Goal Categories"}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1.5",children:Object.entries(Zl).filter(([,Bl])=>Bl>0).sort(([,Bl],[,ru])=>ru-Bl).map(([Bl,ru])=>jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"text-xs font-mono",children:[Bl.replace(/_/g," ")," ",ru>1?`(${ru})`:""]},Bl))})]}),Dl&&Object.values(Dl).some(Bl=>Bl>0)&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Friction Points"}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1.5",children:Object.entries(Dl).filter(([,Bl])=>Bl>0).sort(([,Bl],[,ru])=>ru-Bl).map(([Bl,ru])=>jsxRuntimeExports.jsxs(Badge,{variant:"destructive",className:"text-xs font-mono",children:[Bl.replace(/_/g," ")," (",ru,")"]},Bl))}),Il&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:Il})]})]})]})]}):ol&&jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs(CardTitle,{className:"font-mono text-lg flex items-center gap-2",children:["Analysis",hl!=null&&jsxRuntimeExports.jsxs(Badge,{variant:hl>=80?"default":hl>=50?"secondary":"destructive",className:"font-mono",children:[hl,"% adherence"]})]}),eu]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:Tl}),ul&&ul.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-2",children:"Suggestions"}),ul.map((Bl,ru)=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded p-3 mb-2 bg-background",children:[jsxRuntimeExports.jsx("p",{className:"text-sm",children:Bl.rationale}),jsxRuntimeExports.jsxs("div",{className:"mt-2 grid grid-cols-2 gap-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Current"}),jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono p-2 bg-card rounded",children:Bl.currentContent})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-primary mb-1",children:"Suggested"}),jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono p-2 bg-card rounded border-primary/20 border",children:Bl.suggestedContent})]})]})]},ru))]})]})]}),jsxRuntimeExports.jsxs(TooltipProvider,{children:[(dl.length>0||fl.length>0)&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[dl.length>0&&jsxRuntimeExports.jsx(ContextBlock,{instructions:dl}),fl.length>0&&fl.map(Bl=>jsxRuntimeExports.jsx(InstructionCard,{instruction:Bl},Bl.instructionId))]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-4",children:[jsxRuntimeExports.jsxs("h3",{className:"text-sm font-medium flex items-center gap-1.5",children:["Timeline",jsxRuntimeExports.jsx(InfoTip,{content:"Conversation turns between you and the AI, including tool calls, thinking, and responses. Proxy snapshots show the exact context sent to the LLM for each turn."})]}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1 ml-auto",children:Ou.map(Bl=>jsxRuntimeExports.jsx(Badge,{asChild:!0,className:"py-1",variant:Ga===Bl.key?"default":"outline",children:jsxRuntimeExports.jsx("button",{type:"button",className:"cursor-pointer",onClick:()=>Va(Bl.key),children:Bl.label})},Bl.key))}),((Ha==null?void 0:Ha.length)??0)>0&&jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"text-xs font-mono shrink-0",children:[Ha.length," snapshots"]})]}),Ga==="turns"&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 mb-3 text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono",children:"Layout"}),[{key:"default",label:"Inline"},{key:"split",label:"Side panel"},{key:"capped",label:"Capped + summary"}].map(Bl=>jsxRuntimeExports.jsx(Badge,{asChild:!0,className:"py-1",variant:Ya===Bl.key?"default":"outline",children:jsxRuntimeExports.jsx("button",{type:"button",className:"cursor-pointer",onClick:()=>{el(Bl.key);const ru=new URLSearchParams($);Bl.key==="default"?ru.delete("layout"):ru.set("layout",Bl.key),ts(ru,{replace:!0})},children:Bl.label})},Bl.key))]}),ja?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:10}).map((Bl,ru)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-16 w-full"},ru))}):Ga==="turns"?jsxRuntimeExports.jsxs("div",{children:[cl.length===0&&((Ha==null?void 0:Ha.length)??0)===0?jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(FileText,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:"No activity captured"}),jsxRuntimeExports.jsxs("p",{className:"text-sm mt-1",children:["Use ",jsxRuntimeExports.jsx("code",{className:"font-mono text-xs bg-secondary px-1 py-0.5 rounded",children:"rulemetric proxy start"})," to capture LLM context, or install hooks for event capture"]})]}):cl.length===0?jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground py-8 text-center",children:["No conversation turns — ",(Ha==null?void 0:Ha.length)??0," proxy snapshots captured."]}):(()=>{var Mu,lc;const Bl=((lc=(Mu=is==null?void 0:is.eventCounts)==null?void 0:Mu.byType)==null?void 0:lc.user_message)??cl.length,ru=[...cl].map((Tu,Eu)=>({turn:Tu,chronoIdx:Eu})).reverse();if(Ya==="split")return jsxRuntimeExports.jsx("div",{className:"space-y-2",children:ru.map(({turn:Tu,chronoIdx:Eu},Ua)=>{var yl;const ll=Ha==null?void 0:Ha[Eu];return jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_360px] gap-6 border-t border-border/40 first:border-t-0",children:[jsxRuntimeExports.jsx(TurnContainer,{turn:Tu,index:Ua,totalTurns:Bl,snapshot:ll,hideSnapshot:!0}),jsxRuntimeExports.jsx("div",{className:"hidden lg:block pt-6",children:ll?jsxRuntimeExports.jsx("div",{className:"sticky top-4",children:jsxRuntimeExports.jsx(InlineTurnSnapshot,{snapshot:ll})}):jsxRuntimeExports.jsx("div",{className:"sticky top-4 text-xs text-muted-foreground/60 font-mono pt-2",children:"No snapshot for this turn"})})]},((yl=Tu.userMessage)==null?void 0:yl.id)??`turn-${Eu}`)})});if(Ya==="capped"){const Tu=(Ha??[]).reduce((Ua,ll)=>Ua+(ll.estimatedTokens??0),0),Eu=nl.tools;return jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-[minmax(0,1fr)_320px] gap-8",children:[jsxRuntimeExports.jsx("div",{className:"max-w-3xl",children:ru.map(({turn:Ua,chronoIdx:ll},yl)=>{var $l;return jsxRuntimeExports.jsx(TurnContainer,{turn:Ua,index:yl,totalTurns:Bl,snapshot:Ha==null?void 0:Ha[ll]},(($l=Ua.userMessage)==null?void 0:$l.id)??`turn-${ll}`)})}),jsxRuntimeExports.jsx("aside",{className:"hidden xl:block",children:jsxRuntimeExports.jsxs("div",{className:"sticky top-4 space-y-3 border border-border rounded-lg p-4 bg-card",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Session Summary"}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Turns"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:Bl})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Tool calls"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:Eu})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Snapshots"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:(Ha==null?void 0:Ha.length)??0})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"~Total tokens"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:Tu.toLocaleString()})]})]}),jsxRuntimeExports.jsxs("div",{className:"border-t border-border/40 pt-3",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Per-turn"}),jsxRuntimeExports.jsx("div",{className:"space-y-1 max-h-96 overflow-y-auto pr-1",children:ru.map(({turn:Ua,chronoIdx:ll},yl)=>{var bl,_l;const $l=Ha==null?void 0:Ha[ll],kl=Bl-yl,Za=Ua.events.filter(Ol=>Ol.eventType==="tool_call").length,al=eventUsage(Ua.assistantResponse)??((bl=$l==null?void 0:$l.metadata)==null?void 0:bl.usage),El=al==null?void 0:al.output_tokens;return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-mono",children:[jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/60 w-10",children:["T",kl]}),Za>0&&jsxRuntimeExports.jsxs("span",{className:"text-amber-500",children:[Za,"t"]}),El!=null&&El>0&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[formatTokenCount(El),"tk"]}),($l==null?void 0:$l.estimatedTokens)!=null&&jsxRuntimeExports.jsxs("span",{className:"text-cyan-500/80 ml-auto",children:[formatTokenCount($l.estimatedTokens)," ctx"]})]},((_l=Ua.userMessage)==null?void 0:_l.id)??`meta-${ll}`)})})]})]})})]})}return ru.map(({turn:Tu,chronoIdx:Eu},Ua)=>{var ll;return jsxRuntimeExports.jsx(TurnContainer,{turn:Tu,index:Ua,totalTurns:Bl,snapshot:Ha==null?void 0:Ha[Eu]},((ll=Tu.userMessage)==null?void 0:ll.id)??`turn-${Eu}`)})})(),Na&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-6 pb-2",children:jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Aa(),disabled:Oa,className:"cursor-pointer",children:Oa?"Loading...":"Load more events"})})]}):rl.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No events match the current filter."}):jsxRuntimeExports.jsxs("div",{children:[rl.map(Bl=>jsxRuntimeExports.jsx("div",{children:renderEvent(Bl)},Bl.id)),Na&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-6 pb-2",children:jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Aa(),disabled:Oa,className:"cursor-pointer",children:Oa?"Loading...":"Load more events"})})]})]})]}),yu&&jsxRuntimeExports.jsx(ResumeBar,{sessionId:is.id,session:is,externalSessionId:is.externalSessionId,launchProjectPath:is.primaryCheckoutPath??is.projectPath??"/tmp",resumePrompt:qa,setResumePrompt:Fa,resumeMutation:La})]})}function ResumeBar({sessionId:es,session:$,externalSessionId:ts,launchProjectPath:is,resumePrompt:cs,setResumePrompt:Qr,resumeMutation:ja}){const{data:Na}=useSessionTerminalTarget(es),Aa=useSendMessage$1(es),{data:Oa}=useLaunchJobs(),Ia=(Na==null?void 0:Na.target)??null,La=(Na==null?void 0:Na.capabilities)??{liveSend:!1,fallbackResume:!0,tmuxAvailable:!1,workerOnline:!1},Ba=(()=>{const ol=!!(Ia&&Ia.status==="active");return!La.workerOnline&&ol?"worker_offline":ol&&La.liveSend?"live_ready":Ia&&Ia.status!=="active"?"target_missing":La.tmuxAvailable?"launch_ready":"tmux_missing"})(),Ma=Aa.isPending?"sending":Aa.isError?"send_failed":Aa.isSuccess?"sent":Ba,qa=Ba==="live_ready"&&(Ma==="live_ready"||Ma==="sending"||Ma==="sent"),Fa=qa?"Send to live Claude session… (Enter submits, Shift+Enter for newline)":"Resume this session… (Enter submits, Shift+Enter for newline)",Ha=(()=>{switch(Ma){case"live_ready":return"Send to live Claude";case"launch_ready":return"Resume in Terminal";case"tmux_missing":return"Resume in Terminal";case"target_missing":return"Start new live session";case"worker_offline":return"Worker offline";case"sending":return qa?"Sending…":"Resuming…";case"sent":return qa?"Sent":"Resumed";case"send_failed":return"Retry"}})(),Ka=Ma==="worker_offline"||Ma==="sending"||ja.isPending,Ga=Aa.data,Va=(Ga==null?void 0:Ga.delivery)==="live"?Ga.target.target:null,Ja=(Ia==null?void 0:Ia.attachCommand)??(Ia!=null&&Ia.target?`tmux attach -t ${Ia.target}`:null),Ya=(Oa??[]).find(ol=>{var hl;return((hl=ol.config)==null?void 0:hl.resumeSessionId)===ts}),el=Ya==null?void 0:Ya.status,tl=!!(Ya!=null&&Ya.completedAt)&&Date.now()-new Date(Ya.completedAt).getTime()<3e4,rl=(()=>{var ol;return Ma==="send_failed"?{dot:"bg-red-500",label:Aa.error instanceof Error?Aa.error.message:"Send failed"}:Ma==="sent"&&qa&&Va?{dot:"bg-teal-500",label:`Sent to ${Va}`}:el==="pending"||el==="claimed"?{dot:"bg-amber-500 animate-pulse",label:"Queued — waiting for worker"}:el==="running"?{dot:"bg-teal-500 animate-pulse",label:(ol=Ya==null?void 0:Ya.result)!=null&&ol.pid?`Running (PID ${Ya.result.pid})`:"Running"}:el==="failed"?{dot:"bg-red-500",label:(Ya==null?void 0:Ya.error)??"Failed"}:el==="completed"&&tl?{dot:"bg-teal-500",label:"Resumed — Claude is now active"}:null})(),cl=La.workerOnline?"":" Worker offline — job will queue and run when the worker connects.",dl=(()=>{switch(Ba){case"worker_offline":return"Start worker: `rulemetric service install` or `rulemetric evals agent`";case"tmux_missing":return"Install tmux to enable live send."+cl;case"target_missing":return"The previous tmux session ended. Starting a new one will spawn a fresh terminal."+cl;case"launch_ready":return"Live send needs a tmux target. Fallback will spawn a new terminal."+cl;default:return null}})(),fl=ol=>{ts&&ja.mutate({tool:"claude_code",projectPath:is,mode:"interactive",resumeSessionId:ts,...ol?{prompt:ol}:{}},{onSuccess:()=>{ue$1(ol?"Resume request sent":"Resume request sent (no prompt)"),Qr("")},onError:hl=>ue$1.error(hl instanceof Error?hl.message:"Failed to resume")})},nl=()=>{if(Ka)return;const ol=cs.trim();if(!ol){if(Ba==="live_ready"){ue$1.error("Type a message to send");return}if(!ts)return;fl("");return}if(Ba==="live_ready"){Aa.mutate({message:ol,delivery:"live",submit:!0},{onSuccess:()=>Qr("")});return}ts&&fl(ol)};return jsxRuntimeExports.jsxs("div",{className:"fixed bottom-0 left-0 right-0 z-20 border-t border-border bg-background shadow-[0_-4px_20px_rgba(0,0,0,0.15)]",children:[rl&&jsxRuntimeExports.jsx("div",{className:"border-b border-border/60 bg-secondary/40",children:jsxRuntimeExports.jsxs("div",{className:"max-w-screen-xl mx-auto px-6 py-1.5 sm:px-8 flex items-center gap-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:`h-2 w-2 rounded-full ${rl.dot}`}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:rl.label}),Ja&&Ma==="sent"&&qa&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/70 font-mono ml-2",children:["· ",Ja]})]})}),jsxRuntimeExports.jsxs("div",{className:"max-w-screen-xl mx-auto px-6 py-3 sm:px-8 space-y-2",children:[jsxRuntimeExports.jsx(SessionTargetSummary,{target:Ia,capabilities:La,session:$}),dl&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground font-mono",children:dl}),jsxRuntimeExports.jsxs("form",{onSubmit:ol=>{ol.preventDefault(),nl()},className:"flex items-end gap-2",children:[jsxRuntimeExports.jsx("textarea",{value:cs,onChange:ol=>Qr(ol.target.value),onKeyDown:ol=>{var hl;ol.key==="Enter"&&!ol.shiftKey&&!ol.nativeEvent.isComposing&&(ol.preventDefault(),(hl=ol.currentTarget.form)==null||hl.requestSubmit())},placeholder:Fa,rows:2,className:"flex-1 resize-none rounded-md border border-input bg-card px-3 py-2 text-sm font-mono ring-offset-background placeholder:text-muted-foreground/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",disabled:Ka}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ka,className:"cursor-pointer self-end",children:Ha})]})]})]})}function useProjects(es={}){const $=new URLSearchParams;es.limit&&$.set("limit",String(es.limit)),es.offset&&$.set("offset",String(es.offset));const ts=$.toString();return useQuery({queryKey:["projects",es],queryFn:()=>apiGet(`/api/projects${ts?`?${ts}`:""}`),refetchInterval:POLL.ACTIVE})}function useProject(es){return useQuery({queryKey:["projects",es],queryFn:()=>apiGet(`/api/projects/${es}`),enabled:!!es,refetchInterval:POLL.ACTIVE})}function Select({...es}){return jsxRuntimeExports.jsx(Root2$1,{"data-slot":"select",...es})}function SelectValue({...es}){return jsxRuntimeExports.jsx(Value,{"data-slot":"select-value",...es})}function SelectTrigger({className:es,size:$="default",children:ts,...is}){return jsxRuntimeExports.jsxs(Trigger$3,{"data-slot":"select-trigger","data-size":$,className:cn$1("border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",es),...is,children:[ts,jsxRuntimeExports.jsx(Icon,{asChild:!0,children:jsxRuntimeExports.jsx(ChevronDown,{className:"size-4 opacity-50"})})]})}function SelectContent({className:es,children:$,position:ts="item-aligned",align:is="center",...cs}){return jsxRuntimeExports.jsx(Portal$2,{children:jsxRuntimeExports.jsxs(Content2$2,{"data-slot":"select-content",className:cn$1("bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",ts==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",es),position:ts,align:is,...cs,children:[jsxRuntimeExports.jsx(SelectScrollUpButton,{}),jsxRuntimeExports.jsx(Viewport,{className:cn$1("p-1",ts==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:$}),jsxRuntimeExports.jsx(SelectScrollDownButton,{})]})})}function SelectItem({className:es,children:$,...ts}){return jsxRuntimeExports.jsxs(Item,{"data-slot":"select-item",className:cn$1("focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",es),...ts,children:[jsxRuntimeExports.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:jsxRuntimeExports.jsx(ItemIndicator,{children:jsxRuntimeExports.jsx(Check,{className:"size-4"})})}),jsxRuntimeExports.jsx(ItemText,{children:$})]})}function SelectScrollUpButton({className:es,...$}){return jsxRuntimeExports.jsx(ScrollUpButton,{"data-slot":"select-scroll-up-button",className:cn$1("flex cursor-default items-center justify-center py-1",es),...$,children:jsxRuntimeExports.jsx(ChevronUp,{className:"size-4"})})}function SelectScrollDownButton({className:es,...$}){return jsxRuntimeExports.jsx(ScrollDownButton,{"data-slot":"select-scroll-down-button",className:cn$1("flex cursor-default items-center justify-center py-1",es),...$,children:jsxRuntimeExports.jsx(ChevronDown,{className:"size-4"})})}function Textarea({className:es,...$}){return jsxRuntimeExports.jsx("textarea",{"data-slot":"textarea",className:cn$1("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",es),...$})}function sanitizeTmuxName(es){return`rm-${es.trim().replace(/[^A-Za-z0-9_.-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"session"}`}function previewTmuxTarget(es){return sanitizeTmuxName("claude-auto")}function LaunchSessionDialog({open:es,onOpenChange:$,initialProjectPath:ts}){const is=useNavigate(),{data:cs}=useAvailableLaunchers(),Qr=useCreateLaunchJob(),[ja,Na]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(ts??""),[Ia,La]=reactExports.useState(""),[Ba,Ma]=reactExports.useState(""),[qa,Fa]=reactExports.useState("interactive");reactExports.useEffect(()=>{es&&Oa(Ja=>Ja||(ts??""))},[es,ts]);const Ha=()=>{Na(""),Oa(ts??""),La(""),Ma(""),Fa("interactive")},Ka=reactExports.useMemo(()=>previewTmuxTarget(),[]),Ga=Ja=>{Ja.preventDefault(),!(!ja||!Aa)&&Qr.mutate({tool:ja,projectPath:Aa,prompt:Ia||void 0,model:Ba||void 0,mode:qa},{onSuccess:Ya=>{var cl;const el=Ya.result,tl=(cl=el==null?void 0:el.terminalTarget)==null?void 0:cl.target,rl=(el==null?void 0:el.terminalTarget)&&el.terminalTarget.live===!1;ue$1(qa==="headless"?"Starting headless Claude Code job":tl?`Starting Claude Code in tmux target ${tl}`:rl?"Starting Claude Code in Terminal fallback":`Starting Claude Code in tmux target ${Ka}`),Ya.noLiveWorker&&ue$1.error("No worker online — start `rulemetric evals agent` to process this launch"),Ya.sessionId?is(`/sessions/${Ya.sessionId}`):is("/sessions"),Ha(),$(!1)},onError:Ya=>{ue$1.error(Ya instanceof Error?Ya.message:"Failed to create launch job")}})},Va=!!(ja&&Aa);return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{className:"sm:max-w-md",children:[jsxRuntimeExports.jsx(DialogHeader,{children:jsxRuntimeExports.jsx(DialogTitle,{children:"Launch Session"})}),jsxRuntimeExports.jsxs("form",{onSubmit:Ga,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"tool",children:"Tool"}),jsxRuntimeExports.jsxs(Select,{value:ja,onValueChange:Na,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"tool",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"Select a tool"})}),jsxRuntimeExports.jsx(SelectContent,{children:cs==null?void 0:cs.map(Ja=>jsxRuntimeExports.jsx(SelectItem,{value:Ja.tool,children:Ja.tool.replace(/_/g," ")},Ja.tool))})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"projectPath",children:"Project Path"}),jsxRuntimeExports.jsx(Input,{id:"projectPath",value:Aa,onChange:Ja=>Oa(Ja.target.value),placeholder:"/path/to/project",required:!0})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"prompt",children:"Prompt"}),jsxRuntimeExports.jsx(Textarea,{id:"prompt",value:Ia,onChange:Ja=>La(Ja.target.value),placeholder:"Optional prompt for the session",rows:3})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"model",children:"Model"}),jsxRuntimeExports.jsx(Input,{id:"model",value:Ba,onChange:Ja=>Ma(Ja.target.value),placeholder:"Optional model override"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"mode",children:"Mode"}),jsxRuntimeExports.jsxs(Select,{value:qa,onValueChange:Ja=>Fa(Ja),children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"mode",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"interactive",children:"Interactive"}),jsxRuntimeExports.jsx(SelectItem,{value:"headless",children:"Headless"})]})]})]}),Va&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border bg-muted/30 p-3 text-xs font-mono space-y-1",children:[jsxRuntimeExports.jsx("div",{className:"text-muted-foreground uppercase tracking-wide text-[10px] mb-1",children:"Launch summary"}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Tool"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:ja.replace(/_/g," ")})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Mode"}),jsxRuntimeExports.jsx("span",{children:qa})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Project path"}),jsxRuntimeExports.jsx("span",{className:"truncate",title:Aa,children:Aa})]}),Ia&&jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Prompt"}),jsxRuntimeExports.jsx("span",{className:"truncate max-w-[16rem]",title:Ia,children:Ia})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"Expected target"}),jsxRuntimeExports.jsx("span",{className:"truncate",title:Ka,children:Ka})]}),qa==="interactive"&&jsxRuntimeExports.jsx("div",{className:"pt-1 text-[10px] text-amber-600",children:"Live send requires tmux on the worker host."})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"ghost",onClick:()=>$(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:!ja||!Aa||Qr.isPending,children:Qr.isPending?"Launching...":"Launch"})]})]})]})})}function ProjectCard$1({p:es,onClick:$,onLaunch:ts}){return jsxRuntimeExports.jsxs(Card,{className:"cursor-pointer hover:bg-secondary/30 transition-colors",onClick:$,children:[jsxRuntimeExports.jsxs(CardHeader,{className:"flex flex-row items-start justify-between space-y-0 pb-3",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono text-base font-semibold truncate",children:es.name}),es.gitRemoteUrl&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground font-mono flex items-center gap-1 mt-1",children:[jsxRuntimeExports.jsx(GitBranch,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:es.gitRemoteUrl})]}),es.primaryCheckoutPath&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground font-mono flex items-center gap-1 mt-0.5",children:[jsxRuntimeExports.jsx(Folder,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:es.primaryCheckoutPath})]})]}),jsxRuntimeExports.jsx("div",{className:"flex flex-col items-end gap-1 shrink-0 ml-3",children:es.activeSessionCount>0?jsxRuntimeExports.jsxs(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30",children:[es.activeSessionCount," active"]}):jsxRuntimeExports.jsx(Badge,{variant:"outline",children:"idle"})})]}),jsxRuntimeExports.jsxs(CardContent,{className:"pt-0 pb-4 text-xs text-muted-foreground font-mono flex items-center justify-between",children:[jsxRuntimeExports.jsxs("span",{children:[es.sessionCount," session",es.sessionCount===1?"":"s"," total"]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsxs("span",{children:["last activity ",formatRelativeTime(es.lastActivityAt,{fallback:"never"})]}),es.primaryCheckoutPath&&jsxRuntimeExports.jsxs(Button,{type:"button",size:"sm",variant:"outline",className:"h-7 px-2 text-[11px] cursor-pointer",onClick:is=>{is.stopPropagation(),ts(es.primaryCheckoutPath)},title:`Launch a new session in ${es.primaryCheckoutPath}`,children:[jsxRuntimeExports.jsx(Rocket,{className:"h-3 w-3 mr-1"}),"Launch"]})]})]})]})}function ProjectsListPage(){const es=useNavigate(),{data:$,isLoading:ts,isError:is}=useProjects({limit:100}),[cs,Qr]=reactExports.useState("cards"),[ja,Na]=reactExports.useState(!1),[Aa,Oa]=reactExports.useState(void 0),Ia=Ba=>{Oa(Ba),Na(!0)};let La;return ts?La=jsxRuntimeExports.jsxs("div",{className:"grid gap-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-28 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-28 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-28 w-full"})]}):is?La=jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-destructive font-mono",children:"Failed to load projects."}):!$||$.projects.length===0?La=jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(Layers,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:"No projects yet"}),jsxRuntimeExports.jsx("p",{className:"text-sm mt-1",children:"Projects appear after your first captured session in this org."})]}):cs==="cards"?La=jsxRuntimeExports.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:$.projects.map(Ba=>jsxRuntimeExports.jsx(ProjectCard$1,{p:Ba,onClick:()=>es(`/projects/${Ba.id}`),onLaunch:Ma=>Ia(Ma)},Ba.id))}):La=jsxRuntimeExports.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"bg-card hover:bg-card",children:[jsxRuntimeExports.jsx(TableHead,{children:"Project"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Active"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Total"}),jsxRuntimeExports.jsx(TableHead,{className:"w-40 text-right",children:"Last activity"}),jsxRuntimeExports.jsx(TableHead,{className:"w-28 text-right",children:"Actions"})]})}),jsxRuntimeExports.jsx(TableBody,{children:$.projects.map(Ba=>jsxRuntimeExports.jsxs(TableRow,{className:"cursor-pointer hover:bg-secondary/50 transition-colors",onClick:()=>es(`/projects/${Ba.id}`),children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("div",{className:"font-mono text-sm font-semibold truncate",children:Ba.name}),Ba.gitRemoteUrl&&jsxRuntimeExports.jsx("div",{className:"text-xs text-muted-foreground font-mono truncate",children:Ba.gitRemoteUrl})]})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:Ba.activeSessionCount>0?jsxRuntimeExports.jsx(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30",children:Ba.activeSessionCount}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono text-sm",children:"—"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right font-mono text-sm",children:Ba.sessionCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-sm text-muted-foreground whitespace-nowrap",children:formatRelativeTime(Ba.lastActivityAt,{fallback:"never"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",onClick:Ma=>Ma.stopPropagation(),children:Ba.primaryCheckoutPath?jsxRuntimeExports.jsxs(Button,{type:"button",size:"sm",variant:"outline",className:"h-7 px-2 text-[11px] cursor-pointer",onClick:()=>Ia(Ba.primaryCheckoutPath),title:`Launch a new session in ${Ba.primaryCheckoutPath}`,children:[jsxRuntimeExports.jsx(Rocket,{className:"h-3 w-3 mr-1"}),"Launch"]}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})})]},Ba.id))})]})}),jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 basis-56",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Projects"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"All projects in your active org. Click one to see its sessions."})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[jsxRuntimeExports.jsxs(Button,{size:"sm",className:"h-8 cursor-pointer",onClick:()=>Ia(void 0),children:[jsxRuntimeExports.jsx(Rocket,{className:"h-3.5 w-3.5 mr-1.5"}),"Launch session"]}),jsxRuntimeExports.jsxs("div",{role:"group","aria-label":"View mode",className:"inline-flex items-center rounded-md border border-border bg-card p-0.5",children:[jsxRuntimeExports.jsx(Button,{type:"button",size:"sm",variant:cs==="cards"?"secondary":"ghost","aria-pressed":cs==="cards",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>Qr("cards"),children:"Cards"}),jsxRuntimeExports.jsx(Button,{type:"button",size:"sm",variant:cs==="list"?"secondary":"ghost","aria-pressed":cs==="list",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>Qr("list"),children:"List"})]})]})]}),La,jsxRuntimeExports.jsx(LaunchSessionDialog,{open:ja,onOpenChange:Na,initialProjectPath:Aa})]})}function useRuns(es={}){const $=new URLSearchParams;es.limit&&$.set("limit",String(es.limit)),es.offset&&$.set("offset",String(es.offset)),es.projectId&&$.set("projectId",es.projectId);const ts=$.toString();return useQuery({queryKey:["runs","list",es],queryFn:()=>apiGet(`/api/runs${ts?`?${ts}`:""}`),enabled:es.projectId===void 0||!!es.projectId,refetchInterval:POLL.ACTIVE})}function useRunsEnabled(){return"false"==="1"}function sessionGoal(es){var ts;const $=(ts=es.analysis)==null?void 0:ts.goalSummary;return $?{text:$,isFallback:!1}:es.firstUserPrompt?{text:es.firstUserPrompt,isFallback:!0}:{text:"(no goal yet)",isFallback:!0}}function isActive(es){if(es.endedAt)return!1;const $=new Date(es.lastActivityAt??es.startedAt).getTime();return Date.now()-$<1800*1e3}function duration$1(es){const ts=new Date(es.endedAt??es.lastActivityAt??es.startedAt).getTime()-new Date(es.startedAt).getTime();if(!Number.isFinite(ts)||ts<0)return"—";const is=Math.floor(ts/6e4);return is<1?"<1m":is<60?`${is}m`:`${Math.floor(is/60)}h ${is%60}m`}function SessionCard({s:es,emphasized:$,onOpen:ts}){const is=sessionGoal(es);return jsxRuntimeExports.jsx(Card,{className:`cursor-pointer transition-colors hover:bg-secondary/30 ${$?"border-teal-500/40 shadow-[0_0_12px_-4px_rgba(16,185,129,0.35)]":""}`,onClick:ts,children:jsxRuntimeExports.jsxs(CardContent,{className:"py-3 flex flex-col gap-2 h-full",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground font-mono flex-wrap",children:[jsxRuntimeExports.jsx(ToolIcon,{tool:captureToolKey(es.tool),className:"h-4 w-4 shrink-0"}),jsxRuntimeExports.jsx("span",{children:displayTool(es.tool)}),es.gitBranch&&jsxRuntimeExports.jsxs("span",{children:["· ",es.gitBranch]}),jsxRuntimeExports.jsxs("span",{children:["· ",formatRelativeTime(es.lastActivityAt??es.startedAt)]}),isActive(es)&&jsxRuntimeExports.jsx(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30 text-[10px]",children:"active"})]}),jsxRuntimeExports.jsx("p",{className:`text-sm line-clamp-2 ${is.isFallback?"italic text-muted-foreground":"text-foreground"}`,children:is.text}),es.lastMessagePreview&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground line-clamp-2 font-mono",children:["↳ ",es.lastMessagePreview]}),jsxRuntimeExports.jsxs("div",{className:"mt-auto pt-1 text-[11px] text-muted-foreground font-mono",children:[es.eventCount," events · ",duration$1(es)]})]})})}function ProjectDetailPage(){const{id:es}=useParams(),$=useNavigate(),ts=useProject(es),is=useSessions({projectId:es,hideEmpty:!1,limit:200}),cs=useRunsEnabled();useRuns({projectId:""});const[Qr,ja]=reactExports.useState("cards"),[Na,Aa]=reactExports.useState(!1);if(ts.isLoading)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"})]});if(ts.isError||!ts.data)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs(Link,{to:"/projects",className:"text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"h-3 w-3"})," Projects"]}),jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-destructive font-mono",children:"Project not found."})]});const Oa=ts.data,Ia=is.data??[],La=null,Ba=Ia;let Ma;if(is.isLoading)Ma=jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"});else if(Ia.length===0)Ma=jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground font-mono text-sm",children:"No sessions yet for this project."});else if(Qr==="cards"){const qa=Ba.filter(isActive),Fa=Ba.filter(Ha=>!isActive(Ha));Ma=jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[qa.length>0&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"relative flex h-2 w-2",children:[jsxRuntimeExports.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-teal-500 opacity-60"}),jsxRuntimeExports.jsx("span",{className:"relative inline-flex rounded-full h-2 w-2 bg-teal-500"})]}),jsxRuntimeExports.jsxs("h4",{className:"text-sm font-mono font-semibold text-teal-600",children:["Active now · ",qa.length]})]}),jsxRuntimeExports.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:qa.map(Ha=>jsxRuntimeExports.jsx(SessionCard,{s:Ha,emphasized:!0,onOpen:()=>$(`/sessions/${Ha.id}`)},Ha.id))})]}),Fa.length>0&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[qa.length>0&&jsxRuntimeExports.jsx("h4",{className:"text-sm font-mono font-semibold text-muted-foreground",children:"Earlier"}),jsxRuntimeExports.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-3",children:Fa.map(Ha=>jsxRuntimeExports.jsx(SessionCard,{s:Ha,onOpen:()=>$(`/sessions/${Ha.id}`)},Ha.id))})]})]})}else Ma=jsxRuntimeExports.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"bg-card hover:bg-card",children:[jsxRuntimeExports.jsx(TableHead,{className:"w-40",children:"Tool"}),jsxRuntimeExports.jsx(TableHead,{className:"w-40",children:"Branch"}),jsxRuntimeExports.jsx(TableHead,{children:"Goal"}),jsxRuntimeExports.jsx(TableHead,{className:"w-24",children:"Status"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Last activity"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Ba.map(qa=>{const Fa=sessionGoal(qa);return jsxRuntimeExports.jsxs(TableRow,{className:"cursor-pointer hover:bg-secondary/50 transition-colors",onClick:()=>$(`/sessions/${qa.id}`),children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(ToolIcon,{tool:captureToolKey(qa.tool),className:"h-4 w-4 text-muted-foreground shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm truncate",children:displayTool(qa.tool)})]})}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-sm text-muted-foreground",children:qa.gitBranch??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"max-w-md",children:jsxRuntimeExports.jsx("p",{className:`text-sm line-clamp-2 ${Fa.isFallback?"italic text-muted-foreground":"text-foreground"}`,children:Fa.text})}),jsxRuntimeExports.jsx(TableCell,{children:isActive(qa)?jsxRuntimeExports.jsx(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30",children:"active"}):qa.endedAt?jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs font-mono",children:"ended"}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs font-mono",children:"idle"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-sm text-muted-foreground whitespace-nowrap",children:formatRelativeTime(qa.lastActivityAt??qa.startedAt)})]},qa.id)})})]})});return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs(Link,{to:"/projects",className:"text-sm text-muted-foreground hover:text-foreground inline-flex items-center gap-1",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"h-3 w-3"})," Projects"]}),jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight truncate",children:Oa.name}),Oa.description&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Oa.description}),jsxRuntimeExports.jsxs("div",{className:"mt-2 space-y-1",children:[Oa.gitRemoteUrl&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground font-mono flex items-center gap-1.5",children:[jsxRuntimeExports.jsx(GitBranch,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:Oa.gitRemoteUrl})]}),Oa.primaryCheckoutPath&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground font-mono flex items-center gap-1.5",children:[jsxRuntimeExports.jsx(Folder,{className:"h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{className:"truncate",children:Oa.primaryCheckoutPath})]})]})]}),jsxRuntimeExports.jsxs("div",{className:"text-right shrink-0 space-y-1.5 flex flex-col items-end",children:[cs,Oa.activeSessionCount>0&&jsxRuntimeExports.jsxs(Badge,{className:"bg-teal-500/15 text-teal-600 border-teal-500/30",children:[Oa.activeSessionCount," active"]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground font-mono",children:[Oa.sessionCount," total"]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground font-mono",children:["last ",formatRelativeTime(Oa.lastActivityAt)]})]})]})})}),La,jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-mono font-semibold",children:"Sessions"}),jsxRuntimeExports.jsxs("div",{role:"group","aria-label":"View mode",className:"inline-flex items-center rounded-md border border-border bg-card p-0.5",children:[jsxRuntimeExports.jsx(Button,{type:"button",size:"sm",variant:Qr==="cards"?"secondary":"ghost","aria-pressed":Qr==="cards",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>ja("cards"),children:"Cards"}),jsxRuntimeExports.jsx(Button,{type:"button",size:"sm",variant:Qr==="list"?"secondary":"ghost","aria-pressed":Qr==="list",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>ja("list"),children:"List"})]})]}),Ma,cs]})}function useEvalTargets(es){return useQuery({queryKey:["eval-targets",es],queryFn:()=>apiGet("/api/eval-targets")})}function useEvalTarget(es){return useQuery({queryKey:["eval-targets",es],queryFn:()=>apiGet(`/api/eval-targets/${es}`),enabled:!!es})}function useEvals(es){return useQuery({queryKey:["eval-targets",es,"evals"],queryFn:()=>apiGet(`/api/eval-targets/${es}/evals`),enabled:!!es})}function useEvalRuns(es,$){return useQuery({queryKey:["eval-targets",es,"runs",$],queryFn:()=>apiGet(`/api/eval-targets/${es}/runs`),enabled:!!es})}function useBenchmarks(es){return useQuery({queryKey:["eval-targets",es,"benchmarks"],queryFn:()=>apiGet(`/api/eval-targets/${es}/benchmarks`),enabled:!!es})}function useEvalComparisons(es){return useQuery({queryKey:["eval-targets",es,"comparisons"],queryFn:()=>apiGet(`/api/eval-targets/${es}/comparisons`),enabled:!!es})}function useEvalComparison(es,$=!0){return useQuery({queryKey:["eval-comparisons",es],queryFn:()=>apiGet(`/api/eval-comparisons/${es}`),enabled:!!es&&$})}function useGradeAnnotations(es){return useQuery({queryKey:["eval-targets",es,"annotations"],queryFn:()=>apiGet(`/api/eval-targets/${es}/annotations?limit=500`),enabled:!!es})}function useAnnotateGrade(es){const $=useQueryClient();return useMutation({mutationFn:({runId:ts,expectationIndex:is,verdict:cs,flag:Qr,note:ja})=>apiPut(`/api/eval-runs/${ts}/annotations/${is}`,{verdict:cs,...Qr!==void 0?{flag:Qr}:{},...ja!==void 0?{note:ja}:{}}),onSuccess:()=>{$.invalidateQueries({queryKey:["eval-targets",es,"annotations"]}),$.invalidateQueries({queryKey:["eval-targets",es,"judge-calibration"]})}})}function useRemoveGradeAnnotation(es){const $=useQueryClient();return useMutation({mutationFn:({runId:ts,expectationIndex:is})=>apiDelete(`/api/eval-runs/${ts}/annotations/${is}`),onSuccess:()=>{$.invalidateQueries({queryKey:["eval-targets",es,"annotations"]}),$.invalidateQueries({queryKey:["eval-targets",es,"judge-calibration"]})}})}function useJudgeDisagreements(es){return useQuery({queryKey:["eval-targets",es,"judge-disagreements"],queryFn:()=>apiGet(`/api/eval-targets/${es}/judge-reviews/disagreements`),enabled:!!es})}function useResolveJudgeReview(es){const $=useQueryClient();return useMutation({mutationFn:({id:ts,resolution:is})=>apiPatch(`/api/judge-reviews/${ts}/resolve`,{resolution:is}),onSuccess:()=>{$.invalidateQueries({queryKey:["eval-targets",es,"judge-disagreements"]})}})}function useJudgeCalibration(es){return useQuery({queryKey:["eval-targets",es,"judge-calibration"],queryFn:()=>apiGet(`/api/eval-targets/${es}/judge-calibration`),enabled:!!es})}function useAnnotationQueue(es){return useQuery({queryKey:["eval-targets",es,"annotation-queue"],queryFn:()=>apiGet(`/api/eval-targets/${es}/annotation-queue`),enabled:!!es})}function EvalTargetsListPage(){const es=useNavigate(),{data:$,isLoading:ts}=useEvalTargets();return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Eval Targets"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Manage eval targets and view benchmark results"})]}),ts?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:5}).map((is,cs)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 w-full"},cs))}):$!=null&&$.length?jsxRuntimeExports.jsx("div",{className:"border border-border rounded-lg overflow-hidden",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"bg-card hover:bg-card",children:[jsxRuntimeExports.jsx(TableHead,{children:"Name"}),jsxRuntimeExports.jsx(TableHead,{children:"Type"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Version"}),jsxRuntimeExports.jsx(TableHead,{children:"Description"}),jsxRuntimeExports.jsx(TableHead,{children:"Updated"})]})}),jsxRuntimeExports.jsx(TableBody,{children:$.map(is=>jsxRuntimeExports.jsxs(TableRow,{className:"cursor-pointer hover:bg-secondary/50 transition-colors",onClick:()=>es(`/eval-targets/${is.id}`),children:[jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-sm font-medium",children:is.name}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono",children:is.type})}),jsxRuntimeExports.jsxs(TableCell,{className:"text-right font-mono text-sm",children:["v",is.version]}),jsxRuntimeExports.jsx(TableCell,{className:"text-sm text-muted-foreground max-w-64 truncate",children:is.description||"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-sm text-muted-foreground",children:new Date(is.updatedAt).toLocaleDateString()})]},is.id))})]})}):jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:"No eval targets yet"}),jsxRuntimeExports.jsxs("p",{className:"text-sm mt-1",children:["Create eval targets via the CLI with"," ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric eval-targets create"})]})]})]})}function StudiesPanel({targetId:es}){var ts;const $=useQuery({queryKey:["eval-targets",es,"studies"],queryFn:()=>apiGet(`/api/eval-targets/${es}/studies`)});return $.isPending?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading frozen studies…"}):$.isError?jsxRuntimeExports.jsx("p",{role:"alert",className:"text-sm",children:"Study evidence could not be loaded."}):(ts=$.data)!=null&&ts.length?jsxRuntimeExports.jsx("section",{"aria-label":"Frozen performance studies",className:"mb-6 space-y-3",children:$.data.map(is=>{var cs;return jsxRuntimeExports.jsxs("article",{className:"rounded-lg border border-border p-4 space-y-2",children:[jsxRuntimeExports.jsx("h3",{className:"font-medium",children:is.question}),jsxRuntimeExports.jsxs("p",{className:"text-sm",children:[is.result.decision.replaceAll("_"," ")," · ",is.result.role.replaceAll("_"," ")," · ",is.interventionType.replaceAll("_"," ")]}),!!((cs=is.sourceIncidentIds)!=null&&cs.length)&&jsxRuntimeExports.jsxs("p",{className:"text-sm",children:["Source incidents: ",is.sourceIncidentIds.map((Qr,ja)=>jsxRuntimeExports.jsxs("span",{children:[ja>0?", ":"",jsxRuntimeExports.jsxs(Link,{className:"underline",to:`/sessions/${Qr}`,children:["Incident ",ja+1]})]},Qr))]}),jsxRuntimeExports.jsxs("p",{className:"text-sm",children:["Outcome: ",is.primaryOutcome]}),jsxRuntimeExports.jsxs("p",{className:"text-sm",children:[is.result.analyzedTasks,"/",is.result.taskCount," tasks analyzed, ",is.result.repetitions," repetitions per arm. ",is.result.observedCalls,"/",is.result.assignedCalls," calls recorded; ",is.result.excluded.length," excluded; ",is.result.missingCalls," missing."]}),jsxRuntimeExports.jsxs("p",{className:"text-sm",children:[is.scope.engine," · ",is.scope.model," · ",is.scope.provider,". Scope expires ",new Date(is.scope.expiresAt).toLocaleDateString(),"."]}),jsxRuntimeExports.jsxs("p",{className:"text-sm",children:["Recorded actor time: ",is.result.totalDurationMs===null?"unknown":`${(is.result.totalDurationMs/6e4).toFixed(1)} minutes`,". Total effort includes infrastructure and review; unmeasured overhead remains unknown. Tokens: ",is.result.tokens??"unknown",". Cost: ",is.result.costUsd===null?"unknown":`$${is.result.costUsd.toFixed(2)}`,". Human review: ",is.result.humanReviewMinutes===null?"unknown":`${is.result.humanReviewMinutes} minutes`,"."]}),is.result.taskUncertaintyUsable&&is.result.taskEstimate&&jsxRuntimeExports.jsxs("p",{className:"text-sm",children:["Task-level interval: ",(is.result.taskEstimate.lower*100).toFixed(1)," to ",(is.result.taskEstimate.upper*100).toFixed(1)," percentage points."]}),!is.result.taskUncertaintyUsable&&jsxRuntimeExports.jsx("p",{className:"text-sm",children:"No usable task-level uncertainty estimate."}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:is.result.explanation}),jsxRuntimeExports.jsx("p",{className:"text-sm",children:is.result.performanceAdoptionAllowed?"Supports consideration of adoption within this scope; application and live confirmation are separate.":"Does not authorize performance-based adoption."})]},is.id)})}):jsxRuntimeExports.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:"No frozen performance studies for this target."})}function usePromotions(es){return useQuery({queryKey:["eval-targets",es,"promotions"],queryFn:()=>apiGet(`/api/eval-targets/${es}/promotions?limit=50`),enabled:!!es})}function useEvalJobs(es){return useQuery({queryKey:["eval-jobs",es],queryFn:()=>apiGet(`/api/eval-targets/${es}/jobs`),enabled:!!es})}function useCreateEvalJob(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/eval-jobs",$),onSuccess:$=>{es.invalidateQueries({queryKey:["eval-jobs",$.evalTargetId]})}})}function useCancelEvalJob(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/eval-jobs/${$}/cancel`,{}),onSuccess:$=>{es.invalidateQueries({queryKey:["eval-jobs",$.evalTargetId]})}})}function useRealtimeEvalJobs(es,$){const ts=useQueryClient(),[is,cs]=reactExports.useState(null);return reactExports.useEffect(()=>{if(!es)return;const Qr=`user_id=eq.${es}`,ja=supabase.channel(`eval-jobs-${$??"all"}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"eval_jobs",filter:Qr},Na=>{const Aa=Na.new;$&&Aa.evalTargetId!==$||(cs(Aa),ts.invalidateQueries({queryKey:["eval-jobs",Aa.evalTargetId]}))}).on("postgres_changes",{event:"UPDATE",schema:"public",table:"eval_jobs",filter:Qr},Na=>{const Aa=Na.new;$&&Aa.evalTargetId!==$||(Aa.status==="completed"||Aa.status==="failed"||Aa.status==="cancelled"?(cs(null),ts.invalidateQueries({queryKey:["eval-runs",Aa.evalTargetId]}),ts.invalidateQueries({queryKey:["eval-jobs",Aa.evalTargetId]})):cs(Aa))}).subscribe();return()=>{supabase.removeChannel(ja)}},[es,$,ts]),is}function useEvalConversation(es){return useQuery({queryKey:["eval-conversation",es],queryFn:()=>apiGet(`/api/eval-targets/${es}/conversations`),enabled:!!es})}function useCreateConversation(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/eval-targets/${$}/conversations`,{}),onSuccess:$=>{es.invalidateQueries({queryKey:["eval-conversation",$.evalTargetId]})}})}function useSendMessage(){const es=useQueryClient();return useMutation({mutationFn:({conversationId:$,content:ts})=>apiPost(`/api/eval-conversations/${$}/messages`,{content:ts}),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["eval-conversation-messages",ts.conversationId]})}})}function useConversationMessages(es,$=2e3){return useQuery({queryKey:["eval-conversation-messages",es],queryFn:()=>apiGet(`/api/eval-conversations/${es}/messages`),enabled:!!es,refetchInterval:$})}function useApplyProposal(){const es=useQueryClient(),$=useNavigate();return useMutation({mutationFn:({conversationId:ts,messageId:is})=>apiPost(`/api/eval-conversations/${ts}/apply-proposal`,{messageId:is}),onSuccess:ts=>{es.invalidateQueries({queryKey:["eval-targets"]}),es.invalidateQueries({queryKey:["eval-conversation"]}),es.invalidateQueries({queryKey:["eval-conversation-messages"]}),$(`/eval-targets/${ts.newTarget.id}`)}})}function ChatPanel({targetId:es}){const{data:$}=useEvalConversation(es),ts=useCreateConversation(),is=useSendMessage(),cs=useApplyProposal(),Qr=$==null?void 0:$.id,{data:ja}=useConversationMessages(Qr,2e3),[Na,Aa]=reactExports.useState(""),[Oa,Ia]=reactExports.useState(!1),[La,Ba]=reactExports.useState(!1),Ma=reactExports.useRef(null);reactExports.useEffect(()=>{var Va;(Va=Ma.current)==null||Va.scrollIntoView({behavior:"smooth"})},[ja==null?void 0:ja.length]);const qa=reactExports.useCallback(async Va=>{if(!(!Va.trim()||Oa)){Ia(!0);try{let Ja=Qr;Ja||(Ja=(await ts.mutateAsync(es)).id);const Ya=await is.mutateAsync({conversationId:Ja,content:Va.trim()});Ba(Ya.noLiveWorker),Aa("")}finally{Ia(!1)}}},[Qr,ts,is,es,Oa]),Fa=async()=>{await qa(Na)},Ha=Va=>{Va.key==="Enter"&&!Va.shiftKey&&(Va.preventDefault(),Fa())},Ka=Va=>{Qr&&cs.mutate({conversationId:Qr,messageId:Va})},Ga=ja??($==null?void 0:$.messages)??[];return jsxRuntimeExports.jsxs("div",{className:"flex flex-col h-[600px]",children:[jsxRuntimeExports.jsxs("div",{className:"flex-1 overflow-y-auto space-y-3 p-4",children:[Ga.length===0&&jsxRuntimeExports.jsxs("div",{className:"text-center text-muted-foreground text-sm py-12 space-y-3",children:[jsxRuntimeExports.jsx("p",{children:"Start by running evals or generating test cases."}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 justify-center",children:[jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",disabled:Oa,onClick:()=>qa("Generate test cases for this instruction"),children:[jsxRuntimeExports.jsx(Sparkles,{className:"h-3 w-3 mr-1"}),"Generate Test Cases"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",disabled:Oa,onClick:()=>qa("Run the evals"),children:[jsxRuntimeExports.jsx(Play,{className:"h-3 w-3 mr-1"}),"Run Evals"]})]})]}),Ga.map((Va,Ja)=>Va.type==="status"&&Ga.slice(Ja+1).some(Ya=>Ya.type==="results"||Ya.type==="proposal"||Ya.type==="generated"||Ya.role==="user")?null:jsxRuntimeExports.jsx(MessageBubble,{message:Va,onApply:Ka,applyingProposal:cs.isPending,isLastStatus:Va.type==="status"},Va.id)),jsxRuntimeExports.jsx("div",{ref:Ma})]}),La&&jsxRuntimeExports.jsxs("div",{className:"border-t border-amber-500/30 bg-amber-500/5 px-3 py-2 text-xs text-amber-500",children:["No CLI worker is listening — your message is queued but nothing will answer it. Start one with ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric evals agent"}),"."]}),jsxRuntimeExports.jsxs("div",{className:"border-t border-border p-3 flex gap-2",children:[jsxRuntimeExports.jsx("textarea",{value:Na,onChange:Va=>Aa(Va.target.value),onKeyDown:Ha,placeholder:"Type a message... (e.g. 'run evals', 'this output is missing X')",className:"flex-1 bg-muted rounded-lg px-3 py-2 text-sm resize-none min-h-[40px] max-h-[120px] focus:outline-none focus:ring-1 focus:ring-primary",rows:1,disabled:Oa}),jsxRuntimeExports.jsx(Button,{size:"icon",onClick:Fa,disabled:Oa||!Na.trim(),className:"shrink-0",children:Oa?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin"}):jsxRuntimeExports.jsx(Send,{className:"h-4 w-4"})})]})]})}function MessageBubble({message:es,onApply:$,applyingProposal:ts,isLastStatus:is}){if(es.role==="user")return jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsx("div",{className:"bg-primary text-primary-foreground rounded-lg px-3 py-2 max-w-[80%] text-sm",children:es.content})});switch(es.type){case"status":return jsxRuntimeExports.jsx(StatusMessage,{content:es.content,isActive:!!is});case"results":return jsxRuntimeExports.jsx(ResultsMessage,{content:es.content,data:es.data});case"proposal":return jsxRuntimeExports.jsx(ProposalMessage,{content:es.content,data:es.data,messageId:es.id,onApply:$,applying:ts});case"applied":return jsxRuntimeExports.jsx(AppliedMessage,{content:es.content});case"generated":return jsxRuntimeExports.jsx(GeneratedMessage,{content:es.content,data:es.data});default:return jsxRuntimeExports.jsx("div",{className:"flex justify-start",children:jsxRuntimeExports.jsx("div",{className:"bg-card border border-border rounded-lg px-3 py-2 max-w-[80%] text-sm",children:es.content})})}}function StatusMessage({content:es,isActive:$}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground px-3 py-1",children:[$?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}):jsxRuntimeExports.jsx(CircleCheck,{className:"h-3 w-3 text-muted-foreground/50"}),es]})}function ResultsMessage({content:es,data:$}){const[ts,is]=reactExports.useState(null);if(!$)return jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:es});const{summary:cs,results:Qr}=$,ja=cs.passRate>=.8?"text-teal-500":cs.passRate>=.5?"text-yellow-500":"text-red-500";return jsxRuntimeExports.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 space-y-3 max-w-[90%]",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsxs("span",{className:`font-mono text-lg font-bold ${ja}`,children:[cs.passed,"/",cs.total]}),jsxRuntimeExports.jsxs("span",{className:"text-sm text-muted-foreground",children:["evals passed (",Math.round(cs.passRate*100),"%)"]})]}),jsxRuntimeExports.jsx("div",{className:"space-y-1",children:Qr.map((Na,Aa)=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>is(ts===Aa?null:Aa),className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-left hover:bg-secondary/30",children:[ts===Aa?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3"}),Na.passed?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 text-teal-500"}):jsxRuntimeExports.jsx(CircleX,{className:"h-4 w-4 text-red-500"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:Na.evalName})]}),ts===Aa&&jsxRuntimeExports.jsxs("div",{className:"px-3 pb-3 space-y-2 border-t border-border pt-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Output:"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-2 rounded mt-1 overflow-x-auto max-h-40 whitespace-pre-wrap",children:Na.output})]}),Na.evidence&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Evidence:"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-2 rounded mt-1 overflow-x-auto max-h-32 whitespace-pre-wrap",children:Na.evidence})]})]})]},Aa))})]})}function ProposalMessage({content:es,data:$,messageId:ts,onApply:is,applying:cs}){const[Qr,ja]=reactExports.useState(!1);return jsxRuntimeExports.jsxs("div",{className:"bg-card border border-primary/30 rounded-lg p-4 space-y-3 max-w-[90%]",children:[jsxRuntimeExports.jsx("p",{className:"text-sm",children:es}),($==null?void 0:$.suggestions)&&$.suggestions.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("button",{onClick:()=>ja(!Qr),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground",children:[Qr?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3"}),$.suggestions.length," suggested change",$.suggestions.length>1?"s":""]}),Qr&&jsxRuntimeExports.jsx("div",{className:"space-y-2",children:$.suggestions.map((Na,Aa)=>jsxRuntimeExports.jsxs("div",{className:"bg-muted rounded p-3 text-xs space-y-1",children:[jsxRuntimeExports.jsx("div",{className:"font-mono font-medium text-primary",children:Na.section}),Na.current&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-red-400 font-medium",children:"- "}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:Na.current})]}),Na.proposed&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-teal-400 font-medium",children:"+ "}),jsxRuntimeExports.jsx("span",{children:Na.proposed})]}),jsxRuntimeExports.jsx("div",{className:"text-muted-foreground italic",children:Na.reasoning})]},Aa))})]}),jsxRuntimeExports.jsx("div",{className:"flex gap-2",children:jsxRuntimeExports.jsxs(Button,{size:"sm",onClick:()=>is(ts),disabled:cs,children:[cs?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin mr-1"}):null,"Apply Changes"]})})]})}function AppliedMessage({content:es}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-teal-500 px-3 py-1",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4"}),es]})}function GeneratedMessage({content:es,data:$}){const[ts,is]=reactExports.useState(null);return jsxRuntimeExports.jsxs("div",{className:"bg-card border border-border rounded-lg p-4 space-y-3 max-w-[90%]",children:[jsxRuntimeExports.jsx("p",{className:"text-sm",children:es}),($==null?void 0:$.cases)&&jsxRuntimeExports.jsx("div",{className:"space-y-1",children:$.cases.map((cs,Qr)=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>is(ts===Qr?null:Qr),className:"w-full flex items-center gap-2 px-3 py-2 text-sm text-left hover:bg-secondary/30",children:[ts===Qr?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:cs.name})]}),ts===Qr&&jsxRuntimeExports.jsxs("div",{className:"px-3 pb-3 space-y-2 border-t border-border pt-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Prompt:"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-2 rounded mt-1 whitespace-pre-wrap",children:cs.prompt})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Expectations:"}),jsxRuntimeExports.jsx("div",{className:"mt-1 space-y-1",children:cs.expectations.map((ja,Na)=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs font-normal",children:ja},Na))})]})]})]},Qr))})]})}const MIN_QUOTE_LEN=12,MIN_CODE_LEN=4,SHORT_CANDIDATE_LEN=20;function extractEvidenceQuotes(es){const $=[],ts=is=>{const cs=is==null?void 0:is.trim();cs&&$.push(cs)};for(const is of[/"([^"]+)"/g,/“([^”]+)”/g,/'([^']+)'/g,/‘([^’]+)’/g])for(const cs of es.matchAll(is))cs[1].length>=MIN_QUOTE_LEN&&ts(cs[1]);for(const is of es.matchAll(/`([^`]+)`/g))is[1].length>=MIN_CODE_LEN&&ts(is[1]);return es.trim().length>=SHORT_CANDIDATE_LEN&&ts(es),[...new Set($)]}function findEvidenceRanges(es,$){if(!es||!$)return[];const ts=[];for(const cs of extractEvidenceQuotes($))for(const[Qr,ja]of[[es,cs],[es.toLowerCase(),cs.toLowerCase()]]){let Na=0,Aa=!1;for(;;){const Oa=Qr.indexOf(ja,Na);if(Oa===-1||(ts.push([Oa,Oa+ja.length]),Aa=!0,cs.length<SHORT_CANDIDATE_LEN))break;Na=Oa+ja.length}if(Aa)break}ts.sort((cs,Qr)=>cs[0]-Qr[0]||cs[1]-Qr[1]);const is=[];for(const[cs,Qr]of ts){const ja=is[is.length-1];ja&&cs<=ja[1]?ja[1]=Math.max(ja[1],Qr):is.push([cs,Qr])}return is}function segmentByRanges(es,$){if($.length===0)return[{text:es,highlighted:!1}];const ts=[];let is=0;for(const[cs,Qr]of $)cs>is&&ts.push({text:es.slice(is,cs),highlighted:!1}),ts.push({text:es.slice(cs,Qr),highlighted:!0}),is=Qr;return is<es.length&&ts.push({text:es.slice(is),highlighted:!1}),ts}function SecondOpinions({flags:es,actions:$}){const ts=reactExports.useMemo(()=>{const Ka=new Map;for(const Ga of es){const Va=`${Ga.evalRunId}:${Ga.expectationIndex}`;Ka.set(Va,[...Ka.get(Va)??[],Ga])}return[...Ka.entries()].map(([Ga,Va])=>({key:Ga,rows:Va,first:Va[0],humanVerdict:Va[0].humanPassed===Va[0].judgePassed?"approve":"reject",consensus:new Set(Va.map(Ja=>Ja.reviewerEngine)).size>1})).sort((Ga,Va)=>Number(Va.consensus)-Number(Ga.consensus))},[es]),[is,cs]=reactExports.useState(new Set),[Qr,ja]=reactExports.useState(null),[Na,Aa]=reactExports.useState(!1),Oa=ts.length>0&&ts.every(Ka=>is.has(Ka.key)),Ia=()=>cs(Oa?new Set:new Set(ts.map(Ka=>Ka.key))),La=Ka=>cs(Ga=>{const Va=new Set(Ga);return Va.has(Ka)?Va.delete(Ka):Va.add(Ka),Va}),Ba=async(Ka,Ga,Va)=>{Aa(!0);let Ja=0,Ya=0;for(const el of Va)try{await Ga(el),Ja+=1}catch{Ya+=1}Aa(!1),cs(new Set),Ya===0?ue$1.success(`${Ka} ${Ja} label${Ja===1?"":"s"}`):ue$1.error(`${Ka} ${Ja}, ${Ya} failed — the rest are still flagged`)},Ma=Ka=>$.resolve({id:Ka.first.id,resolution:"kept"}),qa=async Ka=>{await $.annotate({runId:Ka.first.evalRunId,expectationIndex:Ka.first.expectationIndex,verdict:Ka.humanVerdict==="approve"?"reject":"approve"}),await $.resolve({id:Ka.first.id,resolution:"relabeled"})},Fa=async Ka=>{await $.removeAnnotation({runId:Ka.first.evalRunId,expectationIndex:Ka.first.expectationIndex}),await $.resolve({id:Ka.first.id,resolution:"relabeled"})};if(ts.length===0)return null;const Ha=ts.filter(Ka=>is.has(Ka.key));return jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3 border-b border-border px-3 py-2",children:[jsxRuntimeExports.jsxs("label",{className:"flex cursor-pointer items-center gap-2",children:[jsxRuntimeExports.jsx("input",{type:"checkbox",checked:Oa,onChange:Ia,className:"h-3.5 w-3.5 accent-teal-500","aria-label":"Select all flags"}),jsxRuntimeExports.jsxs("span",{className:"text-sm font-medium",children:["Second opinions",jsxRuntimeExports.jsxs("span",{className:"ml-1.5 text-muted-foreground font-normal",children:[ts.length," label",ts.length===1?"":"s"," flagged"]})]})]}),Ha.length>0?jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"h-6 px-2 text-xs",disabled:Na,onClick:()=>Ba("Kept",Ma,Ha),children:["Keep ",Ha.length," label",Ha.length===1?"":"s"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"h-6 px-2 text-xs",disabled:Na,onClick:()=>Ba("Flipped",qa,Ha),children:["Flip ",Ha.length]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",disabled:Na,onClick:()=>Ba("Removed",Fa,Ha),children:["Remove ",Ha.length," & requeue"]})]}):jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"A second model disagrees with these labels — keep yours, or flip it if the reviewer caught a judge error."})]}),jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:ts.map(Ka=>{const Ga=Ka.first,Va=Qr===Ka.key;return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:cn$1("flex items-center gap-2 px-3 py-1.5 text-sm",is.has(Ka.key)&&"bg-primary/[0.04]"),children:[jsxRuntimeExports.jsx("input",{type:"checkbox",checked:is.has(Ka.key),onChange:()=>La(Ka.key),className:"h-3.5 w-3.5 shrink-0 accent-teal-500","aria-label":`Select ${Ga.expectationText}`}),jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>ja(Va?null:Ka.key),className:"flex min-w-0 flex-1 items-center gap-2 text-left",children:[Va?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[13px]",children:Ga.expectationText}),jsxRuntimeExports.jsxs("span",{className:"hidden shrink-0 font-mono text-[11px] text-muted-foreground sm:inline",children:[Ga.evalName??"case"," #",Ga.runNumber]}),Ka.consensus&&jsxRuntimeExports.jsx("span",{className:"shrink-0 rounded bg-amber-500/10 px-1.5 py-0.5 text-[10px] font-medium text-amber-500",children:"2 vendors"}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px]",children:["You: ",Ka.humanVerdict==="approve"?"right":"wrong"]}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 rounded bg-red-500/10 px-1.5 py-0.5 text-[10px] text-red-500",children:[Ka.rows.length," reviewer",Ka.rows.length===1?"":"s"," disagree"]})]}),jsxRuntimeExports.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs",disabled:Na,onClick:()=>Ba("Kept",Ma,[Ka]),children:"Keep"}),jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-red-500 hover:text-red-400",disabled:Na,onClick:()=>Ba("Flipped",qa,[Ka]),children:"Flip"})]})]}),Va&&jsxRuntimeExports.jsxs("div",{className:"space-y-2 border-t border-border/50 bg-muted/20 px-9 py-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[jsxRuntimeExports.jsxs("span",{className:"rounded bg-muted px-1.5 py-0.5",children:["Judge: ",Ga.judgePassed?"PASS":"FAIL"]}),jsxRuntimeExports.jsxs("span",{className:"rounded bg-muted px-1.5 py-0.5",children:["You: judge was ",Ka.humanVerdict==="approve"?"right":"wrong"]}),Ka.rows.map(Ja=>jsxRuntimeExports.jsxs("span",{className:"rounded bg-red-500/10 px-1.5 py-0.5 text-red-500",children:[Ja.reviewerModel,": ",Ja.reviewerPassed?"PASS":"FAIL"]},Ja.id)),jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground",children:Ga.configuration})]}),Ga.outputExcerpt&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"mb-1 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Agent output (excerpt)"}),jsxRuntimeExports.jsx("pre",{className:"max-h-48 overflow-y-auto whitespace-pre-wrap rounded-md bg-muted p-2 text-xs",children:Ga.outputExcerpt})]})]})]},Ka.key)})})]})}function AnchorProgressCard({check:es,judge:$,pooling:ts}){const is=Math.min(100,Math.round(es.nAnchors/es.pilotTarget*100));return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("h3",{className:"font-mono font-medium flex items-center gap-1.5",children:["Anchor set",jsxRuntimeExports.jsx(InfoTip,{term:"anchorSet"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[($==null?void 0:$.currentModel)&&jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs text-muted-foreground flex items-center gap-1",children:[jsxRuntimeExports.jsx(InfoTip,{term:"judge",children:"judge"}),": ",$.currentModel]}),es.adequate?jsxRuntimeExports.jsx(Badge,{className:"font-mono text-xs",children:"adequate"}):jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",children:"not yet adequate"}),jsxRuntimeExports.jsx(InfoTip,{term:"adequate"})]})]}),$!=null&&$.staleAnchors>0&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-500",children:[$.staleAnchors," label",$.staleAnchors===1?"":"s"," from an older judge model no longer count toward this judge's calibration — the queue below only serves runs graded by the current judge."]}),jsxRuntimeExports.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:jsxRuntimeExports.jsx("div",{className:"bg-primary rounded-full h-2 transition-all duration-300",style:{width:`${is}%`}})}),ts&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:ts.engaged?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["rectifier: ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"pooled"})," from"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:ts.poolTargets})," same-judge targets /"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:ts.poolAnchors})," anchors (λ=",jsxRuntimeExports.jsx("span",{className:"font-mono",children:ts.withLambda.toFixed(2)}),Math.abs(ts.withLambda-ts.withoutLambda)>.01&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" / ",ts.withoutLambda.toFixed(2)]}),")"]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["rectifier: ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"target-specific"}),ts.withReason?` — ${ts.withReason}`:""]})}),(ts==null?void 0:ts.engaged)&&ts.assumedExchangeability&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-500",children:["Pool spans ",ts.poolTargets," of the 3 targets needed to MEASURE between-target variance — until then the judge is assumed to behave the same across targets rather than shown to. No calibrated verdict rests on that assumption."]}),jsxRuntimeExports.jsxs("p",{className:"text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[es.nAnchors," / ",es.pilotTarget]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(InfoTip,{term:"humanLabeledRuns",children:"human-labeled runs"})," (with"," ",es.nAnchorsWith," · without ",es.nAnchorsWithout,")",es.mde!=null&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" · ",jsxRuntimeExports.jsx(InfoTip,{term:"mde",children:"MDE"})," ±",(es.mde*100).toFixed(0),"pp vs ±",(es.targetEffect*100).toFixed(0),"pp target"]})]})]}),es.adequate?jsxRuntimeExports.jsx("p",{className:"text-xs text-teal-500",children:"Pilot target, cohort minimums, and target detectable effect all met — corrected estimates are publishable at this precision."}):jsxRuntimeExports.jsx("ul",{className:"text-xs text-muted-foreground space-y-0.5",children:es.reasons.map((cs,Qr)=>jsxRuntimeExports.jsxs("li",{children:["— ",cs]},Qr))})]})}function CaseDiscriminationCard({data:es}){const $=cs=>`${(cs*100).toFixed(0)}%`,ts=es.nonDiscriminating+es.unpaired,is=es.total>0&&ts/es.total>=.5;return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("h3",{className:"font-mono font-medium flex items-center gap-1.5",children:["Case discrimination",jsxRuntimeExports.jsx(InfoTip,{term:"discrimination"})]}),is?jsxRuntimeExports.jsxs(Badge,{variant:"destructive",className:"font-mono text-xs",children:[ts,"/",es.total," measure nothing"]}):jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"font-mono text-xs",children:[es.discriminating,"/",es.total," discriminate"]})]}),is&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-500",children:"Most cases don't separate with vs without, so the effect can't be resolved by adding runs — the variance is structural. Cull or replace the flagged cases before labeling."}),jsxRuntimeExports.jsxs("ul",{className:"text-xs space-y-1",children:[es.cases.map(cs=>jsxRuntimeExports.jsxs("li",{className:"flex items-baseline justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:cs.discriminating?"text-foreground":"text-muted-foreground line-through",children:cs.name}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-muted-foreground whitespace-nowrap",children:[$(cs.withPassRate)," vs ",$(cs.withoutPassRate),cs.discriminating?jsxRuntimeExports.jsxs("span",{className:"text-teal-500",children:[" · ",jsxRuntimeExports.jsxs(InfoTip,{term:"separation",children:["Δ",$(cs.separation)]})]}):jsxRuntimeExports.jsxs("span",{className:"text-amber-500",children:[" · ",jsxRuntimeExports.jsx(InfoTip,{term:"flat",children:"flat"})]})]})]},cs.name)),es.unpaired>0&&jsxRuntimeExports.jsxs("li",{className:"text-muted-foreground",children:["+ ",es.unpaired," case",es.unpaired===1?"":"s"," with no baseline cohort (can't be diagnosed — every baseline run missing or failed)"]})]})]})}function JudgeCalibrationCard({data:es}){const{anchors:$,calibration:ts,judge:is}=es,cs=Qr=>`${(Qr*100).toFixed(0)}%`;return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono font-medium",children:"Judge calibration"}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:[(is==null?void 0:is.currentModel)&&`judge ${is.currentModel} · `,$.llmAnchors," human label",$.llmAnchors===1?"":"s",$.flagged>0&&` · ${$.flagged} flagged`]})]}),is!=null&&(is.staleAnchors>0||is.staleRuns>0)&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-500",children:["Judge model changed — ",is.staleRuns," graded run",is.staleRuns===1?"":"s"," and ",is.staleAnchors," label",is.staleAnchors===1?"":"s"," from older judges are excluded here. Re-run evals and re-label in the Review tab to rebuild the anchor set under the current judge."]}),$.llmAnchors===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No human labels yet. Work through the Review tab (approve/reject each judge grade) — labels measure the judge's bias and correct the pass-rate estimates below (PPI)."}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[$.agreementRate!=null&&jsxRuntimeExports.jsxs("p",{className:"text-sm",children:["Judge/human agreement:"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:cs($.agreementRate)}),$.agreementCi&&jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs text-muted-foreground",children:[" ","[",cs($.agreementCi.lower),"–",cs($.agreementCi.upper),"]"]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["on ",$.llmAnchors," reviewed assertion",$.llmAnchors===1?"":"s"]})]}),ts&&(ts.sufficient?jsxRuntimeExports.jsxs("div",{className:"text-sm space-y-1",children:[jsxRuntimeExports.jsxs("p",{children:["Corrected pass rates:"," ",jsxRuntimeExports.jsxs("span",{className:"font-mono",children:["with ",cs(ts.with.estimate)," · without"," ",cs(ts.without.estimate)]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["(judge-only said ",cs(ts.with.naive)," ·"," ",cs(ts.without.naive),")"]})]}),jsxRuntimeExports.jsxs("p",{children:["Corrected delta:"," ",jsxRuntimeExports.jsxs("span",{className:`font-mono ${ts.significant?ts.delta>=0?"text-teal-500":"text-red-500":""}`,children:[ts.delta>=0?"+":"",cs(ts.delta)]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["95% CI ",cs(ts.ci.lower)," to ",cs(ts.ci.upper),ts.significant?"":" — not significant"," (unpaired, judge-bias-corrected)"]})]})]}):jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:[ts.insufficientReason??`need >= ${$.minAnchors} fully-reviewed runs per cohort for a corrected estimate`,". Fully-reviewed runs so far: ",$.labeledRuns.with," with ·"," ",$.labeledRuns.without," without."]})),es.powerCheck&&(es.powerCheck.adequate?jsxRuntimeExports.jsxs("p",{className:"text-xs text-teal-500",children:["Anchor set adequate — pilot target, cohort minimums, and ±",(es.powerCheck.targetEffect*100).toFixed(0),"pp detectable-effect target all met."]}):jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-500",children:["Anchor set not yet adequate (",es.powerCheck.nAnchors,"/",es.powerCheck.pilotTarget," pilot labels",es.powerCheck.mde!=null&&`, MDE ±${(es.powerCheck.mde*100).toFixed(0)}pp vs ±${(es.powerCheck.targetEffect*100).toFixed(0)}pp target`,") — treat corrected numbers as provisional; grow it in the Review tab."]}))]})]})}function CopyButton({text:es,what:$}){const{copy:ts}=useCopyToClipboard();return jsxRuntimeExports.jsx("button",{type:"button",onClick:async()=>await ts(es)?ue$1.success(`Copied ${$}`):ue$1.error("Copy failed — clipboard unavailable"),title:`Copy ${$}`,className:"rounded p-1 text-muted-foreground/60 transition-colors hover:text-foreground",children:jsxRuntimeExports.jsx(Copy,{className:"h-3.5 w-3.5"})})}function Kbd({children:es,className:$}){return jsxRuntimeExports.jsx("kbd",{className:cn$1("inline-flex items-center rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[10px] font-medium text-muted-foreground",$),children:es})}function ReviewerAgreementCard({reviewers:es}){const $=is=>`${(is*100).toFixed(0)}%`,ts=is=>is==null?"—":is.toFixed(2);return jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border",children:[jsxRuntimeExports.jsx("div",{className:"border-b border-border px-3 py-2",children:jsxRuntimeExports.jsxs("span",{className:"text-sm font-medium",children:["Second-opinion agreement",jsxRuntimeExports.jsx("span",{className:"ml-1.5 font-normal text-muted-foreground",children:"vs your current labels"})]})}),jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:es.filter(is=>is.pairs>0).map(is=>{const cs=is.kappa!=null&&is.snapshotKappa!=null&&Math.abs(is.kappa-is.snapshotKappa)>=.005;return jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 px-3 py-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-[13px] text-foreground",children:is.models.join(", ")}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[is.pairs," assertion",is.pairs===1?"":"s",is.orphaned>0&&` (+${is.orphaned} requeued)`]}),is.agreementRate!=null&&jsxRuntimeExports.jsxs("span",{children:["matches you ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:$(is.agreementRate)})]}),jsxRuntimeExports.jsxs("span",{children:["κ ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:ts(is.kappa)}),cs&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" ","(was ",ts(is.snapshotKappa)," before your corrections)"]})]}),is.judgeAgreementRate!=null&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:["judge matches you ",$(is.judgeAgreementRate)]}),is.suggestedAnchorWeight!=null&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:["anchor weight ",is.suggestedAnchorWeight.toFixed(2)]})]},is.engine)})})]})}function ReviewTab({targetId:es,queue:$,isFetching:ts,refetchQueue:is,annotations:cs,powerCheck:Qr,judge:ja,caseDiscrimination:Na,pooling:Aa,reviewers:Oa,targetContent:Ia,targetType:La}){var Gl,cu;const[Ba,Ma]=reactExports.useState(0),[qa,Fa]=reactExports.useState(!1),Ha=reactExports.useRef(!1);reactExports.useEffect(()=>{Aa!=null&&Aa.engaged&&!Ha.current&&(Ha.current=!0,Fa(!0))},[Aa==null?void 0:Aa.engaged]);const[Ka,Ga]=reactExports.useState(!1),[Va,Ja]=reactExports.useState({}),Ya=reactExports.useRef([]),el=useJudgeDisagreements(es),tl=useResolveJudgeReview(es),[rl,cl]=reactExports.useState({}),dl=useAnnotateGrade(es),fl=useRemoveGradeAnnotation(es),nl=new Map(cs.map(Al=>[`${Al.evalRunId}:${Al.expectationIndex}`,Al])),ol=(Al,Ml)=>{var xu,fu;const Ql=`${Al.id}:${Ml}`;if(Ql in rl)return rl[Ql];const eu=nl.get(Ql);return eu?eu.verdict:((fu=(xu=Al.expectations[Ml])==null?void 0:xu.annotation)==null?void 0:fu.verdict)??null},hl=(Al,Ml,Ql,eu)=>{const xu=`${Al}:${Ml}`;eu===Ql?(cl(fu=>{const Ou={...fu};return delete Ou[xu],Ou}),fl.mutate({runId:Al,expectationIndex:Ml},{onError:()=>ue$1.error("Couldn't remove the label — it may still be recorded. Retry in a moment.")})):(cl(fu=>({...fu,[xu]:Ql})),Ya.current.push({runId:Al,expectationIndex:Ml}),dl.mutate({runId:Al,expectationIndex:Ml,verdict:Ql},{onError:()=>{cl(fu=>{const Ou={...fu};return delete Ou[xu],Ou}),ue$1.error("Label didn't save — check your connection and mark it again.")}}))},Tl=$==null?void 0:$.runs[Ba],ul=(Tl==null?void 0:Tl.expectations.filter(Al=>Al.method==="llm"&&!Al.errored))??[],pl=Tl?ul.filter(Al=>ol(Tl,Al.index)!=null).length:0,jl=Tl!=null&&ul.length>0&&pl===ul.length,Nl=Tl?((Gl=ul.find(Al=>ol(Tl,Al.index)==null))==null?void 0:Gl.index)??null:null,[zl,Zl]=reactExports.useState(null);reactExports.useEffect(()=>{Zl(null),Ga(!1)},[Tl==null?void 0:Tl.id]);const Dl=zl??Nl,Il=reactExports.useRef(null),Fl=reactExports.useRef(null),ql=reactExports.useMemo(()=>{const Al=Tl==null?void 0:Tl.expectations.find(Ql=>Ql.method==="llm"&&Ql.index===Dl);if(!Al||!(Tl!=null&&Tl.output))return{segments:null,count:0};const Ml=findEvidenceRanges(Tl.output,Al.evidence);return Ml.length===0?{segments:null,count:0}:{segments:segmentByRanges(Tl.output,Ml),count:Ml.length}},[Tl,Dl]);reactExports.useEffect(()=>{const Al=Il.current,Ml=Fl.current;if(!Al||!Ml)return;const Ql=Ml.getBoundingClientRect().top-Al.getBoundingClientRect().top;Al.scrollTo({top:Al.scrollTop+Ql-48,behavior:"smooth"})},[Dl,Tl==null?void 0:Tl.id,ql.count]),reactExports.useEffect(()=>{const Al=Ml=>{if(Ml.metaKey||Ml.ctrlKey||Ml.altKey)return;const Ql=Ml.target;if(Ql&&(Ql.tagName==="INPUT"||Ql.tagName==="TEXTAREA"||Ql.isContentEditable)||!Tl)return;const eu=Ml.key.toLowerCase();if((eu==="1"||eu==="a")&&Nl!=null)Ml.preventDefault(),hl(Tl.id,Nl,"approve",null);else if((eu==="2"||eu==="d")&&Nl!=null)Ml.preventDefault(),hl(Tl.id,Nl,"reject",null);else if((Ml.key==="Enter"||eu==="n")&&jl)Ml.preventDefault(),Ma(xu=>xu+1);else if(eu==="s")Ml.preventDefault(),Ma(xu=>xu+1);else if(eu==="u"){const xu=Ya.current.pop();if(xu){Ml.preventDefault();const fu=`${xu.runId}:${xu.expectationIndex}`;cl(Ou=>{const yu={...Ou};return delete yu[fu],yu}),fl.mutate(xu,{onError:()=>ue$1.error("Couldn't undo — the label may still be recorded.")})}}else Ml.key==="ArrowRight"&&$&&Ba<$.runs.length-1?(Ml.preventDefault(),Ma(xu=>xu+1)):Ml.key==="ArrowLeft"&&Ba>0&&(Ml.preventDefault(),Ma(xu=>xu-1))};return window.addEventListener("keydown",Al),()=>window.removeEventListener("keydown",Al)},[Tl,Nl,jl,Ba,$]);const nu=Al=>{const Ml=Al.expectations.filter(eu=>eu.method==="llm");if(Ml.length===0)return"done";const Ql=Ml.filter(eu=>ol(Al,eu.index)!=null).length;return Ql===Ml.length?"done":Ql>0?"partial":"todo"};return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[$&&$.remaining>0&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-primary/40 bg-primary/[0.06] px-4 py-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"Review the judge's grade — not the output."}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-[13px] text-muted-foreground",children:["For each assertion below, decide whether the AI judge got the pass/fail right — mark"," ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"Judge was right"})," if it did, or"," ",jsxRuntimeExports.jsx("span",{className:"text-foreground",children:"Judge was wrong"})," if it didn't. Each mark adds one"," ",jsxRuntimeExports.jsx(InfoTip,{term:"humanLabeledRuns",children:"human anchor"}),Qr&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" ","(",jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[Qr.nAnchors,"/",Qr.pilotTarget]}),")"]})," ","toward calibrating this judge — so a real verdict can be shown."]}),jsxRuntimeExports.jsxs("p",{className:"mt-2 flex flex-wrap items-center gap-x-1.5 gap-y-1 text-xs text-muted-foreground",children:["Keyboard: ",jsxRuntimeExports.jsx(Kbd,{children:"1"})," judge was right ",jsxRuntimeExports.jsx(Kbd,{children:"2"})," judge was wrong",jsxRuntimeExports.jsx(Kbd,{children:"U"})," undo last ",jsxRuntimeExports.jsx(Kbd,{children:"Enter"})," next run ",jsxRuntimeExports.jsx(Kbd,{children:"S"})," skip ",jsxRuntimeExports.jsx(Kbd,{children:"←"}),jsxRuntimeExports.jsx(Kbd,{children:"→"})," switch run"]})]}),cs.length>=10&&cs.every(Al=>Al.verdict==="approve")&&(((cu=el.data)==null?void 0:cu.length)??0)===0&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-amber-500/40 bg-amber-500/[0.06] px-4 py-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm font-medium text-amber-500",children:["All ",cs.length," labels agree with the judge"]}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-[13px] text-muted-foreground",children:["A label set with zero rejects can't detect judge bias — don't hunt for rejects, but if the judge looks wrong, say so. To surface likely judge errors worth a second look, run"," ",jsxRuntimeExports.jsxs("span",{className:"font-mono text-foreground",children:["rulemetric evals validate-judge ",es]})," ","— assertions where a second model disagrees with the judge are the best candidates."]})]}),el.data&&el.data.length>0&&jsxRuntimeExports.jsx(SecondOpinions,{flags:el.data,actions:{annotate:Al=>dl.mutateAsync(Al),removeAnnotation:Al=>fl.mutateAsync(Al),resolve:Al=>tl.mutateAsync(Al)}}),Oa&&Oa.some(Al=>Al.pairs>0)&&jsxRuntimeExports.jsx(ReviewerAgreementCard,{reviewers:Oa}),Qr?jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>Fa(Al=>!Al),className:"flex w-full items-center gap-3 rounded-lg px-4 py-2.5 text-left transition-colors hover:bg-muted/40",children:[qa?jsxRuntimeExports.jsx(ChevronDown,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-3 text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[Qr.nAnchors,"/",Qr.pilotTarget," labeled"]}),jsxRuntimeExports.jsxs("span",{className:"truncate text-xs text-muted-foreground",children:[$?`${$.remaining} to review`:"",Qr.mde!=null&&` · MDE ±${(Qr.mde*100).toFixed(0)}pp`,Na&&Na.total>0&&` · ${Na.discriminating}/${Na.total} cases discriminate`,Aa&&(Aa.engaged?jsxRuntimeExports.jsx("span",{className:"text-teal-500",children:` · pooled ✓ (${Aa.poolTargets} targets / ${Aa.poolAnchors} anchors)`}):" · rectifier: target-specific")]})]}),jsxRuntimeExports.jsx("div",{className:"mt-1.5 h-1.5 w-full rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-1.5 rounded-full bg-primary transition-all",style:{width:`${Math.min(100,Math.round(Qr.nAnchors/Qr.pilotTarget*100))}%`}})})]})]}),qa&&jsxRuntimeExports.jsxs("div",{className:"space-y-4 border-t border-border p-4",children:[jsxRuntimeExports.jsx(AnchorProgressCard,{check:Qr,judge:ja,pooling:Aa}),Na&&Na.total>0&&jsxRuntimeExports.jsx(CaseDiscriminationCard,{data:Na})]})]}):Na&&Na.total>0&&jsxRuntimeExports.jsx(CaseDiscriminationCard,{data:Na}),$?$.remaining===0?jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:"All caught up — every LLM-judged assertion of this target is reviewed."}):Tl?jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 p-3 border-b border-border",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",title:Tl.configuration==="with_target"?"This run executed WITH the content under test in the agent's context":"Baseline arm — this run executed WITHOUT the content under test",children:Tl.configuration==="with_target"?"with instruction":"baseline · no instruction"}),jsxRuntimeExports.jsxs("span",{className:"min-w-0 break-words font-mono text-sm",children:[Tl.evalName," · run #",Tl.runNumber]})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[jsxRuntimeExports.jsx("span",{className:"mr-1 text-xs text-muted-foreground",children:"batch"}),$.runs.map((Al,Ml)=>{const Ql=nu(Al);return jsxRuntimeExports.jsx("button",{onClick:()=>Ma(Ml),title:`${Al.evalName} · ${Al.configuration}${Ql==="done"?" · reviewed":Ql==="partial"?" · partially reviewed":""}`,className:cn$1("h-6 min-w-6 rounded border px-1 font-mono text-[11px] transition-colors",Ql==="done"?"bg-teal-500/10 text-teal-500":Ql==="partial"?"bg-amber-500/10 text-amber-500":"text-muted-foreground hover:text-foreground",Ml===Ba?"border-primary/70":"border-border"),children:Ql==="done"?"✓":Ml+1},Al.id)})]})]}),jsxRuntimeExports.jsxs("div",{className:"p-4 grid gap-4 xl:grid-cols-2",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-3 xl:sticky xl:top-4 xl:self-start",children:[jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border","data-testid":"review-input-panel",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/60 bg-muted/40 px-3 py-1.5",children:[jsxRuntimeExports.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Input — what the agent was asked"}),jsxRuntimeExports.jsx(CopyButton,{text:Tl.prompt,what:"prompt"})]}),jsxRuntimeExports.jsx("p",{className:"max-h-44 overflow-y-auto whitespace-pre-wrap p-3 text-sm",children:Tl.prompt})]}),Tl.configuration==="with_target"&&Ia&&jsxRuntimeExports.jsxs("details",{className:"rounded-md border border-border","data-testid":"review-target-panel",children:[jsxRuntimeExports.jsxs("summary",{className:"cursor-pointer rounded-md bg-muted/40 px-3 py-1.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground transition-colors hover:text-foreground",children:["Also in context — the ",La," under test"]}),jsxRuntimeExports.jsx("pre",{className:"max-h-60 overflow-y-auto whitespace-pre-wrap border-t border-border/60 p-3 text-xs",children:Ia})]}),!Tl.output&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-dashed border-border px-3 py-2.5 text-xs text-muted-foreground",children:"No output was captured for this run — the judge graded an empty transcript. Treat its passes with suspicion."}),Tl.output&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border","data-testid":"review-output-panel",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 border-b border-border/60 bg-muted/40 px-3 py-1.5",children:[jsxRuntimeExports.jsxs("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:["Output — what the judge graded",Tl.outputTruncated?" (first 20k chars)":""]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-0.5",children:[jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>Ga(Al=>!Al),className:"rounded px-1.5 py-0.5 text-[11px] text-muted-foreground/70 transition-colors hover:text-foreground",children:Ka?"Collapse":"Show all"}),jsxRuntimeExports.jsx(CopyButton,{text:Tl.output,what:"output"})]})]}),jsxRuntimeExports.jsx("pre",{ref:Il,className:cn$1("text-xs p-3 overflow-x-auto overflow-y-auto whitespace-pre-wrap rounded-b-md bg-muted/30",Ka?"max-h-none":"max-h-[26rem]"),children:ql.segments?ql.segments.map((Al,Ml)=>{if(!Al.highlighted)return jsxRuntimeExports.jsx("span",{children:Al.text},Ml);const Ql=ql.segments.findIndex(eu=>eu.highlighted)===Ml;return jsxRuntimeExports.jsx("mark",{ref:Ql?Fl:void 0,className:"bg-teal-500/25 text-inherit rounded-sm",children:Al.text},Ml)}):Tl.output})]})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Judge grades — did the judge get each one right?"}),jsxRuntimeExports.jsx(InfoTip,{content:"You're checking the AI JUDGE, not re-grading the output. For each assertion, decide whether the judge's pass/fail verdict was correct: approve if the judge got it right, reject if it got it wrong. Each click is one human anchor that calibrates how much to trust the judge."})]}),Tl.expectations.map(Al=>{const Ml=Al.method==="llm"&&!Al.errored,Ql=Ml?ol(Tl,Al.index):null,eu=Ml&&Al.index===Nl,xu=Ml&&Al.index===Dl;return jsxRuntimeExports.jsxs("div",{onMouseEnter:Ml?()=>Zl(Al.index):void 0,onMouseLeave:Ml?()=>Zl(null):void 0,className:cn$1("rounded-md border p-3 transition-colors",eu?"border-primary/60 bg-primary/[0.04]":"border-border"),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2.5",children:[Al.errored?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"mt-0.5 shrink-0 text-[10px] text-muted-foreground",title:"The grader crashed or the assertion definition is broken — no verdict exists to review. Re-run grading.",children:"grader errored"}):Ml?jsxRuntimeExports.jsxs("span",{className:cn$1("mt-0.5 shrink-0 rounded px-1.5 py-0.5 font-mono text-[10px] font-medium",Al.passed?"bg-teal-500/10 text-teal-500":"bg-red-500/10 text-red-500"),children:["Judge: ",Al.passed?"PASS":"FAIL"]}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"mt-0.5 shrink-0 text-[10px]",children:["auto ",Al.passed?"✓":"✗"]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"font-mono text-sm",children:Al.text}),Al.evidence&&jsxRuntimeExports.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{className:"font-medium text-muted-foreground/70",children:["Judge's evidence:"," "]}),Al.evidence]}),xu&&(ql.count>0?jsxRuntimeExports.jsxs("p",{className:"mt-1 text-[11px] text-teal-500",children:[ql.count," cited span",ql.count===1?"":"s"," highlighted in the output above"]}):jsxRuntimeExports.jsx("p",{className:"mt-1 text-[11px] text-muted-foreground/70",children:"evidence isn't quoted verbatim — nothing to highlight"}))]})]}),Ml&&jsxRuntimeExports.jsxs("div",{className:"mt-2.5 flex flex-wrap items-center gap-2 pl-0.5",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>hl(Tl.id,Al.index,"approve",Ql),disabled:dl.isPending||fl.isPending,className:cn$1("flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs transition-colors",Ql==="approve"?"border-teal-500/60 bg-teal-500/10 text-teal-500":"border-border text-muted-foreground hover:border-teal-500/40 hover:text-teal-500"),children:[jsxRuntimeExports.jsx(ThumbsUp,{className:"h-3.5 w-3.5"})," Judge was right",eu&&jsxRuntimeExports.jsx(Kbd,{children:"1"})]}),jsxRuntimeExports.jsxs("button",{onClick:()=>hl(Tl.id,Al.index,"reject",Ql),disabled:dl.isPending||fl.isPending,className:cn$1("flex items-center gap-1.5 rounded-md border px-2.5 py-1 text-xs transition-colors",Ql==="reject"?"border-red-500/60 bg-red-500/10 text-red-500":"border-border text-muted-foreground hover:border-red-500/40 hover:text-red-500"),children:[jsxRuntimeExports.jsx(ThumbsDown,{className:"h-3.5 w-3.5"})," Judge was wrong",eu&&jsxRuntimeExports.jsx(Kbd,{children:"2"})]}),Ql&&jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"✓ recorded"})]}),Ml&&Ql==="reject"&&(()=>{var Bl;const fu=`${Tl.id}:${Al.index}`,Ou=((Bl=nl.get(fu))==null?void 0:Bl.note)??"",yu=Va[fu]??Ou,ic=yu!==Ou,Iu=()=>dl.mutate({runId:Tl.id,expectationIndex:Al.index,verdict:"reject",note:yu.trim()||null},{onError:()=>ue$1.error("Note didn't save — try again.")});return jsxRuntimeExports.jsxs("div",{className:"mt-2 flex items-center gap-2 pl-0.5",children:[jsxRuntimeExports.jsx("input",{type:"text",value:yu,maxLength:2e3,onChange:ru=>Ja(Mu=>({...Mu,[fu]:ru.target.value})),onKeyDown:ru=>{ru.key==="Enter"&&ic&&(ru.preventDefault(),Iu())},placeholder:"Why was the judge wrong? (optional — saved with the label)",className:"h-7 min-w-0 flex-1 rounded-md border border-border bg-background px-2 text-xs placeholder:text-muted-foreground/60 focus:border-primary/50 focus:outline-none"}),jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",disabled:!ic||dl.isPending,onClick:Iu,children:Ou&&!ic?"Saved":"Save note"})]})})()]},Al.index)})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 border-t border-border p-3",children:[jsxRuntimeExports.jsxs("span",{className:"min-w-0 flex-1 basis-48 text-xs text-muted-foreground",children:[pl,"/",ul.length," assertions reviewed",jl?jsxRuntimeExports.jsx("span",{className:"text-teal-500",children:" · this run now counts toward the pilot"}):ul.length>1?jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/70",children:[" ","· label all ",ul.length," for this run to count toward the pilot"]}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[!jl&&ul.length>1&&jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",disabled:dl.isPending,onClick:()=>{for(const Al of ul)ol(Tl,Al.index)==null&&hl(Tl.id,Al.index,"approve",null)},children:["Mark all ",ul.length," right"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:jl?"default":"ghost",onClick:()=>Ma(Ba+1),children:[jl?"Next run":"Skip run",jsxRuntimeExports.jsx(Kbd,{className:"ml-1.5 border-transparent bg-transparent",children:jl?"↵":"S"}),jsxRuntimeExports.jsx(ChevronRight,{className:"ml-0.5 h-3 w-3"})]})]})]})]}):jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-6 text-center space-y-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Batch reviewed — ",$.remaining," run",$.remaining===1?"":"s"," still need",$.remaining===1?"s":""," review."]}),jsxRuntimeExports.jsxs(Button,{size:"sm",disabled:ts,onClick:()=>{Ma(0),is()},children:[ts&&jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 mr-1.5 animate-spin"}),"Load next batch"]})]}):jsxRuntimeExports.jsx(Skeleton,{className:"h-48 w-full"})]})}const FINISHED_FILTERS=["all","evolution","decided","skipped","failed"],FinishedFilterSchema=enumType(FINISHED_FILTERS),PAGE_SIZES=[20,50,100],JobOutcomeSchema=enumType(["ok","skipped","decided","failed"]),PendingKindSchema=objectType({kind:stringType(),count:numberType(),oldestMinutes:numberType()}).strict(),WorkerVerdictSchema=objectType({severity:enumType(["ok","warn","fail"]),headline:stringType(),hints:arrayType(stringType()),stuck:arrayType(PendingKindSchema),unclaimable:arrayType(PendingKindSchema),engineBlocked:arrayType(PendingKindSchema)}).strict(),WorkerSchema=objectType({present:booleanType(),active:booleanType(),ageSeconds:numberType().nullable(),clientName:stringType().nullable(),clientVersion:stringType().nullable(),lastHeartbeat:stringType().nullable()}).strict(),ReviewGateTargetSchema=objectType({id:stringType(),name:stringType(),awaitingReview:numberType(),humanLabeled:numberType(),humanLabeledWith:numberType(),humanLabeledWithout:numberType(),pilotTarget:numberType()}).strict(),ReviewGateSchema=objectType({blocking:booleanType(),totalAwaitingReview:numberType(),targets:arrayType(ReviewGateTargetSchema)}).strict(),RunningJobSchema=objectType({id:stringType(),kind:stringType(),label:stringType().nullable(),claimedAt:stringType().nullable(),elapsedSeconds:numberType().nullable(),leaseHealthy:booleanType()}).strict(),QueuedJobSchema=objectType({id:stringType(),kind:stringType(),label:stringType().nullable(),createdAt:stringType(),waitedSeconds:numberType(),attempts:numberType()}).strict(),FinishedJobSchema=objectType({id:stringType(),kind:stringType(),label:stringType().nullable(),finishedAt:stringType().nullable(),durationSeconds:numberType().nullable(),outcome:JobOutcomeSchema,reason:stringType().nullable(),detail:stringType().nullable()}).strict(),LoopProposalSchema=objectType({id:stringType(),evalTargetId:stringType().nullable(),targetName:stringType().nullable(),createdAt:stringType(),decision:stringType(),applied:booleanType(),effectClass:stringType(),proposalSource:stringType()}).strict(),LoopChangesSchema=objectType({decisions:numberType(),applied:numberType(),byDecision:objectType({promote:numberType(),revert:numberType(),refuse:numberType()}).strict(),readyToApply:numberType(),readyToApplyTargetId:stringType().nullable(),readyToApplyPromotionId:stringType().nullable(),lastAppliedAt:stringType().nullable(),lastDecidedAt:stringType().nullable(),suggestionsProposed:numberType(),suggestionsAccepted:numberType(),suggestionsPending:numberType(),lastAcceptedAt:stringType().nullable(),landedTotal:numberType(),window:objectType({hours:numberType(),landed:numberType(),decisions:numberType(),promotionsApplied:numberType(),adoptionApplied:numberType(),suggestionsSurfaced:numberType(),suggestionsAccepted:numberType(),suggestionsDeclined:numberType()}).strict()}).strict(),DeliveryProjectSchema=objectType({projectId:stringType(),name:stringType().nullable(),canonicalPath:stringType().nullable(),canonicalLastSeenAt:stringType().nullable(),stale:booleanType(),lastActivityAt:stringType().nullable(),lastAnalysedAt:stringType().nullable(),suggestionsPending:numberType(),suggestionsAccepted:numberType(),lastAcceptedAt:stringType().nullable()}).strict(),RecommendationApplicationSchema=objectType({id:stringType(),instructionId:stringType(),title:stringType(),artifact:stringType(),harness:stringType(),targetPath:stringType(),projectPath:stringType(),status:stringType(),applyMode:stringType(),verdictDetail:stringType().nullable(),updatedAt:stringType()}).strict(),PromotionPathProjectSchema=objectType({projectId:stringType(),trials:objectType({running:numberType(),orphaned:numberType(),eligible:numberType(),maxConcurrent:numberType(),maxPerRun:numberType(),blocked:enumType(["none","concurrency","per-run","no-candidates"])}).strict(),autoAccept:objectType({enabled:booleanType(),usedInWindow:numberType(),maxPerWindow:numberType(),maxPerRun:numberType(),windowDays:numberType(),eligible:numberType(),windowResetsAt:stringType().nullable()}).strict()}).strict(),LoopSummarySchema=objectType({worker:WorkerSchema,verdict:WorkerVerdictSchema,reviewGate:ReviewGateSchema,running:arrayType(RunningJobSchema),queued:arrayType(QueuedJobSchema),failedInWindow:numberType(),proposals:arrayType(LoopProposalSchema),proposalTotal:numberType(),changes:LoopChangesSchema,counts:objectType({experimentsRunning:numberType(),suggestions:recordType(stringType(),numberType())}).strict(),windowHours:numberType()}).strict(),LoopDiagnosticsSchema=objectType({recent:arrayType(FinishedJobSchema),recentTotal:numberType(),filterCounts:objectType({all:numberType(),evolution:numberType(),decided:numberType(),skipped:numberType(),failed:numberType()}).strict(),insights:objectType({entries:numberType(),distinct:numberType(),repeated:numberType(),dismissed:numberType(),maxTimesGenerated:numberType(),lastSeenAt:stringType().nullable()}).strict(),delivery:objectType({projects:arrayType(DeliveryProjectSchema),total:numberType(),staleCount:numberType()}).strict(),promotionPaths:objectType({projects:arrayType(PromotionPathProjectSchema)}).strict(),adoption:objectType({available:booleanType(),counts:recordType(stringType(),numberType()),applications:arrayType(RecommendationApplicationSchema)}).strict(),windowHours:numberType(),limit:numberType(),filter:FinishedFilterSchema}).strict();LoopSummarySchema.merge(LoopDiagnosticsSchema).strict();Object.keys(LoopSummarySchema.shape);Object.keys(LoopDiagnosticsSchema.shape);const loopQueryKeys={summary:es=>["loop","summary",es.hours,es.limit],diagnostics:es=>["loop","diagnostics",es.hours,es.limit,es.filter]};function summaryPollInterval(es){var ts,is;return(((ts=es==null?void 0:es.running)==null?void 0:ts.length)??0)>0||(((is=es==null?void 0:es.queued)==null?void 0:is.length)??0)>0?POLL.LIVE:POLL.HEARTBEAT}function assertLoopPayload(es,$){const ts=es==="summary"?["running","queued","proposals"]:["recent"],is=$;if(!(typeof is=="object"&&is!==null&&ts.every(Qr=>Array.isArray(is[Qr]))&&(es==="summary"?typeof is.changes=="object"&&is.changes!==null&&typeof is.worker=="object":typeof is.filterCounts=="object"&&is.filterCounts!==null))){const Qr=typeof $=="string"?`${$.slice(0,40).replace(/\s+/g," ")}…`:typeof $;throw new Error(`/api/loop/${es} returned something that is not a loop ${es} (got ${Qr}). An API that predates this page answers with the SPA fallback — is the API you are talking to current?`)}return $}function diagnosticsQuery(es){return{enabled:es.open,refetchInterval:es.open?POLL.HEARTBEAT:!1}}function diagnosticsPanelState(es){return es.open?es.hasData?"ready":es.isError?"error":"loading":"closed"}function headlineInputs(es){return{workerPresent:es.worker.present,leaseUnhealthy:es.running.some($=>!$.leaseHealthy),readyToApply:es.changes.readyToApply,failedRecently:es.failedInWindow,running:es.running.length,queued:es.queued.length,engineBlocked:(es.verdict.engineBlocked??[]).reduce(($,ts)=>$+ts.count,0)}}function useProvenanceImpact(){return useQuery({queryKey:["provenance-impact"],queryFn:()=>apiGet("/api/insights/provenance-impact"),refetchInterval:POLL.SLOW})}function usePromotionDetail(es,$){return useQuery({queryKey:["promotion",es],queryFn:()=>apiGet(`/api/promotions/${es}`),enabled:$&&!!es,staleTime:5*6e4})}function useApplyPromotion(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost(`/api/promotions/${$}/apply`,{}),onSuccess:()=>{es.invalidateQueries({queryKey:["loop"]}),es.invalidateQueries({queryKey:["promotion"]})}})}function useRunLoopNow(){const es=useQueryClient();return useMutation({mutationFn:()=>apiPost("/api/loop/run-now",{}),onSuccess:()=>{es.invalidateQueries({queryKey:["loop"]})}})}function useLoopSummary(es){const $=new URLSearchParams({hours:String(es.hours),limit:String(es.limit)});return useQuery({queryKey:loopQueryKeys.summary(es),queryFn:async()=>assertLoopPayload("summary",await apiGet(`/api/loop/summary?${$.toString()}`)),placeholderData:ts=>ts,refetchInterval:ts=>summaryPollInterval(ts.state.data)})}function useLoopDiagnostics(es,$){const ts=new URLSearchParams({hours:String(es.hours),limit:String(es.limit),filter:es.filter}),is=diagnosticsQuery($);return useQuery({queryKey:loopQueryKeys.diagnostics(es),queryFn:async()=>assertLoopPayload("diagnostics",await apiGet(`/api/loop/diagnostics?${ts.toString()}`)),enabled:is.enabled,placeholderData:cs=>cs,refetchInterval:is.refetchInterval})}const MAX_LINES=4e3,toLines=es=>es===""?[]:es.split(`
|
|
143
|
+
`);function lineDiff(es,$){const ts=toLines(es),is=toLines($);if(ts.length>MAX_LINES||is.length>MAX_LINES)return[...ts.map((Aa,Oa)=>({op:"remove",text:Aa,oldLine:Oa+1,newLine:null})),...is.map((Aa,Oa)=>({op:"add",text:Aa,oldLine:null,newLine:Oa+1}))];const cs=Array.from({length:ts.length+1},()=>new Array(is.length+1).fill(0));for(let Aa=ts.length-1;Aa>=0;Aa--)for(let Oa=is.length-1;Oa>=0;Oa--)cs[Aa][Oa]=ts[Aa]===is[Oa]?cs[Aa+1][Oa+1]+1:Math.max(cs[Aa+1][Oa],cs[Aa][Oa+1]);const Qr=[];let ja=0,Na=0;for(;ja<ts.length&&Na<is.length;)ts[ja]===is[Na]?(Qr.push({op:"same",text:ts[ja],oldLine:ja+1,newLine:Na+1}),ja++,Na++):cs[ja+1][Na]>=cs[ja][Na+1]?(Qr.push({op:"remove",text:ts[ja],oldLine:ja+1,newLine:null}),ja++):(Qr.push({op:"add",text:is[Na],oldLine:null,newLine:Na+1}),Na++);for(;ja<ts.length;)Qr.push({op:"remove",text:ts[ja],oldLine:++ja,newLine:null});for(;Na<is.length;)Qr.push({op:"add",text:is[Na],oldLine:null,newLine:++Na});return Qr}function toHunks(es,$=3){const ts=new Set;es.forEach((Na,Aa)=>{if(Na.op!=="same")for(let Oa=Math.max(0,Aa-$);Oa<=Math.min(es.length-1,Aa+$);Oa++)ts.add(Oa)});const is=[];let cs=[],Qr=0,ja=0;return es.forEach((Na,Aa)=>{ts.has(Aa)?(cs.length===0&&(Qr=ja,ja=0),cs.push(Na)):(cs.length>0&&(is.push({lines:cs,skippedBefore:Qr}),cs=[]),ja++)}),cs.length>0&&is.push({lines:cs,skippedBefore:Qr}),is}function diffStat(es){let $=0,ts=0;for(const is of es)is.op==="add"?$++:is.op==="remove"&&ts++;return{added:$,removed:ts}}function EvidenceJson({label:es,value:$}){return Object.keys($).length===0?null:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium text-foreground",children:es}),jsxRuntimeExports.jsx("pre",{className:"mt-1 overflow-x-auto rounded border border-border bg-background/60 p-2 text-xs text-muted-foreground",children:JSON.stringify($,null,2)})]})}function PromotionDetailPanel({promotionId:es,open:$,allowApply:ts=!1,testId:is}){const{data:cs,isLoading:Qr,isError:ja}=usePromotionDetail(es,$),Na=useApplyPromotion();if(!$)return null;const Aa=cs?lineDiff(cs.fromContent,cs.toContent):[],Oa=cs?toHunks(Aa):[],Ia=diffStat(Aa);return jsxRuntimeExports.jsxs("div",{className:"reveal min-w-0 border-t border-border bg-muted/10 px-3 py-3","data-testid":is??`proposal-detail-${es}`,children:[Qr&&jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}),ja&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-400/90",children:"Could not load this proposed change."}),cs&&jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"grid gap-3 text-sm md:grid-cols-2",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Decision rationale"}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-foreground",children:cs.rationale||"No final rationale was recorded."})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Proposal rationale"}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-foreground",children:cs.proposalRationale||"No proposal rationale was recorded."})]})]}),cs.refusals.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-medium uppercase tracking-wide text-amber-400",children:"Refusal reasons"}),jsxRuntimeExports.jsx("ul",{className:"list-disc space-y-1 pt-1 pl-5 text-sm text-foreground",children:cs.refusals.map((La,Ba)=>jsxRuntimeExports.jsx("li",{children:La},Ba))})]}),cs.touchedSections.length>0&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"font-medium text-foreground",children:"Touched sections:"})," ",cs.touchedSections.join(" · ")]}),jsxRuntimeExports.jsxs("div",{className:"grid min-w-0 gap-3 md:grid-cols-2",children:[jsxRuntimeExports.jsx(EvidenceJson,{label:"Verdict evidence",value:cs.verdict}),jsxRuntimeExports.jsx(EvidenceJson,{label:"Decision gates",value:cs.gates})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("p",{className:"pb-1 font-mono text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{className:"text-teal-400",children:["+",Ia.added]})," ",jsxRuntimeExports.jsxs("span",{className:"text-amber-400",children:["−",Ia.removed]})," lines"]}),jsxRuntimeExports.jsx("div",{className:"max-h-96 max-w-full overflow-auto rounded border border-border bg-background/50","data-testid":"promotion-diff",children:jsxRuntimeExports.jsx("div",{className:"w-max min-w-full font-mono text-xs leading-relaxed",children:Oa.map((La,Ba)=>jsxRuntimeExports.jsxs("div",{children:[La.skippedBefore>0&&jsxRuntimeExports.jsxs("div",{className:"bg-muted/30 px-2 py-0.5 text-muted-foreground",children:["… ",La.skippedBefore," unchanged line",La.skippedBefore===1?"":"s"]}),La.lines.map((Ma,qa)=>jsxRuntimeExports.jsxs("div",{className:cn$1("px-2",Ma.op==="add"&&"bg-teal-400/10 text-teal-300",Ma.op==="remove"&&"bg-amber-400/10 text-amber-300",Ma.op==="same"&&"text-muted-foreground"),children:[jsxRuntimeExports.jsx("span",{className:"select-none pr-2 opacity-50",children:Ma.op==="add"?"+":Ma.op==="remove"?"−":" "}),Ma.text||" "]},qa))]},Ba))})})]}),ts&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:Na.isPending||Na.isSuccess,onClick:()=>Na.mutate(es),className:cn$1("rounded border px-3 py-1 text-xs transition-colors duration-150",Na.isSuccess?"border-teal-400/40 text-teal-400":"cursor-pointer border-teal-400/40 text-teal-400 hover:bg-teal-400/10",Na.isPending&&"opacity-60"),"data-testid":"apply-promotion",children:Na.isSuccess?"Applied":Na.isPending?"Applying…":"Apply this change"}),Na.isError&&jsxRuntimeExports.jsx("span",{className:"text-xs text-amber-400/90","data-testid":"apply-error",children:Na.error instanceof Error?Na.error.message:"Could not apply this change."})]})]})]})}function PromotionsTab({promotions:es,isLoading:$}){const[ts,is]=reactExports.useState(null);return $?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading promotions…"}):es.length===0?jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-border px-4 py-3",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No evolution decisions yet. The nightly loop records one row here per measured proposal — promote, revert, or refuse."})}):jsxRuntimeExports.jsx("div",{className:"rounded-lg border border-border divide-y divide-border",children:es.map(cs=>{const Qr=ts===cs.id;return jsxRuntimeExports.jsxs("div",{"data-testid":"promotion-row",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>is(Qr?null:cs.id),"aria-expanded":Qr,"aria-controls":`proposal-detail-${cs.id}`,className:"flex min-h-11 w-full cursor-pointer items-start justify-between gap-4 px-4 py-3 text-left hover:bg-muted/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring","data-testid":`promotion-toggle-${cs.id}`,children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[Qr?jsxRuntimeExports.jsx(ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("p",{className:"font-mono text-sm",children:[cs.decision," · ",cs.effectClass," · ",new Date(cs.createdAt).toLocaleDateString()]}),jsxRuntimeExports.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["via ",cs.proposalSource]}),cs.rationale&&jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-muted-foreground",children:cs.rationale})]})]}),jsxRuntimeExports.jsx("span",{className:cn$1("shrink-0 rounded border px-2 py-0.5 text-xs",cs.applied?"border-teal-400/40 text-teal-400":"border-muted-foreground/40 text-muted-foreground"),children:cs.applied?"applied":"not applied"})]}),jsxRuntimeExports.jsx(PromotionDetailPanel,{promotionId:cs.id,open:Qr})]},cs.id)})})}function ActiveJobCard({job:es}){const $=es.progress,ts=$.total>0?Math.round($.completed/$.total*100):0;return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 bg-secondary/20 space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin text-primary"}),jsxRuntimeExports.jsxs("span",{className:"text-sm font-medium",children:[es.status==="pending"&&"Waiting for CLI worker to pick up job...",es.status==="claimed"&&`Claimed by ${es.claimedBy}. Starting...`,es.status==="running"&&($.message||"Running...")]})]}),$.total>0&&jsxRuntimeExports.jsxs("span",{className:"text-sm font-mono text-muted-foreground",children:[$.completed,"/",$.total," (",ts,"%)"]})]}),$.total>0&&jsxRuntimeExports.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:jsxRuntimeExports.jsx("div",{className:"bg-primary rounded-full h-2 transition-all duration-300",style:{width:`${ts}%`}})}),$.current&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground font-mono truncate",children:$.current})]})}function BackgroundMeasurement({targetId:es}){var Na,Aa,Oa,Ia;const $=useQueryClient(),ts=["eval-targets",es,"background"],is=useQuery({queryKey:ts,queryFn:()=>apiGet(`/api/eval-targets/${es}/background`),refetchInterval:15e3}),cs=useMutation({mutationFn:La=>apiPatch(`/api/eval-targets/${es}/background`,{enabled:La}),onSuccess:()=>{$.invalidateQueries({queryKey:ts})}}),Qr=is.data,ja=is.error??cs.error;return jsxRuntimeExports.jsxs("section",{"aria-label":"Background measurement",className:"rounded-lg border border-border p-4 space-y-2 text-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[jsxRuntimeExports.jsxs("h3",{className:"font-medium",children:["Background measurement",Qr?` · ${Qr.enabled?"On":"Off"}`:""]}),Qr&&jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",disabled:cs.isPending||!Qr.enabled&&Qr.blockers.length>0,onClick:()=>cs.mutate(!Qr.enabled),children:cs.isPending?"Saving…":Qr.enabled?"Pause nightly trials":"Enable nightly trials"})]}),ja&&jsxRuntimeExports.jsx("p",{role:"alert",className:"break-words text-destructive",children:ja.message}),!Qr&&!ja&&jsxRuntimeExports.jsx("p",{role:"status",children:"Loading schedule…"}),Qr&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground",children:[Qr.schedule,"; up to ",Qr.maxRuns/2," paired cases per night, rotating through ",Qr.liveCases," cases until sufficient evidence. Uses your local worker and subscription quota. Does not rewrite files."]}),jsxRuntimeExports.jsxs("p",{className:"break-words",children:["Actor: ",Qr.measurement?`${Qr.measurement.engine} · ${Qr.measurement.model??"CLI default"}`:"Existing worker defaults","; grader: ",Qr.judge.engine," · ",Qr.judge.model??"default",". ",jsxRuntimeExports.jsx(Link,{className:"underline",to:"/settings",children:"Measurement settings"})]}),!Qr.ready&&jsxRuntimeExports.jsx("p",{role:"status",className:"text-amber-500",children:"Waiting for a compatible worker. Start or upgrade your local worker; installed engines do not guarantee account credits."}),Qr.blockers.map(La=>jsxRuntimeExports.jsx("p",{className:"text-amber-500",children:La},La)),Qr.latest?jsxRuntimeExports.jsxs("p",{className:"break-words","data-testid":"background-last-result",children:["Last batch: ",Qr.latest.status," · ",new Date(Qr.latest.createdAt).toLocaleString(),((Na=Qr.latest.result)==null?void 0:Na.ranRuns)!=null&&` · ${Qr.latest.result.ranRuns} completed, ${Qr.latest.result.failedRuns??0} failed`,` — ${Qr.latest.error??((Aa=Qr.latest.result)==null?void 0:Aa.failures)??((Oa=Qr.latest.result)==null?void 0:Oa.reason)??((Ia=Qr.latest.result)==null?void 0:Ia.skipped)??"Waiting for results"}`]}):jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"No background batch yet. Results appear in Runs and Review below."}),!Qr.enabled&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"No new nightly batches will start. A batch already executing may finish."})]})]})}const label=es=>typeof es=="string"&&es?es:"Not recorded",number=es=>typeof es=="number"&&Number.isFinite(es)&&es>=0?es:null;function RunEvidence({run:es}){const $=number(es.outputs.costUsd),ts=number(es.timing.total_tokens);return jsxRuntimeExports.jsxs("div",{className:"space-y-2 text-xs","data-testid":"run-evidence",children:[jsxRuntimeExports.jsxs("dl",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2 [&_dd]:break-words [&_dt]:text-muted-foreground",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Harness / provider"}),jsxRuntimeExports.jsxs("dd",{children:[label(es.outputs.engine)," / ",label(es.outputs.provider)]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Resolved model"}),jsxRuntimeExports.jsx("dd",{children:label(es.outputs.model)})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Tokens"}),jsxRuntimeExports.jsx("dd",{children:ts===null?"Not recorded":ts.toLocaleString()})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Estimated API-equivalent cost"}),jsxRuntimeExports.jsx("dd",{children:$===null?"Unavailable — not zero":`$${$.toFixed(5)}`})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Methodology / delivery"}),jsxRuntimeExports.jsxs("dd",{children:[label(es.outputs.methodology)," / ",label(es.outputs.delivery)]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("dt",{children:"Judge"}),jsxRuntimeExports.jsxs("dd",{children:[label(es.grading.judge_engine)," / ",label(es.grading.judge_model)]})]})]}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Compare revisions within the same harness, provider, model and methodology. Dollar estimates are not subscription charges or proven savings."}),es.outputs.isolated===!1&&jsxRuntimeExports.jsx("p",{className:"text-amber-500",children:"No repository workspace was available for this run."}),Array.isArray(es.outputs.leakedFiles)&&es.outputs.leakedFiles.length>0&&jsxRuntimeExports.jsx("p",{role:"alert",className:"text-destructive",children:"Contaminated workspace: instruction files survived baseline isolation."}),typeof es.outputs.error=="string"&&jsxRuntimeExports.jsx("p",{role:"alert",className:"break-words text-destructive",children:es.outputs.error})]})}const TAB_KEYS=["chat","evals","runs","review","benchmarks","comparisons","promotions"],RUNS_PAGE_LIMIT=50,COMPARISONS_PAGE_LIMIT=50;function EvalTargetDetailPage(){const{id:es}=useParams(),[$,ts]=useTabParam(TAB_KEYS,"chat"),{data:is,isLoading:cs}=useEvalTarget(es),{data:Qr,isLoading:ja}=useEvals(es),{data:Na,isLoading:Aa}=useEvalRuns(es),{data:Oa,isLoading:Ia}=useBenchmarks(es),{data:La,isLoading:Ba}=useEvalComparisons(es),{data:Ma}=useGradeAnnotations(es),{data:qa}=useJudgeCalibration(es),{data:Fa,isFetching:Ha,refetch:Ka}=useAnnotationQueue(es),{data:Ga,isLoading:Va}=usePromotions(es),{data:Ja}=useJudgeDisagreements(es),{user:Ya}=useAuth(),{data:el}=useEvalJobs(es),tl=useCreateEvalJob(),rl=useCancelEvalJob(),cl=useRealtimeEvalJobs(Ya==null?void 0:Ya.id,es),{isConnected:dl,workerCount:fl}=useWorkerStatus("cli-worker"),nl=cl??(el==null?void 0:el.find(pl=>["pending","claimed","running"].includes(pl.status)))??null,ol=!!nl&&["pending","claimed","running"].includes(nl.status),hl=(el==null?void 0:el[0])??null,Tl=!ol&&(hl==null?void 0:hl.status)==="failed"?hl:null;if(cs)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-96"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"})]});if(!is)return jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Eval target not found."});const ul=[{key:"chat",label:"Chat"},{key:"evals",label:"Evals",count:Qr==null?void 0:Qr.length},{key:"runs",label:"Runs",count:Na&&Na.length>=RUNS_PAGE_LIMIT?`${RUNS_PAGE_LIMIT}+`:Na==null?void 0:Na.length},{key:"review",label:"Review",count:Fa==null?void 0:Fa.remaining},{key:"benchmarks",label:"Benchmarks",count:Oa==null?void 0:Oa.length},{key:"comparisons",label:"Comparisons",count:La&&La.length>=COMPARISONS_PAGE_LIMIT?`${COMPARISONS_PAGE_LIMIT}+`:La==null?void 0:La.length},{key:"promotions",label:"Promotions",count:Ga==null?void 0:Ga.total}];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/eval-targets",children:jsxRuntimeExports.jsx(ArrowLeft,{className:"h-4 w-4"})})}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1 basis-64",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight break-words",children:is.name}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground break-words",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"mr-2 font-mono",children:is.type}),"v",is.version,is.description&&` — ${is.description}`]})]}),jsxRuntimeExports.jsxs("div",{className:"ml-auto flex items-center gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("div",{className:`h-2 w-2 rounded-full ${dl?"bg-teal-500":"bg-red-500"}`}),dl?`${fl} worker${fl>1?"s":""} online`:"No workers"]}),ol?jsxRuntimeExports.jsxs(Button,{variant:"destructive",size:"sm",onClick:()=>nl&&rl.mutate(nl.id),disabled:rl.isPending,children:[jsxRuntimeExports.jsx(Square,{className:"h-3 w-3 mr-1.5"}),"Cancel Run"]}):jsxRuntimeExports.jsxs(Button,{size:"sm",onClick:()=>es&&tl.mutate({evalTargetId:es}),disabled:tl.isPending||!(Qr!=null&&Qr.length)||!dl,title:dl?Qr!=null&&Qr.length?void 0:"Add eval cases first — none defined for this target":"Start a CLI worker: rulemetric evals agent",children:[jsxRuntimeExports.jsx(Play,{className:"h-3 w-3 mr-1.5"}),"Run Evals"]})]})]}),jsxRuntimeExports.jsx(BackgroundMeasurement,{targetId:is.id}),!ol&&Qr&&Qr.length===0&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 px-4 py-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-amber-500 font-medium",children:"No eval cases defined"}),jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Add cases via CLI: ",jsxRuntimeExports.jsxs("code",{className:"bg-muted px-1 py-0.5 rounded text-[11px]",children:["rulemetric evals create ",es,' --name "..." --prompt "..." -e "..."']})]})]}),nl&&["pending","claimed","running"].includes(nl.status)&&jsxRuntimeExports.jsx(ActiveJobCard,{job:nl}),Tl&&jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-red-500/30 bg-red-500/5 px-4 py-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-red-500 font-medium",children:"Last run failed"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1 font-mono break-words",children:Tl.error??"No error recorded for this job."})]}),$!=="review"&&(((Fa==null?void 0:Fa.remaining)??0)>0||((Ja==null?void 0:Ja.length)??0)>0)&&jsxRuntimeExports.jsx("button",{type:"button","data-testid":"review-callout",onClick:()=>ts("review"),className:"group w-full rounded-lg border border-primary/40 bg-primary/[0.06] px-4 py-3 text-left transition-colors hover:bg-primary/[0.1]",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm font-medium",children:[((Fa==null?void 0:Fa.remaining)??0)>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Fa.remaining," run",Fa.remaining===1?"":"s"," await your review"]}),((Fa==null?void 0:Fa.remaining)??0)>0&&((Ja==null?void 0:Ja.length)??0)>0&&" · ",((Ja==null?void 0:Ja.length)??0)>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Ja.length," label",Ja.length===1?"":"s"," flagged by a second opinion"]})]}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-[13px] text-muted-foreground",children:"For each run you'll see the prompt, the agent's output, and the judge's pass/fail on every assertion — you mark whether the judge got it right. A few minutes of labels calibrate the judge so its verdicts can be trusted."})]}),jsxRuntimeExports.jsxs("span",{className:"flex shrink-0 items-center gap-1 text-sm font-medium text-primary",children:["Start reviewing",jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 transition-transform group-hover:translate-x-0.5"})]})]})}),jsxRuntimeExports.jsx("div",{className:"flex gap-1 border-b border-border overflow-x-auto",children:ul.map(pl=>jsxRuntimeExports.jsxs("button",{onClick:()=>ts(pl.key),className:`shrink-0 whitespace-nowrap px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${$===pl.key?"border-primary text-primary":"border-transparent text-muted-foreground hover:text-foreground"}`,children:[pl.label,pl.count!=null&&jsxRuntimeExports.jsxs("span",{className:"ml-1.5 text-xs text-muted-foreground",children:["(",pl.count,")"]})]},pl.key))}),$==="evals"&&jsxRuntimeExports.jsx(EvalsTab,{evalCases:Qr??[],isLoading:ja}),$==="runs"&&jsxRuntimeExports.jsx(RunsTab,{targetId:es,runs:Na??[],isLoading:Aa,annotations:Ma??[]}),$==="review"&&jsxRuntimeExports.jsx(ReviewTab,{targetId:es,queue:Fa,isFetching:Ha,refetchQueue:Ka,annotations:Ma??[],powerCheck:qa==null?void 0:qa.powerCheck,judge:qa==null?void 0:qa.judge,caseDiscrimination:qa==null?void 0:qa.caseDiscrimination,pooling:qa==null?void 0:qa.pooling,reviewers:qa==null?void 0:qa.reviewers,targetContent:is.content??null,targetType:is.type}),$==="benchmarks"&&jsxRuntimeExports.jsx(BenchmarksTab,{benchmarks:Oa??[],isLoading:Ia,judgeCalibration:qa}),$==="comparisons"&&jsxRuntimeExports.jsx(ComparisonsTab,{comparisons:La??[],isLoading:Ba}),$==="promotions"&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[es&&jsxRuntimeExports.jsx(StudiesPanel,{targetId:es}),jsxRuntimeExports.jsx(PromotionsTab,{promotions:(Ga==null?void 0:Ga.promotions)??[],isLoading:Va})]}),$==="chat"&&es&&jsxRuntimeExports.jsx(ChatPanel,{targetId:es})]})}function EvalsTab({evalCases:es,isLoading:$}){return $?jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"}):es.length?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:es.map(ts=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-2",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono font-medium",children:ts.name}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:ts.prompt}),ts.expectations.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:ts.expectations.map((is,cs)=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:is},cs))})]},ts.id))}):jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:"No evals defined yet."})}function RunsTab({targetId:es,runs:$,isLoading:ts,annotations:is}){const[cs,Qr]=reactExports.useState(null),ja=useAnnotateGrade(es),Na=useRemoveGradeAnnotation(es),Aa=new Map(is.map(Ia=>[`${Ia.evalRunId}:${Ia.expectationIndex}`,Ia])),Oa=(Ia,La,Ba)=>{const Ma=Aa.get(`${Ia}:${La}`);(Ma==null?void 0:Ma.verdict)===Ba?Na.mutate({runId:Ia,expectationIndex:La}):ja.mutate({runId:Ia,expectationIndex:La,verdict:Ba})};return ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"}):$.length?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[$.length>=RUNS_PAGE_LIMIT&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing the ",RUNS_PAGE_LIMIT," most recent runs — older runs are not loaded."]}),$.map(Ia=>{var Ma,qa,Fa,Ha,Ka;const La=cs===Ia.id,Ba=(qa=(Ma=Ia.grading)==null?void 0:Ma.summary)==null?void 0:qa.pass_rate;return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>Qr(La?null:Ia.id),className:"w-full flex flex-wrap items-center justify-between gap-2 p-3 text-left hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 flex-wrap items-center gap-3",children:[La?jsxRuntimeExports.jsx(ChevronDown,{className:"h-4 w-4 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Badge,{variant:Ia.status==="completed"?"default":"destructive",className:"font-mono text-xs",children:Ia.status}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm",children:[Ia.configuration," · run #",Ia.runNumber," · iter ",Ia.iteration]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[Ba!=null&&jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[(Ba*100).toFixed(0),"% pass"]}),((Fa=Ia.timing)==null?void 0:Fa.duration_ms)&&jsxRuntimeExports.jsxs("span",{children:[(Ia.timing.duration_ms/1e3).toFixed(1),"s"]}),jsxRuntimeExports.jsx("span",{children:new Date(Ia.createdAt).toLocaleDateString()})]})]}),La&&jsxRuntimeExports.jsxs("div",{className:"border-t border-border p-4 space-y-3",children:[jsxRuntimeExports.jsx(RunEvidence,{run:Ia}),((Ha=Ia.grading)==null?void 0:Ha.expectations)&&jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Expectations"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"— review each grade: your labels calibrate the judge"})]}),Ia.grading.expectations.map((Ga,Va)=>{const Ja=Aa.get(`${Ia.id}:${Va}`);return jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2 text-sm group",children:[Ga.passed?jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 text-teal-500 mt-0.5 shrink-0"}):jsxRuntimeExports.jsx(CircleX,{className:"h-4 w-4 text-red-500 mt-0.5 shrink-0"}),jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports.jsx("span",{className:"font-mono",children:Ga.text}),Ga.method==="deterministic"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"ml-1.5 text-[10px] align-middle",children:"deterministic"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-xs",children:Ga.evidence})]}),Ga.method!=="deterministic"&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[jsxRuntimeExports.jsx("button",{onClick:()=>Oa(Ia.id,Va,"approve"),disabled:ja.isPending||Na.isPending,title:"Judge graded this correctly",className:`p-1 rounded transition-colors ${(Ja==null?void 0:Ja.verdict)==="approve"?"text-teal-500 bg-teal-500/10":"text-muted-foreground/50 hover:text-teal-500"}`,children:jsxRuntimeExports.jsx(ThumbsUp,{className:"h-3.5 w-3.5"})}),jsxRuntimeExports.jsx("button",{onClick:()=>Oa(Ia.id,Va,"reject"),disabled:ja.isPending||Na.isPending,title:"Judge got this grade wrong",className:`p-1 rounded transition-colors ${(Ja==null?void 0:Ja.verdict)==="reject"?"text-red-500 bg-red-500/10":"text-muted-foreground/50 hover:text-red-500"}`,children:jsxRuntimeExports.jsx(ThumbsDown,{className:"h-3.5 w-3.5"})})]})]},Va)})]}),!!((Ka=Ia.outputs)!=null&&Ka.transcript)&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:"Output"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-3 rounded-md overflow-x-auto max-h-48",children:String(Ia.outputs.transcript)})]})]})]},Ia.id)})]}):jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:"No runs yet. Execute evals via the CLI."})}function BenchmarksTab({benchmarks:es,isLoading:$,judgeCalibration:ts}){return $?jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"}):es.length?jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[ts&&jsxRuntimeExports.jsx(JudgeCalibrationCard,{data:ts}),es.map(is=>jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg p-4 space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("h3",{className:"font-mono font-medium",children:["Iteration ",is.iteration]}),jsxRuntimeExports.jsx("span",{className:"text-sm text-muted-foreground",children:new Date(is.createdAt).toLocaleDateString()})]}),Object.entries(is.runSummary).map(([cs,Qr])=>cs==="delta"?jsxRuntimeExports.jsxs("div",{className:"bg-muted/50 rounded-md p-3",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:"Delta (with - without target)"}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-4 text-sm font-mono",children:Object.entries(Qr).map(([ja,Na])=>jsxRuntimeExports.jsxs("span",{children:[ja,": ",Na]},ja))}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Mean difference only — no significance test. At the default 1 run per eval this is a single-run difference and is not statistically meaningful."})]},cs):jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:cs}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:Object.entries(Qr).map(([ja,Na])=>{const Aa=Na;return jsxRuntimeExports.jsxs("div",{className:"bg-muted/30 rounded-md p-2 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs",children:ja}),jsxRuntimeExports.jsxs("div",{className:"font-mono",children:[Aa.mean.toFixed(3),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["±",Aa.stddev.toFixed(3)]})]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["[",Aa.min.toFixed(3),", ",Aa.max.toFixed(3),"]"]})]},ja)})})]},cs)),is.notes.length>0&&jsxRuntimeExports.jsx("div",{className:"text-sm space-y-1",children:is.notes.map((cs,Qr)=>jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground",children:["— ",cs]},Qr))})]},is.id))]}):jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[ts&&jsxRuntimeExports.jsx(JudgeCalibrationCard,{data:ts}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["No benchmarks yet. Run"," ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric evals benchmark"})," ","to create one."]})]})}function ComparisonsTab({comparisons:es,isLoading:$}){const[ts,is]=reactExports.useState(null);return $?jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"}):es.length?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[es.length>=COMPARISONS_PAGE_LIMIT&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing the ",COMPARISONS_PAGE_LIMIT," most recent comparisons — older ones are not loaded."]}),es.map(cs=>{var Aa,Oa;const Qr=ts===cs.id,ja=Ia=>Ia===cs.targetAId?`${cs.targetAName} v${cs.targetAVersion}`:Ia===cs.targetBId?`${cs.targetBName} v${cs.targetBVersion}`:null,Na=cs.status==="parse_failed"?"unparseable":ja(cs.winnerTargetId)??"TIE";return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>is(Qr?null:cs.id),className:"w-full flex items-center justify-between p-3 text-left hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[Qr?jsxRuntimeExports.jsx(ChevronDown,{className:"h-4 w-4 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Badge,{variant:cs.status==="parse_failed"?"destructive":cs.winnerTargetId?"default":"secondary",className:"font-mono text-xs",children:Na}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm",children:[cs.targetAName," v",cs.targetAVersion," vs ",cs.targetBName," v",cs.targetBVersion]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[cs.model&&jsxRuntimeExports.jsx("span",{className:"font-mono text-xs",children:cs.model}),jsxRuntimeExports.jsx("span",{children:new Date(cs.createdAt).toLocaleDateString()})]})]}),Qr&&jsxRuntimeExports.jsxs("div",{className:"border-t border-border p-4 space-y-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Judged blind",cs.isSwapped?" (labels swapped)":""," — winners shown unblinded."]}),cs.status==="parse_failed"?jsxRuntimeExports.jsx(ComparisonRawOutput,{id:cs.id}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[cs.overall.reasoning&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:"Overall"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:cs.overall.reasoning})]}),(Aa=cs.overall.strengthsWinner)!=null&&Aa.length||(Oa=cs.overall.weaknessesLoser)!=null&&Oa.length?jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 text-sm",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"font-medium mb-1",children:"Winner strengths"}),jsxRuntimeExports.jsx("ul",{className:"text-muted-foreground list-disc list-inside space-y-0.5",children:(cs.overall.strengthsWinner??[]).map((Ia,La)=>jsxRuntimeExports.jsx("li",{children:Ia},La))})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"font-medium mb-1",children:"Loser weaknesses"}),jsxRuntimeExports.jsx("ul",{className:"text-muted-foreground list-disc list-inside space-y-0.5",children:(cs.overall.weaknessesLoser??[]).map((Ia,La)=>jsxRuntimeExports.jsx("li",{children:Ia},La))})]})]}):null,cs.perEval.length>0&&jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Per eval"}),cs.perEval.map((Ia,La)=>jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[jsxRuntimeExports.jsx(Badge,{variant:Ia.winnerTargetId?"default":"secondary",className:"font-mono text-xs shrink-0",children:ja(Ia.winnerTargetId)??"TIE"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"font-mono",children:Ia.evalName}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-xs",children:Ia.reasoning})]})]},La))]})]})]})]},cs.id)})]}):jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["No comparisons yet. Run"," ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric evals compare <target-a> <target-b>"})," ","to create one."]})}function ComparisonRawOutput({id:es}){const{data:$,isLoading:ts}=useEvalComparison(es);return ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-16 w-full"}):jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:"Judge output (not parseable as a structured verdict)"}),jsxRuntimeExports.jsx("pre",{className:"text-xs bg-muted p-3 rounded-md overflow-x-auto max-h-48 whitespace-pre-wrap",children:($==null?void 0:$.rawOutput)??"No raw output recorded."})]})}function PublicDocsShell({children:es}){return jsxRuntimeExports.jsxs("div",{className:"min-h-screen bg-background text-foreground",children:[jsxRuntimeExports.jsx("nav",{className:"sticky top-0 z-50 border-b border-border bg-background/80 backdrop-blur-sm",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl flex items-center justify-between px-4 h-14",children:[jsxRuntimeExports.jsxs(Link,{to:"/",className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:"h-2 w-2 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-semibold",children:"RuleMetric"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",className:"cursor-pointer",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/login",children:"Sign in"})}),jsxRuntimeExports.jsx(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/signup",children:"Get Started"})})]})]})}),jsxRuntimeExports.jsx("main",{className:"mx-auto max-w-6xl px-4 py-8",children:es})]})}function DocsRoute(){const{session:es,loading:$}=useAuth();return $?jsxRuntimeExports.jsx("div",{className:"flex h-screen items-center justify-center",children:jsxRuntimeExports.jsxs("div",{className:"space-y-4 w-64",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-1/2"})]})}):es?jsxRuntimeExports.jsx(RootLayout,{children:jsxRuntimeExports.jsx(DocsPage,{})}):jsxRuntimeExports.jsx(PublicDocsShell,{children:jsxRuntimeExports.jsx(DocsPage,{})})}function useHarnessReleases(es,$=50){const ts=new URLSearchParams;return ts.set("harness",es),ts.set("limit",String($)),useQuery({queryKey:["harness-releases",es,$],queryFn:()=>apiGet(`/api/harness-releases?${ts}`)})}function useSyncHarnessReleases(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/harness-releases/sync",{harness:$}),onSuccess:()=>es.invalidateQueries({queryKey:["harness-releases"]})})}function AnalysisFreshnessBanner({freshness:es,totalAnalyzed:$}){if(!es||$===0)return null;const{with_timestamp:ts,pre_instrumentation:is,stale_30d:cs,oldest_analyzed_at:Qr}=es,ja=$>0?Math.round(is/$*100):0,Na=ts>0?Math.round(cs/ts*100):0;if(is===0&&cs===0)return null;const Aa=ja>=25||Na>=50?"warn":"info",Oa=Aa==="warn"?"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-300":"border-border bg-muted/40 text-muted-foreground";return jsxRuntimeExports.jsxs("div",{className:`flex items-start gap-2 rounded-md border px-3 py-2 text-xs ${Oa}`,children:[Aa==="warn"?jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 shrink-0 mt-0.5"}):jsxRuntimeExports.jsx(Clock,{className:"h-4 w-4 shrink-0 mt-0.5"}),jsxRuntimeExports.jsxs("div",{className:"flex-1 font-mono space-y-0.5",children:[jsxRuntimeExports.jsx("p",{className:"font-medium",children:Aa==="warn"?"Some inputs to these stats are stale or untimestamped":"Input freshness"}),jsxRuntimeExports.jsxs("p",{children:[is>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[is," of ",$," analyzed sessions (",ja,"%) predate timestamp tracking. Re-analyze them to participate in freshness checks."]}),is>0&&cs>0&&" ",cs>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[cs," of ",ts," timestamped analyses (",Na,"%) are over 30 days old",Qr&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" ","(oldest: ",new Date(Qr).toLocaleDateString(),")"]}),"."]})]})]})]})}function jobStepLabel(es){const $=es.progress;return $!=null&&$.step&&($!=null&&$.current)&&($!=null&&$.total)?`${$.step} (${$.current}/${$.total})`:$!=null&&$.step?$.step:es.status==="claimed"?"starting...":es.status==="pending"?"queued":es.status}function JobStatusIcon({status:es}){switch(es){case"completed":return jsxRuntimeExports.jsx(CircleCheck,{className:"h-3.5 w-3.5 text-teal-500 shrink-0"});case"running":case"claimed":return jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3.5 w-3.5 text-blue-500 animate-spin shrink-0"});case"failed":return jsxRuntimeExports.jsx(CircleX,{className:"h-3.5 w-3.5 text-red-500 shrink-0"});case"pending":default:return jsxRuntimeExports.jsx(CircleDashed,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})}}function JobTracker({jobs:es}){if(es.length===0)return null;const $=es.filter(La=>La.status==="completed").length,ts=es.filter(La=>La.status==="failed").length,is=es.filter(La=>La.status==="running"||La.status==="claimed").length,cs=es.filter(La=>La.status==="pending").length,Qr=es.length,ja=$+ts,Na=ja===Qr,Aa=$/Qr*100,Oa=ts/Qr*100,Ia=is/Qr*100;return jsxRuntimeExports.jsx(Card,{className:Na?"border-teal-500/30 bg-teal-500/5":"border-blue-500/30 bg-blue-500/5",children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-4 pb-4 space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[Na?jsxRuntimeExports.jsx(Check,{className:"h-4 w-4 text-teal-500"}):jsxRuntimeExports.jsx(LoaderCircle,{className:"h-4 w-4 animate-spin text-blue-500"}),jsxRuntimeExports.jsx("p",{className:"min-w-0 break-words text-sm font-medium",children:Na?Qr===1?"Recommendations ready":`All ${Qr} projects done`:Qr===1?`Generating recommendations — ${jobStepLabel(es[0])}`:`Generating recommendations — ${ja}/${Qr} complete`})]}),Qr>1&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted-foreground font-mono",children:[$>0&&jsxRuntimeExports.jsxs("span",{className:"text-teal-500",children:[$," done"]}),is>0&&jsxRuntimeExports.jsxs("span",{className:"text-blue-500",children:[is," running"]}),cs>0&&jsxRuntimeExports.jsxs("span",{children:[cs," queued"]}),ts>0&&jsxRuntimeExports.jsxs("span",{className:"text-red-500",children:[ts," failed"]})]})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden flex",children:Qr===1?(()=>{const La=es[0],Ba=La.progress,Ma=Ba!=null&&Ba.current&&(Ba!=null&&Ba.total)?Ba.current/Ba.total*100:0;return La.status==="completed"?jsxRuntimeExports.jsx("div",{className:"h-full bg-teal-500",style:{width:"100%"}}):La.status==="failed"?jsxRuntimeExports.jsx("div",{className:"h-full bg-red-500",style:{width:"100%"}}):jsxRuntimeExports.jsx("div",{className:"h-full bg-blue-500 animate-pulse transition-all duration-500",style:{width:`${Math.max(Ma,5)}%`}})})():jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Aa>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-teal-500 transition-all duration-500",style:{width:`${Aa}%`}}),Oa>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-red-500 transition-all duration-500",style:{width:`${Oa}%`}}),Ia>0&&jsxRuntimeExports.jsx("div",{className:"h-full bg-blue-500 animate-pulse transition-all duration-500",style:{width:`${Ia}%`}})]})}),Qr>1&&jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-x-6 gap-y-1",children:es.map(La=>jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-2 py-0.5 text-xs",children:[jsxRuntimeExports.jsx(JobStatusIcon,{status:La.status}),jsxRuntimeExports.jsx("span",{className:"min-w-0 flex-1 truncate font-mono",children:La.projectPath??"global"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground ml-auto shrink-0",children:La.status==="running"||La.status==="claimed"?jobStepLabel(La):La.status==="failed"?"error":La.status==="completed"?"done":"queued"})]},La.id))})]})})}function ProjectJobBadge({job:es}){return es.status==="completed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-teal-500/10 text-teal-500 border-teal-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"mr-1 h-2.5 w-2.5"})," done"]}):es.status==="failed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-red-500/10 text-red-500 border-red-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleX,{className:"mr-1 h-2.5 w-2.5"})," failed"]}):es.status==="running"||es.status==="claimed"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-blue-500/10 text-blue-500 border-blue-500/20 font-mono",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-1 h-2.5 w-2.5 animate-spin"})," ",jobStepLabel(es)]}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-amber-500/10 text-amber-500 border-amber-500/20 font-mono",children:[jsxRuntimeExports.jsx(CircleDashed,{className:"mr-1 h-2.5 w-2.5"})," queued"]})}function WorkerOfflineBanner(){const{workers:es,isLoading:$}=useWorkerStatus("cli-worker");if($)return null;const ts=es.slice().sort((Qr,ja)=>new Date(ja.lastHeartbeat).getTime()-new Date(Qr.lastHeartbeat).getTime())[0];if((ts==null?void 0:ts.status)==="active")return null;const cs=ts?`${Math.round((Date.now()-new Date(ts.lastHeartbeat).getTime())/1e3)}s ago`:"never";return jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-sm",children:[jsxRuntimeExports.jsx("div",{className:"font-medium text-amber-500 mb-1",children:"Worker offline"}),jsxRuntimeExports.jsxs("div",{className:"text-muted-foreground",children:["No cli-worker has heartbeat'd within the last 60s (last seen: ",cs,"). Insights jobs will queue but won't run until the worker is healthy. Restart with"," ",jsxRuntimeExports.jsx("code",{className:"font-mono text-xs bg-secondary px-1 py-0.5 rounded",children:"launchctl kickstart -k gui/$UID/com.rulemetric.worker"}),"."]})]})}function formatCompact(es){return new Intl.NumberFormat("en-US",{notation:"compact",maximumFractionDigits:1}).format(es)}function parseTimestamp(es){if(!es)return null;const $=es.replace(" ","T").replace(/([+-]\d{2})$/,"$1:00"),ts=new Date($);return Number.isNaN(ts.getTime())?null:ts}function formatSessionRange(es,$){const ts=parseTimestamp(es),is=parseTimestamp($),cs={month:"short",day:"numeric",year:"numeric"};if(ts&&is){const ja=ts.getFullYear()===is.getFullYear();return`${ts.toLocaleDateString(void 0,ja?{month:"short",day:"numeric"}:cs)} – ${is.toLocaleDateString(void 0,cs)}`}const Qr=ts??is;return Qr?Qr.toLocaleDateString(void 0,cs):null}function outcomeScore(es){const $=(es.achieved??0)+(es.mostly_achieved??0),ts=Object.values(es).reduce((is,cs)=>is+cs,0);return ts?Math.round($/ts*100):null}function InsightsOverview({computed:es}){var Na;const $=outcomeScore(es.outcomes??{}),ts=es.total_sessions?Math.round(es.sessions_with_analysis/es.total_sessions*100):0,is=Object.entries(es.friction??{}).sort((Aa,Oa)=>Oa[1]-Aa[1])[0],cs=Object.entries(es.tool_counts??{}).sort((Aa,Oa)=>Oa[1]-Aa[1]).slice(0,5),Qr=((Na=cs[0])==null?void 0:Na[1])??1,ja=[{label:"Successful outcomes",value:$==null?"—":`${$}%`,detail:`${es.sessions_with_analysis} analyzed`,icon:CircleCheck},{label:"Estimated spend",value:`$${(es.estimated_cost_usd??0).toFixed(2)}`,detail:`${formatCompact(es.total_input_tokens+es.total_output_tokens)} tokens`,icon:DollarSign},{label:"Tool errors",value:es.total_tool_errors.toLocaleString(),detail:`${es.total_interruptions} interruptions`,icon:TriangleAlert},{label:"Code changed",value:`+${formatCompact(es.total_lines_added)}`,detail:`${formatCompact(es.total_lines_removed)} removed · ${es.git_commits} commits`,icon:TrendingUp}];return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:ja.map(({label:Aa,value:Oa,detail:Ia,icon:La})=>jsxRuntimeExports.jsx(Card,{className:"min-w-0",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"text-xs font-medium uppercase tracking-wide",children:Aa}),jsxRuntimeExports.jsx(La,{className:"h-4 w-4"})]}),jsxRuntimeExports.jsx("p",{className:"mt-3 text-2xl font-mono font-semibold",children:Oa}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:Ia})]})},Aa))}),es.truncated&&jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-1.5 text-xs text-amber-600",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3 shrink-0"}),"Computed from your 500 most-recent sessions — spend and token totals are a floor, not a complete sum."]}),jsxRuntimeExports.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[jsxRuntimeExports.jsxs(Card,{className:"min-w-0 lg:col-span-2",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"What is slowing work down?"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[Object.entries(es.friction??{}).sort((Aa,Oa)=>Oa[1]-Aa[1]).slice(0,5).map(([Aa,Oa])=>{const Ia=Math.max(1,Object.values(es.friction).reduce((La,Ba)=>La+Ba,0));return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"mb-1 flex min-w-0 justify-between gap-2 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"min-w-0 break-words",children:Aa.replace(/_/g," ")}),jsxRuntimeExports.jsx("span",{className:"shrink-0 font-mono text-muted-foreground",children:Oa})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 overflow-hidden rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-full rounded-full bg-amber-500",style:{width:`${Math.max(4,Oa/Ia*100)}%`}})})]},Aa)}),!is&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No friction has been detected in analyzed sessions."})]})]}),jsxRuntimeExports.jsxs(Card,{className:"min-w-0",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-base flex items-center gap-2",children:[jsxRuntimeExports.jsx(Wrench,{className:"h-4 w-4"})," Most-used tools"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:cs.map(([Aa,Oa])=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-xs",children:Aa}),jsxRuntimeExports.jsx("div",{className:"h-1.5 w-20 overflow-hidden rounded-full bg-muted",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary",style:{width:`${Oa/Qr*100}%`}})}),jsxRuntimeExports.jsx("span",{className:"w-10 text-right font-mono text-xs text-muted-foreground",children:Oa})]},Aa))})]})]}),ts<80&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Analysis coverage is ",ts,"%. Outcome and friction metrics reflect ",es.sessions_with_analysis," of ",es.total_sessions," sessions."]})]})}function ProjectCard({project:es,hasReport:$,activeJob:ts,onClick:is}){const cs=formatSessionRange(es.firstSession,es.lastSession);return jsxRuntimeExports.jsxs(Card,{className:"min-w-0 cursor-pointer hover:border-primary/50 transition-colors",...activatable(is),children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntimeExports.jsx(CardTitle,{className:"min-w-0 break-words text-base font-mono",children:es.name}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 sm:shrink-0",children:[ts?jsxRuntimeExports.jsx(ProjectJobBadge,{job:ts}):$?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs bg-teal-500/10 text-teal-500 border-teal-500/20",children:"Recommendations"}):null,jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-xs",children:[es.enrichedCount," enriched"]})]})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-6 gap-y-1 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:[es.sessionCount," sessions"]}),es.analyzedCount>0&&jsxRuntimeExports.jsxs("span",{children:[es.analyzedCount," analyzed"]})]}),cs&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:cs})]})]})}function ReleaseCategorySection({label:es,items:$,colorClass:ts}){const[is,cs]=reactExports.useState(!1);return $.length===0?null:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>cs(!is),className:"flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors w-full text-left cursor-pointer",children:[is?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3.5 w-3.5 shrink-0"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3.5 w-3.5 shrink-0"}),jsxRuntimeExports.jsx("span",{className:ts,children:es}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",$.length,")"]})]}),is&&jsxRuntimeExports.jsx("ul",{className:"mt-1.5 ml-5 space-y-1",children:$.map((Qr,ja)=>jsxRuntimeExports.jsx("li",{className:"text-xs text-muted-foreground leading-relaxed",children:Qr},ja))})]})}function ReleaseCard({release:es}){var ja,Na,Aa;const $=es.categories??{features:[],fixes:[],security:[]},ts=((ja=$.features)==null?void 0:ja.length)??0,is=((Na=$.fixes)==null?void 0:Na.length)??0,cs=((Aa=$.security)==null?void 0:Aa.length)??0,Qr=new Date(es.publishedAt).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"});return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{className:"pb-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-base font-mono",children:es.version}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:Qr})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[ts>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-teal-500/10 text-teal-500 border-teal-500/20",children:[ts," feature",ts!==1?"s":""]}),is>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-amber-500/10 text-amber-500 border-amber-500/20",children:[is," fix",is!==1?"es":""]}),cs>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-red-500/10 text-red-500 border-red-500/20",children:[cs," security"]})]})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-2",children:[jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Features",items:$.features??[],colorClass:"text-teal-500"}),jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Fixes",items:$.fixes??[],colorClass:"text-amber-500"}),jsxRuntimeExports.jsx(ReleaseCategorySection,{label:"Security",items:$.security??[],colorClass:"text-red-500"}),es.url&&jsxRuntimeExports.jsx("div",{className:"pt-1 flex justify-end",children:jsxRuntimeExports.jsxs("a",{href:es.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["View release ",jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]})})]})]})}function HarnessUpdatesTab(){const{data:es,isLoading:$}=useHarnessReleases("claude_code"),ts=useSyncHarnessReleases();return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-mono font-semibold",children:"Claude Code Releases"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Changelog from the Claude Code GitHub repository"})]}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",onClick:()=>ts.mutate("claude_code"),disabled:ts.isPending,className:"cursor-pointer",children:[ts.isPending?jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-3.5 w-3.5 animate-spin"}):jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-3.5 w-3.5"}),"Sync"]})]}),ts.isSuccess&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["Synced ",ts.data.synced," new release",ts.data.synced!==1?"s":""," (",ts.data.total," total checked)"]}),$?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[...Array(4)].map((is,cs)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-32"},cs))}):!es||es.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"text-center space-y-4 py-8",children:[jsxRuntimeExports.jsx(Package,{className:"h-12 w-12 mx-auto text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-semibold",children:"No releases synced yet"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Click Sync to fetch the latest releases from GitHub."})]})]})})}):jsxRuntimeExports.jsx("div",{className:"space-y-3",children:es.map(is=>jsxRuntimeExports.jsx(ReleaseCard,{release:is},is.id))})]})}function InsightsListPage(){const[es,$]=useTabParam(["overview","harness-updates"],"overview"),ts=useNavigate(),{data:is,isLoading:cs}=useComputedInsights(),{data:Qr}=useInsightsProjects(),ja=useRegenerateAllInsights(),Na=useActiveInsightsJobs(),{data:Aa}=useInsightsJobs(void 0,500),Oa=(Aa??[]).filter(Fa=>Fa.status!=="cancelled"),Ia=(()=>{if(Oa.length<2)return[];const Fa=[...Oa].sort((Ka,Ga)=>new Date(Ka.createdAt).getTime()-new Date(Ga.createdAt).getTime());let Ha=[];for(let Ka=0;Ka<Fa.length;Ka++){const Ga=new Date(Fa[Ka].createdAt).getTime(),Va=Fa.filter(Ja=>new Date(Ja.createdAt).getTime()-Ga<12e4&&new Date(Ja.createdAt).getTime()>=Ga);Va.length>Ha.length&&(Ha=Va)}return Ha.length<2?[]:Ha})(),La=Ia.length>1,Ba=new Map;for(const Fa of Ia)Fa.projectPath&&!Ba.has(Fa.projectPath)&&Ba.set(Fa.projectPath,Fa);const Ma=new Set(Oa.filter(Fa=>Fa.status==="completed"&&Fa.projectPath).map(Fa=>Fa.projectPath)),qa=Fa=>{if(Fa.errors.length>0&&ue$1.error(`${Fa.errors.length} project${Fa.errors.length===1?"":"s"} failed to enqueue`,{description:`${Fa.errors[0].projectPath}: ${Fa.errors[0].error}`}),Fa.created>0){ue$1.success(`Started ${Fa.created} regeneration job${Fa.created===1?"":"s"}`,Fa.noLiveWorker?{description:"No live worker — start `rulemetric evals agent` to run them."}:void 0);return}const Ha=Fa.skipped.filter(Ga=>Ga.reason==="fresh").length,Ka=Fa.skipped.length-Ha;Ha>0?ue$1(Ka>0?`${Ha} project${Ha===1?"":"s"} fresh (<4h), ${Ka} skipped`:`All ${Ha} project${Ha===1?" is":"s are"} fresh (regenerated <4h ago)`,{action:{label:"Force regenerate",onClick:()=>ja.mutate({force:!0},{onSuccess:qa,onError:Ga=>ue$1.error("Couldn't start the regeneration",{description:Ga instanceof Error?Ga.message:"Please try again."})})}}):Ka>0?ue$1(`${Ka} project${Ka===1?"":"s"} skipped (no checkout or too few sessions)`):Fa.errors.length===0&&ue$1("No projects eligible for regeneration")};return cs?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]}),jsxRuntimeExports.jsx("div",{className:"space-y-4",children:[...Array(3)].map((Fa,Ha)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-28"},Ha))})]}):!is||is.total_sessions===0?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Claude Code session analytics and AI-powered recommendations"})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"harness-updates",children:[jsxRuntimeExports.jsx(Package,{className:"h-4 w-4"}),"Harness Updates"]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"overview",className:"space-y-4 pt-2",children:jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"text-center space-y-4 py-8",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-12 w-12 mx-auto text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h3",{className:"text-lg font-semibold",children:"No sessions captured yet"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground max-w-md mx-auto mt-2",children:["Run ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"rulemetric hooks install"})," in a project to start capturing Claude Code sessions. Insights will appear automatically after your next session."]})]})]})})})}),jsxRuntimeExports.jsx(TabsContent,{value:"harness-updates",className:"pt-2",children:jsxRuntimeExports.jsx(HarnessUpdatesTab,{})})]})]}):jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-6",children:[jsxRuntimeExports.jsx(WorkerOfflineBanner,{}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Insights"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Claude Code session analytics and AI-powered recommendations"})]}),jsxRuntimeExports.jsx("div",{className:"flex items-center gap-2 sm:shrink-0",children:jsxRuntimeExports.jsx(Button,{onClick:()=>ja.mutate(void 0,{onSuccess:qa,onError:Fa=>ue$1.error("Couldn't start the regeneration",{description:Fa instanceof Error?Fa.message:"Please try again."})}),disabled:ja.isPending||Na.length>0,className:"w-full cursor-pointer sm:w-auto",children:Na.length>0?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating (",Na.length," remaining)..."]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(RefreshCw,{className:"mr-2 h-4 w-4"}),"Regenerate All"]})})})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"harness-updates",children:[jsxRuntimeExports.jsx(Package,{className:"h-4 w-4"}),"Harness Updates"]})]}),jsxRuntimeExports.jsxs(TabsContent,{value:"overview",className:"space-y-4 pt-2",children:[La&&jsxRuntimeExports.jsx(JobTracker,{jobs:Ia}),(is==null?void 0:is.analysis_freshness)&&jsxRuntimeExports.jsx(AnalysisFreshnessBanner,{freshness:is.analysis_freshness,totalAnalyzed:is.sessions_with_analysis}),jsxRuntimeExports.jsxs("div",{className:"space-y-5",children:[jsxRuntimeExports.jsx(InsightsOverview,{computed:is}),jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>ts("/insights/computed"),className:"text-sm font-medium text-primary hover:underline cursor-pointer",children:"Explore detailed trends and recommendations →"}),Qr&&Qr.length>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-mono font-semibold text-muted-foreground pt-2",children:"By Project"}),Qr.filter(Fa=>Fa.sessionCount>=3).map(Fa=>{const Ha=Ma.has(Fa.projectPath),Ka=Ba.get(Fa.projectPath),Ga=Fa.projectId??void 0,Va=Ga?`/insights/computed?projectPath=${encodeURIComponent(Fa.projectPath)}&projectId=${encodeURIComponent(Ga)}`:`/insights/computed?projectPath=${encodeURIComponent(Fa.projectPath)}`;return jsxRuntimeExports.jsx(ProjectCard,{project:Fa,hasReport:Ha,activeJob:Ka,onClick:()=>ts(Va)},Ga??Fa.projectPath)})]})]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"harness-updates",className:"pt-2",children:jsxRuntimeExports.jsx(HarnessUpdatesTab,{})})]})]})}function RecEntryControls({item:es,projectPath:$}){const ts=useDismissRecommendation();return es.id?jsxRuntimeExports.jsxs("span",{className:"flex items-center gap-1 shrink-0",children:[(es.timesGenerated??1)>1&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-muted-foreground",title:`This exact advice has been generated by ${es.timesGenerated} separate insights runs. Dismissing it stops the repetition for 90 days.`,"data-testid":"rec-seen-count",children:["seen ×",es.timesGenerated]}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"cursor-pointer h-6 w-6 p-0 text-muted-foreground",title:"Dismiss — hidden for 90 days",disabled:ts.isPending,"data-testid":"rec-dismiss",onClick:()=>ts.mutate({contentHash:es.id,projectPath:$},{onError:is=>ue$1.error(is.message)}),children:jsxRuntimeExports.jsx(X$1,{className:"h-3 w-3"})})]}):null}function RecommendationCandidates({items:es=[]}){return es.length?jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Proposals from session evidence"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"These proposals have not demonstrated a performance improvement. Inspect the source work and test the proposed remedy before adopting it."}),es.map(($,ts)=>jsxRuntimeExports.jsxs("article",{className:"rounded-lg border border-border p-3 space-y-2","data-testid":"evidence-proposal",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-2",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("h3",{className:"font-medium break-words",children:$.title}),jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Proposed · ",$.artifact]})]}),jsxRuntimeExports.jsx(CopyButton$2,{text:$.canonicalBody})]}),jsxRuntimeExports.jsx("p",{className:"text-sm break-words",children:$.rationale}),jsxRuntimeExports.jsx("ul",{className:"space-y-2 text-sm",children:$.evidence.map((is,cs)=>jsxRuntimeExports.jsxs("li",{className:"break-words",children:[is.sessionId&&/^[a-f0-9-]{36}$/i.test(is.sessionId)&&jsxRuntimeExports.jsx(Link,{className:"underline text-primary",to:`/sessions/${encodeURIComponent(is.sessionId)}`,children:"Source session"}),jsxRuntimeExports.jsx("p",{children:is.finding})]},cs))}),jsxRuntimeExports.jsxs("p",{className:"text-sm",children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:"Proposed outcome check: "}),$.outcomeMetric]}),jsxRuntimeExports.jsxs("details",{children:[jsxRuntimeExports.jsx("summary",{className:"cursor-pointer text-sm",children:"View proposed content"}),jsxRuntimeExports.jsx("pre",{className:"mt-2 whitespace-pre-wrap break-words rounded bg-muted p-3 text-xs",children:$.canonicalBody})]})]},$.id??ts))]})]}):null}function verdictState(es){return es.sufficient?es.significant?"significant":"no-effect":(es.strataDroppedForTimeSeparation??0)>0?"no-comparable-cohort":"insufficient"}function VerdictBadge({verdict:es}){const $=`95% CI ${(es.ci.lower*100).toFixed(0)}–${(es.ci.upper*100).toFixed(0)}%`,ts=`n=${es.nWith}`,is=es.strata!=null?` · within ${es.strata} project${es.strata===1?"":"s"}`:"",cs=es.confounded?` · observational${is}`:"",Qr=verdictState(es);if(Qr==="no-comparable-cohort"){const Oa=es.strataDroppedForTimeSeparation;return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`No comparable cohort. ${Oa} project-month${Oa===1?"":"s"} held both exposed and unexposed sessions, but they're separated in time — this treatment's sessions all ran later than the ones without it, so any difference is a calendar difference, not an effect. More sessions won't resolve it; a randomised holdout would.`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-amber-400 border-amber-400/40",children:"no comparable cohort"})})}if(Qr==="insufficient")return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Not enough sessions to measure this yet, so no number is shown (rather than a fabricated one).${es.insufficientReason?` ${es.insufficientReason}`:""}`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-muted-foreground",children:"insufficient data"})});if(Qr==="no-effect")return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`The with-vs-without difference isn't statistically distinguishable from zero, so we report no effect rather than noise. ${$}, ${ts}${cs}.`,children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-muted-foreground",children:"no measured effect"})});const ja=es.delta>0,Na=`${ja?"+":""}${(es.delta*100).toFixed(0)}%`,Aa=es.pValue!=null?`, p=${es.pValue.toFixed(3)}`:"";return jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Sessions with this ${ja?"did measurably BETTER":"did measurably WORSE"} than sessions without it, and the difference is statistically significant. ${$}, ${ts}${Aa}${cs}. Observational — a correlation from real sessions, not a controlled experiment.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("text-[10px] font-mono shrink-0",ja?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40"),children:[Na," outcome"]})})}function SessionsTab({data:es}){return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[Object.keys(es.projects).length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono",children:["Projects (",Object.keys(es.projects).length,")"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:es.projects})})]}),es.session_summaries.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono",children:["Sessions with Analysis (",es.session_summaries.length,")"]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:es.session_summaries.map($=>{const ts=$.id.length===36&&$.id.includes("-"),is=jsxRuntimeExports.jsxs("div",{className:`flex items-start gap-3 rounded-lg border border-border bg-background p-3 ${ts?"hover:border-primary/50 cursor-pointer":""}`,children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs shrink-0",children:$.date}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"text-sm truncate",children:$.summary||$.goal||"No summary"}),$.goal&&$.summary&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:$.goal}),"outcome"in $&&$.outcome&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"mt-1 text-[10px]",children:friendlyLabel($.outcome)})]})]});return ts?jsxRuntimeExports.jsx(Link,{to:`/sessions/${$.id}`,children:is},$.id):jsxRuntimeExports.jsx("div",{children:is},$.id)})})})]})]})}function RecommendationsTab({rec:es,projectPath:$,autoAddAvailable:ts}){var ja,Na,Aa,Oa,Ia,La;const is=useAutoAddSuggestion(),[cs,Qr]=reactExports.useState(new Set);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[es.at_a_glance&&jsxRuntimeExports.jsxs(Card,{className:"border-amber-500/30 bg-amber-500/5",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Sparkles,{className:"h-4 w-4 text-amber-500"}),"At a Glance"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:Object.entries(es.at_a_glance).map(([Ba,Ma])=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-semibold text-muted-foreground uppercase tracking-wide mb-1",children:Ba.replace(/_/g," ")}),jsxRuntimeExports.jsx("p",{className:"text-sm",children:Ma})]},Ba))})]}),((ja=es.what_works)==null?void 0:ja.impressive_workflows)&&es.what_works.impressive_workflows.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Impressive Things You Did"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.what_works.impressive_workflows.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.title}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.description})]},Ma))})]}),((Na=es.friction_analysis)==null?void 0:Na.categories)&&es.friction_analysis.categories.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 text-amber-500"}),"Where Things Go Wrong"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.friction_analysis.categories.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.category}),jsxRuntimeExports.jsx(RecEntryControls,{item:Ba,projectPath:$})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.description}),Ba.examples.length>0&&jsxRuntimeExports.jsx("ul",{className:"mt-2 space-y-1",children:Ba.examples.map((qa,Fa)=>jsxRuntimeExports.jsx("li",{className:"text-xs text-muted-foreground pl-3 border-l-2 border-border",children:qa},Fa))})]},Ba.id??Ma))})]}),((Aa=es.suggestions)==null?void 0:Aa.features_to_try)&&es.suggestions.features_to_try.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"h-4 w-4 text-blue-500"}),"Features to Try"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.features_to_try.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.feature}),Ba.example_code&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Ba.example_code}),jsxRuntimeExports.jsx(CopyButton$2,{text:Ba.example_code})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.why_for_you}),Ba.example_code&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Ba.example_code})]},Ma))})]}),jsxRuntimeExports.jsx(RecommendationCandidates,{items:es.recommendation_candidates}),((Oa=es.suggestions)==null?void 0:Oa.claude_md_additions)&&es.suggestions.claude_md_additions.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Suggested CLAUDE.md Additions"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.claude_md_additions.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono bg-muted px-2 py-1 rounded flex-1 overflow-x-auto",children:Ba.addition}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RecEntryControls,{item:Ba,projectPath:$}),jsxRuntimeExports.jsx(CopyButton$2,{text:Ba.addition}),$&&ts&&jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"cursor-pointer h-7 text-xs",disabled:cs.has(Ma)||is.isPending,onClick:qa=>{qa.stopPropagation(),is.mutate({projectPath:$,addition:Ba.addition,why:Ba.why},{onSuccess:Fa=>{(Fa.success||Fa.reason==="already_present")&&Qr(Ha=>new Set(Ha).add(Ma))},onError:Fa=>{const Ha=Fa instanceof ApiError&&(Fa.code==="not_local_mode"||Fa.statusCode===501);ue$1.error(Ha?"Add to CLAUDE.md only works when the API runs on your machine (local mode) — use the copy button instead.":Fa instanceof Error?Fa.message:"Failed to update CLAUDE.md")}})},children:is.isPending?jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}):cs.has(Ma)?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3 text-teal-500"}):jsxRuntimeExports.jsx(Upload,{className:"h-3 w-3"})})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:Ba.why}),cs.has(Ma)&&jsxRuntimeExports.jsx("p",{className:"text-xs text-teal-500 mt-1",children:"Added to CLAUDE.md"})]},Ma))})]}),((Ia=es.suggestions)==null?void 0:Ia.usage_patterns)&&es.suggestions.usage_patterns.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"h-4 w-4 text-cyan-500"}),"Usage Patterns"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.suggestions.usage_patterns.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.title}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[Ba.copyable_prompt&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Ba.copyable_prompt}),jsxRuntimeExports.jsx(CopyButton$2,{text:Ba.copyable_prompt})]}),jsxRuntimeExports.jsx(RecEntryControls,{item:Ba,projectPath:$})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.suggestion}),Ba.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Ba.copyable_prompt})]},Ba.id??Ma))})]}),((La=es.on_the_horizon)==null?void 0:La.opportunities)&&es.on_the_horizon.opportunities.length>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-2",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"h-4 w-4 text-pink-500"}),"On the Horizon"]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:es.on_the_horizon.opportunities.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:Ba.title}),Ba.copyable_prompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Ba.copyable_prompt}),jsxRuntimeExports.jsx(CopyButton$2,{text:Ba.copyable_prompt})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ba.whats_possible}),Ba.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto",children:Ba.copyable_prompt})]},Ma))})]}),es.fun_ending&&jsxRuntimeExports.jsx(Card,{className:"border-pink-500/20 bg-pink-500/5",children:jsxRuntimeExports.jsxs(CardContent,{className:"pt-6",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:es.fun_ending.headline}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:es.fun_ending.detail})]})})]})}function ScorePair({label:es,withVal:$,withoutVal:ts,delta:is,unit:cs,inverted:Qr}){const ja=Oa=>Oa!=null?`${Oa}${cs}`:"—",Na=is!=null&&is!==0?(Qr?is<0:is>0)?"text-teal-500":"text-red-500":"text-muted-foreground",Aa=is!=null&&is>0?"+":"";return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:es}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"font-mono",children:ja($)}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"vs"}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:ja(ts)})]}),is!=null&&is!==0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:`text-[10px] mt-1 ${Na} ${(Qr?is<0:is>0)?"bg-teal-500/10 border-teal-500/20":"bg-red-500/10 border-red-500/20"}`,children:[Aa,is,cs]})]})}function SegmentLine({title:es,noun:$,segments:ts}){if(!ts||ts.length===0)return null;const is=ts.filter(Qr=>Qr.verdict.sufficient),cs=ts.length-is.length;return is.length===0&&cs===0?null:jsxRuntimeExports.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"text-[10px] text-muted-foreground mr-0.5",children:es}),is.map(Qr=>{const ja=Qr.verdict,Na=ja.delta>0,Aa=ja.significant?`${Na?"+":""}${(ja.delta*100).toFixed(0)}%`:"no effect",Oa=ja.significant?Na?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40":"text-muted-foreground",Ia=`95% CI ${(ja.ci.lower*100).toFixed(0)}–${(ja.ci.upper*100).toFixed(0)}%, n=${ja.nWith} exposed / ${ja.nWithout} unexposed (observational)`;return jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("text-[10px] font-mono",Oa),title:Ia,children:[Qr.label," ",Aa]},Qr.label)}),cs>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-muted-foreground",title:`Not enough exposed + unexposed sessions within a project to measure ${cs===1?`this ${$}`:`these ${$}s`} yet.`,children:[cs," ",$,cs===1?"":"s",": insufficient"]})]})}function SegmentBreakdown({impact:es}){const $=(es.segments??[]).map(is=>({label:is.model,verdict:is.verdict})),ts=(es.harnessSegments??[]).map(is=>({label:is.harness,verdict:is.verdict}));return $.length===0&&ts.length===0?null:jsxRuntimeExports.jsxs("div",{className:"mt-3 pt-3 border-t",children:[jsxRuntimeExports.jsx(SegmentLine,{title:"By model:",noun:"model",segments:$}),jsxRuntimeExports.jsx(SegmentLine,{title:"By harness:",noun:"harness",segments:ts})]})}function RandomisedBadges({randomised:es}){const $=ts=>ts.split("/").filter(Boolean).pop()??ts;return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[es.verdicts.map(ts=>jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`RANDOMISED verdict on ${ts.projectPath}: sessions were assigned to receive or not receive this instruction, and the ${ts.decision==="always"?"receiving":"withheld"} arm did measurably ${ts.decision==="always"?"better":"better without it"}. ${(ts.delta>0?"+":"")+(ts.delta*100).toFixed(0)}pp, 95% CI ${(ts.ciLower*100).toFixed(0)} to ${(ts.ciUpper*100).toFixed(0)}pp, n=${ts.nTreated}/${ts.nControl}. This supersedes the observational estimate for that project — assignment, not correlation.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:ts.decision==="always"?"text-[10px] font-mono shrink-0 text-teal-400 border-teal-400/40":"text-[10px] font-mono shrink-0 text-red-400 border-red-400/40","data-testid":"randomised-verdict-badge",children:["randomised · ",ts.delta>0?"+":"",(ts.delta*100).toFixed(0),"pp on ",$(ts.projectPath)]})},ts.projectPath)),es.experiments.map(ts=>jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Under randomised measurement on ${ts.projectPath} right now — injected to some sessions and withheld from the rest until the arms decide.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono shrink-0 text-muted-foreground","data-testid":"randomised-running-badge",children:["measuring · ",$(ts.projectPath)]})},ts.id))]})}function ImpactCard({impact:es,linkedSessions:$,source:ts}){const is=es.with,cs=es.without,Qr=es.comparison;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono truncate",children:es.instructionName}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[jsxRuntimeExports.jsx(ProvenanceBadge,{source:ts}),es.autoAdded&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-teal-400 border-teal-400/40",title:`Auto-added from a recommendation${es.autoAdded.count>1?` ×${es.autoAdded.count}`:""}`+(es.autoAdded.lastAssignedAt?` (last ${new Date(es.autoAdded.lastAssignedAt).toLocaleDateString()})`:"")+" — the verdict beside this is whether it helped.",children:["auto-added",es.autoAdded.count>1?` ×${es.autoAdded.count}`:""]}),es.randomised&&jsxRuntimeExports.jsx(RandomisedBadges,{randomised:es.randomised}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.verdict}),$!=null&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono",children:[$," sessions"]})]})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 text-xs",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:"Sessions"}),jsxRuntimeExports.jsxs("p",{className:"font-mono",children:[is.sessionCount," with / ",cs.sessionCount," without"]}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground mt-0.5",children:[is.enrichedCount," / ",cs.enrichedCount," enriched"]})]}),jsxRuntimeExports.jsx(ScorePair,{label:"Outcome Score",withVal:is.avgOutcomeScore,withoutVal:cs.avgOutcomeScore,delta:Qr.outcomeScoreDelta,unit:""}),jsxRuntimeExports.jsx(ScorePair,{label:"Tool Errors",withVal:is.avgToolErrors,withoutVal:cs.avgToolErrors,delta:Qr.toolErrorsDelta,unit:"",inverted:!0}),jsxRuntimeExports.jsx(ScorePair,{label:"Avg Duration",withVal:is.avgDurationMinutes,withoutVal:cs.avgDurationMinutes,delta:Qr.durationDelta,unit:"m",inverted:!0})]}),jsxRuntimeExports.jsx(SegmentBreakdown,{impact:es})]})]})}function InstructionImpactLoader({instructionId:es,linkedSessions:$,source:ts}){const{data:is,isLoading:cs}=useInstructionImpact(es);return cs?jsxRuntimeExports.jsx(Skeleton,{className:"h-24"}):!is||is.with.sessionCount===0&&is.without.sessionCount===0?null:jsxRuntimeExports.jsx(ImpactCard,{impact:is,linkedSessions:$,source:ts})}function GroomingCard(){const{data:es,isLoading:$}=useGroomCandidates(),ts=useArchiveInstruction(),is=useRestoreInstruction(),[cs,Qr]=reactExports.useState(new Set);if($||!es)return null;if(!es.captureHealthy)return jsxRuntimeExports.jsxs(Card,{className:"border-amber-500/30",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Grooming paused"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:es.reason})})]});const ja=es.harmful??[],Na=es.bloated??[],Aa=es.candidates.length+ja.length;if(Aa===0&&Na.length===0)return null;const Oa=La=>jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",className:"h-6 text-[10px] shrink-0",disabled:cs.has(La)||ts.isPending,onClick:()=>ts.mutate(La,{onSuccess:()=>{Qr(Ba=>new Set(Ba).add(La)),ue$1.success("Archived",{description:"Soft delete — this can be restored.",action:{label:"Undo",onClick:()=>is.mutate(La,{onSuccess:()=>{Qr(Ba=>{const Ma=new Set(Ba);return Ma.delete(La),Ma}),ue$1.success("Restored")},onError:()=>ue$1.error("Restore failed")})}})},onError:()=>ue$1.error("Archive failed")}),children:cs.has(La)?"Archived":"Archive"}),Ia=es.safetyGuarded+(es.harmfulSafetyGuarded??0);return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{className:"pb-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm",children:["Instructions worth a second look (",Aa+Na.length,")"]}),Ia>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-muted-foreground shrink-0",title:"Safety / destructive-guardrail rules are never proposed for retirement, however rarely they fire or however they score.",children:[Ia," safety rule",Ia===1?"":"s"," protected"]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Your own instructions worth a second look. Archiving is reversible; safety rules are never listed here."})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[Na.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-amber-400/90 mb-0.5",children:"Expensive, no measurable effect"}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:"Enough exposure to detect an effect and none was found — so these are candidates to SHORTEN, not to retire. Neutral means undetected, not worthless; the rule may carry something the outcome score cannot see. No archive button here on purpose."}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-64 overflow-y-auto",children:Na.map(La=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:La.name,children:La.name}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:La.verdict}),La.containsSafetyLanguage&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] border-amber-500/40 text-amber-400 shrink-0",title:"Contains destructive-command or credential guardrail language. Shown anyway — a trim changes nothing on its own — but preserve those lines when shortening.",children:"has guardrails"})]}),jsxRuntimeExports.jsxs("span",{className:"text-[10px] font-mono text-muted-foreground shrink-0",title:"Estimated from content length (chars/4), not a tokenizer count.",children:["~",La.estimatedTokens.toLocaleString()," tok/session"]})]},La.id))})]}),ja.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-red-400/90 mb-0.5",children:"Measurably worse outcomes"}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:"Present in sessions that scored significantly lower. Correlational, not proven cause — the rule may just ride along with harder tasks — so review before retiring; the verdict beside each shows the effect."}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-64 overflow-y-auto",children:ja.map(La=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:La.name,children:La.name}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:La.verdict})]}),Oa(La.id)]},La.id))})]}),es.candidates.length>0&&jsxRuntimeExports.jsxs("div",{children:[ja.length>0&&jsxRuntimeExports.jsx("p",{className:"text-[11px] font-medium text-muted-foreground mb-1.5",children:"No recent use"}),jsxRuntimeExports.jsx("div",{className:"space-y-1.5 max-h-80 overflow-y-auto",children:es.candidates.map(La=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono truncate",title:La.name,children:La.name}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] shrink-0 text-muted-foreground",children:La.reason})]}),Oa(La.id)]},La.id))})]})]})]})}function InstructionsTab({projectFilter:es}){const{data:$,isLoading:ts}=useLinkedInstructions(es);return ts?jsxRuntimeExports.jsx("div",{className:"space-y-3",children:[...Array(3)].map((is,cs)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},cs))}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx(GroomingCard,{}),!$||$.length===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No instructions linked to sessions yet. Instructions are auto-captured from context snapshots — the session-end hook snapshots your on-disk CLAUDE.md files, and the proxy additionally captures runtime-rendered prompts and skills."})})}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Instructions linked to sessions, ranked by usage. Comparing sessions with vs. without each instruction."}),$.map(is=>jsxRuntimeExports.jsx(InstructionImpactLoader,{instructionId:is.id,linkedSessions:is.linkedSessions,source:is.source},is.id))]})]})}function InsightsDetailPage(){const{id:es}=useParams(),[$]=useSearchParams(),ts=es==="computed",is=ts?$.get("projectPath")??$.get("project")??void 0:void 0,cs=ts?$.get("projectId")??void 0:void 0,[Qr,ja]=reactExports.useState(""),{data:Na,recommendations:Aa,isLoading:Oa,fullProjectPath:Ia,title:La,subtitle:Ba,lastCompletedJob:Ma,activeJobs:qa,createJob:Fa}=useProjectInsights(es,is,cs,Qr||void 0),[Ha,Ka]=useTabParam(["overview","tools","quality","sessions","instructions","recommendations"],"overview");if(Oa)return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-48"}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[...Array(4)].map((Ya,el)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},el))})]});if(!Na)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/insights",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Report not found."})]});const Ga=ts?Na.tools_used??{}:{},Va=Object.keys(Ga).sort((Ya,el)=>(Ga[el]??0)-(Ga[Ya]??0)),Ja=Na.autoAddAvailable!==!1;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/insights",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:La}),ts&&(Va.length>1||Qr)&&jsxRuntimeExports.jsxs("select",{value:Qr,onChange:Ya=>ja(Ya.target.value),className:"h-8 rounded-md border border-input bg-background px-2 text-xs font-mono cursor-pointer focus:outline-none focus:ring-1 focus:ring-ring",children:[jsxRuntimeExports.jsx("option",{value:"",children:"All Tools"}),Va.map(Ya=>jsxRuntimeExports.jsxs("option",{value:Ya,children:[displayTool(Ya)," (",Ga[Ya],")"]},Ya)),Qr&&!Va.includes(Qr)&&jsxRuntimeExports.jsx("option",{value:Qr,children:displayTool(Qr)})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:Ba}),ts&&Va.length>0&&!Qr&&jsxRuntimeExports.jsx("div",{className:"flex items-center gap-1.5 mt-1 flex-wrap",children:Va.map(Ya=>jsxRuntimeExports.jsx(Badge,{asChild:!0,variant:"outline",children:jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>ja(Ya),className:"text-[10px] font-mono cursor-pointer hover:bg-primary/10",children:[displayTool(Ya),": ",Ga[Ya]]})},Ya))})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[Ma&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["Last generated ",new Date(Ma.completedAt).toLocaleDateString(void 0,{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"})]}),jsxRuntimeExports.jsxs(Button,{onClick:()=>Fa.mutate(Ia??is,{onSuccess:Ya=>{Ya.noLiveWorker?ue$1.warning("Queued, but no worker is listening",{description:"Start one with `rulemetric evals agent` (or `rulemetric service install --worker-only`) and it will pick this up."}):ue$1.success("Generating recommendations…")},onError:Ya=>ue$1.error("Couldn't start the run",{description:Ya instanceof Error?Ya.message:"Please try again."})}),disabled:Fa.isPending||qa.length>0,variant:"outline",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mr-2 h-4 w-4"}),qa.length>0?`Generating — ${jobStepLabel(qa[0])}`:Aa?"Refresh Recommendations":"Generate Recommendations"]})]})]}),ts&&jsxRuntimeExports.jsx(AnalysisFreshnessBanner,{freshness:Na.analysis_freshness,totalAnalyzed:Na.sessions_with_analysis??0}),jsxRuntimeExports.jsx(WorkerOfflineBanner,{}),qa.length>0&&jsxRuntimeExports.jsx(JobTracker,{jobs:qa}),jsxRuntimeExports.jsxs(Tabs,{value:Ha,onValueChange:Ka,children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsxs(TabsTrigger,{value:"overview",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(ChartColumn,{className:"mr-2 h-4 w-4"}),"Overview"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"tools",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Terminal,{className:"mr-2 h-4 w-4"}),"Tools"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"quality",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(TrendingUp,{className:"mr-2 h-4 w-4"}),"Quality"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"sessions",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(MessageSquare,{className:"mr-2 h-4 w-4"}),"Sessions"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"instructions",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"mr-2 h-4 w-4"}),"Instructions"]}),jsxRuntimeExports.jsxs(TabsTrigger,{value:"recommendations",className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mr-2 h-4 w-4"}),"Recommendations"]})]}),jsxRuntimeExports.jsx(TabsContent,{value:"overview",className:"mt-6",children:jsxRuntimeExports.jsx(OverviewTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"tools",className:"mt-6",children:jsxRuntimeExports.jsx(ToolsTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"quality",className:"mt-6",children:jsxRuntimeExports.jsx(QualityTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"sessions",className:"mt-6",children:jsxRuntimeExports.jsx(SessionsTab,{data:Na})}),jsxRuntimeExports.jsx(TabsContent,{value:"instructions",className:"mt-6",children:jsxRuntimeExports.jsx(InstructionsTab,{projectFilter:is})}),jsxRuntimeExports.jsx(TabsContent,{value:"recommendations",className:"mt-6",children:Aa?jsxRuntimeExports.jsx(RecommendationsTab,{rec:Aa,projectPath:Ia,autoAddAvailable:Ja}):jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:qa.length>0?`Generating recommendations — ${jobStepLabel(qa[0])}`:'No recommendations yet. Use "Generate Recommendations" above to analyze this project’s sessions.'})})})})]})]})}const MEMORY_PAGE_SIZE=50;function useMemories(es="active",$="",ts="all"){return useInfiniteQuery({queryKey:["memories",{status:es,search:$,kind:ts}],initialPageParam:0,queryFn:({pageParam:is})=>{const cs=new URLSearchParams({status:es,limit:String(MEMORY_PAGE_SIZE),offset:String(is)});return $&&cs.set("search",$),ts&&ts!=="all"&&cs.set("kind",ts),apiGet(`/api/memories?${cs.toString()}`).then(Qr=>Qr.memories)},getNextPageParam:(is,cs)=>is.length<MEMORY_PAGE_SIZE?void 0:cs.length*MEMORY_PAGE_SIZE})}function useMemory(es){return useQuery({queryKey:["memories",es],queryFn:()=>apiGet(`/api/memories/${es}`),enabled:!!es})}function useMemoryImpact(es){return useQuery({queryKey:["insights","memory-impact",es],queryFn:()=>apiGet(`/api/insights/memory-impact?memoryId=${es}`),enabled:!!es})}function useMemoryExperiments(es){return useQuery({queryKey:["memories",es,"experiments"],queryFn:()=>apiGet(`/api/memories/${es}/experiments`),enabled:!!es,select:$=>$.experiments,refetchInterval:$=>{var is;return(((is=$.state.data)==null?void 0:is.experiments)??[]).some(cs=>cs.status==="pending"||cs.status==="running")?5e3:!1}})}function useCreateExperiment(es){const $=useQueryClient();return useMutation({mutationFn:ts=>apiPost(`/api/memories/${es}/experiments`,ts),onSuccess:()=>$.invalidateQueries({queryKey:["memories",es,"experiments"]})})}function useCreateMemory(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/memories",$),onSuccess:()=>es.invalidateQueries({queryKey:["memories"]})})}function useUpdateMemory(){const es=useQueryClient();return useMutation({mutationFn:({id:$,...ts})=>apiPatch(`/api/memories/${$}`,ts),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["memories"]}),es.invalidateQueries({queryKey:["memories",ts.id]})}})}function useArchiveMemory(){const es=useQueryClient();return useMutation({mutationFn:$=>apiDelete(`/api/memories/${$}`),onSuccess:($,ts)=>{es.invalidateQueries({queryKey:["memories"]}),es.invalidateQueries({queryKey:["memories",ts]})}})}const KINDS=["fact","decision","correction","convention"];function MemoryFormDialog({open:es,onOpenChange:$,memory:ts}){const is=!!ts,cs=useCreateMemory(),Qr=useUpdateMemory(),[ja,Na]=reactExports.useState("fact"),[Aa,Oa]=reactExports.useState(""),[Ia,La]=reactExports.useState("");reactExports.useEffect(()=>{es&&(Na((ts==null?void 0:ts.kind)??"fact"),Oa((ts==null?void 0:ts.title)??""),La((ts==null?void 0:ts.body)??""))},[es,ts==null?void 0:ts.id]);const Ba=cs.isPending||Qr.isPending,Ma=Aa.trim().length>0&&Ia.trim().length>0&&!Ba,qa=()=>{if(!Ma)return;const Fa=Ka=>()=>{ue$1.success(`Memory ${Ka}`),$(!1)},Ha=Ka=>ue$1.error(Ka instanceof Error?Ka.message:"Something went wrong");is?Qr.mutate({id:ts.id,kind:ja,title:Aa.trim(),body:Ia.trim()},{onSuccess:Fa("updated"),onError:Ha}):cs.mutate({kind:ja,title:Aa.trim(),body:Ia.trim()},{onSuccess:Fa("created"),onError:Ha})};return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:is?"Edit memory":"New memory"}),jsxRuntimeExports.jsx(DialogDescription,{children:"A durable note the session-start hook injects into future sessions as context. Its measured effect is tracked automatically."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Kind"}),jsxRuntimeExports.jsxs(Select,{value:ja,onValueChange:Fa=>Na(Fa),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsx(SelectContent,{children:KINDS.map(Fa=>jsxRuntimeExports.jsx(SelectItem,{value:Fa,className:"capitalize",children:Fa},Fa))})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Title"}),jsxRuntimeExports.jsx(Input,{value:Aa,onChange:Fa=>Oa(Fa.target.value),placeholder:"Short, memorable summary",maxLength:300})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsx(Label,{children:"Body"}),jsxRuntimeExports.jsx(Textarea,{value:Ia,onChange:Fa=>La(Fa.target.value),placeholder:"The fact / decision / correction / convention to remember.",rows:5})]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>$(!1),className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{onClick:qa,disabled:!Ma,className:"cursor-pointer",children:Ba?"Saving…":is?"Save changes":"Create"})]})]})})}const kindColors={fact:"bg-blue-500/15 text-blue-400 border-blue-500/30",decision:"bg-primary/15 text-primary border-primary/30",correction:"bg-red-500/15 text-red-400 border-red-500/30",convention:"bg-pink-500/15 text-pink-400 border-pink-500/30"};function useDebouncedValue(es,$){const[ts,is]=reactExports.useState(es);return reactExports.useEffect(()=>{const cs=setTimeout(()=>is(es),$);return()=>clearTimeout(cs)},[es,$]),ts}function MemoryList(){const[es,$]=reactExports.useState("active"),[ts,is]=reactExports.useState(""),[cs,Qr]=reactExports.useState("all"),[ja,Na]=reactExports.useState(!1),Aa=useNavigate(),Oa=useDebouncedValue(ts.trim(),300),{data:Ia,isLoading:La,error:Ba,hasNextPage:Ma,fetchNextPage:qa,isFetchingNextPage:Fa}=useMemories(es,Oa,cs),Ha=reactExports.useMemo(()=>(Ia==null?void 0:Ia.pages.flat())??[],[Ia]),Ka=Oa!==""||cs!=="all";if(Ba)return jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-destructive",children:["Failed to load memories: ",Ba.message]});const Ga=es!=="active";return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"relative min-w-40 flex-1",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{placeholder:"Search memories...",value:ts,onChange:Va=>is(Va.target.value),className:"pl-9 bg-background border-border"})]}),jsxRuntimeExports.jsxs(Select,{value:cs,onValueChange:Qr,children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-36 cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"all",children:"All kinds"}),jsxRuntimeExports.jsx(SelectItem,{value:"fact",children:"Fact"}),jsxRuntimeExports.jsx(SelectItem,{value:"decision",children:"Decision"}),jsxRuntimeExports.jsx(SelectItem,{value:"correction",children:"Correction"}),jsxRuntimeExports.jsx(SelectItem,{value:"convention",children:"Convention"})]})]}),jsxRuntimeExports.jsxs(Select,{value:es,onValueChange:Va=>$(Va),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-32 cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"active",children:"Active"}),jsxRuntimeExports.jsx(SelectItem,{value:"archived",children:"Archived"}),jsxRuntimeExports.jsx(SelectItem,{value:"all",children:"All"})]})]}),jsxRuntimeExports.jsxs(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"New"]})]}),La?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((Va,Ja)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 rounded-lg"},Ja))}):Ha.length===0?jsxRuntimeExports.jsxs("div",{className:"text-center py-12",children:[jsxRuntimeExports.jsx(Brain,{className:"mx-auto h-8 w-8 text-muted-foreground/40 mb-3"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-4",children:Ka?"No memories match your filters.":"No memories yet. Create one, or let the distiller extract them from your sessions."}),!Ka&&jsxRuntimeExports.jsxs(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"Create memory"]})]}):jsxRuntimeExports.jsx("div",{className:"bg-card border border-border rounded-lg",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{className:"hover:bg-transparent",children:[jsxRuntimeExports.jsx(TableHead,{children:"Title"}),jsxRuntimeExports.jsx(TableHead,{children:"Kind"}),jsxRuntimeExports.jsx(TableHead,{className:"hidden md:table-cell",children:"Scope"}),jsxRuntimeExports.jsx(TableHead,{className:"hidden lg:table-cell",children:"Source"}),Ga&&jsxRuntimeExports.jsx(TableHead,{children:"Status"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Updated"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Ha.map(Va=>jsxRuntimeExports.jsxs(TableRow,{className:"hover:bg-secondary/50 transition-colors duration-200 cursor-pointer",onClick:()=>Aa(`/memories/${Va.id}`),children:[jsxRuntimeExports.jsx(TableCell,{className:"font-medium max-w-md truncate",children:Va.title}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:`capitalize ${kindColors[Va.kind]}`,children:Va.kind})}),jsxRuntimeExports.jsx(TableCell,{className:"hidden md:table-cell text-xs text-muted-foreground",children:Va.projectId?"Project":"Global"}),jsxRuntimeExports.jsx(TableCell,{className:"hidden lg:table-cell text-xs text-muted-foreground",children:Va.source}),Ga&&jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs capitalize text-muted-foreground",children:Va.status})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-xs text-muted-foreground",children:formatDistanceToNow(Va.updatedAt)})]},Va.id))})]})}),Ma&&jsxRuntimeExports.jsx("div",{className:"flex justify-center",children:jsxRuntimeExports.jsx(Button,{variant:"outline",className:"cursor-pointer",disabled:Fa,onClick:()=>qa(),children:Fa?"Loading…":"Load more"})}),jsxRuntimeExports.jsx(MemoryFormDialog,{open:ja,onOpenChange:Na})]})}function MemoriesListPage(){return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Memories"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Durable project facts your agent recalls — injected at session start, and measured for whether they actually help."})]}),jsxRuntimeExports.jsx(MemoryList,{})]})}function ExperimentRow({exp:es}){var $,ts,is;return jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3 py-2 border-b border-border last:border-0",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"text-xs font-mono truncate",title:es.taskPrompt,children:es.taskPrompt}),jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:["v",es.memoryVersion," · ",es.engine," · ",es.trials," trials · ",formatDistanceToNow(es.createdAt)]}),es.status==="failed"&&es.error&&jsxRuntimeExports.jsx("p",{className:"text-[10px] text-red-400 mt-0.5",title:es.error,children:es.error}),es.result&&jsxRuntimeExports.jsxs("details",{className:"mt-2 text-xs",children:[jsxRuntimeExports.jsxs("summary",{className:"cursor-pointer",children:["Trial evidence · ",es.result.completedTrials,"/",es.trials," usable pairs"]}),jsxRuntimeExports.jsxs("p",{className:"break-words mt-2",children:[es.result.engine," · ",es.result.model??"Model not recorded",es.result.judge&&` · configured grader ${es.result.judge.engine} ${es.result.judge.model??"(default)"}`]}),es.result.actualJudge&&jsxRuntimeExports.jsx("p",{className:"break-words",children:es.result.actualJudge.engine?`Actual grader: ${es.result.actualJudge.engine} · ${es.result.actualJudge.model??"model not recorded"}`:"Deterministic assertions · no model grader used"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"With memory / without memory. Dollar values are API-equivalent estimates, not subscription charges."}),jsxRuntimeExports.jsx("ol",{className:"space-y-1 mt-2",children:($=es.result.pairs)==null?void 0:$.map((cs,Qr)=>{var ja,Na,Aa,Oa;return jsxRuntimeExports.jsxs("li",{className:"break-words",children:["Pair ",Qr+1,": score ",cs.withScore,"/",cs.withoutScore,"; tokens ",cs.withTokens??"?","/",cs.withoutTokens??"?",";"," ","seconds ",((ja=cs.withLatency)==null?void 0:ja.toFixed(1))??"?","/",((Na=cs.withoutLatency)==null?void 0:Na.toFixed(1))??"?",";"," ","estimated $ ",((Aa=cs.withCostUsd)==null?void 0:Aa.toFixed(5))??"unknown","/",((Oa=cs.withoutCostUsd)==null?void 0:Oa.toFixed(5))??"unknown"]},Qr)})}),(ts=es.result.excluded)==null?void 0:ts.map(cs=>jsxRuntimeExports.jsxs("p",{className:"break-words text-amber-500",children:["Excluded trial ",cs.trial,": ",cs.reason]},cs.trial))]})]}),jsxRuntimeExports.jsx("div",{className:"shrink-0",children:es.status==="completed"&&((is=es.result)!=null&&is.verdict)?jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["n=",es.result.completedTrials]}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.result.verdict})]}):es.status==="failed"||es.status==="completed"?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] text-red-400 border-red-400/40",children:es.status==="failed"?"failed":"no usable verdict"}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] text-muted-foreground gap-1",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-3 w-3 animate-spin"}),es.status==="running"?"running":"queued"]})})]})}function MemoryExperiments({memoryId:es}){const{data:$,isLoading:ts}=useMemoryExperiments(es),is=useCreateExperiment(es),[cs,Qr]=reactExports.useState(!1),[ja,Na]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(""),[Ia,La]=reactExports.useState(10),[Ba,Ma]=reactExports.useState("claude"),[qa,Fa]=reactExports.useState(""),[Ha,Ka]=reactExports.useState("claude"),[Ga,Va]=reactExports.useState("");function Ja(){const Ya=Aa.split(`
|
|
144
144
|
`).map(el=>el.trim()).filter(Boolean);if(!ja.trim()||Ya.length===0){ue$1.error("A task prompt and at least one expectation are required.");return}is.mutate({taskPrompt:ja.trim(),expectations:Ya,trials:Ia,engine:Ba,graderEngine:Ha,...Ga.trim()?{graderModel:Ga.trim()}:{},...qa.trim()?{model:qa.trim()}:{}},{onSuccess:el=>{ue$1.success(el.noLiveWorker?"Queued — start `rulemetric evals agent` on your laptop to run it":"Controlled A/B started — the causal verdict appears when it finishes"),Na(""),Oa(""),Qr(!1)},onError:el=>ue$1.error(`Failed: ${el.message}`)})}return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs(CardTitle,{className:"text-sm font-mono flex items-center gap-1.5",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"h-3.5 w-3.5"})," Controlled A/B"]}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs",onClick:()=>Qr(Ya=>!Ya),children:cs?"Cancel":"Run A/B"})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["The gold-standard causal test: the same task run with vs without this memory injected, graded and paired. Unlike the observational effect above, this holds the task and harness constant — so its delta isn't confounded. Each trial runs the selected harness on your laptop (needs"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:"rulemetric evals agent"}),"). Ten trials is a minimum, not a guarantee of a conclusive result."]}),cs&&jsxRuntimeExports.jsxs("div",{className:"space-y-2 rounded-md border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-task",className:"text-xs",children:"Task prompt"}),jsxRuntimeExports.jsx(Textarea,{id:"ab-task",value:ja,onChange:Ya=>Na(Ya.target.value),placeholder:"e.g. Add a new dependency to this project.",className:"text-xs min-h-16"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-exp",className:"text-xs",children:"Expectations (one per line)"}),jsxRuntimeExports.jsx(Textarea,{id:"ab-exp",value:Aa,onChange:Ya=>Oa(Ya.target.value),placeholder:`Uses pnpm, not npm
|
|
145
145
|
Runs the install command`,className:"text-xs min-h-16"})]}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap items-end justify-between gap-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-end gap-2",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-engine",className:"text-xs",children:"Harness"}),jsxRuntimeExports.jsxs(Select,{value:Ba,onValueChange:Ya=>Ma(Ya),children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"ab-engine",size:"sm",className:"w-28 cursor-pointer",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"claude",children:"Claude"}),jsxRuntimeExports.jsx(SelectItem,{value:"codex",children:"Codex"}),jsxRuntimeExports.jsx(SelectItem,{value:"pi",children:"Pi"})]})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-trials",className:"text-xs",children:"Trials"}),jsxRuntimeExports.jsx(Input,{id:"ab-trials",type:"number",min:1,max:50,value:Ia,onChange:Ya=>La(Math.max(1,Math.min(50,Number(Ya.target.value)||1))),className:"text-xs h-8 w-20"})]})]})}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"ab-model",className:"text-xs",children:"Trial model pin"}),jsxRuntimeExports.jsx(Input,{id:"ab-model",value:qa,onChange:Ya=>Fa(Ya.target.value),placeholder:Ba==="pi"?"openai-codex/gpt-5.4-mini":Ba==="codex"?"Required Codex model":"Optional Claude model"}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Both arms use this model. The independent grader below must also be available on the worker."})]}),jsxRuntimeExports.jsxs("details",{className:"text-xs space-y-2",children:[jsxRuntimeExports.jsxs("summary",{className:"cursor-pointer",children:["Grader: ",Ha," · ",Ga||"default"]}),jsxRuntimeExports.jsx(Label,{htmlFor:"ab-grader",children:"Grader harness"}),jsxRuntimeExports.jsxs("select",{id:"ab-grader",className:"w-full rounded border bg-background p-2",value:Ha,onChange:Ya=>{Ka(Ya.target.value),Va("")},children:[jsxRuntimeExports.jsx("option",{value:"claude",children:"Claude"}),jsxRuntimeExports.jsx("option",{value:"codex",children:"Codex / OpenAI"})]}),jsxRuntimeExports.jsx(Label,{htmlFor:"ab-grader-model",children:"Grader model pin"}),jsxRuntimeExports.jsx(Input,{id:"ab-grader-model",value:Ga,onChange:Ya=>Va(Ya.target.value),placeholder:Ha==="codex"?"Required Codex model":"Optional Claude model"})]}),jsxRuntimeExports.jsx(Button,{size:"sm",disabled:is.isPending||Ha==="codex"&&!Ga.trim()||Ba==="codex"&&!qa.trim()||Ba==="pi"&&!/^[^\s/:]+\/[^\s/]+$/.test(qa.trim()),onClick:Ja,children:is.isPending?"Starting…":"Run experiment"})]}),ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-12"}):!$||$.length===0?jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"No controlled experiments yet. Run one to get an unconfounded causal delta."}):jsxRuntimeExports.jsxs("div",{children:[$.length>=20&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Showing the 20 most recent experiments."}),$.map(Ya=>jsxRuntimeExports.jsx(ExperimentRow,{exp:Ya},Ya.id))]})]})]})}function formatTokens(es){return es==null?"—":es>=1e6?`${(es/1e6).toFixed(1)}M`:es>=1e3?`${(es/1e3).toFixed(0)}K`:String(es)}function Cohort({label:es,value:$}){return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-1",children:es}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:$})]})}function MemoryImpactCard({impact:es}){const $=es.with,ts=es.without,is=es.comparison,cs=$.avgOutcomeScore!=null&&ts.avgOutcomeScore!=null?`${$.avgOutcomeScore} vs ${ts.avgOutcomeScore}${is.outcomeScoreDelta!=null?` (${is.outcomeScoreDelta>0?"+":""}${is.outcomeScoreDelta})`:""}`:"—",Qr=$.avgTotalTokens!=null&&ts.avgTotalTokens!=null?`${formatTokens($.avgTotalTokens)} vs ${formatTokens(ts.avgTotalTokens)}`:"—";return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Measured effect"}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:es.verdict})]})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 text-xs",children:[jsxRuntimeExports.jsx(Cohort,{label:"Sessions",value:`${$.sessionCount} with / ${ts.sessionCount} without`}),jsxRuntimeExports.jsx(Cohort,{label:"Outcome score",value:cs}),jsxRuntimeExports.jsx(Cohort,{label:"Avg tokens/session",value:Qr})]}),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground mt-3",children:"Observational — sessions exposed to this memory vs not, compared within each project. Not a controlled experiment; cost is estimated."})]})]})}function VersionHistoryCard({versions:es}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Effect by version"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-2",children:[es.map($=>jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2 text-xs",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:["v",$.version]}),$.isCurrent&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] py-0 text-muted-foreground",children:"current"}),jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[$.with.sessionCount," session",$.with.sessionCount===1?"":"s"]})]}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:$.verdict})]},$.version)),jsxRuntimeExports.jsx("p",{className:"text-[10px] text-muted-foreground pt-1",children:"Each edit bumps the version and re-opens measurement, so a version is scored only on the sessions that actually saw it."})]})]})}function MemoryImpactLoader({memoryId:es}){const{data:$,isLoading:ts}=useMemoryImpact(es);return ts?jsxRuntimeExports.jsx(Skeleton,{className:"h-28"}):!$||$.with.sessionCount===0&&$.without.sessionCount===0?jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No measured effect yet. Once this memory is injected into sessions (via the session-start hook) and those sessions are analyzed, its verdict appears here."})})}):jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(MemoryImpactCard,{impact:$}),$.versions.length>1&&jsxRuntimeExports.jsx(VersionHistoryCard,{versions:$.versions})]})}function MemoryDetail({id:es}){const{data:$,isLoading:ts,error:is}=useMemory(es),cs=useArchiveMemory(),Qr=useUpdateMemory(),[ja,Na]=reactExports.useState(!1);if(ts)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40"})]});if(is||!$)return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",asChild:!0,className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/memories",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Memory not found."})]});const Aa=$.status==="archived";return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/memories",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-4 w-4"})," Back"]})}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer",onClick:()=>Na(!0),children:[jsxRuntimeExports.jsx(Pencil,{className:"mr-1.5 h-3.5 w-3.5"})," Edit"]}),Aa?jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer",disabled:Qr.isPending,onClick:()=>Qr.mutate({id:$.id,status:"active"},{onSuccess:()=>ue$1.success("Memory restored"),onError:()=>ue$1.error("Restore failed")}),children:[jsxRuntimeExports.jsx(RotateCcw,{className:"mr-1.5 h-3.5 w-3.5"})," Restore"]}):jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer text-red-400 hover:text-red-400",disabled:cs.isPending,onClick:()=>cs.mutate($.id,{onSuccess:()=>ue$1.success("Memory archived (reversible)"),onError:()=>ue$1.error("Archive failed")}),children:[jsxRuntimeExports.jsx(Archive,{className:"mr-1.5 h-3.5 w-3.5"})," Archive"]})]})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:`capitalize ${kindColors[$.kind]??""}`,children:$.kind}),Aa&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-muted-foreground",children:"archived"}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["v",$.version," · ",$.source," · ",$.projectId?"project-scoped":"global"]})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold tracking-tight mt-2",children:$.title})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Content"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("p",{className:"text-sm whitespace-pre-wrap leading-relaxed",children:$.body})})]}),jsxRuntimeExports.jsx(MemoryImpactLoader,{memoryId:$.id}),jsxRuntimeExports.jsx(MemoryExperiments,{memoryId:$.id}),jsxRuntimeExports.jsx(MemoryFormDialog,{open:ja,onOpenChange:Na,memory:$})]})}function MemoryDetailPage(){const{id:es}=useParams();return es?jsxRuntimeExports.jsx(MemoryDetail,{id:es}):null}const CATEGORY_LABELS={workflow:"Workflow",language:"Language",framework:"Framework",tool:"Tool",security:"Security",testing:"Testing",architecture:"Architecture",devops:"DevOps",documentation:"Documentation",performance:"Performance",other:"Other"};function CopyInstallButton({skill:es}){const{copied:$,copy:ts}=useCopyToClipboard(),is=`rulemetric skills install ${es.id}`;return jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5",onClick:cs=>{cs.stopPropagation(),ts(is)},title:is,children:[$?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),$?"Copied!":"Install"]})}function SkillCard({skill:es,onSelect:$}){return jsxRuntimeExports.jsxs(Card,{className:"cursor-pointer hover:bg-secondary/30 transition-colors",onClick:()=>$(es),children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono leading-tight",children:es.name}),jsxRuntimeExports.jsx(CopyInstallButton,{skill:es})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:es.description}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-[10px] font-mono",children:CATEGORY_LABELS[es.category]??es.category}),es.tools.slice(0,3).map(ts=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] font-mono",children:displayTool(ts)},ts)),es.tools.length>3&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono",children:["+",es.tools.length-3]})]}),es.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:es.tags.slice(0,4).map(ts=>jsxRuntimeExports.jsxs("span",{className:"text-[10px] text-muted-foreground font-mono",children:["#",ts]},ts))})]})]})}function SkillDetailDialog({skill:es,open:$,onClose:ts}){var Oa;const{copied:is,copy:cs}=useCopyToClipboard(),{data:Qr,isLoading:ja}=useSkill($?es==null?void 0:es.id:void 0);if(!es)return null;const Na=Qr??es,Aa=`rulemetric skills install ${Na.id}`;return jsxRuntimeExports.jsx(Dialog,{open:$,onOpenChange:Ia=>!Ia&&ts(),children:jsxRuntimeExports.jsxs(DialogContent,{className:"sm:max-w-[95vw] max-h-[90vh] overflow-y-auto",children:[jsxRuntimeExports.jsx(DialogHeader,{children:jsxRuntimeExports.jsx(DialogTitle,{className:"font-mono",children:Na.name})}),jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:Na.description}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",children:CATEGORY_LABELS[Na.category]??Na.category}),Na.tools.map(Ia=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs",children:displayTool(Ia)},Ia))]}),(((Oa=Na.languages)==null?void 0:Oa.length)??0)>0&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"Languages:"}),Na.languages.map(Ia=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs font-mono",children:Ia},Ia))]}),jsxRuntimeExports.jsxs("div",{className:"rounded-lg border border-border bg-muted/30 p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-2",children:[jsxRuntimeExports.jsx("span",{className:"text-xs font-medium font-mono",children:"Install"}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5",children:[Na.content&&jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5 border-primary/30 text-primary hover:bg-primary/10",onClick:()=>{const Ia=new Blob([Na.content],{type:"text/markdown"}),La=URL.createObjectURL(Ia),Ba=document.createElement("a");Ba.href=La,Ba.download=`${Na.id}.md`,Ba.click(),URL.revokeObjectURL(La)},children:[jsxRuntimeExports.jsx(Download,{className:"h-3 w-3"}),"Download"]}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",className:"cursor-pointer h-7 text-xs gap-1.5",onClick:()=>{cs(Aa)},children:[is?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3"}):jsxRuntimeExports.jsx(Copy,{className:"h-3 w-3"}),is?"Copied!":"Copy CLI"]})]})]}),jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono bg-[#0B1120] text-muted-foreground rounded p-2 overflow-x-auto",children:Aa})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-xs font-medium font-mono mb-2",children:"Content"}),ja&&!Na.content?jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"}):Na.content?jsxRuntimeExports.jsx("pre",{className:"text-xs font-mono bg-[#0B1120] text-muted-foreground rounded p-3 overflow-x-auto whitespace-pre-wrap max-h-[55vh]",children:Na.content}):jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"No content available."})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:["Source:"," ",jsxRuntimeExports.jsxs("a",{href:Na.source.url,target:"_blank",rel:"noopener noreferrer",className:"underline inline-flex items-center gap-1",children:[Na.source.repo,jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]})]}),Na.source.license&&jsxRuntimeExports.jsx("span",{children:Na.source.license})]})]})]})})}const PAGE_SIZE$1=60;function SkillsListPage(){const{data:es,isLoading:$}=useSkillsRegistry(),[ts,is]=reactExports.useState(""),[cs,Qr]=reactExports.useState(null),[ja,Na]=reactExports.useState(null),[Aa,Oa]=reactExports.useState(null),[Ia,La]=reactExports.useState(PAGE_SIZE$1),Ba=(es==null?void 0:es.skills)??[],Ma=reactExports.useMemo(()=>[...new Set(Ba.map(Ga=>Ga.category))].sort(),[Ba]),qa=reactExports.useMemo(()=>[...new Set(Ba.flatMap(Ga=>Ga.tools))].sort(),[Ba]),Fa=reactExports.useMemo(()=>{let Ga=Ba;if(ts){const Va=ts.toLowerCase();Ga=Ga.filter(Ja=>Ja.name.toLowerCase().includes(Va)||Ja.description.toLowerCase().includes(Va)||Ja.tags.some(Ya=>Ya.toLowerCase().includes(Va))||Ja.id.toLowerCase().includes(Va))}return cs&&(Ga=Ga.filter(Va=>Va.category===cs)),ja&&(Ga=Ga.filter(Va=>Va.tools.includes(ja)||Va.tools.includes("universal"))),Ga.sort((Va,Ja)=>{var tl,rl;const Ya=((tl=Va.popularity)==null?void 0:tl.stars)??0,el=((rl=Ja.popularity)==null?void 0:rl.stars)??0;return Ya!==el?el-Ya:Va.name.localeCompare(Ja.name)}),Ga},[Ba,ts,cs,ja]);reactExports.useEffect(()=>{La(PAGE_SIZE$1)},[ts,cs,ja]);const Ha=Fa.slice(0,Ia),Ka=Fa.length>Ia;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Skills Registry"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Browse and install community-contributed skills for your AI coding tools"})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"relative flex-1",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{placeholder:"Search skills...",value:ts,onChange:Ga=>is(Ga.target.value),className:"pl-9 font-mono"})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 flex-wrap",children:[cs&&jsxRuntimeExports.jsxs(Button,{variant:"secondary",size:"sm",className:"cursor-pointer gap-1 font-mono text-xs",onClick:()=>Qr(null),children:[CATEGORY_LABELS[cs]??cs,jsxRuntimeExports.jsx(X$1,{className:"h-3 w-3"})]}),ja&&jsxRuntimeExports.jsxs(Button,{variant:"secondary",size:"sm",className:"cursor-pointer gap-1 font-mono text-xs",onClick:()=>Na(null),children:[displayTool(ja),jsxRuntimeExports.jsx(X$1,{className:"h-3 w-3"})]})]})]}),!cs&&!ja&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground mr-1 self-center",children:"Category:"}),Ma.map(Ga=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"cursor-pointer text-xs font-mono hover:bg-secondary",onClick:()=>Qr(Ga),children:CATEGORY_LABELS[Ga]??Ga},Ga))]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground mr-1 self-center",children:"Tool:"}),qa.map(Ga=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"cursor-pointer text-xs font-mono hover:bg-secondary",onClick:()=>Na(Ga),children:displayTool(Ga)},Ga))]})]}),$?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((Ga,Va)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-40"},Va))}):Fa.length===0?jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[jsxRuntimeExports.jsx(Sparkles,{className:"mx-auto h-12 w-12 mb-4 opacity-50"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:Ba.length===0?"No skills in registry":"No matching skills"}),Ba.length===0&&jsxRuntimeExports.jsxs("p",{className:"text-sm mt-1",children:["Run"," ",jsxRuntimeExports.jsx("code",{className:"bg-muted px-1 rounded",children:"rulemetric skills update"})," ","to fetch the registry"]})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground font-mono",children:["Showing ",Ha.length," of ",Fa.length," skill",Fa.length!==1?"s":"",ts||cs||ja?" matching filters":""]}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Ha.map(Ga=>jsxRuntimeExports.jsx(SkillCard,{skill:Ga,onSelect:Oa},Ga.id))}),Ka&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-2",children:jsxRuntimeExports.jsxs(Button,{variant:"outline",className:"cursor-pointer font-mono",onClick:()=>La(Ga=>Ga+PAGE_SIZE$1),children:["Load ",Math.min(PAGE_SIZE$1,Fa.length-Ia)," more"]})})]}),jsxRuntimeExports.jsx(SkillDetailDialog,{skill:Aa,open:!!Aa,onClose:()=>Oa(null)})]})}function relativeDate(es){if(!es)return"recently";const $=new Date(es).getTime();if(Number.isNaN($))return"recently";const ts=Math.floor((Date.now()-$)/864e5);return ts<1?"today":ts===1?"yesterday":ts<30?`${ts}d ago`:ts<365?`${Math.floor(ts/30)}mo ago`:`${Math.floor(ts/365)}y ago`}function formatStars(es){return es>=1e3?`${(es/1e3).toFixed(1)}k`:String(es)}function PublicCatalogPage(){const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(es);reactExports.useEffect(()=>{const La=setTimeout(()=>is(es),250);return()=>clearTimeout(La)},[es]);const{data:cs,isLoading:Qr,isFetchingNextPage:ja,fetchNextPage:Na,hasNextPage:Aa,error:Oa}=usePublicCatalog(ts||void 0),Ia=reactExports.useMemo(()=>(cs==null?void 0:cs.pages.flat())??[],[cs]);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h2",{className:"text-2xl font-bold tracking-tight flex items-center gap-2",children:[jsxRuntimeExports.jsx(Globe,{className:"h-6 w-6"}),"Public Catalog"]}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Community-maintained skills and instructions, browsable here for reference."})]}),jsxRuntimeExports.jsxs("div",{className:"relative",children:[jsxRuntimeExports.jsx(Search,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),jsxRuntimeExports.jsx(Input,{placeholder:"Search public catalog...",value:es,onChange:La=>$(La.target.value),className:"pl-9"})]}),Oa?jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-destructive",children:["Failed to load public catalog: ",Oa.message]}):Qr?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((La,Ba)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-40 rounded-lg"},Ba))}):Ia.length===0?jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground",children:ts?`No public skills match "${ts}".`:"No public skills available yet. The registry syncs daily."}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Ia.map(La=>jsxRuntimeExports.jsx(Link,{to:`/catalog/public/${La.id}`,className:"block",children:jsxRuntimeExports.jsxs(Card,{className:"flex flex-col h-full hover:border-primary/50 hover:bg-muted/30 transition-colors cursor-pointer",children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:La.name}),La.description&&jsxRuntimeExports.jsx(CardDescription,{className:"line-clamp-3",children:La.description})]}),jsxRuntimeExports.jsxs(CardContent,{className:"mt-auto space-y-2",children:[La.tags&&La.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:La.tags.slice(0,5).map(Ba=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:Ba},Ba))}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{title:La.sourceUpdatedAt??La.updatedAt,children:["Updated ",relativeDate(La.sourceUpdatedAt??La.updatedAt)]}),typeof La.popularityScore=="number"&&La.popularityScore>0&&jsxRuntimeExports.jsxs("span",{className:"flex items-center gap-1",title:"GitHub stars on the source repo",children:[jsxRuntimeExports.jsx(Star,{className:"h-3 w-3 fill-current"}),formatStars(La.popularityScore)]})]})]})]})},La.id))}),Aa&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-4",children:jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Na(),disabled:ja,className:"cursor-pointer",children:ja?"Loading…":`Load more (showing ${Ia.length})`})}),!Aa&&Ia.length>0&&jsxRuntimeExports.jsxs("div",{className:"text-center text-xs text-muted-foreground pt-2",children:[Ia.length," skill",Ia.length===1?"":"s"," loaded"]})]})]})}function PublicSkillDetailPage(){var cs,Qr;const{id:es}=useParams(),{data:$,isLoading:ts,error:is}=useQuery({queryKey:["instruction",es],queryFn:()=>apiGet(`/api/instructions/${es}`),enabled:!!es});return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/catalog/public",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"}),"Back to Public Catalog"]})}),is?jsxRuntimeExports.jsxs("div",{className:"text-destructive",children:["Failed to load: ",is.message]}):ts||!$?jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-1/2"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Globe,{className:"h-4 w-4 text-muted-foreground"}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:$.scope}),((cs=$.frontmatter)==null?void 0:cs.category)&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:$.frontmatter.category})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:$.name}),$.description&&jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:$.description})]}),$.tags&&$.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:$.tags.map(ja=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:ja},ja))}),((Qr=$.frontmatter)==null?void 0:Qr.source)&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Source"})}),jsxRuntimeExports.jsxs(CardContent,{className:"text-sm space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"font-mono text-xs text-muted-foreground",children:[$.frontmatter.source.repo,$.frontmatter.source.path&&` / ${$.frontmatter.source.path}`]}),$.frontmatter.source.url&&jsxRuntimeExports.jsxs("a",{href:$.frontmatter.source.url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline inline-flex items-center gap-1",children:["View on GitHub ",jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]}),$.frontmatter.source.license&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["License: ",$.frontmatter.source.license]})]})]}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Content"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("pre",{className:"whitespace-pre-wrap break-words text-xs font-mono bg-muted/40 rounded p-3 max-h-[60vh] overflow-y-auto",children:$.content})})]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:["Version ",$.version," · updated ",new Date($.updatedAt).toLocaleString()]})]})]})}const scopeColors={public:"bg-teal-500/15 text-teal-400 border-teal-500/30",org:"bg-blue-500/15 text-blue-400 border-blue-500/30",team:"bg-primary/15 text-primary border-primary/30",personal:"bg-muted text-muted-foreground border-border"};function SuggestionRow({suggestion:es,projectPath:$,verdict:ts,experiment:is,evidence:cs}){var Ja;const Qr=useLogSuggestionEvent(),ja=usePromoteFromPublic(),Na=useArchiveInstruction(),Aa=useRestoreInstruction(),Oa=useNominateExperiment(),Ia=es.kind??"add",[La,Ba]=reactExports.useState(!1),Ma=useInstructionDetail(es.instructionId,La),qa=Qr.isPending||ja.isPending||Na.isPending||Oa.isPending;function Fa(Ya){Oa.mutate({instructionId:es.instructionId,projectPath:$,source:Ya},{onSuccess:()=>ue$1(`Under measurement: ${es.name}`,{description:"Injected to half your sessions on this project; the verdict decides."}),onError:el=>ue$1.error(`Could not start the trial: ${el.message}`)})}async function Ha(){try{await Na.mutateAsync(es.instructionId),await Qr.mutateAsync({suggestionId:es.id,eventType:"accepted",projectPath:$}),ue$1(`Retired: ${es.name}`,{description:"Archived — soft delete, restorable.",action:{label:"Undo",onClick:()=>Aa.mutate(es.instructionId,{onSuccess:()=>ue$1.success("Restored"),onError:()=>ue$1.error("Restore failed")})}})}catch(Ya){ue$1.error(`Failed: ${Ya.message}`)}}async function Ka(){try{await Qr.mutateAsync({suggestionId:es.id,eventType:"accepted",projectPath:$}),ue$1(`Noted: ${es.name}`,{description:"Nothing changed — shorten it yourself and the next cycle re-measures it."})}catch(Ya){ue$1.error(`Failed: ${Ya.message}`)}}async function Ga(){try{es.instructionScope==="public"&&await ja.mutateAsync({sourceInstructionId:es.instructionId,targetScope:"personal"}),await Qr.mutateAsync({suggestionId:es.id,eventType:"accepted",projectPath:$}),ue$1(`Accepted: ${es.name}`)}catch(Ya){ue$1.error(`Failed: ${Ya.message}`)}}async function Va(){try{await Qr.mutateAsync({suggestionId:es.id,eventType:"dismissed",projectPath:$}),ue$1(`Dismissed: ${es.name}`)}catch(Ya){ue$1.error(`Failed: ${Ya.message}`)}}return jsxRuntimeExports.jsxs("div",{"data-testid":"suggestion-row","data-suggestion-id":es.id,"data-kind":Ia,className:"flex flex-wrap items-start justify-between gap-x-4 gap-y-2 py-3 border-b border-border last:border-0",children:[jsxRuntimeExports.jsxs("div",{...activatable(()=>Ba(Ya=>!Ya)),"aria-expanded":La,"data-testid":"suggestion-row-toggle",className:"flex-1 min-w-0 basis-56 space-y-1 cursor-pointer rounded-md -mx-1 px-1 hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(ChevronRight,{"aria-hidden":!0,className:cn$1("h-4 w-4 shrink-0 text-muted-foreground transition-transform",La&&"rotate-90")}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:scopeColors[es.instructionScope]??scopeColors.personal,children:es.instructionScope}),jsxRuntimeExports.jsx("span",{className:"min-w-0 break-words font-medium",children:es.name}),Ia!=="add"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:Ia==="remove"?"text-xs border-red-500/40 text-red-400":"text-xs border-amber-500/40 text-amber-400",children:Ia==="remove"?"retire":"trim"}),es.estimatedTokens!=null&&es.estimatedTokens>0&&Ia!=="add"&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"font-mono text-xs text-muted-foreground",title:"Estimated from content length (chars/4), not a tokenizer count.",children:["~",es.estimatedTokens.toLocaleString()," tok/session"]}),jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",children:es.score.toFixed(2)}),es.isStale&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:"stale"}),(ts==null?void 0:ts.sufficient)&&jsxRuntimeExports.jsx(VerdictBadge,{verdict:ts}),is&&jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"This instruction is under randomised measurement on this project: injected to some sessions and withheld from the rest, until the arms decide. It is not being pitched while the question is being answered.",children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] font-mono text-teal-400 border-teal-400/40","data-testid":"under-measurement-badge",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"mr-1 h-3 w-3"}),"under measurement",is.source==="trial"?" · trial":is.source==="borrow"?" · borrowed":""]})}),(cs??[]).map(Ya=>jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Measured on ${Ya.projectPath}: ${Ya.decision==="always"?"helped":"hurt"} (${Number(Ya.delta)>0?"+":""}${(Number(Ya.delta)*100).toFixed(0)}pp, 95% CI ${(Number(Ya.ciLower)*100).toFixed(0)} to ${(Number(Ya.ciUpper)*100).toFixed(0)}pp, n=${Ya.nTreated}/${Ya.nControl}). That evidence was earned THERE — it does not transfer here; it argues for measuring here.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:Ya.decision==="always"?"text-[10px] font-mono text-teal-400 border-teal-400/40":"text-[10px] font-mono text-red-400 border-red-400/40","data-testid":"cross-project-evidence",children:[Number(Ya.delta)>0?"+":"",(Number(Ya.delta)*100).toFixed(0),"pp elsewhere"]})},Ya.projectPath))]}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason}),es.description&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.description}),jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Generated ",formatDistanceToNow(es.generatedAt)]})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 shrink-0",children:[Ia==="add"&&!is&&jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"ghost",className:"cursor-pointer",onClick:()=>Fa(((cs==null?void 0:cs.length)??0)>0?"borrow":"trial"),disabled:qa,"data-testid":"trial-button",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"h-4 w-4 mr-1"}),((cs==null?void 0:cs.length)??0)>0?"Test here":"Trial"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"cursor-pointer",onClick:Ia==="remove"?Ha:Ia==="trim"?Ka:Ga,disabled:qa,children:[jsxRuntimeExports.jsx(Check,{className:"h-4 w-4 mr-1"}),Ia==="remove"?"Retire":Ia==="trim"?"Noted":"Accept"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"ghost",className:"cursor-pointer",onClick:Va,disabled:qa,children:[jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4 mr-1"}),"Dismiss"]})]}),La&&jsxRuntimeExports.jsx("div",{className:"basis-full","data-testid":"suggestion-detail",children:Ma.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-16","data-testid":"suggestion-detail-loading"}):Ma.isError?jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-400/90","data-testid":"suggestion-detail-error",children:["Could not load this instruction's body: ",Ma.error.message]}):(Ja=Ma.data)!=null&&Ja.content?jsxRuntimeExports.jsx("pre",{"data-testid":"suggestion-detail-content",className:"whitespace-pre-wrap break-words rounded-md border border-border bg-secondary/20 p-3 font-mono text-xs",children:Ma.data.content}):Ma.data?jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground","data-testid":"suggestion-detail-empty",children:"This instruction stores no body — it is tracked by reference, so there is nothing to preview here."}):null})]})}function AdoptedRow({row:es,projectPath:$}){var Ka;const ts=useArchiveInstruction(),is=useQueryClient(),[cs,Qr]=reactExports.useState(!1),[ja,Na]=reactExports.useState(!1),[Aa,Oa]=reactExports.useState(null),Ia=useInstructionDetail(es.instructionId,cs),La=es.promotedToInstructionId??es.instructionId,Ba=es.archived||ja,Ma=`rulemetric instructions retract ${La}`;async function qa(){Oa(null);try{await ts.mutateAsync(La),Na(!0),is.invalidateQueries({queryKey:["instruction-suggestions","adopted",$]}),ue$1(`Archived: ${es.name}`,{description:"RuleMetric stops injecting it. Run the command shown to remove it from the file."})}catch(Ga){Oa(Ga.message)}}async function Fa(){try{await navigator.clipboard.writeText(Ma),ue$1.success("Copied")}catch{ue$1.error("Could not copy — select the command and copy it by hand.")}}const Ha=new Date(es.acceptedAt);return jsxRuntimeExports.jsxs("div",{"data-testid":"adopted-row","data-suggestion-id":es.id,"data-actor":es.actor,className:"flex flex-wrap items-start justify-between gap-x-4 gap-y-2 py-3 border-b border-border last:border-0",children:[jsxRuntimeExports.jsxs("div",{...activatable(()=>Qr(Ga=>!Ga)),"aria-expanded":cs,"data-testid":"adopted-row-toggle",className:"flex-1 min-w-0 basis-56 space-y-1 cursor-pointer rounded-md -mx-1 px-1 hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[jsxRuntimeExports.jsx(ChevronRight,{"aria-hidden":!0,className:cn$1("h-4 w-4 shrink-0 text-muted-foreground transition-transform",cs&&"rotate-90")}),jsxRuntimeExports.jsx("span",{className:"min-w-0 break-words font-medium",children:es.name}),es.actor==="auto"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-xs border-amber-500/40 text-amber-400",title:"Accepted by the auto-accept cron (score ≥ your threshold) with nobody watching.",children:[jsxRuntimeExports.jsx(Bot,{"aria-hidden":!0,className:"mr-1 h-3 w-3"}),"Automatic"]}):es.actor==="human"?jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-xs border-teal-500/40 text-teal-400",children:[jsxRuntimeExports.jsx(User,{"aria-hidden":!0,className:"mr-1 h-3 w-3"}),"You accepted"]}):jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-muted-foreground",title:"No acceptance event was recorded for this row, so who accepted it is not known.",children:"Actor unknown"}),es.kind!=="add"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:es.kind==="remove"?"retired":"trim noted"}),jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono text-xs",children:es.score.toFixed(2)}),Ba&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-muted-foreground","data-testid":"adopted-archived",children:"archived"})]}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground","data-testid":"adopted-reason",children:["Adopted because: ",es.reason]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground","data-testid":"adopted-when",children:jsxRuntimeExports.jsxs("time",{dateTime:es.acceptedAt,title:Ha.toLocaleString(),children:["Adopted ",formatDistanceToNow(es.acceptedAt)]})})]}),jsxRuntimeExports.jsx("div",{className:"flex gap-2 shrink-0",children:!Ba&&jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"cursor-pointer",onClick:qa,disabled:ts.isPending,"data-testid":"adopted-retract",children:[jsxRuntimeExports.jsx(Undo2,{className:"h-4 w-4 mr-1"}),ts.isPending?"Archiving…":"Retract"]})}),Aa&&jsxRuntimeExports.jsxs("p",{className:"basis-full text-xs text-amber-400/90","data-testid":"retract-error",children:["Could not archive: ",Aa]}),Ba&&jsxRuntimeExports.jsxs("div",{className:"basis-full rounded-md border border-border bg-secondary/20 p-3 space-y-2","data-testid":"retract-panel",children:[jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground","data-testid":"retract-note",children:["Archived — RuleMetric no longer injects this instruction. The block is still in your instruction file on disk; this removes it (dry-run first, add ",jsxRuntimeExports.jsx("code",{children:"--apply"})," to write):"]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("code",{className:"flex-1 min-w-0 break-all font-mono text-xs","data-testid":"retract-command",children:Ma}),jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"cursor-pointer shrink-0",onClick:Fa,"aria-label":"Copy command",children:jsxRuntimeExports.jsx(Copy,{className:"h-4 w-4"})})]})]}),cs&&jsxRuntimeExports.jsx("div",{className:"basis-full","data-testid":"suggestion-detail",children:Ia.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-16","data-testid":"suggestion-detail-loading"}):Ia.isError?jsxRuntimeExports.jsxs("p",{className:"text-xs text-amber-400/90","data-testid":"suggestion-detail-error",children:["Could not load this instruction's body: ",Ia.error.message]}):(Ka=Ia.data)!=null&&Ka.content?jsxRuntimeExports.jsx("pre",{"data-testid":"suggestion-detail-content",className:"whitespace-pre-wrap break-words rounded-md border border-border bg-secondary/20 p-3 font-mono text-xs",children:Ia.data.content}):Ia.data?jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground","data-testid":"suggestion-detail-empty",children:"This instruction stores no body — it is tracked by reference, so there is nothing to preview here."}):null})]})}function AdoptedDisclosure({projectPath:es}){var ja,Na,Aa;const[$,ts]=reactExports.useState(!1),is=useAdoptedSuggestions(es),cs=(Na=(ja=is.data)==null?void 0:ja.pages[0])==null?void 0:Na.counts,Qr=((Aa=is.data)==null?void 0:Aa.pages.flatMap(Oa=>Oa.adopted))??[];return is.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-64 mt-4","data-testid":"adopted-loading"}):is.isError?jsxRuntimeExports.jsxs("p",{className:"mt-4 text-xs text-amber-400/90","data-testid":"adopted-error",children:["Could not load what was adopted here: ",is.error.message]}):cs?jsxRuntimeExports.jsxs("div",{className:"mt-4 border-t border-border pt-3","data-testid":"adopted-section",children:[jsxRuntimeExports.jsxs("div",{...activatable(()=>ts(Oa=>!Oa)),"aria-expanded":$,"data-testid":"adopted-toggle",className:"flex items-center gap-2 text-sm cursor-pointer rounded-md -mx-1 px-1 py-1 hover:bg-secondary/30 transition-colors",children:[jsxRuntimeExports.jsx(ChevronRight,{"aria-hidden":!0,className:cn$1("h-4 w-4 shrink-0 text-muted-foreground transition-transform",$&&"rotate-90")}),jsxRuntimeExports.jsxs("span",{children:["Adopted into this project · ",cs.total,cs.total>0&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[" (",cs.byActor.auto," automatic)"]})]}),jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"Suggestions that were written into this project's instruction file. Automatic ones were accepted by the auto-accept cron with nobody watching — read the evidence line on each and retract anything that is not true of your project.",children:jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground underline decoration-dotted",children:"what is this?"})})]}),$&&jsxRuntimeExports.jsxs("div",{"data-testid":"adopted-list",children:[cs.total===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"Nothing has been adopted into this project yet."}):Qr.map(Oa=>jsxRuntimeExports.jsx(AdoptedRow,{row:Oa,projectPath:es},Oa.id)),is.hasNextPage&&jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"cursor-pointer mt-2",onClick:()=>is.fetchNextPage(),disabled:is.isFetchingNextPage,"data-testid":"adopted-load-more",children:is.isFetchingNextPage?"Loading…":`Load more (${cs.total-Qr.length} remaining)`})]})]}):null}function SuggestionsListPage(){const es=useProjectPaths(),$=es.data??[],ts=useSuggestionsForProjects($),is=es.isLoading,cs=ts.some(Oa=>Oa.isLoading),Qr=ts.map((Oa,Ia)=>{var La,Ba,Ma;return{projectPath:$[Ia],suggestions:((La=Oa.data)==null?void 0:La.suggestions)??[],experiments:(Ba=Oa.data)==null?void 0:Ba.experiments,crossProject:(Ma=Oa.data)==null?void 0:Ma.crossProject,isLoading:Oa.isLoading}}).filter(Oa=>Oa.projectPath),ja=Qr.reduce((Oa,Ia)=>Oa+Ia.suggestions.length,0),Na=Qr.flatMap(Oa=>Oa.suggestions.map(Ia=>Ia.instructionId)),{data:Aa}=useSuggestionImpacts(Na);return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h2",{className:"text-2xl font-bold tracking-tight flex items-center gap-2",children:[jsxRuntimeExports.jsx(Lightbulb,{className:"h-6 w-6"}),"Suggestions"]}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Precomputed instruction suggestions for your recent projects. Updated daily at 04:30."})]}),is?jsxRuntimeExports.jsx("div",{className:"space-y-4",children:Array.from({length:3}).map((Oa,Ia)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-40 rounded-lg"},Ia))}):Qr.length===0?jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No recent projects found. Run a session through Claude Code or Cursor to populate this view."}):jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[!cs&&ja===0&&jsxRuntimeExports.jsx("div",{className:"text-center py-6 text-muted-foreground","data-testid":"no-open-suggestions",children:"No open suggestions. The cron runs daily at 04:30 and scores your recent projects against your library."}),Qr.map(Oa=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base font-mono truncate",children:Oa.projectPath})}),jsxRuntimeExports.jsxs(CardContent,{children:[Oa.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-16"}):Oa.suggestions.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No suggestions for this project."}):jsxRuntimeExports.jsx("div",{children:Oa.suggestions.map(Ia=>{var La,Ba;return jsxRuntimeExports.jsx(SuggestionRow,{suggestion:Ia,projectPath:Oa.projectPath,verdict:Aa==null?void 0:Aa[Ia.instructionId],experiment:(La=Oa.experiments)==null?void 0:La[Ia.instructionId],evidence:(Ba=Oa.crossProject)==null?void 0:Ba[Ia.instructionId]},Ia.id)})}),jsxRuntimeExports.jsx(AdoptedDisclosure,{projectPath:Oa.projectPath})]})]},Oa.projectPath))]})]})}function useInstructionExperiments(es=50){return useQuery({queryKey:["instruction-experiments",es],queryFn:()=>apiGet(`/api/instruction-experiments?limit=${es}`)})}const LIMIT=50,pp=es=>`${es>0?"+":""}${(es*100).toFixed(0)}pp`;function VerdictHeadline({verdict:es}){if(es.resolution==="resolved"&&es.delta!=null&&es.ci!=null){const $=es.delta>0;return jsxRuntimeExports.jsxs("div",{className:"space-y-1","data-testid":"verdict-resolved",children:[jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("font-mono text-sm",$?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40"),"data-testid":"verdict-delta",children:[pp(es.delta)," outcome"]}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sessions assigned this instruction scored measurably"," ",$?"better":"worse"," than sessions assigned to control. This measures general session outcomes, not the specific behavior the instruction targets."]}),jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-muted-foreground","data-testid":"verdict-ci",children:["95% CI ",pp(es.ci.lower)," to ",pp(es.ci.upper)," · n=",es.measured.treated," ","treated / ",es.measured.control," control"]})]})}return es.invalidTemplate?jsxRuntimeExports.jsx("p",{className:"text-sm text-amber-400",children:"Unfilled template — no improvement decision is supported."}):es.contentChanged?jsxRuntimeExports.jsxs("div",{className:"space-y-1","data-testid":"verdict-edited",children:[jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"The instruction was edited while the experiment ran, so the arms measured different texts and no verdict transfers to the new content. The experiment stopped; the instruction re-enters testing as new content.",children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-sm text-amber-400 border-amber-400/40",children:"edited mid-test"})}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason})]}):es.randomisationSuspect?jsxRuntimeExports.jsxs("div",{className:"space-y-1","data-testid":"verdict-suspect",children:[jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"The two arms ran at different times. Randomisation interleaves them by construction, so this is evidence the assignment itself broke — an experiment created mid-stream, a re-salted experiment, or a backfilled arm. More sessions will not resolve it.",children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-sm text-amber-400 border-amber-400/40",children:"randomisation suspect"})}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason})]}):es.resolution==="insufficient"?jsxRuntimeExports.jsxs("div",{className:"space-y-1","data-testid":"verdict-insufficient",children:[jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"Not enough graded sessions on one or both arms yet, so no number is shown rather than a fabricated one. Check whether assigned sessions are being captured and graded before waiting for more data.",children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-sm text-muted-foreground",children:"insufficient data"})}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-1","data-testid":"verdict-inconclusive",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-sm text-muted-foreground",children:"inconclusive"}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason})]})}function ArmCounts({verdict:es}){const $=es.assigned.treated+es.assigned.control,ts=es.measured.treated+es.measured.control,is=$-ts,cs=({label:Qr,arm:ja})=>jsxRuntimeExports.jsxs("div",{className:"contents",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:Qr}),jsxRuntimeExports.jsx("span",{className:"text-right font-mono","data-testid":`assigned-${ja}`,children:es.assigned[ja]}),jsxRuntimeExports.jsx("span",{className:"text-right font-mono","data-testid":`measured-${ja}`,children:es.measured[ja]})]});return jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto] gap-x-6 gap-y-1 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"arm"}),jsxRuntimeExports.jsx("span",{className:"text-right text-xs uppercase tracking-wide text-muted-foreground",children:jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"Sessions bucketed into this arm before anything was injected.",children:jsxRuntimeExports.jsx("span",{className:"cursor-help border-b border-dotted border-muted-foreground/50",children:"assigned"})})}),jsxRuntimeExports.jsx("span",{className:"text-right text-xs uppercase tracking-wide text-muted-foreground",children:jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:"Assigned sessions that came back with a graded outcome. This is the verdict's real n.",children:jsxRuntimeExports.jsx("span",{className:"cursor-help border-b border-dotted border-muted-foreground/50",children:"measured"})})}),jsxRuntimeExports.jsx(cs,{label:"treated (assigned)",arm:"treated"}),jsxRuntimeExports.jsx(cs,{label:"control (assigned)",arm:"control"})]}),es.evidence&&jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground space-y-1","data-testid":"evidence-gaps",children:[jsxRuntimeExports.jsxs("p",{children:["Decision requires at least ",es.evidence.decisionMinPerArm," measured sessions per arm and a supported result."]}),jsxRuntimeExports.jsxs("p",{children:["Missing capture: ",es.evidence.missingSession.treated," treated / ",es.evidence.missingSession.control," control. Captured without a gradeable outcome: ",es.evidence.missingOutcome.treated," treated / ",es.evidence.missingOutcome.control," control."]}),jsxRuntimeExports.jsx("p",{children:"Assignment records do not confirm delivery or use of the instruction. Outcomes measure overall session success."})]}),is>0&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground","data-testid":"ungraded-note",children:[is," assigned session",is===1?"":"s"," ",is===1?"has":"have"," no graded outcome yet — counted as assigned, not toward the verdict."]})]})}function ExperimentCard({experiment:es}){return jsxRuntimeExports.jsxs(Card,{"data-testid":"experiment-card","data-experiment-id":es.id,children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[jsxRuntimeExports.jsx(CardTitle,{className:"min-w-0 break-words text-base","data-testid":"experiment-name",children:es.instructionName}),jsxRuntimeExports.jsx(ProvenanceBadge,{source:es.instructionSource}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("text-xs",es.status==="running"?"text-teal-400 border-teal-400/40":"text-muted-foreground"),children:es.status}),es.source!=="manual"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-muted-foreground","data-testid":"source-badge",children:es.source==="groom"?"nominated by grooming":es.source==="trial"?"trial":"borrowed evidence"}),(es.stoppedReason==="trial_neutral"||es.stoppedReason==="trial_inconclusive")&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-muted-foreground","data-testid":"stopped-reason-badge",children:"ended · inconclusive"}),es.stoppedReason==="invalid_template"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-amber-400",children:"ended · unfilled template"}),es.stoppedReason==="delivery_refused"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-amber-400",children:"ended · delivery refused"}),es.stoppedReason==="content_changed"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-amber-400 border-amber-400/40","data-testid":"stopped-reason-badge",children:"ended · content or delivery changed"}),es.graduation&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:cn$1("font-mono text-xs",es.graduation.decision==="always"?"text-teal-400 border-teal-400/40":"text-red-400 border-red-400/40"),"data-testid":"graduation-badge",children:["graduated · ",es.graduation.decision==="always"?"always inject":"never inject"]})]}),jsxRuntimeExports.jsx("p",{className:"min-w-0 break-all font-mono text-xs text-muted-foreground",children:es.projectPath})]}),jsxRuntimeExports.jsx(CardContent,{className:"grid gap-6 md:grid-cols-2",children:es.verdict?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(VerdictHeadline,{verdict:es.verdict}),jsxRuntimeExports.jsx(ArmCounts,{verdict:es.verdict})]}):jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"This experiment is no longer readable — it was removed while the page was open."})})]})}function ExperimentsListPage(){const{data:es,isLoading:$,isError:ts,error:is}=useInstructionExperiments(LIMIT),cs=(es==null?void 0:es.experiments)??[],Qr=(es==null?void 0:es.total)??0;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h2",{className:"flex items-center gap-2 text-2xl font-bold tracking-tight",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"h-6 w-6"}),"Experiments"]}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Instructions being withheld from half your sessions, so the difference they make is measured rather than assumed."})]}),$?jsxRuntimeExports.jsx("div",{className:"space-y-4",children:Array.from({length:2}).map((ja,Na)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-48 rounded-lg"},Na))}):ts?jsxRuntimeExports.jsxs("div",{className:"py-12 text-center text-muted-foreground","data-testid":"experiments-error",children:["Could not load experiments: ",is.message]}):cs.length===0?jsxRuntimeExports.jsx("div",{className:"py-12 text-center text-muted-foreground","data-testid":"experiments-empty",children:"No instructions are under test. An instruction enters the loop when it is nominated for measurement — until then, nothing is being withheld from any session."}):jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[cs.map(ja=>jsxRuntimeExports.jsx(ExperimentCard,{experiment:ja},ja.id)),Qr>cs.length&&jsxRuntimeExports.jsxs("p",{className:"text-center text-xs text-muted-foreground","data-testid":"experiments-truncated",children:["Showing ",cs.length," of ",Qr,"."]})]})]})}function isNotable(es){return es.outcome==="decided"||es.outcome==="failed"?!0:typeof es.detail=="string"&&es.detail.trim().length>0}function partitionFinished(es){const $=[],ts=new Map;for(const cs of es){if(isNotable(cs)){$.push(cs);continue}const Qr=ts.get(cs.kind)??{kind:cs.kind,count:0,outcomes:{},totalSeconds:0,slowestSeconds:0};Qr.count+=1,Qr.outcomes[cs.outcome]=(Qr.outcomes[cs.outcome]??0)+1;const ja=cs.durationSeconds??0;Qr.totalSeconds+=ja,Qr.slowestSeconds=Math.max(Qr.slowestSeconds,ja),ts.set(cs.kind,Qr)}const is=[...ts.values()].sort((cs,Qr)=>Qr.count-cs.count);return{notable:$,routine:is,routineCount:is.reduce((cs,Qr)=>cs+Qr.count,0)}}function duration(es){return es==null?"—":es<60?`${es}s`:es<3600?`${Math.floor(es/60)}m ${es%60}s`:`${Math.floor(es/3600)}h ${Math.floor(es%3600/60)}m`}function shortDuration(es){return es==null?"—":es<60?`${Math.round(es)}s`:es<3600?`${Math.round(es/60)}m`:`${(es/3600).toFixed(1)}h`}function headlineState(es){const{workerPresent:$,leaseUnhealthy:ts,readyToApply:is,failedRecently:cs,running:Qr,queued:ja,engineBlocked:Na}=es;return ts?{tone:"critical",text:"A job is claimed but its lease has expired — the worker took work and stopped."}:$?Na>0?{tone:"critical",text:(Na===1?"1 job needs":`${Na} jobs need`)+" a local LLM engine (`claude` or `codex`) that the worker cannot find — they will finish empty, not fail."}:is>0?{tone:"action",text:`${is} measured edit${is===1?"":"s"} waiting for you to apply.`}:cs>0?{tone:"warn",text:`${cs} job${cs===1?"":"s"} failed in this window.`}:Qr>0||ja>0?{tone:"calm",text:`${Qr} running, ${ja} queued.`}:{tone:"calm",text:"Idle — nothing queued, nothing waiting on you."}:{tone:"critical",text:"No worker is connected, so nothing will run."}}function loopFunnel(es){const $=es.window??{hours:0,landed:es.applied+es.suggestionsAccepted,decisions:es.decisions,promotionsApplied:es.applied,suggestionsSurfaced:es.suggestionsProposed,suggestionsAccepted:es.suggestionsAccepted,suggestionsDeclined:0},ts=$.suggestionsAccepted+$.suggestionsDeclined,is=es.byDecision.promote;return{windowHours:$.hours,landed:$.landed,landedTotal:es.landedTotal??es.applied+es.suggestionsAccepted,surfaced:$.suggestionsSurfaced,accepted:$.suggestionsAccepted,declined:$.suggestionsDeclined,answered:ts,answeredRate:$.suggestionsSurfaced>0?ts/$.suggestionsSurfaced:null,pending:es.suggestionsPending??0,promotesApplied:es.applied,promotes:is,decisionsWithoutEdit:es.byDecision.revert+es.byDecision.refuse,lastLandedAt:[es.lastAppliedAt,es.lastAcceptedAt].filter(cs=>typeof cs=="string"&&cs.length>0).sort().at(-1)??null,neverActed:(es.landedTotal??es.applied+es.suggestionsAccepted)===0&&es.decisions+es.suggestionsProposed>0}}const FILTERS=[{key:"all",label:"All",testId:"filter-all"},{key:"evolution",label:"Evolution",testId:"filter-evolution"},{key:"decided",label:"Decisions",testId:"filter-decided"},{key:"skipped",label:"Skipped",testId:"filter-skipped"},{key:"failed",label:"Failed",testId:"filter-failed"}],HISTORY_RANGES=[{hours:24,label:"24h",testId:"range-24"},{hours:168,label:"7d",testId:"range-168"},{hours:720,label:"30d",testId:"range-720"}],GROUP="inline-flex flex-wrap items-center gap-0.5 self-start rounded-lg border border-border bg-card p-0.5",SEGMENT="inline-flex min-h-11 cursor-pointer items-center whitespace-nowrap rounded-md px-2.5 text-xs transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",SEGMENT_ACTIVE="bg-teal-400/10 font-medium text-teal-400",SEGMENT_IDLE="text-muted-foreground hover:bg-muted/60 hover:text-foreground";function LoopRangeControl({hours:es,onChange:$}){return jsxRuntimeExports.jsx("div",{className:GROUP,role:"group","aria-label":"History range","data-testid":"loop-controls",children:HISTORY_RANGES.map(ts=>jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>$({hours:ts.hours}),"aria-pressed":ts.hours===es,className:cn$1(SEGMENT,ts.hours===es?SEGMENT_ACTIVE:SEGMENT_IDLE),"data-testid":ts.testId,children:ts.label},ts.hours))})}function FinishedControls({counts:es,filter:$,limit:ts,onChange:is}){return jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 font-normal",children:[jsxRuntimeExports.jsx("div",{className:GROUP,role:"group","aria-label":"Finished job filter",children:FILTERS.map(cs=>{const Qr=cs.key===$,ja=es[cs.key];return jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>is({filter:cs.key}),"aria-pressed":Qr,className:cn$1(SEGMENT,Qr?SEGMENT_ACTIVE:SEGMENT_IDLE,!Qr&&ja===0&&"opacity-60"),"data-testid":cs.testId,children:[cs.label,jsxRuntimeExports.jsx("span",{className:"pl-1.5 tabular-nums opacity-70",children:ja})]},cs.key)})}),jsxRuntimeExports.jsxs("label",{className:"ml-auto flex items-center gap-1 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Rows"}),jsxRuntimeExports.jsx("select",{value:ts,onChange:cs=>is({limit:Number(cs.target.value)}),className:cn$1("min-h-11 cursor-pointer rounded-lg border border-border bg-card px-2.5 text-xs","text-muted-foreground transition-colors duration-150 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"),"data-testid":"limit-select",children:PAGE_SIZES.map(cs=>jsxRuntimeExports.jsxs("option",{value:cs,children:[cs," rows"]},cs))})]})]})}function Funnel({f:es}){const $=ts=>es.surfaced>0?ts/es.surfaced*100:0;return jsxRuntimeExports.jsxs("div",{className:"space-y-1.5",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-baseline gap-x-1.5 gap-y-0.5 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{className:"font-semibold tabular-nums text-foreground",children:es.surfaced}),jsxRuntimeExports.jsx("span",{children:"surfaced"}),jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3 shrink-0","aria-hidden":!0}),jsxRuntimeExports.jsx("span",{className:"font-semibold tabular-nums text-foreground","data-testid":"funnel-answered",children:es.answered}),jsxRuntimeExports.jsx("span",{children:"answered"}),jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3 shrink-0","aria-hidden":!0}),jsxRuntimeExports.jsx("span",{className:"font-semibold tabular-nums text-teal-400","data-testid":"changes-accepted",children:es.accepted}),jsxRuntimeExports.jsx("span",{children:"accepted"})]}),jsxRuntimeExports.jsxs("div",{className:"flex h-1.5 overflow-hidden rounded-full bg-border","aria-hidden":!0,children:[jsxRuntimeExports.jsx("div",{className:"bg-teal-400 transition-[width] duration-500 ease-out",style:{width:`${$(es.accepted)}%`}}),jsxRuntimeExports.jsx("div",{className:"bg-muted-foreground/50 transition-[width] duration-500 ease-out",style:{width:`${$(es.declined)}%`}})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground","data-testid":"funnel-rate",children:es.answeredRate==null?"Nothing surfaced in this window.":`${Math.round(es.answeredRate*100)}% answered · ${es.declined} declined · ${es.pending} still open`})]})}function Chip({value:es,of:$,label:ts,good:is,testId:cs,ratioTestId:Qr,to:ja}){const Na=jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("span",{className:cn$1("font-semibold tabular-nums",is?"text-teal-400":"text-foreground"),"data-testid":cs,children:es}),$!=null&&jsxRuntimeExports.jsxs("span",{className:"tabular-nums text-muted-foreground",children:["/",$]})," ",jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:ts})]});return ja?jsxRuntimeExports.jsx(Link,{to:ja,className:"inline-block min-h-11 whitespace-nowrap leading-[2.75rem] transition-colors duration-150 hover:text-foreground","data-testid":Qr,children:Na}):jsxRuntimeExports.jsx("span",{className:"whitespace-nowrap","data-testid":Qr,children:Na})}function KpiStrip({status:es,insights:$}){const{changes:ts,counts:is}=es,cs=loopFunnel(ts),Qr=HISTORY_RANGES.find(ja=>ja.hours===cs.windowHours);return jsxRuntimeExports.jsx(Card,{className:cn$1(cs.neverActed&&"border-amber-400/40"),"data-testid":"changes-headline",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-0",children:[jsxRuntimeExports.jsxs("div",{className:"grid divide-y divide-border sm:grid-cols-[minmax(0,15.5rem)_minmax(0,1fr)] sm:divide-x sm:divide-y-0",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 px-4 py-3",children:[jsxRuntimeExports.jsxs("p",{className:"flex items-baseline gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:cn$1("text-4xl font-semibold tabular-nums",cs.landed>0?"text-teal-400":"text-muted-foreground"),"data-testid":"changes-landed",children:cs.landed}),Qr&&jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["in ",Qr.label]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"changes landed"}),jsxRuntimeExports.jsxs("p",{className:"pt-0.5 font-mono text-[11px] leading-snug text-muted-foreground/80","data-testid":"changes-landed-detail",children:[cs.landedTotal," all time",cs.lastLandedAt&&` · last ${cs.lastLandedAt.slice(0,10)}`]})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-2 px-4 py-3",children:[jsxRuntimeExports.jsx(Funnel,{f:cs}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 border-t border-border pt-1 text-xs",children:[jsxRuntimeExports.jsx(Chip,{value:cs.promotesApplied,of:cs.promotes||void 0,label:"promotes applied",good:cs.promotesApplied>0,testId:"changes-applied",ratioTestId:"changes-applied-ratio"}),jsxRuntimeExports.jsx(Chip,{value:is.experimentsRunning,label:"trials running",good:is.experimentsRunning>0,testId:"changes-trials",to:"/experiments"}),$&&jsxRuntimeExports.jsx(Chip,{value:$.repeated,of:$.distinct||void 0,label:"insights repeated",good:$.repeated>0,testId:"changes-insights"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-[11px] text-muted-foreground/80","data-testid":"changes-applied-detail",children:`${ts.byDecision.promote}P · ${ts.byDecision.revert}R · ${ts.byDecision.refuse}X`})]})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 border-t border-border px-4 py-1.5 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("span",{"data-testid":"apply-scope-note",children:"“Applied” updates the stored instruction body, not the file on disk."}),jsxRuntimeExports.jsx(InfoTip,{content:'Deciding is not applying. A proposal can be measured, gated and recorded as "promote" and still never touch a file — that separation is deliberate (effectiveness.md §13). Applying updates `eval_targets.content`, which is what future eval runs measure against; the only code that writes an instruction FILE is retraction, and only for removals.'}),cs.neverActed&&jsxRuntimeExports.jsx("span",{className:"text-amber-400/90","data-testid":"never-acted",children:"· Measuring, not acting: nothing has ever been applied or accepted."})]})]})})}function windowLabel(es){return es%24===0&&es>=48?`${es/24}d`:`${es}h`}function RunningRow({job:es}){return jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3 py-2","data-testid":"running-job",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4 shrink-0 text-teal-400"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono text-sm",children:es.kind}),!es.leaseHealthy&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"shrink-0 border-red-400/40 text-red-400",children:"lease expired"})]}),es.label&&jsxRuntimeExports.jsx("p",{className:"truncate text-sm text-muted-foreground",title:es.label,children:es.label})]}),jsxRuntimeExports.jsx("span",{className:"shrink-0 font-mono text-sm text-muted-foreground",children:duration(es.elapsedSeconds)})]})}function QueuedRow({job:es}){return jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3 py-2","data-testid":"queued-job",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[jsxRuntimeExports.jsx(Clock,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"truncate font-mono text-sm",children:es.kind})]}),es.label&&jsxRuntimeExports.jsx("p",{className:"truncate text-sm text-muted-foreground",title:es.label,children:es.label})]}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 font-mono text-sm text-muted-foreground",children:["waited ",duration(es.waitedSeconds)]})]})}const OUTCOME_ICON={ok:jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-teal-400"}),decided:jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 shrink-0 text-teal-400"}),skipped:jsxRuntimeExports.jsx(CircleMinus,{className:"h-4 w-4 shrink-0 text-amber-400"}),failed:jsxRuntimeExports.jsx(CircleX,{className:"h-4 w-4 shrink-0 text-red-400"})};function FinishedRow({job:es}){return jsxRuntimeExports.jsxs("div",{className:"py-2","data-testid":`finished-job-${es.outcome}`,children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[OUTCOME_ICON[es.outcome],jsxRuntimeExports.jsx("span",{className:"truncate font-mono text-sm",children:es.kind}),es.outcome==="skipped"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"shrink-0 border-amber-400/40 text-amber-400",children:"skipped"}),es.outcome==="decided"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"shrink-0 border-teal-400/40 text-teal-400",children:es.reason})]}),jsxRuntimeExports.jsx("span",{className:"shrink-0 font-mono text-xs text-muted-foreground",children:duration(es.durationSeconds)})]}),es.label&&jsxRuntimeExports.jsx("p",{className:"truncate pl-6 text-sm text-muted-foreground",title:es.label,children:es.label}),es.detail&&jsxRuntimeExports.jsx("p",{className:"whitespace-pre-wrap break-words pl-6 font-mono text-xs text-amber-400/90","data-testid":"finished-reason",children:es.detail})]})}function RoutineRow({group:es}){const $=es.outcomes.failed??0;return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-3 py-1.5 text-xs","data-testid":"routine-group",children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"truncate font-mono text-muted-foreground",children:es.kind}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 tabular-nums text-muted-foreground/70",children:["×",es.count]}),$>0&&jsxRuntimeExports.jsxs("span",{className:"shrink-0 text-amber-400/90","data-testid":"routine-failed",children:[$," failed"]})]}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 tabular-nums text-muted-foreground/70",children:["slowest ",shortDuration(es.slowestSeconds)]})]})}function FinishedList({status:es,idle:$,workerPresent:ts,controls:is}){const[cs,Qr]=reactExports.useState(!1),{notable:ja,routine:Na,routineCount:Aa}=partitionFinished(es.recent);return jsxRuntimeExports.jsxs(Card,{className:"gap-2",children:[jsxRuntimeExports.jsxs(CardHeader,{className:"gap-2 pb-0",children:[jsxRuntimeExports.jsxs(CardTitle,{className:"flex flex-wrap items-baseline gap-x-2 text-base",children:["Finished",jsxRuntimeExports.jsxs("span",{className:"text-xs font-normal text-muted-foreground","data-testid":"finished-window",children:["last ",windowLabel(es.windowHours),es.filter!=="all"&&` · ${es.filter}`,es.recentTotal>es.recent.length&&` · ${es.recent.length} of ${es.recentTotal}`]})]}),is]}),jsxRuntimeExports.jsx(CardContent,{className:"pt-0",children:es.recent.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground","data-testid":"nothing-finished",children:es.filter!=="all"&&es.filterCounts.all>0?`No ${es.filter} jobs in the last ${windowLabel(es.windowHours)} — ${es.filterCounts.all} finished overall.`:$&&!ts?"No worker connected, so nothing has run.":`No jobs finished in the last ${windowLabel(es.windowHours)}.`}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ja.length>0?jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:ja.map(Oa=>jsxRuntimeExports.jsx(FinishedRow,{job:Oa},Oa.id))}):jsxRuntimeExports.jsx("p",{className:"py-1 text-sm text-muted-foreground","data-testid":"nothing-notable",children:"Nothing decided, failed or explained itself — just throughput."}),Aa>0&&jsxRuntimeExports.jsxs("div",{className:"mt-2 border-t border-border pt-2",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>Qr(Oa=>!Oa),className:"flex min-h-11 w-full cursor-pointer items-center justify-between gap-2 text-xs text-muted-foreground transition-colors duration-150 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-expanded":cs,"data-testid":"toggle-routine",children:[jsxRuntimeExports.jsxs("span",{children:[Aa," routine job",Aa===1?"":"s"," across ",Na.length," ","kind",Na.length===1?"":"s"]}),cs?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3 shrink-0"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3 shrink-0"})]}),cs&&jsxRuntimeExports.jsx("div",{className:"reveal divide-y divide-border pt-1",children:Na.map(Oa=>jsxRuntimeExports.jsx(RoutineRow,{group:Oa},Oa.kind))})]})]})})]})}function when(es){return es?new Date(es).toLocaleDateString():"never"}function DeliveryRow({project:es}){const $=es.canonicalPath;return jsxRuntimeExports.jsxs("div",{className:"py-2","data-testid":es.stale?"delivery-stale":"delivery-row",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"truncate text-sm",title:es.name??"",children:es.name??"(unnamed project)"}),jsxRuntimeExports.jsx("p",{className:"break-all font-mono text-xs text-muted-foreground","data-testid":"delivery-path",children:$??"no checkout recorded — nothing can be written"})]}),jsxRuntimeExports.jsxs("span",{className:"shrink-0 text-right font-mono text-[11px] text-muted-foreground",children:[es.suggestionsAccepted," adopted"]})]}),jsxRuntimeExports.jsxs("p",{className:"pt-0.5 font-mono text-[11px] text-muted-foreground/80",children:["seen ",when(es.canonicalLastSeenAt)," · analysed ",when(es.lastAnalysedAt)," ·"," ",es.suggestionsPending," pending"]}),es.stale&&jsxRuntimeExports.jsxs("p",{className:"flex items-start gap-1.5 pt-1 text-xs text-amber-400/90","data-testid":"delivery-stale-note",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"mt-0.5 h-3 w-3 shrink-0"}),jsxRuntimeExports.jsx("span",{children:"This project is active but its recorded checkout is not — edits written here land in a path nobody is working in."})]})]})}function DeliveryBlock({status:es}){const{projects:$,total:ts,staleCount:is}=es.delivery;return jsxRuntimeExports.jsxs(Card,{className:cn$1("gap-2",is>0&&"border-amber-400/40"),"data-testid":"delivery",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex flex-wrap items-baseline gap-x-2 text-base",children:["Where edits land",ts>$.length&&jsxRuntimeExports.jsxs("span",{className:"text-xs font-normal text-muted-foreground",children:[$.length," of ",ts," projects"]}),jsxRuntimeExports.jsx(InfoTip,{content:"Insights analyse a project at its canonical checkout path, and the auto-accept actuator writes the CLAUDE.md under that same path. If the path is stale, every stage still succeeds — it just succeeds somewhere nobody is working. Ranking is live-before-stale, then real checkout before worktree, then most recently seen."})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"pt-0",children:[is>0&&jsxRuntimeExports.jsxs("p",{className:"pb-2 text-xs text-amber-400/90","data-testid":"delivery-stale-summary",children:[is," of ",ts," project",ts===1?"":"s"," would be written to a checkout that has gone quiet."]}),$.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground","data-testid":"delivery-empty",children:"No project has recorded sessions yet, so there is nowhere to write."}):jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:$.map(cs=>jsxRuntimeExports.jsx(DeliveryRow,{project:cs},cs.projectId))})]})]})}function AdoptionBlock({status:es}){const[$,ts]=reactExports.useState("all"),[is,cs]=reactExports.useState("all"),[Qr,ja]=reactExports.useState("all"),Na=es.adoption??{available:!1,counts:{},applications:[]},Aa=reactExports.useMemo(()=>Na.applications.filter(Ia=>($==="all"||Ia.harness===$)&&(is==="all"||Ia.artifact===is)&&(Qr==="all"||Ia.status===Qr)),[Na.applications,$,is,Qr]),Oa=Ia=>[...new Set(Na.applications.map(La=>La[Ia]))].sort();return jsxRuntimeExports.jsxs(Card,{className:"gap-2","data-testid":"adoption-ledger",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center justify-between text-base",children:["Cross-harness adoption",jsxRuntimeExports.jsx(Link,{to:"/insights",className:"inline-flex min-h-11 items-center text-xs font-normal text-teal-400 transition-colors duration-150 hover:underline",children:"View insights"})]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-3",children:Na.available?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-2",children:[["Harness",$,ts,Oa("harness")],["Artifact",is,cs,Oa("artifact")],["State",Qr,ja,Oa("status")]].map(([Ia,La,Ba,Ma])=>jsxRuntimeExports.jsxs("label",{className:"text-xs text-muted-foreground",children:[Ia," ",jsxRuntimeExports.jsxs("select",{value:La,onChange:qa=>Ba(qa.target.value),className:"rounded border border-border bg-background px-2 py-1 text-foreground",children:[jsxRuntimeExports.jsx("option",{value:"all",children:"all"}),Ma.map(qa=>jsxRuntimeExports.jsx("option",{value:qa,children:qa},qa))]})]},Ia))}),jsxRuntimeExports.jsx("p",{className:"font-mono text-xs text-muted-foreground",children:Object.entries(Na.counts).filter(([,Ia])=>Ia>0).map(([Ia,La])=>`${La} ${Ia}`).join(" · ")||"No applications yet"}),jsxRuntimeExports.jsxs("div",{className:"divide-y divide-border",children:[Aa.map(Ia=>jsxRuntimeExports.jsxs("details",{className:"py-2",children:[jsxRuntimeExports.jsxs("summary",{className:"flex cursor-pointer list-none items-center justify-between gap-2 text-sm",children:[jsxRuntimeExports.jsx("span",{className:"min-w-0 truncate",children:Ia.title}),jsxRuntimeExports.jsxs("span",{className:"flex shrink-0 gap-1",children:[jsxRuntimeExports.jsx(Badge,{variant:"outline",children:Ia.harness}),jsxRuntimeExports.jsx(Badge,{variant:"outline",children:Ia.status})]})]}),jsxRuntimeExports.jsxs("div",{className:"pt-2 font-mono text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("p",{children:[Ia.artifact," · ",Ia.applyMode," apply"]}),jsxRuntimeExports.jsxs("p",{className:"break-all",children:[Ia.projectPath,"/",Ia.targetPath]}),Ia.verdictDetail&&jsxRuntimeExports.jsx("p",{className:"pt-1 font-sans",children:Ia.verdictDetail})]})]},Ia.id)),Aa.length===0&&jsxRuntimeExports.jsx("p",{className:"py-2 text-sm text-muted-foreground",children:"No applications match these filters."})]})]}):jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Adoption tracking is gated off until migration 00187 is applied."})})]})}function PromotionPathsBlock({status:es}){const $=es.promotionPaths??{projects:[]},ts=new Map(es.delivery.projects.map(cs=>[cs.projectId,cs.name])),is=$.projects.filter(cs=>cs.trials.running>0||cs.trials.orphaned>0||cs.trials.eligible>0||cs.autoAccept.usedInWindow>0||cs.autoAccept.eligible>0);return jsxRuntimeExports.jsxs(Card,{className:"gap-2","data-testid":"promotion-paths",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"Promotion throughput"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-4",children:is.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground","data-testid":"paths-empty",children:"Nothing is being trialled or adopted anywhere — no eligible suggestions, no running experiments, no budget spent."}):is.map(cs=>jsxRuntimeExports.jsx(ProjectPaths,{paths:cs,name:ts.get(cs.projectId)??null},cs.projectId))})]})}function ProjectPaths({paths:es,name:$}){const{trials:ts,autoAccept:is}=es,cs=Math.max(0,is.maxPerWindow-is.usedInWindow);return jsxRuntimeExports.jsxs("div",{className:"space-y-1","data-testid":"paths-project",children:[jsxRuntimeExports.jsx("p",{className:"truncate text-sm font-medium",children:$??es.projectId}),jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-muted-foreground","data-testid":"paths-trials",children:[ts.running,"/",ts.maxConcurrent," trial slots in use · ",ts.eligible," eligible waiting",ts.blocked==="concurrency"&&" · at capacity",ts.blocked==="no-candidates"&&ts.running===0&&" · nothing to trial"]}),ts.orphaned>0&&jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-amber-400/90","data-testid":"paths-orphaned",children:[ts.orphaned," running trial",ts.orphaned===1?"":"s"," aimed at a stale subpath — no sessions arrive there, so they will never conclude"]}),jsxRuntimeExports.jsx("p",{className:"font-mono text-xs text-muted-foreground","data-testid":"paths-auto-accept",children:is.enabled?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["auto-accept ",is.usedInWindow,"/",is.maxPerWindow," used this"," ",is.windowDays,"d window · ",is.eligible," above the bar",cs===0&&is.windowResetsAt&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" · budget resets ",new Date(is.windowResetsAt).toLocaleDateString()]})]}):jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:"auto-accept is off for this project"})})]})}function ProvenanceBlock(){const{data:es}=useProvenanceImpact();return!es||es.groups.length===0?null:jsxRuntimeExports.jsxs(Card,{className:"gap-2",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"Does generated advice help?"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx("div",{className:"overflow-x-auto",children:jsxRuntimeExports.jsxs("table",{className:"w-full text-sm","data-testid":"provenance-table",children:[jsxRuntimeExports.jsx("thead",{children:jsxRuntimeExports.jsxs("tr",{className:"text-left text-xs uppercase tracking-wide text-muted-foreground",children:[jsxRuntimeExports.jsx("th",{className:"py-1 pr-4 font-normal",children:"Source"}),jsxRuntimeExports.jsx("th",{className:"py-1 pr-4 font-normal",children:"Rules"}),jsxRuntimeExports.jsx("th",{className:"py-1 pr-4 font-normal",children:"Sessions reached"}),jsxRuntimeExports.jsx("th",{className:"py-1 pr-4 font-normal",children:"Accepted"}),jsxRuntimeExports.jsx("th",{className:"py-1 font-normal",children:"Measured effect"})]})}),jsxRuntimeExports.jsx("tbody",{children:es.groups.map($=>jsxRuntimeExports.jsxs("tr",{className:"border-t border-border",children:[jsxRuntimeExports.jsx("td",{className:"py-1.5 pr-4 font-mono text-xs",children:$.provenance}),jsxRuntimeExports.jsx("td",{className:"py-1.5 pr-4",children:$.instructions}),jsxRuntimeExports.jsx("td",{className:"py-1.5 pr-4",children:$.exposedSessions}),jsxRuntimeExports.jsx("td",{className:"py-1.5 pr-4",children:$.accepted}),jsxRuntimeExports.jsx("td",{className:"py-1.5",children:$.evidenceClass==="randomised"&&$.meanDelta!=null?jsxRuntimeExports.jsxs("span",{className:cn$1("font-mono",$.meanDelta>0?"text-teal-400":"text-red-400"),children:[$.meanDelta>0?"+":"",($.meanDelta*100).toFixed(1),"pp",jsxRuntimeExports.jsxs("span",{className:"pl-1 text-xs text-muted-foreground",children:["(",$.randomisedVerdicts," verdict",$.randomisedVerdicts===1?"":"s",")"]})]}):jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"not yet measurable"})})]},$.provenance))})]})}),es.note&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-400/90","data-testid":"provenance-note",children:es.note})]})]})}function InFlightCard({summary:es}){return es.running.length===0&&es.queued.length===0?null:jsxRuntimeExports.jsxs(Card,{className:"gap-2",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center justify-between text-base",children:["In flight",jsxRuntimeExports.jsx(InfoTip,{content:"Jobs are claimed one at a time by your local worker, oldest first, and background crons are claimed last so they never starve user-visible work. A long wait here is usually queueing, not a failure."})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3 pt-0",children:[es.running.length>0&&jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:es.running.map($=>jsxRuntimeExports.jsx(RunningRow,{job:$},$.id))}),es.queued.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("p",{className:"pb-1 text-xs uppercase tracking-wide text-muted-foreground",children:["Queued (",es.queued.length,")"]}),jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:es.queued.map($=>jsxRuntimeExports.jsx(QueuedRow,{job:$},$.id))})]})]})]})}function InsightsMemory({insights:es,suggestions:$}){return jsxRuntimeExports.jsxs(Card,{className:"gap-2",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"Insights memory"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{"data-testid":"insights-memory",children:[jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-muted-foreground",children:[es.entries," entries · ",es.distinct," distinct · ",es.repeated," repeated ·"," ",es.dismissed," dismissed · max seen ×",es.maxTimesGenerated]}),es.entries>0&&es.repeated===0&&jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-amber-400/90",children:"Nothing has repeated yet — identity is a verbatim content hash, so a paraphrase counts as a new ask."})]}),jsxRuntimeExports.jsxs("p",{className:"border-t border-border pt-2 text-xs text-muted-foreground",children:["suggestions:"," ",Object.entries($).map(([ts,is])=>`${is} ${ts}`).join(" · ")||"none"]})]})]})}function OperationalDetails({summary:es,query:$,onChange:ts,onDiagnostics:is}){const[cs,Qr]=reactExports.useState(!1),{data:ja,isError:Na,isPlaceholderData:Aa}=useLoopDiagnostics($,{open:cs}),Oa=diagnosticsPanelState({open:cs,hasData:ja!=null,isError:Na});reactExports.useEffect(()=>{is==null||is(ja)},[ja,is]);const Ia=es.running.length===0&&es.queued.length===0;return jsxRuntimeExports.jsxs("section",{"data-testid":"operational-details","aria-labelledby":"operational-details-toggle",children:[jsxRuntimeExports.jsxs("button",{id:"operational-details-toggle",type:"button",onClick:()=>Qr(La=>!La),"aria-expanded":cs,"aria-controls":"operational-details-body",className:"flex min-h-11 w-full cursor-pointer items-center gap-2 rounded-md border border-border bg-card px-3 text-left text-sm transition-colors duration-150 hover:bg-muted/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","data-testid":"operational-details-toggle",children:[cs?jsxRuntimeExports.jsx(ChevronDown,{className:"h-4 w-4 shrink-0 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-medium",children:"Operational details"}),jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"in-flight and finished jobs, where edits land, throughput, adoption"})]}),Oa!=="closed"&&jsxRuntimeExports.jsxs("div",{id:"operational-details-body",className:cn$1("reveal space-y-4 pt-4 transition-opacity duration-200",Aa&&"opacity-50"),"data-testid":"operational-details-body",children:[Oa==="loading"&&jsxRuntimeExports.jsxs("div",{className:"space-y-4","data-testid":"diagnostics-loading",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"})]}),Oa==="error"&&jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsxs(CardContent,{className:"flex items-center gap-2 py-6 text-sm text-muted-foreground","data-testid":"diagnostics-error",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 shrink-0 text-amber-400"}),"Could not load the operational details. The summary above is still live."]})}),Oa==="ready"&&ja&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Na&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-400/90","data-testid":"diagnostics-stale",children:"The last refresh failed — showing the details as of the previous load."}),jsxRuntimeExports.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-4",children:[jsxRuntimeExports.jsx(InFlightCard,{summary:es}),jsxRuntimeExports.jsx(FinishedList,{status:ja,idle:Ia,workerPresent:es.worker.present,controls:jsxRuntimeExports.jsx(FinishedControls,{counts:ja.filterCounts,filter:$.filter,limit:$.limit,onChange:ts})}),jsxRuntimeExports.jsx(DeliveryBlock,{status:ja}),jsxRuntimeExports.jsx(PromotionPathsBlock,{status:ja})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-4",children:[jsxRuntimeExports.jsx(InsightsMemory,{insights:ja.insights,suggestions:es.counts.suggestions}),jsxRuntimeExports.jsx(AdoptionBlock,{status:ja}),jsxRuntimeExports.jsx(ProvenanceBlock,{})]})]})]})]})]})}function useLoopQuery(){const[es,$]=useSearchParams(),ts=(Na,Aa,Oa)=>Aa.includes(Na)?Na:Oa,is=Number(es.get("hours")),cs=Number(es.get("limit")),Qr={hours:HISTORY_RANGES.some(Na=>Na.hours===is)?is:24,limit:PAGE_SIZES.includes(cs)?cs:20,filter:ts(es.get("filter"),FINISHED_FILTERS,"all")};return{query:Qr,update:Na=>{const Aa={...Qr,...Na},Oa=new URLSearchParams;Aa.hours!==24&&Oa.set("hours",String(Aa.hours)),Aa.limit!==20&&Oa.set("limit",String(Aa.limit)),Aa.filter!=="all"&&Oa.set("filter",Aa.filter),$(Oa,{replace:!0})}}}function WorkerChip({status:es}){const{worker:$,verdict:ts}=es,is=$.present&&ts.severity!=="ok";return jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2","data-testid":"worker-chip",children:[jsxRuntimeExports.jsx("span",{className:cn$1("inline-block h-2 w-2 rounded-full",$.present?$.active?"bg-teal-400":"bg-amber-400":"bg-muted-foreground")}),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium",children:$.present?$.active?"Worker running":"Worker stale":"No worker seen"}),$.clientName&&jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs text-muted-foreground",children:[$.clientName," · ",$.clientVersion??"?",$.ageSeconds!=null&&` · ${duration($.ageSeconds)} ago`]}),is&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("min-w-0 whitespace-normal break-words text-left",ts.severity==="fail"?"border-red-400/40 text-red-400":"border-amber-400/40 text-amber-400"),children:ts.headline})]})}function PendingDiff({promotionId:es}){const[$,ts]=reactExports.useState(!1);return jsxRuntimeExports.jsxs("div",{className:"pt-2",children:[jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>ts(is=>!is),className:"inline-flex min-h-11 cursor-pointer items-center text-xs text-teal-400 transition-colors duration-150 hover:underline","data-testid":"toggle-pending-diff",children:$?"Hide the diff":"Show what it would change →"}),jsxRuntimeExports.jsx("div",{className:"pt-2",children:jsxRuntimeExports.jsx(PromotionDetailPanel,{promotionId:es,open:$,allowApply:!0,testId:"pending-diff"})})]})}function ReviewGateCallout({gate:es}){const $=(es==null?void 0:es.targets)??[];if(!(es!=null&&es.blocking)||$.length===0)return null;const ts=$[0];return jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-amber-400/50 bg-amber-400/10 p-4","data-testid":"review-gate",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1",children:[jsxRuntimeExports.jsxs("p",{className:"text-base font-semibold text-amber-300","data-testid":"review-gate-headline",children:["The loop is waiting on you — ",es.totalAwaitingReview," run",es.totalAwaitingReview===1?"":"s"," need human review"]}),jsxRuntimeExports.jsx(Link,{to:`/eval-targets/${ts.id}?tab=review`,className:"inline-flex min-h-[36px] items-center rounded-md border border-amber-400/60 bg-amber-400/10 px-3 text-sm font-medium text-amber-200 transition-colors duration-150 hover:bg-amber-400/20","data-testid":"review-gate-action",children:"Review runs →"})]}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-sm text-muted-foreground",children:"Nothing else can do this step: an LLM labeling anchors to calibrate an LLM judge is circular. Until these are labeled the loop keeps measuring and keeps refusing to decide."}),jsxRuntimeExports.jsx("ul",{className:"pt-2 space-y-1",children:$.map(is=>jsxRuntimeExports.jsxs("li",{className:"text-sm","data-testid":"review-gate-target",children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:is.name})," ",jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:["— ",is.awaitingReview," unreviewed, and"," ",jsxRuntimeExports.jsx("span",{className:"text-amber-300/90",children:"no human labels yet in this judge segment"}),"."]})]},is.id))})]})}function ReadyToApplyCallout({changes:es}){return es.readyToApply<=0?null:jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-teal-400/40 bg-teal-400/5 p-3","data-testid":"ready-to-apply",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"font-medium text-teal-400",children:[es.readyToApply," measured improvement",es.readyToApply===1?" is":"s are"," ","ready to apply"]})," ","— decided ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:"promote"}),", never applied, and still measured against the file as it stands today."]}),es.readyToApplyPromotionId&&jsxRuntimeExports.jsx(PendingDiff,{promotionId:es.readyToApplyPromotionId})]})}function RunNowButton(){const es=useRunLoopNow();return jsxRuntimeExports.jsxs("div",{className:"text-right",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:es.isPending,onClick:()=>es.mutate(),className:cn$1("cursor-pointer rounded border border-teal-400/40 px-3 py-1.5 text-sm text-teal-400 transition-colors duration-150 hover:bg-teal-400/10",es.isPending&&"opacity-60"),"data-testid":"run-loop-now",children:es.isPending?"Queuing…":"Run cycle now"}),es.isSuccess&&jsxRuntimeExports.jsx("p",{className:"pt-1 font-mono text-xs text-muted-foreground","data-testid":"run-now-result",children:Object.entries(es.data).map(([$,ts])=>`${$}: ${String(ts).replace(/^regenerated: /,"")}`).join(" · ")}),es.isError&&jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-amber-400/90",children:"Could not queue the cycle."})]})}function StatusBanner({status:es}){const $=headlineState(headlineInputs(es));return jsxRuntimeExports.jsx("p",{className:cn$1("text-sm",$.tone==="critical"&&"text-red-400",$.tone==="action"&&"text-teal-400",$.tone==="warn"&&"text-amber-400/90",$.tone==="calm"&&"text-muted-foreground"),"data-testid":"loop-headline",children:$.text})}function LoopPage(){const{query:es,update:$}=useLoopQuery(),{data:ts,isLoading:is,isError:cs,isPlaceholderData:Qr}=useLoopSummary(es),[ja,Na]=reactExports.useState(null),[Aa,Oa]=reactExports.useState(void 0);return is?jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-48"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"})]}):cs||!ts?jsxRuntimeExports.jsx("div",{className:"p-6",children:jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsxs(CardContent,{className:"flex items-center gap-2 py-6 text-muted-foreground",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4"}),"Could not load loop status."]})})}):jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6","data-testid":"loop-page",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-semibold",children:"Loop"}),jsxRuntimeExports.jsx(RunNowButton,{})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pt-1",children:[jsxRuntimeExports.jsx(WorkerChip,{status:ts}),jsxRuntimeExports.jsx(StatusBanner,{status:ts})]})]}),jsxRuntimeExports.jsx(ReviewGateCallout,{gate:ts.reviewGate}),jsxRuntimeExports.jsx(LoopRangeControl,{hours:es.hours,onChange:$}),jsxRuntimeExports.jsxs("div",{className:cn$1("space-y-4 transition-opacity duration-200",Qr&&"opacity-50"),children:[jsxRuntimeExports.jsx(ReadyToApplyCallout,{changes:ts.changes}),jsxRuntimeExports.jsx(KpiStrip,{status:ts,insights:Aa==null?void 0:Aa.insights}),jsxRuntimeExports.jsxs(Card,{className:"gap-2",children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-0",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-base",children:["Proposed changes",ts.proposalTotal>ts.proposals.length&&jsxRuntimeExports.jsxs("span",{className:"pl-2 font-normal text-muted-foreground",children:["showing ",ts.proposals.length," of ",ts.proposalTotal]})]})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-4",children:ts.proposals.length>0?jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:ts.proposals.map(Ia=>{const La=ja===Ia.id;return jsxRuntimeExports.jsxs("div",{"data-testid":"proposal",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>Na(La?null:Ia.id),"aria-expanded":La,"aria-controls":`proposal-detail-${Ia.id}`,className:"flex min-h-11 w-full cursor-pointer items-start justify-between gap-3 rounded-sm px-1 py-2 text-left transition-colors duration-150 hover:bg-muted/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring","data-testid":`proposal-toggle-${Ia.id}`,children:[jsxRuntimeExports.jsxs("div",{className:"flex min-w-0 items-start gap-2",children:[La?jsxRuntimeExports.jsx(ChevronDown,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}):jsxRuntimeExports.jsx(ChevronRight,{className:"mt-0.5 h-4 w-4 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("p",{className:"truncate text-sm",title:Ia.targetName??"",children:[Ia.targetName?Ia.targetName.split("/").pop():"(target deleted)",Ia.targetName&&jsxRuntimeExports.jsx("span",{className:"pl-1.5 text-xs text-muted-foreground",children:Ia.targetName.split("/").slice(-3,-1).join("/")})]}),jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-muted-foreground",children:[Ia.decision," · ",Ia.effectClass," · via ",Ia.proposalSource," ·"," ",new Date(Ia.createdAt).toLocaleDateString()]})]})]}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("shrink-0",Ia.applied?"border-teal-400/40 text-teal-400":"border-muted-foreground/40 text-muted-foreground"),"data-testid":"proposal-applied",children:Ia.applied?"applied":"not applied"})]}),jsxRuntimeExports.jsx(PromotionDetailPanel,{promotionId:Ia.id,open:La})]},Ia.id)})}):jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No changes proposed yet."})})]}),jsxRuntimeExports.jsx(OperationalDetails,{summary:ts,query:es,onChange:$,onDiagnostics:Oa})]})]})}function ToggleSwitch({checked:es,label:$,onToggle:ts,disabled:is,danger:cs,testId:Qr,id:ja}){return jsxRuntimeExports.jsx("button",{type:"button",id:ja,role:"switch","aria-checked":es,"aria-label":$,disabled:is,onClick:ts,"data-testid":Qr,className:cn$1("relative flex h-11 w-11 shrink-0 items-center justify-center rounded-md",is?"cursor-not-allowed opacity-60":"cursor-pointer"),children:jsxRuntimeExports.jsx("span",{className:cn$1("relative block h-6 w-11 rounded-full border transition-colors",es?cs?"border-amber-400/60 bg-amber-400/30":"border-teal-400/60 bg-teal-400/30":"border-muted-foreground/40 bg-muted"),children:jsxRuntimeExports.jsx("span",{className:cn$1("absolute top-0.5 h-4 w-4 rounded-full transition-all",es?cn$1("left-6",cs?"bg-amber-400":"bg-teal-400"):"left-0.5 bg-muted-foreground")})})})}function useMeasurementSettings(){return useQuery({queryKey:["settings","measurement"],queryFn:()=>apiGet("/api/settings/measurement")})}function useHarborSettings(){return useQuery({queryKey:["settings","harbor"],queryFn:()=>apiGet("/api/settings/harbor")})}function useSetMeasurement(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPatch("/api/settings/measurement",$),onSuccess:()=>{es.invalidateQueries({queryKey:["settings"]})}})}function useSetHarbor(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPatch("/api/settings/harbor",{cadence:$}),onSuccess:()=>{es.invalidateQueries({queryKey:["settings","harbor"]})}})}function useAutoAcceptSettings(es){return useQuery({queryKey:["settings","auto-accept",null],queryFn:()=>apiGet("/api/settings/auto-accept")})}function useSetAutoAccept(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPatch("/api/settings/auto-accept",$),onSuccess:()=>{es.invalidateQueries({queryKey:["settings","auto-accept"]}),es.invalidateQueries({queryKey:["loop-status"]})}})}function useEvolutionTargets(){return useQuery({queryKey:["settings","evolution"],queryFn:()=>apiGet("/api/settings/evolution/targets")})}function useSetEvolution(){const es=useQueryClient();return useMutation({mutationFn:({evalTargetId:$,...ts})=>apiPatch(`/api/settings/evolution?evalTargetId=${encodeURIComponent($)}`,ts),onSuccess:()=>{es.invalidateQueries({queryKey:["settings","evolution"]}),es.invalidateQueries({queryKey:["loop-status"]})}})}function useEvolutionAccount(){return useQuery({queryKey:["settings","evolution-account"],queryFn:()=>apiGet("/api/settings/evolution-account")})}function useSetEvolutionAccount(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPatch("/api/settings/evolution-account",$),onSuccess:()=>{es.invalidateQueries({queryKey:["settings","evolution-account"]}),es.invalidateQueries({queryKey:["settings","evolution"]}),es.invalidateQueries({queryKey:["loop-status"]})}})}function Row({label:es,hint:$,htmlFor:ts,children:is}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-start gap-2","data-testid":"evolution-setting-row",children:[jsxRuntimeExports.jsxs("label",{htmlFor:ts,className:"min-w-0 cursor-pointer text-xs",children:[es,$&&jsxRuntimeExports.jsx("span",{className:"block text-[11px] text-muted-foreground",children:$})]}),is]})}function TargetRow({target:es,minPairs:$,maxPairs:ts,onPatch:is,pending:cs}){const{settings:Qr,name:ja}=es,Na=ja.split("/").pop()||ja,Aa=ja.slice(0,Math.max(0,ja.length-Na.length-1)),Oa=Ia=>`evolution-${Ia}-${es.evalTargetId}`;return jsxRuntimeExports.jsxs("div",{className:"space-y-3 rounded-md border border-border p-3","data-testid":"evolution-target",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("p",{className:"truncate font-mono text-sm",title:ja,children:Na}),Aa&&jsxRuntimeExports.jsx("p",{className:"truncate text-xs text-muted-foreground",title:ja,children:Aa}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-muted-foreground","data-testid":"evolution-summary",children:es.summary}),Qr.pausedBy==="account"&&jsxRuntimeExports.jsx("p",{className:"pt-1 text-[11px] text-amber-400/90",children:"Held by the account-wide pause above — the per-target switch cannot clear it."})]}),jsxRuntimeExports.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[jsxRuntimeExports.jsx(Row,{label:"Enrolled",hint:"measure this instruction",htmlFor:Oa("enabled"),children:jsxRuntimeExports.jsx(ToggleSwitch,{id:Oa("enabled"),checked:Qr.enabled,label:`Enrol ${Na} in evolution`,testId:"evolution-enabled",disabled:cs,onToggle:()=>is({enabled:!Qr.enabled})})}),jsxRuntimeExports.jsx(Row,{label:"May rewrite",hint:"act on a verdict, not just record it",htmlFor:Oa("apply"),children:jsxRuntimeExports.jsx(ToggleSwitch,{id:Oa("apply"),checked:Qr.apply,danger:!0,label:`Allow evolution to rewrite ${Na}`,testId:"evolution-apply",disabled:cs,onToggle:()=>is({apply:!Qr.apply})})}),jsxRuntimeExports.jsx(Row,{label:"Paused",hint:"stop spending, keep the opt-in",htmlFor:Oa("paused"),children:jsxRuntimeExports.jsx(ToggleSwitch,{id:Oa("paused"),checked:Qr.pausedBy==="target",label:`Pause evolution for ${Na}`,testId:"evolution-paused",disabled:cs||Qr.pausedBy==="account",onToggle:()=>is({paused:Qr.pausedBy!=="target"})})}),jsxRuntimeExports.jsx(Row,{label:"Skip auto-enrolment",hint:"never picked up by the rule",htmlFor:Oa("optout"),children:jsxRuntimeExports.jsx(ToggleSwitch,{id:Oa("optout"),checked:Qr.optOut,label:`Exclude ${Na} from automatic enrolment`,testId:"evolution-optout",disabled:cs,onToggle:()=>is({optOut:!Qr.optOut})})}),jsxRuntimeExports.jsx(Row,{label:"Pool across nights",hint:"one candidate, evidence accumulated",htmlFor:Oa("accumulate"),children:jsxRuntimeExports.jsx(ToggleSwitch,{id:Oa("accumulate"),checked:Qr.accumulate,label:`Accumulate evidence across nights for ${Na}`,testId:"evolution-accumulate",disabled:cs,onToggle:()=>is({accumulate:!Qr.accumulate})})})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-t border-border pt-3",children:[jsxRuntimeExports.jsx("label",{className:"text-xs",htmlFor:`pairs-${es.evalTargetId}`,children:"Evidence required"}),jsxRuntimeExports.jsx("input",{id:`pairs-${es.evalTargetId}`,type:"number",min:$,max:ts,defaultValue:Qr.pairs,disabled:cs,"data-testid":"evolution-pairs",onBlur:Ia=>{const La=Number(Ia.currentTarget.value);Number.isFinite(La)&&La!==Qr.pairs&&is({pairs:La})},className:"w-20 rounded border border-border bg-transparent px-2 py-1 text-xs"}),jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["paired tasks before it may act (",$,"–",ts,"). Higher is stricter: more evidence and a tighter interval, at a bigger nightly bill."]})]})]})}function EvolutionCard(){const{data:es,isLoading:$}=useEvolutionTargets(),{data:ts}=useEvolutionAccount(),is=useSetEvolution(),cs=useSetEvolutionAccount(),Qr=(ts==null?void 0:ts.paused)??(es==null?void 0:es.accountPaused)??!1;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"Instruction evolution"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-4",children:$||!es?jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-6 rounded-md border border-border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsx("p",{className:"text-sm",children:"Stop all instruction evolution"}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-muted-foreground",children:"Account-wide. No instruction is measured or rewritten while this is on, whatever its own switches say. Turning it off restores exactly what was set before."})]}),jsxRuntimeExports.jsx(ToggleSwitch,{checked:Qr,danger:!0,label:"Pause instruction evolution for the whole account",testId:"evolution-account-pause",disabled:cs.isPending,onToggle:()=>cs.mutate({paused:!Qr})})]}),jsxRuntimeExports.jsx("p",{className:"text-sm","data-testid":"evolution-writable",children:Qr?jsxRuntimeExports.jsx("span",{className:"font-medium text-amber-400",children:"Evolution is paused for this account."}):es.writable===0?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:"No instruction may be rewritten automatically. The loop can still measure and record decisions."}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("span",{className:"font-medium text-amber-400",children:[es.writable," instruction",es.writable===1?"":"s"]})," ","may be rewritten by the nightly loop without asking."]})}),es.targets.length===0?jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["None of your ",es.totalInstructionTargets," instructions are enrolled. Evolution measures a proposed edit against the current version and only acts on a controlled verdict."]}):jsxRuntimeExports.jsx("div",{className:"space-y-3",children:es.targets.map(ja=>jsxRuntimeExports.jsx(TargetRow,{target:ja,minPairs:es.limits.minPairs,maxPairs:es.limits.maxPairs,pending:is.isPending,onPatch:Na=>is.mutate({evalTargetId:ja.evalTargetId,...Na})},ja.evalTargetId))}),es.unconfigured>0&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:[es.unconfigured," other instruction",es.unconfigured===1?" is":"s are"," not configured for evolution and are left alone."]}),(is.isError||cs.isError)&&jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-2 text-xs text-amber-400/90",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3"}),"Could not save that. Try again."]})]})})]})}const selectClass="h-10 w-full rounded-md border border-input bg-background px-3 text-sm focus-visible:outline focus-visible:outline-2";function MeasurementForm({preference:es,onSave:$,pending:ts}){const is=reactExports.useId(),[cs,Qr]=reactExports.useState(es.engine??"legacy"),[ja,Na]=reactExports.useState(es.model??""),Aa=MeasurementPreferenceSchema.safeParse({engine:cs==="legacy"?null:cs,model:ja.trim()||null}),Oa=cs!==(es.engine??"legacy")||ja.trim()!==(es.model??"");return jsxRuntimeExports.jsxs("form",{className:"space-y-3",onSubmit:Ia=>{Ia.preventDefault(),Aa.success&&$(Aa.data)},children:[jsxRuntimeExports.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{htmlFor:`${is}-engine`,className:"text-sm",children:"Measurement engine"}),jsxRuntimeExports.jsxs("select",{id:`${is}-engine`,className:selectClass,value:cs,disabled:ts,onChange:Ia=>{Qr(Ia.target.value),Na("")},children:[jsxRuntimeExports.jsx("option",{value:"legacy",children:"Unset (existing worker defaults)"}),jsxRuntimeExports.jsx("option",{value:"claude",children:"Claude"}),jsxRuntimeExports.jsx("option",{value:"codex",children:"Codex"}),jsxRuntimeExports.jsx("option",{value:"pi",children:"Pi"})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{htmlFor:`${is}-model`,className:"text-sm",children:"Model pin"}),jsxRuntimeExports.jsx(Input,{id:`${is}-model`,value:ja,disabled:cs==="legacy"||ts,onChange:Ia=>Na(Ia.target.value),"aria-describedby":`${is}-help`,placeholder:cs==="codex"?"Your supported Codex model":"Optional for Claude"})]})]}),jsxRuntimeExports.jsx("p",{id:`${is}-help`,className:"text-xs text-muted-foreground",children:cs==="pi"?"Pi requires a provider/model pin, for example openai-codex/gpt-5.4-mini. Uses your installed Pi and its account. Harbor is not supported with Pi.":cs==="codex"?"Codex requires a model pin supported by your installed CLI and account.":"Unset preserves existing behavior. Claude without a pin uses its eval default and Haiku for Harbor."}),cs==="codex"&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Codex reports tokens, not measured dollars. Harbor reward tasks run as calibration; the dollar-cost-only locality task is unsupported."}),jsxRuntimeExports.jsx("p",{className:"max-w-prose text-xs text-muted-foreground",children:"Saving affects future opted-in jobs only, not queued or running work. It does not enable a schedule or grant permission to rewrite files."}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:!Aa.success||!Oa||ts,children:ts?"Saving…":"Save measurement engine"})]})}function HarborControls({data:es,pending:$,onSave:ts}){const is=reactExports.useId(),[cs,Qr]=reactExports.useState(es.cadence);return jsxRuntimeExports.jsxs("form",{className:"space-y-3 border-t pt-4",onSubmit:ja=>{ja.preventDefault(),ts(cs)},children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{htmlFor:is,className:"text-sm",children:"Harbor schedule"}),jsxRuntimeExports.jsx("select",{id:is,className:selectClass,value:cs,disabled:$,onChange:ja=>Qr(ja.target.value),children:es.options.map(ja=>jsxRuntimeExports.jsx("option",{value:ja.cadence,children:ja.label},ja.cadence))})]}),jsxRuntimeExports.jsx("p",{className:"text-sm",children:es.summary}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:es.readiness.reported?es.readiness.ready?"A worker reports the required Harbor dependencies.":`Worker not ready: ${es.readiness.missing.join(", ")}.`:"No recent worker readiness report. Start or upgrade your local worker."}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Background runs need your local worker awake. Harbor also needs Docker running; this does not provide cloud execution."}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:$||cs===es.cadence||cs!=="off"&&!es.readiness.ready,children:$?"Saving…":"Save Harbor schedule"}),es.sweeps.length>0&&jsxRuntimeExports.jsx("ul",{className:"space-y-2 text-xs",children:es.sweeps.map(ja=>jsxRuntimeExports.jsxs("li",{className:"break-words",children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:ja.task}),": ",ja.last?`${ja.last.decision??ja.last.status} — ${ja.last.reason??"No result yet"}`:"Not run yet"]},ja.task))})]})}function MeasurementCard(){var Qr,ja;const es=useMeasurementSettings(),$=useHarborSettings(),ts=useSetMeasurement(),is=useSetHarbor(),cs=es.error??$.error??ts.error??is.error;return jsxRuntimeExports.jsxs(Card,{"data-testid":"measurement-card",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"Measurement and background runs"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[cs&&jsxRuntimeExports.jsx("p",{role:"alert",className:"break-words text-sm text-destructive",children:cs.message}),es.data?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(MeasurementForm,{preference:es.data.preference,onSave:Na=>ts.mutate(Na),pending:ts.isPending},JSON.stringify(es.data.preference)),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:(Qr=es.data.workers)!=null&&Qr.length?es.data.workers.map(Na=>`${Na.engines.join(", ")||"No engines reported"}; protocol ${Na.protocol??"unknown"}; seen ${Na.lastSeen}`).join(". "):"No recent measurement worker report."}),(es.data.graderBlockers??[]).map(Na=>jsxRuntimeExports.jsxs("p",{className:"break-words text-xs text-amber-500",children:[Na.name,": configured grader unavailable (",Na.engine,", ",Na.model,"). Install that engine on the selected worker, or deliberately reconfigure and recalibrate this target."]},Na.targetId))]}):!cs&&jsxRuntimeExports.jsx("p",{role:"status",children:"Loading measurement settings…"}),$.data&&jsxRuntimeExports.jsx(HarborControls,{data:$.data,pending:is.isPending,onSave:Na=>is.mutate(Na)},`${$.data.cadence}:${JSON.stringify((ja=es.data)==null?void 0:ja.preference)}`)]})]})}function SettingsPage(){const{data:es,isLoading:$}=useAutoAcceptSettings(),ts=useSetAutoAccept();return jsxRuntimeExports.jsxs("div",{className:"space-y-6 p-6","data-testid":"settings-page",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-semibold",children:"Settings"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"What RuleMetric is allowed to do on its own."})]}),jsxRuntimeExports.jsx(MeasurementCard,{}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base",children:"Automatic adoption"})}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-4",children:$||!es?jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-6",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("p",{className:"text-sm",children:["Let the nightly loop add high-confidence suggestions to your"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:"CLAUDE.md"})," without asking."]}),jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-muted-foreground",children:"On by default. Every rule it adds is a tagged block you can remove with one command, and it never removes or edits anything you wrote."})]}),jsxRuntimeExports.jsx(ToggleSwitch,{checked:es.effective,label:"Automatic adoption",disabled:ts.isPending,onToggle:()=>ts.mutate({enabled:!es.effective}),testId:"auto-accept-toggle"})]}),jsxRuntimeExports.jsxs("p",{className:"text-sm","data-testid":"auto-accept-state",children:["Currently"," ",jsxRuntimeExports.jsx("span",{className:es.effective?"font-medium text-teal-400":"font-medium",children:es.effective?"ON":"OFF"}),es.source==="project"&&" for this project"]}),jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border p-3",children:[jsxRuntimeExports.jsx("p",{className:"pb-2 text-xs uppercase tracking-wide text-muted-foreground",children:"What it may do"}),jsxRuntimeExports.jsxs("ul",{className:"space-y-1 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("li",{children:["• Only ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:es.limits.kind})," proposals — removals and trims always wait for you"]}),jsxRuntimeExports.jsxs("li",{children:["• Only above score ",es.limits.minScore,", which is already injected into every session"]}),jsxRuntimeExports.jsx("li",{children:"• Never text containing unfilled placeholders"}),jsxRuntimeExports.jsxs("li",{children:["• At most ",es.limits.maxPerRun," per night and ",es.limits.maxPerWindow," per"," ",es.limits.windowDays," days, per project"]})]})]}),ts.isError&&jsxRuntimeExports.jsxs("p",{className:"flex items-center gap-2 text-xs text-amber-400/90",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-3 w-3"}),"Could not save that. Try again."]}),jsxRuntimeExports.jsxs("div",{className:"border-t border-border pt-3 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx("p",{children:"Also available from the CLI:"}),jsxRuntimeExports.jsxs("pre",{className:"overflow-x-auto pt-1 font-mono",children:["rulemetric suggestions auto --off",`
|
|
146
146
|
`,"rulemetric suggestions auto --off --project <project-id>",`
|