@rulemetric/local 0.9.0 → 0.10.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.
@@ -141,7 +141,7 @@ 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),Kr=es.currentStepId,Qr=CORE_ORDER.slice(1).find(Fa=>es.steps[Fa].state!=="detected")??Kr,ja=ts&&Kr==="install"?Qr:Kr;reactExports.useEffect(()=>{Kr!=="install"&&ts&&is(!1)},[Kr,ts]);const Ca=reactExports.useRef(ja),[Aa,Oa]=reactExports.useState(null);reactExports.useEffect(()=>{const Fa=Ca.current;if(Ca.current=ja,Fa==null||Fa===ja)return;const Ka=es.steps[Fa];if(Ka.state!=="detected")return;Oa({label:Ka.label});const Ha=setTimeout(()=>Oa(null),800);return()=>clearTimeout(Ha)},[ja,es.steps]);function Ia(){$.invalidateQueries({queryKey:["worker-status"]}),$.invalidateQueries({queryKey:["sessions"]}),$.invalidateQueries({queryKey:["terminal-targets"]})}if(es.coreComplete||ja==null)return null;const Da=es.steps[ja],Ba=CORE_ORDER.indexOf(ja)+1,Ma=Da.state==="attention",qa=Da.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 Ka=es.steps[Fa],Ha=Ka.state==="detected",Qa=Fa===ja;return jsxRuntimeExports.jsx("span",{className:cn$1("h-2 w-2 rounded-full transition-colors",Ha?"bg-teal-500":Qa?"bg-primary ring-2 ring-primary/30":"bg-muted"),"aria-label":`${Ka.label}: ${Ka.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:Da.label})]}),stateBadge(Da.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:[Da.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:Da.command})]}),jsxRuntimeExports.jsx("pre",{className:"overflow-auto rounded-md border border-border bg-[#0B1120] p-3 text-xs font-mono whitespace-pre-wrap",children:Da.command})]}),Da.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 ",Da.waitingFor,"…"]}),Da.hint&&jsxRuntimeExports.jsx("p",{className:"text-xs leading-relaxed text-muted-foreground/80",children:Da.hint}),Ma&&!Da.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=5e3;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})}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,Ka,Ha,Qa,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,Kr=((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||Kr!=null||Qr!=null,Ca=(Ka=$.data)==null?void 0:Ka.estimated_cost_usd,Aa=((Ha=$.data)==null?void 0:Ha.total_input_tokens)??0,Oa=((Qa=$.data)==null?void 0:Qa.total_output_tokens)??0,Ia=(Va=$.data)==null?void 0:Va.estimated_cost_by_model,Da=typeof Ca=="number"&&Ca>0||Aa>0||Oa>0;if(!ja&&!Da)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(([,Ya],[,Ja])=>Ja.cost_usd-Ya.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==null?void 0:is.used_percentage)??null}),jsxRuntimeExports.jsx(LimitChip,{label:"7d",obs:(Kr==null?void 0:Kr.used_percentage)??null}),jsxRuntimeExports.jsx(LimitChip,{label:"7d Opus",obs:(Qr==null?void 0:Qr.used_percentage)??null})]})]}),Da&&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(Ca??0)]})]}),Ba.length>0&&jsxRuntimeExports.jsx("div",{className:"space-y-1",children:Ba.slice(0,3).map(([Ya,Ja])=>{const el=Ca&&Ca>0?Math.round(Ja.cost_usd/Ca*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:Ya}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 font-mono",children:[jsxRuntimeExports.jsx("span",{children:formatUsd$1(Ja.cost_usd)}),jsxRuntimeExports.jsxs("span",{className:"w-8 text-right text-muted-foreground",children:[el,"%"]})]})]},Ya)})})]})]})}function LimitChip({label:es,obs:$}){return $==null?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($),"%"]})]})}function PlanDetection({caps:es}){var Oa,Ia;const $=useQueryClient(),[ts,is]=reactExports.useState(!1),[Kr,Qr]=reactExports.useState(null),ja=useMutation({mutationFn:Da=>apiPatch("/api/profile",{claudeCodePlan:Da}),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 Ca=((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(Ca)})]}),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(Da=>{const Ba=Kr===Da.code||!Aa&&Da.code===Ca,Ma=ja.isPending&&ja.variables===Da.code;return jsxRuntimeExports.jsxs(Button,{role:"radio","aria-checked":Ba,variant:Ba?"default":"outline",size:"sm",disabled:Ma,onClick:()=>{Qr(Da.code),ja.mutate(Da.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"}),Da.label]},Da.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,Kr=es.steps.target,Qr=is.state==="detected"&&Kr.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:Kr})]}),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(),Kr=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(Kr.state),jsxRuntimeExports.jsx("span",{className:"text-sm font-medium truncate",children:Kr.label})]}),Kr.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:Kr.state==="loading"?"Checking…":`Waiting for ${Kr.waitingFor}`})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:Kr.hint}),Kr.state!=="detected"&&Kr.command&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Recommended:"," ",jsxRuntimeExports.jsx("span",{className:"font-mono text-foreground",children:Kr.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:Kr}=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:()=>Kr("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(){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 flex-1 flex-col overflow-hidden",children:[jsxRuntimeExports.jsx(Header,{}),jsxRuntimeExports.jsx(AlertBanner,{}),jsxRuntimeExports.jsx(WorkerHealthBanner,{}),jsxRuntimeExports.jsx(CliUpdateBanner,{}),jsxRuntimeExports.jsx("main",{className:"flex-1 overflow-y-auto p-4 md:p-6",children:jsxRuntimeExports.jsx(Outlet,{})})]}),jsxRuntimeExports.jsx(SetupWalkthroughModal,{})]})})}const formats=[{name:"CLAUDE.md",tier:"full"},{name:"AGENTS.md",tier:"full"},{name:".cursor/rules",tier:"full"},{name:"copilot-instructions.md",tier:"full"},{name:".windsurfrules",tier:"partial"},{name:".clinerules",tier:"partial"},{name:".roo/rules",tier:"partial"},{name:"CONVENTIONS.md (Aider)",tier:"partial"},{name:"GEMINI.md",tier:"partial"},{name:".continuerules",tier:"partial"},{name:".junie/guidelines.md",tier:"partial"},{name:".aiassistant/rules (JetBrains)",tier:"partial"},{name:"AGENTS.md (Codex)",tier:"partial"},{name:"SOUL.md",tier:"partial"},{name:".amazonq/rules",tier:"minimal"},{name:".goosehints",tier:"minimal"},{name:".kilocode/rules",tier:"minimal"},{name:".augment-guidelines",tier:"minimal"},{name:".tabnine/instructions.md",tier:"minimal"},{name:"AGENTS.md (OpenCode)",tier:"minimal"},{name:".warp/rules",tier:"minimal"},{name:".trae/rules",tier:"minimal"},{name:".vscode/copilot-instructions.md",tier:"minimal"},{name:".qodo/guidelines.md",tier:"minimal"},{name:".genkit",tier:"minimal"},{name:"AGENTS.md (Amp)",tier:"minimal"}],tierColors={full:"bg-primary/15 text-primary border-primary/30",partial:"bg-blue-500/15 text-blue-400 border-blue-500/30",minimal:"bg-muted text-muted-foreground border-border"},verdict={rule:"CLAUDE.md — RuleMetric's own repo (785-line version)",deltaLabel:"−23%",deltaCaption:"less likely to succeed",significance:"Significant · p < 0.001",ci:{lower:-31.7,upper:-13.9},n:{with:168,without:247},method:"observational · stratified",domain:{min:-40,max:10}};function VerdictCard(){const es=verdict.domain.max-verdict.domain.min,$=is=>`${(is-verdict.domain.min)/es*100}%`,ts=(verdict.ci.upper-verdict.ci.lower)/es*100;return jsxRuntimeExports.jsxs("div",{className:"bg-card border border-border rounded-lg overflow-hidden shadow-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between px-4 py-2.5 border-b border-border",children:[jsxRuntimeExports.jsx("span",{className:"text-xs font-mono text-muted-foreground uppercase tracking-wide",children:"Instruction impact"}),jsxRuntimeExports.jsx("span",{className:"inline-flex items-center rounded-full bg-primary/10 border border-primary/30 px-2 py-0.5 text-[10px] font-mono text-primary uppercase tracking-wide",children:"real verdict"})]}),jsxRuntimeExports.jsxs("div",{className:"p-5 space-y-5",children:[jsxRuntimeExports.jsx("div",{className:"font-mono text-sm text-foreground bg-[#0B1120] border border-border rounded px-3 py-2",children:verdict.rule}),jsxRuntimeExports.jsxs("div",{className:"flex items-end gap-3",children:[jsxRuntimeExports.jsx(TrendingDown,{className:"h-8 w-8 text-destructive mb-1"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"font-mono text-4xl font-bold text-destructive leading-none",children:verdict.deltaLabel}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground mt-1",children:verdict.deltaCaption})]})]}),jsxRuntimeExports.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full bg-primary/10 border border-primary/30 px-2.5 py-1 text-xs font-mono text-primary",children:[jsxRuntimeExports.jsx(BadgeCheck,{className:"h-3.5 w-3.5"}),verdict.significance]}),jsxRuntimeExports.jsxs("div",{className:"pt-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground mb-1.5",children:[jsxRuntimeExports.jsx("span",{children:"95% CI"}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-foreground",children:[verdict.ci.lower," to ",verdict.ci.upper," pp"]})]}),jsxRuntimeExports.jsxs("div",{className:"relative h-2 rounded-full bg-muted",children:[jsxRuntimeExports.jsx("div",{className:"absolute top-0 h-full rounded-full bg-destructive/60",style:{left:$(verdict.ci.lower),width:`${ts}%`}}),jsxRuntimeExports.jsx("div",{className:"absolute -top-0.5 h-3 w-px bg-muted-foreground/70",style:{left:$(0)}})]}),jsxRuntimeExports.jsxs("div",{className:"relative h-4 text-[10px] font-mono text-muted-foreground mt-1",children:[jsxRuntimeExports.jsxs("span",{className:"absolute left-0",children:[verdict.domain.min,"pp"]}),jsxRuntimeExports.jsx("span",{className:"absolute -translate-x-1/2",style:{left:$(0)},children:"0"}),jsxRuntimeExports.jsxs("span",{className:"absolute right-0",children:["+",verdict.domain.max,"pp"]})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1.5 text-sm border-t border-border pt-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"sessions"}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-foreground",children:[verdict.n.with," with · ",verdict.n.without," without"]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"method"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-foreground",children:verdict.method})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground border-t border-border pt-3",children:"Our own rules were measurably hurting us. We rewrote the file the same week — that's the loop working."})]})]})}const terminalLines=[{prompt:"$ rulemetric hooks install",delay:0},{output:"Installed hooks for Claude Code, Cursor, Copilot",delay:800},{output:"Session tracking active",delay:1400},{prompt:"$ rulemetric sessions list",delay:2400},{output:"24 sessions captured across Claude Code + Cursor",delay:3200},{output:"18 sessions linked to 6 instructions",delay:3800},{output:"Enriched with outcomes + friction analysis",delay:4400}];function AnimatedTerminal(){const[es,$]=reactExports.useState(0);return reactExports.useEffect(()=>{const ts=[],is=()=>{terminalLines.forEach((Kr,Qr)=>{ts.push(setTimeout(()=>$(Qr+1),Kr.delay))})};return is(),ts.push(setTimeout(()=>$(0),6e3)),ts.push(setTimeout(is,6500)),()=>ts.forEach(clearTimeout)},[]),jsxRuntimeExports.jsxs("div",{className:"bg-[#0B1120] border border-border rounded-lg overflow-hidden",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1.5 px-4 py-2.5 border-b border-border",children:[jsxRuntimeExports.jsx("div",{className:"h-2.5 w-2.5 rounded-full bg-destructive/60"}),jsxRuntimeExports.jsx("div",{className:"h-2.5 w-2.5 rounded-full bg-chart-3/60"}),jsxRuntimeExports.jsx("div",{className:"h-2.5 w-2.5 rounded-full bg-primary/60"}),jsxRuntimeExports.jsx("span",{className:"ml-2 text-xs text-muted-foreground font-mono",children:"terminal"})]}),jsxRuntimeExports.jsxs("div",{className:"p-4 font-mono text-sm space-y-1 min-h-[200px]",children:[terminalLines.slice(0,es).map((ts,is)=>"prompt"in ts?jsxRuntimeExports.jsx("div",{className:"text-primary",children:ts.prompt},is):jsxRuntimeExports.jsx("div",{className:"text-muted-foreground",children:ts.output},is)),es>0&&es<terminalLines.length&&jsxRuntimeExports.jsx("span",{className:"inline-block w-2 h-4 bg-primary animate-pulse"})]})]})}const loop=[{step:"01",icon:Activity,title:"Capture",description:"Automatic session tracking across Claude Code, Cursor, and Copilot. Lightweight hooks capture every session with zero config; an optional local proxy records the exact system prompt each model saw, plus live cost and rate-limit data."},{step:"02",icon:Link2,title:"Link",description:"Every session is matched back to the instructions that shaped it. The insights pipeline links context snapshots to your rules automatically — no manual tagging."},{step:"03",icon:ChartColumn,title:"Insight",description:"See which rules actually help. With-vs-without impact analysis produces a real significance verdict for each instruction, alongside outcome trends and friction patterns."},{step:"04",icon:Share2,title:"Share",description:"Publish the rules that win to your team catalog. Browse, fork, and share instructions across your org with scoped visibility."}],insightPoints=[{icon:Scale,title:"With vs. without",description:"Compare sessions that ran with a rule against those that didn't — the honest counterfactual, computed for you."},{icon:BadgeCheck,title:"Significance verdict",description:"Not a vanity number. Each instruction gets a statistical verdict so you know the effect is real, not noise."},{icon:ChartLine,title:"Outcomes & friction",description:"Track outcome trends and friction patterns over time, broken down by tool, project, and instruction."}],sharePoints=[{icon:Users,title:"Team catalog",description:"Browse and adopt the instructions your team already proved effective."},{icon:GitBranch,title:"Fork & remix",description:"Fork any rule set, adapt it to your project, and keep the version history."},{icon:Eye,title:"Scoped visibility",description:"Private, team, or org visibility with badges — share exactly as far as you mean to."}],roadmap=[{icon:GraduationCap,title:"Training",status:"Beta",dashed:!1,description:"Turn your proven rules into fine-tuning and prompt-training signal. In beta."},{icon:Shield,title:"Security scans",status:"Soon",dashed:!0,description:"Flag risky instructions and leaked secrets across your captured sessions. Coming soon."}],accessMethods=[{icon:Globe,title:"Web Dashboard",description:"Visual management with analytics, insights, and verdicts",code:"rulemetric.com"},{icon:Terminal,title:"CLI",description:"Full CRUD, convert, import, and session sync",code:"rulemetric sessions list"},{icon:Cpu,title:"MCP Server",description:"17 tools for AI assistants, auto-installs hooks",code:"claude mcp add rulemetric"},{icon:CodeXml,title:"REST API",description:"Programmatic access for CI/CD and automation",code:"GET /api/insights/compute"}],stats=[{value:"25+",label:"Output Formats"},{value:"3",label:"AI Tools Tracked"},{value:"17",label:"MCP Tools"},{value:"4",label:"Access Methods"}];function LandingPage(){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("div",{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 mt-2",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("section",{className:"py-24 px-4",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl grid lg:grid-cols-2 gap-12 items-center",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h1",{className:"text-4xl lg:text-5xl font-mono font-bold leading-tight mb-6",children:["Prove which AI rules"," ",jsxRuntimeExports.jsx("span",{className:"text-primary",children:"actually work."})]}),jsxRuntimeExports.jsx("p",{className:"text-lg text-muted-foreground mb-8 max-w-lg",children:"RuleMetric captures every coding session across Claude Code, Cursor, and Copilot, links each one back to the instructions that shaped it, and gives you a real significance verdict on which rules improve outcomes."}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-3",children:jsxRuntimeExports.jsx(Button,{size:"lg",className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/signup",children:["Get Started Free",jsxRuntimeExports.jsx(ArrowRight,{className:"ml-2 h-4 w-4"})]})})})]}),jsxRuntimeExports.jsx(VerdictCard,{})]})}),jsxRuntimeExports.jsx("section",{className:"py-20 px-4 bg-card",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl text-center",children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-mono font-bold mb-4",children:"You write rules. But do they help?"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-12 max-w-2xl mx-auto",children:"Teams maintain CLAUDE.md, .cursorrules, and copilot-instructions.md across every project but have no idea which rules improve AI output and which add noise. RuleMetric closes that gap."}),jsxRuntimeExports.jsxs("div",{className:"grid md:grid-cols-3 gap-6 max-w-3xl mx-auto text-left",children:[jsxRuntimeExports.jsxs("div",{className:"bg-background border border-border rounded-lg p-5",children:[jsxRuntimeExports.jsx("div",{className:"text-2xl font-mono font-bold text-destructive/80 mb-2",children:"25+"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:"instruction formats to keep in sync across tools"})]}),jsxRuntimeExports.jsxs("div",{className:"bg-background border border-border rounded-lg p-5",children:[jsxRuntimeExports.jsx("div",{className:"text-2xl font-mono font-bold text-chart-3/80 mb-2",children:"0%"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:"visibility into which rules actually improve sessions"})]}),jsxRuntimeExports.jsxs("div",{className:"bg-background border border-border rounded-lg p-5",children:[jsxRuntimeExports.jsx("div",{className:"text-2xl font-mono font-bold text-blue-400/80 mb-2",children:"???"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:"hours lost to friction that better rules could prevent"})]})]})]})}),jsxRuntimeExports.jsx("section",{className:"py-20 px-4",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl",children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-mono font-bold text-center mb-4",children:"Capture → Link → Insight → Share"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-center mb-12 max-w-xl mx-auto",children:"The full feedback loop that connects the rules you write to the outcomes they actually produce."}),jsxRuntimeExports.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-4 gap-6",children:loop.map(es=>jsxRuntimeExports.jsxs("div",{className:"bg-card border border-border rounded-lg p-6 hover:border-primary/30 transition-colors duration-200",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-xs text-primary",children:es.step}),jsxRuntimeExports.jsx(es.icon,{className:"h-5 w-5 text-primary"})]}),jsxRuntimeExports.jsx("h3",{className:"font-mono text-lg font-semibold mb-2",children:es.title}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.description})]},es.step))})]})}),jsxRuntimeExports.jsx("section",{className:"py-20 px-4 bg-card",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl grid lg:grid-cols-2 gap-12 items-center",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-mono font-bold mb-4",children:"How capture works"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-6 max-w-lg",children:"One command installs the hooks. From then on every session flows in automatically — captured, linked to the instructions that shaped it, and enriched with outcomes and friction. No manual logging, no changes to how you work."}),jsxRuntimeExports.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsxs("li",{className:"flex items-start gap-2",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),"Hooks capture Claude Code, Cursor, and Copilot with zero config"]}),jsxRuntimeExports.jsxs("li",{className:"flex items-start gap-2",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),"An optional local proxy records the exact rendered system prompt"]}),jsxRuntimeExports.jsxs("li",{className:"flex items-start gap-2",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),"Outcomes, friction, tool usage, and token cost logged for you"]})]})]}),jsxRuntimeExports.jsx(AnimatedTerminal,{})]})}),jsxRuntimeExports.jsx("section",{className:"py-20 px-4",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl",children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-mono font-bold text-center mb-4",children:"The insight nobody else gives you"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-center mb-12 max-w-xl mx-auto",children:"Most tools tell you what your AI did. RuleMetric tells you whether your rules made it better — with a verdict you can trust."}),jsxRuntimeExports.jsx("div",{className:"grid md:grid-cols-3 gap-6",children:insightPoints.map(es=>jsxRuntimeExports.jsxs("div",{className:"bg-card border border-border rounded-lg p-6 hover:border-primary/30 transition-colors duration-200",children:[jsxRuntimeExports.jsx(es.icon,{className:"h-5 w-5 text-primary mb-3"}),jsxRuntimeExports.jsx("h3",{className:"font-mono text-base font-semibold mb-2",children:es.title}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.description})]},es.title))})]})}),jsxRuntimeExports.jsx("section",{className:"py-20 px-4 bg-card",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl",children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-mono font-bold text-center mb-4",children:"Share what works"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-center mb-12 max-w-xl mx-auto",children:"Once a rule is proven, roll it out. The catalog turns one person's win into the whole team's default."}),jsxRuntimeExports.jsx("div",{className:"grid md:grid-cols-3 gap-6",children:sharePoints.map(es=>jsxRuntimeExports.jsxs("div",{className:"bg-background border border-border rounded-lg p-6 hover:border-primary/30 transition-colors duration-200",children:[jsxRuntimeExports.jsx(es.icon,{className:"h-5 w-5 text-primary mb-3"}),jsxRuntimeExports.jsx("h3",{className:"font-mono text-base font-semibold mb-2",children:es.title}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.description})]},es.title))})]})}),jsxRuntimeExports.jsx("section",{className:"py-20 px-4",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl",children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-mono font-bold text-center mb-4",children:"Every format. Every tool."}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-center mb-8 max-w-xl mx-auto",children:"Write your rules once and convert to 25+ formats — full-fidelity, partial, and minimal converters, with reverse parsing to import what you already have."}),jsxRuntimeExports.jsxs("div",{className:"grid gap-6 md:grid-cols-3",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h3",{className:"font-mono text-sm font-semibold text-primary mb-3 flex items-center gap-2",children:[jsxRuntimeExports.jsx(Shield,{className:"h-4 w-4"})," Full Fidelity"]}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1.5",children:formats.filter(es=>es.tier==="full").map(es=>jsxRuntimeExports.jsx("span",{className:`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-mono ${tierColors.full}`,children:es.name},es.name))})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h3",{className:"font-mono text-sm font-semibold text-blue-400 mb-3 flex items-center gap-2",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-4 w-4"})," Partial"]}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1.5",children:formats.filter(es=>es.tier==="partial").map(es=>jsxRuntimeExports.jsx("span",{className:`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-mono ${tierColors.partial}`,children:es.name},es.name))})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("h3",{className:"font-mono text-sm font-semibold text-muted-foreground mb-3 flex items-center gap-2",children:[jsxRuntimeExports.jsx(Zap,{className:"h-4 w-4"})," Minimal"]}),jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1.5",children:formats.filter(es=>es.tier==="minimal").map(es=>jsxRuntimeExports.jsx("span",{className:`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-mono ${tierColors.minimal}`,children:es.name},es.name))})]})]})]})}),jsxRuntimeExports.jsx("section",{className:"py-20 px-4 bg-card",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl",children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-mono font-bold text-center mb-4",children:"Access from anywhere"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-center mb-12 max-w-xl mx-auto",children:"Web dashboard, CLI, MCP server, or REST API. Use whichever fits your workflow."}),jsxRuntimeExports.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-4 gap-4",children:accessMethods.map(es=>jsxRuntimeExports.jsxs("div",{className:"bg-background border border-border rounded-lg p-5 hover:border-primary/30 transition-colors duration-200",children:[jsxRuntimeExports.jsx(es.icon,{className:"h-5 w-5 text-primary mb-3"}),jsxRuntimeExports.jsx("h3",{className:"font-mono text-sm font-semibold mb-1",children:es.title}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:es.description}),jsxRuntimeExports.jsx("code",{className:"block bg-[#0B1120] border border-border rounded px-2.5 py-1.5 font-mono text-xs text-muted-foreground truncate",children:es.code})]},es.title))})]})}),jsxRuntimeExports.jsx("section",{className:"py-20 px-4",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl",children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-mono font-bold text-center mb-4",children:"On the roadmap"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-center mb-12 max-w-xl mx-auto",children:"What we're building next on top of the capture-and-verdict loop."}),jsxRuntimeExports.jsx("div",{className:"grid md:grid-cols-2 gap-6 max-w-3xl mx-auto",children:roadmap.map(es=>jsxRuntimeExports.jsxs("div",{className:`bg-card rounded-lg p-6 ${es.dashed?"border border-dashed border-border":"border border-border"}`,children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between mb-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(es.icon,{className:"h-5 w-5 text-primary"}),jsxRuntimeExports.jsx("h3",{className:"font-mono text-base font-semibold",children:es.title})]}),jsxRuntimeExports.jsx("span",{className:`inline-flex items-center rounded-full px-2.5 py-0.5 text-[10px] font-mono uppercase tracking-wide ${es.dashed?"border border-dashed border-border text-muted-foreground":"bg-primary/15 text-primary border border-primary/30"}`,children:es.status})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.description})]},es.title))})]})}),jsxRuntimeExports.jsx("section",{className:"py-16 px-4",children:jsxRuntimeExports.jsx("div",{className:"mx-auto max-w-4xl grid grid-cols-2 md:grid-cols-4 gap-8",children:stats.map(es=>jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("div",{className:"font-mono text-4xl font-bold text-primary mb-1",children:es.value}),jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:es.label})]},es.label))})}),jsxRuntimeExports.jsx("section",{className:"py-24 px-4 bg-card",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-2xl text-center",children:[jsxRuntimeExports.jsx("h2",{className:"text-3xl font-mono font-bold mb-4",children:"Your instructions should be measurable."}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground mb-8",children:"Capture every session, link it to your rules, and prove which ones actually work. Free to start."}),jsxRuntimeExports.jsx(Button,{size:"lg",className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/signup",children:["Get Started Free",jsxRuntimeExports.jsx(ArrowRight,{className:"ml-2 h-4 w-4"})]})})]})}),jsxRuntimeExports.jsx("footer",{className:"border-t border-border py-8 px-4",children:jsxRuntimeExports.jsxs("div",{className:"mx-auto max-w-6xl flex items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:"h-1.5 w-1.5 rounded-full bg-primary"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:"RuleMetric"})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Capture, link, and prove your AI coding instructions."})]})})]})}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 Kr=new AbortController;return fetchEnabledSocialAuthProviders(Kr.signal).then($).finally(()=>{Kr.signal.aborted||is(!1)}),()=>Kr.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(),[Kr,Qr]=reactExports.useState(null),[ja,Ca]=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){Ca(null),Qr(Oa);try{await $(Oa,es)}catch(Ia){Ca(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:Kr!==null,onClick:()=>void Aa(Oa),"aria-label":`Continue with ${Ia}`,children:[Oa==="github"?jsxRuntimeExports.jsx(Github,{className:"h-4 w-4"}):jsxRuntimeExports.jsx(GoogleIcon,{}),Kr===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,Kr]=reactExports.useState(""),[Qr,ja]=reactExports.useState(""),[Ca,Aa]=reactExports.useState(""),[Oa,Ia]=reactExports.useState(!1);async function Da(qa){qa.preventDefault(),Aa(""),Ia(!0);try{await es(is,Qr);const Fa=safeNext(ts.get("next"));if(Fa){$(Fa,{replace:!0});return}const Ka=await getPostAuthRedirect();$(Ka)}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:Da,children:[jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[Ca&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:Ca}),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=>Kr(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")),Kr=is?`/login?next=${encodeURIComponent(is)}`:"/login",[Qr,ja]=reactExports.useState(""),[Ca,Aa]=reactExports.useState(""),[Oa,Ia]=reactExports.useState(""),[Da,Ba]=reactExports.useState(""),[Ma,qa]=reactExports.useState(!1),[Fa,Ka]=reactExports.useState(!1),[Ha,Qa]=reactExports.useState(!1);async function Va(Ya){if(Ya.preventDefault(),Ba(""),qa(!1),Ca!==Oa){Ba("Passwords do not match");return}if(Ca.length<6){Ba("Password must be at least 6 characters");return}Qa(!0);try{const{needsConfirmation:Ja,alreadyRegistered:el}=await es(Qr,Ca,is??void 0);if(el){qa(!0);return}if(Ja){Ka(!0);return}if(is){$(is,{replace:!0});return}const tl=await getPostAuthRedirect();$(tl,{replace:!0})}catch(Ja){Ba(Ja instanceof Error?Ja.message:"Signup failed")}finally{Qa(!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:Kr,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:[Da&&jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:Da}),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:Kr,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:Ya=>ja(Ya.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:Ca,onChange:Ya=>Aa(Ya.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:Ya=>Ia(Ya.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:Ha,children:Ha?"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:Kr,className:"text-primary underline",children:"Sign in"})]})]})]})]})})}function ConfirmPage(){const es=useNavigate(),[$]=useSearchParams(),{session:ts,loading:is}=useAuth(),[Kr,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 Ca=window.location.hash;(!Ca||!Ca.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"})]}),Kr?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Confirmation failed"}),jsxRuntimeExports.jsx(CardDescription,{children:Kr})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Confirming..."}),jsxRuntimeExports.jsx(CardDescription,{children:"Verifying your email address"})]})]}),Kr&&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")??"",Kr=ts.get("extension_id")??"",Qr=ts.get("nonce")??"",[ja,Ca]=reactExports.useState(null),[Aa,Oa]=reactExports.useState(!1),[Ia,Da]=reactExports.useState(null),Ba=ALLOWED_EDITOR_SCHEMES.has(is)&&ALLOWED_EXTENSION_IDS.has(Kr)&&/^[A-Za-z0-9_-]{8,128}$/.test(Qr);if(reactExports.useEffect(()=>{var Ma;if(!$&&es){if(!Ba){Ca("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}://${Kr}/auth?nonce=${encodeURIComponent(Qr)}&code=${encodeURIComponent(qa)}`;Da(Fa),window.location.href=Fa,Oa(!0)}).catch(qa=>{mintedNonces.delete(Qr),Ca(qa instanceof Error?qa.message:"Failed to mint auth code")}))}},[$,es,is,Kr,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,Kr]=reactExports.useState(""),[Qr,ja]=reactExports.useState(!1),[Ca,Aa]=reactExports.useState(!1);async function Oa(Ia){Ia.preventDefault(),Kr(""),Aa(!0);try{await es($),ja(!0)}catch(Da){Kr(Da instanceof Error?Da.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:Ca,children:Ca?"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(),[Kr,Qr]=reactExports.useState(""),[ja,Ca]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(""),[Ia,Da]=reactExports.useState(!1),[Ba,Ma]=reactExports.useState(()=>{const Ha=new URLSearchParams(window.location.search);return!!(Ha.get("token_hash")&&Ha.get("type"))}),[qa,Fa]=reactExports.useState(null);if(reactExports.useEffect(()=>{const Ha=new URLSearchParams(window.location.search),Qa=Ha.get("token_hash"),Va=Ha.get("type");if(!Qa||!Va)return;let Ya=!1,Ja=verifyPromises.get(Qa);return Ja||(Ja=supabase.auth.verifyOtp({token_hash:Qa,type:Va}),verifyPromises.set(Qa,Ja)),Ja.then(({error:el})=>{Ya||(el&&Fa(el.message||"This reset link is invalid or has expired."),window.history.replaceState({},"","/reset-password"),Ma(!1))}),()=>{Ya=!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 Ka(Ha){if(Ha.preventDefault(),Oa(""),Kr!==ja){Oa("Passwords do not match");return}if(Kr.length<6){Oa("Password must be at least 6 characters");return}Da(!0);try{await es(Kr),is("/sessions",{replace:!0})}catch(Qa){Oa(Qa instanceof Error?Qa.message:"Failed to update password")}finally{Da(!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:Ka,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:Kr,onChange:Ha=>Qr(Ha.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:Ha=>Ca(Ha.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 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"};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:Kr=0,cacheWriteTokens:Qr=0,byModel:ja,byTool:Ca}){const Aa=$??{inputUsd:0,outputUsd:0,cacheReadUsd:0,cacheWriteUsd:0},Oa=ja?Object.entries(ja).sort(([,Da],[,Ba])=>Ba.cost_usd-Da.cost_usd):[],Ia=Ca?Object.entries(Ca).sort(([,Da],[,Ba])=>Ba.cost_usd-Da.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:Kr>0?`${formatTokens$1(Kr)} 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(([Da,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(Da)}),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,"%"]})]})]},Da)})]})]}),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(([Da,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:Da}),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,"%"]})]})]},Da)})]})]}),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."})})]})})]})]})}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}){return jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardContent,{className:"pt-6",children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("div",{className:"rounded-lg bg-primary/10 p-2",children:jsxRuntimeExports.jsx(es,{className:"h-4 w-4 text-primary"})}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-2xl font-bold font-mono",children:ts}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:$}),is&&jsxRuntimeExports.jsx("p",{className:"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 Kr=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/Kr*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,Kr)=>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:`${Kr}:00 — ${is} messages`},Kr))})}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,Kr])=>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:`${Kr/ts*100}%`}})}),jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground w-8 text-right",children:Kr})]},is))})}function OverviewTab({data:es}){const $=es.estimated_cost_usd??0,ts=es.truncated??!1,is=es.response_time,Kr=es.parallel_sessions,Qr=es.tools_used,ja=es.tool_error_categories??{},Ca=es.total_interruptions??0,Aa=es.sessions_using_task_agent??0,Oa=es.sessions_using_mcp??0;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",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 Hours",value:Math.round(es.total_duration_hours),sub:Ca>0?`${Ca} interruptions`:void 0}),Aa>0&&jsxRuntimeExports.jsx(StatCard$2,{icon:Zap,label:"Task Agents",value:Aa,sub:"sessions"}),Oa>0&&jsxRuntimeExports.jsx(StatCard$2,{icon:Zap,label:"MCP Sessions",value:Oa,sub:"sessions"})]})]}),Kr&&Kr.events>0&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Parallel Sessions"})}),jsxRuntimeExports.jsxs(CardContent,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-8",children:[jsxRuntimeExports.jsxs("div",{className:"text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-2xl font-bold font-mono",children:Kr.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:Kr.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(Kr.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,{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,{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,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:"Messages by Time of Day"})}),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,{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:Kr=>ts(`/sessions?outcome=${Kr}`)},{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:Kr=>ts(`/sessions?friction=${Kr}`)}].filter(Kr=>Object.keys(Kr.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(Kr=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-mono",children:Kr.title})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(HorizontalBar,{items:Kr.items,onItemClick:Kr.onClick})})]},Kr.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"}),Kr=URL.createObjectURL(is),Qr=document.createElement("a");Qr.href=Kr,Qr.download=`${es}.md`,Qr.click(),URL.revokeObjectURL(Kr)},children:[jsxRuntimeExports.jsx(Download,{className:"h-3 w-3"}),"Download"]})}function SuggestionsTab({rec:es,isAuto:$}){var Aa,Oa,Ia;const{data:ts}=useSkillsRegistry(),Kr=es.recommended_skills??[],Qr=((Aa=es.suggestions)==null?void 0:Aa.features_to_try)??[],ja=((Oa=es.suggestions)==null?void 0:Oa.usage_patterns)??[],Ca=((Ia=es.on_the_horizon)==null?void 0:Ia.opportunities)??[];return Qr.length===0&&ja.length===0&&Ca.length===0&&Kr.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((Da,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:Da.feature}),Da.example_code&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Da.example_code,label:"Run"}),jsxRuntimeExports.jsx(CopyButton$2,{text:Da.example_code})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Da.why_for_you}),Da.example_code&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto text-muted-foreground",children:Da.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((Da,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:Da.title}),Da.copyable_prompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Da.copyable_prompt,label:"Run"}),jsxRuntimeExports.jsx(CopyButton$2,{text:Da.copyable_prompt})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Da.suggestion}),Da.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto text-muted-foreground",children:Da.copyable_prompt})]},Ba))})]}),Ca.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:Ca.map((Da,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:Da.title}),Da.copyable_prompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(RunCommandButton,{prompt:Da.copyable_prompt,label:"Run"}),jsxRuntimeExports.jsx(CopyButton$2,{text:Da.copyable_prompt})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Da.whats_possible}),Da.copyable_prompt&&jsxRuntimeExports.jsx("pre",{className:"mt-2 rounded bg-[#0B1120] p-2 text-xs font-mono overflow-x-auto text-muted-foreground",children:Da.copyable_prompt})]},Ba))})]}),Kr.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:[Kr.map(Da=>{var qa;const Ba=(qa=ts==null?void 0:ts.skills)==null?void 0:qa.find(Fa=>Fa.id===Da.skillId),Ma=`rulemetric skills install ${Da.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)??Da.skillId}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[(Ba==null?void 0:Ba.content)&&jsxRuntimeExports.jsx(SkillDownloadButton,{skillId:Da.skillId,content:Ba.content}),jsxRuntimeExports.jsx(RunCommandButton,{prompt:Ma,label:"Install"})]})]}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Da.reason}),(Ba==null?void 0:Ba.description)&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:Ba.description})]},Da.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:Kr}=useComputedInsights();return is?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[...Array(4)].map((ja,Ca)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},Ca))}):Kr||!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();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",children:jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",className:"cursor-pointer",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/import",children:[jsxRuntimeExports.jsx(Upload,{className:"mr-1.5 h-3.5 w-3.5"}),"Import"]})})})]}),jsxRuntimeExports.jsx(PendingSuggestionsCallout,{}),jsxRuntimeExports.jsxs("div",{className:"grid gap-4 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:jsxRuntimeExports.jsx("div",{className:"text-sm text-muted-foreground",children:"View all"})})]})})]}),jsxRuntimeExports.jsx(InsightsSection,{})]})}function useImportInstruction(){const es=useQueryClient();return useMutation({mutationFn:$=>apiPost("/api/instructions/import",$),onSuccess:()=>{es.invalidateQueries({queryKey:["instructions"]})}})}const IMPORTABLE_FORMATS=["agents-md","claude-md","cursorrules","copilot","windsurf"],FILENAME_MAP={"agents.md":"agents-md","claude.md":"claude-md","CLAUDE.md":"claude-md",".cursorrules":"cursorrules","copilot-instructions.md":"copilot",".windsurfrules":"windsurf"};function detectFormat(es){const{content:$,filename:ts}=es;if(ts){const is=ts.split("/").pop()??ts,Kr=FILENAME_MAP[is];if(Kr)return{format:Kr,confidence:.95};const Qr=is.toLowerCase();if(Qr.includes("claude"))return{format:"claude-md",confidence:.85};if(Qr.includes("cursor"))return{format:"cursorrules",confidence:.85};if(Qr.includes("copilot"))return{format:"copilot",confidence:.85};if(Qr.includes("windsurf"))return{format:"windsurf",confidence:.85};if(Qr.includes("agent"))return{format:"agents-md",confidence:.8}}if($){if($.includes("alwaysApply:")&&$.includes("---"))return{format:"cursorrules",confidence:.7};if($.includes("## File Access")||$.includes("## Code Rules"))return{format:"claude-md",confidence:.7};if($.includes("## Identity")||$.includes("## File Handling"))return{format:"agents-md",confidence:.65}}return null}const steps=["Input","Detect","Save"];function StepIndicator({currentStep:es}){return jsxRuntimeExports.jsx("div",{className:"flex items-center gap-2",children:steps.map(($,ts)=>{const is=ts+1,Kr=is<es,Qr=is===es;return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[ts>0&&jsxRuntimeExports.jsx("div",{className:`h-px w-8 ${Kr?"bg-primary":"bg-border"}`}),jsxRuntimeExports.jsxs(Badge,{variant:Qr?"default":Kr?"secondary":"outline",className:`gap-1 ${Qr?"bg-primary text-primary-foreground":Kr?"text-primary":""}`,children:[Kr?jsxRuntimeExports.jsx(Check,{className:"h-3 w-3 text-primary"}):jsxRuntimeExports.jsxs("span",{children:[is,"."]}),$]})]},$)})})}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 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",...Kr}){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,...Kr,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 ImportWizardPage(){const es=useNavigate(),$=useImportInstruction(),ts=reactExports.useRef(null),[is,Kr]=reactExports.useState(1),[Qr,ja]=reactExports.useState(""),[Ca,Aa]=reactExports.useState(""),[Oa,Ia]=reactExports.useState(null),[Da,Ba]=reactExports.useState(0),[Ma,qa]=reactExports.useState(""),[Fa,Ka]=reactExports.useState(""),[Ha,Qa]=reactExports.useState(""),[Va,Ya]=reactExports.useState("personal"),[Ja,el]=reactExports.useState("");reactExports.useEffect(()=>{if(is===2){const rl=detectFormat({content:Qr,filename:Ca});rl?(Ia(rl.format),Ba(rl.confidence),qa(rl.format)):(Ia(null),Ba(0),qa(""))}},[is,Qr,Ca]),reactExports.useEffect(()=>{if(is===3&&!Fa){const rl=Qr.match(/^#\s+(.+)$/m);rl&&Ka(rl[1].trim())}},[is,Qr,Fa]);function tl(rl){var nl;const dl=(nl=rl.target.files)==null?void 0:nl[0];if(!dl)return;Aa(dl.name);const xl=new FileReader;xl.onload=()=>{ja(xl.result)},xl.readAsText(dl)}function il(){$.mutate({content:Qr,sourceFormat:Ma,filename:Ca||void 0,name:Fa||void 0,scope:Va,tags:Ja.split(",").map(rl=>rl.trim()).filter(Boolean)},{onSuccess:()=>{ue$1.success("Instruction imported successfully"),es("/dashboard")},onError:rl=>ue$1.error(rl.message)})}return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",className:"cursor-pointer",asChild:!0,children:jsxRuntimeExports.jsxs(Link,{to:"/dashboard",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"}),"Back to Dashboard"]})}),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:"Import Instruction"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Import instructions from other AI tools"})]}),jsxRuntimeExports.jsx(StepIndicator,{currentStep:is}),is===1&&jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Paste or upload content"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"content",children:"Content"}),jsxRuntimeExports.jsx(Textarea,{id:"content",value:Qr,onChange:rl=>ja(rl.target.value),rows:16,className:"font-mono text-sm bg-background border-border",placeholder:"Paste your instruction content here..."})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("input",{ref:ts,type:"file",className:"hidden",accept:".md,.txt,.cursorrules,.windsurfrules",onChange:tl}),jsxRuntimeExports.jsxs(Button,{type:"button",variant:"outline",className:"cursor-pointer",onClick:()=>{var rl;return(rl=ts.current)==null?void 0:rl.click()},children:[jsxRuntimeExports.jsx(Upload,{className:"mr-2 h-4 w-4"}),"Upload File"]}),Ca&&jsxRuntimeExports.jsx("span",{className:"text-sm text-muted-foreground font-mono",children:Ca})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"filename",children:"Filename (optional)"}),jsxRuntimeExports.jsx(Input,{id:"filename",value:Ca,onChange:rl=>Aa(rl.target.value),placeholder:"e.g. CLAUDE.md, .cursorrules",className:"bg-background border-border"})]})]}),jsxRuntimeExports.jsx(CardFooter,{children:jsxRuntimeExports.jsx(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>Kr(2),disabled:!Qr.trim(),children:"Next"})})]}),is===2&&jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Format Detection"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[Oa?jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx("span",{className:"text-sm",children:"Detected:"}),jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"font-mono",children:Oa}),jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:Da>=.8?"bg-primary/15 text-primary border-primary/30":"bg-chart-3/15 text-chart-3 border-chart-3/30",children:[Math.round(Da*100),"% confidence"]})]}):jsxRuntimeExports.jsx("p",{className:"text-sm text-chart-3",children:"Could not auto-detect format. Please select one manually."}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{children:"Source Format"}),jsxRuntimeExports.jsxs(Select,{value:Ma,onValueChange:qa,children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"bg-background border-border",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"Select a format..."})}),jsxRuntimeExports.jsx(SelectContent,{children:IMPORTABLE_FORMATS.map(rl=>jsxRuntimeExports.jsx(SelectItem,{value:rl,children:rl},rl))})]})]})]}),jsxRuntimeExports.jsxs(CardFooter,{className:"gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",className:"cursor-pointer",onClick:()=>Kr(1),children:"Back"}),jsxRuntimeExports.jsx(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>Kr(3),disabled:!Ma,children:"Next"})]})]}),is===3&&jsxRuntimeExports.jsxs(Card,{className:"bg-card border-border",children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"font-mono",children:"Review & Save"})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"name",value:Fa,onChange:rl=>Ka(rl.target.value),placeholder:"Instruction name",className:"bg-background border-border"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"scope",children:"Scope"}),jsxRuntimeExports.jsxs(Select,{value:Va,onValueChange:Ya,children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"bg-background border-border",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"personal",children:"Personal"}),jsxRuntimeExports.jsx(SelectItem,{value:"team",children:"Team"}),jsxRuntimeExports.jsx(SelectItem,{value:"org",children:"Organization"}),jsxRuntimeExports.jsx(SelectItem,{value:"project",children:"Project"})]})]})]})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"description",children:"Description"}),jsxRuntimeExports.jsx(Input,{id:"description",value:Ha,onChange:rl=>Qa(rl.target.value),placeholder:"What does this instruction do?",className:"bg-background border-border"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"tags",children:"Tags (comma-separated)"}),jsxRuntimeExports.jsx(Input,{id:"tags",value:Ja,onChange:rl=>el(rl.target.value),placeholder:"security, review",className:"bg-background border-border"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{children:"Content Preview"}),jsxRuntimeExports.jsx("pre",{className:"max-h-64 overflow-auto whitespace-pre-wrap rounded-lg bg-[#0B1120] border border-border p-4 font-mono text-xs",children:Qr})]})]}),jsxRuntimeExports.jsxs(CardFooter,{className:"gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",className:"cursor-pointer",onClick:()=>Kr(2),children:"Back"}),jsxRuntimeExports.jsx(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:il,disabled:$.isPending,children:$.isPending?"Importing...":"Import"})]})]})]})]})}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,Kr=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",Kr,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:Kr,activeWorkers:Qr,isConnected:ja,isLoading:Ca}=useWorkerStatus("mcp"),Aa=useSetupProgress(),{openModal:Oa,progress:Ia}=useSetupWalkthrough(),{data:Da,isLoading:Ba}=useApiKeys(),Ma=useCreateApiKey(),qa=useRevokeApiKey(),[Fa,Ka]=reactExports.useState(""),[Ha,Qa]=reactExports.useState(null),[Va,Ya]=reactExports.useState(!0),[Ja,el]=reactExports.useState(null),{profile:tl}=useActiveOrg(),il=(tl==null?void 0:tl.liveSendSkipped)??!1,rl=(Da==null?void 0:Da.filter(pl=>!pl.revokedAt))??[];function dl(){const pl=Fa.trim()||"default";Ma.mutate({name:pl},{onSuccess:jl=>{Qa(jl.key),Ya(!0),Ka("")}})}function xl(pl){qa.mutate(pl,{onSuccess:()=>el(null)})}const nl="<your-api-key>",ll=`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`,fl=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),cl=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.":il?"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.":il?"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:Ca?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))})]}):Kr&&Kr.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(Kr[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."}),Ha&&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?Ha:"rm_"+"•".repeat(40)}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:()=>Ya(!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:Ha})]}),jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",onClick:()=>Qa(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=>Ka(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..."}):rl.length===0&&!Ha?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:rl.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)]}),Ja===pl.id?jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[jsxRuntimeExports.jsx(Button,{variant:"destructive",size:"sm",onClick:()=>xl(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:ll})]}),jsxRuntimeExports.jsx("pre",{className:"overflow-auto rounded-lg border border-border bg-[#0B1120] p-4 text-sm font-mono whitespace-pre-wrap",children:ll})]})]}),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:fl})]}),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:fl})]})]})]}),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:cl})]}),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:cl})]})]}),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:fl})]}),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:fl})]})]}),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
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 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 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 Kr;const is=(Kr=ts.state.data)==null?void 0:Kr.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 projectDisplayName(es){var Kr;if(es.projectName)return es.projectName;const $=lastTwoSegments(es.primaryCheckoutPath);if($)return $;const ts=nameFromRemote((Kr=es.metadata)==null?void 0:Kr.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 Kr=Math.floor(is/60);return Kr<24?`${Kr}h ${is%60}m`:`${Math.floor(Kr/24)}d ${Kr%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:Kr,className:Qr}){const ja=ts===$,Ca=ja?is==="asc"?ArrowUp:ArrowDown:ArrowUpDown;return jsxRuntimeExports.jsx(TableHead,{className:`cursor-pointer select-none hover:text-foreground transition-colors ${Qr??""}`,onClick:()=>Kr($),children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-1",children:[es,jsxRuntimeExports.jsx(Ca,{className:`h-3 w-3 ${ja?"text-primary":"text-muted-foreground/50"}`})]})})}function SessionsListPage(){const es=useNavigate(),[$,ts]=useSearchParams(),is=$.get("outcome")??void 0,Kr=$.get("friction")??void 0,Qr=$.get("instructionId")??void 0,ja=[is&&{key:"outcome",label:`outcome: ${is.replace(/_/g," ")}`},Kr&&{key:"friction",label:`friction: ${Kr.replace(/_/g," ")}`},Qr&&{key:"instructionId",label:"linked instruction"}].filter(Boolean),Ca=dl=>{const xl=new URLSearchParams($);xl.delete(dl),ts(xl,{replace:!0})},{data:Aa,isLoading:Oa}=useSessions({hideEmpty:!0,outcome:is,friction:Kr,instructionId:Qr}),[Ia,Da]=reactExports.useState("date"),[Ba,Ma]=reactExports.useState("desc"),[qa,Fa]=reactExports.useState(new Set),[Ka,Ha]=reactExports.useState(new Set),Qa=useDeleteSession(),Va=dl=>{Ha(xl=>{const nl=new Set(xl);return nl.has(dl)?nl.delete(dl):nl.add(dl),nl})},Ya=dl=>{Fa(xl=>{const nl=new Set(xl);return nl.has(dl)?nl.delete(dl):nl.add(dl),nl})},Ja=()=>{il&&(qa.size===il.length?Fa(new Set):Fa(new Set(il.map(dl=>dl.id))))},el=async()=>{const dl=[...qa];for(const xl of dl)await Qa.mutateAsync(xl);Fa(new Set)},tl=dl=>{dl===Ia?Ma(xl=>xl==="asc"?"desc":"asc"):(Da(dl),Ma("desc"))},il=Aa?[...Aa].sort((dl,xl)=>{const nl=Ba==="asc"?1:-1;switch(Ia){case"date":return nl*(new Date(dl.lastActivityAt??dl.startedAt).getTime()-new Date(xl.lastActivityAt??xl.startedAt).getTime());case"events":return nl*(dl.eventCount-xl.eventCount);case"project":return nl*projectDisplayName(dl).localeCompare(projectDisplayName(xl));default:return 0}}):void 0,rl=[];if(il){let dl=null;for(const xl of il){const nl=new Date(xl.startedAt).toISOString().slice(0,19),ll=`${xl.tool}|${xl.projectPath??"∅"}|${nl}`;dl&&dl.key===ll?dl.siblings.push(xl):(dl&&rl.push(dl),dl={key:ll,rep:xl,siblings:[]})}dl&&rl.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:()=>Ca(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:Qa.isPending,children:[jsxRuntimeExports.jsx(Trash2,{className:"h-3 w-3 mr-1"}),Qa.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,xl)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 w-full"},xl))}):il!=null&&il.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":!!il&&qa.size===il.length&&il.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:Ja,children:il&&qa.size===il.length&&il.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:rl.flatMap(dl=>{const xl=Ka.has(dl.key),nl=dl.siblings.length>0;return[{session:dl.rep,isSibling:!1},...xl?dl.siblings.map(fl=>({session:fl,isSibling:!0})):[]].map(({session:fl,isSibling:Tl})=>{var pl,jl;const cl=fl.analysis;return jsxRuntimeExports.jsxs(TableRow,{className:`cursor-pointer hover:bg-secondary/50 transition-colors ${qa.has(fl.id)?"bg-primary/5":""} ${Tl?"bg-muted/20":""}`,onClick:()=>es(`/sessions/${fl.id}`),children:[jsxRuntimeExports.jsx(TableCell,{onClick:Nl=>Nl.stopPropagation(),children:jsxRuntimeExports.jsx("button",{type:"button",role:"checkbox","aria-checked":qa.has(fl.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(),Ya(fl.id)},children:qa.has(fl.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:xl?"Collapse parallel sessions":"Expand parallel sessions",children:xl?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:fl.tool,className:"h-4 w-4 text-muted-foreground shrink-0"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm truncate",children:displayTool(fl.tool)})]}),(fl.dataTier||((pl=fl.metadata)==null?void 0:pl.headless)||nl&&!Tl)&&jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-1 mt-1 ml-6",children:[fl.dataTier&&jsxRuntimeExports.jsx(DataTierBadge,{tier:fl.dataTier}),((jl=fl.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(fl)}),fl.projectName&&(fl.primaryCheckoutPath||fl.projectPath)&&jsxRuntimeExports.jsx("div",{className:"truncate text-[10px] text-muted-foreground/70",children:fl.primaryCheckoutPath??fl.projectPath}),fl.linkedInstructions&&fl.linkedInstructions.length>0&&jsxRuntimeExports.jsxs("div",{className:"flex gap-1 mt-0.5 flex-wrap",children:[fl.linkedInstructions.slice(0,3).map((Nl,zl)=>{var ql;const Zl=((ql=Nl.contextIdentity)==null?void 0:ql.split("::").pop())??Nl.name,Pl=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:Pl.length>20?Pl.slice(0,20)+"...":Pl},zl)}),fl.linkedInstructions.length>3&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[9px] font-mono px-1 py-0",children:["+",fl.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:fl.lastMessagePreview??void 0,children:fl.lastMessagePreview??"—"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-sm text-muted-foreground w-24 max-w-24 truncate",title:fl.gitBranch??void 0,children:fl.gitBranch??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-right font-mono text-sm",children:fl.eventCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right text-sm text-muted-foreground",children:formatDuration(fl.startedAt,fl.lastActivityAt??fl.endedAt)}),jsxRuntimeExports.jsxs(TableCell,{className:"text-right text-sm text-muted-foreground whitespace-nowrap",children:[jsxRuntimeExports.jsx("div",{children:fl.lastActivityAt??fl.startedAt?new Date(fl.lastActivityAt??fl.startedAt).toLocaleString():"—"}),!!(cl!=null&&cl.outcome)&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[9px] mt-0.5",children:String(cl.outcome).replace(/_/g," ")})]})]},fl.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"})]})]})}const INJECTED_TYPES=new Set(["system_reminder","claude_md","memory","skill_catalog","git_context","hook_output","deferred_tools"]);function getContextItems(es){const ts=(es.metadata??{}).contextItems??[];let is=0;for(const Kr of ts)INJECTED_TYPES.has(Kr.type)&&(Kr.instruction_index==null&&(Kr.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),Kr=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)]})]}),Kr&&jsxRuntimeExports.jsx("span",{className:"text-muted-foreground font-mono truncate max-w-[40ch]",children:Kr}),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:Kr=>{Kr.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":$})]})}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.",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:Kr=13,plain:Qr=!1}){const ja=$??(es?GLOSSARY[es]:null);if(!ja)return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:ts});const Ca=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:Kr,height:Kr},"aria-hidden":!0})});return jsxRuntimeExports.jsx(TooltipProvider,{delayDuration:150,children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:Ca}),jsxRuntimeExports.jsx(TooltipContent,{className:"max-w-[19rem] whitespace-normal text-xs font-normal leading-relaxed",children:ja})]})})}function ProvenanceBadge({source:es,frontmatter:$,className:ts}){const is=es==="insights"||es==="evolution"?es:readStampedSource($),Kr=provenanceLabel(is);return!is||!Kr?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:Kr})}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),Kr=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,Kr&&"..."]})]}),$&&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 Ca of es){const Aa=extractCategory(Ca);ja[Aa]||(ja[Aa]=[]),ja[Aa].push(Ca)}return ja},[es]),Kr=reactExports.useMemo(()=>es.filter(ja=>isGenerated(classifyProvenance({source:ja.source},null))).length,[es]),Qr=reactExports.useMemo(()=>Object.keys(is).sort((Ca,Aa)=>{const Oa=CATEGORY_ORDER.indexOf(Ca),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}),Kr>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:Kr===1?"from insights":`${Kr} 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(Ca=>jsxRuntimeExports.jsx(ContextFileRow,{instruction:Ca},Ca.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(),Kr=Math.floor(is/6e4),Qr=$.toDateString()===ts.toDateString();return Kr<1?"just now":Kr<60?`${Kr}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 Kr=0,Qr;for(;(Qr=ts.exec($))!==null;)Qr.index>Kr&&is.push({type:"text",value:$.slice(Kr,Qr.index)}),is.push({type:"tool",value:Qr[1]}),Kr=Qr.index+Qr[0].length;return Kr<$.length&&is.push({type:"text",value:$.slice(Kr)}),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,Ca)=>ja.type==="tool"?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"mx-1 text-xs font-mono",children:ja.value},Ca):jsxRuntimeExports.jsx("span",{children:ja.value},Ca)):$})})]})}function ToolCallCard({event:es}){const[$,ts]=reactExports.useState(!1),is=es.metadata??{},Kr=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)}),Kr!=null&&jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:Kr<1e3?`${Kr}ms`:`${(Kr/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??"",Kr=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":`${Kr}${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??"",Kr=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:[Kr,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,Kr=es.cache_creation_input_tokens??0,Qr=$+ts+is+Kr;if(Qr===0)return null;const ja=[{value:is,color:"bg-teal-500",label:"cache read"},{value:Kr,color:"bg-amber-500",label:"cache write"},{value:$,color:"bg-blue-500",label:"input"},{value:ts,color:"bg-primary",label:"output"}].filter(Ca=>Ca.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(Ca=>jsxRuntimeExports.jsx("div",{className:`${Ca.color} h-full`,style:{width:`${Ca.value/Qr*100}%`},title:`${Ca.label}: ${formatTokenCount(Ca.value)}`},Ca.label))}),jsxRuntimeExports.jsx("div",{className:"flex gap-3 mt-1",children:ja.map(Ca=>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 ${Ca.color}`}),formatTokenCount(Ca.value)," ",Ca.label]},Ca.label))})]})}function AssistantResponseCard({event:es}){const $=es.metadata??{},ts=$.usage,is=$.stop_reason,Kr=$.content_block_types,Qr=$.model,ja=$.response_time_ms,Ca=$.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}),Ca&&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}),Kr&&Object.keys(Kr).length>0&&jsxRuntimeExports.jsx("div",{className:"flex gap-2 mt-2",children:Object.entries(Kr).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 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 isAgentResponseEvent(es){return es.eventType==="assistant_response"||es.eventType==="assistant_message"}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 InlineTurnSnapshot({snapshot:es}){var Aa;const[$,ts]=reactExports.useState(!1),{data:is}=useContextSnapshotDetail($?es.id:void 0),Kr=is??es,Qr=reactExports.useMemo(()=>$?getContextItems(Kr):[],[$,Kr]),ja=reactExports.useMemo(()=>{var Ia;return((es.metadata??{}).contextItems??[]).length||(((Ia=es.injectedInstructions)==null?void 0:Ia.length)??0)},[es]),Ca=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 ${Ca} 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 Da;return(Oa[Da=Ia.type]??(Oa[Da]=[])).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((Da,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:Da.name}),Da.estimated_tokens!=null&&jsxRuntimeExports.jsxs("span",{className:"text-[10px] shrink-0",children:["~",Da.estimated_tokens.toLocaleString()," tok"]})]},Ba))]},Oa))]}),Kr.systemPrompt&&jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:["System prompt: ",(Kr.systemPrompt.length??0).toLocaleString()," chars"]}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-[10px]",children:["hash: ",((Aa=Kr.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:[Kr.maxTokens!=null&&jsxRuntimeExports.jsxs("span",{children:["Max tokens: ",Kr.maxTokens.toLocaleString()]}),Kr.temperature!=null&&jsxRuntimeExports.jsxs("span",{children:["Temp: ",Kr.temperature]}),Array.isArray(Kr.tools)&&jsxRuntimeExports.jsxs("span",{children:[Kr.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:Kr}){var Oa,Ia,Da,Ba,Ma,qa,Fa,Ka;const Qr=es.events.filter(Ha=>Ha.eventType==="tool_call").length,ja=(Oa=es.assistantResponse)==null?void 0:Oa.tokenUsage,Ca=((Da=(Ia=es.assistantResponse)==null?void 0:Ia.metadata)==null?void 0:Da.usage)??(ja?{input_tokens:ja.input_tokens??ja.input,output_tokens:ja.output_tokens??ja.output,cache_read_input_tokens:ja.cache_read_input_tokens??ja.cacheRead,cache_creation_input_tokens:ja.cache_creation_input_tokens??ja.cacheWrite}:void 0)??((Ba=is==null?void 0:is.metadata)==null?void 0:Ba.usage),Aa=Ca==null?void 0:Ca.output_tokens;return((qa=(Ma=es.assistantResponse)==null?void 0:Ma.metadata)==null?void 0:qa.response_time_ms)??((Ka=(Fa=is==null?void 0:is.metadata)==null?void 0:Fa.responseHeaders)==null||Ka["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":""]}),Aa!=null&&Aa>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(Aa)," 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(Ha=>{if(Ha.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:Ha})]},Ha.id);const Qa=Ha.eventType==="tool_call"?"bg-amber-500":Ha.eventType==="thinking"?"bg-rose-500":Ha.eventType==="tool_result"?"bg-teal-500":Ha.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(Ha)]},Ha.id)}),is&&!Kr&&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,Lu;const{id:es}=useParams(),[$,ts]=useSearchParams(),{data:is,isLoading:Kr}=useSession(es),{data:Qr,isLoading:ja,hasNextPage:Ca,fetchNextPage:Aa,isFetchingNextPage:Oa}=useSessionEventsInfinite(es),Ia=useAnalyzeSession(),Da=useCreateLaunchJob(),Ba=(ic=Ia.data)==null?void 0:ic.jobId,{data:Ma}=useInsightsJob(Ba),[qa,Fa]=reactExports.useState(""),{data:Ka}=useContextSnapshots(es),Ha=$.get("filter"),[Qa,Va]=reactExports.useState(Ha??"turns"),Ya=$.get("layout"),[Ja,el]=reactExports.useState(Ya??"default"),tl=reactExports.useMemo(()=>(Qr==null?void 0:Qr.pages.flat())??[],[Qr]),il=reactExports.useMemo(()=>{switch(Qa){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,Qa]),rl=reactExports.useMemo(()=>groupEventsIntoTurns([...tl].sort((Bl,su)=>Bl.sequence-su.sequence)),[tl]),dl=reactExports.useMemo(()=>((is==null?void 0:is.linkedInstructions)??[]).filter(Bl=>Bl.linkMethod==="context_file"),[is==null?void 0:is.linkedInstructions]),xl=reactExports.useMemo(()=>((is==null?void 0:is.linkedInstructions)??[]).filter(Bl=>Bl.linkMethod!=="context_file"),[is==null?void 0:is.linkedInstructions]),nl=reactExports.useMemo(()=>{if(is!=null&&is.eventCounts){const Eu=is.eventCounts.byType??{};return{messages:is.eventCounts.messages,tools:is.eventCounts.toolCalls,assistantResponses:(Eu.assistant_response??0)+(Eu.assistant_message??0),total:is.eventCounts.total}}const Bl=tl.filter(Eu=>Eu.eventType==="user_message"||Eu.eventType==="assistant_message").length,su=tl.filter(Eu=>Eu.eventType==="tool_call").length;return{messages:Bl,tools:su,assistantResponses:0,total:tl.length}},[is==null?void 0:is.eventCounts,tl]);if(Kr)return jsxRuntimeExports.jsx(Skeleton,{className:"h-96 w-full"});if(!is)return jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Session not found"});const ll=is.analysis,fl=ll==null?void 0:ll.adherenceScore,Tl=ll==null?void 0:ll.summary,cl=ll==null?void 0:ll.suggestions,pl=ll==null?void 0:ll.brief_summary,jl=ll==null?void 0:ll.underlying_goal,Nl=ll==null?void 0:ll.outcome,zl=ll==null?void 0:ll.session_type,Zl=ll==null?void 0:ll.goal_categories,Pl=ll==null?void 0:ll.friction_counts,Il=ll==null?void 0:ll.friction_detail,ql=ll==null?void 0:ll.primary_success,Fl=ll==null?void 0:ll.tool,nu=is.analyzedAt??(ll==null?void 0:ll.analyzed_at),Gl=is.analyzedEventCount??(ll==null?void 0:ll.analyzed_event_count),cu=is.analyzedTurnCount??(ll==null?void 0:ll.analyzed_turn_count),Ol=!!pl||!!jl,Ml=Object.values(Pl??{}).reduce((Bl,su)=>Bl+su,0),Ql=is.endedAt?Math.max(0,Math.round((new Date(is.endedAt).getTime()-new Date(is.startedAt).getTime())/6e4)):null,eu=ll?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&&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,Iu=[{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.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:!ll&&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"]})]}),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:ll?`${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..."]}),!!((Lu=Ma.progress)!=null&&Lu.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))}`]})]})]})})})}),ll&&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",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," ")}),Fl&&jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:["via ",displayTool(Fl)]})]}),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})]}),ql&&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:ql})]}),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],[,su])=>su-Bl).map(([Bl,su])=>jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"text-xs font-mono",children:[Bl.replace(/_/g," ")," ",su>1?`(${su})`:""]},Bl))})]}),Pl&&Object.values(Pl).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(Pl).filter(([,Bl])=>Bl>0).sort(([,Bl],[,su])=>su-Bl).map(([Bl,su])=>jsxRuntimeExports.jsxs(Badge,{variant:"destructive",className:"text-xs font-mono",children:[Bl.replace(/_/g," ")," (",su,")"]},Bl))}),Il&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:Il})]})]})]})]}):ll&&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",fl!=null&&jsxRuntimeExports.jsxs(Badge,{variant:fl>=80?"default":fl>=50?"secondary":"destructive",className:"font-mono",children:[fl,"% adherence"]})]}),eu]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:Tl}),cl&&cl.length>0&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-2",children:"Suggestions"}),cl.map((Bl,su)=>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})]})]})]},su))]})]})]}),jsxRuntimeExports.jsxs(TooltipProvider,{children:[(dl.length>0||xl.length>0)&&jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[dl.length>0&&jsxRuntimeExports.jsx(ContextBlock,{instructions:dl}),xl.length>0&&xl.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:Iu.map(Bl=>jsxRuntimeExports.jsx(Badge,{asChild:!0,className:"py-1",variant:Qa===Bl.key?"default":"outline",children:jsxRuntimeExports.jsx("button",{type:"button",className:"cursor-pointer",onClick:()=>Va(Bl.key),children:Bl.label})},Bl.key))}),((Ka==null?void 0:Ka.length)??0)>0&&jsxRuntimeExports.jsxs(Badge,{variant:"secondary",className:"text-xs font-mono shrink-0",children:[Ka.length," snapshots"]})]}),Qa==="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:Ja===Bl.key?"default":"outline",children:jsxRuntimeExports.jsx("button",{type:"button",className:"cursor-pointer",onClick:()=>{el(Bl.key);const su=new URLSearchParams($);Bl.key==="default"?su.delete("layout"):su.set("layout",Bl.key),ts(su,{replace:!0})},children:Bl.label})},Bl.key))]}),ja?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:10}).map((Bl,su)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-16 w-full"},su))}):Qa==="turns"?jsxRuntimeExports.jsxs("div",{children:[rl.length===0&&((Ka==null?void 0:Ka.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"]})]}):rl.length===0?jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground py-8 text-center",children:["No conversation turns — ",(Ka==null?void 0:Ka.length)??0," proxy snapshots captured."]}):(()=>{var Eu,lc;const Bl=((lc=(Eu=is==null?void 0:is.eventCounts)==null?void 0:Eu.byType)==null?void 0:lc.user_message)??rl.length,su=[...rl].map((ku,bu)=>({turn:ku,chronoIdx:bu})).reverse();if(Ja==="split")return jsxRuntimeExports.jsx("div",{className:"space-y-2",children:su.map(({turn:ku,chronoIdx:bu},Ua)=>{var El;const ul=Ka==null?void 0:Ka[bu];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:ku,index:Ua,totalTurns:Bl,snapshot:ul,hideSnapshot:!0}),jsxRuntimeExports.jsx("div",{className:"hidden lg:block pt-6",children:ul?jsxRuntimeExports.jsx("div",{className:"sticky top-4",children:jsxRuntimeExports.jsx(InlineTurnSnapshot,{snapshot:ul})}):jsxRuntimeExports.jsx("div",{className:"sticky top-4 text-xs text-muted-foreground/60 font-mono pt-2",children:"No snapshot for this turn"})})]},((El=ku.userMessage)==null?void 0:El.id)??`turn-${bu}`)})});if(Ja==="capped"){const ku=(Ka??[]).reduce((Ua,ul)=>Ua+(ul.estimatedTokens??0),0),bu=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:su.map(({turn:Ua,chronoIdx:ul},El)=>{var $l;return jsxRuntimeExports.jsx(TurnContainer,{turn:Ua,index:El,totalTurns:Bl,snapshot:Ka==null?void 0:Ka[ul]},(($l=Ua.userMessage)==null?void 0:$l.id)??`turn-${ul}`)})}),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:bu})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Snapshots"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:(Ka==null?void 0:Ka.length)??0})]}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"~Total tokens"}),jsxRuntimeExports.jsx("p",{className:"font-mono",children:ku.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:su.map(({turn:Ua,chronoIdx:ul},El)=>{var Rl,_l,Al,yl;const $l=Ka==null?void 0:Ka[ul],kl=Bl-El,Ga=Ua.events.filter(Ul=>Ul.eventType==="tool_call").length,ol=((_l=(Rl=Ua.assistantResponse)==null?void 0:Rl.metadata)==null?void 0:_l.usage)??((Al=$l==null?void 0:$l.metadata)==null?void 0:Al.usage),bl=ol==null?void 0:ol.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]}),Ga>0&&jsxRuntimeExports.jsxs("span",{className:"text-amber-500",children:[Ga,"t"]}),bl!=null&&bl>0&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:[formatTokenCount(bl),"tk"]}),($l==null?void 0:$l.estimatedTokens)!=null&&jsxRuntimeExports.jsxs("span",{className:"text-cyan-500/80 ml-auto",children:[formatTokenCount($l.estimatedTokens)," ctx"]})]},((yl=Ua.userMessage)==null?void 0:yl.id)??`meta-${ul}`)})})]})]})})]})}return su.map(({turn:ku,chronoIdx:bu},Ua)=>{var ul;return jsxRuntimeExports.jsx(TurnContainer,{turn:ku,index:Ua,totalTurns:Bl,snapshot:Ka==null?void 0:Ka[bu]},((ul=ku.userMessage)==null?void 0:ul.id)??`turn-${bu}`)})})(),Ca&&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"})})]}):il.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:[il.map(Bl=>jsxRuntimeExports.jsx("div",{children:renderEvent(Bl)},Bl.id)),Ca&&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:Da})]})}function ResumeBar({sessionId:es,session:$,externalSessionId:ts,launchProjectPath:is,resumePrompt:Kr,setResumePrompt:Qr,resumeMutation:ja}){const{data:Ca}=useSessionTerminalTarget(es),Aa=useSendMessage$1(es),{data:Oa}=useLaunchJobs(),Ia=(Ca==null?void 0:Ca.target)??null,Da=(Ca==null?void 0:Ca.capabilities)??{liveSend:!1,fallbackResume:!0,tmuxAvailable:!1,workerOnline:!1},Ba=(()=>{const ll=!!(Ia&&Ia.status==="active");return!Da.workerOnline&&ll?"worker_offline":ll&&Da.liveSend?"live_ready":Ia&&Ia.status!=="active"?"target_missing":Da.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)",Ka=(()=>{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"}})(),Ha=Ma==="worker_offline"||Ma==="sending"||ja.isPending,Qa=Aa.data,Va=(Qa==null?void 0:Qa.delivery)==="live"?Qa.target.target:null,Ya=(Ia==null?void 0:Ia.attachCommand)??(Ia!=null&&Ia.target?`tmux attach -t ${Ia.target}`:null),Ja=(Oa??[]).find(ll=>{var fl;return((fl=ll.config)==null?void 0:fl.resumeSessionId)===ts}),el=Ja==null?void 0:Ja.status,tl=!!(Ja!=null&&Ja.completedAt)&&Date.now()-new Date(Ja.completedAt).getTime()<3e4,il=(()=>{var ll;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:(ll=Ja==null?void 0:Ja.result)!=null&&ll.pid?`Running (PID ${Ja.result.pid})`:"Running"}:el==="failed"?{dot:"bg-red-500",label:(Ja==null?void 0:Ja.error)??"Failed"}:el==="completed"&&tl?{dot:"bg-teal-500",label:"Resumed — Claude is now active"}:null})(),rl=Da.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."+rl;case"target_missing":return"The previous tmux session ended. Starting a new one will spawn a fresh terminal."+rl;case"launch_ready":return"Live send needs a tmux target. Fallback will spawn a new terminal."+rl;default:return null}})(),xl=ll=>{ts&&ja.mutate({tool:"claude_code",projectPath:is,mode:"interactive",resumeSessionId:ts,...ll?{prompt:ll}:{}},{onSuccess:()=>{ue$1(ll?"Resume request sent":"Resume request sent (no prompt)"),Qr("")},onError:fl=>ue$1.error(fl instanceof Error?fl.message:"Failed to resume")})},nl=()=>{if(Ha)return;const ll=Kr.trim();if(!ll){if(Ba==="live_ready"){ue$1.error("Type a message to send");return}if(!ts)return;xl("");return}if(Ba==="live_ready"){Aa.mutate({message:ll,delivery:"live",submit:!0},{onSuccess:()=>Qr("")});return}ts&&xl(ll)};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:[il&&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 ${il.dot}`}),jsxRuntimeExports.jsx("span",{className:"font-mono",children:il.label}),Ya&&Ma==="sent"&&qa&&jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/70 font-mono ml-2",children:["· ",Ya]})]})}),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:Da,session:$}),dl&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground font-mono",children:dl}),jsxRuntimeExports.jsxs("form",{onSubmit:ll=>{ll.preventDefault(),nl()},className:"flex items-end gap-2",children:[jsxRuntimeExports.jsx("textarea",{value:Kr,onChange:ll=>Qr(ll.target.value),onKeyDown:ll=>{var fl;ll.key==="Enter"&&!ll.shiftKey&&!ll.nativeEvent.isComposing&&(ll.preventDefault(),(fl=ll.currentTarget.form)==null||fl.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:Ha}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ha,className:"cursor-pointer self-end",children:Ka})]})]})]})}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 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:Kr}=useAvailableLaunchers(),Qr=useCreateLaunchJob(),[ja,Ca]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(ts??""),[Ia,Da]=reactExports.useState(""),[Ba,Ma]=reactExports.useState(""),[qa,Fa]=reactExports.useState("interactive");reactExports.useEffect(()=>{es&&Oa(Ya=>Ya||(ts??""))},[es,ts]);const Ka=()=>{Ca(""),Oa(ts??""),Da(""),Ma(""),Fa("interactive")},Ha=reactExports.useMemo(()=>previewTmuxTarget(),[]),Qa=Ya=>{Ya.preventDefault(),!(!ja||!Aa)&&Qr.mutate({tool:ja,projectPath:Aa,prompt:Ia||void 0,model:Ba||void 0,mode:qa},{onSuccess:Ja=>{var rl;const el=Ja.result,tl=(rl=el==null?void 0:el.terminalTarget)==null?void 0:rl.target,il=(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}`:il?"Starting Claude Code in Terminal fallback":`Starting Claude Code in tmux target ${Ha}`),Ja.noLiveWorker&&ue$1.error("No worker online — start `rulemetric evals agent` to process this launch"),Ja.sessionId?is(`/sessions/${Ja.sessionId}`):is("/sessions"),Ka(),$(!1)},onError:Ja=>{ue$1.error(Ja instanceof Error?Ja.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:Qa,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:Ca,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"tool",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"Select a tool"})}),jsxRuntimeExports.jsx(SelectContent,{children:Kr==null?void 0:Kr.map(Ya=>jsxRuntimeExports.jsx(SelectItem,{value:Ya.tool,children:Ya.tool.replace(/_/g," ")},Ya.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:Ya=>Oa(Ya.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:Ya=>Da(Ya.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:Ya=>Ma(Ya.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:Ya=>Fa(Ya),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:Ha,children:Ha})]}),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}),[Kr,Qr]=reactExports.useState("cards"),[ja,Ca]=reactExports.useState(!1),[Aa,Oa]=reactExports.useState(void 0),Ia=Ba=>{Oa(Ba),Ca(!0)};let Da;return ts?Da=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?Da=jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-destructive font-mono",children:"Failed to load projects."}):!$||$.projects.length===0?Da=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."})]}):Kr==="cards"?Da=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))}):Da=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:Kr==="cards"?"secondary":"ghost","aria-pressed":Kr==="cards",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>Qr("cards"),children:"Cards"}),jsxRuntimeExports.jsx(Button,{type:"button",size:"sm",variant:Kr==="list"?"secondary":"ghost","aria-pressed":Kr==="list",className:"h-7 px-3 text-xs cursor-pointer",onClick:()=>Qr("list"),children:"List"})]})]})]}),Da,jsxRuntimeExports.jsx(LaunchSessionDialog,{open:ja,onOpenChange:Ca,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}),Kr=useRunsEnabled();useRuns({projectId:""});const[Qr,ja]=reactExports.useState("cards"),[Ca,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??[],Da=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(Ka=>!isActive(Ka));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(Ka=>jsxRuntimeExports.jsx(SessionCard,{s:Ka,emphasized:!0,onOpen:()=>$(`/sessions/${Ka.id}`)},Ka.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(Ka=>jsxRuntimeExports.jsx(SessionCard,{s:Ka,onOpen:()=>$(`/sessions/${Ka.id}`)},Ka.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:[Kr,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)]})]})]})})}),Da,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,Kr]})}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:Kr,flag:Qr,note:ja})=>apiPut(`/api/eval-runs/${ts}/annotations/${is}`,{verdict:Kr,...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,Kr)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 w-full"},Kr))}):$!=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,Kr]=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},Ca=>{const Aa=Ca.new;$&&Aa.evalTargetId!==$||(Kr(Aa),ts.invalidateQueries({queryKey:["eval-jobs",Aa.evalTargetId]}))}).on("postgres_changes",{event:"UPDATE",schema:"public",table:"eval_jobs",filter:Qr},Ca=>{const Aa=Ca.new;$&&Aa.evalTargetId!==$||(Aa.status==="completed"||Aa.status==="failed"||Aa.status==="cancelled"?(Kr(null),ts.invalidateQueries({queryKey:["eval-runs",Aa.evalTargetId]}),ts.invalidateQueries({queryKey:["eval-jobs",Aa.evalTargetId]})):Kr(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(),Kr=useApplyProposal(),Qr=$==null?void 0:$.id,{data:ja}=useConversationMessages(Qr,2e3),[Ca,Aa]=reactExports.useState(""),[Oa,Ia]=reactExports.useState(!1),[Da,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 Ya=Qr;Ya||(Ya=(await ts.mutateAsync(es)).id);const Ja=await is.mutateAsync({conversationId:Ya,content:Va.trim()});Ba(Ja.noLiveWorker),Aa("")}finally{Ia(!1)}}},[Qr,ts,is,es,Oa]),Fa=async()=>{await qa(Ca)},Ka=Va=>{Va.key==="Enter"&&!Va.shiftKey&&(Va.preventDefault(),Fa())},Ha=Va=>{Qr&&Kr.mutate({conversationId:Qr,messageId:Va})},Qa=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:[Qa.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"]})]})]}),Qa.map((Va,Ya)=>Va.type==="status"&&Qa.slice(Ya+1).some(Ja=>Ja.type==="results"||Ja.type==="proposal"||Ja.type==="generated"||Ja.role==="user")?null:jsxRuntimeExports.jsx(MessageBubble,{message:Va,onApply:Ha,applyingProposal:Kr.isPending,isLastStatus:Va.type==="status"},Va.id)),jsxRuntimeExports.jsx("div",{ref:Ma})]}),Da&&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:Ca,onChange:Va=>Aa(Va.target.value),onKeyDown:Ka,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||!Ca.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:Kr,results:Qr}=$,ja=Kr.passRate>=.8?"text-teal-500":Kr.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:[Kr.passed,"/",Kr.total]}),jsxRuntimeExports.jsxs("span",{className:"text-sm text-muted-foreground",children:["evals passed (",Math.round(Kr.passRate*100),"%)"]})]}),jsxRuntimeExports.jsx("div",{className:"space-y-1",children:Qr.map((Ca,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"}),Ca.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:Ca.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:Ca.output})]}),Ca.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:Ca.evidence})]})]})]},Aa))})]})}function ProposalMessage({content:es,data:$,messageId:ts,onApply:is,applying:Kr}){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((Ca,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:Ca.section}),Ca.current&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-red-400 font-medium",children:"- "}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:Ca.current})]}),Ca.proposed&&jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("span",{className:"text-teal-400 font-medium",children:"+ "}),jsxRuntimeExports.jsx("span",{children:Ca.proposed})]}),jsxRuntimeExports.jsx("div",{className:"text-muted-foreground italic",children:Ca.reasoning})]},Aa))})]}),jsxRuntimeExports.jsx("div",{className:"flex gap-2",children:jsxRuntimeExports.jsxs(Button,{size:"sm",onClick:()=>is(ts),disabled:Kr,children:[Kr?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((Kr,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:Kr.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:Kr.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:Kr.expectations.map((ja,Ca)=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs font-normal",children:ja},Ca))})]})]})]},Qr))})]})}const MIN_QUOTE_LEN=12,MIN_CODE_LEN=4,SHORT_CANDIDATE_LEN=20;function extractEvidenceQuotes(es){const $=[],ts=is=>{const Kr=is==null?void 0:is.trim();Kr&&$.push(Kr)};for(const is of[/"([^"]+)"/g,/“([^”]+)”/g,/'([^']+)'/g,/‘([^’]+)’/g])for(const Kr of es.matchAll(is))Kr[1].length>=MIN_QUOTE_LEN&&ts(Kr[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 Kr of extractEvidenceQuotes($))for(const[Qr,ja]of[[es,Kr],[es.toLowerCase(),Kr.toLowerCase()]]){let Ca=0,Aa=!1;for(;;){const Oa=Qr.indexOf(ja,Ca);if(Oa===-1||(ts.push([Oa,Oa+ja.length]),Aa=!0,Kr.length<SHORT_CANDIDATE_LEN))break;Ca=Oa+ja.length}if(Aa)break}ts.sort((Kr,Qr)=>Kr[0]-Qr[0]||Kr[1]-Qr[1]);const is=[];for(const[Kr,Qr]of ts){const ja=is[is.length-1];ja&&Kr<=ja[1]?ja[1]=Math.max(ja[1],Qr):is.push([Kr,Qr])}return is}function segmentByRanges(es,$){if($.length===0)return[{text:es,highlighted:!1}];const ts=[];let is=0;for(const[Kr,Qr]of $)Kr>is&&ts.push({text:es.slice(is,Kr),highlighted:!1}),ts.push({text:es.slice(Kr,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 Ha=new Map;for(const Qa of es){const Va=`${Qa.evalRunId}:${Qa.expectationIndex}`;Ha.set(Va,[...Ha.get(Va)??[],Qa])}return[...Ha.entries()].map(([Qa,Va])=>({key:Qa,rows:Va,first:Va[0],humanVerdict:Va[0].humanPassed===Va[0].judgePassed?"approve":"reject",consensus:new Set(Va.map(Ya=>Ya.reviewerEngine)).size>1})).sort((Qa,Va)=>Number(Va.consensus)-Number(Qa.consensus))},[es]),[is,Kr]=reactExports.useState(new Set),[Qr,ja]=reactExports.useState(null),[Ca,Aa]=reactExports.useState(!1),Oa=ts.length>0&&ts.every(Ha=>is.has(Ha.key)),Ia=()=>Kr(Oa?new Set:new Set(ts.map(Ha=>Ha.key))),Da=Ha=>Kr(Qa=>{const Va=new Set(Qa);return Va.has(Ha)?Va.delete(Ha):Va.add(Ha),Va}),Ba=async(Ha,Qa,Va)=>{Aa(!0);let Ya=0,Ja=0;for(const el of Va)try{await Qa(el),Ya+=1}catch{Ja+=1}Aa(!1),Kr(new Set),Ja===0?ue$1.success(`${Ha} ${Ya} label${Ya===1?"":"s"}`):ue$1.error(`${Ha} ${Ya}, ${Ja} failed — the rest are still flagged`)},Ma=Ha=>$.resolve({id:Ha.first.id,resolution:"kept"}),qa=async Ha=>{await $.annotate({runId:Ha.first.evalRunId,expectationIndex:Ha.first.expectationIndex,verdict:Ha.humanVerdict==="approve"?"reject":"approve"}),await $.resolve({id:Ha.first.id,resolution:"relabeled"})},Fa=async Ha=>{await $.removeAnnotation({runId:Ha.first.evalRunId,expectationIndex:Ha.first.expectationIndex}),await $.resolve({id:Ha.first.id,resolution:"relabeled"})};if(ts.length===0)return null;const Ka=ts.filter(Ha=>is.has(Ha.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"]})]})]}),Ka.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:Ca,onClick:()=>Ba("Kept",Ma,Ka),children:["Keep ",Ka.length," label",Ka.length===1?"":"s"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"h-6 px-2 text-xs",disabled:Ca,onClick:()=>Ba("Flipped",qa,Ka),children:["Flip ",Ka.length]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-muted-foreground",disabled:Ca,onClick:()=>Ba("Removed",Fa,Ka),children:["Remove ",Ka.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(Ha=>{const Qa=Ha.first,Va=Qr===Ha.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(Ha.key)&&"bg-primary/[0.04]"),children:[jsxRuntimeExports.jsx("input",{type:"checkbox",checked:is.has(Ha.key),onChange:()=>Da(Ha.key),className:"h-3.5 w-3.5 shrink-0 accent-teal-500","aria-label":`Select ${Qa.expectationText}`}),jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>ja(Va?null:Ha.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:Qa.expectationText}),jsxRuntimeExports.jsxs("span",{className:"hidden shrink-0 font-mono text-[11px] text-muted-foreground sm:inline",children:[Qa.evalName??"case"," #",Qa.runNumber]}),Ha.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: ",Ha.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:[Ha.rows.length," reviewer",Ha.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:Ca,onClick:()=>Ba("Kept",Ma,[Ha]),children:"Keep"}),jsxRuntimeExports.jsx(Button,{size:"sm",variant:"ghost",className:"h-6 px-2 text-xs text-red-500 hover:text-red-400",disabled:Ca,onClick:()=>Ba("Flipped",qa,[Ha]),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: ",Qa.judgePassed?"PASS":"FAIL"]}),jsxRuntimeExports.jsxs("span",{className:"rounded bg-muted px-1.5 py-0.5",children:["You: judge was ",Ha.humanVerdict==="approve"?"right":"wrong"]}),Ha.rows.map(Ya=>jsxRuntimeExports.jsxs("span",{className:"rounded bg-red-500/10 px-1.5 py-0.5 text-red-500",children:[Ya.reviewerModel,": ",Ya.reviewerPassed?"PASS":"FAIL"]},Ya.id)),jsxRuntimeExports.jsx("span",{className:"font-mono text-muted-foreground",children:Qa.configuration})]}),Qa.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:Qa.outputExcerpt})]})]})]},Ha.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((Kr,Qr)=>jsxRuntimeExports.jsxs("li",{children:["— ",Kr]},Qr))})]})}function CaseDiscriminationCard({data:es}){const $=Kr=>`${(Kr*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(Kr=>jsxRuntimeExports.jsxs("li",{className:"flex items-baseline justify-between gap-3",children:[jsxRuntimeExports.jsx("span",{className:Kr.discriminating?"text-foreground":"text-muted-foreground line-through",children:Kr.name}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-muted-foreground whitespace-nowrap",children:[$(Kr.withPassRate)," vs ",$(Kr.withoutPassRate),Kr.discriminating?jsxRuntimeExports.jsxs("span",{className:"text-teal-500",children:[" · ",jsxRuntimeExports.jsxs(InfoTip,{term:"separation",children:["Δ",$(Kr.separation)]})]}):jsxRuntimeExports.jsxs("span",{className:"text-amber-500",children:[" · ",jsxRuntimeExports.jsx(InfoTip,{term:"flat",children:"flat"})]})]})]},Kr.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,Kr=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:Kr($.agreementRate)}),$.agreementCi&&jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs text-muted-foreground",children:[" ","[",Kr($.agreementCi.lower),"–",Kr($.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 ",Kr(ts.with.estimate)," · without"," ",Kr(ts.without.estimate)]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["(judge-only said ",Kr(ts.with.naive)," ·"," ",Kr(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?"+":"",Kr(ts.delta)]})," ",jsxRuntimeExports.jsxs("span",{className:"text-xs text-muted-foreground",children:["95% CI ",Kr(ts.ci.lower)," to ",Kr(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 Kr=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)}),Kr&&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:Kr,powerCheck:Qr,judge:ja,caseDiscrimination:Ca,pooling:Aa,reviewers:Oa,targetContent:Ia,targetType:Da}){var Gl,cu;const[Ba,Ma]=reactExports.useState(0),[qa,Fa]=reactExports.useState(!1),Ka=reactExports.useRef(!1);reactExports.useEffect(()=>{Aa!=null&&Aa.engaged&&!Ka.current&&(Ka.current=!0,Fa(!0))},[Aa==null?void 0:Aa.engaged]);const[Ha,Qa]=reactExports.useState(!1),[Va,Ya]=reactExports.useState({}),Ja=reactExports.useRef([]),el=useJudgeDisagreements(es),tl=useResolveJudgeReview(es),[il,rl]=reactExports.useState({}),dl=useAnnotateGrade(es),xl=useRemoveGradeAnnotation(es),nl=new Map(Kr.map(Ol=>[`${Ol.evalRunId}:${Ol.expectationIndex}`,Ol])),ll=(Ol,Ml)=>{var xu,fu;const Ql=`${Ol.id}:${Ml}`;if(Ql in il)return il[Ql];const eu=nl.get(Ql);return eu?eu.verdict:((fu=(xu=Ol.expectations[Ml])==null?void 0:xu.annotation)==null?void 0:fu.verdict)??null},fl=(Ol,Ml,Ql,eu)=>{const xu=`${Ol}:${Ml}`;eu===Ql?(rl(fu=>{const Iu={...fu};return delete Iu[xu],Iu}),xl.mutate({runId:Ol,expectationIndex:Ml},{onError:()=>ue$1.error("Couldn't remove the label — it may still be recorded. Retry in a moment.")})):(rl(fu=>({...fu,[xu]:Ql})),Ja.current.push({runId:Ol,expectationIndex:Ml}),dl.mutate({runId:Ol,expectationIndex:Ml,verdict:Ql},{onError:()=>{rl(fu=>{const Iu={...fu};return delete Iu[xu],Iu}),ue$1.error("Label didn't save — check your connection and mark it again.")}}))},Tl=$==null?void 0:$.runs[Ba],cl=(Tl==null?void 0:Tl.expectations.filter(Ol=>Ol.method==="llm"&&!Ol.errored))??[],pl=Tl?cl.filter(Ol=>ll(Tl,Ol.index)!=null).length:0,jl=Tl!=null&&cl.length>0&&pl===cl.length,Nl=Tl?((Gl=cl.find(Ol=>ll(Tl,Ol.index)==null))==null?void 0:Gl.index)??null:null,[zl,Zl]=reactExports.useState(null);reactExports.useEffect(()=>{Zl(null),Qa(!1)},[Tl==null?void 0:Tl.id]);const Pl=zl??Nl,Il=reactExports.useRef(null),ql=reactExports.useRef(null),Fl=reactExports.useMemo(()=>{const Ol=Tl==null?void 0:Tl.expectations.find(Ql=>Ql.method==="llm"&&Ql.index===Pl);if(!Ol||!(Tl!=null&&Tl.output))return{segments:null,count:0};const Ml=findEvidenceRanges(Tl.output,Ol.evidence);return Ml.length===0?{segments:null,count:0}:{segments:segmentByRanges(Tl.output,Ml),count:Ml.length}},[Tl,Pl]);reactExports.useEffect(()=>{const Ol=Il.current,Ml=ql.current;if(!Ol||!Ml)return;const Ql=Ml.getBoundingClientRect().top-Ol.getBoundingClientRect().top;Ol.scrollTo({top:Ol.scrollTop+Ql-48,behavior:"smooth"})},[Pl,Tl==null?void 0:Tl.id,Fl.count]),reactExports.useEffect(()=>{const Ol=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(),fl(Tl.id,Nl,"approve",null);else if((eu==="2"||eu==="d")&&Nl!=null)Ml.preventDefault(),fl(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=Ja.current.pop();if(xu){Ml.preventDefault();const fu=`${xu.runId}:${xu.expectationIndex}`;rl(Iu=>{const yu={...Iu};return delete yu[fu],yu}),xl.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",Ol),()=>window.removeEventListener("keydown",Ol)},[Tl,Nl,jl,Ba,$]);const nu=Ol=>{const Ml=Ol.expectations.filter(eu=>eu.method==="llm");if(Ml.length===0)return"done";const Ql=Ml.filter(eu=>ll(Ol,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"]})]}),Kr.length>=10&&Kr.every(Ol=>Ol.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 ",Kr.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:Ol=>dl.mutateAsync(Ol),removeAnnotation:Ol=>xl.mutateAsync(Ol),resolve:Ol=>tl.mutateAsync(Ol)}}),Oa&&Oa.some(Ol=>Ol.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(Ol=>!Ol),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`,Ca&&Ca.total>0&&` · ${Ca.discriminating}/${Ca.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}),Ca&&Ca.total>0&&jsxRuntimeExports.jsx(CaseDiscriminationCard,{data:Ca})]})]}):Ca&&Ca.total>0&&jsxRuntimeExports.jsx(CaseDiscriminationCard,{data:Ca}),$?$.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((Ol,Ml)=>{const Ql=nu(Ol);return jsxRuntimeExports.jsx("button",{onClick:()=>Ma(Ml),title:`${Ol.evalName} · ${Ol.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},Ol.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 ",Da," 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:()=>Qa(Ol=>!Ol),className:"rounded px-1.5 py-0.5 text-[11px] text-muted-foreground/70 transition-colors hover:text-foreground",children:Ha?"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",Ha?"max-h-none":"max-h-[26rem]"),children:Fl.segments?Fl.segments.map((Ol,Ml)=>{if(!Ol.highlighted)return jsxRuntimeExports.jsx("span",{children:Ol.text},Ml);const Ql=Fl.segments.findIndex(eu=>eu.highlighted)===Ml;return jsxRuntimeExports.jsx("mark",{ref:Ql?ql:void 0,className:"bg-teal-500/25 text-inherit rounded-sm",children:Ol.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(Ol=>{const Ml=Ol.method==="llm"&&!Ol.errored,Ql=Ml?ll(Tl,Ol.index):null,eu=Ml&&Ol.index===Nl,xu=Ml&&Ol.index===Pl;return jsxRuntimeExports.jsxs("div",{onMouseEnter:Ml?()=>Zl(Ol.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:[Ol.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",Ol.passed?"bg-teal-500/10 text-teal-500":"bg-red-500/10 text-red-500"),children:["Judge: ",Ol.passed?"PASS":"FAIL"]}):jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"mt-0.5 shrink-0 text-[10px]",children:["auto ",Ol.passed?"✓":"✗"]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx("p",{className:"font-mono text-sm",children:Ol.text}),Ol.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:"," "]}),Ol.evidence]}),xu&&(Fl.count>0?jsxRuntimeExports.jsxs("p",{className:"mt-1 text-[11px] text-teal-500",children:[Fl.count," cited span",Fl.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:()=>fl(Tl.id,Ol.index,"approve",Ql),disabled:dl.isPending||xl.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:()=>fl(Tl.id,Ol.index,"reject",Ql),disabled:dl.isPending||xl.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}:${Ol.index}`,Iu=((Bl=nl.get(fu))==null?void 0:Bl.note)??"",yu=Va[fu]??Iu,ic=yu!==Iu,Lu=()=>dl.mutate({runId:Tl.id,expectationIndex:Ol.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:su=>Ya(Eu=>({...Eu,[fu]:su.target.value})),onKeyDown:su=>{su.key==="Enter"&&ic&&(su.preventDefault(),Lu())},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:Lu,children:Iu&&!ic?"Saved":"Save note"})]})})()]},Ol.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,"/",cl.length," assertions reviewed",jl?jsxRuntimeExports.jsx("span",{className:"text-teal-500",children:" · this run now counts toward the pilot"}):cl.length>1?jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground/70",children:[" ","· label all ",cl.length," for this run to count toward the pilot"]}):null]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[!jl&&cl.length>1&&jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",disabled:dl.isPending,onClick:()=>{for(const Ol of cl)ll(Tl,Ol.index)==null&&fl(Tl.id,Ol.index,"approve",null)},children:["Mark all ",cl.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 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:Kr}=useEvalTarget(es),{data:Qr,isLoading:ja}=useEvals(es),{data:Ca,isLoading:Aa}=useEvalRuns(es),{data:Oa,isLoading:Ia}=useBenchmarks(es),{data:Da,isLoading:Ba}=useEvalComparisons(es),{data:Ma}=useGradeAnnotations(es),{data:qa}=useJudgeCalibration(es),{data:Fa,isFetching:Ka,refetch:Ha}=useAnnotationQueue(es),{data:Qa,isLoading:Va}=usePromotions(es),{data:Ya}=useJudgeDisagreements(es),{user:Ja}=useAuth(),{data:el}=useEvalJobs(es),tl=useCreateEvalJob(),il=useCancelEvalJob(),rl=useRealtimeEvalJobs(Ja==null?void 0:Ja.id,es),{isConnected:dl,workerCount:xl}=useWorkerStatus("cli-worker"),nl=rl??(el==null?void 0:el.find(pl=>["pending","claimed","running"].includes(pl.status)))??null,ll=!!nl&&["pending","claimed","running"].includes(nl.status),fl=(el==null?void 0:el[0])??null,Tl=!ll&&(fl==null?void 0:fl.status)==="failed"?fl:null;if(Kr)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 cl=[{key:"chat",label:"Chat"},{key:"evals",label:"Evals",count:Qr==null?void 0:Qr.length},{key:"runs",label:"Runs",count:Ca&&Ca.length>=RUNS_PAGE_LIMIT?`${RUNS_PAGE_LIMIT}+`:Ca==null?void 0:Ca.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:Da&&Da.length>=COMPARISONS_PAGE_LIMIT?`${COMPARISONS_PAGE_LIMIT}+`:Da==null?void 0:Da.length},{key:"promotions",label:"Promotions",count:Qa==null?void 0:Qa.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?`${xl} worker${xl>1?"s":""} online`:"No workers"]}),ll?jsxRuntimeExports.jsxs(Button,{variant:"destructive",size:"sm",onClick:()=>nl&&il.mutate(nl.id),disabled:il.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"]})]})]}),!ll&&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||((Ya==null?void 0:Ya.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&&((Ya==null?void 0:Ya.length)??0)>0&&" · ",((Ya==null?void 0:Ya.length)??0)>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Ya.length," label",Ya.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:cl.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:Ca??[],isLoading:Aa,annotations:Ma??[]}),$==="review"&&jsxRuntimeExports.jsx(ReviewTab,{targetId:es,queue:Fa,isFetching:Ka,refetchQueue:Ha,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:Da??[],isLoading:Ba}),$==="promotions"&&jsxRuntimeExports.jsx(PromotionsTab,{promotions:(Qa==null?void 0:Qa.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,Kr)=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:is},Kr))})]},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[Kr,Qr]=reactExports.useState(null),ja=useAnnotateGrade(es),Ca=useRemoveGradeAnnotation(es),Aa=new Map(is.map(Ia=>[`${Ia.evalRunId}:${Ia.expectationIndex}`,Ia])),Oa=(Ia,Da,Ba)=>{const Ma=Aa.get(`${Ia}:${Da}`);(Ma==null?void 0:Ma.verdict)===Ba?Ca.mutate({runId:Ia,expectationIndex:Da}):ja.mutate({runId:Ia,expectationIndex:Da,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,Ka,Ha;const Da=Kr===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(Da?null:Ia.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:[Da?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()})]})]}),Da&&jsxRuntimeExports.jsxs("div",{className:"border-t border-border p-4 space-y-3",children:[((Ka=Ia.grading)==null?void 0:Ka.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((Qa,Va)=>{const Ya=Aa.get(`${Ia.id}:${Va}`);return jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2 text-sm group",children:[Qa.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:Qa.text}),Qa.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:Qa.evidence})]}),Qa.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||Ca.isPending,title:"Judge graded this correctly",className:`p-1 rounded transition-colors ${(Ya==null?void 0:Ya.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||Ca.isPending,title:"Judge got this grade wrong",className:`p-1 rounded transition-colors ${(Ya==null?void 0:Ya.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)})]}),!!((Ha=Ia.outputs)!=null&&Ha.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(([Kr,Qr])=>Kr==="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,Ca])=>jsxRuntimeExports.jsxs("span",{children:[ja,": ",Ca]},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."})]},Kr):jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium mb-1",children:Kr}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:Object.entries(Qr).map(([ja,Ca])=>{const Aa=Ca;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)})})]},Kr)),is.notes.length>0&&jsxRuntimeExports.jsx("div",{className:"text-sm space-y-1",children:is.notes.map((Kr,Qr)=>jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground",children:["— ",Kr]},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(Kr=>{var Aa,Oa;const Qr=ts===Kr.id,ja=Ia=>Ia===Kr.targetAId?`${Kr.targetAName} v${Kr.targetAVersion}`:Ia===Kr.targetBId?`${Kr.targetBName} v${Kr.targetBVersion}`:null,Ca=Kr.status==="parse_failed"?"unparseable":ja(Kr.winnerTargetId)??"TIE";return jsxRuntimeExports.jsxs("div",{className:"border border-border rounded-lg",children:[jsxRuntimeExports.jsxs("button",{onClick:()=>is(Qr?null:Kr.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:Kr.status==="parse_failed"?"destructive":Kr.winnerTargetId?"default":"secondary",className:"font-mono text-xs",children:Ca}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm",children:[Kr.targetAName," v",Kr.targetAVersion," vs ",Kr.targetBName," v",Kr.targetBVersion]})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3 text-sm text-muted-foreground",children:[Kr.model&&jsxRuntimeExports.jsx("span",{className:"font-mono text-xs",children:Kr.model}),jsxRuntimeExports.jsx("span",{children:new Date(Kr.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",Kr.isSwapped?" (labels swapped)":""," — winners shown unblinded."]}),Kr.status==="parse_failed"?jsxRuntimeExports.jsx(ComparisonRawOutput,{id:Kr.id}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Kr.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:Kr.overall.reasoning})]}),(Aa=Kr.overall.strengthsWinner)!=null&&Aa.length||(Oa=Kr.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:(Kr.overall.strengthsWinner??[]).map((Ia,Da)=>jsxRuntimeExports.jsx("li",{children:Ia},Da))})]}),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:(Kr.overall.weaknessesLoser??[]).map((Ia,Da)=>jsxRuntimeExports.jsx("li",{children:Ia},Da))})]})]}):null,Kr.perEval.length>0&&jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("h4",{className:"text-sm font-medium",children:"Per eval"}),Kr.perEval.map((Ia,Da)=>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})]})]},Da))]})]})]})]},Kr.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 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 PromotionsTab({promotions:es,isLoading:$}){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(ts=>jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4 px-4 py-3","data-testid":"promotion-row",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("p",{className:"font-mono text-sm",children:[ts.decision," · ",ts.effectClass," · ",new Date(ts.createdAt).toLocaleDateString()]}),ts.rationale&&jsxRuntimeExports.jsx("p",{className:"pt-1 text-xs text-muted-foreground",children:ts.rationale})]}),jsxRuntimeExports.jsx("span",{className:cn$1("shrink-0 rounded border px-2 py-0.5 text-xs",ts.applied?"border-teal-400/40 text-teal-400":"border-muted-foreground/40 text-muted-foreground"),children:ts.applied?"applied":"not applied"})]},ts.id))})}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:Kr,oldest_analyzed_at:Qr}=es,ja=$>0?Math.round(is/$*100):0,Ca=ts>0?Math.round(Kr/ts*100):0;if(is===0&&Kr===0)return null;const Aa=ja>=25||Ca>=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&&Kr>0&&" ",Kr>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[Kr," of ",ts," timestamped analyses (",Ca,"%) 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(Da=>Da.status==="completed").length,ts=es.filter(Da=>Da.status==="failed").length,is=es.filter(Da=>Da.status==="running"||Da.status==="claimed").length,Kr=es.filter(Da=>Da.status==="pending").length,Qr=es.length,ja=$+ts,Ca=ja===Qr,Aa=$/Qr*100,Oa=ts/Qr*100,Ia=is/Qr*100;return jsxRuntimeExports.jsx(Card,{className:Ca?"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 items-center justify-between",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[Ca?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:"text-sm font-medium",children:Ca?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 items-center gap-3 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"]}),Kr>0&&jsxRuntimeExports.jsxs("span",{children:[Kr," 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 Da=es[0],Ba=Da.progress,Ma=Ba!=null&&Ba.current&&(Ba!=null&&Ba.total)?Ba.current/Ba.total*100:0;return Da.status==="completed"?jsxRuntimeExports.jsx("div",{className:"h-full bg-teal-500",style:{width:"100%"}}):Da.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(Da=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs py-0.5",children:[jsxRuntimeExports.jsx(JobStatusIcon,{status:Da.status}),jsxRuntimeExports.jsx("span",{className:"font-mono truncate",children:Da.projectPath??"global"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground ml-auto shrink-0",children:Da.status==="running"||Da.status==="claimed"?jobStepLabel(Da):Da.status==="failed"?"error":Da.status==="completed"?"done":"queued"})]},Da.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 Kr=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: ",Kr,"). 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($),Kr={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"}:Kr)} – ${is.toLocaleDateString(void 0,Kr)}`}const Qr=ts??is;return Qr?Qr.toLocaleDateString(void 0,Kr):null}function outcomeScore(es){const $=(es.achieved??0)+(es.mostly_achieved??0),ts=Object.values(es).reduce((is,Kr)=>is+Kr,0);return ts?Math.round($/ts*100):null}function InsightsOverview({computed:es}){var Ca;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],Kr=Object.entries(es.tool_counts??{}).sort((Aa,Oa)=>Oa[1]-Aa[1]).slice(0,5),Qr=((Ca=Kr[0])==null?void 0:Ca[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:Da})=>jsxRuntimeExports.jsx(Card,{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(Da,{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:"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((Da,Ba)=>Da+Ba,0));return jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"mb-1 flex justify-between text-sm",children:[jsxRuntimeExports.jsx("span",{children:Aa.replace(/_/g," ")}),jsxRuntimeExports.jsx("span",{className:"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,{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:Kr.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 Kr=formatSessionRange(es.firstSession,es.lastSession);return jsxRuntimeExports.jsxs(Card,{className:"cursor-pointer hover:border-primary/50 transition-colors",...activatable(is),children:[jsxRuntimeExports.jsx(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.name}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",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 items-center gap-6 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{children:[es.sessionCount," sessions"]}),es.analyzedCount>0&&jsxRuntimeExports.jsxs("span",{children:[es.analyzedCount," analyzed"]})]}),Kr&&jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:Kr})]})]})}function ReleaseCategorySection({label:es,items:$,colorClass:ts}){const[is,Kr]=reactExports.useState(!1);return $.length===0?null:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>Kr(!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,Ca,Aa;const $=es.categories??{features:[],fixes:[],security:[]},ts=((ja=$.features)==null?void 0:ja.length)??0,is=((Ca=$.fixes)==null?void 0:Ca.length)??0,Kr=((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":""]}),Kr>0&&jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:"text-[10px] bg-red-500/10 text-red-500 border-red-500/20",children:[Kr," 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,Kr)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-32"},Kr))}):!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:Kr}=useComputedInsights(),{data:Qr}=useInsightsProjects(),ja=useRegenerateAllInsights(),Ca=useActiveInsightsJobs(),{data:Aa}=useInsightsJobs(void 0,500),Oa=(Aa??[]).filter(Fa=>Fa.status!=="cancelled"),Ia=(()=>{if(Oa.length<2)return[];const Fa=[...Oa].sort((Ha,Qa)=>new Date(Ha.createdAt).getTime()-new Date(Qa.createdAt).getTime());let Ka=[];for(let Ha=0;Ha<Fa.length;Ha++){const Qa=new Date(Fa[Ha].createdAt).getTime(),Va=Fa.filter(Ya=>new Date(Ya.createdAt).getTime()-Qa<12e4&&new Date(Ya.createdAt).getTime()>=Qa);Va.length>Ka.length&&(Ka=Va)}return Ka.length<2?[]:Ka})(),Da=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 Ka=Fa.skipped.filter(Qa=>Qa.reason==="fresh").length,Ha=Fa.skipped.length-Ka;Ka>0?ue$1(Ha>0?`${Ka} project${Ka===1?"":"s"} fresh (<4h), ${Ha} skipped`:`All ${Ka} project${Ka===1?" is":"s are"} fresh (regenerated <4h ago)`,{action:{label:"Force regenerate",onClick:()=>ja.mutate({force:!0},{onSuccess:qa,onError:Qa=>ue$1.error("Couldn't start the regeneration",{description:Qa instanceof Error?Qa.message:"Please try again."})})}}):Ha>0?ue$1(`${Ha} project${Ha===1?"":"s"} skipped (no checkout or too few sessions)`):Fa.errors.length===0&&ue$1("No projects eligible for regeneration")};return Kr?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,Ka)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-28"},Ka))})]}):!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:"space-y-6",children:[jsxRuntimeExports.jsx(WorkerOfflineBanner,{}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",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.jsx("div",{className:"flex items-center gap-2",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||Ca.length>0,className:"cursor-pointer",children:Ca.length>0?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Generating (",Ca.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:[Da&&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 Ka=Ma.has(Fa.projectPath),Ha=Ba.get(Fa.projectPath),Qa=Fa.projectId??void 0,Va=Qa?`/insights/computed?projectPath=${encodeURIComponent(Fa.projectPath)}&projectId=${encodeURIComponent(Qa)}`:`/insights/computed?projectPath=${encodeURIComponent(Fa.projectPath)}`;return jsxRuntimeExports.jsx(ProjectCard,{project:Fa,hasReport:Ka,activeJob:Ha,onClick:()=>ts(Va)},Qa??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"}`:"",Kr=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}${Kr}.`,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,Ca=`${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}${Kr}. 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:[Ca," 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,Ca,Aa,Oa,Ia,Da;const is=useAutoAddSuggestion(),[Kr,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))})]}),((Ca=es.friction_analysis)==null?void 0:Ca.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:Kr.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(Ka=>new Set(Ka).add(Ma))},onError:Fa=>{const Ka=Fa instanceof ApiError&&(Fa.code==="not_local_mode"||Fa.statusCode===501);ue$1.error(Ka?"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"}):Kr.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}),Kr.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))})]}),((Da=es.on_the_horizon)==null?void 0:Da.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:Kr,inverted:Qr}){const ja=Oa=>Oa!=null?`${Oa}${Kr}`:"—",Ca=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 ${Ca} ${(Qr?is<0:is>0)?"bg-teal-500/10 border-teal-500/20":"bg-red-500/10 border-red-500/20"}`,children:[Aa,is,Kr]})]})}function SegmentLine({title:es,noun:$,segments:ts}){if(!ts||ts.length===0)return null;const is=ts.filter(Qr=>Qr.verdict.sufficient),Kr=ts.length-is.length;return is.length===0&&Kr===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,Ca=ja.delta>0,Aa=ja.significant?`${Ca?"+":""}${(ja.delta*100).toFixed(0)}%`:"no effect",Oa=ja.significant?Ca?"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)}),Kr>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 ${Kr===1?`this ${$}`:`these ${$}s`} yet.`,children:[Kr," ",$,Kr===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,Kr=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 / ",Kr.sessionCount," without"]}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground mt-0.5",children:[is.enrichedCount," / ",Kr.enrichedCount," enriched"]})]}),jsxRuntimeExports.jsx(ScorePair,{label:"Outcome Score",withVal:is.avgOutcomeScore,withoutVal:Kr.avgOutcomeScore,delta:Qr.outcomeScoreDelta,unit:""}),jsxRuntimeExports.jsx(ScorePair,{label:"Tool Errors",withVal:is.avgToolErrors,withoutVal:Kr.avgToolErrors,delta:Qr.toolErrorsDelta,unit:"",inverted:!0}),jsxRuntimeExports.jsx(ScorePair,{label:"Avg Duration",withVal:is.avgDurationMinutes,withoutVal:Kr.avgDurationMinutes,delta:Qr.durationDelta,unit:"m",inverted:!0})]}),jsxRuntimeExports.jsx(SegmentBreakdown,{impact:es})]})]})}function InstructionImpactLoader({instructionId:es,linkedSessions:$,source:ts}){const{data:is,isLoading:Kr}=useInstructionImpact(es);return Kr?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(),[Kr,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??[],Ca=es.bloated??[],Aa=es.candidates.length+ja.length;if(Aa===0&&Ca.length===0)return null;const Oa=Da=>jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",className:"h-6 text-[10px] shrink-0",disabled:Kr.has(Da)||ts.isPending,onClick:()=>ts.mutate(Da,{onSuccess:()=>{Qr(Ba=>new Set(Ba).add(Da)),ue$1.success("Archived",{description:"Soft delete — this can be restored.",action:{label:"Undo",onClick:()=>is.mutate(Da,{onSuccess:()=>{Qr(Ba=>{const Ma=new Set(Ba);return Ma.delete(Da),Ma}),ue$1.success("Restored")},onError:()=>ue$1.error("Restore failed")})}})},onError:()=>ue$1.error("Archive failed")}),children:Kr.has(Da)?"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+Ca.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:[Ca.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:Ca.map(Da=>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:Da.name,children:Da.name}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:Da.verdict}),Da.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:["~",Da.estimatedTokens.toLocaleString()," tok/session"]})]},Da.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(Da=>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:Da.name,children:Da.name}),jsxRuntimeExports.jsx(VerdictBadge,{verdict:Da.verdict})]}),Oa(Da.id)]},Da.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(Da=>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:Da.name,children:Da.name}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] shrink-0 text-muted-foreground",children:Da.reason})]}),Oa(Da.id)]},Da.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,Kr)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},Kr))}):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,Kr=ts?$.get("projectId")??void 0:void 0,[Qr,ja]=reactExports.useState(""),{data:Ca,recommendations:Aa,isLoading:Oa,fullProjectPath:Ia,title:Da,subtitle:Ba,lastCompletedJob:Ma,activeJobs:qa,createJob:Fa}=useProjectInsights(es,is,Kr,Qr||void 0),[Ka,Ha]=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((Ja,el)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-24"},el))})]});if(!Ca)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 Qa=ts?Ca.tools_used??{}:{},Va=Object.keys(Qa).sort((Ja,el)=>(Qa[el]??0)-(Qa[Ja]??0)),Ya=Ca.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:Da}),ts&&(Va.length>1||Qr)&&jsxRuntimeExports.jsxs("select",{value:Qr,onChange:Ja=>ja(Ja.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(Ja=>jsxRuntimeExports.jsxs("option",{value:Ja,children:[displayTool(Ja)," (",Qa[Ja],")"]},Ja)),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(Ja=>jsxRuntimeExports.jsx(Badge,{asChild:!0,variant:"outline",children:jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>ja(Ja),className:"text-[10px] font-mono cursor-pointer hover:bg-primary/10",children:[displayTool(Ja),": ",Qa[Ja]]})},Ja))})]})]}),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:Ja=>{Ja.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:Ja=>ue$1.error("Couldn't start the run",{description:Ja instanceof Error?Ja.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:Ca.analysis_freshness,totalAnalyzed:Ca.sessions_with_analysis??0}),jsxRuntimeExports.jsx(WorkerOfflineBanner,{}),qa.length>0&&jsxRuntimeExports.jsx(JobTracker,{jobs:qa}),jsxRuntimeExports.jsxs(Tabs,{value:Ka,onValueChange:Ha,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:Ca})}),jsxRuntimeExports.jsx(TabsContent,{value:"tools",className:"mt-6",children:jsxRuntimeExports.jsx(ToolsTab,{data:Ca})}),jsxRuntimeExports.jsx(TabsContent,{value:"quality",className:"mt-6",children:jsxRuntimeExports.jsx(QualityTab,{data:Ca})}),jsxRuntimeExports.jsx(TabsContent,{value:"sessions",className:"mt-6",children:jsxRuntimeExports.jsx(SessionsTab,{data:Ca})}),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:Ya}):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 Kr=new URLSearchParams({status:es,limit:String(MEMORY_PAGE_SIZE),offset:String(is)});return $&&Kr.set("search",$),ts&&ts!=="all"&&Kr.set("kind",ts),apiGet(`/api/memories?${Kr.toString()}`).then(Qr=>Qr.memories)},getNextPageParam:(is,Kr)=>is.length<MEMORY_PAGE_SIZE?void 0:Kr.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(Kr=>Kr.status==="pending"||Kr.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,Kr=useCreateMemory(),Qr=useUpdateMemory(),[ja,Ca]=reactExports.useState("fact"),[Aa,Oa]=reactExports.useState(""),[Ia,Da]=reactExports.useState("");reactExports.useEffect(()=>{es&&(Ca((ts==null?void 0:ts.kind)??"fact"),Oa((ts==null?void 0:ts.title)??""),Da((ts==null?void 0:ts.body)??""))},[es,ts==null?void 0:ts.id]);const Ba=Kr.isPending||Qr.isPending,Ma=Aa.trim().length>0&&Ia.trim().length>0&&!Ba,qa=()=>{if(!Ma)return;const Fa=Ha=>()=>{ue$1.success(`Memory ${Ha}`),$(!1)},Ka=Ha=>ue$1.error(Ha instanceof Error?Ha.message:"Something went wrong");is?Qr.mutate({id:ts.id,kind:ja,title:Aa.trim(),body:Ia.trim()},{onSuccess:Fa("updated"),onError:Ka}):Kr.mutate({kind:ja,title:Aa.trim(),body:Ia.trim()},{onSuccess:Fa("created"),onError:Ka})};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=>Ca(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=>Da(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 Kr=setTimeout(()=>is(es),$);return()=>clearTimeout(Kr)},[es,$]),ts}function MemoryList(){const[es,$]=reactExports.useState("active"),[ts,is]=reactExports.useState(""),[Kr,Qr]=reactExports.useState("all"),[ja,Ca]=reactExports.useState(!1),Aa=useNavigate(),Oa=useDebouncedValue(ts.trim(),300),{data:Ia,isLoading:Da,error:Ba,hasNextPage:Ma,fetchNextPage:qa,isFetchingNextPage:Fa}=useMemories(es,Oa,Kr),Ka=reactExports.useMemo(()=>(Ia==null?void 0:Ia.pages.flat())??[],[Ia]),Ha=Oa!==""||Kr!=="all";if(Ba)return jsxRuntimeExports.jsxs("div",{className:"text-center py-12 text-destructive",children:["Failed to load memories: ",Ba.message]});const Qa=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:Kr,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:()=>Ca(!0),children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"New"]})]}),Da?jsxRuntimeExports.jsx("div",{className:"space-y-2",children:Array.from({length:6}).map((Va,Ya)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-12 rounded-lg"},Ya))}):Ka.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:Ha?"No memories match your filters.":"No memories yet. Create one, or let the distiller extract them from your sessions."}),!Ha&&jsxRuntimeExports.jsxs(Button,{className:"cursor-pointer bg-primary text-primary-foreground hover:bg-primary/90",onClick:()=>Ca(!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"}),Qa&&jsxRuntimeExports.jsx(TableHead,{children:"Status"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Updated"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Ka.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}),Qa&&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:Ca})]})}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}){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.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})]}),jsxRuntimeExports.jsx("div",{className:"shrink-0",children:es.status==="completed"&&es.result?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"?jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px] text-red-400 border-red-400/40",children:"failed"}):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),[Kr,Qr]=reactExports.useState(!1),[ja,Ca]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(""),[Ia,Da]=reactExports.useState(10);function Ba(){const Ma=Aa.split(`
143
143
  `).map(qa=>qa.trim()).filter(Boolean);if(!ja.trim()||Ma.length===0){ue$1.error("A task prompt and at least one expectation are required.");return}is.mutate({taskPrompt:ja.trim(),expectations:Ma,trials:Ia},{onSuccess:qa=>{ue$1.success(qa.noLiveWorker?"Queued — start `rulemetric evals agent` on your laptop to run it":"Controlled A/B started — the causal verdict appears when it finishes"),Ca(""),Oa(""),Qr(!1)},onError:qa=>ue$1.error(`Failed: ${qa.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(Ma=>!Ma),children:Kr?"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 constant — so its delta isn't confounded. Each trial runs"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:"claude"})," on your laptop (needs"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:"rulemetric evals agent"}),"); ≥10 trials to clear the significance gate."]}),Kr&&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:Ma=>Ca(Ma.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:Ma=>Oa(Ma.target.value),placeholder:`Uses pnpm, not npm
144
- Runs the install command`,className:"text-xs min-h-16"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-end justify-between gap-2",children:[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:Ma=>Da(Math.max(1,Math.min(50,Number(Ma.target.value)||1))),className:"text-xs h-8 w-20"})]}),jsxRuntimeExports.jsx(Button,{size:"sm",className:"cursor-pointer",disabled:is.isPending,onClick:Ba,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.jsx("div",{children:$.map(Ma=>jsxRuntimeExports.jsx(ExperimentRow,{exp:Ma},Ma.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,Kr=$.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:Kr}),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),Kr=useArchiveMemory(),Qr=useUpdateMemory(),[ja,Ca]=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:()=>Ca(!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:Kr.isPending,onClick:()=>Kr.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:Ca,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:Kr=>{Kr.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:Kr}=useCopyToClipboard(),{data:Qr,isLoading:ja}=useSkill($?es==null?void 0:es.id:void 0);if(!es)return null;const Ca=Qr??es,Aa=`rulemetric skills install ${Ca.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:Ca.name})}),jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:Ca.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[Ca.category]??Ca.category}),Ca.tools.map(Ia=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs",children:displayTool(Ia)},Ia))]}),(((Oa=Ca.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:"}),Ca.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:[Ca.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([Ca.content],{type:"text/markdown"}),Da=URL.createObjectURL(Ia),Ba=document.createElement("a");Ba.href=Da,Ba.download=`${Ca.id}.md`,Ba.click(),URL.revokeObjectURL(Da)},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:()=>{Kr(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&&!Ca.content?jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"}):Ca.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:Ca.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:Ca.source.url,target:"_blank",rel:"noopener noreferrer",className:"underline inline-flex items-center gap-1",children:[Ca.source.repo,jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]})]}),Ca.source.license&&jsxRuntimeExports.jsx("span",{children:Ca.source.license})]})]})]})})}const PAGE_SIZE$1=60;function SkillsListPage(){const{data:es,isLoading:$}=useSkillsRegistry(),[ts,is]=reactExports.useState(""),[Kr,Qr]=reactExports.useState(null),[ja,Ca]=reactExports.useState(null),[Aa,Oa]=reactExports.useState(null),[Ia,Da]=reactExports.useState(PAGE_SIZE$1),Ba=(es==null?void 0:es.skills)??[],Ma=reactExports.useMemo(()=>[...new Set(Ba.map(Qa=>Qa.category))].sort(),[Ba]),qa=reactExports.useMemo(()=>[...new Set(Ba.flatMap(Qa=>Qa.tools))].sort(),[Ba]),Fa=reactExports.useMemo(()=>{let Qa=Ba;if(ts){const Va=ts.toLowerCase();Qa=Qa.filter(Ya=>Ya.name.toLowerCase().includes(Va)||Ya.description.toLowerCase().includes(Va)||Ya.tags.some(Ja=>Ja.toLowerCase().includes(Va))||Ya.id.toLowerCase().includes(Va))}return Kr&&(Qa=Qa.filter(Va=>Va.category===Kr)),ja&&(Qa=Qa.filter(Va=>Va.tools.includes(ja)||Va.tools.includes("universal"))),Qa.sort((Va,Ya)=>{var tl,il;const Ja=((tl=Va.popularity)==null?void 0:tl.stars)??0,el=((il=Ya.popularity)==null?void 0:il.stars)??0;return Ja!==el?el-Ja:Va.name.localeCompare(Ya.name)}),Qa},[Ba,ts,Kr,ja]);reactExports.useEffect(()=>{Da(PAGE_SIZE$1)},[ts,Kr,ja]);const Ka=Fa.slice(0,Ia),Ha=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:Qa=>is(Qa.target.value),className:"pl-9 font-mono"})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 flex-wrap",children:[Kr&&jsxRuntimeExports.jsxs(Button,{variant:"secondary",size:"sm",className:"cursor-pointer gap-1 font-mono text-xs",onClick:()=>Qr(null),children:[CATEGORY_LABELS[Kr]??Kr,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:()=>Ca(null),children:[displayTool(ja),jsxRuntimeExports.jsx(X$1,{className:"h-3 w-3"})]})]})]}),!Kr&&!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(Qa=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"cursor-pointer text-xs font-mono hover:bg-secondary",onClick:()=>Qr(Qa),children:CATEGORY_LABELS[Qa]??Qa},Qa))]}),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(Qa=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"cursor-pointer text-xs font-mono hover:bg-secondary",onClick:()=>Ca(Qa),children:displayTool(Qa)},Qa))]})]}),$?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((Qa,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 ",Ka.length," of ",Fa.length," skill",Fa.length!==1?"s":"",ts||Kr||ja?" matching filters":""]}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Ka.map(Qa=>jsxRuntimeExports.jsx(SkillCard,{skill:Qa,onSelect:Oa},Qa.id))}),Ha&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-2",children:jsxRuntimeExports.jsxs(Button,{variant:"outline",className:"cursor-pointer font-mono",onClick:()=>Da(Qa=>Qa+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 Da=setTimeout(()=>is(es),250);return()=>clearTimeout(Da)},[es]);const{data:Kr,isLoading:Qr,isFetchingNextPage:ja,fetchNextPage:Ca,hasNextPage:Aa,error:Oa}=usePublicCatalog(ts||void 0),Ia=reactExports.useMemo(()=>(Kr==null?void 0:Kr.pages.flat())??[],[Kr]);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:Da=>$(Da.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((Da,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(Da=>jsxRuntimeExports.jsx(Link,{to:`/catalog/public/${Da.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:Da.name}),Da.description&&jsxRuntimeExports.jsx(CardDescription,{className:"line-clamp-3",children:Da.description})]}),jsxRuntimeExports.jsxs(CardContent,{className:"mt-auto space-y-2",children:[Da.tags&&Da.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:Da.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:Da.sourceUpdatedAt??Da.updatedAt,children:["Updated ",relativeDate(Da.sourceUpdatedAt??Da.updatedAt)]}),typeof Da.popularityScore=="number"&&Da.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(Da.popularityScore)]})]})]})]})},Da.id))}),Aa&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-4",children:jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Ca(),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 Kr,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}),((Kr=$.frontmatter)==null?void 0:Kr.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:Kr}){const Qr=useLogSuggestionEvent(),ja=usePromoteFromPublic(),Ca=useArchiveInstruction(),Aa=useRestoreInstruction(),Oa=useNominateExperiment(),Ia=es.kind??"add",Da=Qr.isPending||ja.isPending||Ca.isPending||Oa.isPending;function Ba(Ha){Oa.mutate({instructionId:es.instructionId,projectPath:$,source:Ha},{onSuccess:()=>ue$1(`Under measurement: ${es.name}`,{description:"Injected to half your sessions on this project; the verdict decides."}),onError:Qa=>ue$1.error(`Could not start the trial: ${Qa.message}`)})}async function Ma(){try{await Ca.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(Ha){ue$1.error(`Failed: ${Ha.message}`)}}async function qa(){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(Ha){ue$1.error(`Failed: ${Ha.message}`)}}async function Fa(){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(Ha){ue$1.error(`Failed: ${Ha.message}`)}}async function Ka(){try{await Qr.mutateAsync({suggestionId:es.id,eventType:"dismissed",projectPath:$}),ue$1(`Dismissed: ${es.name}`)}catch(Ha){ue$1.error(`Failed: ${Ha.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",{className:"flex-1 min-w-0 basis-56 space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[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":""]})}),(Kr??[]).map(Ha=>jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Measured on ${Ha.projectPath}: ${Ha.decision==="always"?"helped":"hurt"} (${Number(Ha.delta)>0?"+":""}${(Number(Ha.delta)*100).toFixed(0)}pp, 95% CI ${(Number(Ha.ciLower)*100).toFixed(0)} to ${(Number(Ha.ciUpper)*100).toFixed(0)}pp, n=${Ha.nTreated}/${Ha.nControl}). That evidence was earned THERE — it does not transfer here; it argues for measuring here.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:Ha.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(Ha.delta)>0?"+":"",(Number(Ha.delta)*100).toFixed(0),"pp elsewhere"]})},Ha.projectPath))]}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason}),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:()=>Ba(((Kr==null?void 0:Kr.length)??0)>0?"borrow":"trial"),disabled:Da,"data-testid":"trial-button",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"h-4 w-4 mr-1"}),((Kr==null?void 0:Kr.length)??0)>0?"Test here":"Trial"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"cursor-pointer",onClick:Ia==="remove"?Ma:Ia==="trim"?qa:Fa,disabled:Da,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:Ka,disabled:Da,children:[jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4 mr-1"}),"Dismiss"]})]})]})}function SuggestionsListPage(){const es=useProjectPaths(),$=es.data??[],ts=useSuggestionsForProjects($),is=es.isLoading,Kr=ts.some(Oa=>Oa.isLoading),Qr=ts.map((Oa,Ia)=>{var Da,Ba,Ma;return{projectPath:$[Ia],suggestions:((Da=Oa.data)==null?void 0:Da.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),Ca=Qr.flatMap(Oa=>Oa.suggestions.map(Ia=>Ia.instructionId)),{data:Aa}=useSuggestionImpacts(Ca);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."}):!Kr&&ja===0?jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No suggestions yet. The cron runs daily at 04:30 and scores your recent projects against your library."}):jsxRuntimeExports.jsx("div",{className:"space-y-4",children:Qr.map(Oa=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base font-mono truncate",children:Oa.projectPath})}),jsxRuntimeExports.jsx(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 Da,Ba;return jsxRuntimeExports.jsx(SuggestionRow,{suggestion:Ia,projectPath:Oa.projectPath,verdict:Aa==null?void 0:Aa[Ia.instructionId],experiment:(Da=Oa.experiments)==null?void 0:Da[Ia.instructionId],evidence:(Ba=Oa.crossProject)==null?void 0:Ba[Ia.instructionId]},Ia.id)})})})]},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 that received this instruction scored measurably"," ",$?"better":"worse"," than the sessions it was withheld from."]}),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.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. This one resolves itself: keep running sessions on this project.",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:"no measured effect"}),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,Kr=({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(Kr,{label:"treated (shown)",arm:"treated"}),jsxRuntimeExports.jsx(Kr,{label:"control (withheld)",arm:"control"})]}),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"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-muted-foreground","data-testid":"stopped-reason-badge",children:"ended · no detectable effect"}),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 edited"}),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),Kr=(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,Ca)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-48 rounded-lg"},Ca))}):ts?jsxRuntimeExports.jsxs("div",{className:"py-12 text-center text-muted-foreground","data-testid":"experiments-error",children:["Could not load experiments: ",is.message]}):Kr.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:[Kr.map(ja=>jsxRuntimeExports.jsx(ExperimentCard,{experiment:ja},ja.id)),Qr>Kr.length&&jsxRuntimeExports.jsxs("p",{className:"text-center text-xs text-muted-foreground","data-testid":"experiments-truncated",children:["Showing ",Kr.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 Kr of es){if(isNotable(Kr)){$.push(Kr);continue}const Qr=ts.get(Kr.kind)??{kind:Kr.kind,count:0,outcomes:{},totalSeconds:0,slowestSeconds:0};Qr.count+=1,Qr.outcomes[Kr.outcome]=(Qr.outcomes[Kr.outcome]??0)+1;const ja=Kr.durationSeconds??0;Qr.totalSeconds+=ja,Qr.slowestSeconds=Math.max(Qr.slowestSeconds,ja),ts.set(Kr.kind,Qr)}const is=[...ts.values()].sort((Kr,Qr)=>Qr.count-Kr.count);return{notable:$,routine:is,routineCount:is.reduce((Kr,Qr)=>Kr+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:Kr,running:Qr,queued:ja}=es;return ts?{tone:"critical",text:"A job is claimed but its lease has expired — the worker took work and stopped."}:$?is>0?{tone:"action",text:`${is} measured edit${is===1?"":"s"} waiting for you to apply.`}:Kr>0?{tone:"warn",text:`${Kr} job${Kr===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 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}){const[$,ts]=reactExports.useState(!1),{notable:is,routine:Kr,routineCount:Qr}=partitionFinished(es.recent),ja=es.running.length===0&&es.queued.length===0;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",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",children:["last ",es.windowHours,"h",es.recentTotal>es.recent.length&&` · ${es.recent.length} of ${es.recentTotal}`]})]})}),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:ja&&!es.worker.present?"No worker connected, so nothing has run.":`No jobs finished in the last ${es.windowHours}h.`}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[is.length>0?jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:is.map(Ca=>jsxRuntimeExports.jsx(FinishedRow,{job:Ca},Ca.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."}),Qr>0&&jsxRuntimeExports.jsxs("div",{className:"mt-2 border-t border-border pt-2",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>ts(Ca=>!Ca),className:"flex min-h-11 w-full cursor-pointer items-center justify-between gap-2 text-xs text-muted-foreground hover:text-foreground","aria-expanded":$,"data-testid":"toggle-routine",children:[jsxRuntimeExports.jsxs("span",{children:[Qr," routine job",Qr===1?"":"s"," across ",Kr.length," ","kind",Kr.length===1?"":"s"]}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3 shrink-0"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3 shrink-0"})]}),$&&jsxRuntimeExports.jsx("div",{className:"divide-y divide-border pt-1",children:Kr.map(Ca=>jsxRuntimeExports.jsx(RoutineRow,{group:Ca},Ca.kind))})]})]})})]})}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-status"]}),es.invalidateQueries({queryKey:["promotion"]})}})}function useRunLoopNow(){const es=useQueryClient();return useMutation({mutationFn:()=>apiPost("/api/loop/run-now",{}),onSuccess:()=>{es.invalidateQueries({queryKey:["loop-status"]})}})}function useLoopStatus(){return useQuery({queryKey:["loop-status"],queryFn:()=>apiGet("/api/loop/status"),refetchInterval:es=>{var $;return((($=es.state.data)==null?void 0:$.running.length)??0)>0?5e3:3e4}})}function ProvenanceBlock(){const{data:es}=useProvenanceImpact();return!es||es.groups.length===0?null:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",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})]})]})}const MAX_LINES=4e3,toLines=es=>es===""?[]:es.split(`
145
- `);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 Kr=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--)Kr[Aa][Oa]=ts[Aa]===is[Oa]?Kr[Aa+1][Oa+1]+1:Math.max(Kr[Aa+1][Oa],Kr[Aa][Oa+1]);const Qr=[];let ja=0,Ca=0;for(;ja<ts.length&&Ca<is.length;)ts[ja]===is[Ca]?(Qr.push({op:"same",text:ts[ja],oldLine:ja+1,newLine:Ca+1}),ja++,Ca++):Kr[ja+1][Ca]>=Kr[ja][Ca+1]?(Qr.push({op:"remove",text:ts[ja],oldLine:ja+1,newLine:null}),ja++):(Qr.push({op:"add",text:is[Ca],oldLine:null,newLine:Ca+1}),Ca++);for(;ja<ts.length;)Qr.push({op:"remove",text:ts[ja],oldLine:++ja,newLine:null});for(;Ca<is.length;)Qr.push({op:"add",text:is[Ca],oldLine:null,newLine:++Ca});return Qr}function toHunks(es,$=3){const ts=new Set;es.forEach((Ca,Aa)=>{if(Ca.op!=="same")for(let Oa=Math.max(0,Aa-$);Oa<=Math.min(es.length-1,Aa+$);Oa++)ts.add(Oa)});const is=[];let Kr=[],Qr=0,ja=0;return es.forEach((Ca,Aa)=>{ts.has(Aa)?(Kr.length===0&&(Qr=ja,ja=0),Kr.push(Ca)):(Kr.length>0&&(is.push({lines:Kr,skippedBefore:Qr}),Kr=[]),ja++)}),Kr.length>0&&is.push({lines:Kr,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 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(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),{data:is,isLoading:Kr,isError:Qr}=usePromotionDetail(es,$),ja=useApplyPromotion(),Ca=is?lineDiff(is.fromContent,is.toContent):[],Aa=is?toHunks(Ca):[],Oa=diffStat(Ca);return jsxRuntimeExports.jsxs("div",{className:"pt-2",children:[jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>ts(Ia=>!Ia),className:"inline-flex min-h-11 cursor-pointer items-center text-xs text-teal-400 hover:underline","data-testid":"toggle-pending-diff",children:$?"Hide the diff":"Show what it would change →"}),$&&jsxRuntimeExports.jsxs("div",{className:"pt-2","data-testid":"pending-diff",children:[Kr&&jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}),Qr&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-400/90",children:"Could not load the proposed change."}),is&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[is.proposalRationale&&jsxRuntimeExports.jsx("p",{className:"pb-2 text-xs text-muted-foreground",children:is.proposalRationale}),jsxRuntimeExports.jsxs("p",{className:"pb-1 font-mono text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{className:"text-teal-400",children:["+",Oa.added]})," ",jsxRuntimeExports.jsxs("span",{className:"text-amber-400",children:["−",Oa.removed]})," lines"]}),jsxRuntimeExports.jsx("div",{className:"max-h-96 overflow-auto rounded border border-border bg-background/50",children:jsxRuntimeExports.jsx("pre",{className:"w-max min-w-full font-mono text-xs leading-relaxed",children:Aa.map((Ia,Da)=>jsxRuntimeExports.jsxs("div",{children:[Ia.skippedBefore>0&&jsxRuntimeExports.jsxs("div",{className:"bg-muted/30 px-2 py-0.5 text-muted-foreground",children:["… ",Ia.skippedBefore," unchanged line",Ia.skippedBefore===1?"":"s"]}),Ia.lines.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:cn$1("px-2",Ba.op==="add"&&"bg-teal-400/10 text-teal-300",Ba.op==="remove"&&"bg-amber-400/10 text-amber-300",Ba.op==="same"&&"text-muted-foreground"),children:[jsxRuntimeExports.jsx("span",{className:"select-none pr-2 opacity-50",children:Ba.op==="add"?"+":Ba.op==="remove"?"−":" "}),Ba.text||" "]},Ma))]},Da))})}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3 pt-2",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:ja.isPending||ja.isSuccess,onClick:()=>ja.mutate(es),className:cn$1("rounded border px-3 py-1 text-xs",ja.isSuccess?"border-teal-400/40 text-teal-400":"cursor-pointer border-teal-400/40 text-teal-400 hover:bg-teal-400/10",ja.isPending&&"opacity-60"),"data-testid":"apply-promotion",children:ja.isSuccess?"Applied":ja.isPending?"Applying…":"Apply this change"}),ja.isError&&jsxRuntimeExports.jsx("span",{className:"text-xs text-amber-400/90","data-testid":"apply-error",children:ja.error instanceof Error?ja.error.message:"Could not apply this change."})]})]})]})]})}function Kpi({value:es,of:$,label:ts,detail:is,good:Kr,testId:Qr}){return jsxRuntimeExports.jsxs("div",{className:"min-w-0 px-3 py-2",children:[jsxRuntimeExports.jsxs("p",{className:"flex items-baseline gap-1",children:[jsxRuntimeExports.jsx("span",{className:cn$1("text-2xl font-semibold tabular-nums",Kr?"text-teal-400":"text-muted-foreground"),"data-testid":Qr,children:es}),$!=null&&jsxRuntimeExports.jsxs("span",{className:"text-xs tabular-nums text-muted-foreground",children:["/ ",$]})]}),jsxRuntimeExports.jsx("p",{className:"truncate text-xs text-muted-foreground",children:ts}),is&&jsxRuntimeExports.jsx("p",{className:"truncate font-mono text-[11px] text-muted-foreground/80",children:is})]})}function KpiStrip({status:es}){const{changes:$,counts:ts,insights:is}=es,{applied:Kr,decisions:Qr,byDecision:ja,suggestionsAccepted:Ca,suggestionsProposed:Aa}=$,Oa=Kr===0&&Ca===0;return jsxRuntimeExports.jsx(Card,{className:cn$1(Oa&&Qr+Aa>0&&"border-amber-400/40"),"data-testid":"changes-headline",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-0",children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 divide-x divide-y divide-border sm:grid-cols-3 sm:divide-y-0 lg:grid-cols-5",children:[jsxRuntimeExports.jsx(Kpi,{value:Kr,of:Qr||void 0,label:"edits applied",detail:Qr>0?`${ja.promote}P · ${ja.revert}R · ${ja.refuse}X`:void 0,good:Kr>0,testId:"changes-applied"}),jsxRuntimeExports.jsx(Kpi,{value:Ca,of:Aa||void 0,label:"suggestions accepted",good:Ca>0,testId:"changes-accepted"}),jsxRuntimeExports.jsx(Kpi,{value:Qr,label:"decisions recorded",good:Qr>0}),jsxRuntimeExports.jsx(Kpi,{value:ts.experimentsRunning,label:"experiments running",good:ts.experimentsRunning>0}),jsxRuntimeExports.jsx(Kpi,{value:is.repeated,of:is.distinct||void 0,label:"insights repeated",detail:is.entries>0?`${is.entries} entries`:void 0,good:is.repeated>0})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 border-t border-border px-3 py-2 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.'}),Oa&&Qr+Aa>0&&jsxRuntimeExports.jsx("span",{className:"text-amber-400/90","data-testid":"never-acted",children:"· Measuring, not acting: nothing has ever been applied or accepted."})]})]})})}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 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({workerPresent:es.worker.present,leaseUnhealthy:es.running.some(ts=>!ts.leaseHealthy),readyToApply:es.changes.readyToApply,failedRecently:es.recent.filter(ts=>ts.outcome==="failed").length,running:es.running.length,queued:es.queued.length});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{data:es,isLoading:$,isError:ts}=useLoopStatus();return $?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"})]}):ts||!es?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."]})})}):(es.running.length===0&&es.queued.length,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:es}),jsxRuntimeExports.jsx(StatusBanner,{status:es})]})]}),jsxRuntimeExports.jsx(ReadyToApplyCallout,{changes:es.changes}),jsxRuntimeExports.jsx(KpiStrip,{status:es}),jsxRuntimeExports.jsxs("div",{className:"grid gap-4 lg:grid-cols-5",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-4 lg:col-span-3",children:[(es.running.length>0||es.queued.length>0)&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",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(is=>jsxRuntimeExports.jsx(RunningRow,{job:is},is.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(is=>jsxRuntimeExports.jsx(QueuedRow,{job:is},is.id))})]})]})]}),jsxRuntimeExports.jsx(FinishedList,{status:es})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-4 lg:col-span-2",children:[jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-base",children:["Proposed changes",es.proposalTotal>es.proposals.length&&jsxRuntimeExports.jsxs("span",{className:"pl-2 font-normal text-muted-foreground",children:["showing ",es.proposals.length," of ",es.proposalTotal]})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[es.proposals.length>0?jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:es.proposals.map(is=>jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3 py-1.5","data-testid":"proposal",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("p",{className:"truncate text-sm",title:is.targetName??"",children:[is.targetName?is.targetName.split("/").pop():"(target deleted)",is.targetName&&jsxRuntimeExports.jsx("span",{className:"pl-1.5 text-xs text-muted-foreground",children:is.targetName.split("/").slice(-3,-1).join("/")})]}),jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-muted-foreground",children:[is.decision," · ",is.effectClass," · via ",is.proposalSource]})]}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("shrink-0",is.applied?"border-teal-400/40 text-teal-400":"border-muted-foreground/40 text-muted-foreground"),"data-testid":"proposal-applied",children:is.applied?"applied":"not applied"})]},is.id))}):jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No changes proposed yet."}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-4 border-t border-border pt-3 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs(Link,{to:"/experiments",className:"hover:text-foreground",children:[es.counts.experimentsRunning," experiment",es.counts.experimentsRunning===1?"":"s"," running"]}),jsxRuntimeExports.jsxs(Link,{to:"/suggestions",className:"hover:text-foreground",children:["suggestions:"," ",Object.entries(es.counts.suggestions).map(([is,Kr])=>`${Kr} ${is}`).join(" · ")||"none"]})]}),jsxRuntimeExports.jsxs("div",{className:"border-t border-border pt-3","data-testid":"insights-memory",children:[jsxRuntimeExports.jsx("p",{className:"pb-1 text-xs uppercase tracking-wide text-muted-foreground",children:"Insights memory"}),jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-muted-foreground",children:[es.insights.entries," entries · ",es.insights.distinct," distinct ·"," ",es.insights.repeated," repeated · ",es.insights.dismissed," dismissed · max seen ×",es.insights.maxTimesGenerated]}),es.insights.entries>0&&es.insights.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.jsx(ProvenanceBlock,{})]})]})]}))}function ToggleSwitch({checked:es,label:$,onToggle:ts,disabled:is,danger:Kr,testId:Qr}){return jsxRuntimeExports.jsx("button",{type:"button",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?Kr?"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",Kr?"bg-amber-400":"bg-teal-400"):"left-0.5 bg-muted-foreground")})})})}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:$,children:ts}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-3",children:[jsxRuntimeExports.jsxs("span",{className:"min-w-0 text-xs",children:[es,$&&jsxRuntimeExports.jsx("span",{className:"block text-[11px] text-muted-foreground",children:$})]}),ts]})}function TargetRow({target:es,minPairs:$,maxPairs:ts,onPatch:is,pending:Kr}){const{settings:Qr,name:ja}=es,Ca=ja.split("/").pop()||ja,Aa=ja.slice(0,Math.max(0,ja.length-Ca.length-1));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:Ca}),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-2 sm:grid-cols-2 lg:grid-cols-3",children:[jsxRuntimeExports.jsx(Row,{label:"Enrolled",hint:"measure this instruction",children:jsxRuntimeExports.jsx(ToggleSwitch,{checked:Qr.enabled,label:`Enrol ${Ca} in evolution`,testId:"evolution-enabled",disabled:Kr,onToggle:()=>is({enabled:!Qr.enabled})})}),jsxRuntimeExports.jsx(Row,{label:"May rewrite",hint:"act on a verdict, not just record it",children:jsxRuntimeExports.jsx(ToggleSwitch,{checked:Qr.apply,danger:!0,label:`Allow evolution to rewrite ${Ca}`,testId:"evolution-apply",disabled:Kr,onToggle:()=>is({apply:!Qr.apply})})}),jsxRuntimeExports.jsx(Row,{label:"Paused",hint:"stop spending, keep the opt-in",children:jsxRuntimeExports.jsx(ToggleSwitch,{checked:Qr.pausedBy==="target",label:`Pause evolution for ${Ca}`,testId:"evolution-paused",disabled:Kr||Qr.pausedBy==="account",onToggle:()=>is({paused:Qr.pausedBy!=="target"})})}),jsxRuntimeExports.jsx(Row,{label:"Skip auto-enrolment",hint:"never picked up by the rule",children:jsxRuntimeExports.jsx(ToggleSwitch,{checked:Qr.optOut,label:`Exclude ${Ca} from automatic enrolment`,testId:"evolution-optout",disabled:Kr,onToggle:()=>is({optOut:!Qr.optOut})})}),jsxRuntimeExports.jsx(Row,{label:"Pool across nights",hint:"one candidate, evidence accumulated",children:jsxRuntimeExports.jsx(ToggleSwitch,{checked:Qr.accumulate,label:`Accumulate evidence across nights for ${Ca}`,testId:"evolution-accumulate",disabled:Kr,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:Kr,"data-testid":"evolution-pairs",onBlur:Oa=>{const Ia=Number(Oa.currentTarget.value);Number.isFinite(Ia)&&Ia!==Qr.pairs&&is({pairs:Ia})},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(),Kr=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:Kr.isPending,onToggle:()=>Kr.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:Ca=>is.mutate({evalTargetId:ja.evalTargetId,...Ca})},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||Kr.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."]})]})})]})}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.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",`
144
+ Runs the install command`,className:"text-xs min-h-16"})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-end justify-between gap-2",children:[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:Ma=>Da(Math.max(1,Math.min(50,Number(Ma.target.value)||1))),className:"text-xs h-8 w-20"})]}),jsxRuntimeExports.jsx(Button,{size:"sm",className:"cursor-pointer",disabled:is.isPending,onClick:Ba,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.jsx("div",{children:$.map(Ma=>jsxRuntimeExports.jsx(ExperimentRow,{exp:Ma},Ma.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,Kr=$.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:Kr}),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),Kr=useArchiveMemory(),Qr=useUpdateMemory(),[ja,Ca]=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:()=>Ca(!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:Kr.isPending,onClick:()=>Kr.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:Ca,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:Kr=>{Kr.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:Kr}=useCopyToClipboard(),{data:Qr,isLoading:ja}=useSkill($?es==null?void 0:es.id:void 0);if(!es)return null;const Ca=Qr??es,Aa=`rulemetric skills install ${Ca.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:Ca.name})}),jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:Ca.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[Ca.category]??Ca.category}),Ca.tools.map(Ia=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"font-mono text-xs",children:displayTool(Ia)},Ia))]}),(((Oa=Ca.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:"}),Ca.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:[Ca.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([Ca.content],{type:"text/markdown"}),Da=URL.createObjectURL(Ia),Ba=document.createElement("a");Ba.href=Da,Ba.download=`${Ca.id}.md`,Ba.click(),URL.revokeObjectURL(Da)},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:()=>{Kr(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&&!Ca.content?jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"}):Ca.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:Ca.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:Ca.source.url,target:"_blank",rel:"noopener noreferrer",className:"underline inline-flex items-center gap-1",children:[Ca.source.repo,jsxRuntimeExports.jsx(ExternalLink,{className:"h-3 w-3"})]})]}),Ca.source.license&&jsxRuntimeExports.jsx("span",{children:Ca.source.license})]})]})]})})}const PAGE_SIZE$1=60;function SkillsListPage(){const{data:es,isLoading:$}=useSkillsRegistry(),[ts,is]=reactExports.useState(""),[Kr,Qr]=reactExports.useState(null),[ja,Ca]=reactExports.useState(null),[Aa,Oa]=reactExports.useState(null),[Ia,Da]=reactExports.useState(PAGE_SIZE$1),Ba=(es==null?void 0:es.skills)??[],Ma=reactExports.useMemo(()=>[...new Set(Ba.map(Qa=>Qa.category))].sort(),[Ba]),qa=reactExports.useMemo(()=>[...new Set(Ba.flatMap(Qa=>Qa.tools))].sort(),[Ba]),Fa=reactExports.useMemo(()=>{let Qa=Ba;if(ts){const Va=ts.toLowerCase();Qa=Qa.filter(Ya=>Ya.name.toLowerCase().includes(Va)||Ya.description.toLowerCase().includes(Va)||Ya.tags.some(Ja=>Ja.toLowerCase().includes(Va))||Ya.id.toLowerCase().includes(Va))}return Kr&&(Qa=Qa.filter(Va=>Va.category===Kr)),ja&&(Qa=Qa.filter(Va=>Va.tools.includes(ja)||Va.tools.includes("universal"))),Qa.sort((Va,Ya)=>{var tl,il;const Ja=((tl=Va.popularity)==null?void 0:tl.stars)??0,el=((il=Ya.popularity)==null?void 0:il.stars)??0;return Ja!==el?el-Ja:Va.name.localeCompare(Ya.name)}),Qa},[Ba,ts,Kr,ja]);reactExports.useEffect(()=>{Da(PAGE_SIZE$1)},[ts,Kr,ja]);const Ka=Fa.slice(0,Ia),Ha=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:Qa=>is(Qa.target.value),className:"pl-9 font-mono"})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2 flex-wrap",children:[Kr&&jsxRuntimeExports.jsxs(Button,{variant:"secondary",size:"sm",className:"cursor-pointer gap-1 font-mono text-xs",onClick:()=>Qr(null),children:[CATEGORY_LABELS[Kr]??Kr,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:()=>Ca(null),children:[displayTool(ja),jsxRuntimeExports.jsx(X$1,{className:"h-3 w-3"})]})]})]}),!Kr&&!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(Qa=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"cursor-pointer text-xs font-mono hover:bg-secondary",onClick:()=>Qr(Qa),children:CATEGORY_LABELS[Qa]??Qa},Qa))]}),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(Qa=>jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"cursor-pointer text-xs font-mono hover:bg-secondary",onClick:()=>Ca(Qa),children:displayTool(Qa)},Qa))]})]}),$?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Array.from({length:6}).map((Qa,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 ",Ka.length," of ",Fa.length," skill",Fa.length!==1?"s":"",ts||Kr||ja?" matching filters":""]}),jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Ka.map(Qa=>jsxRuntimeExports.jsx(SkillCard,{skill:Qa,onSelect:Oa},Qa.id))}),Ha&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-2",children:jsxRuntimeExports.jsxs(Button,{variant:"outline",className:"cursor-pointer font-mono",onClick:()=>Da(Qa=>Qa+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 Da=setTimeout(()=>is(es),250);return()=>clearTimeout(Da)},[es]);const{data:Kr,isLoading:Qr,isFetchingNextPage:ja,fetchNextPage:Ca,hasNextPage:Aa,error:Oa}=usePublicCatalog(ts||void 0),Ia=reactExports.useMemo(()=>(Kr==null?void 0:Kr.pages.flat())??[],[Kr]);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:Da=>$(Da.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((Da,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(Da=>jsxRuntimeExports.jsx(Link,{to:`/catalog/public/${Da.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:Da.name}),Da.description&&jsxRuntimeExports.jsx(CardDescription,{className:"line-clamp-3",children:Da.description})]}),jsxRuntimeExports.jsxs(CardContent,{className:"mt-auto space-y-2",children:[Da.tags&&Da.tags.length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:Da.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:Da.sourceUpdatedAt??Da.updatedAt,children:["Updated ",relativeDate(Da.sourceUpdatedAt??Da.updatedAt)]}),typeof Da.popularityScore=="number"&&Da.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(Da.popularityScore)]})]})]})]})},Da.id))}),Aa&&jsxRuntimeExports.jsx("div",{className:"flex justify-center pt-4",children:jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Ca(),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 Kr,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}),((Kr=$.frontmatter)==null?void 0:Kr.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:Kr}){const Qr=useLogSuggestionEvent(),ja=usePromoteFromPublic(),Ca=useArchiveInstruction(),Aa=useRestoreInstruction(),Oa=useNominateExperiment(),Ia=es.kind??"add",Da=Qr.isPending||ja.isPending||Ca.isPending||Oa.isPending;function Ba(Ha){Oa.mutate({instructionId:es.instructionId,projectPath:$,source:Ha},{onSuccess:()=>ue$1(`Under measurement: ${es.name}`,{description:"Injected to half your sessions on this project; the verdict decides."}),onError:Qa=>ue$1.error(`Could not start the trial: ${Qa.message}`)})}async function Ma(){try{await Ca.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(Ha){ue$1.error(`Failed: ${Ha.message}`)}}async function qa(){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(Ha){ue$1.error(`Failed: ${Ha.message}`)}}async function Fa(){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(Ha){ue$1.error(`Failed: ${Ha.message}`)}}async function Ka(){try{await Qr.mutateAsync({suggestionId:es.id,eventType:"dismissed",projectPath:$}),ue$1(`Dismissed: ${es.name}`)}catch(Ha){ue$1.error(`Failed: ${Ha.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",{className:"flex-1 min-w-0 basis-56 space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[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":""]})}),(Kr??[]).map(Ha=>jsxRuntimeExports.jsx(InfoTip,{plain:!0,content:`Measured on ${Ha.projectPath}: ${Ha.decision==="always"?"helped":"hurt"} (${Number(Ha.delta)>0?"+":""}${(Number(Ha.delta)*100).toFixed(0)}pp, 95% CI ${(Number(Ha.ciLower)*100).toFixed(0)} to ${(Number(Ha.ciUpper)*100).toFixed(0)}pp, n=${Ha.nTreated}/${Ha.nControl}). That evidence was earned THERE — it does not transfer here; it argues for measuring here.`,children:jsxRuntimeExports.jsxs(Badge,{variant:"outline",className:Ha.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(Ha.delta)>0?"+":"",(Number(Ha.delta)*100).toFixed(0),"pp elsewhere"]})},Ha.projectPath))]}),es.reason&&jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:es.reason}),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:()=>Ba(((Kr==null?void 0:Kr.length)??0)>0?"borrow":"trial"),disabled:Da,"data-testid":"trial-button",children:[jsxRuntimeExports.jsx(FlaskConical,{className:"h-4 w-4 mr-1"}),((Kr==null?void 0:Kr.length)??0)>0?"Test here":"Trial"]}),jsxRuntimeExports.jsxs(Button,{size:"sm",variant:"outline",className:"cursor-pointer",onClick:Ia==="remove"?Ma:Ia==="trim"?qa:Fa,disabled:Da,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:Ka,disabled:Da,children:[jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4 mr-1"}),"Dismiss"]})]})]})}function SuggestionsListPage(){const es=useProjectPaths(),$=es.data??[],ts=useSuggestionsForProjects($),is=es.isLoading,Kr=ts.some(Oa=>Oa.isLoading),Qr=ts.map((Oa,Ia)=>{var Da,Ba,Ma;return{projectPath:$[Ia],suggestions:((Da=Oa.data)==null?void 0:Da.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),Ca=Qr.flatMap(Oa=>Oa.suggestions.map(Ia=>Ia.instructionId)),{data:Aa}=useSuggestionImpacts(Ca);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."}):!Kr&&ja===0?jsxRuntimeExports.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"No suggestions yet. The cron runs daily at 04:30 and scores your recent projects against your library."}):jsxRuntimeExports.jsx("div",{className:"space-y-4",children:Qr.map(Oa=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-base font-mono truncate",children:Oa.projectPath})}),jsxRuntimeExports.jsx(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 Da,Ba;return jsxRuntimeExports.jsx(SuggestionRow,{suggestion:Ia,projectPath:Oa.projectPath,verdict:Aa==null?void 0:Aa[Ia.instructionId],experiment:(Da=Oa.experiments)==null?void 0:Da[Ia.instructionId],evidence:(Ba=Oa.crossProject)==null?void 0:Ba[Ia.instructionId]},Ia.id)})})})]},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 that received this instruction scored measurably"," ",$?"better":"worse"," than the sessions it was withheld from."]}),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.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. This one resolves itself: keep running sessions on this project.",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:"no measured effect"}),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,Kr=({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(Kr,{label:"treated (shown)",arm:"treated"}),jsxRuntimeExports.jsx(Kr,{label:"control (withheld)",arm:"control"})]}),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"&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs text-muted-foreground","data-testid":"stopped-reason-badge",children:"ended · no detectable effect"}),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 edited"}),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),Kr=(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,Ca)=>jsxRuntimeExports.jsx(Skeleton,{className:"h-48 rounded-lg"},Ca))}):ts?jsxRuntimeExports.jsxs("div",{className:"py-12 text-center text-muted-foreground","data-testid":"experiments-error",children:["Could not load experiments: ",is.message]}):Kr.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:[Kr.map(ja=>jsxRuntimeExports.jsx(ExperimentCard,{experiment:ja},ja.id)),Qr>Kr.length&&jsxRuntimeExports.jsxs("p",{className:"text-center text-xs text-muted-foreground","data-testid":"experiments-truncated",children:["Showing ",Kr.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 Kr of es){if(isNotable(Kr)){$.push(Kr);continue}const Qr=ts.get(Kr.kind)??{kind:Kr.kind,count:0,outcomes:{},totalSeconds:0,slowestSeconds:0};Qr.count+=1,Qr.outcomes[Kr.outcome]=(Qr.outcomes[Kr.outcome]??0)+1;const ja=Kr.durationSeconds??0;Qr.totalSeconds+=ja,Qr.slowestSeconds=Math.max(Qr.slowestSeconds,ja),ts.set(Kr.kind,Qr)}const is=[...ts.values()].sort((Kr,Qr)=>Qr.count-Kr.count);return{notable:$,routine:is,routineCount:is.reduce((Kr,Qr)=>Kr+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:Kr,running:Qr,queued:ja,engineBlocked:Ca}=es;return ts?{tone:"critical",text:"A job is claimed but its lease has expired — the worker took work and stopped."}:$?Ca>0?{tone:"critical",text:(Ca===1?"1 job needs":`${Ca} 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.`}:Kr>0?{tone:"warn",text:`${Kr} job${Kr===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 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}){const[$,ts]=reactExports.useState(!1),{notable:is,routine:Kr,routineCount:Qr}=partitionFinished(es.recent),ja=es.running.length===0&&es.queued.length===0;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",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",children:["last ",es.windowHours,"h",es.recentTotal>es.recent.length&&` · ${es.recent.length} of ${es.recentTotal}`]})]})}),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:ja&&!es.worker.present?"No worker connected, so nothing has run.":`No jobs finished in the last ${es.windowHours}h.`}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[is.length>0?jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:is.map(Ca=>jsxRuntimeExports.jsx(FinishedRow,{job:Ca},Ca.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."}),Qr>0&&jsxRuntimeExports.jsxs("div",{className:"mt-2 border-t border-border pt-2",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>ts(Ca=>!Ca),className:"flex min-h-11 w-full cursor-pointer items-center justify-between gap-2 text-xs text-muted-foreground hover:text-foreground","aria-expanded":$,"data-testid":"toggle-routine",children:[jsxRuntimeExports.jsxs("span",{children:[Qr," routine job",Qr===1?"":"s"," across ",Kr.length," ","kind",Kr.length===1?"":"s"]}),$?jsxRuntimeExports.jsx(ChevronDown,{className:"h-3 w-3 shrink-0"}):jsxRuntimeExports.jsx(ChevronRight,{className:"h-3 w-3 shrink-0"})]}),$&&jsxRuntimeExports.jsx("div",{className:"divide-y divide-border pt-1",children:Kr.map(Ca=>jsxRuntimeExports.jsx(RoutineRow,{group:Ca},Ca.kind))})]})]})})]})}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-status"]}),es.invalidateQueries({queryKey:["promotion"]})}})}function useRunLoopNow(){const es=useQueryClient();return useMutation({mutationFn:()=>apiPost("/api/loop/run-now",{}),onSuccess:()=>{es.invalidateQueries({queryKey:["loop-status"]})}})}function useLoopStatus(){return useQuery({queryKey:["loop-status"],queryFn:()=>apiGet("/api/loop/status"),refetchInterval:es=>{var $;return((($=es.state.data)==null?void 0:$.running.length)??0)>0?5e3:3e4}})}function ProvenanceBlock(){const{data:es}=useProvenanceImpact();return!es||es.groups.length===0?null:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-3",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})]})]})}const MAX_LINES=4e3,toLines=es=>es===""?[]:es.split(`
145
+ `);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 Kr=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--)Kr[Aa][Oa]=ts[Aa]===is[Oa]?Kr[Aa+1][Oa+1]+1:Math.max(Kr[Aa+1][Oa],Kr[Aa][Oa+1]);const Qr=[];let ja=0,Ca=0;for(;ja<ts.length&&Ca<is.length;)ts[ja]===is[Ca]?(Qr.push({op:"same",text:ts[ja],oldLine:ja+1,newLine:Ca+1}),ja++,Ca++):Kr[ja+1][Ca]>=Kr[ja][Ca+1]?(Qr.push({op:"remove",text:ts[ja],oldLine:ja+1,newLine:null}),ja++):(Qr.push({op:"add",text:is[Ca],oldLine:null,newLine:Ca+1}),Ca++);for(;ja<ts.length;)Qr.push({op:"remove",text:ts[ja],oldLine:++ja,newLine:null});for(;Ca<is.length;)Qr.push({op:"add",text:is[Ca],oldLine:null,newLine:++Ca});return Qr}function toHunks(es,$=3){const ts=new Set;es.forEach((Ca,Aa)=>{if(Ca.op!=="same")for(let Oa=Math.max(0,Aa-$);Oa<=Math.min(es.length-1,Aa+$);Oa++)ts.add(Oa)});const is=[];let Kr=[],Qr=0,ja=0;return es.forEach((Ca,Aa)=>{ts.has(Aa)?(Kr.length===0&&(Qr=ja,ja=0),Kr.push(Ca)):(Kr.length>0&&(is.push({lines:Kr,skippedBefore:Qr}),Kr=[]),ja++)}),Kr.length>0&&is.push({lines:Kr,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 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(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),{data:is,isLoading:Kr,isError:Qr}=usePromotionDetail(es,$),ja=useApplyPromotion(),Ca=is?lineDiff(is.fromContent,is.toContent):[],Aa=is?toHunks(Ca):[],Oa=diffStat(Ca);return jsxRuntimeExports.jsxs("div",{className:"pt-2",children:[jsxRuntimeExports.jsx("button",{type:"button",onClick:()=>ts(Ia=>!Ia),className:"inline-flex min-h-11 cursor-pointer items-center text-xs text-teal-400 hover:underline","data-testid":"toggle-pending-diff",children:$?"Hide the diff":"Show what it would change →"}),$&&jsxRuntimeExports.jsxs("div",{className:"pt-2","data-testid":"pending-diff",children:[Kr&&jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}),Qr&&jsxRuntimeExports.jsx("p",{className:"text-xs text-amber-400/90",children:"Could not load the proposed change."}),is&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[is.proposalRationale&&jsxRuntimeExports.jsx("p",{className:"pb-2 text-xs text-muted-foreground",children:is.proposalRationale}),jsxRuntimeExports.jsxs("p",{className:"pb-1 font-mono text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs("span",{className:"text-teal-400",children:["+",Oa.added]})," ",jsxRuntimeExports.jsxs("span",{className:"text-amber-400",children:["−",Oa.removed]})," lines"]}),jsxRuntimeExports.jsx("div",{className:"max-h-96 overflow-auto rounded border border-border bg-background/50",children:jsxRuntimeExports.jsx("pre",{className:"w-max min-w-full font-mono text-xs leading-relaxed",children:Aa.map((Ia,Da)=>jsxRuntimeExports.jsxs("div",{children:[Ia.skippedBefore>0&&jsxRuntimeExports.jsxs("div",{className:"bg-muted/30 px-2 py-0.5 text-muted-foreground",children:["… ",Ia.skippedBefore," unchanged line",Ia.skippedBefore===1?"":"s"]}),Ia.lines.map((Ba,Ma)=>jsxRuntimeExports.jsxs("div",{className:cn$1("px-2",Ba.op==="add"&&"bg-teal-400/10 text-teal-300",Ba.op==="remove"&&"bg-amber-400/10 text-amber-300",Ba.op==="same"&&"text-muted-foreground"),children:[jsxRuntimeExports.jsx("span",{className:"select-none pr-2 opacity-50",children:Ba.op==="add"?"+":Ba.op==="remove"?"−":" "}),Ba.text||" "]},Ma))]},Da))})}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3 pt-2",children:[jsxRuntimeExports.jsx("button",{type:"button",disabled:ja.isPending||ja.isSuccess,onClick:()=>ja.mutate(es),className:cn$1("rounded border px-3 py-1 text-xs",ja.isSuccess?"border-teal-400/40 text-teal-400":"cursor-pointer border-teal-400/40 text-teal-400 hover:bg-teal-400/10",ja.isPending&&"opacity-60"),"data-testid":"apply-promotion",children:ja.isSuccess?"Applied":ja.isPending?"Applying…":"Apply this change"}),ja.isError&&jsxRuntimeExports.jsx("span",{className:"text-xs text-amber-400/90","data-testid":"apply-error",children:ja.error instanceof Error?ja.error.message:"Could not apply this change."})]})]})]})]})}function Kpi({value:es,of:$,label:ts,detail:is,good:Kr,testId:Qr}){return jsxRuntimeExports.jsxs("div",{className:"min-w-0 px-3 py-2",children:[jsxRuntimeExports.jsxs("p",{className:"flex items-baseline gap-1",children:[jsxRuntimeExports.jsx("span",{className:cn$1("text-2xl font-semibold tabular-nums",Kr?"text-teal-400":"text-muted-foreground"),"data-testid":Qr,children:es}),$!=null&&jsxRuntimeExports.jsxs("span",{className:"text-xs tabular-nums text-muted-foreground",children:["/ ",$]})]}),jsxRuntimeExports.jsx("p",{className:"truncate text-xs text-muted-foreground",children:ts}),is&&jsxRuntimeExports.jsx("p",{className:"truncate font-mono text-[11px] text-muted-foreground/80","data-testid":Qr?`${Qr}-detail`:void 0,children:is})]})}function KpiStrip({status:es}){const{changes:$,counts:ts,insights:is}=es,{applied:Kr,decisions:Qr,byDecision:ja,suggestionsAccepted:Ca,suggestionsProposed:Aa}=$,Oa=Kr===0&&Ca===0;return jsxRuntimeExports.jsx(Card,{className:cn$1(Oa&&Qr+Aa>0&&"border-amber-400/40"),"data-testid":"changes-headline",children:jsxRuntimeExports.jsxs(CardContent,{className:"p-0",children:[jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 divide-x divide-y divide-border sm:grid-cols-3 sm:divide-y-0 lg:grid-cols-5",children:[jsxRuntimeExports.jsx(Kpi,{value:Kr,of:Qr||void 0,label:"edits applied",detail:Qr>0?`${ja.promote}P · ${ja.revert}R · ${ja.refuse}X`:void 0,good:Kr>0,testId:"changes-applied"}),jsxRuntimeExports.jsx(Kpi,{value:Ca,of:Aa||void 0,label:"suggestions accepted",good:Ca>0,testId:"changes-accepted"}),jsxRuntimeExports.jsx(Kpi,{value:Qr,label:"decisions recorded",good:Qr>0}),jsxRuntimeExports.jsx(Kpi,{value:ts.experimentsRunning,label:"experiments running",good:ts.experimentsRunning>0}),jsxRuntimeExports.jsx(Kpi,{value:is.repeated,of:is.distinct||void 0,label:"insights repeated",detail:is.entries>0?`${is.entries} entries`:void 0,good:is.repeated>0})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 border-t border-border px-3 py-2 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.'}),Oa&&Qr+Aa>0&&jsxRuntimeExports.jsx("span",{className:"text-amber-400/90","data-testid":"never-acted",children:"· Measuring, not acting: nothing has ever been applied or accepted."})]})]})})}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 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({workerPresent:es.worker.present,leaseUnhealthy:es.running.some(ts=>!ts.leaseHealthy),readyToApply:es.changes.readyToApply,failedRecently:es.recent.filter(ts=>ts.outcome==="failed").length,running:es.running.length,queued:es.queued.length,engineBlocked:(es.verdict.engineBlocked??[]).reduce((ts,is)=>ts+is.count,0)});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{data:es,isLoading:$,isError:ts}=useLoopStatus();return $?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"})]}):ts||!es?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."]})})}):(es.running.length===0&&es.queued.length,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:es}),jsxRuntimeExports.jsx(StatusBanner,{status:es})]})]}),jsxRuntimeExports.jsx(ReadyToApplyCallout,{changes:es.changes}),jsxRuntimeExports.jsx(KpiStrip,{status:es}),jsxRuntimeExports.jsxs("div",{className:"grid gap-4 lg:grid-cols-5",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-4 lg:col-span-3",children:[(es.running.length>0||es.queued.length>0)&&jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",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(is=>jsxRuntimeExports.jsx(RunningRow,{job:is},is.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(is=>jsxRuntimeExports.jsx(QueuedRow,{job:is},is.id))})]})]})]}),jsxRuntimeExports.jsx(FinishedList,{status:es})]}),jsxRuntimeExports.jsxs("div",{className:"min-w-0 space-y-4 lg:col-span-2",children:[jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"text-base",children:["Proposed changes",es.proposalTotal>es.proposals.length&&jsxRuntimeExports.jsxs("span",{className:"pl-2 font-normal text-muted-foreground",children:["showing ",es.proposals.length," of ",es.proposalTotal]})]})}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-4",children:[es.proposals.length>0?jsxRuntimeExports.jsx("div",{className:"divide-y divide-border",children:es.proposals.map(is=>jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-3 py-1.5","data-testid":"proposal",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0",children:[jsxRuntimeExports.jsxs("p",{className:"truncate text-sm",title:is.targetName??"",children:[is.targetName?is.targetName.split("/").pop():"(target deleted)",is.targetName&&jsxRuntimeExports.jsx("span",{className:"pl-1.5 text-xs text-muted-foreground",children:is.targetName.split("/").slice(-3,-1).join("/")})]}),jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-muted-foreground",children:[is.decision," · ",is.effectClass," · via ",is.proposalSource]})]}),jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("shrink-0",is.applied?"border-teal-400/40 text-teal-400":"border-muted-foreground/40 text-muted-foreground"),"data-testid":"proposal-applied",children:is.applied?"applied":"not applied"})]},is.id))}):jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No changes proposed yet."}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap gap-4 border-t border-border pt-3 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsxs(Link,{to:"/experiments",className:"hover:text-foreground",children:[es.counts.experimentsRunning," experiment",es.counts.experimentsRunning===1?"":"s"," running"]}),jsxRuntimeExports.jsxs(Link,{to:"/suggestions",className:"hover:text-foreground",children:["suggestions:"," ",Object.entries(es.counts.suggestions).map(([is,Kr])=>`${Kr} ${is}`).join(" · ")||"none"]})]}),jsxRuntimeExports.jsxs("div",{className:"border-t border-border pt-3","data-testid":"insights-memory",children:[jsxRuntimeExports.jsx("p",{className:"pb-1 text-xs uppercase tracking-wide text-muted-foreground",children:"Insights memory"}),jsxRuntimeExports.jsxs("p",{className:"font-mono text-xs text-muted-foreground",children:[es.insights.entries," entries · ",es.insights.distinct," distinct ·"," ",es.insights.repeated," repeated · ",es.insights.dismissed," dismissed · max seen ×",es.insights.maxTimesGenerated]}),es.insights.entries>0&&es.insights.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.jsx(ProvenanceBlock,{})]})]})]}))}function ToggleSwitch({checked:es,label:$,onToggle:ts,disabled:is,danger:Kr,testId:Qr}){return jsxRuntimeExports.jsx("button",{type:"button",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?Kr?"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",Kr?"bg-amber-400":"bg-teal-400"):"left-0.5 bg-muted-foreground")})})})}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:$,children:ts}){return jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-3",children:[jsxRuntimeExports.jsxs("span",{className:"min-w-0 text-xs",children:[es,$&&jsxRuntimeExports.jsx("span",{className:"block text-[11px] text-muted-foreground",children:$})]}),ts]})}function TargetRow({target:es,minPairs:$,maxPairs:ts,onPatch:is,pending:Kr}){const{settings:Qr,name:ja}=es,Ca=ja.split("/").pop()||ja,Aa=ja.slice(0,Math.max(0,ja.length-Ca.length-1));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:Ca}),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-2 sm:grid-cols-2 lg:grid-cols-3",children:[jsxRuntimeExports.jsx(Row,{label:"Enrolled",hint:"measure this instruction",children:jsxRuntimeExports.jsx(ToggleSwitch,{checked:Qr.enabled,label:`Enrol ${Ca} in evolution`,testId:"evolution-enabled",disabled:Kr,onToggle:()=>is({enabled:!Qr.enabled})})}),jsxRuntimeExports.jsx(Row,{label:"May rewrite",hint:"act on a verdict, not just record it",children:jsxRuntimeExports.jsx(ToggleSwitch,{checked:Qr.apply,danger:!0,label:`Allow evolution to rewrite ${Ca}`,testId:"evolution-apply",disabled:Kr,onToggle:()=>is({apply:!Qr.apply})})}),jsxRuntimeExports.jsx(Row,{label:"Paused",hint:"stop spending, keep the opt-in",children:jsxRuntimeExports.jsx(ToggleSwitch,{checked:Qr.pausedBy==="target",label:`Pause evolution for ${Ca}`,testId:"evolution-paused",disabled:Kr||Qr.pausedBy==="account",onToggle:()=>is({paused:Qr.pausedBy!=="target"})})}),jsxRuntimeExports.jsx(Row,{label:"Skip auto-enrolment",hint:"never picked up by the rule",children:jsxRuntimeExports.jsx(ToggleSwitch,{checked:Qr.optOut,label:`Exclude ${Ca} from automatic enrolment`,testId:"evolution-optout",disabled:Kr,onToggle:()=>is({optOut:!Qr.optOut})})}),jsxRuntimeExports.jsx(Row,{label:"Pool across nights",hint:"one candidate, evidence accumulated",children:jsxRuntimeExports.jsx(ToggleSwitch,{checked:Qr.accumulate,label:`Accumulate evidence across nights for ${Ca}`,testId:"evolution-accumulate",disabled:Kr,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:Kr,"data-testid":"evolution-pairs",onBlur:Oa=>{const Ia=Number(Oa.currentTarget.value);Number.isFinite(Ia)&&Ia!==Qr.pairs&&is({pairs:Ia})},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(),Kr=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:Kr.isPending,onToggle:()=>Kr.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:Ca=>is.mutate({evalTargetId:ja.evalTargetId,...Ca})},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||Kr.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."]})]})})]})}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.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>",`
147
147
  `,"rulemetric suggestions undo <instruction-id>"]})]})]})})]}),jsxRuntimeExports.jsx(EvolutionCard,{})]})}function tierFor(es){return es>=95?"red":es>=80?"orange":es>=60?"yellow":"green"}const TIER_COLOR={green:"stroke-teal-500",yellow:"stroke-yellow-500",orange:"stroke-orange-500",red:"stroke-red-500"},TIER_TEXT={green:"text-teal-600",yellow:"text-yellow-600",orange:"text-orange-600",red:"text-red-600"};function formatCountdown(es,$){const ts=es.getTime()-$.getTime();if(ts<=0)return"resetting now";const is=Math.floor(ts/6e4),Kr=Math.floor(is/1440),Qr=Math.floor((is-Kr*60*24)/60),ja=is-Kr*60*24-Qr*60;return Kr>0?`resets in ${Kr}d ${Qr}h`:Qr>0?`resets in ${Qr}h ${ja}m`:`resets in ${ja}m`}function formatObservedAt(es,$){const ts=$.getTime()-es.getTime();if(ts<6e4)return{label:"live",fresh:!0};const is=Math.floor(ts/6e4);return is<60?{label:`synced ${is}m ago`,fresh:!1}:{label:`synced ${Math.floor(is/60)}h ago`,fresh:!1}}function Ring({pct:es,tier:$}){const is=2*Math.PI*30,Qr=Math.max(0,Math.min(100,es))/100*is;return jsxRuntimeExports.jsxs("svg",{width:80,height:80,viewBox:"0 0 80 80",className:"-rotate-90",children:[jsxRuntimeExports.jsx("circle",{cx:40,cy:40,r:30,strokeWidth:8,fill:"none",className:"stroke-muted"}),jsxRuntimeExports.jsx("circle",{cx:40,cy:40,r:30,strokeWidth:8,fill:"none",strokeLinecap:"round",strokeDasharray:`${Qr} ${is}`,className:cn$1("transition-all duration-500",TIER_COLOR[$])})]})}function LimitRing(es){const{label:$,usedPercentage:ts,resetsAt:is,observedAt:Kr,inferredCap:Qr,unit:ja,confidenceBandPct:Ca,capQualifier:Aa="inferred cap",providerReported:Oa=!1}=es,[Ia,Da]=reactExports.useState(()=>new Date);reactExports.useEffect(()=>{const Va=setInterval(()=>Da(new Date),6e4);return()=>clearInterval(Va)},[]);const Ba=ts!=null,Ma=ts??0,qa=tierFor(Ma),Fa=Ma>=100?{icon:Ban,text:"hit",color:"text-red-600"}:Ma>=95?{icon:TriangleAlert,text:"imminent",color:"text-red-600"}:Ma>=80?{icon:TriangleAlert,text:"approaching",color:"text-yellow-600"}:null,Ka=is?formatCountdown(new Date(is),Ia):"—",Ha=Kr?formatObservedAt(new Date(Kr),Ia):null,Qa=Ba&&Qr!=null?Math.round(Ma/100*Qr):null;return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-4 rounded-lg border border-border bg-card p-4",children:[jsxRuntimeExports.jsx(Ring,{pct:Ma,tier:qa}),jsxRuntimeExports.jsxs("div",{className:"flex-1 min-w-0",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-semibold",children:$}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[jsxRuntimeExports.jsx("span",{className:cn$1("font-mono",TIER_TEXT[qa]),children:Ba?`${Math.round(Ma)}%`:"—"}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:Ka}),Ha?jsxRuntimeExports.jsx("span",{className:cn$1("text-xs",Ha.fresh?"text-teal-600":"text-muted-foreground"),children:Ha.fresh?"✓ live":Ha.label}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"? unknown"})]})]}),jsxRuntimeExports.jsxs("div",{className:"mt-1 flex items-center justify-between gap-2 text-xs text-muted-foreground",children:[jsxRuntimeExports.jsx(TooltipProvider,{children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:Oa?jsxRuntimeExports.jsx("span",{className:"cursor-help font-mono",children:"Provider-reported quota window percentage"}):jsxRuntimeExports.jsxs("span",{className:"cursor-help font-mono",children:["≈"," ",Qa??"?"," ","/ ",Qr??"?"," ",ja," (",Aa," · ±",Ca,"%)"]})}),jsxRuntimeExports.jsx(TooltipContent,{className:"max-w-xs",children:jsxRuntimeExports.jsx("p",{className:"text-xs",children:Oa?"Reported directly by the provider's rate-limit feed — the percentage is authoritative, not an estimate.":"Estimate based on Anthropic-published ranges. Actuals vary per user."})})]})}),Fa?jsxRuntimeExports.jsxs("span",{className:cn$1("flex items-center gap-1 font-mono",Fa.color),children:[jsxRuntimeExports.jsx(Fa.icon,{className:"h-3 w-3"}),Fa.text]}):null]}),Ba?null:jsxRuntimeExports.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:Oa?"no observation yet — run this tool through the proxy":"~ estimated · no observation yet"})]})]})}const SOURCE_LABEL="Live usage · all tracked tools",COST_POLL_MS=3e4,RATE_LIMIT_RINGS=[{key:"five_hour",label:"5-hour window",unit:"msgs"},{key:"seven_day",label:"7-day (Sonnet tier)",unit:"hrs"},{key:"seven_day_opus",label:"7-day (Opus tier)",unit:"hrs"}],CODEX_RINGS=[{key:"five_hour",label:"Codex 5-hour window"},{key:"seven_day",label:"Codex 7-day window"}],PLAN_LABELS={max_20x:"Max-20x",max_5x:"Max-5x",pro:"Pro"};function planLabel(es){return PLAN_LABELS[es]??es}function startOfMonthIso(){const es=new Date;return new Date(es.getFullYear(),es.getMonth(),1).toISOString()}function UsagePage(){var el,tl,il,rl,dl,xl,nl,ll,fl,Tl,cl,pl,jl,Nl,zl,Zl,Pl,Il,ql,Fl;const es=useCurrentLimits(),$=useCurrentLimits("codex"),ts=useInferredCaps(),is=startOfMonthIso(),Kr=useComputedInsights(void 0,void 0,{since:is,refetchIntervalMs:COST_POLL_MS}),Qr=((el=es.data)==null?void 0:el.five_hour)??null,ja=((tl=es.data)==null?void 0:tl.seven_day)??null,Ca=((il=es.data)==null?void 0:il.seven_day_opus)??null,Aa=((rl=$.data)==null?void 0:rl.five_hour)??null,Oa=((dl=$.data)==null?void 0:dl.seven_day)??null,Ia={five_hour:Aa,seven_day:Oa},Da=!!(Aa||Oa),Ba=((xl=ts.data)==null?void 0:xl.five_hour_percent.inferred_cap)??null,Ma=((nl=ts.data)==null?void 0:nl.five_hour_percent.confidence_band_pct)??20,qa=((ll=ts.data)==null?void 0:ll.seven_day_percent.inferred_cap)??null,Fa=((fl=ts.data)==null?void 0:fl.seven_day_percent.confidence_band_pct)??20,Ka=((Tl=ts.data)==null?void 0:Tl.seven_day_opus_percent.inferred_cap)??null,Ha=((cl=ts.data)==null?void 0:cl.seven_day_opus_percent.confidence_band_pct)??20,Qa=ts.data?`${planLabel(ts.data.plan)}${ts.data.assumed?" est.":""}`:"inferred cap",Va=es.isLoading||ts.isLoading,Ya={five_hour:{obs:Qr,cap:Ba,band:Ma},seven_day:{obs:ja,cap:qa,band:Fa},seven_day_opus:{obs:Ca,cap:Ka,band:Ha}},Ja=new Date(is).toLocaleString(void 0,{month:"long",year:"numeric"});return jsxRuntimeExports.jsxs("div",{className:"max-w-3xl mx-auto space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-3",children:[jsxRuntimeExports.jsx(Gauge,{className:"h-6 w-6 text-primary"}),jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h1",{className:"font-mono text-xl font-semibold",children:"Usage"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:SOURCE_LABEL})]})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-4",children:[jsxRuntimeExports.jsx("h2",{className:"font-mono text-xs uppercase tracking-wide text-muted-foreground",children:"Rate limits"}),Va?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"})]}):es.isError?jsxRuntimeExports.jsxs("div",{role:"status",className:"flex items-center gap-2 rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 flex-shrink-0"}),jsxRuntimeExports.jsxs("span",{children:["Couldn't load rate limits",es.error instanceof Error?`: ${es.error.message}`:"",". Retrying…"]})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono text-sm font-semibold",children:"Claude Code"}),RATE_LIMIT_RINGS.map(nu=>{var cu,Ol,Ml;const Gl=Ya[nu.key];return jsxRuntimeExports.jsx(LimitRing,{label:nu.label,usedPercentage:((cu=Gl.obs)==null?void 0:cu.used_percentage)??null,resetsAt:((Ol=Gl.obs)==null?void 0:Ol.resets_at)??null,observedAt:((Ml=Gl.obs)==null?void 0:Ml.observed_at)??null,inferredCap:Gl.cap,unit:nu.unit,confidenceBandPct:Gl.band,capQualifier:Qa},nu.key)})]}),Da?jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx("h3",{className:"font-mono text-sm font-semibold",children:"Codex"}),CODEX_RINGS.map(nu=>{const Gl=Ia[nu.key];return jsxRuntimeExports.jsx(LimitRing,{label:nu.label,usedPercentage:(Gl==null?void 0:Gl.used_percentage)??null,resetsAt:(Gl==null?void 0:Gl.resets_at)??null,observedAt:(Gl==null?void 0:Gl.observed_at)??null,inferredCap:null,unit:"",confidenceBandPct:0,providerReported:!0},nu.key)})]}):null]}),jsxRuntimeExports.jsxs("section",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("h2",{className:"font-mono text-xs uppercase tracking-wide text-muted-foreground",children:["Estimated cost · ",Ja]}),Kr.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-48 w-full"}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(CostBreakdownCard,{totalUsd:((pl=Kr.data)==null?void 0:pl.estimated_cost_usd)??0,breakdown:(jl=Kr.data)==null?void 0:jl.estimated_cost_breakdown,inputTokens:((Nl=Kr.data)==null?void 0:Nl.total_input_tokens)??0,outputTokens:((zl=Kr.data)==null?void 0:zl.total_output_tokens)??0,cacheReadTokens:((Zl=Kr.data)==null?void 0:Zl.total_cache_read_tokens)??0,cacheWriteTokens:((Pl=Kr.data)==null?void 0:Pl.total_cache_write_tokens)??0,byModel:(Il=Kr.data)==null?void 0:Il.estimated_cost_by_model,byTool:(ql=Kr.data)==null?void 0:ql.estimated_cost_by_tool}),(Fl=Kr.data)!=null&&Fl.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 flex-shrink-0"}),"Showing your 500 most recent sessions this month — older sessions in the window aren't counted, so this is a lower bound."]}):null]})]})]})}function AdminOverviewPage(){var Aa,Oa,Ia,Da,Ba,Ma;const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",ts=useQuery({queryKey:["org-detail",$],queryFn:()=>getOrg($),enabled:!!$}),is=useQuery({queryKey:["org-activity",$,"7d"],queryFn:()=>getOrgActivity($,"7d"),enabled:!!$}),Kr=(Aa=ts.data)==null?void 0:Aa.members.length,Qr=(Oa=ts.data)==null?void 0:Oa.teams.length,ja=(Ia=is.data)==null?void 0:Ia.sessionCount,Ca=((Ma=(Ba=(Da=is.data)==null?void 0:Da.topTools)==null?void 0:Ba[0])==null?void 0:Ma.tool)??null;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx(Building2,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{children:"Organization admin"})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight mt-1",children:(es==null?void 0:es.name)??"—"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx("code",{className:"text-xs",children:es==null?void 0:es.slug}),es&&jsxRuntimeExports.jsxs("span",{className:"ml-2 capitalize",children:["· you are ",es.role]})]})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/admin/members",children:"Members"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/admin/members/invitations",children:"Pending invites"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/admin/settings",children:"Settings"})})]})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Users,{className:"h-4 w-4"}),label:"Members",value:Kr,loading:ts.isLoading,error:!!ts.error}),jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Layers,{className:"h-4 w-4"}),label:"Teams",value:Qr,loading:ts.isLoading,error:!!ts.error}),jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4"}),label:"Sessions (7d)",value:ja,loading:is.isLoading,error:!!is.error}),jsxRuntimeExports.jsx(StatCard$1,{icon:jsxRuntimeExports.jsx(Wrench,{className:"h-4 w-4"}),label:"Top tool",value:Ca??"—",loading:is.isLoading,error:!!is.error})]})]})}function StatCard$1({icon:es,label:$,value:ts,loading:is,error:Kr}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[es,$]})}),jsxRuntimeExports.jsx(CardContent,{children:is?jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"}):Kr?jsxRuntimeExports.jsx("span",{className:"text-sm text-destructive",children:"failed to load"}):jsxRuntimeExports.jsx("span",{className:"text-3xl font-mono font-semibold tabular-nums",children:ts??"—"})})]})}const NO_TEAM="__none";function InviteDialog({open:es,onOpenChange:$,orgSlug:ts}){const is=useQueryClient(),[Kr,Qr]=reactExports.useState(""),[ja,Ca]=reactExports.useState("member"),[Aa,Oa]=reactExports.useState(NO_TEAM),[Ia,Da]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Qr(""),Ca("member"),Oa(NO_TEAM),Da(null))},[es]);const Ba=useQuery({queryKey:["org-teams",ts],queryFn:()=>listTeams(ts),enabled:es&&!!ts}),Ma=useMutation({mutationFn:Fa=>createInvitation(ts,Fa),onSuccess:Fa=>{Fa.emailSent?ue$1.success(`Invitation sent to ${Fa.email}`):ue$1.warning("Invite created, but the email could not be sent",{description:Fa.emailError?`${Fa.emailError} — share the invite link directly.`:"Share the invite link directly.",duration:3e4,action:{label:"Copy invite link",onClick:()=>{var Ka;(Ka=navigator.clipboard)==null||Ka.writeText(Fa.acceptUrl).then(()=>ue$1.success("Invite link copied")).catch(()=>ue$1.error("Couldn't copy — the link is in the invite row"))}}}),is.invalidateQueries({queryKey:["org-invitations",ts]}),$(!1)},onError:Fa=>{if(Fa instanceof ApiError){if(Fa.code==="INVITE_ALREADY_PENDING"){Da("There's already a pending invitation for this email. Resend it from the Pending Invites page instead.");return}if(Fa.code==="INVALID_TEAM"){Da("That team no longer exists in this organization. Refresh and try again.");return}ue$1.error(Fa.message);return}ue$1.error(Fa instanceof Error?Fa.message:"Failed to send invite")}});function qa(Fa){Fa.preventDefault(),Da(null);const Ka=Kr.trim();if(!Ka){Da("Email is required.");return}if(!/^\S+@\S+\.\S+$/.test(Ka)){Da("Enter a valid email address.");return}Ma.mutate({email:Ka,role:ja,...Aa!==NO_TEAM?{teamId:Aa}:{}})}return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Invite a member"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Send an invitation email. The recipient gets a link that's valid for 7 days."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:qa,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"invite-email",type:"email",autoComplete:"off",value:Kr,onChange:Fa=>Qr(Fa.target.value),placeholder:"teammate@example.com",required:!0,disabled:Ma.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-role",children:"Role"}),jsxRuntimeExports.jsxs(Select,{value:ja,onValueChange:Fa=>Ca(Fa),disabled:Ma.isPending,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"invite-role",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"Member"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"Admin"})]})]}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Admins can invite, remove, and re-role other members. Members have read-only access to admin pages."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-team",children:"Team (optional)"}),jsxRuntimeExports.jsxs(Select,{value:Aa,onValueChange:Oa,disabled:Ma.isPending||Ba.isLoading,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"invite-team",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"No team"})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:NO_TEAM,children:"No team"}),(Ba.data??[]).map(Fa=>jsxRuntimeExports.jsx(SelectItem,{value:Fa.id,children:Fa.name},Fa.id))]})]}),Ba.error&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-destructive",children:["Couldn't load teams: ",Ba.error.message]})]}),Ia&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Ia}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>$(!1),disabled:Ma.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ma.isPending,className:"cursor-pointer",children:Ma.isPending?"Sending…":"Send invitation"})]})]})]})})}function AdminMembersPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",ts=useQueryClient(),[is,Kr]=reactExports.useState(!1),[Qr,ja]=reactExports.useState(null),Ca=useQuery({queryKey:["org-members",$],queryFn:()=>listMembers($),enabled:!!$}),Aa=useMutation({mutationFn:({userId:Da,role:Ba})=>updateMemberRole($,Da,Ba),onSuccess:()=>{ue$1.success("Role updated"),ts.invalidateQueries({queryKey:["org-members",$]}),ts.invalidateQueries({queryKey:["orgs"]})},onError:Da=>{Da instanceof ApiError&&Da.code==="LAST_OWNER"?ue$1.error("Cannot demote the last owner."):ue$1.error(Da instanceof Error?Da.message:"Failed to update role"),ts.invalidateQueries({queryKey:["org-members",$]})}}),Oa=useMutation({mutationFn:Da=>removeMember($,Da),onSuccess:()=>{ue$1.success("Member removed"),ts.invalidateQueries({queryKey:["org-members",$]}),ts.invalidateQueries({queryKey:["orgs"]}),ja(null)},onError:Da=>{Da instanceof ApiError&&Da.code==="LAST_OWNER"?ue$1.error("Cannot remove the last owner."):ue$1.error(Da instanceof Error?Da.message:"Failed to remove member")}}),Ia=Ca.data??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Members"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["Manage who has access to"," ",jsxRuntimeExports.jsx("strong",{className:"font-medium",children:(es==null?void 0:es.name)??"—"}),"."]})]}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/admin/members/invitations",children:[jsxRuntimeExports.jsx(Mail,{className:"mr-2 h-4 w-4"}),"Pending invites"]})}),jsxRuntimeExports.jsxs(Button,{onClick:()=>Kr(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(UserPlus,{className:"mr-2 h-4 w-4"}),"Invite"]})]})]}),Ca.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load members: ",Ca.error.message]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{className:"w-12"}),jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{children:"Display name"}),jsxRuntimeExports.jsx(TableHead,{children:"Role"}),jsxRuntimeExports.jsx(TableHead,{children:"Teams"}),jsxRuntimeExports.jsx(TableHead,{children:"Last active"}),jsxRuntimeExports.jsx(TableHead,{className:"w-12"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Ca.isLoading?jsxRuntimeExports.jsx(SkeletonRows$2,{}):Ia.length===0?jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No members yet."})}):Ia.map(Da=>{var Ba;return jsxRuntimeExports.jsx(MemberRow,{member:Da,pending:Aa.isPending&&((Ba=Aa.variables)==null?void 0:Ba.userId)===Da.userId,onRoleChange:Ma=>Aa.mutate({userId:Da.userId,role:Ma}),onRemove:()=>ja(Da)},Da.userId)})})]})}),jsxRuntimeExports.jsx(InviteDialog,{open:is,onOpenChange:Kr,orgSlug:$}),jsxRuntimeExports.jsx(RemoveMemberDialog$1,{member:Qr,onCancel:()=>ja(null),onConfirm:()=>Qr&&Oa.mutate(Qr.userId),pending:Oa.isPending})]})}function MemberRow({member:es,pending:$,onRoleChange:ts,onRemove:is}){const Kr=reactExports.useMemo(()=>(es.email??es.displayName??"?").slice(0,1).toUpperCase(),[es.email,es.displayName]);return jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Avatar,{size:"sm",children:jsxRuntimeExports.jsx(AvatarFallback,{children:Kr})})}),jsxRuntimeExports.jsx(TableCell,{className:"font-medium",children:es.email??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:es.displayName??"—"}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs(Select,{value:es.role,onValueChange:Qr=>ts(Qr),disabled:$,children:[jsxRuntimeExports.jsx(SelectTrigger,{size:"sm",className:"w-32 capitalize",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"owner",children:"Owner"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"Admin"}),jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"Member"})]})]})}),jsxRuntimeExports.jsx(TableCell,{children:es.teams.length===0?jsxRuntimeExports.jsx("span",{className:"text-muted-foreground text-xs",children:"—"}):jsxRuntimeExports.jsx("div",{className:"flex flex-wrap gap-1",children:es.teams.map(Qr=>jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"text-xs",children:Qr.name},Qr.id))})}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground text-sm",children:es.lastActiveAt?formatDistanceToNow(es.lastActiveAt):"never"}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"h-8 w-8 cursor-pointer",children:[jsxRuntimeExports.jsx(Ellipsis,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Member actions"})]})}),jsxRuntimeExports.jsx(DropdownMenuContent,{align:"end",children:jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:is,className:"text-destructive focus:text-destructive cursor-pointer",children:"Remove from organization"})})]})})]})}function SkeletonRows$2(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Array.from({length:4}).map((es,$)=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-6 rounded-full"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-40"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-32"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-20"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-8"})})]},$))})}function RemoveMemberDialog$1({member:es,onCancel:$,onConfirm:ts,pending:is}){return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:Kr=>{Kr||$()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Remove member?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[(es==null?void 0:es.email)??"This member"," will lose access to the organization. They can be re-invited later."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:$,disabled:is,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:ts,disabled:is,className:"cursor-pointer",children:is?"Removing…":"Remove"})]})]})})}function AdminInvitationsPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",ts=useQueryClient(),[is,Kr]=reactExports.useState(!1),[Qr,ja]=reactExports.useState(null),Ca=useQuery({queryKey:["org-invitations",$],queryFn:()=>listInvitations($),enabled:!!$}),Aa=useMutation({mutationFn:Da=>resendInvitation($,Da),onSuccess:Da=>{Da.emailSent?ue$1.success(`Resent invitation to ${Da.email}`):ue$1.warning("Invite link refreshed, but the email could not be sent",{description:Da.emailError?`${Da.emailError} — share the invite link directly.`:"Share the invite link directly.",duration:3e4,action:{label:"Copy invite link",onClick:()=>{var Ba;(Ba=navigator.clipboard)==null||Ba.writeText(Da.acceptUrl).then(()=>ue$1.success("Invite link copied")).catch(()=>ue$1.error("Couldn't copy the invite link"))}}}),ts.invalidateQueries({queryKey:["org-invitations",$]})},onError:Da=>ue$1.error(Da instanceof Error?Da.message:"Failed to resend invitation")}),Oa=useMutation({mutationFn:Da=>revokeInvitation($,Da),onSuccess:()=>{ue$1.success("Invitation revoked"),ts.invalidateQueries({queryKey:["org-invitations",$]}),ja(null)},onError:Da=>ue$1.error(Da instanceof Error?Da.message:"Failed to revoke invitation")}),Ia=Ca.data??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"ghost",size:"sm",className:"cursor-pointer mb-2 -ml-2 text-muted-foreground",children:jsxRuntimeExports.jsxs(Link,{to:"/admin/members",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-4 w-4"}),"Back to members"]})}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Pending invitations"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground text-sm",children:"Sent but not yet accepted. Invitations expire 7 days after they're issued or last resent."})]}),jsxRuntimeExports.jsxs(Button,{onClick:()=>Kr(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(UserPlus,{className:"mr-2 h-4 w-4"}),"Invite"]})]}),Ca.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load invitations:"," ",Ca.error.message]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{children:"Role"}),jsxRuntimeExports.jsx(TableHead,{children:"Team"}),jsxRuntimeExports.jsx(TableHead,{children:"Invited by"}),jsxRuntimeExports.jsx(TableHead,{children:"Expires"}),jsxRuntimeExports.jsx(TableHead,{className:"w-48 text-right",children:"Actions"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Ca.isLoading?jsxRuntimeExports.jsx(SkeletonRows$1,{}):Ia.length===0?jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No pending invitations. Send one from the Members tab."})}):Ia.map(Da=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{className:"font-medium",children:Da.email}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"capitalize",children:Da.role})}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:Da.teamName??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:Da.invitedByName??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground text-sm",children:formatDistanceToFuture(Da.expiresAt)}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2",children:[jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",disabled:Aa.isPending&&Aa.variables===Da.id,onClick:()=>Aa.mutate(Da.id),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(RefreshCw,{className:"mr-1 h-3 w-3"}),"Resend"]}),jsxRuntimeExports.jsxs(Button,{variant:"outline",size:"sm",onClick:()=>ja(Da),className:"cursor-pointer text-destructive hover:text-destructive",children:[jsxRuntimeExports.jsx(Trash2,{className:"mr-1 h-3 w-3"}),"Revoke"]})]})})]},Da.id))})]})}),jsxRuntimeExports.jsx(InviteDialog,{open:is,onOpenChange:Kr,orgSlug:$}),jsxRuntimeExports.jsx(Dialog,{open:!!Qr,onOpenChange:Da=>{Da||ja(null)},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Revoke invitation?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[Qr!=null&&Qr.email?`${Qr.email} will no longer be able to accept this invitation.`:"This invitation will be revoked."," ","You can send a new one from the Members tab."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>ja(null),disabled:Oa.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:()=>Qr&&Oa.mutate(Qr.id),disabled:Oa.isPending,className:"cursor-pointer",children:Oa.isPending?"Revoking…":"Revoke"})]})]})})]})}function SkeletonRows$1(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Array.from({length:3}).map((es,$)=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-40"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-20"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"})]})})]},$))})}const SLUG_REGEX$2=/^(?=.{3,40}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;function slugify$1(es){return es.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)}function AdminTeamsPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",[ts,is]=reactExports.useState(!1),[Kr,Qr]=reactExports.useState(null),[ja,Ca]=reactExports.useState(null),Aa=useQuery({queryKey:["org-teams",$],queryFn:()=>listTeams($),enabled:!!$}),Oa=Aa.data??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight",children:"Teams"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["Group members of"," ",jsxRuntimeExports.jsx("strong",{className:"font-medium",children:(es==null?void 0:es.name)??"—"})," ","to scope activity dashboards."]})]}),jsxRuntimeExports.jsxs(Button,{onClick:()=>is(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"New team"]})]}),Aa.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load teams: ",Aa.error.message]}):Aa.isLoading?jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:Array.from({length:4}).map((Ia,Da)=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-20 mt-2"})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})})]},Da))}):Oa.length===0?jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center justify-center rounded-md border border-dashed border-border py-16 text-center",children:[jsxRuntimeExports.jsx(Layers,{className:"h-10 w-10 text-muted-foreground mb-3"}),jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"No teams yet."}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Create one to start grouping members."}),jsxRuntimeExports.jsxs(Button,{onClick:()=>is(!0),className:"cursor-pointer",variant:"outline",children:[jsxRuntimeExports.jsx(Plus,{className:"mr-2 h-4 w-4"}),"Create team"]})]}):jsxRuntimeExports.jsx("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3",children:Oa.map(Ia=>jsxRuntimeExports.jsx(TeamCard,{team:Ia,onRename:()=>Qr(Ia),onDelete:()=>Ca(Ia)},Ia.id))}),jsxRuntimeExports.jsx(CreateTeamDialog,{open:ts,onOpenChange:is,orgSlug:$}),jsxRuntimeExports.jsx(RenameTeamDialog,{team:Kr,orgSlug:$,onClose:()=>Qr(null)}),jsxRuntimeExports.jsx(DeleteTeamDialog,{team:ja,orgSlug:$,onClose:()=>Ca(null)})]})}function TeamCard({team:es,onRename:$,onDelete:ts}){return jsxRuntimeExports.jsxs(Card,{className:"relative",children:[jsxRuntimeExports.jsxs(CardHeader,{className:"flex flex-row items-start justify-between space-y-0",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsx(CardTitle,{className:"truncate",children:jsxRuntimeExports.jsx(Link,{to:`/admin/teams/${encodeURIComponent(es.slug)}`,className:"hover:underline",children:es.name})}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:jsxRuntimeExports.jsx("code",{children:es.slug})})]}),jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"h-8 w-8 cursor-pointer -mr-2 -mt-1",children:[jsxRuntimeExports.jsx(Ellipsis,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Team actions"})]})}),jsxRuntimeExports.jsxs(DropdownMenuContent,{align:"end",children:[jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:$,className:"cursor-pointer",children:"Rename"}),jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:ts,className:"text-destructive focus:text-destructive cursor-pointer",children:"Delete"})]})]})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[jsxRuntimeExports.jsx(Users,{className:"h-4 w-4"}),es.memberCount," ",es.memberCount===1?"member":"members"]})})]})}function CreateTeamDialog({open:es,onOpenChange:$,orgSlug:ts}){const is=useQueryClient(),[Kr,Qr]=reactExports.useState(""),[ja,Ca]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(!1),[Ia,Da]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Qr(""),Ca(""),Oa(!1),Da(null))},[es]);const Ba=useMutation({mutationFn:Fa=>createTeam(ts,Fa),onSuccess:()=>{ue$1.success("Team created"),is.invalidateQueries({queryKey:["org-teams",ts]}),is.invalidateQueries({queryKey:["org-detail",ts]}),$(!1)},onError:Fa=>{if(Fa instanceof ApiError&&Fa.code==="TEAM_SLUG_TAKEN"){Da("That slug is already in use by another team.");return}if(Fa instanceof ApiError&&Fa.code==="VALIDATION_ERROR"){Da("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(Fa instanceof Error?Fa.message:"Failed to create team")}});function Ma(Fa){Qr(Fa),Aa||Ca(slugify$1(Fa))}function qa(Fa){Fa.preventDefault(),Da(null);const Ka=Kr.trim(),Ha=ja.trim();if(!Ka){Da("Name is required.");return}if(!SLUG_REGEX$2.test(Ha)){Da("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}Ba.mutate({name:Ka,slug:Ha})}return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"New team"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Teams group members of an organization for scoped activity views."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:qa,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"team-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"team-name",value:Kr,onChange:Fa=>Ma(Fa.target.value),placeholder:"Platform",required:!0,disabled:Ba.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"team-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"team-slug",value:ja,onChange:Fa=>{Ca(Fa.target.value),Oa(!0)},placeholder:"platform",required:!0,disabled:Ba.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Lowercase letters, numbers, and dashes. Used in URLs."})]}),Ia&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Ia}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>$(!1),disabled:Ba.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ba.isPending,className:"cursor-pointer",children:Ba.isPending?"Creating…":"Create team"})]})]})]})})}function RenameTeamDialog({team:es,orgSlug:$,onClose:ts}){const is=useQueryClient(),[Kr,Qr]=reactExports.useState(""),[ja,Ca]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Qr(es.name),Ca(es.slug),Oa(null))},[es]);const Ia=useMutation({mutationFn:({name:Ba,slug:Ma})=>updateTeam($,es.id,{name:Ba,slug:Ma}),onSuccess:()=>{ue$1.success("Team updated"),is.invalidateQueries({queryKey:["org-teams",$]}),is.invalidateQueries({queryKey:["org-detail",$]}),ts()},onError:Ba=>{if(Ba instanceof ApiError&&Ba.code==="TEAM_SLUG_TAKEN"){Oa("That slug is already in use by another team.");return}if(Ba instanceof ApiError&&Ba.code==="VALIDATION_ERROR"){Oa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(Ba instanceof Error?Ba.message:"Failed to update team")}});function Da(Ba){Ba.preventDefault(),Oa(null);const Ma=Kr.trim(),qa=ja.trim();if(!Ma){Oa("Name is required.");return}if(!SLUG_REGEX$2.test(qa)){Oa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}Ia.mutate({name:Ma,slug:qa})}return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:Ba=>{Ba||ts()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Rename team"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Change the team's display name and/or URL slug."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Da,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"rename-team-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"rename-team-name",value:Kr,onChange:Ba=>Qr(Ba.target.value),required:!0,disabled:Ia.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"rename-team-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"rename-team-slug",value:ja,onChange:Ba=>Ca(Ba.target.value),required:!0,disabled:Ia.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Changing the slug breaks any bookmarked links to this team."})]}),Aa&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Aa}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:ts,disabled:Ia.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ia.isPending,className:"cursor-pointer",children:Ia.isPending?"Saving…":"Save"})]})]})]})})}function DeleteTeamDialog({team:es,orgSlug:$,onClose:ts}){const is=useQueryClient(),Kr=useMutation({mutationFn:()=>deleteTeam($,es.id),onSuccess:()=>{ue$1.success("Team deleted"),is.invalidateQueries({queryKey:["org-teams",$]}),is.invalidateQueries({queryKey:["org-detail",$]}),ts()},onError:Qr=>{ue$1.error(Qr instanceof Error?Qr.message:"Failed to delete team")}});return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:Qr=>{Qr||ts()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Delete team?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[jsxRuntimeExports.jsx("strong",{children:es==null?void 0:es.name})," will be permanently deleted. Members will remain in the organization but will no longer be grouped under this team."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:ts,disabled:Kr.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:()=>Kr.mutate(),disabled:Kr.isPending,className:"cursor-pointer",children:Kr.isPending?"Deleting…":"Delete"})]})]})})}function TeamDetailPage(){const{activeOrg:es}=useActiveOrg(),$=(es==null?void 0:es.slug)??"",{teamSlug:ts=""}=useParams(),[is,Kr]=useTabParam(["members","activity"],"members"),Qr=useQuery({queryKey:["org-teams",$],queryFn:()=>listTeams($),enabled:!!$}),ja=reactExports.useMemo(()=>{var Ca;return((Ca=Qr.data)==null?void 0:Ca.find(Aa=>Aa.slug===ts))??null},[Qr.data,ts]);return Qr.isLoading?jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-32"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-10 w-full"})]}):Qr.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load team: ",Qr.error.message]}):ja?jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx("div",{className:"flex items-start justify-between gap-4",children:jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs(Link,{to:"/admin/teams",className:"text-xs text-muted-foreground hover:text-foreground inline-flex items-center",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-1 h-3 w-3"}),"All teams"]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight mt-1",children:ja.name}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx("code",{className:"text-xs",children:ja.slug}),jsxRuntimeExports.jsxs("span",{className:"ml-2",children:["· ",ja.memberCount," ",ja.memberCount===1?"member":"members"]})]})]})}),jsxRuntimeExports.jsxs(Tabs,{value:is,onValueChange:Kr,children:[jsxRuntimeExports.jsxs(TabsList,{variant:"line",children:[jsxRuntimeExports.jsx(TabsTrigger,{value:"members",children:"Members"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"activity",children:"Activity"})]}),jsxRuntimeExports.jsx(TabsContent,{value:"members",className:"pt-4",children:jsxRuntimeExports.jsx(MembersTab,{orgSlug:$,teamId:ja.id})}),jsxRuntimeExports.jsx(TabsContent,{value:"activity",className:"pt-4",children:jsxRuntimeExports.jsx(ActivityTab,{orgSlug:$,teamId:ja.id})})]})]}):jsxRuntimeExports.jsxs("div",{className:"flex flex-col items-center justify-center rounded-md border border-dashed border-border py-16 text-center",children:[jsxRuntimeExports.jsx("p",{className:"text-sm font-medium",children:"Team not found"}),jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground mb-4",children:["No team with slug ",jsxRuntimeExports.jsx("code",{className:"text-xs",children:ts})," in this organization."]}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"cursor-pointer",children:jsxRuntimeExports.jsxs(Link,{to:"/admin/teams",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"}),"Back to teams"]})})]})}function MembersTab({orgSlug:es,teamId:$}){const ts=useQueryClient(),[is,Kr]=reactExports.useState(!1),[Qr,ja]=reactExports.useState(null),Ca=useQuery({queryKey:["org-members",es],queryFn:()=>listMembers(es),enabled:!!es}),Aa=reactExports.useMemo(()=>(Ca.data??[]).filter(Da=>Da.teams.some(Ba=>Ba.id===$)),[Ca.data,$]),Oa=reactExports.useMemo(()=>(Ca.data??[]).filter(Da=>!Da.teams.some(Ba=>Ba.id===$)),[Ca.data,$]),Ia=useMutation({mutationFn:Da=>removeTeamMember(es,$,Da),onSuccess:()=>{ue$1.success("Member removed from team"),ts.invalidateQueries({queryKey:["org-members",es]}),ts.invalidateQueries({queryKey:["org-teams",es]}),ja(null)},onError:Da=>{ue$1.error(Da instanceof Error?Da.message:"Failed to remove member")}});return jsxRuntimeExports.jsxs("div",{className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Members in this team. Adding a member here doesn't change their organization role — only the team grouping."}),jsxRuntimeExports.jsxs(Button,{onClick:()=>Kr(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(UserPlus,{className:"mr-2 h-4 w-4"}),"Add member"]})]}),Ca.error?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load members: ",Ca.error.message]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border",children:jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{className:"w-12"}),jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{children:"Display name"}),jsxRuntimeExports.jsx(TableHead,{children:"Org role"}),jsxRuntimeExports.jsx(TableHead,{className:"w-12"})]})}),jsxRuntimeExports.jsx(TableBody,{children:Ca.isLoading?jsxRuntimeExports.jsx(SkeletonRows,{}):Aa.length===0?jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No members in this team yet."})}):Aa.map(Da=>jsxRuntimeExports.jsx(TeamMemberRow,{member:Da,onRemove:()=>ja(Da)},Da.userId))})]})}),jsxRuntimeExports.jsx(AddMemberDialog,{open:is,onOpenChange:Kr,orgSlug:es,teamId:$,addable:Oa,loading:Ca.isLoading}),jsxRuntimeExports.jsx(RemoveMemberDialog,{member:Qr,onCancel:()=>ja(null),onConfirm:()=>Qr&&Ia.mutate(Qr.userId),pending:Ia.isPending})]})}function TeamMemberRow({member:es,onRemove:$}){const ts=reactExports.useMemo(()=>(es.email??es.displayName??"?").slice(0,1).toUpperCase(),[es.email,es.displayName]);return jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Avatar,{size:"sm",children:jsxRuntimeExports.jsx(AvatarFallback,{children:ts})})}),jsxRuntimeExports.jsx(TableCell,{className:"font-medium",children:es.email??"—"}),jsxRuntimeExports.jsx(TableCell,{className:"text-muted-foreground",children:es.displayName??"—"}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Badge,{variant:"secondary",className:"capitalize",children:es.role})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs(DropdownMenu,{children:[jsxRuntimeExports.jsx(DropdownMenuTrigger,{asChild:!0,children:jsxRuntimeExports.jsxs(Button,{variant:"ghost",size:"icon",className:"h-8 w-8 cursor-pointer",children:[jsxRuntimeExports.jsx(Ellipsis,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{className:"sr-only",children:"Member actions"})]})}),jsxRuntimeExports.jsx(DropdownMenuContent,{align:"end",children:jsxRuntimeExports.jsx(DropdownMenuItem,{onClick:$,className:"text-destructive focus:text-destructive cursor-pointer",children:"Remove from team"})})]})})]})}function SkeletonRows(){return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:Array.from({length:3}).map((es,$)=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-6 rounded-full"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-40"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-24"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-16"})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-8"})})]},$))})}const NO_USER="__none";function AddMemberDialog({open:es,onOpenChange:$,orgSlug:ts,teamId:is,addable:Kr,loading:Qr}){const ja=useQueryClient(),[Ca,Aa]=reactExports.useState(NO_USER),[Oa,Ia]=reactExports.useState(null);reactExports.useEffect(()=>{es&&(Aa(NO_USER),Ia(null))},[es]);const Da=useMutation({mutationFn:Ma=>addTeamMember(ts,is,Ma),onSuccess:()=>{ue$1.success("Member added to team"),ja.invalidateQueries({queryKey:["org-members",ts]}),ja.invalidateQueries({queryKey:["org-teams",ts]}),$(!1)},onError:Ma=>{ue$1.error(Ma instanceof Error?Ma.message:"Failed to add member")}});function Ba(Ma){if(Ma.preventDefault(),Ca===NO_USER){Ia("Pick a member to add.");return}Da.mutate(Ca)}return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Add member to team"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Pick an organization member to add. Only members not already on this team are listed."})]}),jsxRuntimeExports.jsxs("form",{onSubmit:Ba,className:"space-y-4",children:[jsxRuntimeExports.jsx("div",{className:"space-y-2",children:jsxRuntimeExports.jsxs(Select,{value:Ca,onValueChange:Ma=>{Aa(Ma),Ia(null)},disabled:Da.isPending||Qr,children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:Qr?"Loading…":"Select member"})}),jsxRuntimeExports.jsx(SelectContent,{children:Kr.length===0?jsxRuntimeExports.jsx(SelectItem,{value:NO_USER,disabled:!0,children:Qr?"Loading…":"All org members are on this team."}):Kr.map(Ma=>jsxRuntimeExports.jsx(SelectItem,{value:Ma.userId,children:Ma.email??Ma.displayName??Ma.userId},Ma.userId))})]})}),Oa&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Oa}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>$(!1),disabled:Da.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Da.isPending||Kr.length===0||Ca===NO_USER,className:"cursor-pointer",children:Da.isPending?"Adding…":"Add"})]})]})]})})}function RemoveMemberDialog({member:es,onCancel:$,onConfirm:ts,pending:is}){return jsxRuntimeExports.jsx(Dialog,{open:!!es,onOpenChange:Kr=>{Kr||$()},children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Remove from team?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[(es==null?void 0:es.email)??"This member"," will no longer be grouped under this team. They'll remain in the organization."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:$,disabled:is,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",variant:"destructive",onClick:ts,disabled:is,className:"cursor-pointer",children:is?"Removing…":"Remove"})]})]})})}function ActivityTab({orgSlug:es,teamId:$}){var ja,Ca;const[ts,is]=reactExports.useState("7d"),Kr=useQuery({queryKey:["team-activity",es,$,ts],queryFn:()=>getTeamActivity(es,$,ts),enabled:!!es&&!!$});if(Kr.error)return jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive",children:["Failed to load activity: ",Kr.error.message]});const Qr=Kr.data;return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx("div",{className:"flex items-center justify-end",children:jsxRuntimeExports.jsxs(Select,{value:ts,onValueChange:Aa=>is(Aa),children:[jsxRuntimeExports.jsx(SelectTrigger,{size:"sm",className:"w-32",children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"7d",children:"Last 7 days"}),jsxRuntimeExports.jsx(SelectItem,{value:"30d",children:"Last 30 days"})]})]})}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4"}),label:`Sessions (${ts})`,value:Qr==null?void 0:Qr.sessionCount,loading:Kr.isLoading}),jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Users,{className:"h-4 w-4"}),label:"Active members",value:Qr==null?void 0:Qr.memberCount,loading:Kr.isLoading}),jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Wrench,{className:"h-4 w-4"}),label:"Top tool",value:((Ca=(ja=Qr==null?void 0:Qr.topTools)==null?void 0:ja[0])==null?void 0:Ca.tool)??"—",loading:Kr.isLoading}),jsxRuntimeExports.jsx(StatCard,{icon:jsxRuntimeExports.jsx(Activity,{className:"h-4 w-4"}),label:"Avg friction",value:Qr!=null&&Qr.frictionTrend&&Qr.frictionTrend.length>0?(Qr.frictionTrend.reduce((Aa,Oa)=>Aa+Oa.avgFriction,0)/Qr.frictionTrend.length).toFixed(2):"—",loading:Kr.isLoading})]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[jsxRuntimeExports.jsx(TopToolsCard,{data:Qr,loading:Kr.isLoading}),jsxRuntimeExports.jsx(TopMembersCard,{data:Qr,loading:Kr.isLoading}),jsxRuntimeExports.jsx(FrictionTrendCard,{data:Qr,loading:Kr.isLoading}),jsxRuntimeExports.jsx(InstructionEffectivenessCard,{data:Qr,loading:Kr.isLoading})]})]})}function StatCard({icon:es,label:$,value:ts,loading:is}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center gap-2 text-sm font-medium text-muted-foreground",children:[es,$]})}),jsxRuntimeExports.jsx(CardContent,{children:is?jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-20"}):jsxRuntimeExports.jsx("span",{className:"text-3xl font-mono font-semibold tabular-nums",children:ts??"—"})})]})}function TopToolsCard({data:es,loading:$}){var Kr;const ts=(es==null?void 0:es.topTools)??[],is=((Kr=ts[0])==null?void 0:Kr.count)??0;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Top tools"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"})]}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No data yet."}):jsxRuntimeExports.jsx("ul",{className:"space-y-2",children:ts.map(Qr=>jsxRuntimeExports.jsxs("li",{className:"space-y-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-baseline justify-between text-sm",children:[jsxRuntimeExports.jsx("span",{className:"font-medium",children:Qr.tool}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:Qr.count})]}),jsxRuntimeExports.jsx("div",{className:"h-1.5 w-full rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary",style:{width:`${is>0?Qr.count/is*100:0}%`}})})]},Qr.tool))})})]})}function TopMembersCard({data:es,loading:$}){const ts=(es==null?void 0:es.topMembers)??[];return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Top members"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"})]}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No data yet."}):jsxRuntimeExports.jsx("ul",{className:"space-y-2",children:ts.map(is=>jsxRuntimeExports.jsxs("li",{className:"flex items-baseline justify-between text-sm",children:[jsxRuntimeExports.jsx("span",{className:"truncate font-medium",children:is.email??is.displayName??is.userId}),jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:is.count})]},is.userId))})})]})}function FrictionTrendCard({data:es,loading:$}){const ts=(es==null?void 0:es.frictionTrend)??[],is=ts.reduce((Kr,Qr)=>Math.max(Kr,Qr.avgFriction),0);return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Friction trend"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsx(Skeleton,{className:"h-24 w-full"}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No friction data in this range."}):jsxRuntimeExports.jsx("ul",{className:"space-y-1.5",children:ts.map(Kr=>jsxRuntimeExports.jsxs("li",{className:"space-y-0.5",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-baseline justify-between text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:Kr.day}),jsxRuntimeExports.jsx("span",{className:"font-medium tabular-nums",children:Kr.avgFriction.toFixed(2)})]}),jsxRuntimeExports.jsx("div",{className:"h-1 w-full rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:"h-full bg-primary",style:{width:`${is>0?Kr.avgFriction/is*100:0}%`}})})]},Kr.day))})})]})}function InstructionEffectivenessCard({data:es,loading:$}){const ts=(es==null?void 0:es.instructionEffectiveness)??[];return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm font-medium",children:"Instruction effectiveness"})}),jsxRuntimeExports.jsx(CardContent,{children:$?jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-6 w-full"})]}):ts.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No linked instructions in this range."}):jsxRuntimeExports.jsx("ul",{className:"space-y-2",children:ts.map(is=>jsxRuntimeExports.jsxs("li",{className:"flex items-baseline justify-between gap-2 text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"flex min-w-0 items-baseline gap-1.5",children:[jsxRuntimeExports.jsx("span",{className:"truncate font-medium",children:is.name}),jsxRuntimeExports.jsx(ProvenanceBadge,{source:is.source})]}),jsxRuntimeExports.jsx("span",{className:is.deltaPct==null?"text-muted-foreground tabular-nums":is.deltaPct>=0?"text-teal-600 dark:text-teal-500 tabular-nums":"text-destructive tabular-nums",children:is.deltaPct==null?"—":`${is.deltaPct>=0?"+":""}${is.deltaPct.toFixed(1)}%`})]},is.instructionId))})})]})}const SLUG_REGEX$1=/^(?=.{3,40}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;function AdminSettingsPage(){const{activeOrg:es}=useActiveOrg();if(!es)return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"})]});const $=es.role==="owner";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:"Settings"}),jsxRuntimeExports.jsxs("p",{className:"text-muted-foreground text-sm",children:["Manage"," ",jsxRuntimeExports.jsx("strong",{className:"font-medium",children:es.name}),"'s name, slug, ownership, and lifecycle."]})]}),jsxRuntimeExports.jsx(GeneralSection,{orgName:es.name,orgSlug:es.slug}),$&&jsxRuntimeExports.jsx(TransferOwnershipSection,{orgSlug:es.slug}),$&&jsxRuntimeExports.jsx(DeleteOrgSection,{orgName:es.name,orgSlug:es.slug})]})}function Section({title:es,description:$,destructive:ts,children:is}){return jsxRuntimeExports.jsx(Card,{className:ts?"border-destructive/30":void 0,children:jsxRuntimeExports.jsx(CardContent,{className:"p-6",children:jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-[200px_1fr]",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("h3",{className:ts?"font-mono text-base font-semibold text-destructive":"font-mono text-base font-semibold",children:es}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:$})]}),jsxRuntimeExports.jsx("div",{className:"space-y-4",children:is})]})})})}function GeneralSection({orgName:es,orgSlug:$}){const ts=useQueryClient(),is=useNavigate(),[Kr,Qr]=reactExports.useState(es),[ja,Ca]=reactExports.useState($),[Aa,Oa]=reactExports.useState(null);reactExports.useEffect(()=>{Qr(es),Ca($),Oa(null)},[es,$]);const Ia=useMutation({mutationFn:Ma=>updateOrg($,Ma),onSuccess:Ma=>{ue$1.success("Organization updated"),ts.invalidateQueries({queryKey:["profile"]}),ts.invalidateQueries({queryKey:["orgs"]}),ts.invalidateQueries({queryKey:["org-detail",$]}),Ma.slug!==$&&is("/admin/settings",{replace:!0})},onError:Ma=>{if(Ma instanceof ApiError&&Ma.code==="ORG_SLUG_TAKEN"){Oa("That slug is already taken by another organization.");return}if(Ma instanceof ApiError&&Ma.code==="VALIDATION_ERROR"){Oa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(Ma instanceof Error?Ma.message:"Failed to update organization")}});function Da(Ma){Ma.preventDefault(),Oa(null);const qa=Kr.trim(),Fa=ja.trim();if(!qa){Oa("Name is required.");return}if(!SLUG_REGEX$1.test(Fa)){Oa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}const Ka={};qa!==es&&(Ka.name=qa),Fa!==$&&(Ka.slug=Fa),!(!Ka.name&&!Ka.slug)&&Ia.mutate(Ka)}const Ba=Kr.trim()!==es||ja.trim()!==$;return jsxRuntimeExports.jsx(Section,{title:"General",description:"The display name and URL slug of this organization.",children:jsxRuntimeExports.jsxs("form",{onSubmit:Da,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"org-name",value:Kr,onChange:Ma=>Qr(Ma.target.value),required:!0,disabled:Ia.isPending})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"org-slug",value:ja,onChange:Ma=>Ca(Ma.target.value),required:!0,disabled:Ia.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Lowercase letters, numbers, and dashes. Used in URLs and CLI commands. Changing the slug breaks any bookmarked links."})]}),Aa&&jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive",children:Aa}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ia.isPending||!Ba,className:"cursor-pointer",children:Ia.isPending?"Saving…":"Save"})})]})})}function TransferOwnershipSection({orgSlug:es}){const $=useQueryClient(),ts=useNavigate(),is=useQuery({queryKey:["org-members",es],queryFn:()=>listMembers(es),enabled:!!es}),Kr=reactExports.useMemo(()=>(is.data??[]).filter(Da=>Da.role==="admin"),[is.data]),[Qr,ja]=reactExports.useState(null),[Ca,Aa]=reactExports.useState(!1),Oa=useMutation({mutationFn:Da=>transferOwnership(es,Da),onSuccess:()=>{ue$1.success("Ownership transferred. You're now an admin."),$.invalidateQueries({queryKey:["org-members",es]}),$.invalidateQueries({queryKey:["orgs"]}),$.invalidateQueries({queryKey:["profile"]}),Aa(!1),ts("/admin/members")},onError:Da=>{if(Da instanceof ApiError&&Da.code==="SAME_USER"){ue$1.error("You can't transfer ownership to yourself.");return}if(Da instanceof ApiError&&Da.code==="NOT_A_MEMBER"){ue$1.error("That user is no longer a member of this organization.");return}ue$1.error(Da instanceof Error?Da.message:"Failed to transfer ownership")}}),Ia=Kr.find(Da=>Da.userId===Qr);return jsxRuntimeExports.jsxs(Section,{title:"Transfer ownership",description:"Promote another admin to owner. You will become an admin afterward.",children:[is.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-10 w-full"}):Kr.length===0?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-dashed border-border px-4 py-6 text-sm text-muted-foreground",children:["No other admins to transfer to. Promote a member to admin first on the"," ",jsxRuntimeExports.jsx("a",{href:"/admin/members",className:"underline",children:"Members"})," ","page."]}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"transfer-target",children:"New owner"}),jsxRuntimeExports.jsxs(Select,{value:Qr??"",onValueChange:Da=>ja(Da),disabled:Oa.isPending,children:[jsxRuntimeExports.jsx(SelectTrigger,{id:"transfer-target",className:"w-full",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"Select an admin…"})}),jsxRuntimeExports.jsx(SelectContent,{children:Kr.map(Da=>jsxRuntimeExports.jsx(SelectItem,{value:Da.userId,children:Da.email??Da.displayName??Da.userId},Da.userId))})]})]}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsxs(Button,{type:"button",variant:"outline",disabled:!Qr||Oa.isPending,onClick:()=>Aa(!0),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(ArrowRightLeft,{className:"mr-2 h-4 w-4"}),"Transfer ownership"]})})]}),jsxRuntimeExports.jsx(Dialog,{open:Ca,onOpenChange:Aa,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Transfer ownership?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:[jsxRuntimeExports.jsx("strong",{children:(Ia==null?void 0:Ia.email)??(Ia==null?void 0:Ia.displayName)??"the selected user"})," ","will become the new owner of this organization. You'll keep admin access but lose the ability to delete the org or transfer ownership again."]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{type:"button",variant:"outline",onClick:()=>Aa(!1),disabled:Oa.isPending,className:"cursor-pointer",children:"Cancel"}),jsxRuntimeExports.jsx(Button,{type:"button",onClick:()=>Qr&&Oa.mutate(Qr),disabled:!Qr||Oa.isPending,className:"cursor-pointer",children:Oa.isPending?"Transferring…":"Transfer"})]})]})})]})}function DeleteOrgSection({orgName:es,orgSlug:$}){const ts=useQueryClient(),is=useSetActiveOrg(),Kr=useNavigate(),[Qr,ja]=reactExports.useState(""),Ca=Qr===$,Aa=useMutation({mutationFn:()=>deleteOrg($),onSuccess:async()=>{ue$1.success(`Deleted ${es}`);try{await is.mutateAsync(null)}catch{}ts.clear(),Kr("/",{replace:!0})},onError:Oa=>{ue$1.error(Oa instanceof Error?Oa.message:"Failed to delete organization")}});return jsxRuntimeExports.jsxs(Section,{title:"Delete organization",description:"Permanently delete this organization, its teams, invitations, and member roles. Sessions are preserved (org_id is cleared).",destructive:!0,children:[jsxRuntimeExports.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 px-4 py-3",children:jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4 mt-0.5 text-destructive shrink-0"}),jsxRuntimeExports.jsx("div",{className:"text-sm text-destructive",children:"This action cannot be undone."})]})}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs(Label,{htmlFor:"delete-confirm",children:["Type ",jsxRuntimeExports.jsx("code",{className:"text-xs font-mono px-1 rounded bg-muted",children:$})," to confirm"]}),jsxRuntimeExports.jsx(Input,{id:"delete-confirm",value:Qr,onChange:Oa=>ja(Oa.target.value),autoComplete:"off",disabled:Aa.isPending})]}),jsxRuntimeExports.jsx("div",{className:"flex justify-end",children:jsxRuntimeExports.jsxs(Button,{type:"button",variant:"destructive",disabled:!Ca||Aa.isPending,onClick:()=>Aa.mutate(),className:"cursor-pointer",children:[jsxRuntimeExports.jsx(Trash2,{className:"mr-2 h-4 w-4"}),Aa.isPending?"Deleting…":"Delete organization"]})})]})}function useActiveLimits(){return useQuery({queryKey:["research","active-limits"],queryFn:()=>apiGet("/api/research/active-limits")})}function useObservations(es={}){const $=new URLSearchParams;es.provider&&$.set("provider",es.provider),es.plan&&$.set("plan",es.plan),es.limitType&&$.set("limit_type",es.limitType),es.limit!=null&&$.set("limit",String(es.limit)),es.offset!=null&&$.set("offset",String(es.offset));const ts=$.toString();return useQuery({queryKey:["research","observations",es],queryFn:()=>apiGet(`/api/research/observations${ts?`?${ts}`:""}`)})}function useDocChanges(es){return useQuery({queryKey:["research","doc-changes","default"],queryFn:()=>apiGet("/api/research/doc-changes")})}function useDisagreements(es=14){return useQuery({queryKey:["research","disagreements",es],queryFn:()=>apiGet(`/api/research/disagreements?since_days=${es}`)})}function useConfidenceHistory(es,$,ts,is=90){return useQuery({queryKey:["research","confidence-history",es,$,ts,is],queryFn:()=>{const Qr=new URLSearchParams({provider:es,plan:$,limit_type:ts,days:String(is)});return apiGet(`/api/research/confidence-history?${Qr}`)},enabled:!!es&&!!$&&!!ts})}function ConfidenceBar({value:es}){const $=Math.max(0,Math.min(1,es))*100,ts=es>=.9?"high":es>=.6?"mid":"low",is=ts==="high"?"bg-teal-500":ts==="mid"?"bg-amber-500":"bg-rose-500";return jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("div",{className:"h-1.5 w-16 rounded-full bg-muted overflow-hidden",children:jsxRuntimeExports.jsx("div",{className:`h-full ${is}`,style:{width:`${$}%`}})}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",children:[$.toFixed(0),"%"]})]})}function ConfidenceTrendSparkline({provider:es,plan:$,limitType:ts,width:is=80,height:Kr=20}){const{data:Qr,isLoading:ja}=useConfidenceHistory(es,$,ts);if(ja)return jsxRuntimeExports.jsx("div",{className:"h-5 w-20 animate-pulse rounded bg-muted"});const Ca=(Qr==null?void 0:Qr.items)??[];if(Ca.length===0)return jsxRuntimeExports.jsx("span",{className:"text-xs text-muted-foreground",children:"—"});if(Ca.length===1)return jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs tabular-nums text-muted-foreground",children:[(Ca[0].confidence*100).toFixed(0),"%"]});const Aa=Ca.map((Ma,qa)=>qa/(Ca.length-1)*is),Oa=Ca.map(Ma=>Kr-Ma.confidence*Kr),Ia=Aa.map((Ma,qa)=>`${qa===0?"M":"L"}${Ma.toFixed(1)},${Oa[qa].toFixed(1)}`).join(" "),Da=Ca[Ca.length-1].confidence,Ba=Da>=.9?"stroke-teal-500":Da>=.6?"stroke-amber-500":"stroke-rose-500";return jsxRuntimeExports.jsx("svg",{width:is,height:Kr,viewBox:`0 0 ${is} ${Kr}`,className:"overflow-visible",role:"img","aria-label":`Confidence trend (${Ca.length} points)`,children:jsxRuntimeExports.jsx("path",{d:Ia,fill:"none",className:Ba,strokeWidth:1.5,strokeLinejoin:"round"})})}function ActiveLimitsTable(){const{data:es,isLoading:$,error:ts}=useActiveLimits();if($)return jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"});if(ts)return jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load active limits."});const is=((es==null?void 0:es.items)??[]).slice().sort((Kr,Qr)=>Kr.provider!==Qr.provider?Kr.provider.localeCompare(Qr.provider):Kr.plan!==Qr.plan?Kr.plan.localeCompare(Qr.plan):Kr.limitType.localeCompare(Qr.limitType));return is.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No active limits recorded yet."}):jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Provider"}),jsxRuntimeExports.jsx(TableHead,{children:"Plan"}),jsxRuntimeExports.jsx(TableHead,{children:"Limit type"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Value"}),jsxRuntimeExports.jsx(TableHead,{children:"Unit"}),jsxRuntimeExports.jsx(TableHead,{children:"Confidence"}),jsxRuntimeExports.jsx(TableHead,{children:"Trend (90d)"}),jsxRuntimeExports.jsx(TableHead,{children:"Effective from"})]})}),jsxRuntimeExports.jsx(TableBody,{children:is.map(Kr=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Kr.provider}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Kr.plan}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Kr.limitType}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-right tabular-nums",children:Number(Kr.value).toLocaleString()}),jsxRuntimeExports.jsx(TableCell,{className:"text-xs text-muted-foreground",children:Kr.unit}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(ConfidenceBar,{value:Number(Kr.confidence)})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(ConfidenceTrendSparkline,{provider:Kr.provider,plan:Kr.plan,limitType:Kr.limitType})}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs text-muted-foreground",children:new Date(Kr.effectiveFrom).toLocaleString()})]},`${Kr.provider}-${Kr.plan}-${Kr.limitType}-${Kr.effectiveFrom}`))})]})}function RecentDocChanges(){const{data:es,isLoading:$,error:ts}=useDocChanges(),[is,Kr]=reactExports.useState(null);if($)return jsxRuntimeExports.jsx(Skeleton,{className:"h-32 w-full"});if(ts)return jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load doc snapshots."});const ja=((es==null?void 0:es.items)??[]).slice().sort((Ca,Aa)=>Ca.changed!==Aa.changed?Ca.changed?-1:1:new Date(Aa.latestFetchedAt).getTime()-new Date(Ca.latestFetchedAt).getTime());return ja.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No doc snapshots in window."}):jsxRuntimeExports.jsx("ul",{className:"divide-y divide-border rounded-md border border-border",children:ja.map(Ca=>{const Aa=`${Ca.provider}::${Ca.docUrl}`,Oa=is===Aa;return jsxRuntimeExports.jsxs("li",{className:"px-3 py-2",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>Kr(Oa?null:Aa),className:"flex w-full items-center justify-between gap-3 text-left cursor-pointer",children:[jsxRuntimeExports.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-xs",children:Ca.provider}),Ca.changed?jsxRuntimeExports.jsx(Badge,{variant:"default",className:"text-[10px]",children:"changed"}):jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-[10px]",children:"stable"}),!Ca.parseSuccess&&jsxRuntimeExports.jsx(Badge,{variant:"destructive",className:"text-[10px]",children:"parse-fail"})]}),jsxRuntimeExports.jsx("div",{className:"truncate font-mono text-xs text-muted-foreground",children:Ca.docUrl})]}),jsxRuntimeExports.jsx("div",{className:"flex-shrink-0 font-mono text-xs text-muted-foreground tabular-nums",children:new Date(Ca.latestFetchedAt).toLocaleString()})]}),Oa&&jsxRuntimeExports.jsx(DocSnapshotDetail,{group:Ca})]},Aa)})})}function DocSnapshotDetail({group:es}){return jsxRuntimeExports.jsx("div",{className:"mt-2 ml-2 border-l-2 border-border pl-3 space-y-1",children:es.snapshots.slice(0,5).map($=>jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 font-mono text-xs",children:[jsxRuntimeExports.jsx("span",{className:"text-muted-foreground tabular-nums",children:new Date($.fetchedAt).toLocaleString()}),jsxRuntimeExports.jsx("span",{className:"truncate text-muted-foreground",children:$.contentHash.slice(0,12)}),!$.parseSuccess&&jsxRuntimeExports.jsx(Badge,{variant:"destructive",className:"text-[10px]",children:"parse-fail"})]},$.id))})}function SourceBadge({sourceType:es}){const $=LABELS[es]??es,ts=VARIANTS[es]??"outline";return jsxRuntimeExports.jsx(Badge,{variant:ts,className:"font-mono text-[10px] uppercase tracking-wide",children:$})}const LABELS={oauth_usage:"live",self_observed_429:"429",official_docs:"docs",self_observed_lower_bound:"lower",community:"community",llm_research:"llm"},VARIANTS={oauth_usage:"default",self_observed_429:"destructive",official_docs:"secondary",self_observed_lower_bound:"outline",community:"outline",llm_research:"outline"},PAGE_SIZE=50,ANY="__any";function ObservationsList(){const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(""),[Kr,Qr]=reactExports.useState(""),[ja,Ca]=reactExports.useState(0),Aa=useActiveLimits(),Oa=reactExports.useMemo(()=>{var Qa;const Fa=new Set,Ka=new Set,Ha=new Set;for(const Va of((Qa=Aa.data)==null?void 0:Qa.items)??[])Fa.add(Va.provider),Ka.add(Va.plan),Ha.add(Va.limitType);return{providers:Array.from(Fa).sort(),plans:Array.from(Ka).sort(),limitTypes:Array.from(Ha).sort()}},[Aa.data]),{data:Ia,isLoading:Da,error:Ba}=useObservations({provider:es||void 0,plan:ts||void 0,limitType:Kr||void 0,limit:PAGE_SIZE,offset:ja}),Ma=(Ia==null?void 0:Ia.total)??0,qa=(Ia==null?void 0:Ia.items)??[];return jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[jsxRuntimeExports.jsx(FilterSelect,{label:"Provider",value:es,options:Oa.providers,onChange:Fa=>{$(Fa),Ca(0)}}),jsxRuntimeExports.jsx(FilterSelect,{label:"Plan",value:ts,options:Oa.plans,onChange:Fa=>{is(Fa),Ca(0)}}),jsxRuntimeExports.jsx(FilterSelect,{label:"Limit type",value:Kr,options:Oa.limitTypes,onChange:Fa=>{Qr(Fa),Ca(0)}}),jsxRuntimeExports.jsx("div",{className:"ml-auto font-mono text-xs text-muted-foreground tabular-nums",children:Ma>0&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[ja+1,"–",Math.min(ja+PAGE_SIZE,Ma)," of ",Ma]})})]}),Da?jsxRuntimeExports.jsx(Skeleton,{className:"h-48 w-full"}):Ba?jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load observations."}):qa.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No observations match these filters."}):jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Observed at"}),jsxRuntimeExports.jsx(TableHead,{children:"Provider"}),jsxRuntimeExports.jsx(TableHead,{children:"Plan"}),jsxRuntimeExports.jsx(TableHead,{children:"Limit type"}),jsxRuntimeExports.jsx(TableHead,{className:"text-right",children:"Value"}),jsxRuntimeExports.jsx(TableHead,{children:"Unit"}),jsxRuntimeExports.jsx(TableHead,{children:"Source"}),jsxRuntimeExports.jsx(TableHead,{children:"Confidence"})]})}),jsxRuntimeExports.jsx(TableBody,{children:qa.map(Fa=>jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs text-muted-foreground tabular-nums",children:new Date(Fa.observedAt).toLocaleString()}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Fa.provider}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Fa.plan}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-xs",children:Fa.limitType}),jsxRuntimeExports.jsx(TableCell,{className:"font-mono text-right tabular-nums",children:Number(Fa.value).toLocaleString()}),jsxRuntimeExports.jsx(TableCell,{className:"text-xs text-muted-foreground",children:Fa.unit}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(SourceBadge,{sourceType:Fa.sourceType})}),jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsx(ConfidenceBar,{value:Number(Fa.confidence)})})]},Fa.id))})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-end gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:ja===0,onClick:()=>Ca(Math.max(0,ja-PAGE_SIZE)),children:"Previous"}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:ja+PAGE_SIZE>=Ma,onClick:()=>Ca(ja+PAGE_SIZE),children:"Next"})]})]})}function FilterSelect({label:es,value:$,options:ts,onChange:is}){return jsxRuntimeExports.jsxs(Select,{value:$||ANY,onValueChange:Kr=>is(Kr===ANY?"":Kr),children:[jsxRuntimeExports.jsx(SelectTrigger,{className:"h-8 w-[180px] text-xs",children:jsxRuntimeExports.jsx(SelectValue,{placeholder:es})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsxs(SelectItem,{value:ANY,children:["All ",es.toLowerCase(),"s"]}),ts.map(Kr=>jsxRuntimeExports.jsx(SelectItem,{value:Kr,className:"font-mono text-xs",children:Kr},Kr))]})]})}function DisagreementView(){const{data:es,isLoading:$,error:ts}=useDisagreements();if($)return jsxRuntimeExports.jsx(Skeleton,{className:"h-40 w-full"});if(ts)return jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",children:"Failed to load disagreements."});const is=(es==null?void 0:es.items)??[];return is.length===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"No disagreements (>20% spread) detected in the last 14 days."}):jsxRuntimeExports.jsx("div",{className:"space-y-3",children:is.map(Kr=>jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{className:"pb-2",children:jsxRuntimeExports.jsxs(CardTitle,{className:"flex items-center justify-between gap-2 text-sm",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono",children:[Kr.provider," / ",Kr.plan," / ",Kr.limitType]}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-xs text-destructive tabular-nums",children:["Δ ",Kr.spreadPct.toFixed(1),"% (",Kr.minValue.toLocaleString()," →"," ",Kr.maxValue.toLocaleString(),")"]})]})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx("ul",{className:"divide-y divide-border",children:Kr.observations.map(Qr=>jsxRuntimeExports.jsxs("li",{className:"flex items-center gap-3 py-1.5 font-mono text-xs",children:[jsxRuntimeExports.jsx("span",{className:"w-40 text-muted-foreground tabular-nums",children:new Date(Qr.observedAt).toLocaleString()}),jsxRuntimeExports.jsx("span",{className:"w-24 text-right tabular-nums",children:Qr.value.toLocaleString()}),jsxRuntimeExports.jsx("span",{className:"w-16 text-muted-foreground",children:Qr.unit}),jsxRuntimeExports.jsx(SourceBadge,{sourceType:Qr.sourceType}),jsxRuntimeExports.jsx("div",{className:"ml-auto",children:jsxRuntimeExports.jsx(ConfidenceBar,{value:Qr.confidence})})]},Qr.id))})})]},`${Kr.provider}-${Kr.plan}-${Kr.limitType}`))})}function AdminResearchPage(){const[es,$]=useTabParam(["active","docs","observations","disagreements"],"active");return jsxRuntimeExports.jsxs("div",{className:"space-y-6",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[jsxRuntimeExports.jsx(Database,{className:"h-4 w-4"}),jsxRuntimeExports.jsx("span",{children:"Usage research"})]}),jsxRuntimeExports.jsx("h2",{className:"text-2xl font-mono font-bold tracking-tight mt-1",children:"Provider limits intelligence"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Fused view of provider rate-limits sourced from OAuth headers, 429 responses, official docs, and community signals."})]}),jsxRuntimeExports.jsxs(Tabs,{value:es,onValueChange:$,className:"space-y-4",children:[jsxRuntimeExports.jsxs(TabsList,{children:[jsxRuntimeExports.jsx(TabsTrigger,{value:"active",children:"Active limits"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"docs",children:"Doc changes"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"observations",children:"Observations"}),jsxRuntimeExports.jsx(TabsTrigger,{value:"disagreements",children:"Disagreements"})]}),jsxRuntimeExports.jsx(TabsContent,{value:"active",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Active fused limits"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(ActiveLimitsTable,{})})]})}),jsxRuntimeExports.jsx(TabsContent,{value:"docs",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Recent doc snapshots (7d)"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(RecentDocChanges,{})})]})}),jsxRuntimeExports.jsx(TabsContent,{value:"observations",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Raw observations"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(ObservationsList,{})})]})}),jsxRuntimeExports.jsx(TabsContent,{value:"disagreements",children:jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsx(CardTitle,{className:"text-sm",children:"Source disagreements (14d, >20% spread)"})}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(DisagreementView,{})})]})})]})]})}function statusBadgeVariant(es){switch(es){case"draft":return{className:"bg-muted text-muted-foreground",label:"draft"};case"queued":return{className:"bg-blue-500/15 text-blue-700 dark:text-blue-300",label:"queued"};case"sending":return{className:"bg-blue-500/15 text-blue-700 dark:text-blue-300 animate-pulse",label:"sending"};case"sent":return{className:"bg-teal-500/15 text-teal-700 dark:text-teal-300",label:"sent"};case"failed":return{className:"bg-destructive/15 text-destructive",label:"failed"}}}function StatusBadge({status:es}){const{className:$,label:ts}=statusBadgeVariant(es);return jsxRuntimeExports.jsx(Badge,{variant:"outline",className:cn$1("font-mono text-xs",$),children:ts})}function AdminAnnouncementsPage(){var Qr;const{profile:es,isLoading:$}=useActiveOrg(),[ts,is]=reactExports.useState(null),Kr=useQuery({queryKey:["admin","announcements"],queryFn:()=>apiGet("/api/announcements"),refetchInterval:POLL.BACKGROUND,enabled:!!(es!=null&&es.isSuperadmin)});return reactExports.useEffect(()=>{var ja;!ts&&((ja=Kr.data)!=null&&ja.announcements.length)&&is(Kr.data.announcements[0].id)},[Kr.data,ts]),$?jsxRuntimeExports.jsx("div",{className:"p-6",children:jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-64"})}):es!=null&&es.isSuperadmin?jsxRuntimeExports.jsxs("div",{className:"flex h-[calc(100vh-4rem)] flex-col",children:[jsxRuntimeExports.jsxs("header",{className:"border-b border-border p-6",children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-semibold",children:"Announcements"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Superadmin · CHANGELOG-driven product announcement emails. Drafts are editable; sent ones are immutable."})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-1 flex-col overflow-hidden md:flex-row",children:[jsxRuntimeExports.jsx("aside",{className:"max-h-64 w-full shrink-0 overflow-y-auto border-b border-border md:max-h-none md:w-80 md:border-b-0 md:border-r",children:Kr.isLoading?jsxRuntimeExports.jsxs("div",{className:"space-y-2 p-4",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-16"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-16"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-16"})]}):Kr.error?jsxRuntimeExports.jsxs("p",{className:"p-4 text-sm text-destructive",children:["Failed to load: ",Kr.error.message]}):(((Qr=Kr.data)==null?void 0:Qr.announcements.length)??0)===0?jsxRuntimeExports.jsx("div",{className:"p-6 text-center",children:jsxRuntimeExports.jsxs("p",{className:"text-sm text-muted-foreground",children:["No announcements yet. Add an entry to"," ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"CHANGELOG.md"}),", then run"," ",jsxRuntimeExports.jsx("code",{className:"font-mono",children:"rulemetric crons run cron_check_changelog"})," ","if this release merits an announcement draft."]})}):jsxRuntimeExports.jsx("ul",{className:"divide-y divide-border",children:Kr.data.announcements.map(ja=>{const Ca=ja.id===ts;return jsxRuntimeExports.jsx("li",{children:jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>is(ja.id),className:cn$1("flex w-full flex-col gap-1 px-4 py-3 text-left transition-colors","hover:bg-muted/50",Ca&&"bg-secondary"),children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between gap-2",children:[jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm font-medium",children:["v",ja.version]}),jsxRuntimeExports.jsx(StatusBadge,{status:ja.status})]}),jsxRuntimeExports.jsxs("div",{className:"text-xs text-muted-foreground",children:[ja.releaseDate,ja.status==="sent"&&ja.recipientCount!==null&&jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[" · ",ja.recipientCount," recipients"]})]}),jsxRuntimeExports.jsx("div",{className:"line-clamp-2 text-sm",children:ja.subject})]})},ja.id)})})}),jsxRuntimeExports.jsx("main",{className:"flex-1 overflow-y-auto",children:ts?jsxRuntimeExports.jsx(AnnouncementDetailPane,{id:ts}):jsxRuntimeExports.jsx("div",{className:"flex h-full items-center justify-center text-sm text-muted-foreground",children:"Select an announcement to view details."})})]})]}):jsxRuntimeExports.jsx(Navigate,{to:"/admin",replace:!0})}function AnnouncementDetailPane({id:es}){var rl,dl;const $=useQueryClient(),ts=useQuery({queryKey:["admin","announcement",es],queryFn:()=>apiGet(`/api/announcements/${es}`),refetchInterval:xl=>{var ll;const nl=(ll=xl.state.data)==null?void 0:ll.status;return nl==="queued"||nl==="sending"?3e3:!1}}),is=useQuery({queryKey:["admin","announcement",es,"recipient-count"],queryFn:()=>apiGet(`/api/announcements/${es}/recipients/count`)}),[Kr,Qr]=reactExports.useState(!1),[ja,Ca]=reactExports.useState(""),[Aa,Oa]=reactExports.useState(!1),[Ia,Da]=reactExports.useState(""),[Ba,Ma]=reactExports.useState("");reactExports.useEffect(()=>{Qr(!1),Oa(!1)},[es]);const qa=ts.data,Fa=(qa==null?void 0:qa.status)==="draft",Ka=()=>{$.invalidateQueries({queryKey:["admin","announcements"]}),$.invalidateQueries({queryKey:["admin","announcement",es]})},Ha=useMutation({mutationFn:xl=>apiPatch(`/api/announcements/${es}`,xl),onSuccess:()=>{ue$1.success("Saved"),Qr(!1),Oa(!1),Ka()},onError:xl=>{const nl=xl instanceof ApiError?xl.message:String(xl);ue$1.error(`Save failed: ${nl}`)}}),[Qa,Va]=reactExports.useState(!1),Ya=useMutation({mutationFn:()=>apiPost(`/api/announcements/${es}/send`,{}),onSuccess:xl=>{ue$1.success(xl.resumed?"Resuming send…":"Sending…"),Va(!1),Ka()},onError:xl=>{const nl=xl instanceof ApiError?xl.message:String(xl);ue$1.error(`Send failed: ${nl}`)}}),Ja=reactExports.useMemo(()=>!(qa!=null&&qa.sections)||typeof qa.sections!="object"?[]:Object.entries(qa.sections).map(([nl,ll])=>({key:nl,items:Array.isArray(ll)?ll.map(String):[String(ll)]})),[qa==null?void 0:qa.sections]);if(ts.isLoading)return jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-2/3"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"})]});if(ts.error||!qa)return jsxRuntimeExports.jsxs("p",{className:"p-6 text-sm text-destructive",children:["Failed to load announcement:"," ",((rl=ts.error)==null?void 0:rl.message)??"not found"]});const el=((dl=is.data)==null?void 0:dl.count)??null,tl=!Fa||el===0||Ya.isPending,il=Fa?el===0?"No opted-in recipients":"":`Already ${qa.status} — cannot resend`;return jsxRuntimeExports.jsxs("div",{className:"space-y-6 p-6",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntimeExports.jsx(StatusBadge,{status:qa.status}),jsxRuntimeExports.jsxs("span",{className:"font-mono text-sm text-muted-foreground",children:["v",qa.version]}),jsxRuntimeExports.jsx("span",{className:"text-sm text-muted-foreground",children:qa.releaseDate}),qa.sentAt&&jsxRuntimeExports.jsxs("span",{className:"text-sm text-muted-foreground",children:["· Sent ",new Date(qa.sentAt).toLocaleString()]}),qa.recipientCount!==null&&qa.status==="sent"&&jsxRuntimeExports.jsxs("span",{className:"text-sm text-muted-foreground",children:["· ",qa.recipientCount," recipients"]})]}),qa.deliveryCounts&&Object.keys(qa.deliveryCounts).length>0&&jsxRuntimeExports.jsx("div",{className:"flex flex-wrap items-center gap-2",children:["sent","failed","skipped","pending"].filter(xl=>{var nl;return(((nl=qa.deliveryCounts)==null?void 0:nl[xl])??0)>0}).map(xl=>{var nl;return jsxRuntimeExports.jsxs(Badge,{variant:xl==="failed"?"destructive":"outline",className:"font-mono text-xs",children:[(nl=qa.deliveryCounts)==null?void 0:nl[xl]," ",xl]},xl)})}),Kr?jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Input,{value:ja,onChange:xl=>Ca(xl.target.value),autoFocus:!0,className:"text-lg"}),jsxRuntimeExports.jsx(Button,{size:"sm",disabled:!ja.trim()||Ha.isPending,onClick:()=>Ha.mutate({subject:ja.trim()}),children:Ha.isPending?"Saving…":"Save"}),jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",onClick:()=>Qr(!1),children:"Cancel"})]}):jsxRuntimeExports.jsxs("div",{className:"flex items-start gap-2",children:[jsxRuntimeExports.jsx("h2",{className:"text-xl font-semibold",children:qa.subject}),Fa&&jsxRuntimeExports.jsx(Button,{size:"icon",variant:"ghost",onClick:()=>{Ca(qa.subject),Qr(!0)},"aria-label":"Edit subject",children:jsxRuntimeExports.jsx(Pencil,{className:"h-4 w-4"})})]})]}),qa.error&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 font-medium text-destructive",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4"})," Last error"]}),jsxRuntimeExports.jsx("pre",{className:"mt-2 whitespace-pre-wrap font-mono text-xs",children:qa.error})]}),jsxRuntimeExports.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 rounded-md border border-border bg-muted/30 p-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Recipients (opted in)"}),jsxRuntimeExports.jsx("div",{className:"font-mono text-3xl font-semibold",children:is.isLoading?"…":el??"?"}),jsxRuntimeExports.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["Live count from ",jsxRuntimeExports.jsx("code",{children:"notification_preferences"})," — server-side aggregation, not a client filter."]})]}),jsxRuntimeExports.jsx(TooltipProvider,{children:jsxRuntimeExports.jsxs(Tooltip,{children:[jsxRuntimeExports.jsx(TooltipTrigger,{asChild:!0,children:jsxRuntimeExports.jsx("span",{tabIndex:tl?0:-1,children:jsxRuntimeExports.jsxs(Button,{size:"lg",disabled:tl,onClick:()=>Va(!0),children:[jsxRuntimeExports.jsx(Send,{className:"mr-2 h-4 w-4"}),"Send announcement"]})})}),il&&jsxRuntimeExports.jsx(TooltipContent,{children:il})]})})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-2",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-medium",children:"HTML preview"}),Fa&&jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",onClick:()=>{Aa||(Da(qa.htmlBody),Ma(qa.textBody)),Oa(xl=>!xl)},children:Aa?"Close editor":"Edit body"})]}),jsxRuntimeExports.jsx("iframe",{sandbox:"allow-same-origin",srcDoc:qa.htmlBody,title:"Announcement HTML preview",className:"h-[480px] w-full rounded-md border border-border bg-white"})]}),Aa&&jsxRuntimeExports.jsxs("section",{className:"space-y-4 rounded-md border border-border p-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"html_body"}),jsxRuntimeExports.jsx(Textarea,{value:Ia,onChange:xl=>Da(xl.target.value),rows:12,className:"font-mono text-xs"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx("label",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"text_body"}),jsxRuntimeExports.jsx(Textarea,{value:Ba,onChange:xl=>Ma(xl.target.value),rows:8,className:"font-mono text-xs"})]}),jsxRuntimeExports.jsxs("div",{className:"flex justify-end gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",onClick:()=>Oa(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{size:"sm",disabled:Ha.isPending||Ia===qa.htmlBody&&Ba===qa.textBody,onClick:()=>Ha.mutate({htmlBody:Ia,textBody:Ba}),children:Ha.isPending?"Saving…":"Save body"})]})]}),jsxRuntimeExports.jsx(CollapsibleSection,{title:"Plain-text body",children:jsxRuntimeExports.jsx("pre",{className:"max-h-96 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-muted/30 p-3 font-mono text-xs",children:qa.textBody})}),Ja.length>0&&jsxRuntimeExports.jsx(CollapsibleSection,{title:"Parsed sections",children:jsxRuntimeExports.jsx("div",{className:"space-y-3",children:Ja.map(({key:xl,items:nl})=>jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:xl}),jsxRuntimeExports.jsx("ul",{className:"ml-4 list-disc text-sm",children:nl.map((ll,fl)=>jsxRuntimeExports.jsx("li",{children:ll},fl))})]},xl))})}),jsxRuntimeExports.jsx(Dialog,{open:Qa,onOpenChange:Va,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Send announcement?"}),jsxRuntimeExports.jsxs(DialogDescription,{children:["Send ",jsxRuntimeExports.jsxs("span",{className:"font-semibold",children:['"',qa.subject,'"']})," to"," ",jsxRuntimeExports.jsx("span",{className:"font-mono font-semibold",children:el??"?"})," ","recipients?"]})]}),jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/50 bg-destructive/10 p-3 text-sm",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 font-medium text-destructive",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-4 w-4"}),"This cannot be undone."]}),jsxRuntimeExports.jsx("p",{className:"mt-1 text-xs",children:"Recipients will receive an email within ~1 minute."})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Va(!1),disabled:Ya.isPending,children:"Cancel"}),jsxRuntimeExports.jsx(Button,{onClick:()=>Ya.mutate(),disabled:Ya.isPending,children:Ya.isPending?"Queuing…":"Send now"})]})]})})]})}function CollapsibleSection({title:es,children:$}){const[ts,is]=reactExports.useState(!1);return jsxRuntimeExports.jsxs("section",{className:"rounded-md border border-border",children:[jsxRuntimeExports.jsxs("button",{type:"button",onClick:()=>is(Kr=>!Kr),className:"flex w-full items-center justify-between px-4 py-2 text-left text-sm font-medium hover:bg-muted/30",children:[jsxRuntimeExports.jsx("span",{children:es}),jsxRuntimeExports.jsx("span",{className:"font-mono text-xs text-muted-foreground",children:ts?"−":"+"})]}),ts&&jsxRuntimeExports.jsx("div",{className:"border-t border-border p-4",children:$})]})}function listUsers(es={}){const $=new URLSearchParams;es.search&&$.set("search",es.search),es.limit!==void 0&&$.set("limit",String(es.limit)),es.offset!==void 0&&$.set("offset",String(es.offset));const ts=$.toString();return apiGet(`/api/superadmin/users${ts?`?${ts}`:""}`)}function getUserDetail(es){return apiGet(`/api/superadmin/users/${es}`)}function listAllOrgs(){return apiGet("/api/superadmin/orgs")}function assignUserToOrg(es,$){return apiPost(`/api/superadmin/users/${es}/assign`,$)}function removeUserFromOrg(es,$){return apiDelete(`/api/superadmin/users/${es}/orgs/${$}`)}function forceLogoutUser(es){return apiPost(`/api/superadmin/users/${es}/force-logout`,{})}function resetUserPassword(es){return apiPost(`/api/superadmin/users/${es}/reset-password`,{})}function setUserSuspended(es,$){return apiPatch(`/api/superadmin/users/${es}/suspend`,{suspended:$})}function deleteUser(es,$){return api(`/api/superadmin/users/${es}`,{method:"DELETE",body:{confirmEmail:$}})}function inviteUser(es){return apiPost("/api/superadmin/users/invite",es)}function SuperadminUsersPage(){var Ia,Da,Ba,Ma;const[es,$]=reactExports.useState(""),[ts,is]=reactExports.useState(""),[Kr,Qr]=reactExports.useState(null),[ja,Ca]=reactExports.useState(!1),Aa=qa=>{$(qa);const Fa=window.setTimeout(()=>is(qa),300);return()=>window.clearTimeout(Fa)},Oa=useQuery({queryKey:["superadmin","users",ts],queryFn:()=>listUsers({search:ts||void 0,limit:100})});return jsxRuntimeExports.jsxs("div",{className:"space-y-4 p-6",children:[jsxRuntimeExports.jsxs("header",{className:"flex items-start justify-between gap-4",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("h1",{className:"text-2xl font-semibold",children:"Superadmin · Users"}),jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Platform-level user directory. Click Manage to assign org membership, reset passwords, suspend, or delete."})]}),jsxRuntimeExports.jsx(Button,{onClick:()=>Ca(!0),children:"Invite user"})]}),jsxRuntimeExports.jsxs("div",{className:"relative max-w-md",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,{value:es,onChange:qa=>Aa(qa.target.value),placeholder:"Search by email…",className:"pl-9"})]}),Oa.isLoading?jsxRuntimeExports.jsx(Skeleton,{className:"h-64 w-full"}):Oa.error?jsxRuntimeExports.jsxs("p",{className:"text-sm text-destructive",children:["Failed to load: ",Oa.error.message]}):jsxRuntimeExports.jsxs("div",{className:"rounded-md border",children:[jsxRuntimeExports.jsxs(Table,{children:[jsxRuntimeExports.jsx(TableHeader,{children:jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableHead,{children:"Email"}),jsxRuntimeExports.jsx(TableHead,{className:"w-24 text-right",children:"Orgs"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Sessions"}),jsxRuntimeExports.jsx(TableHead,{className:"w-32 text-right",children:"Orphan org_id"}),jsxRuntimeExports.jsx(TableHead,{className:"w-28",children:"Created"}),jsxRuntimeExports.jsx(TableHead,{className:"w-28 text-right",children:"Actions"})]})}),jsxRuntimeExports.jsxs(TableBody,{children:[(Ia=Oa.data)==null?void 0:Ia.users.map(qa=>jsxRuntimeExports.jsx(UserRow,{user:qa,onManage:()=>Qr(qa.id)},qa.id)),((Da=Oa.data)==null?void 0:Da.users.length)===0&&jsxRuntimeExports.jsx(TableRow,{children:jsxRuntimeExports.jsx(TableCell,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No users."})})]})]}),jsxRuntimeExports.jsxs("div",{className:"border-t p-2 text-xs text-muted-foreground text-right",children:["Showing ",(Ba=Oa.data)==null?void 0:Ba.users.length," of ",(Ma=Oa.data)==null?void 0:Ma.total," total"]})]}),Kr&&jsxRuntimeExports.jsx(ManageUserSheet,{userId:Kr,onClose:()=>Qr(null)}),jsxRuntimeExports.jsx(InviteUserDialog,{open:ja,onOpenChange:Ca})]})}function InviteUserDialog({open:es,onOpenChange:$}){var Da;const ts=useQueryClient(),[is,Kr]=reactExports.useState(""),[Qr,ja]=reactExports.useState(""),[Ca,Aa]=reactExports.useState("member"),Oa=useQuery({queryKey:["superadmin","all-orgs"],queryFn:listAllOrgs,enabled:es}),Ia=useMutation({mutationFn:()=>inviteUser({email:is,orgId:Qr||void 0,role:Qr?Ca:void 0}),onSuccess:Ba=>{ue$1.success(`Invite sent to ${Ba.email}`+(Ba.assigned?` · pre-assigned as ${Ba.assigned.role}`:"")),ts.invalidateQueries({queryKey:["superadmin","users"]}),Kr(""),ja(""),Aa("member"),$(!1)},onError:Ba=>{const Ma=Ba instanceof ApiError?Ba.message:String(Ba);ue$1.error(`Invite failed: ${Ma}`)}});return jsxRuntimeExports.jsx(Dialog,{open:es,onOpenChange:$,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Invite user"}),jsxRuntimeExports.jsx(DialogDescription,{children:"Sends a Supabase invite email. Optionally pre-assign them to an org."})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-3 py-2",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"invite-email",children:"Email"}),jsxRuntimeExports.jsx(Input,{id:"invite-email",type:"email",value:is,onChange:Ba=>Kr(Ba.target.value),placeholder:"user@example.com"})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{children:"Pre-assign to org (optional)"}),jsxRuntimeExports.jsxs(Select,{value:Qr,onValueChange:ja,children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"None — invite only"})}),jsxRuntimeExports.jsx(SelectContent,{children:(((Da=Oa.data)==null?void 0:Da.orgs)??[]).map(Ba=>jsxRuntimeExports.jsx(SelectItem,{value:Ba.id,children:Ba.name},Ba.id))})]})]}),Qr&&jsxRuntimeExports.jsxs("div",{className:"space-y-1",children:[jsxRuntimeExports.jsx(Label,{children:"Role"}),jsxRuntimeExports.jsxs(Select,{value:Ca,onValueChange:Ba=>Aa(Ba),children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"owner",children:"owner"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"admin"}),jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"member"})]})]})]})]}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>$(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{disabled:!is||Ia.isPending,onClick:()=>Ia.mutate(),children:Ia.isPending?"Sending…":"Send invite"})]})]})})}function UserRow({user:es,onManage:$}){return jsxRuntimeExports.jsxs(TableRow,{children:[jsxRuntimeExports.jsx(TableCell,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx("span",{className:"font-mono text-sm",children:es.email??"—"}),es.isSuperadmin&&jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"text-xs",children:"superadmin"})]})}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:es.orgCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:es.sessionCount}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:es.orphanSessionCount>0?jsxRuntimeExports.jsx(Badge,{variant:"destructive",className:"font-mono",children:es.orphanSessionCount}):jsxRuntimeExports.jsx("span",{className:"text-muted-foreground",children:"0"})}),jsxRuntimeExports.jsx(TableCell,{className:"text-xs text-muted-foreground",children:new Date(es.createdAt).toISOString().slice(0,10)}),jsxRuntimeExports.jsx(TableCell,{className:"text-right",children:jsxRuntimeExports.jsx(Button,{size:"sm",variant:"outline",onClick:$,children:"Manage"})})]})}function ManageUserSheet({userId:es,onClose:$}){var xl;const ts=useQueryClient(),is=useQuery({queryKey:["superadmin","user",es],queryFn:()=>getUserDetail(es)}),Kr=useQuery({queryKey:["superadmin","all-orgs"],queryFn:listAllOrgs}),[Qr,ja]=reactExports.useState(""),[Ca,Aa]=reactExports.useState("member"),[Oa,Ia]=reactExports.useState(!0),Da=()=>{ts.invalidateQueries({queryKey:["superadmin","users"]}),ts.invalidateQueries({queryKey:["superadmin","user",es]})},Ba=useMutation({mutationFn:()=>assignUserToOrg(es,{orgId:Qr,role:Ca,claimSessions:Oa}),onSuccess:nl=>{ue$1.success(`Assigned as ${nl.role}`+(nl.claimed_sessions>0?` · claimed ${nl.claimed_sessions} orphan session${nl.claimed_sessions===1?"":"s"}`:"")),ja(""),Da()},onError:nl=>{const ll=nl instanceof ApiError?nl.message:String(nl);ue$1.error(`Assign failed: ${ll}`)}}),Ma=useMutation({mutationFn:nl=>removeUserFromOrg(es,nl),onSuccess:()=>{ue$1.success("Removed from org"),Da()},onError:nl=>{const ll=nl instanceof ApiError?nl.message:String(nl);ue$1.error(`Remove failed: ${ll}`)}}),qa=nl=>ll=>{const fl=ll instanceof ApiError?ll.message:String(ll);ue$1.error(`${nl} failed: ${fl}`)},Fa=useMutation({mutationFn:()=>forceLogoutUser(es),onSuccess:()=>ue$1.success("All sessions revoked"),onError:qa("Force logout")}),Ka=useMutation({mutationFn:()=>resetUserPassword(es),onSuccess:nl=>{nl.actionLink?(navigator.clipboard.writeText(nl.actionLink).catch(()=>{}),ue$1.success(`Recovery link copied for ${nl.email}`)):ue$1.success(`Recovery email sent to ${nl.email}`)},onError:qa("Reset password")}),Ha=useMutation({mutationFn:nl=>setUserSuspended(es,nl),onSuccess:nl=>{ue$1.success(nl.suspended?"User suspended":"User reinstated"),Da()},onError:qa("Suspend")}),[Qa,Va]=reactExports.useState(!1),[Ya,Ja]=reactExports.useState(""),el=useMutation({mutationFn:()=>deleteUser(es,Ya),onSuccess:()=>{ue$1.success("User deleted"),Va(!1),Ja(""),ts.invalidateQueries({queryKey:["superadmin","users"]}),$()},onError:qa("Delete")}),tl=is.data,il=((xl=Kr.data)==null?void 0:xl.orgs)??[],rl=new Set((tl==null?void 0:tl.memberships.map(nl=>nl.orgId))??[]),dl=il.filter(nl=>!rl.has(nl.id));return jsxRuntimeExports.jsxs(Sheet,{open:!0,onOpenChange:nl=>!nl&&$(),children:[jsxRuntimeExports.jsxs(SheetContent,{side:"right",className:"w-full sm:max-w-md overflow-y-auto",children:[jsxRuntimeExports.jsxs(SheetHeader,{children:[jsxRuntimeExports.jsx(SheetTitle,{className:"font-mono text-base",children:(tl==null?void 0:tl.user.email)??"Loading…"}),jsxRuntimeExports.jsx(SheetDescription,{children:tl?`${tl.sessionCounts.total} sessions, ${tl.sessionCounts.orphan} without an org`:""})]}),jsxRuntimeExports.jsxs("div",{className:"mt-6 space-y-6 px-1",children:[jsxRuntimeExports.jsxs("section",{children:[jsxRuntimeExports.jsx("h3",{className:"mb-2 text-sm font-medium",children:"Current memberships"}),(tl==null?void 0:tl.memberships.length)===0?jsxRuntimeExports.jsx("p",{className:"text-sm text-muted-foreground",children:"Not a member of any org."}):jsxRuntimeExports.jsx("ul",{className:"space-y-1",children:tl==null?void 0:tl.memberships.map(nl=>jsxRuntimeExports.jsxs("li",{className:"flex items-center justify-between rounded-md border px-3 py-2 text-sm",children:[jsxRuntimeExports.jsxs("div",{children:[jsxRuntimeExports.jsx("div",{className:"font-medium",children:nl.orgName}),jsxRuntimeExports.jsx("div",{className:"text-xs text-muted-foreground",children:nl.orgSlug})]}),jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(Badge,{variant:"secondary",children:nl.role}),jsxRuntimeExports.jsx(Button,{size:"icon",variant:"ghost",disabled:Ma.isPending,onClick:()=>Ma.mutate(nl.orgId),"aria-label":"Remove from org",children:jsxRuntimeExports.jsx(X$1,{className:"h-4 w-4"})})]})]},nl.orgId))})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-2 rounded-md border p-3",children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-medium",children:"Account actions"}),(tl==null?void 0:tl.user.banned)&&jsxRuntimeExports.jsx(Badge,{variant:"destructive",children:"Suspended"})]}),(tl==null?void 0:tl.user.lastSignInAt)&&jsxRuntimeExports.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sign-in: ",new Date(tl.user.lastSignInAt).toLocaleString()]}),jsxRuntimeExports.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:Ka.isPending,onClick:()=>Ka.mutate(),children:Ka.isPending?"Generating…":"Reset password"}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:Fa.isPending,onClick:()=>Fa.mutate(),children:Fa.isPending?"Revoking…":"Force logout"}),jsxRuntimeExports.jsx(Button,{variant:"outline",size:"sm",disabled:Ha.isPending,onClick:()=>Ha.mutate(!(tl!=null&&tl.user.banned)),children:Ha.isPending?"Updating…":tl!=null&&tl.user.banned?"Reinstate":"Suspend"}),jsxRuntimeExports.jsx(Button,{variant:"destructive",size:"sm",onClick:()=>Va(!0),children:"Delete user"})]})]}),jsxRuntimeExports.jsxs("section",{className:"space-y-3 rounded-md border p-3",children:[jsxRuntimeExports.jsx("h3",{className:"text-sm font-medium",children:"Add to org"}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsxs(Select,{value:Qr,onValueChange:ja,children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{placeholder:"Choose an org…"})}),jsxRuntimeExports.jsx(SelectContent,{children:dl.length===0?jsxRuntimeExports.jsx("div",{className:"p-2 text-sm text-muted-foreground",children:"No orgs available (already a member of all)."}):dl.map(nl=>jsxRuntimeExports.jsxs(SelectItem,{value:nl.id,children:[nl.name," ",jsxRuntimeExports.jsxs("span",{className:"text-muted-foreground",children:["(",nl.memberCount,")"]})]},nl.id))})]}),jsxRuntimeExports.jsxs(Select,{value:Ca,onValueChange:nl=>Aa(nl),children:[jsxRuntimeExports.jsx(SelectTrigger,{children:jsxRuntimeExports.jsx(SelectValue,{})}),jsxRuntimeExports.jsxs(SelectContent,{children:[jsxRuntimeExports.jsx(SelectItem,{value:"owner",children:"owner"}),jsxRuntimeExports.jsx(SelectItem,{value:"admin",children:"admin"}),jsxRuntimeExports.jsx(SelectItem,{value:"member",children:"member"})]})]}),jsxRuntimeExports.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[jsxRuntimeExports.jsx("input",{type:"checkbox",checked:Oa,onChange:nl=>Ia(nl.target.checked),className:"h-4 w-4"}),"Claim ",(tl==null?void 0:tl.sessionCounts.orphan)??0," orphan session",(tl==null?void 0:tl.sessionCounts.orphan)===1?"":"s"," for this org"]}),jsxRuntimeExports.jsx(Button,{disabled:!Qr||Ba.isPending,onClick:()=>Ba.mutate(),className:"w-full",children:Ba.isPending?"Assigning…":"Assign"})]})]})]})]}),jsxRuntimeExports.jsx(Dialog,{open:Qa,onOpenChange:Va,children:jsxRuntimeExports.jsxs(DialogContent,{children:[jsxRuntimeExports.jsxs(DialogHeader,{children:[jsxRuntimeExports.jsx(DialogTitle,{children:"Delete user"}),jsxRuntimeExports.jsxs(DialogDescription,{children:["This permanently deletes the auth user and cascades all their sessions and memberships. Type"," ",jsxRuntimeExports.jsx("span",{className:"font-mono",children:(tl==null?void 0:tl.user.email)??"—"})," to confirm."]})]}),jsxRuntimeExports.jsx(Input,{value:Ya,onChange:nl=>Ja(nl.target.value),placeholder:(tl==null?void 0:tl.user.email)??"",autoComplete:"off"}),jsxRuntimeExports.jsxs(DialogFooter,{children:[jsxRuntimeExports.jsx(Button,{variant:"outline",onClick:()=>Va(!1),children:"Cancel"}),jsxRuntimeExports.jsx(Button,{variant:"destructive",disabled:!(tl!=null&&tl.user.email)||Ya.toLowerCase()!==tl.user.email.toLowerCase()||el.isPending,onClick:()=>el.mutate(),children:el.isPending?"Deleting…":"Delete permanently"})]})]})})]})}function SuperAdminGuard({children:es}){const{profile:$,isLoading:ts}=useActiveOrg();return ts?jsxRuntimeExports.jsx("div",{className:"flex h-full items-center justify-center p-8",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"})]})}):$!=null&&$.isSuperadmin?jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment,{children:es??jsxRuntimeExports.jsx(Outlet,{})}):jsxRuntimeExports.jsx(Navigate,{to:"/dashboard",replace:!0})}const SLUG_REGEX=/^(?=.{3,40}$)[a-z0-9]+(?:-[a-z0-9]+)*$/;function slugify(es){return es.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,40)}function NewOrgPage(){const es=useNavigate(),$=useSetActiveOrg(),[ts,is]=reactExports.useState(""),[Kr,Qr]=reactExports.useState(""),[ja,Ca]=reactExports.useState(!1),[Aa,Oa]=reactExports.useState(null),[Ia,Da]=reactExports.useState(null),Ba=useMutation({mutationFn:Ka=>createOrg(Ka),onSuccess:async Ka=>{try{await $.mutateAsync(Ka.id)}catch{}ue$1.success(`Created ${Ka.name}`),es("/admin",{replace:!0})},onError:Ka=>{if(Ka instanceof ApiError&&Ka.code==="ORG_SLUG_TAKEN"){const Ha=Kr.replace(/-\d+$/,""),Qa=(()=>{const Ya=Kr.match(/-(\d+)$/);return Ya?Number(Ya[1])+1:2})(),Va=`${Ha}-${Qa}`.slice(0,40);Da(Va),Oa("That slug is already taken.");return}if(Ka instanceof ApiError&&Ka.code==="VALIDATION_ERROR"){Oa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}ue$1.error(Ka instanceof Error?Ka.message:"Failed to create organization")}});function Ma(Ka){is(Ka),ja||Qr(slugify(Ka))}function qa(Ka){Ka.preventDefault(),Oa(null),Da(null);const Ha=ts.trim(),Qa=Kr.trim();if(!Ha){Oa("Name is required.");return}if(Ha.length>100){Oa("Name must be 100 characters or fewer.");return}if(!SLUG_REGEX.test(Qa)){Oa("Slug must be lowercase letters, numbers, and dashes (3–40 chars).");return}Ba.mutate({name:Ha,slug:Qa})}function Fa(){Ia&&(Qr(Ia),Ca(!0),Da(null),Oa(null))}return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 py-12 bg-background",children:jsxRuntimeExports.jsxs("div",{className:"w-full max-w-md space-y-4",children:[jsxRuntimeExports.jsx(Button,{variant:"ghost",size:"sm",asChild:!0,className:"cursor-pointer -ml-2",children:jsxRuntimeExports.jsxs(Link,{to:"/dashboard",children:[jsxRuntimeExports.jsx(ArrowLeft,{className:"mr-2 h-4 w-4"}),"Back to dashboard"]})}),jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(Building2,{className:"h-5 w-5 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"New organization"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:"Create organization"}),jsxRuntimeExports.jsx(CardDescription,{children:"You'll be the owner. Your existing personal sessions stay where they are — only sessions captured after you switch to this org will be attributed to it."})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsxs("form",{onSubmit:qa,className:"space-y-4",children:[jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-name",children:"Name"}),jsxRuntimeExports.jsx(Input,{id:"org-name",value:ts,onChange:Ka=>Ma(Ka.target.value),placeholder:"Acme Inc.",required:!0,maxLength:100,disabled:Ba.isPending,autoFocus:!0})]}),jsxRuntimeExports.jsxs("div",{className:"space-y-2",children:[jsxRuntimeExports.jsx(Label,{htmlFor:"org-slug",children:"Slug"}),jsxRuntimeExports.jsx(Input,{id:"org-slug",value:Kr,onChange:Ka=>{Qr(Ka.target.value),Ca(!0)},placeholder:"acme",required:!0,disabled:Ba.isPending}),jsxRuntimeExports.jsx("p",{className:"text-xs text-muted-foreground",children:"Lowercase letters, numbers, and dashes. Used in URLs and CLI commands."})]}),Aa&&jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive space-y-1",children:[jsxRuntimeExports.jsx("div",{children:Aa}),Ia&&jsxRuntimeExports.jsxs("div",{children:["Try"," ",jsxRuntimeExports.jsx("button",{type:"button",onClick:Fa,className:"font-mono underline cursor-pointer",children:Ia}),"?"]})]}),jsxRuntimeExports.jsx(Button,{type:"submit",disabled:Ba.isPending,className:"w-full cursor-pointer",children:Ba.isPending?"Creating…":"Create organization"})]})})]})]})})}function AcceptInvitationPage(){const{token:es}=useParams(),{session:$,loading:ts}=useAuth(),is=useNavigate(),Kr=useSetActiveOrg(),Qr=useQuery({queryKey:["invitation-preview",es,($==null?void 0:$.user.id)??null],queryFn:()=>previewInvitation(es),enabled:!!es&&!ts,retry:!1}),[ja,Ca]=reactExports.useState(!1),Aa=useMutation({mutationFn:()=>{var Da;return acceptInvitation({token:es,acknowledgedSessionCount:((Da=Qr.data)==null?void 0:Da.sessionCount)??0})},onMutate:()=>{Ca(!0)},onSuccess:async Da=>{var Ba;try{await Kr.mutateAsync(Da.orgId)}catch{}ue$1.success(`Joined ${((Ba=Qr.data)==null?void 0:Ba.orgName)??"the organization"}`),is("/admin",{replace:!0})},onError:async Da=>{if(Ca(!1),Da instanceof ApiError){if(Da.code==="ALREADY_MEMBER"){ue$1.success("You're already a member. Taking you there now."),is("/admin",{replace:!0});return}if(Da.code==="INVITE_EMAIL_MISMATCH"){ue$1.error("This invitation was sent to a different email address. Sign out and sign in with the correct email to accept.");return}if(Da.code==="SESSION_COUNT_CHANGED"){await Qr.refetch(),ue$1.error("Your session count changed since you reviewed the consent notice. Please re-confirm.");return}if(Da.code==="INVITE_GONE"||Da.code==="INVITE_NOT_FOUND"){ue$1.error("This invitation is no longer valid.");return}}ue$1.error(Da instanceof Error?Da.message:"Failed to accept invitation")}}),Oa=Qr.error,Ia=Oa instanceof ApiError&&(Oa.code==="INVITE_GONE"||Oa.code==="INVITE_NOT_FOUND"||Oa.statusCode===410||Oa.statusCode===404);return reactExports.useEffect(()=>{Aa.isSuccess&&Ca(!1)},[Aa.isSuccess]),jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center px-4 py-12 bg-background",children:jsxRuntimeExports.jsx("div",{className:"w-full max-w-md",children:es?ts||Qr.isLoading?jsxRuntimeExports.jsx(LoadingCard$1,{}):Ia?jsxRuntimeExports.jsx(GoneCard,{message:"This invitation is no longer valid. It may have been revoked, expired, or already accepted."}):Oa?jsxRuntimeExports.jsx(ErrorCard,{message:Oa.message}):Qr.data?jsxRuntimeExports.jsx(InvitationCard,{preview:Qr.data,token:es,isSignedIn:!!$,accepting:ja||Aa.isPending,onAccept:()=>Aa.mutate()}):jsxRuntimeExports.jsx(LoadingCard$1,{}):jsxRuntimeExports.jsx(GoneCard,{message:"Missing invitation token in URL."})})})}function LoadingCard$1(){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-5 w-32"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-8 w-48 mt-2"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-full mt-2"})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx(Skeleton,{className:"h-4 w-3/4"}),jsxRuntimeExports.jsx(Skeleton,{className:"h-10 w-full"})]})]})}function GoneCard({message:es}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-5 w-5 text-destructive"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-destructive",children:"Invitation unavailable"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-xl font-mono",children:"This invitation is no longer valid"}),jsxRuntimeExports.jsx(CardDescription,{children:es})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"w-full cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/",children:"Back home"})})})]})}function ErrorCard({message:es}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-5 w-5 text-destructive"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-destructive",children:"Couldn't load invitation"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-xl font-mono",children:"Something went wrong"}),jsxRuntimeExports.jsx(CardDescription,{children:es})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"w-full cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:"/",children:"Back home"})})})]})}function InvitationCard({preview:es,token:$,isSignedIn:ts,accepting:is,onAccept:Kr}){const Qr=`/invite/${encodeURIComponent($)}`;return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[jsxRuntimeExports.jsx(Building2,{className:"h-5 w-5 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"Organization invitation"})]}),jsxRuntimeExports.jsx(CardTitle,{className:"text-2xl font-mono",children:es.orgName}),jsxRuntimeExports.jsx(CardDescription,{className:"space-y-2",children:jsxRuntimeExports.jsx("span",{className:"block",children:es.inviterName?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx("strong",{children:es.inviterName})," invited you to join"," ",jsxRuntimeExports.jsx("strong",{children:es.orgName})," as"," ",jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"capitalize ml-1",children:es.role})]}):jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:["You've been invited to join ",jsxRuntimeExports.jsx("strong",{children:es.orgName})," ","as"," ",jsxRuntimeExports.jsx(Badge,{variant:"outline",className:"capitalize ml-1",children:es.role})]})})})]}),jsxRuntimeExports.jsx(CardContent,{className:"space-y-4",children:ts?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(ConsentNotice,{orgName:es.orgName,sessionCount:es.sessionCount}),jsxRuntimeExports.jsxs(Button,{type:"button",onClick:Kr,disabled:is,className:"w-full cursor-pointer",children:[jsxRuntimeExports.jsx(UserCheck,{className:"mr-2 h-4 w-4"}),is?"Joining…":`Accept and join ${es.orgName}`]})]}):jsxRuntimeExports.jsxs("div",{className:"space-y-3",children:[jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border bg-muted/50 px-4 py-3 text-sm",children:"Sign in or sign up with the email this invitation was sent to, and we'll bring you back here to accept."}),jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"default",className:"flex-1 cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:`/login?next=${encodeURIComponent(Qr)}`,children:"Sign in"})}),jsxRuntimeExports.jsx(Button,{asChild:!0,variant:"outline",className:"flex-1 cursor-pointer",children:jsxRuntimeExports.jsx(Link,{to:`/signup?next=${encodeURIComponent(Qr)}`,children:"Sign up"})})]})]})})]})}function ConsentNotice({orgName:es,sessionCount:$}){return $===null?jsxRuntimeExports.jsx("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/10 px-4 py-3 text-sm",children:jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(ShieldAlert,{className:"h-4 w-4 mt-0.5 shrink-0"}),jsxRuntimeExports.jsx("div",{children:"You're signed in with a different email than this invitation was sent to. Sign out and sign in with the matching email to accept."})]})}):$===0?jsxRuntimeExports.jsxs("div",{className:"rounded-md border border-border bg-muted/40 px-4 py-3 text-sm text-muted-foreground",children:["Accepting will give you ",es," access. You don't have any existing sessions, so nothing will be retroactively shared."]}):jsxRuntimeExports.jsx("div",{className:"rounded-md border border-border bg-muted/40 px-4 py-3 text-sm",children:jsxRuntimeExports.jsxs("div",{className:"flex gap-2",children:[jsxRuntimeExports.jsx(ShieldAlert,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),jsxRuntimeExports.jsxs("div",{children:["By accepting, all of your existing personal RuleMetric sessions"," (","at least"," ",jsxRuntimeExports.jsx("strong",{className:"font-mono tabular-nums",children:$}),$===1?" session":" sessions"," as of now",") will become visible to ",jsxRuntimeExports.jsx("strong",{children:es})," admins."]})]})})}const API_BASE="";async function fetchUnsubscribePreview(es){const $=await fetch(`${API_BASE}/api/unsubscribe/${encodeURIComponent(es)}`);if($.status===404){const ts=new Error("invalid_token");throw ts.statusCode=404,ts}if(!$.ok)throw new Error(`HTTP ${$.status}`);return await $.json()}async function postUnsubscribe(es){const $=await fetch(`${API_BASE}/api/unsubscribe/${encodeURIComponent(es)}`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!$.ok){const ts=new Error(`HTTP ${$.status}`);throw ts.statusCode=$.status,ts}}function UnsubscribePage(){const{token:es}=useParams(),[$,ts]=reactExports.useState(!1),is=useQuery({queryKey:["unsubscribe-preview",es],queryFn:()=>fetchUnsubscribePreview(es),enabled:!!es,retry:!1}),Kr=useMutation({mutationFn:()=>postUnsubscribe(es),onSuccess:()=>ts(!0)});return jsxRuntimeExports.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background px-4 py-12",children:jsxRuntimeExports.jsx("div",{className:"w-full max-w-md",children:es?is.isLoading?jsxRuntimeExports.jsx(LoadingCard,{}):is.error?jsxRuntimeExports.jsx(InvalidCard,{}):is.data?$?jsxRuntimeExports.jsx(UnsubscribedCard,{justConfirmed:!0}):is.data.alreadyUnsubscribed?jsxRuntimeExports.jsx(UnsubscribedCard,{}):jsxRuntimeExports.jsx(ConfirmCard,{onConfirm:()=>Kr.mutate(),pending:Kr.isPending,error:Kr.error?"Failed to unsubscribe. Please try again.":null}):jsxRuntimeExports.jsx(LoadingCard,{}):jsxRuntimeExports.jsx(InvalidCard,{})})})}function LoadingCard(){return jsxRuntimeExports.jsx(Card,{children:jsxRuntimeExports.jsx(CardHeader,{children:jsxRuntimeExports.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"h-5 w-5 animate-spin text-muted-foreground"}),jsxRuntimeExports.jsx(CardTitle,{className:"text-lg",children:"Loading…"})]})})})}function InvalidCard(){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(TriangleAlert,{className:"h-5 w-5 text-destructive"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-destructive",children:"Link invalid"})]}),jsxRuntimeExports.jsx(CardTitle,{children:"This unsubscribe link is invalid or expired"}),jsxRuntimeExports.jsx(CardDescription,{children:"The unsubscribe link you used isn't recognized. It may have been truncated by your email client, or the preference may have been reset."})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Link,{to:"/",className:"text-sm text-primary underline",children:"Return to RuleMetric"})})]})}function ConfirmCard({onConfirm:es,pending:$,error:ts}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(Bell,{className:"h-5 w-5 text-muted-foreground"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-muted-foreground",children:"Product announcements"})]}),jsxRuntimeExports.jsx(CardTitle,{children:"Unsubscribe from RuleMetric product announcements?"}),jsxRuntimeExports.jsx(CardDescription,{children:"You won't receive product update emails from us anymore. You'll still receive transactional emails like sign-in links, invitations, and security alerts."})]}),jsxRuntimeExports.jsxs(CardContent,{className:"space-y-3",children:[jsxRuntimeExports.jsx(Button,{onClick:es,disabled:$,className:"w-full",variant:"destructive",children:$?jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(LoaderCircle,{className:"mr-2 h-4 w-4 animate-spin"}),"Unsubscribing…"]}):"Confirm unsubscribe"}),ts?jsxRuntimeExports.jsx("p",{className:"text-sm text-destructive",role:"alert",children:ts}):null,jsxRuntimeExports.jsx(Link,{to:"/",className:"block text-center text-sm text-muted-foreground underline",children:"Cancel"})]})]})}function UnsubscribedCard({justConfirmed:es=!1}){return jsxRuntimeExports.jsxs(Card,{children:[jsxRuntimeExports.jsxs(CardHeader,{children:[jsxRuntimeExports.jsxs("div",{className:"mb-2 flex items-center gap-2",children:[jsxRuntimeExports.jsx(CircleCheck,{className:"h-5 w-5 text-teal-500"}),jsxRuntimeExports.jsx("span",{className:"font-mono text-sm font-medium text-teal-600",children:"Unsubscribed"})]}),jsxRuntimeExports.jsx(CardTitle,{children:es?"You've been unsubscribed":"You're already unsubscribed"}),jsxRuntimeExports.jsx(CardDescription,{children:es?"You'll still receive transactional emails (sign-in, invitations, security alerts).":"You're already off the product-announcements list. You'll still receive transactional emails (sign-in, invitations, security alerts)."})]}),jsxRuntimeExports.jsx(CardContent,{children:jsxRuntimeExports.jsx(Link,{to:"/",className:"text-sm text-primary underline",children:"Return to RuleMetric"})})]})}function NotFoundPage(){return jsxRuntimeExports.jsxs("div",{className:"flex min-h-screen flex-col items-center justify-center gap-4",children:[jsxRuntimeExports.jsx("h1",{className:"text-4xl font-bold",children:"404"}),jsxRuntimeExports.jsx("p",{className:"text-muted-foreground",children:"Page not found"}),jsxRuntimeExports.jsx(Button,{asChild:!0,children:jsxRuntimeExports.jsx(Link,{to:"/dashboard",children:"Go to Dashboard"})})]})}const queryClient=new QueryClient({defaultOptions:{queries:{staleTime:3e4,retry:1}}});function App(){const es=useRunsEnabled();return jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx(QueryClientProvider,{client:queryClient,children:jsxRuntimeExports.jsxs(AuthProvider,{children:[jsxRuntimeExports.jsx(BrowserRouter,{children:jsxRuntimeExports.jsx(PostHogProvider,{children:jsxRuntimeExports.jsxs(Routes,{children:[jsxRuntimeExports.jsx(Route,{path:"/",element:jsxRuntimeExports.jsx(LandingPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/login",element:jsxRuntimeExports.jsx(LoginPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/signup",element:jsxRuntimeExports.jsx(SignupPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/auth/confirm",element:jsxRuntimeExports.jsx(ConfirmPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/auth/extension",element:jsxRuntimeExports.jsx(ExtensionAuthPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/forgot-password",element:jsxRuntimeExports.jsx(ForgotPasswordPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/reset-password",element:jsxRuntimeExports.jsx(ResetPasswordPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/invite/:token",element:jsxRuntimeExports.jsx(AcceptInvitationPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/unsubscribe/:token",element:jsxRuntimeExports.jsx(UnsubscribePage,{})}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(AuthGuard,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/orgs/new",element:jsxRuntimeExports.jsx(NewOrgPage,{})}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(RootLayout,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/dashboard",element:jsxRuntimeExports.jsx(DashboardPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/import",element:jsxRuntimeExports.jsx(ImportWizardPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/connect",element:jsxRuntimeExports.jsx(ConnectPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/sessions",element:jsxRuntimeExports.jsx(SessionsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/sessions/:id",element:jsxRuntimeExports.jsx(SessionDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/projects",element:jsxRuntimeExports.jsx(ProjectsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/projects/:id",element:jsxRuntimeExports.jsx(ProjectDetailPage,{})}),es,jsxRuntimeExports.jsx(Route,{path:"/eval-targets",element:jsxRuntimeExports.jsx(EvalTargetsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/eval-targets/:id",element:jsxRuntimeExports.jsx(EvalTargetDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/insights",element:jsxRuntimeExports.jsx(InsightsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/insights/:id",element:jsxRuntimeExports.jsx(InsightsDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/memories",element:jsxRuntimeExports.jsx(MemoriesListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/memories/:id",element:jsxRuntimeExports.jsx(MemoryDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/skills",element:jsxRuntimeExports.jsx(SkillsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/catalog/public",element:jsxRuntimeExports.jsx(PublicCatalogPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/catalog/public/:id",element:jsxRuntimeExports.jsx(PublicSkillDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/suggestions",element:jsxRuntimeExports.jsx(SuggestionsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/experiments",element:jsxRuntimeExports.jsx(ExperimentsListPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/loop",element:jsxRuntimeExports.jsx(LoopPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/settings",element:jsxRuntimeExports.jsx(SettingsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/usage",element:jsxRuntimeExports.jsx(UsagePage,{})}),jsxRuntimeExports.jsx(Route,{path:"/docs",element:jsxRuntimeExports.jsx(DocsPage,{})}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(SuperAdminGuard,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/superadmin",element:jsxRuntimeExports.jsx(Navigate,{to:"/superadmin/users",replace:!0})}),jsxRuntimeExports.jsx(Route,{path:"/superadmin/users",element:jsxRuntimeExports.jsx(SuperadminUsersPage,{})})]}),jsxRuntimeExports.jsxs(Route,{element:jsxRuntimeExports.jsx(OrgAdminGuard,{}),children:[jsxRuntimeExports.jsx(Route,{path:"/admin",element:jsxRuntimeExports.jsx(AdminOverviewPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/members",element:jsxRuntimeExports.jsx(AdminMembersPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/members/invitations",element:jsxRuntimeExports.jsx(AdminInvitationsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/teams",element:jsxRuntimeExports.jsx(AdminTeamsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/teams/:teamSlug",element:jsxRuntimeExports.jsx(TeamDetailPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/settings",element:jsxRuntimeExports.jsx(AdminSettingsPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/research",element:jsxRuntimeExports.jsx(AdminResearchPage,{})}),jsxRuntimeExports.jsx(Route,{path:"/admin/announcements",element:jsxRuntimeExports.jsx(AdminAnnouncementsPage,{})})]})]})]}),jsxRuntimeExports.jsx(Route,{path:"*",element:jsxRuntimeExports.jsx(NotFoundPage,{})})]})})}),jsxRuntimeExports.jsx(Toaster,{})]})})})}"serviceWorker"in navigator&&window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js").catch(es=>{console.error("Service worker registration failed:",es)})});clientExports.createRoot(document.getElementById("root")).render(jsxRuntimeExports.jsx(reactExports.StrictMode,{children:jsxRuntimeExports.jsx(App,{})}));