claude-code-session-manager 0.138.0 → 0.139.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.
Files changed (91) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +339 -82
  3. package/dist/assets/{AppSettings-CgDhqrsU.js → AppSettings-CUfWY9vN.js} +2 -2
  4. package/dist/assets/History-DDnqaLyw.js +2 -0
  5. package/dist/assets/HomeClaudeConfig-CGD2Onjv.js +3 -0
  6. package/dist/assets/{Panel-CeDiyuNn.js → Panel-Csyd9HbD.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-C-jlYpC_.js +26 -0
  8. package/dist/assets/{Scheduler-CkhTvG7C.js → Scheduler-NLs08fx7.js} +9 -9
  9. package/dist/assets/{SkillReferenceGraph-CFMK8NJh.js → SkillReferenceGraph-DcscPXAG.js} +1 -1
  10. package/dist/assets/Skills-BpGRKOcY.js +67 -0
  11. package/dist/assets/{TiptapBody-D1kTj-tn.js → TiptapBody-DSU3769X.js} +60 -54
  12. package/dist/assets/ViewTabs-C0PRZx4_.js +1 -0
  13. package/dist/assets/{VoiceButton-CZeyPM31.js → VoiceButton-D2rMurNg.js} +1 -1
  14. package/dist/assets/{historyTotals-B00l64Jw.js → historyTotals-TcIQs2sh.js} +1 -1
  15. package/dist/assets/{index-62tyjEQB.css → index-BCySPdtU.css} +1 -1
  16. package/dist/assets/{index-CgCxpunJ.js → index-C-d0DCre.js} +523 -515
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +469 -450
  20. package/package.json +13 -5
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
  23. package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +12 -5
  25. package/scripts/README.md +1 -0
  26. package/scripts/scheduler-mcp-server.cjs +161 -18
  27. package/src/main/build-info.json +4 -4
  28. package/src/main/chatRunner.cjs +2 -2
  29. package/src/main/exchanges.cjs +70 -5
  30. package/src/main/historyAggregator.cjs +84 -58
  31. package/src/main/historyDashboard.cjs +18 -13
  32. package/src/main/index.cjs +22 -2
  33. package/src/main/ipcSchemas.cjs +122 -5
  34. package/src/main/lib/claude/effectiveModelInfo.cjs +2 -2
  35. package/src/main/lib/claude/modelPricing.cjs +148 -0
  36. package/src/main/lib/epic/epicAdminRoutes.cjs +101 -0
  37. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  38. package/src/main/lib/epic/epicOutsideRead.cjs +306 -0
  39. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  40. package/src/main/lib/epic/epicSettle.cjs +1 -1
  41. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  42. package/src/main/lib/epic/externalRef.cjs +37 -0
  43. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  44. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  45. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  46. package/src/main/lib/externalContract.cjs +111 -0
  47. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +121 -4
  48. package/src/main/lib/feedback-remote/crossProjectReply.cjs +83 -1
  49. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  50. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  51. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  52. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  53. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  54. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  55. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +120 -2
  56. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  57. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  58. package/src/main/lib/feedback-remote/needsYouStore.cjs +281 -0
  59. package/src/main/lib/historyRollup.cjs +32 -5
  60. package/src/main/lib/mcpToolCatalog.cjs +111 -14
  61. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  62. package/src/main/lib/promptSessionSchema.cjs +4 -0
  63. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  64. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  65. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  66. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  67. package/src/main/loopEfficiencyHandlers.cjs +1 -1
  68. package/src/main/scheduler.cjs +29 -0
  69. package/src/main/templates/PRD_AUTHORING.md +1 -0
  70. package/src/main/transcripts.cjs +62 -7
  71. package/src/main/webRemote.cjs +122 -18
  72. package/src/preload/api.d.ts +71 -8
  73. package/src/preload/apiSurface.cjs +7 -0
  74. package/src/preload/apiSurface.json +408 -83
  75. package/src/preload/index.cjs +15 -3
  76. package/dist/assets/AgentLibrary-C1d_D7uQ.js +0 -2
  77. package/dist/assets/Button-Bk23rEnZ.js +0 -1
  78. package/dist/assets/DocumentEditorPane-BqY5Nq6W.js +0 -1
  79. package/dist/assets/Extensions-CXem-uwI.js +0 -2
  80. package/dist/assets/History-BwO3coo4.js +0 -2
  81. package/dist/assets/Library-BDV69fSe.js +0 -32
  82. package/dist/assets/ListDetail-CD-Fm6mh.js +0 -1
  83. package/dist/assets/ProjectClaudeConfig-NjdKdwe8.js +0 -25
  84. package/dist/assets/ProvenanceBadge-Bu8NmI_R.js +0 -1
  85. package/dist/assets/Settings-COT34hBF.js +0 -2
  86. package/dist/assets/Skills-BgexoUkQ.js +0 -29
  87. package/dist/assets/SourceChip-BXjcdeb1.js +0 -1
  88. package/dist/assets/SystemPrompt-CeeH3EeW.js +0 -1
  89. package/dist/assets/Toggle-CENi19iK.js +0 -1
  90. package/dist/assets/ViewTabs-DDBb0x96.js +0 -1
  91. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
@@ -0,0 +1,2 @@
1
+ import{aM as fe,aU as Ye,bF as ze,aB as e,aR as h,ba as q,aN as E,aO as O,by as Ve,bn as Xe,bw as ye,aH as qe,bm as Qe,m as Ze}from"./index-C-d0DCre.js";import{P as Je}from"./Panel-Csyd9HbD.js";import{p as De,i as B,m as Ee,t as I,u as $,f as et}from"./historyTotals-TcIQs2sh.js";import"./monaco-editor-BsIlgG7c.js";function re(){return{promptCount:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,toolCallCount:0,sessionCount:0,errorCount:0,activeMinutes:0,estimatedCostUsd:0}}function Te(t,s){t.promptCount+=s.promptCount,t.inputTokens+=s.inputTokens,t.outputTokens+=s.outputTokens,t.cacheReadTokens+=s.cacheReadTokens,t.cacheCreationTokens+=s.cacheCreationTokens,t.toolCallCount+=s.toolCallCount,t.sessionCount+=s.sessionCount,t.errorCount+=s.errorCount,t.activeMinutes+=s.activeMinutes,t.estimatedCostUsd+=s.estimatedCostUsd}function tt(t){return t.promptCount>0||t.sessionCount>0||t.toolCallCount>0||t.inputTokens>0||t.outputTokens>0}function st(t,s){const o=s===null,a=[],n=re(),r={},c={};let i=0;for(const u of t.days){const d=re();let l=!1;for(const[p,m]of Object.entries(u.byProject)){if(!o&&!s.has(p))continue;Te(d,m),Te(n,m),tt(m)&&(l=!0);for(const[v,k]of Object.entries(m.byModel)){const x=r[v]??(r[v]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});x.inputTokens+=k.inputTokens,x.outputTokens+=k.outputTokens,x.cacheReadTokens+=k.cacheReadTokens,x.cacheCreationTokens+=k.cacheCreationTokens,x.costUsd+=k.costUsd,k.estimated&&(x.estimated=!0)}const T=m.byLauncher??{};for(const[v,k]of Object.entries(T)){const x=c[v]??(c[v]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,sessionCount:0});x.inputTokens+=k.inputTokens,x.outputTokens+=k.outputTokens,x.cacheReadTokens+=k.cacheReadTokens,x.cacheCreationTokens+=k.cacheCreationTokens,x.costUsd+=k.costUsd,x.sessionCount+=k.sessionCount}}l&&(i+=1),a.push({date:u.date,totals:d})}return{days:a,totals:n,prevTotals:o?t.prevTotals:re(),prevAvailable:o,byModelTotals:r,byLauncherTotals:c,activeDays:i}}function Ue(t,s){if(!s)return{pct:null,direction:"flat"};const o=(t-s)/s*100,a=o>0?"up":o<0?"down":"flat";return{pct:o,direction:a}}function nt(t,s,o){return s<=0?0:t/s*o}const ot=["promptCount","inputTokens","outputTokens","cacheReadTokens","cacheCreationTokens","toolCallCount","sessionCount","errorCount","activeMinutes","estimatedCostUsd"],at=["inputTokens","outputTokens","cacheReadTokens","cacheCreationTokens","costUsd"];function Ce(t){const s={promptCount:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,toolCallCount:0,sessionCount:0,errorCount:0,activeMinutes:0,estimatedCostUsd:0,byModel:{}},o=a=>typeof a=="number"&&Number.isFinite(a)?a:0;for(const a of t){for(const n of ot)s[n]+=o(a[n]);for(const[n,r]of Object.entries(a.byModel??{})){const c=s.byModel[n]??(s.byModel[n]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});for(const i of at)c[i]+=o(r==null?void 0:r[i])}}return s}const Pe={in:"In tokens",out:"Out tokens",total:"Total tokens",prompts:"Prompts",sessions:"Sessions",time:"Time",spend:"Spend"};function D(t,s){const o=t.inputTokens+t.cacheReadTokens+t.cacheCreationTokens;switch(s){case"in":return o;case"out":return t.outputTokens;case"total":return o+t.outputTokens;case"prompts":return t.promptCount;case"sessions":return t.sessionCount;case"time":return t.activeMinutes;case"spend":return t.estimatedCostUsd}}function ct(t,s){const o=D(t.totals,s),a=t.prevAvailable?Ue(o,D(t.prevTotals,s)):null,n=t.days.map(r=>D(r.totals,s));return{value:o,delta:a,series:n}}function Ne(t,s){const o=new Map,a=Math.ceil(t.length/2);t.forEach((c,i)=>{for(const[u,d]of Object.entries(c.byProject)){let l=o.get(u);l||(l={totals:{promptCount:0,inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,toolCallCount:0,sessionCount:0,errorCount:0,activeMinutes:0,estimatedCostUsd:0},toolBreakdown:{},firstHalf:0,secondHalf:0},o.set(u,l)),l.totals.promptCount+=d.promptCount,l.totals.inputTokens+=d.inputTokens,l.totals.outputTokens+=d.outputTokens,l.totals.cacheReadTokens+=d.cacheReadTokens,l.totals.cacheCreationTokens+=d.cacheCreationTokens,l.totals.toolCallCount+=d.toolCallCount,l.totals.sessionCount+=d.sessionCount,l.totals.errorCount+=d.errorCount,l.totals.activeMinutes+=d.activeMinutes,l.totals.estimatedCostUsd+=d.estimatedCostUsd;for(const[m,T]of Object.entries(d.toolBreakdown))l.toolBreakdown[m]=(l.toolBreakdown[m]??0)+T;const p=D(d,s);i<a?l.firstHalf+=p:l.secondHalf+=p}});const n=Array.from(o.entries()).map(([c,i])=>{let u="",d=-1;for(const[l,p]of Object.entries(i.toolBreakdown))p>d&&(d=p,u=l);return{projectDir:c,value:D(i.totals,s),sharePct:0,trend:Ue(i.secondHalf,i.firstHalf),sessions:i.totals.sessionCount,topTool:u}}),r=n.reduce((c,i)=>c+i.value,0);for(const c of n)c.sharePct=r>0?c.value/r*100:0;return n.sort((c,i)=>i.value-c.value)}const rt=["date","cost_usd","input_tokens","output_tokens","cache_write_tokens","cache_read_tokens","total_tokens","cache_hit_pct","num_models","top_model"];function it(t){return/[",\n]/.test(t)?`"${t.replace(/"/g,'""')}"`:t}function we(t){return t.inputTokens+t.outputTokens+t.cacheReadTokens+t.cacheCreationTokens}function lt(t){const s=t.map(o=>{const a=o.inputTokens+o.outputTokens+o.cacheCreationTokens+o.cacheReadTokens,n=o.inputTokens+o.cacheReadTokens+o.cacheCreationTokens,r=n>0?o.cacheReadTokens/n*100:0,c=Object.entries(o.byModel).filter(([,l])=>we(l)>0);let i="",u=-1;for(const[l,p]of c){const m=we(p);m>u&&(u=m,i=l)}return[o.date,o.costUsd.toFixed(4),String(o.inputTokens),String(o.outputTokens),String(o.cacheCreationTokens),String(o.cacheReadTokens),String(a),r.toFixed(1),String(c.length),i?fe(i):""].map(it).join(",")});return[rt.join(","),...s].join(`
2
+ `)}const dt=["epic","job","other"];function ut(t){return t.includes("session-manager-epic-worktrees")?"epic":t.includes("session-manager-job-worktrees")?"job":"other"}const xt={folderCount:0,sessionCount:0,promptCount:0,estimatedCostUsd:0,totalTokens:0};function Ae(t,s,o){const a=t.byLauncher[s]??(t.byLauncher[s]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0,sessionCount:0});a.inputTokens+=o.inputTokens,a.outputTokens+=o.outputTokens,a.cacheReadTokens+=o.cacheReadTokens,a.cacheCreationTokens+=o.cacheCreationTokens,a.costUsd+=o.estimatedCostUsd,a.sessionCount+=o.sessionCount}function ft(t,s,o){t.promptCount+=s.promptCount,t.inputTokens+=s.inputTokens,t.outputTokens+=s.outputTokens,t.cacheReadTokens+=s.cacheReadTokens,t.cacheCreationTokens+=s.cacheCreationTokens,t.toolCallCount+=s.toolCallCount,t.sessionCount+=s.sessionCount,t.errorCount+=s.errorCount,t.activeMinutes+=s.activeMinutes,t.estimatedCostUsd+=s.estimatedCostUsd;for(const[a,n]of Object.entries(s.toolBreakdown??{}))t.toolBreakdown[a]=(t.toolBreakdown[a]??0)+n;for(const[a,n]of Object.entries(s.byModel??{})){const r=t.byModel[a]??(t.byModel[a]={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,costUsd:0});r.inputTokens+=n.inputTokens,r.outputTokens+=n.outputTokens,r.cacheReadTokens+=n.cacheReadTokens,r.cacheCreationTokens+=n.cacheCreationTokens,r.costUsd+=n.costUsd,n.estimated&&(r.estimated=!0)}Ae(t,o,s)}function ht(t,s,o){const a={};for(const[r,c]of Object.entries(t.byModel??{}))a[r]={...c};const n={...t,projectDir:s,toolBreakdown:{...t.toolBreakdown??{}},byModel:a,byLauncher:{}};return Ae(n,o,t),n}function pt(t,s){const o={...xt},a=new Set,n=t.map(r=>{const c={};for(const[i,u]of Object.entries(r.byProject)){const d=s[i];if(!d){a.add(i),o.sessionCount+=u.sessionCount,o.promptCount+=u.promptCount,o.estimatedCostUsd+=u.estimatedCostUsd,o.totalTokens+=u.inputTokens+u.outputTokens;continue}const l=ut(i),p=c[d];p?ft(p,u,l):c[d]=ht(u,d,l)}return{...r,byProject:c}});return o.folderCount=a.size,{days:n,excluded:o}}function mt(t){return t.folderCount>0}function gt(t){const s=[`${t.folderCount} transcript folder${t.folderCount===1?"":"s"} with no resolvable working directory`];return t.sessionCount&&s.push(`${t.sessionCount.toLocaleString()} sessions`),t.promptCount&&s.push(`${t.promptCount.toLocaleString()} prompts`),t.estimatedCostUsd>=.005&&s.push(`$${t.estimatedCostUsd.toFixed(2)}`),`Excluded: ${s.join(" · ")}`}async function he(){return(await Ye()).history??{}}let Re=Promise.resolve();function ue(t){const s=Re.then(async()=>{const o=await he();await ze({history:{...o,...t}})});return Re=s.catch(()=>{}),s}const jt=["in","out","total","prompts","sessions","time","spend"],bt=[{value:30,label:"30d"},{value:60,label:"60d"},{value:90,label:"90d"},{value:0,label:"All time"}];function Me({value:t,options:s,onChange:o}){return e.jsx("div",{className:"flex gap-0.5 p-0.5 rounded bg-bg-elev shadow-[inset_0_0_0_1px_rgba(0,0,0,0.06)] text-[11px]",children:s.map(a=>e.jsx("button",{onClick:()=>o(a.value),className:`px-2 py-1 rounded whitespace-nowrap font-mono ${t===a.value?"bg-bg-hi text-fg shadow-sm":"text-fg-faint hover:text-fg"}`,children:a.label},String(a.value)))})}function kt({measure:t,onMeasure:s,range:o,onRange:a,projectsShown:n,projectsTotal:r,fromDate:c,toDate:i,onRefresh:u,onExport:d,exportDisabled:l}){return e.jsxs("div",{className:"sticky top-0 z-10 border-b border-line px-4 py-2.5 flex flex-wrap items-center gap-3 backdrop-blur-sm",style:{backgroundColor:"rgba(246,239,225,0.93)"},children:[e.jsx(Me,{value:t,options:jt.map(p=>({value:p,label:Pe[p]})),onChange:s}),e.jsx(Me,{value:o,options:bt,onChange:a}),e.jsxs("span",{className:"text-[11px] text-fg-faint font-mono",children:[n," / ",r," projects"]}),e.jsxs("span",{className:"text-[11px] text-fg-faint font-mono",children:[c," → ",i]}),e.jsx("div",{className:"flex-1"}),e.jsx("button",{onClick:u,className:"px-2 py-1 text-[11px] border border-line rounded hover:text-fg hover:bg-bg-hi text-fg-faint",title:"Re-fetch the rollup (no scan)",children:"↻ Refresh"}),e.jsx("button",{onClick:d,disabled:l,className:"px-2 py-1 text-[11px] border border-line rounded hover:text-fg hover:bg-bg-hi text-fg-faint disabled:opacity-40 disabled:pointer-events-none",children:"Export CSV"})]})}const N="rounded-card bg-bg-hi border border-line",vt="#ded2bd",yt="#6f7d52";function R({kicker:t,title:s,right:o}){return e.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider text-accent font-mono",children:t}),e.jsx("h2",{className:"font-serif text-[25px] leading-tight tracking-tight text-fg",children:s})]}),o]})}function Q(t,s){switch(t){case"spend":return $(s);case"in":case"out":case"total":return I(s);case"time":return Ee(s);default:return B(s)}}function Tt({measure:t,headline:s,activeDays:o,projectsTouched:a,totalSessions:n}){const r=o>0?s.value/o:0,c=n>0?s.value/n:0,{delta:i}=s,u=i&&(t==="spend"?i.direction==="down":i.direction==="up"),d=i&&i.direction!=="flat"&&(t==="spend"?i.direction==="up":i.direction==="down"),l=u?"text-delta-good":d?"text-delta-bad":"text-fg-faint";return e.jsxs("div",{className:`${N} p-4`,children:[e.jsx(R,{kicker:"01 · overview",title:Pe[t]}),e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[52px] leading-none font-mono tracking-tight text-fg",children:Q(t,s.value)}),i?e.jsxs("div",{className:`text-xs font-mono mt-2 ${l}`,children:[i.direction==="up"?"▲":i.direction==="down"?"▼":"·"," ",De(Math.abs(i.pct??0))," vs prior period"]}):e.jsx("div",{className:"text-xs text-fg-faint mt-2",children:"no prior window to compare"})]}),e.jsx("div",{className:"flex-1 min-w-0 self-stretch",children:e.jsx(Ct,{series:s.series})})]}),e.jsxs("div",{className:"grid grid-cols-4 gap-3 mt-4 pt-3 border-t border-line",children:[e.jsx(X,{label:"per active day",value:Q(t,r)}),e.jsx(X,{label:"per session",value:Q(t,c)}),e.jsx(X,{label:"active days",value:B(o)}),e.jsx(X,{label:"projects touched",value:B(a)})]})]})}function X({label:t,value:s}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider",children:t}),e.jsx("div",{className:"text-[17px] font-mono tracking-tight text-fg-dim",children:s})]})}function Ct({series:t}){if(t.length<2)return null;const a=Math.max(...t,0),n=Math.min(...t,0),r=a-n||1,c=160/(t.length-1),i=t.map((d,l)=>`${l*c},${48-(d-n)/r*48}`).join(" "),u=`0,48 ${i} 160,48`;return e.jsxs("svg",{viewBox:"0 0 160 48",preserveAspectRatio:"none",className:"w-full h-full min-h-[48px]",children:[e.jsx("polygon",{points:u,fill:"#b85c34",opacity:.15}),e.jsx("polyline",{points:i,fill:"none",stroke:"#b85c34",strokeWidth:1.5,vectorEffect:"non-scaling-stroke"})]})}const Nt=50;function wt({days:t}){const[s,o]=h.useState(Nt),a=h.useRef(!1);h.useEffect(()=>{let d=!1;return he().then(l=>{d||a.current||typeof l.budgetCapUsd=="number"&&Number.isFinite(l.budgetCapUsd)&&l.budgetCapUsd>0&&o(l.budgetCapUsd)}),()=>{d=!0}},[]);const n=d=>{a.current=!0;const l=s;o(d),ue({budgetCapUsd:d}).catch(()=>{o(l),q.error("Couldn't save the budget cap — reverted.")})},{mtdSpend:r,projectedSpend:c}=h.useMemo(()=>{const d=new Date,l=d.toLocaleDateString("en-CA").slice(0,7),p=new Date(d.getFullYear(),d.getMonth()+1,0).getDate(),m=d.getDate();let T=0;for(const v of t)if(v.date.startsWith(l))for(const k of Object.values(v.byProject))T+=k.estimatedCostUsd;return{mtdSpend:T,projectedSpend:nt(T,m,p)}},[t]),i=c>s,u=s>0?Math.min(100,r/s*100):0;return e.jsxs("div",{className:`${N} p-3`,children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h3",{className:"text-[10.5px] uppercase tracking-wider text-fg-faint font-mono",children:"Monthly budget"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-[10px] text-fg-faint",children:["cap",e.jsx("span",{children:"$"}),e.jsx("input",{type:"number",min:1,step:1,value:s,onChange:d=>{const l=Number(d.target.value);Number.isFinite(l)&&l>0&&n(l)},className:"w-16 bg-bg border border-line rounded px-1.5 py-0.5 text-xs text-fg font-mono"})]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs font-mono mb-1.5",children:[e.jsxs("span",{className:"text-fg",children:[$(r)," ",e.jsx("span",{className:"text-fg-faint",children:"month-to-date"})]}),e.jsxs("span",{className:i?"text-delta-bad":"text-fg-dim",children:[$(c)," ",e.jsx("span",{className:"text-fg-faint",children:"projected"})]})]}),e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:`h-full ${i?"bg-delta-bad":"bg-sage"}`,style:{width:`${Math.max(u,u>0?2:0)}%`}})}),e.jsx("div",{className:`text-[10px] mt-1 font-mono ${i?"text-delta-bad":"text-fg-faint"}`,children:i?`projected to exceed $${s.toFixed(0)} cap`:`${u.toFixed(0)}% of $${s.toFixed(0)} cap`})]})}function Rt({chips:t,keep:s,onToggle:o,onIsolate:a,onShowAll:n}){const r=s===null;return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsxs("button",{onClick:n,className:`px-2 py-1 rounded text-[11px] font-mono border ${r?"bg-accent text-white border-accent":"border-line text-fg-faint hover:text-fg hover:bg-bg-hi"}`,children:["show all (",t.length,")"]}),t.map(c=>{const i=r||s.has(c.projectDir);return e.jsxs("button",{onClick:u=>u.shiftKey?a(c.projectDir):o(c.projectDir),title:c.projectDir,className:`inline-flex items-center gap-1.5 px-2 py-1 rounded text-[11px] font-mono border ${i?"border-line text-fg-dim bg-bg-hi":"border-line text-fg-faint opacity-40 hover:opacity-70"}`,children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:E(c.projectDir)}}),O(c.projectDir)]},c.projectDir)})]})}function Mt(t,s){const o=new Map;for(const n of t)for(const[r,c]of Object.entries(n.values))o.set(r,(o.get(r)??0)+c);const a=Array.from(o.entries()).sort((n,r)=>r[1]-n[1]).map(([n])=>n);return t.map(n=>{const r=a.reduce((u,d)=>u+(n.values[d]??0),0);let c=0;const i=a.map(u=>{const d=n.values[u]??0;if(r<=0)return{projectDir:u,value:d,y0:0,y1:0};const l=s==="share"?d/r:d,p=c,m=c+l;return c=m,{projectDir:u,value:d,y0:p,y1:m}});return{date:n.date,bands:i,total:r}})}const ie=720,le=220,de=44,St=20;function $t(t,s){return t==="spend"?$(s):I(s)}function Dt({days:t,measure:s,selected:o,onSelect:a}){const[n,r]=h.useState("absolute"),c=h.useMemo(()=>Mt(t,n),[t,n]),i=h.useMemo(()=>{if(n==="share")return 1;let x=0;for(const j of c)x=Math.max(x,j.total);return x||1},[c,n]),u=ie-de,d=le-St,l=c.length>1?u/(c.length-1):u,p=x=>de+x*l,m=x=>d-x/i*d,T=Math.max(1,Math.ceil(c.length/8)),v=4,k=Array.from({length:v+1},(x,j)=>i/v*j);return e.jsxs("div",{className:`${N} p-4`,children:[e.jsx(R,{kicker:"02 · over time",title:"Trend by project",right:e.jsx("div",{className:"flex border border-line rounded overflow-hidden text-[10px] font-mono",children:["absolute","share"].map(x=>e.jsx("button",{onClick:()=>r(x),className:`px-2 py-0.5 ${n===x?"bg-accent text-white":"text-fg-faint hover:text-fg"}`,children:x},x))})}),e.jsxs("svg",{width:"100%",viewBox:`0 0 ${ie} ${le}`,className:"overflow-visible",children:[k.map((x,j)=>e.jsxs("g",{children:[e.jsx("line",{x1:de,x2:ie,y1:m(x),y2:m(x),stroke:"currentColor",className:"text-line",strokeWidth:1}),e.jsx("text",{x:0,y:m(x)+3,fontSize:9,className:"fill-fg-faint",children:n==="share"?`${Math.round(x*100)}%`:$t(s,x)})]},j)),c.map((x,j)=>{if(j===0)return null;const U=c[j-1];return x.bands.map((g,J)=>{const G=U.bands[J],W=o!==null&&o!==g.projectDir,ee=W?vt:E(g.projectDir),te=[`${p(j-1)},${m(G.y0)}`,`${p(j)},${m(g.y0)}`,`${p(j)},${m(g.y1)}`,`${p(j-1)},${m(G.y1)}`].join(" ");return e.jsx("polygon",{points:te,fill:ee,opacity:W?.6:.75,className:"cursor-pointer",onClick:()=>a(o===g.projectDir?null:g.projectDir),children:e.jsx("title",{children:O(g.projectDir)})},`${g.projectDir}-${j}`)})}),c.map((x,j)=>j%T!==0&&j!==c.length-1?null:e.jsx("text",{x:p(j),y:le-4,fontSize:9,textAnchor:"middle",className:"fill-fg-faint",children:x.date.slice(5)},x.date))]})]})}function Et({rows:t,measure:s,selected:o,onSelect:a}){return t.length?e.jsxs("div",{className:`${N} overflow-hidden`,children:[e.jsx("div",{className:"p-4 pb-0",children:e.jsx(R,{kicker:"03 · by project",title:"Ranking"})}),e.jsxs("table",{className:"w-full text-xs",children:[e.jsx("thead",{className:"bg-bg-elev",children:e.jsx("tr",{children:["project","share","value","share %","trend","sessions","top tool"].map(n=>e.jsx("th",{className:"text-left px-3 py-2 text-fg-faint uppercase tracking-wider whitespace-nowrap",children:n},n))})}),e.jsx("tbody",{children:t.map(n=>{const r=E(n.projectDir),c=o===n.projectDir;return e.jsxs("tr",{onClick:()=>a(n.projectDir),className:`border-t border-line hover:bg-bg-elev cursor-pointer ${c?"bg-bg-elev":""}`,children:[e.jsx("td",{className:"px-3 py-2 font-mono text-fg-dim",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:r}}),O(n.projectDir)]})}),e.jsx("td",{className:"px-3 py-2 w-32",children:e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full",style:{width:`${Math.max(n.sharePct,n.sharePct>0?2:0)}%`,backgroundColor:r}})})}),e.jsx("td",{className:"px-3 py-2 text-fg-faint font-mono",children:Q(s,n.value)}),e.jsxs("td",{className:"px-3 py-2 text-fg-faint font-mono",children:[n.sharePct.toFixed(1),"%"]}),e.jsx("td",{className:"px-3 py-2 font-mono",children:n.trend.pct===null?e.jsx("span",{className:"text-fg-faint",children:"—"}):e.jsxs("span",{className:n.trend.direction==="up"?"text-delta-good":n.trend.direction==="down"?"text-delta-bad":"text-fg-faint",children:[n.trend.direction==="up"?"▲":n.trend.direction==="down"?"▼":"·"," ",De(Math.abs(n.trend.pct))]})}),e.jsx("td",{className:"px-3 py-2 text-fg-faint font-mono",children:B(n.sessions)}),e.jsx("td",{className:"px-3 py-2 text-fg-faint font-mono",children:n.topTool||"—"})]},n.projectDir)})})]})]}):e.jsxs("div",{className:`${N} p-4`,children:[e.jsx(R,{kicker:"03 · by project",title:"Ranking"}),e.jsx("div",{className:"text-xs text-fg-faint",children:"no projects in range"})]})}function Ut({projectDir:t,totals:s,byModel:o,toolBreakdown:a,onClear:n}){var l;const r=D(s,"in"),c=D(s,"out"),i=Object.entries(o).sort((p,m)=>m[1].costUsd-p[1].costUsd),u=Object.entries(a).sort((p,m)=>m[1]-p[1]),d=((l=u[0])==null?void 0:l[1])??0;return e.jsxs("div",{className:`${N} p-4`,children:[e.jsx(R,{kicker:"04 · drill in",title:O(t),right:e.jsx("button",{onClick:n,className:"text-[11px] text-fg-faint hover:text-fg font-mono",children:"clear ✕"})}),e.jsx("div",{className:"flex items-center gap-1.5 -mt-2 mb-3",children:e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:E(t)}})}),e.jsxs("div",{className:"grid grid-cols-6 gap-3 mb-4",children:[e.jsx(H,{label:"prompts",value:B(s.promptCount)}),e.jsx(H,{label:"sessions",value:B(s.sessionCount)}),e.jsx(H,{label:"in tokens",value:I(r)}),e.jsx(H,{label:"out tokens",value:I(c)}),e.jsx(H,{label:"spend",value:$(s.estimatedCostUsd)}),e.jsx(H,{label:"time",value:Ee(s.activeMinutes)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider mb-1.5",children:"model mix"}),i.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no model data"}):e.jsx("div",{className:"space-y-1",children:i.map(([p,m])=>e.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono text-fg-dim",children:[e.jsx("span",{children:fe(p)}),e.jsx("span",{className:"text-fg-faint",children:$(m.costUsd)})]},p))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider mb-1.5",children:"tool mix"}),u.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no tool data"}):e.jsx("div",{className:"space-y-1",children:u.slice(0,6).map(([p,m])=>e.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[e.jsx("span",{className:"w-20 shrink-0 truncate text-fg-dim font-mono",children:p}),e.jsx("div",{className:"flex-1 h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full bg-hive-teal",style:{width:`${d>0?m/d*100:0}%`}})}),e.jsx("span",{className:"text-fg-faint font-mono w-8 text-right",children:m})]},p))})]})]})]})}function H({label:t,value:s}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-faint uppercase tracking-wider",children:t}),e.jsx("div",{className:"text-[17px] font-mono tracking-tight text-fg",children:s})]})}function Pt({byModelTotals:t}){const s=Object.entries(t).sort((a,n)=>n[1].costUsd-a[1].costUsd),o=s.reduce((a,[,n])=>a+n.costUsd,0);return e.jsxs("div",{className:`${N} p-4`,children:[e.jsx(R,{kicker:"05 · composition",title:"Model mix",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:[$(o)," total"]})}),s.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no model data in range"}):e.jsx("div",{className:"space-y-2",children:s.map(([a,n])=>{const r=o>0?n.costUsd/o*100:0,c=E(a);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-0.5",children:[e.jsxs("span",{className:"flex items-center gap-1.5 font-mono text-fg-dim truncate",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm shrink-0",style:{backgroundColor:c}}),fe(a),n.estimated&&e.jsx("span",{className:"text-fg-faint",children:"(est.)"})]}),e.jsxs("span",{className:"text-fg-faint whitespace-nowrap ml-2",children:[$(n.costUsd)," · ",r.toFixed(0),"%"]})]}),e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full",style:{width:`${Math.max(r,r>0?2:0)}%`,backgroundColor:c}})})]},a)})})]})}const At={epic:"Epic sessions",job:"Scheduler jobs",other:"Other sessions"};function Lt({byLauncherTotals:t}){const s=dt.map(a=>{var n;return[a,((n=t[a])==null?void 0:n.costUsd)??0]}),o=s.reduce((a,[,n])=>a+n,0);return e.jsxs("div",{className:`${N} p-4`,children:[e.jsx(R,{kicker:"05 · composition",title:"Launcher mix",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:[$(o)," total"]})}),o<=0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no usage in range"}):e.jsx("div",{className:"space-y-2",children:s.map(([a,n])=>{const r=n/o*100,c=E(a);return e.jsxs("div",{"data-testid":`history-launcher-${a}`,children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-0.5",children:[e.jsxs("span",{className:"flex items-center gap-1.5 font-mono text-fg-dim truncate",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm shrink-0",style:{backgroundColor:c}}),At[a]]}),e.jsxs("span",{className:"text-fg-faint whitespace-nowrap ml-2",children:[$(n)," · ",r.toFixed(0),"%"]})]}),e.jsx("div",{className:"h-1.5 rounded bg-bg-hi overflow-hidden",children:e.jsx("div",{className:"h-full",style:{width:`${Math.max(r,r>0?2:0)}%`,backgroundColor:c}})})]},a)})})]})}function Ft({rows:t}){const s=t.slice(0,3),o=s.reduce((r,c)=>r+c.sharePct,0),a=t.slice(3),n=a.reduce((r,c)=>r+c.sharePct,0);return e.jsxs("div",{className:`${N} p-4`,children:[e.jsx(R,{kicker:"05 · composition",title:"Concentration",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:["top 3 = ",o.toFixed(0),"%"]})}),t.length===0?e.jsx("div",{className:"text-xs text-fg-faint",children:"no projects in range"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex h-3 rounded overflow-hidden mb-2",children:t.map(r=>e.jsx("div",{style:{width:`${Math.max(r.sharePct,.5)}%`,backgroundColor:E(r.projectDir)},title:`${O(r.projectDir)} · ${r.sharePct.toFixed(1)}%`},r.projectDir))}),e.jsx("div",{className:"space-y-1 mb-2",children:s.map(r=>e.jsxs("div",{className:"flex items-center justify-between text-[11px] font-mono",children:[e.jsxs("span",{className:"flex items-center gap-1.5 text-fg-dim truncate",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full shrink-0",style:{backgroundColor:E(r.projectDir)}}),O(r.projectDir)]}),e.jsxs("span",{className:"text-fg-faint",children:[r.sharePct.toFixed(1),"%"]})]},r.projectDir))}),a.length>0&&e.jsxs("p",{className:"text-[10px] text-fg-faint",children:[a.length," more project",a.length===1?"":"s"," account for ",n.toFixed(1),"% (long tail)."]})]})]})}const Z=30,xe=9,A=(Z+xe)*2;function _t({totals:t}){const s=t.inputTokens+t.cacheReadTokens+t.cacheCreationTokens,o=s>0?t.cacheReadTokens/s*100:0,a=2*Math.PI*Z,n=A/2;return e.jsxs("div",{className:`${N} p-4`,children:[e.jsx(R,{kicker:"05 · composition",title:"Cache"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"relative shrink-0",style:{width:A,height:A},children:[e.jsxs("svg",{width:A,height:A,viewBox:`0 0 ${A} ${A}`,className:"-rotate-90",children:[e.jsx("circle",{cx:n,cy:n,r:Z,fill:"none",stroke:"currentColor",className:"text-bg-hi",strokeWidth:xe}),e.jsx("circle",{cx:n,cy:n,r:Z,fill:"none",stroke:yt,strokeWidth:xe,strokeDasharray:a,strokeDashoffset:a*(1-o/100),strokeLinecap:"round"})]}),e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center text-[13px] font-mono text-fg",children:[o.toFixed(0),"%"]})]}),e.jsxs("div",{className:"text-[11px] space-y-1 font-mono",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-fg-faint",children:"reused (cache read)"}),e.jsx("span",{className:"text-fg-dim",children:I(t.cacheReadTokens)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-fg-faint",children:"written to cache"}),e.jsx("span",{className:"text-fg-dim",children:I(t.cacheCreationTokens)})]})]})]})]})}const Ht=.05,Ot="—",Se=t=>`$${t.toFixed(2)}`;function Bt(){const[t,s]=h.useState(null),[o,a]=h.useState(null),n=Ve(c=>c.show);h.useEffect(()=>{let c=!0;const i=()=>{window.api.history.loopEfficiency().then(d=>{c&&(s(d),a(null))}).catch(d=>{if(!c)return;const l=d instanceof Error?d.message:String(d);a(l),n("error",`Loop efficiency failed to load: ${l}`)})};i();const u=window.api.history.onUpdated(i);return()=>{c=!1,u()}},[n]);let r;if(o&&!t)r=e.jsxs("div",{"data-testid":"loop-eff-error",className:"text-[11px] font-mono text-fg-faint",children:["Failed to load: ",o]});else if(!t)r=e.jsx("div",{"data-testid":"loop-eff-loading",className:"text-[11px] font-mono text-fg-faint",children:"Loading…"});else if(t.rows.length===0)r=e.jsx("div",{"data-testid":"loop-eff-empty",className:"text-[11px] font-mono text-fg-faint",children:"No runs this week."});else{const c=t.totals.wastedRunRate>Ht;r=e.jsxs(e.Fragment,{children:[e.jsxs("table",{className:"w-full text-[11px] font-mono","data-testid":"loop-eff-table",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"text-fg-faint text-left",children:[e.jsx("th",{className:"font-normal",children:"Project"}),e.jsx("th",{className:"font-normal text-right",children:"Runs"}),e.jsx("th",{className:"font-normal text-right",children:"Wasted"}),e.jsx("th",{className:"font-normal text-right",children:"Verified"}),e.jsx("th",{className:"font-normal text-right",children:"Refuted"}),e.jsx("th",{className:"font-normal text-right",children:"List-price $"}),e.jsx("th",{className:"font-normal text-right",children:"$ / verified"})]})}),e.jsx("tbody",{className:"text-fg-dim",children:t.rows.map(i=>e.jsxs("tr",{"data-testid":"loop-eff-row",children:[e.jsx("td",{children:i.project}),e.jsx("td",{className:"text-right",children:i.runs}),e.jsx("td",{className:"text-right",children:i.wastedRuns}),e.jsx("td",{className:"text-right",children:i.verified}),e.jsx("td",{className:"text-right",children:i.refuted}),e.jsx("td",{className:"text-right",children:Se(i.executorUsd)}),e.jsx("td",{className:"text-right","data-testid":"loop-eff-per-verified",children:i.usdPerVerified==null?Ot:Se(i.usdPerVerified)})]},i.cwd))})]}),e.jsxs("div",{"data-testid":"loop-eff-totals","data-warning":c?"true":"false",className:`mt-2 text-[11px] font-mono ${c?"text-amber-300":"text-fg-dim"}`,children:["wasted runs ",(t.totals.wastedRunRate*100).toFixed(1),"% (",t.totals.wastedRuns,"/",t.totals.runs,") · target ≤ 5%"]}),e.jsx("div",{"data-testid":"loop-eff-usage",className:"mt-1 text-[11px] font-mono text-fg-faint",children:t.verifiedPerUsagePct!=null?`${t.verifiedPerUsagePct} verified PRDs per 1% of weekly usage`:"weekly usage unavailable"})]})}return e.jsxs("div",{className:`${N} p-4`,"data-testid":"loop-efficiency",children:[e.jsx(R,{kicker:"06 · reliability",title:"Loop efficiency"}),r]})}const It=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];function Wt({days:t,measure:s}){const{buckets:o,weekendShare:a,peakIdx:n}=h.useMemo(()=>{const c=new Array(7).fill(0);for(const l of t){const[p,m,T]=l.date.split("-").map(Number),v=new Date(p,m-1,T).getDay();c[v]+=D(l.totals,s)}const i=c.reduce((l,p)=>l+p,0),u=c[0]+c[6];let d=0;for(let l=1;l<7;l++)c[l]>c[d]&&(d=l);return{buckets:c,weekendShare:i>0?u/i*100:0,peakIdx:d}},[t,s]),r=Math.max(...o,1);return e.jsxs("div",{className:`${N} p-4`,children:[e.jsx(R,{kicker:"05 · composition",title:"Rhythm",right:e.jsxs("span",{className:"text-xs font-mono text-fg-faint",children:["weekend ",a.toFixed(0),"%"]})}),e.jsx("div",{className:"flex items-end gap-2 h-24",children:o.map((c,i)=>e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-end gap-1 h-full",children:[e.jsx("div",{className:`w-full rounded-t ${i===n?"bg-accent":"bg-rhythm"}`,style:{height:`${r>0?c/r*100:0}%`,minHeight:c>0?2:0}}),e.jsx("span",{className:"text-[9px] text-fg-faint font-mono",children:It[i]})]},i))})]})}const Gt=["in","out","total","prompts","sessions","time","spend"],Kt=[30,60,90,0],Yt="spend",zt=30,Vt=3e4,Xt=[];function qt(){var ve;const[t,s]=h.useState(Yt),[o,a]=h.useState(zt),n=h.useRef(!1),r=h.useRef(!1),c=f=>{n.current=!0;const b=t;s(f),ue({measure:f}).catch(()=>{s(b),q.error("Couldn't save the measure preference — reverted.")})},i=f=>{r.current=!0;const b=o;a(f),ue({range:f}).catch(()=>{a(b),q.error("Couldn't save the range preference — reverted.")})};h.useEffect(()=>{let f=!1;return he().then(b=>{f||(!n.current&&b.measure&&Gt.includes(b.measure)&&s(b.measure),!r.current&&b.range!==void 0&&Kt.includes(b.range)&&a(b.range))}),()=>{f=!0}},[]);const u=Xe(f=>f.navFace),d=ye(f=>f.tabs),l=ye(f=>f.activeTabId),p=((ve=d.find(f=>f.id===l))==null?void 0:ve.cwd)??null,m=h.useRef(u),T=p?qe(p):null,[v,k]=h.useState(null),x=h.useMemo(()=>u==="project"&&T?new Set([T]):v,[u,T,v]),[j,U]=h.useState(null),[g,J]=h.useState(null),[G,W]=h.useState(!0),[ee,te]=h.useState(0),se=h.useRef(o);se.current=o;const K=h.useRef(!0),ne=h.useRef(0),pe=h.useRef(0),L=h.useRef(null),Y=h.useCallback(f=>{const b=se.current;ne.current+=1,pe.current=Date.now(),et(b).then(y=>{if(ne.current-=1,!(!K.current||b!==se.current)){if(W(!1),y.ok){J(y.data);return}f||q.error(`History analytics failed to load: ${y.error}`)}})},[]);h.useEffect(()=>{K.current=!0,W(!0),Y(!1)},[o,ee,Y]),h.useEffect(()=>{const f=()=>{if(!K.current)return;const w=pe.current+Vt-Date.now();if(ne.current===0&&w<=0){Y(!0);return}L.current||(L.current=setTimeout(()=>{L.current=null,f()},Math.max(w,1e3)))},b=()=>{document.visibilityState==="visible"&&f()},y=window.api.history.onUpdated(f);return window.addEventListener("focus",f),document.addEventListener("visibilitychange",b),()=>{K.current=!1,y(),window.removeEventListener("focus",f),document.removeEventListener("visibilitychange",b),L.current&&(clearTimeout(L.current),L.current=null)}},[Y]);const me=h.useRef(!1);h.useEffect(()=>{if(!me.current){me.current=!0;return}k(null),U(null)},[o]),h.useEffect(()=>{m.current!==u&&(m.current=u,u==="home"&&k(null))},[u]);const{projects:ge,resolving:je}=Qe(),be=h.useMemo(()=>{const f={};for(const b of ge)for(const y of b.encodedIds)f[y]=b.cwd;return f},[ge]),F=h.useMemo(()=>g&&!je?pt(g.days,be):null,[g,be,je]),M=(F==null?void 0:F.days)??(g==null?void 0:g.days)??Xt,oe=(F==null?void 0:F.excluded)??null,S=h.useMemo(()=>g?st({days:M,totals:g.totals,prevTotals:g.prevTotals},x):null,[g,M,x]),_=h.useMemo(()=>x===null?M:M.map(f=>({date:f.date,byProject:Object.fromEntries(Object.entries(f.byProject).filter(([b])=>x.has(b)))})),[M,x]),z=h.useMemo(()=>Ne(M,t),[M,t]),ae=h.useMemo(()=>Ne(_,t),[_,t]),Le=h.useMemo(()=>_.map(f=>({date:f.date,values:Object.fromEntries(Object.entries(f.byProject).map(([b,y])=>[b,D(y,t)]))})),[_,t]),ke=h.useMemo(()=>S?ct(S,t):null,[S,t]),V=h.useMemo(()=>{if(!g||!j)return null;const f=M.flatMap(C=>C.byProject[j]?[C.byProject[j]]:[]),{byModel:b,...y}=Ce(f),w={};for(const C of f)for(const[P,ce]of Object.entries(C.toolBreakdown))w[P]=(w[P]??0)+ce;return{totals:y,byModel:b,toolBreakdown:w}},[g,M,j]);h.useEffect(()=>{j&&x!==null&&!x.has(j)&&U(null)},[j,x]);function Fe(f){k(b=>{const y=new Set(z.map(P=>P.projectDir)),w=b??new Set(y),C=new Set(w);return C.has(f)?C.delete(f):C.add(f),C.size>=y.size?null:C})}function _e(f){k(new Set([f]))}function He(){k(null)}function Oe(){if(!g)return;const f=_.map(P=>{const{byModel:ce,estimatedCostUsd:Be,inputTokens:Ie,outputTokens:We,cacheCreationTokens:Ge,cacheReadTokens:Ke}=Ce(Object.values(P.byProject));return{date:P.date,costUsd:Be,inputTokens:Ie,outputTokens:We,cacheCreationTokens:Ge,cacheReadTokens:Ke,byModel:ce}}),b=lt(f),y=new Blob([b],{type:"text/csv"}),w=URL.createObjectURL(y),C=document.createElement("a");C.href=w,C.download=`usage-history-${g.from}-${g.to}.csv`,C.click(),URL.revokeObjectURL(w)}return G&&!g?e.jsx($e,{}):g&&g.days.length===0?e.jsx(Ze,{title:"no sessions in range",hint:"Widen the range or check back after your next session."}):!g||!S||!ke?e.jsx($e,{}):e.jsxs("div",{"data-testid":"history-dashboard",className:"flex flex-col h-full",children:[e.jsxs("h1",{className:"font-serif text-[42px] leading-tight tracking-tight text-fg px-4 pt-4",children:["Where your ",e.jsx("em",{className:"italic text-accent",children:"Claude time"})," goes"]}),e.jsx(kt,{measure:t,onMeasure:c,range:o,onRange:i,projectsShown:x===null?z.length:x.size,projectsTotal:z.length,fromDate:g.from,toDate:g.to,onRefresh:()=>te(f=>f+1),onExport:Oe,exportDisabled:_.length===0}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-auto p-4 space-y-4",children:[e.jsx(Tt,{measure:t,headline:ke,activeDays:S.activeDays,projectsTouched:ae.length,totalSessions:S.totals.sessionCount}),e.jsx(wt,{days:M}),oe&&mt(oe)&&e.jsx("div",{"data-testid":"history-excluded-note",className:"rounded-[10px] border border-line bg-bg-hi px-3 py-2 text-[11.5px] font-mono text-fg-faint",title:"A project is a working directory. ~/.claude/projects holds one folder per path the CLI was ever launched from — throwaway /tmp dirs and test fixtures included — and a folder whose cwd can't be recovered from its transcripts is not a project. Their totals are stated here rather than silently folded into the charts.",children:gt(oe)}),g.legacyDates&&g.legacyDates.length>0&&e.jsx("div",{"data-testid":"history-legacy-note",className:"rounded-[10px] border border-line bg-bg-hi px-3 py-2 text-[11.5px] font-mono text-fg-faint",children:Qt(g.legacyDates)}),u==="home"&&e.jsx(Rt,{chips:z.map(f=>({projectDir:f.projectDir,value:f.value})),keep:x,onToggle:Fe,onIsolate:_e,onShowAll:He}),e.jsx(Dt,{days:Le,measure:t,selected:j,onSelect:U}),e.jsx(Et,{rows:ae,measure:t,selected:j,onSelect:U}),j&&V&&e.jsx(Ut,{projectDir:j,totals:V.totals,byModel:V.byModel,toolBreakdown:V.toolBreakdown,onClear:()=>U(null)}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsx(Pt,{byModelTotals:S.byModelTotals}),e.jsx(Lt,{byLauncherTotals:S.byLauncherTotals}),e.jsx(Ft,{rows:ae}),e.jsx(_t,{totals:S.totals}),e.jsx(Wt,{days:S.days,measure:t})]}),e.jsx(Bt,{})]})]})}function Qt(t){const s=t.reduce((a,n)=>n>a?n:a),o=t.length;return`${o} ${o===1?"day":"days"} in this range (last: ${s}) were counted with the older method and read about two to three times too high; they cannot be recounted because their transcripts are gone.`}function $e(){return e.jsxs("div",{className:"p-4 space-y-4 animate-pulse",children:[e.jsx("div",{className:"h-24 bg-bg-elev rounded"}),e.jsx("div",{className:"h-16 bg-bg-elev rounded"}),e.jsx("div",{className:"h-8 bg-bg-elev rounded"}),e.jsx("div",{className:"h-56 bg-bg-elev rounded"}),e.jsx("div",{className:"h-40 bg-bg-elev rounded"})]})}function Zt(){return e.jsx(Je,{children:e.jsx(qt,{})})}const ns=h.memo(Zt);export{ns as History};
@@ -0,0 +1,3 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./SkillReferenceGraph-DcscPXAG.js","./index-C-d0DCre.js","./monaco-editor-BsIlgG7c.js","./monaco-editor-Cu5D__1H.css","./index-BCySPdtU.css"])))=>i.map(i=>d[i]);
2
+ import{bl as oe,aR as r,bg as ae,aC as et,C as tt,aB as e,m as Y,F as nt,P as st,ai as at,a9 as Be,aZ as Ne,ag as lt,ba as H,by as ot,bn as ye,a0 as se,bd as Se,b9 as Ee,aa as it,aG as Q,bo as ue,bc as Ue,ae as me,M as He,E as Ge,A as rt,c as We,e as we,bw as ct,aH as dt,aO as ut,b7 as ft,az as Pe,H as mt,L as pt,r as gt,p as xt}from"./index-C-d0DCre.js";import{C as ht,I as bt,p as vt,L as Ve,t as jt,z as yt,A as wt,B as kt,u as Ct,y as Te,c as Ke,b as pe,g as Nt,s as St,r as Et,H as le,d as Je,f as ze,e as ke,i as Ce,F as $t,x as Lt,D as Mt,J as Pt,E as Tt,w as At,G as Dt,m as Rt,a as It,h as Ot,S as Ft,j as _t,k as Bt,l as Ut,M as Ht,P as Gt,n as Wt,o as Vt,v as Kt}from"./Skills-BpGRKOcY.js";import{s as Jt,S as zt}from"./ViewTabs-C0PRZx4_.js";import{_ as qt}from"./monaco-editor-BsIlgG7c.js";import{P as Yt}from"./Panel-Csyd9HbD.js";import"./TiptapBody-DSU3769X.js";const Xt={skills:null,mcp:null,plugins:null},Zt={fileId:"claudeJson",scope:"user"};function Qt(t){return{skillsDir:`${t}/.claude/skills`,commandsDir:`${t}/.claude/commands`,claudeJson:`${t}/.claude.json`,pluginsManifest:`${t}/.claude/plugins/installed_plugins.json`}}async function en(t,n){const[s,l]=await Promise.all([et(t),window.api.config.listDir(n,{filesOnly:!0})]),o=s.errors[0];if(o)throw new Error(`${o.path}: ${o.error}`);if(!l.ok)throw new Error(`${n}: ${l.error??"failed to list directory"}`);return s.entries.length+l.entries.filter(i=>i.name.endsWith(".md")).length}async function tn(){const{data:t}=await window.api.claudeConfig.read(Zt),n=t==null?void 0:t.mcpServers;return n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n).length:0}async function nn(){return(await window.api.plugins.list()).length}function sn(){const t=oe(),[n,s]=r.useState(Xt),l=r.useRef({skills:0,mcp:0,plugins:0}),o=r.useCallback((f,x)=>{const u=l.current,y=++u[f],h=w=>{u[f]===y&&s(S=>S[f]===w?S:{...S,[f]:w})};x().then(h,()=>h(null))},[]),i=r.useMemo(()=>t?Qt(t):null,[t]),a=r.useCallback(()=>{i&&o("skills",()=>en(i.skillsDir,i.commandsDir))},[i,o]),m=r.useCallback(()=>o("mcp",tn),[o]),g=r.useCallback(()=>o("plugins",nn),[o]);return r.useEffect(()=>{const f=l.current;return a(),()=>{f.skills++}},[a]),r.useEffect(()=>{const f=l.current;return m(),g(),()=>{f.mcp++,f.plugins++}},[m,g]),ae(i?[i.skillsDir,i.commandsDir]:[],a),ae(i?[i.claudeJson]:[],m),ae(i?[i.pluginsManifest]:[],g),n}const an="User · every project on this machine",ln={title:"Nothing tells Claude how you like to work yet.",body:"Claude loads this file into every session it starts on this machine, in every project."};function on(){const t=oe(),n=r.useMemo(()=>t?tt.resolve("user",t,null):null,[t]),s=r.useMemo(()=>n?[{path:n,label:an,eyebrow:"YOUR INSTRUCTIONS FOR EVERY PROJECT"}]:[],[n]);return!t||!n?e.jsx(Y,{title:"loading…"}):e.jsx("div",{className:"flex flex-col h-full min-h-0","data-testid":"system-prompt",children:e.jsx(ht,{home:t,scope:"user",roots:s,activeRoot:n,empty:ln,testIdPrefix:"system-prompt",moreMenu:({importSelected:l})=>e.jsx(bt,{path:n,disabled:l})})})}const rn=r.memo(on);function cn({value:t,onChange:n,path:s,readOnly:l,theme:o="dark"}){const i=o==="paper";return e.jsx(nt,{path:`file://${s}`,defaultLanguage:"markdown",value:t,onChange:a=>n(a??""),beforeMount:i?at:void 0,theme:i?st:"vs-dark",options:{minimap:{enabled:!1},fontSize:13,fontFamily:"JetBrains Mono, ui-monospace, Menlo, monospace",lineNumbers:"on",renderLineHighlight:"line",scrollBeyondLastLine:!1,tabSize:2,wordWrap:"on",readOnly:l,automaticLayout:!0}})}const dn=r.lazy(()=>qt(()=>import("./SkillReferenceGraph-DcscPXAG.js"),__vite__mapDeps([0,1,2,3,4]),import.meta.url).then(t=>({default:t.SkillReferenceGraph})));function un({pluginName:t,skills:n,onBack:s,initialSelectedId:l}){var x;const[o,i]=r.useState(l??((x=n[0])==null?void 0:x.id)??null),a=o?n.find(u=>u.id===o)??null:null,m=r.useMemo(()=>vt(n),[n]),[g,f]=r.useState("list");return e.jsxs("div",{className:"flex flex-col h-full min-h-0 overflow-hidden",children:[e.jsxs("div",{className:"shrink-0 h-11 flex items-baseline gap-3.5 px-3 border-b border-line bg-bg",children:[e.jsxs("button",{type:"button",onClick:s,className:"font-mono text-accent hover:underline shrink-0 text-xs",children:["← ",t]}),e.jsx("span",{className:"font-serif text-[22px] text-fg shrink-0 truncate max-w-[16rem]",children:(a==null?void 0:a.name)??(a==null?void 0:a.id)??"skill"}),e.jsx("span",{className:"flex-1"}),e.jsx("div",{className:"flex items-center gap-1.5 shrink-0",children:e.jsxs("div",{className:"flex rounded border border-line overflow-hidden",children:[e.jsx("button",{onClick:()=>f("list"),className:`px-2 py-0.5 text-xs ${g==="list"?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:"list"}),e.jsx("button",{onClick:()=>f("graph"),className:`px-2 py-0.5 text-xs ${g==="graph"?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:"graph"})]})})]}),e.jsxs("div",{className:"shrink-0 h-[26px] flex items-center gap-[18px] px-3 bg-bg-elev border-b border-line text-[9px] font-mono uppercase tracking-wide overflow-hidden",children:[a!=null&&a.description?e.jsx("span",{className:"text-fg-dim truncate normal-case",children:a.description}):null,e.jsxs("span",{className:"ml-auto text-fg-faint truncate normal-case",children:[n.length," ",n.length===1?"skill":"skills"," · ",m.length," ",m.length===1?"reference":"references"]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden",children:n.length===0?e.jsx(Y,{title:"no skills in this plugin"}):g==="graph"?e.jsx(r.Suspense,{fallback:e.jsx("div",{className:"p-6 text-xs text-fg-faint",children:"Loading graph…"}),children:e.jsx(dn,{skills:n,edges:m,selectedId:o,onSelect:i})}):e.jsx(Ve,{sidebar:e.jsx("div",{className:"py-1",children:n.map(u=>e.jsxs("button",{onClick:()=>i(u.id),className:`w-full px-3 py-1 text-xs text-left ${o===u.id?"bg-bg-hi text-fg":"text-fg-dim hover:text-fg hover:bg-bg-hi"}`,children:[e.jsx("div",{className:"truncate",children:u.name??u.id}),u.description?e.jsx("div",{className:"truncate text-fg-faint",children:u.description}):null]},u.id))}),detail:a?e.jsx("div",{className:"h-full min-h-0",children:e.jsx(cn,{path:a.path,value:a.body,onChange:()=>{},readOnly:!0})}):e.jsx(Y,{title:"select a skill"})})})]})}function fn({row:t,busy:n,onUninstall:s}){const[l,o]=r.useState(!1),[i,a]=r.useState(!1),m=r.useRef(null),g=r.useId(),f=r.useCallback(()=>{o(!1),a(!1)},[]);r.useEffect(()=>{if(!l)return;const w=P=>{var E;(E=m.current)!=null&&E.contains(P.target)||f()},S=P=>{P.key==="Escape"&&f()};return window.addEventListener("mousedown",w),window.addEventListener("keydown",S),()=>{window.removeEventListener("mousedown",w),window.removeEventListener("keydown",S)}},[l,f]);const x=()=>{f(),Ne(t.path)},u=async()=>{f(),await lt(t.path)||H.error(`Could not copy ${t.path} to the clipboard`)},y=()=>{f(),s(t)},h="px-2.5 py-[7px] rounded-[5px] text-left whitespace-nowrap hover:bg-bg-elev";return e.jsxs("div",{ref:m,className:"relative self-start",children:[e.jsx("button",{type:"button","data-testid":"plugin-menu","aria-label":`Actions for ${t.name}`,"aria-haspopup":"menu","aria-expanded":l,"aria-controls":l?g:void 0,onClick:()=>l?f():o(!0),className:"w-[30px] h-7 inline-flex items-center justify-center bg-bg border border-line rounded-md text-fg-dim hover:border-rule",children:e.jsxs("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("circle",{cx:"5",cy:"12",r:"1.8"}),e.jsx("circle",{cx:"12",cy:"12",r:"1.8"}),e.jsx("circle",{cx:"19",cy:"12",r:"1.8"})]})}),l&&e.jsx("div",{id:g,role:"menu","aria-label":`Actions for ${t.name}`,className:`absolute ${Be.dialog} right-0 top-[34px] w-[210px] p-[5px] flex flex-col bg-bg-hi border border-line rounded-lg shadow-lg text-[12.5px] text-fg`,children:i?e.jsxs("div",{className:"flex flex-col gap-2 px-2.5 py-[7px]",children:[e.jsxs("span",{className:"font-medium",children:["Uninstall ",t.name,"?"]}),e.jsxs("div",{className:"flex items-center justify-end gap-1.5",children:[e.jsx("button",{type:"button",role:"menuitem","data-testid":"plugin-uninstall",disabled:n,onClick:y,className:"h-6 px-2.5 rounded-[5px] bg-delta-bad text-bg-hi font-medium hover:bg-delta-bad/90 disabled:opacity-40",children:"Confirm"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>a(!1),className:"h-6 px-2.5 rounded-[5px] border border-line text-fg-dim hover:bg-bg-elev",children:"Cancel"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",role:"menuitem",onClick:x,className:h,children:"Reveal in File Explorer"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>void u(),className:h,children:"Copy path"}),e.jsx("div",{role:"separator",className:"h-px mx-1.5 my-1 bg-line"}),e.jsxs("button",{type:"button",role:"menuitem",disabled:!t.marketplace||n,title:t.marketplace?void 0:"No marketplace is recorded for this install",onClick:()=>a(!0),className:`${h} font-medium text-delta-bad hover:bg-delta-bad/10 disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent`,children:["Uninstall ",t.name]})]})})]})}function qe({name:t,enabled:n,disabled:s,onToggle:l,testId:o="plugin-enabled-switch"}){return e.jsx("button",{type:"button",role:"switch","aria-checked":n,"aria-label":`${n?"Disable":"Enable"} ${t}`,"data-testid":o,disabled:s,onClick:i=>{i.stopPropagation(),l()},onKeyDown:i=>i.stopPropagation(),className:`relative shrink-0 w-[30px] h-[18px] rounded-full transition-colors align-middle disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent ${n?"bg-accent":"bg-rule"}`,children:e.jsx("span",{"aria-hidden":"true",className:`absolute top-0.5 w-3.5 h-3.5 rounded-full bg-bg-hi shadow transition-[left] ${n?"left-[14px]":"left-0.5"}`})})}const mn="Saved — matches settings.json › enabledPlugins",pn=250,gn=["hooks/hooks.json",".mcp.json","agents","skills","commands",".claude-plugin/plugin.json"],xn=(t,n,s)=>`${t} ${t===1?n:s}`;function hn(t){var s;const n=["PLUGIN"];return t.marketplace&&n.push(t.marketplace.toUpperCase()),(s=t.manifest)!=null&&s.version&&n.push(`V${t.manifest.version.toUpperCase()}`),n.push(`${(t.scope??"user").toUpperCase()} SCOPE`),n.join(" · ")}function bn(t,n){const s=i=>{const m=i.trim().replace(/^v/i,"").split(/[-+]/)[0].split(".");return m.every(g=>/^\d+$/.test(g))?m.map(Number):null},l=s(t),o=s(n);if(!l||!o)return null;for(let i=0;i<Math.max(l.length,o.length);i++){const a=(l[i]??0)-(o[i]??0);if(a!==0)return Math.sign(a)}return 0}function vn(t,n){if(!t||!n)return null;const s=bn(n,t);return s===null?n.trim()===t.trim()?"up-to-date":"update-available":s>0?"update-available":"up-to-date"}const jn=t=>t.key&&t.key.includes("@")?t.key.slice(0,t.key.lastIndexOf("@")):t.name,de=t=>!!t&&typeof t=="object"&&!Array.isArray(t);function Ae(t,n){if(!de(t))return[];const s=de(t.hooks)?t.hooks:t,l=[];for(const[o,i]of Object.entries(s))Array.isArray(i)&&i.forEach((a,m)=>{if(!de(a)||!Array.isArray(a.hooks))return;const g=typeof a.matcher=="string"&&a.matcher?` · ${a.matcher}`:"";a.hooks.forEach((f,x)=>{const u=de(f)?typeof f.command=="string"?f.command:typeof f.prompt=="string"?f.prompt:null:null;l.push({id:`${n}:${o}:${m}:${x}`,name:`${o}${g}`,description:u})})});return l}async function yn(t,n){const s=n==null?void 0:n.hooks,l=typeof s=="string"?[s]:Array.isArray(s)?s.filter(a=>typeof a=="string"):[],o=new Set;for(const a of l)a.startsWith("/")||a.split("/").includes("..")||o.add(`${t}/${a.replace(/^\.\//,"")}`);o.add(`${t}/hooks/hooks.json`);const i=await Promise.all([...o].map(async a=>{const m=await window.api.config.readJson(a);return{p:a,data:m.exists&&!m.parseError?m.data:null}}));return[...de(s)?Ae(s,"manifest"):[],...i.flatMap(({p:a,data:m})=>Ae(m,a))]}function wn({row:t,home:n,busy:s,onToggle:l,onUninstall:o,onJump:i}){var Z,p,W;const[a,m]=r.useState([]),[g,f]=r.useState([]),[x,u]=r.useState(null),[y,h]=r.useState(!0),[w,S]=r.useState([]),P=r.useRef(0),[E,O]=r.useState(null),A=t.marketplace,j=jn(t);r.useEffect(()=>{if(O(null),!n||!A)return;let c=!0;return jt(n,{quiet:!0}).then(b=>{if(!c)return;const R=b.find(U=>U.marketplace===A&&U.name===j);O((R==null?void 0:R.version)??null)}),()=>{c=!1}},[n,A,j]);const D=r.useCallback(async()=>{const c=++P.current;try{const{manifest:b}=await yt(t.path),[R,U,ee]=await Promise.all([wt(t.path),kt(t.path,b),yn(t.path,b)]),te=R?await Ct(R):[],[B,ne]=await Promise.all([Te(U.agentFiles),Te(U.commandFiles)]),d=await Promise.all([...new Set([...gn.map(v=>`${t.path}/${v}`),...U.sourcePaths])].map(async v=>await window.api.config.exists(v)?v:null));if(c!==P.current)return;const T=(v,V)=>({kind:v,id:V.id,name:v==="command"?`/${V.name??V.id}`:V.name??V.id,description:V.description});m([...ne.map(v=>T("command",v)),...te.map(v=>({kind:"skill",id:v.id,name:v.name??v.id,description:v.description,skill:v})),...B.map(v=>T("agent",v)),...ee.map(v=>({kind:"hook",...v})),...U.mcpServers.map(v=>({kind:"mcp",id:v.id,name:v.name,description:v.description}))]),f(te);const I=d.filter(v=>v!==null);S(v=>v.join("\0")===I.join("\0")?v:I)}catch(b){if(c!==P.current)return;H.error(`Failed to load plugin contents: ${b instanceof Error?b.message:String(b)}`)}finally{c===P.current&&h(!1)}},[t.path]);r.useEffect(()=>(h(!0),D(),()=>{P.current+=1}),[D]);const L=r.useRef(null),_=r.useRef(!1),M=r.useRef(!1),N=r.useCallback(async()=>{if(_.current){M.current=!0;return}_.current=!0;try{do M.current=!1,await D();while(M.current)}finally{_.current=!1}},[D]),F=r.useCallback(()=>{L.current&&clearTimeout(L.current),L.current=setTimeout(()=>{L.current=null,N()},pn)},[N]);if(r.useEffect(()=>()=>{L.current&&clearTimeout(L.current)},[]),ae(w,F,{depth:0}),x)return e.jsx(un,{pluginName:((Z=t.manifest)==null?void 0:Z.name)??t.name,skills:g,initialSelectedId:x.id,onBack:()=>u(null)},x.id);const q=t.enabled===!0,$=((p=t.manifest)==null?void 0:p.version)??null,G=vn($,E),J=(W=t.manifest)==null?void 0:W.description,k=c=>a.filter(b=>b.kind===c).length,X=[["command","COMMAND","COMMANDS"],["skill","SKILL","SKILLS"],["agent","AGENT","AGENTS"],["hook","HOOK","HOOKS"],["mcp","MCP SERVER","MCP SERVERS"]].filter(([c])=>k(c)>0).map(([c,b,R])=>xn(k(c),b,R)).join(" · "),z=k("skill")+k("command")>0;return e.jsxs("div",{"data-testid":"plugin-detail",className:"flex flex-col min-h-0",children:[e.jsx(Ke,{eyebrow:hn(t),title:t.name,actions:e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"flex items-center gap-2 text-[13.5px] text-fg-dim",children:[e.jsx(qe,{name:t.name,enabled:q,disabled:!t.key||s,onToggle:()=>l(t),testId:"plugin-detail-switch"}),"Enabled"]}),G&&e.jsx("span",{"data-testid":"plugin-update-state","data-state":G,title:`Installed v${$} · ${t.marketplace} lists v${E}`,className:`h-7 inline-flex items-center px-3 bg-bg border rounded-md text-[13px] font-semibold ${G==="update-available"?"border-accent text-accent":"border-line text-fg-dim"}`,children:G==="update-available"?"Update available":"Up to date"}),e.jsx(fn,{row:t,busy:s,onUninstall:o})]})}),e.jsxs("div",{className:"px-9 py-6 flex flex-col gap-4 max-w-[1100px]",children:[e.jsx(pe,{label:"DESCRIPTION",labelNote:"FROM THE PLUGIN'S MANIFEST",children:e.jsx("span",{"data-testid":"plugin-description",className:J?void 0:"text-fg-faint",children:J??(t.hasManifest?"The manifest has no description.":"This plugin has no manifest.")})}),e.jsx(pe,{label:"WHAT IT ADDS",labelNote:y?void 0:X||"NOTHING",action:z?e.jsx("button",{type:"button","data-testid":"plugin-open-in-skills",onClick:()=>i("skills"),className:"shrink-0 text-[13px] font-semibold text-accent hover:underline",children:"Open in Skills →"}):void 0,children:y?e.jsx(Y,{title:"scanning…"}):a.length===0?e.jsx("span",{className:"text-fg-faint",children:t.error?`Inspection failed: ${t.error}`:"No commands, skills, agents or hooks."}):e.jsx("ul",{"data-testid":"plugin-adds",className:"-mx-[18px] mt-2 border-t border-line",children:a.map(c=>{const b=e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"w-[200px] shrink-0 truncate font-mono text-[14px] font-semibold text-fg",title:c.name,children:c.name}),e.jsx("span",{className:"flex-1 min-w-0 truncate text-[13.5px] text-fg-dim",title:c.description??void 0,children:c.description??""})]}),R="w-full flex items-baseline gap-4 px-[18px] py-3 text-left";return e.jsx("li",{"data-testid":`plugin-adds-${c.kind}`,className:"border-b border-line last:border-b-0",children:c.skill?e.jsx("button",{type:"button",onClick:()=>u(c.skill),className:`${R} hover:bg-bg-elev`,children:b}):e.jsx("div",{className:R,children:b})},`${c.kind}:${c.id}`)})})}),e.jsx(pe,{label:"INSTALLED AT",action:e.jsx("button",{type:"button","data-testid":"plugin-reveal",onClick:()=>Ne(t.path),className:"shrink-0 text-[13px] text-fg-dim hover:text-fg",children:"Reveal"}),children:e.jsx("span",{"data-testid":"plugin-install-path",title:t.path,className:"block truncate font-mono text-[14px]",children:Jt(t.path,n)})}),e.jsx(Nt,{text:mn})]})]})}const kn="~/.claude/plugins/installed_plugins.json",Cn="On/off is saved in settings.json › enabledPlugins",Nn=t=>ye.getState().openPanel("extensions",t);function Sn(t,n){var s,l;return[t.name,(s=t.manifest)==null?void 0:s.name,t.marketplace,(l=t.manifest)==null?void 0:l.description].some(o=>typeof o=="string"&&o.toLowerCase().includes(n))}const ie=(t,n,s)=>`${t} ${t===1?n:s}`;function En(t){const n=$t(t),s=[];if(t.marketplace&&s.push(t.marketplace),t.error)s.push("inspection failed");else{const l=[n.commands>0?ie(n.commands,"command","commands"):null,n.skills>0?ie(n.skills,"skill","skills"):null,n.agents>0?ie(n.agents,"agent","agents"):null,n.hooks>0?ie(n.hooks,"hook","hooks"):null,n.mcpServers>0?ie(n.mcpServers,"MCP server","MCP servers"):null].filter(o=>o!==null);s.push(...l.length>0?l:["empty"])}return t.scope&&t.scope!=="user"&&s.push(`${t.scope} scope`),s.join(" · ")}function $n({onAdd:t,onJump:n}){const s=oe(),[l,o]=r.useState([]),[i,a]=r.useState(!0),[m,g]=r.useState(null),[f,x]=r.useState(null),[u,y]=r.useState(""),[h,w]=r.useState(null),[S,P]=r.useState(new Set),E=ot(c=>c.show),[O,A]=r.useState(null);r.useEffect(()=>{var b,R;let c=!1;return(R=(b=window.api.app).seedStatus)==null||R.call(b).then(U=>{c||w(U)}).catch(()=>{}),()=>{c=!0}},[]);const j=r.useRef(0),D=r.useRef(!1),L=r.useCallback(async()=>{var ee,te;const c=++j.current;if(!s)return;D.current||a(!0);const b=`${s}/.claude/plugins/installed_plugins.json`;let R=[],U=null;try{const B=await window.api.config.readJson(b);if(B.exists&&B.parseError)U=`could not parse installed_plugins.json${B.error?`: ${B.error}`:""}`;else if(B.exists&&B.data&&typeof B.data=="object"){const ne=B.data,d=[];for(const[I,v]of Object.entries(ne.plugins??{})){if(!Array.isArray(v))continue;const[V,fe]=I.split("@");for(const K of v)K!=null&&K.installPath&&d.push({name:V,marketplace:fe,entry:K})}let T=new Map;try{const I=await((te=(ee=window.api.plugins)==null?void 0:ee.list)==null?void 0:te.call(ee))??[];T=new Map(I.map(v=>[v.key,v.enabled]))}catch{}R=await Tn(d,Pn,async({name:I,marketplace:v,entry:V})=>{var Me;const fe={name:I,path:V.installPath,isDirectory:!0,isFile:!1,mtimeMs:0,size:0};let K;try{K=await St(fe)}catch(xe){K=Et(fe,xe instanceof Error?xe.message:String(xe))}return(Me=K.manifest)!=null&&Me.version||(K.manifest={...K.manifest??{},version:V.version}),K.marketplace=v,K.scope=V.scope,K.key=v?`${I}@${v}`:I,K.enabled=T.get(K.key)===!0,K})}}catch(B){U=`could not read installed_plugins.json: ${B instanceof Error?B.message:String(B)}`}j.current===c&&(g(U),U?H.error(`Plugins: ${U}`):(R.sort((B,ne)=>B.name.localeCompare(ne.name)),D.current=R.length>0,o(R)),a(!1))},[s]);r.useEffect(()=>{L()},[L]);const _=le(c=>c.tab),M=le(c=>c.id),N=le(c=>c.clear);r.useEffect(()=>{if(_!=="plugins"||!M||i)return;const c=M.startsWith("plugins:")?M.slice(8):null,b=c?l.find(R=>R.key===c):void 0;b&&(y(""),x(b.path)),N()},[_,M,i,l,N]),r.useEffect(()=>()=>{j.current+=1},[]),ae(s?[`${s}/.claude/plugins/installed_plugins.json`]:[],L);const F=async c=>{if(c.key){A(c.key);try{const b=await window.api.plugins.setEnabled({key:c.key,enabled:!c.enabled});b.ok||E("error",`Could not ${c.enabled?"disable":"enable"} ${c.name}: ${b.error??"unknown error"}`)}catch(b){E("error",`Could not update ${c.name}: ${b instanceof Error?b.message:String(b)}`)}finally{A(null),await L()}}},q=async c=>{if(c.marketplace){A(c.key??c.name);try{const b=await window.api.plugins.uninstall({slug:c.name,marketplaceName:c.marketplace});b.ok||E("error",`Uninstall ${c.name} failed: ${b.error??`exit ${b.exitCode}`}`)}catch(b){E("error",`Uninstall ${c.name} failed: ${b instanceof Error?b.message:String(b)}`)}finally{A(null),await L()}}},$=r.useMemo(()=>h?Object.keys(h).filter(c=>(h[c].status==="exhausted"||h[c].status==="failed")&&!S.has(c)):[],[h,S]),G=r.useMemo(()=>l.filter(c=>c.enabled===!0).length,[l]),J=u.trim().toLowerCase(),k=r.useMemo(()=>J?l.filter(c=>Sn(c,J)):l,[l,J]),C=k.find(c=>c.path===f)??k[0]??null,X=r.useCallback(()=>t==null?void 0:t(),[t]),z=n??Nn,Z=c=>O!==null&&O===(c.key??c.name),p=e.jsxs(e.Fragment,{children:[e.jsx(Je,{eyebrow:"PLUGINS",badge:`${G} on`,path:kn,note:Cn}),e.jsx(ze,{filter:u,onFilterChange:y,placeholder:"Filter",primaryLabel:"+ Add",onPrimary:X}),i&&l.length===0||m&&l.length===0?null:l.length===0?e.jsxs("div",{"data-testid":"plugins-empty",className:"flex flex-col gap-1 px-3 py-3 border border-dashed border-rule rounded-xl text-[13px] text-fg-dim",children:[e.jsx("span",{className:"font-semibold text-fg",children:"No plugins installed"}),e.jsxs("span",{children:["Use + Add, or run ",e.jsx("code",{className:"font-mono text-xs",children:"claude plugin install"}),"."]})]}):k.length===0?e.jsxs("p",{className:"px-1 text-[13px] text-fg-dim",children:["No plugins match “",u.trim(),"”."]}):e.jsx("div",{role:"listbox","aria-label":"Installed plugins",className:"flex flex-col gap-1",children:k.map(c=>e.jsx(ke,{title:c.name,meta:En(c),muted:c.enabled!==!0,selected:(C==null?void 0:C.path)===c.path,onSelect:()=>x(c.path),trailing:e.jsx(qe,{name:c.name,enabled:c.enabled===!0,disabled:!c.key||Z(c),onToggle:()=>void F(c)})},c.path))})]}),W=C?e.jsx(wn,{row:C,home:s,busy:Z(C),onToggle:c=>void F(c),onUninstall:c=>void q(c),onJump:z},C.path):i?e.jsx(Y,{title:"scanning plugins…"}):m?null:l.length===0?e.jsx(Y,{title:"No plugins installed",hint:"+ Add browses the plugin catalog."}):e.jsx(Y,{title:"No plugin matches the filter"});return e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[$.length>0?e.jsx(Mn,{seeders:$,seedStatus:h,onDismiss:c=>P(b=>new Set(b).add(c)),onOpenLibrary:X}):null,m?e.jsxs("div",{role:"alert",className:"shrink-0 px-3 py-2 border-b border-line bg-red-950/20 text-xs text-red-300",children:[m,l.length>0?" — showing the last known list":null]}):null,e.jsx(Ce,{list:p,detail:W})]})}const Ln=r.memo($n),he={"dev-plugin":"session-manager-dev plugin","scheduler-mcp":"Scheduler MCP server","agent-personas":"Agent personas (Architect, Dev Lead)"};function Mn({seeders:t,seedStatus:n,onDismiss:s,onOpenLibrary:l}){return e.jsx("div",{className:"shrink-0 flex flex-col gap-1.5 px-3 py-2 border-b border-line bg-yellow-950/20",children:t.map(o=>e.jsxs("div",{className:"flex items-start gap-2 text-xs text-yellow-300",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:n[o].status==="failed"?`${he[o]} setup failed — it will retry on next launch. To fix it now:`:`${he[o]} setup failed after retrying — manual fix needed`}),o==="dev-plugin"?e.jsxs("div",{className:"text-yellow-400/80 mt-0.5",children:["Click ",e.jsx("button",{onClick:l,className:"underline hover:no-underline",children:"here"}),' to open the Library tab, then click Install next to "session-manager-dev".']}):e.jsx("div",{className:"text-yellow-400/80 mt-0.5 font-mono",children:n[o].fix})]}),e.jsx("button",{onClick:()=>s(o),className:"shrink-0 text-yellow-400/70 hover:text-yellow-300","aria-label":`Dismiss ${he[o]} warning`,children:"✕"})]},o))})}const Pn=4;async function Tn(t,n,s){const l=new Array(t.length);let o=0;const i=Array.from({length:Math.min(n,t.length)},async()=>{for(;o<t.length;){const a=o++;l[a]=await s(t[a])}});return await Promise.all(i),l}function Ye(t,n){const s=oe();ae([s?`${s}/.claude/agents`:null,...t.map(l=>`${l}/.claude/agents`)],n)}function An({onOpenPersona:t}){const[n,s]=r.useState(se[0].tag),{personas:l,refresh:o}=Se(a=>H.error(a.message||"failed to load agent personas"));Ye([],()=>{o()});const i=se.find(a=>a.tag===n)??null;return e.jsx(Yt,{toolbar:e.jsxs("span",{className:"text-fg-faint",children:[se.length," tag",se.length===1?"":"s"]}),children:e.jsx(Ve,{sidebar:e.jsx("div",{className:"py-1",children:se.map(a=>{const m=Ee(a.tag),g=n===a.tag,f=(l==null?void 0:l.filter(x=>x.tags.includes(a.tag)).length)??0;return e.jsxs("button",{onClick:()=>{s(a.tag)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 border-l-2 ${g?"bg-bg-hi text-fg border-accent":"text-fg-dim hover:text-fg hover:bg-bg-hi border-transparent"}`,children:[e.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-mono font-semibold ${m.bg} ${m.text} ${m.border?"border border-current/30":""}`,children:["#",a.tag]}),e.jsx("span",{className:"truncate",children:a.label}),f>0&&e.jsx("span",{className:"ml-auto text-[10.5px] text-fg-faint font-mono shrink-0",children:f})]},a.tag)})}),detail:i?e.jsx(Rn,{entry:i,personas:l,onOpenPersona:t}):e.jsx(Y,{title:"select a tag"})})})}const Dn=r.memo(An);function Rn({entry:t,personas:n,onOpenPersona:s}){const l=Ee(t.tag),o=it(t.tag),i=(n==null?void 0:n.filter(a=>a.tags.includes(t.tag)))??[];return e.jsxs("div",{className:"p-4 space-y-4 max-w-3xl",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsxs("span",{className:`px-2 py-1 rounded text-xs font-mono font-semibold ${l.bg} ${l.text} ${l.border?"border border-current/30":""}`,children:["#",t.tag]}),e.jsx("span",{className:"text-sm font-semibold text-fg",children:t.label})]}),e.jsx("div",{className:"text-xs text-fg-dim leading-relaxed",children:t.description}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"/develop eagerness"}),e.jsx("span",{className:"px-1.5 py-0.5 text-[10px] rounded border border-line text-fg-dim font-mono",children:t.developEagerness})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"develops via"}),e.jsx("span",{className:"px-1.5 py-0.5 text-[10px] rounded border border-line text-fg-dim font-mono",children:t.developsVia})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"agents carrying this tag"}),n===null?e.jsx("div",{className:"text-xs text-fg-faint italic",children:"loading…"}):e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[i.map(a=>e.jsx("button",{onClick:()=>s==null?void 0:s(a.name),title:`Open ${a.name} in Personas`,className:"inline-flex items-center bg-bg-elev border border-line rounded px-2 py-0.5 text-[11px] font-mono text-fg-dim hover:text-fg hover:bg-bg-hi",children:a.name},a.name)),i.length===0&&e.jsx("span",{className:"text-xs text-fg-faint italic mr-1",children:"no agent carries this tag yet."})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wide text-fg-faint mb-1.5 font-mono",children:"opening framing — sent before the human's goal"}),e.jsx("pre",{className:"text-xs text-fg-dim whitespace-pre-wrap bg-bg-elev border border-line rounded p-3 leading-relaxed font-sans",children:o.initialPromptTemplate})]})]})}const In=t=>{const[n,s]=t.split(".");return Number(n)+(s?Number(s)/100:0)};function On(t){const n=/Effort is supported on ([^.]*?)(?:, with|\.|$)/.exec(t);if(!n)return[];const s=[];for(const l of n[1].split(/,\s*|\s+and\s+/)){const o=/^(\w+)\s+(\d+(?:\.\d+)?)$/.exec(l.trim());o&&s.push({family:o[1].toLowerCase(),version:In(o[2])})}return s}var Fe,_e;const Fn=On(String(((_e=(Fe=Lt.properties)==null?void 0:Fe.effortLevel)==null?void 0:_e.description)??""));function _n(t,n){const s=new RegExp(`${n}-(\\d+)(?:-(\\d{1,2})(?!\\d))?`,"i").exec(t);if(s)return Number(s[1])+(s[2]?Number(s[2])/100:0);const l=new RegExp(`claude-(\\d+)(?:-(\\d{1,2}))?-${n}`,"i").exec(t);return l?Number(l[1])+(l[2]?Number(l[2])/100:0):null}function Xe(t,n=Fn){if(!t||t==="inherit"||n.length===0)return null;const s=Q(t);if(!s)return null;const l=n.filter(i=>i.family===s);if(l.length===0)return!1;const o=_n(t,s);return o===null?null:o>=Math.min(...l.map(i=>i.version))}const be=["Read","Grep","Glob","Bash","Write","Edit","WebFetch","WebSearch","Task"],Bn=["","red","orange","yellow","green","cyan","blue","purple","pink"],De={red:"#c0392b",orange:"#b85c34",yellow:"#c9a227",green:"#6f7d52",cyan:"#3f8f8a",blue:"#4a6fa5",purple:"#7a6a8a",pink:"#b45a80"};function ve(t){return{name:t.name,description:t.description??"",tools:t.tools,model:t.model??"inherit",effort:t.effort??"inherit",color:t.color??"",tags:t.tags,body:t.body,agentCli:t.agentCli??"claude",agentCliModel:t.agentCliModel??""}}const Re={name:"new-agent",description:"",tools:["Read","Grep"],model:"inherit",effort:"inherit",color:"",tags:[],body:"",agentCli:"claude",agentCliModel:""};function $e(t){return[...t.fields.filter(n=>n!=="name"),...t.bodyOverridden?["full body"]:[]]}function Un(t){var s,l;const n=[(s=t.values)==null?void 0:s.model,(l=t.values)==null?void 0:l.effort].filter(o=>!!o);return t.bodyOverridden&&n.push("full body"),n.length?n.join(" · "):$e(t).join(", ")||"overlay"}function Hn({items:t}){const[n,s]=r.useState(!1),l=r.useRef(null),o=r.useRef(null),i=r.useId();return r.useEffect(()=>{if(!n)return;const a=g=>{var x,u;const f=g.target;(x=l.current)!=null&&x.contains(f)||(u=o.current)!=null&&u.contains(f)||s(!1)},m=g=>{g.key==="Escape"&&s(!1)};return window.addEventListener("mousedown",a),window.addEventListener("keydown",m),()=>{window.removeEventListener("mousedown",a),window.removeEventListener("keydown",m)}},[n]),e.jsxs("div",{className:"relative",children:[e.jsx("button",{ref:l,type:"button","data-testid":"agent-detail-more","aria-label":"More actions","aria-haspopup":"menu","aria-expanded":n,"aria-controls":n?i:void 0,onClick:()=>s(a=>!a),className:"h-9 w-9 inline-flex items-center justify-center rounded-[10px] bg-bg-hi border border-line text-fg-dim hover:text-fg hover:border-rule",children:"⋯"}),n&&e.jsx("div",{ref:o,id:i,role:"menu","aria-label":"More actions","data-testid":"agent-detail-more-menu",className:`absolute ${Be.dialog} right-0 top-[42px] min-w-[200px] p-[5px] flex flex-col bg-bg-hi border border-line rounded-lg shadow-lg text-[13px] text-fg`,children:t.map(a=>a.info?e.jsx("div",{role:"note","data-testid":a.testId,className:"px-2.5 pb-[7px] pt-0.5 text-[11px] text-fg-faint whitespace-nowrap border-b border-line mb-1",children:a.label},a.testId):e.jsx("button",{type:"button",role:"menuitem","data-testid":a.testId,disabled:a.disabled,onClick:()=>{s(!1),a.onSelect()},className:`px-2.5 py-[7px] rounded-[5px] text-left whitespace-nowrap hover:bg-bg-elev disabled:opacity-40 ${a.danger?"text-red-400":""}`,children:a.label},a.testId))})]})}function re({children:t}){return e.jsx("span",{className:"shrink-0 w-[150px] text-[11px] font-semibold uppercase tracking-[0.1em] text-fg-faint pt-1",children:t})}function Gn({obj:t,set:n,saved:s,dirty:l,isNew:o,busy:i,confirmDelete:a,setConfirmDelete:m,onDuplicate:g,onRevert:f,onSave:x,onDelete:u,onDropOverride:y,projects:h,selected:w,onSelect:S,onSaveOverride:P}){const E=oe(),{catalog:O,loading:A,degraded:j,refresh:D}=ue(null),{checking:L,recheck:_}=Ue(),[M,N]=r.useState(!1),F=!o&&s?s.path:`${E??"~"}/.claude/agents/${t.name}.md`,q=l||o,$=s&&!o?s.overrideDetails??[]:[],G=!o&&!!s&&(M||w!==null),J=t.tools.length===0,k=O?`Models live-read from claude${O.claudeVersion?` ${O.claudeVersion}`:""}${j?" (cached — CLI probe unavailable)":""}`:A?"Loading model catalog…":"Model catalog unavailable — showing the standard list",C=[{label:A||L?"Re-checking…":"Re-check models & CLIs",testId:"agent-detail-recheck",disabled:A||L,onSelect:()=>{D(),_()}},{label:k,testId:"agent-detail-catalog-info",disabled:!0,info:!0,onSelect:()=>{}},{label:"Reveal in File Explorer",testId:"agent-detail-reveal",disabled:o,onSelect:()=>Ne(F)},...o?[]:[{label:"Delete agent…",testId:"agent-detail-delete",danger:!0,disabled:i,onSelect:()=>m(!0)}]],X=p=>{if(J){n({tools:be.filter(W=>W!==p)});return}n({tools:t.tools.includes(p)?t.tools.filter(W=>W!==p):[...t.tools,p]})},z=e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:g,disabled:i,className:"h-9 px-4 rounded-[10px] bg-bg-hi border border-line text-[13.5px] font-medium text-fg hover:border-rule disabled:opacity-40",children:"Duplicate"}),e.jsx(Hn,{items:C})]}),Z=$.length===0?o?"save first to see project overrides.":"no open project overlays this agent — the global definition applies everywhere.":$.length===1?`a local copy in ${me($[0].cwd,E)}/.claude/agents/ wins there`:"each project's local copy in its .claude/agents/ wins there";return e.jsxs("div",{"data-testid":"agent-detail",className:"flex-1 shrink-0 min-h-full flex flex-col",children:[e.jsx(Ke,{eyebrow:`AGENT · USER · ${me(F,E)}`,title:t.name,pill:o?"unsaved draft":l?"edited":void 0,actions:z}),a&&e.jsxs("div",{"data-testid":"agent-detail-delete-confirm",role:"alert",className:"shrink-0 mx-9 mt-4 px-4 py-2.5 rounded-[10px] border border-red-400/40 bg-red-400/10 flex items-center gap-3 text-[13px] text-fg",children:[e.jsxs("span",{className:"flex-1 min-w-0",children:["Delete ",e.jsx("strong",{className:"font-mono",children:t.name})," and its file?"]}),e.jsx("button",{type:"button",onClick:u,disabled:i,className:"font-semibold text-red-400 hover:text-red-300",children:"Delete"}),e.jsx("button",{type:"button",onClick:()=>m(!1),className:"text-fg-faint hover:text-fg",children:"Keep"})]}),e.jsxs("div",{"data-testid":"agent-detail-body",className:"flex-1 shrink-0 flex flex-col gap-4 px-9 py-6",children:[e.jsx(pe,{label:"DESCRIPTION",labelNote:"CLAUDE READS THIS TO PICK THE AGENT",children:e.jsx("textarea",{"data-testid":"agent-detail-description","aria-label":"Description",rows:2,value:t.description,onKeyDown:p=>{p.key==="Enter"&&p.preventDefault()},onChange:p=>n({description:p.target.value.replace(/\r?\n/g," ")}),placeholder:"What this agent does — Claude reads it to decide when to use it",className:"w-full resize-none bg-transparent outline-none text-fg placeholder:text-fg-faint"})}),e.jsxs("section",{"data-testid":"agent-runtime-card",className:"px-[18px] py-4 rounded-[14px] bg-bg-hi border border-line flex flex-col gap-4",children:[e.jsxs("div",{"data-testid":"agent-runtime-row",className:"grid grid-cols-3 gap-4",children:[e.jsx(Vn,{value:t.model,onChange:p=>n({model:p})}),e.jsx(Kn,{value:t.effort,model:t.model,onChange:p=>n({effort:p})}),e.jsxs("div",{className:"min-w-0 flex flex-col gap-1.5",children:[e.jsx(zn,{value:t.agentCli,onChange:p=>n({agentCli:p,agentCliModel:""})}),t.agentCli!=="claude"&&e.jsx("input",{"data-testid":"agent-persona-cli-model","aria-label":"CLI model",value:t.agentCliModel,maxLength:128,placeholder:"Blank = the CLI's own default",onChange:p=>n({agentCliModel:p.target.value}),className:"w-full bg-bg border border-line rounded-md px-2 py-1 text-xs text-fg font-mono"})]})]}),e.jsxs("div",{className:"flex items-start gap-3","data-testid":"agent-tools-row",children:[e.jsx(re,{children:"tools"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5",children:be.map(p=>{const W=J||t.tools.includes(p);return e.jsx("button",{type:"button","aria-pressed":W,"data-tool":p,onClick:()=>X(p),className:`px-2 py-0.5 rounded-md text-[12px] font-mono border ${W?"bg-honey/20 text-honey-dark border-honey/40":"bg-transparent text-fg-faint border-dashed border-rule"}`,children:p},p)})}),e.jsx("div",{"data-testid":"agent-tools-note",className:"text-[11px] text-fg-faint mt-1 leading-snug",children:J?"All tools — no tools: line, so every tool (MCP included) is granted. Click one to restrict.":e.jsxs(e.Fragment,{children:[t.tools.length," of ",be.length," granted. Anything not filled is refused at call time."," ",e.jsx("button",{type:"button","data-testid":"agent-tools-all",onClick:()=>n({tools:[]}),className:"underline text-fg-dim hover:text-fg",children:"Grant all tools"})]})})]})]}),e.jsxs("div",{className:"flex items-start gap-3","data-testid":"agent-overrides-row",children:[e.jsx(re,{children:"project overrides"}),e.jsxs("div",{className:"flex-1 min-w-0 flex flex-wrap items-center gap-2 pt-0.5",children:[$.map(p=>e.jsxs("span",{"data-testid":"agent-override-chip",title:`${me(p.cwd,E)}/.claude/agents/${s.name}.md`,className:"inline-flex items-center gap-1.5 bg-bg-elev border border-line rounded-md px-2 py-0.5 text-[12px] font-mono text-fg-dim",children:[e.jsx("strong",{className:"font-sans font-semibold text-fg",children:p.project}),Un(p),e.jsx("button",{onClick:()=>y(p.cwd,p.project),title:"Drop the local copy",className:"text-fg-faint hover:text-fg",children:"×"})]},p.cwd)),e.jsx("span",{className:`text-[12px] text-fg-faint ${$.length===0?"italic":""}`,children:Z}),!o&&s&&!G&&e.jsx("button",{type:"button","data-testid":"agent-override-add",onClick:()=>N(!0),className:"text-[12px] font-medium text-accent hover:underline",children:"+ Add override"})]})]}),G&&s&&e.jsx(Xn,{saved:s,projects:h,selected:w,onSelect:S,busy:i,onSave:P,onClose:()=>{N(!1),S(null)}}),e.jsxs("details",{"data-testid":"agent-details",open:o||void 0,className:"group border-t border-line pt-3",children:[e.jsxs("summary",{className:"cursor-pointer select-none flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.1em] text-fg-faint",children:[e.jsx("span",{children:"details"}),e.jsxs("span",{className:"normal-case tracking-normal font-normal font-mono text-fg-dim flex items-center gap-1.5",children:[t.color&&e.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-sm",style:{background:De[t.color]}}),t.color||"no colour"," · ",t.tags.length?t.tags.map(p=>`#${p}`).join(" "):"no tags"]})]}),e.jsxs("div",{className:"flex flex-col gap-3 pt-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(re,{children:"name"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("input",{"data-testid":"agent-detail-name","aria-label":"Name",value:t.name,onChange:p=>n({name:p.target.value.toLowerCase()}),className:"w-full max-w-sm bg-bg border border-line rounded px-2 py-1 text-xs text-fg font-mono"}),e.jsx("div",{className:"text-[11px] text-fg-faint mt-1 leading-snug",children:"Filename on disk — lowercase, hyphenated."})]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(re,{children:"color"}),e.jsx("div",{className:"flex gap-1.5 pt-0.5",children:Bn.map(p=>e.jsx("button",{type:"button",title:p||"none",onClick:()=>n({color:p}),className:"w-5 h-5 rounded",style:{background:p?De[p]:"transparent",border:t.color===p?"2px solid var(--accent, #b85c34)":"1px solid var(--line, #555)"}},p||"none"))})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(re,{children:"tags"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5",children:se.map(p=>{const W=t.tags.includes(p.tag),c=Ee(p.tag);return e.jsxs("button",{type:"button",onClick:()=>n({tags:W?t.tags.filter(b=>b!==p.tag):[...t.tags,p.tag]}),className:`px-2 py-0.5 rounded-full text-[11px] font-mono border ${W?`${c.bg} ${c.text} ${c.border?"border-current/30":"border-transparent"}`:"bg-bg-hi text-fg-faint border-line"}`,children:["#",p.tag]},p.tag)})}),e.jsx("div",{className:"text-[11px] text-fg-faint mt-1 leading-snug",children:"Session mission tags this persona is associated with — shown as the default agent on the Tags tab."})]})]})]})]})]}),e.jsx("div",{"data-testid":"agent-detail-editor","data-busy":i?"true":void 0,className:"flex-1 shrink-0 min-h-[320px] grid rounded-[14px] border border-line bg-bg-hi overflow-hidden",children:e.jsx(Mt,{path:F,value:t.body,defaultMode:"document",dirty:q,isNew:o,onChange:p=>n({body:p}),onSave:()=>{i||x()},onRevert:f})})]})]})}const Wn="w-full h-9 appearance-none pl-3 pr-8 rounded border border-line bg-bg-hi font-mono text-[13px] text-fg focus:outline-none focus:border-fg-faint disabled:opacity-60";function Le({label:t,hint:n,testId:s,value:l,onChange:o,children:i}){return e.jsxs("label",{className:"min-w-0 flex flex-col gap-1.5",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.1em] text-fg-faint",children:t}),e.jsxs("span",{className:"relative block",children:[e.jsx("select",{"data-testid":s,"aria-label":t,title:n,value:l,onChange:a=>o(a.target.value),className:Wn,children:i}),e.jsx("svg",{"aria-hidden":!0,"data-testid":`${s}-chevron`,viewBox:"0 0 16 16",className:"pointer-events-none absolute right-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-fg-faint",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:e.jsx("path",{d:"M4 6l4 4 4-4"})})]})]})}const Ie=t=>{var n;return((n=/\[[^\]]*\]$/.exec(t))==null?void 0:n[0])??""};function Vn({value:t,onChange:n}){const{catalog:s}=ue(null),l=s?["inherit",...s.aliases]:[...He],o=(s==null?void 0:s.availableModels)??null,i=[];if(s){const u=new Set,y=h=>{!u.has(h)&&!l.includes(h)&&(u.add(h),i.push(h))};for(const h of s.models)y(h);for(const h of s.aliases){const w=Q(h),S=Ie(h);if(w&&S)for(const P of s.models)Q(P)===w&&y(P+S)}}const a=u=>!!o&&u!=="inherit"&&!o.includes(u),m=u=>{const y=Q(u);return!!o&&!o.includes(u)&&!(y&&o.includes(y+Ie(u)))&&!(y&&o.includes(y))},g=t||"inherit",f=l.includes(g)||i.includes(g);return e.jsxs(Le,{label:"model",hint:"This persona's default model for its Epics — sets the --model an Epic launches with (Terminal + Chat both honor it). 'inherit' falls back to each view's own default, not this Settings page. Cheap models for read-only personas; opus for judgement calls. Pinned versions fix a concrete id; an alias floats to the latest.",testId:"model-select",value:g,onChange:n,children:[!f&&e.jsxs("option",{value:g,children:[g," (current)"]}),e.jsx("optgroup",{label:"Aliases",children:l.map(u=>e.jsx("option",{value:u,disabled:!!s&&a(u),title:a(u)?ge:void 0,children:u},u))}),i.length>0&&e.jsx("optgroup",{label:"Pinned versions",children:i.map(u=>e.jsx("option",{value:u,disabled:m(u),title:m(u)?ge:void 0,children:u},u))})]})}function Kn({value:t,model:n,onChange:s}){const{catalog:l}=ue(null),o=l&&l.effortLevels.length?["inherit",...l.effortLevels]:[...Ge],i=(l==null?void 0:l.settingsEffortLevels)??[],a=l?o.filter(x=>x!=="inherit"&&!i.includes(x)):[],m=t||"inherit",g=m!=="inherit"&&Xe(n)===!1,f=l?`Effort levels are live-read from the installed claude CLI (what /effort accepts). ${a.length?`${a.join(", ")} ${a.length>1?"are":"is"} session-only — settings.json accepts ${i.join(", ")}. `:""}'inherit' writes no effort: line.`:"Catalog unavailable — showing the standard list. 'inherit' writes no effort: line.";return e.jsxs("div",{className:"min-w-0 flex flex-col gap-1",children:[e.jsxs(Le,{label:"effort",hint:f,testId:"effort-select",value:m,onChange:s,children:[!o.includes(m)&&e.jsxs("option",{value:m,children:[m," (current)"]}),o.map(x=>e.jsx("option",{value:x,children:a.includes(x)?`${x} (session-only)`:x},x))]}),g&&e.jsx("div",{className:"text-[11px] text-amber-400 leading-snug","data-testid":"effort-unsupported-note",children:"This model ignores effort."})]})}const Jn=["codex","gemini","antigravity","cursor","opencode"];function zn({value:t,onChange:n}){const{rows:s}=Ue(),l=new Map((s??[]).map(i=>[i.id,i]));return e.jsxs(Le,{label:"runs on",hint:"Which coding-agent CLI New Session starts this persona on — override per session in New Session → advanced. On a non-Claude CLI the session has no develop loop, no Restore, and this persona's model/effort are not used. Macros, phone launches and scheduled PRDs always run Claude Code.",testId:"agent-persona-cli-select",value:t,onChange:i=>n(i),children:[e.jsx("option",{value:"claude",children:"Claude Code"}),Jn.map(i=>{const a=l.get(i),m=(a==null?void 0:a.label)||rt[i],g=!!(a!=null&&a.installed),f=a?g?"":" (not installed)":s===null?" (checking…)":" (not detected)",x=a?g?[a.version,a.path].filter(Boolean).join(" · ")||void 0:a.install??"Not installed":void 0;return e.jsxs("option",{value:i,disabled:!g&&t!==i,title:x,children:[m,f]},i)})]})}function Ze({label:t,hint:n,children:s}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-[0.1em] text-fg-faint mb-1.5",children:t}),s,n&&e.jsx("div",{className:"text-[11px] text-fg-faint mt-1 leading-snug",children:n})]})}const je="latest",ge="Blocked by the availableModels allowlist in your Claude settings";function qn({value:t,onChange:n,label:s="model",hint:l,testIdPrefix:o="",inheritLabel:i}){var F,q;const{catalog:a,loading:m,degraded:g,refresh:f}=ue(null),x=a?["inherit",...a.aliases]:[...He],u=(a==null?void 0:a.availableModels)??null,y=$=>!!u&&$!=="inherit"&&!u.includes($),h=($,G)=>!!u&&!u.includes($)&&!(G&&u.includes(G)),w=t||"inherit",S=((F=/\[[^\]]*\]$/.exec(w))==null?void 0:F[0])??"",P=x.includes(w),E=!P&&a&&Q(w)&&x.includes(Q(w)+S)?Q(w)+S:null,O=P?w:E??w,A=Q(O),j=((q=/\[[^\]]*\]$/.exec(O))==null?void 0:q[0])??"",D=!!a&&w!=="inherit"&&!!A&&x.includes(O),L=D?a.models.filter($=>Q($)===A).map($=>$+j):[],_=P?je:w,M={};if(a)for(const $ of x)y($)&&(M[$]=ge);const N={};for(const $ of L)h($,A)&&(N[$]=ge);return e.jsxs(Ze,{label:s,hint:l??"This persona's default model for its Epics — sets the --model an Epic launches with (Terminal + Chat both honor it). 'inherit' falls back to each view's own default, not this Settings page. Cheap models for read-only personas; opus for judgement calls.",children:[e.jsx("div",{"data-testid":`${o}model-row`,children:e.jsx(we,{options:x,value:O,onChange:n,mono:!0,blocked:M,labels:i?{inherit:i}:void 0})}),D&&e.jsxs("div",{className:"mt-2","data-testid":`${o}model-version-row`,children:[e.jsx("div",{className:"text-[10.5px] text-fg-faint mb-1 font-mono",children:"version"}),e.jsx(we,{options:[je,...L],value:_,onChange:$=>n($===je?O:$),mono:!0,blocked:N})]}),e.jsxs("div",{className:"text-[11px] text-fg-faint mt-1 leading-snug flex items-center gap-2",children:[e.jsx("span",{children:a?`Models are live-read from the installed claude CLI${g?" (cached — CLI probe unavailable)":""}. "latest" keeps the floating alias.`:m?"Loading model catalog…":"catalog unavailable — showing the standard list."}),e.jsx("button",{"data-testid":`${o}model-catalog-refresh`,onClick:()=>{f()},disabled:m,className:"underline text-fg-dim disabled:opacity-40",children:"refresh"})]})]})}function Yn({value:t,model:n,onChange:s,label:l="effort",testIdPrefix:o="",inheritLabel:i}){const{catalog:a}=ue(null),m=a&&a.effortLevels.length?["inherit",...a.effortLevels]:[...Ge],g=(a==null?void 0:a.settingsEffortLevels)??[],f=a?m.filter(y=>y!=="inherit"&&!g.includes(y)):[],x=t||"inherit",u=x!=="inherit"&&Xe(n)===!1;return e.jsxs(Ze,{label:l,hint:a?`Effort levels are live-read from the installed claude CLI (what /effort accepts). ${f.length?`${f.join(", ")} ${f.length>1?"are":"is"} session-only — settings.json accepts ${g.join(", ")}. `:""}'inherit' writes no effort: line.`:"catalog unavailable — showing the standard list. 'inherit' writes no effort: line.",children:[e.jsx("div",{"data-testid":`${o}effort-row`,children:e.jsx(we,{options:m,value:x,onChange:s,mono:!0,labels:i?{inherit:i}:void 0})}),f.length>0&&e.jsx("div",{className:"text-[11px] text-fg-faint mt-1 font-mono","data-testid":`${o}effort-session-only`,children:f.map(y=>`${y} (session-only)`).join(" · ")}),u&&e.jsx("div",{className:"text-[11px] text-amber-400 mt-1 leading-snug","data-testid":`${o}effort-unsupported-note`,children:"The selected model does not support effort — the CLI will ignore this setting."})]})}function Xn({saved:t,projects:n,selected:s,onSelect:l,busy:o,onSave:i,onClose:a}){var E,O,A;const m=oe(),g=r.useId(),f=new Map;for(const j of n)f.set(j.name,(f.get(j.name)??0)+1);const x=j=>{var M;const D=(f.get(j.name)??0)>1?me(j.cwd,m):j.name,L=(M=t.overrideDetails)==null?void 0:M.find(N=>N.cwd===j.cwd);if(!L)return D;const _=$e(L);return`${D} — ${_.length?`overrides ${_.join(", ")}`:"overlay"}`},u=s?(E=t.overrideDetails)==null?void 0:E.find(j=>j.cwd===s.cwd):void 0,y=!!(u!=null&&u.bodyOverridden),h=((O=u==null?void 0:u.values)==null?void 0:O.model)??"inherit",w=((A=u==null?void 0:u.values)==null?void 0:A.effort)??"inherit",S=t.model??"inherit",P=t.effort??"inherit";return e.jsxs("div",{"data-testid":"project-override-block",className:s?"border border-accent/40 rounded p-3 space-y-3 bg-accent/5":"border border-dashed border-line rounded p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("label",{htmlFor:g,className:`flex-1 text-[10.5px] font-semibold uppercase tracking-wide font-mono ${s?"text-accent":"text-fg-faint"}`,children:"project override"}),e.jsx("button",{type:"button","data-testid":"override-close",onClick:a,className:"text-[11px] text-fg-faint hover:text-fg",children:"Done"})]}),e.jsx("div",{className:"flex flex-col gap-1",children:e.jsxs("select",{id:g,"data-testid":"override-project-select",value:(s==null?void 0:s.cwd)??"",onChange:j=>l(j.target.value||null),disabled:o||n.length===0,className:"rounded-md border border-line bg-bg px-2 py-1.5 font-mono text-[12.5px] text-fg disabled:opacity-60",children:[e.jsx("option",{value:"",children:"Choose a project…"}),n.map(j=>e.jsx("option",{value:j.cwd,children:x(j)},j.cwd))]})}),n.length===0?e.jsx("div",{"data-testid":"project-override-none",className:"text-[11px] text-fg-faint leading-snug",children:"No open project tabs — open a project tab to override this persona's model or effort for it."}):s?e.jsxs("div",{"data-testid":"project-override",className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(We,{tone:"accent",children:[s.name," only"]}),e.jsx("span",{className:"ml-auto min-w-0",children:e.jsx(zt,{path:`${s.cwd}/.claude/agents/${t.name}.md`})})]}),e.jsxs("div",{className:"text-[11px] text-fg-faint leading-snug",children:["Changes what the SCHEDULER (and new Epics) spawn for ",e.jsx("strong",{children:s.name})," only — a frontmatter-only overlay with just the keys you set; the persona's body stays the global one. The global model/effort rows edit the machine-wide persona and are never touched here."]}),y&&e.jsxs("div",{"data-testid":"project-override-fullbody",className:"text-[11px] text-amber-400 leading-snug",children:[s.name,' already has a FULL-BODY override of this persona (its own definition text). It is shown as-is and not converted to a frontmatter-only overlay — edit that file directly, or drop it with its × in the "project overrides" row above.']}),e.jsxs("fieldset",{disabled:o||y,className:"space-y-3 border-0 p-0 m-0 min-w-0",children:[e.jsx(qn,{value:h,onChange:j=>{y||i({model:j,effort:w})},label:"project model",hint:"'use global' writes no model: line in the overlay.",testIdPrefix:"override-",inheritLabel:"use global"}),e.jsx(Yn,{value:w,model:h!=="inherit"?h:S,onChange:j=>{y||i({model:h,effort:j})},label:"project effort",testIdPrefix:"override-",inheritLabel:"use global"})]}),e.jsx("div",{"data-testid":"override-provenance",className:"text-[11px] font-mono text-fg-dim space-y-0.5",children:[["model",S,h],["effort",P,w]].map(([j,D,L])=>e.jsxs("div",{"data-testid":`override-provenance-${j}`,children:[j,": ",L!=="inherit"?e.jsxs(e.Fragment,{children:[D," ",e.jsx("span",{className:"text-fg-faint",children:"(global)"})," → ",e.jsx("span",{className:"text-accent",children:L})," ",e.jsx("span",{className:"text-fg-faint",children:"(this project)"})]}):e.jsxs(e.Fragment,{children:[D," ",e.jsx("span",{className:"text-fg-faint",children:"(global — not overridden)"})]})]},j))})]}):e.jsx("div",{"data-testid":"project-override-unselected",className:"text-[11px] text-fg-faint leading-snug",children:"Pick an open project to see or set this persona's model and effort for that project only. A project that already overrides this persona says what it overrides."})]})}const Zn=new Set(se.map(t=>t.tag));function Qe(t){return t.filter(n=>Zn.has(n))}function Qn(t,n={}){return{name:t.name,originalName:t.name,description:t.description??"",tools:t.tools,model:t.model??"inherit",effort:t.effort??void 0,color:t.color??"",tags:Qe(t.tags),projects:t.projects,action:t.action??void 0,actionLabel:t.actionLabel??void 0,title:t.title??void 0,body:t.body,...t.agentCli?{agentCli:t.agentCli}:{},...t.agentCliModel?{agentCliModel:t.agentCliModel}:{},...n}}function es(t){const n=new Map;for(const s of t){const l=typeof s.cwd=="string"?dt(s.cwd):"";l&&!n.has(l)&&n.set(l,{cwd:l,name:ut(l)})}return[...n.values()].sort((s,l)=>s.name.localeCompare(l.name)||s.cwd.localeCompare(l.cwd))}function ts(t){return(t.overrideDetails??[]).map(n=>`${n.project}: ${$e(n).join(", ")||"overlay"}`).join(`
3
+ `)}const ns=[{key:"personas",label:"Personas"},{key:"tags",label:"Tags"}];function ss(){const[t,n]=r.useState("personas"),{personas:s,refresh:l}=Se(d=>H.error(d.message||"failed to load agent personas")),[o,i]=r.useState(null),[a,m]=r.useState(""),[g,f]=r.useState(null),[x,u]=r.useState(!1),[y,h]=r.useState(!1),[w,S]=r.useState(null),[P,E]=r.useState(!1),O=r.useRef(!0);r.useEffect(()=>()=>{O.current=!1},[]);const A=ct(d=>d.tabs),j=r.useMemo(()=>es(A),[A]),[D,L]=r.useState(null),_=j.find(d=>d.cwd===D)??null,M=async d=>{await l()&&d&&i(d)};Ye(j.map(d=>d.cwd),()=>M()),r.useEffect(()=>{const d=ft();d&&i(d);const T=I=>i(I.detail);return window.addEventListener("sm:select-persona",T),()=>window.removeEventListener("sm:select-persona",T)},[]);const N=le(d=>d.tab),F=le(d=>d.id),q=le(d=>d.clear);r.useEffect(()=>{if(N!=="agents"||!F||s===null)return;const d=F.startsWith("agents:")?F.slice(7):null;d&&s.some(T=>T.name===d)&&(n("personas"),m(""),f(null),u(!1),h(!1),S(null),i(d)),q()},[N,F,s,q]);const $=e.jsx(Je,{eyebrow:"AGENTS FOLDER",badge:s==null?void 0:s.length,path:"~/.claude/agents/",note:"The actor a session opens with — “you are acting as …”",children:e.jsx("div",{role:"group","aria-label":"Agents view","data-testid":"agent-view-switch",className:"mt-1 self-start inline-flex items-center p-0.5 rounded bg-bg-hi border border-line",children:ns.map(d=>e.jsx("button",{type:"button",onClick:()=>n(d.key),"aria-pressed":t===d.key,className:`px-2.5 py-0.5 text-[11px] rounded transition-colors ${t===d.key?"bg-bg text-fg font-medium shadow-sm":"text-fg-dim hover:text-fg"}`,children:d.label},d.key))})});if(t==="tags")return e.jsx("div",{className:"flex flex-col h-full min-h-0",children:e.jsx(Ce,{list:$,detail:e.jsx(Dn,{onOpenPersona:d=>{i(d),f(null),u(!1),n("personas")}})})});if(s===null)return e.jsx(Y,{title:"loading…"});const G=a.toLowerCase(),J=s.filter(d=>!G||d.name.toLowerCase().includes(G)||(d.description??"").toLowerCase().includes(G)),k=s.find(d=>d.name===o)??s[0]??null,C=g??(k?ve(k):null),X=!!g&&!!k&&JSON.stringify(g)!==JSON.stringify(ve(k)),z=x,Z=d=>{f(null),u(!1),h(!1),S(null),i(d)},p=d=>f(T=>({...T??(k?ve(k):Re),...d})),W=()=>{f({...Re}),u(!0),h(!1)},c=()=>{C&&(f({...C,name:C.name+"-copy"}),u(!0))},b=()=>{f(null),u(!1)},R=async()=>{if(C){if(!/^[a-z][a-z0-9-]*$/.test(C.name)){H.error('agent name must be lowercase, hyphenated (e.g. "my-agent")');return}E(!0);try{const d=z?null:k,T={name:C.name,originalName:d==null?void 0:d.name,description:C.description,tools:C.tools,model:C.model,effort:C.effort,color:C.color,tags:Qe(C.tags),body:C.body,agentCli:C.agentCli,...C.agentCli!=="claude"&&C.agentCliModel.trim()?{agentCliModel:C.agentCliModel.trim()}:{}},I=d?Qn(d,T):T;"agentCliModel"in T||delete I.agentCliModel,await window.api.agents.savePersona(I),H.info(z?`created ${C.name}`:`saved ${C.name}`),f(null),u(!1),await M(C.name)}catch(d){H.error(d.message||"failed to save agent persona")}finally{E(!1)}}},U=async()=>{if(k){E(!0);try{await window.api.agents.deletePersona({name:k.name}),H.info(`deleted ${k.name}`),h(!1),f(null),u(!1),await M()}catch(d){H.error(d.message||"failed to delete agent persona")}finally{E(!1)}}},ee=async d=>{E(!0);try{await window.api.agents.deletePersona({name:d}),H.info(`deleted ${d}`),S(null),o===d&&(f(null),u(!1)),await M()}catch(T){H.error(T.message||"failed to delete agent persona")}finally{E(!1)}},te=async(d,T)=>{if(k)try{await window.api.agents.removeOverride({name:k.name,projectCwd:d}),H.info(`removed ${T}'s override of ${k.name}`),await M(k.name)}catch(I){H.error(I.message||"failed to remove override")}},B=async d=>{if(!k||!_)return;const{cwd:T,name:I}=_;E(!0);try{d.model==="inherit"&&d.effort==="inherit"?(await window.api.agents.removeOverride({name:k.name,projectCwd:T}),H.info(`cleared ${I}'s override of ${k.name}`)):(await window.api.agents.savePersona({name:k.name,projectCwd:T,description:"",tools:[],color:"",tags:[],body:"",model:d.model,effort:d.effort}),H.info(`saved ${I}'s override of ${k.name}`)),await M(k.name)}catch(v){H.error(v.message||"failed to save project override")}finally{E(!1)}},ne=e.jsxs(e.Fragment,{children:[$,e.jsx(ze,{filter:a,onFilterChange:m,placeholder:"Filter",primaryLabel:"+ New",onPrimary:W}),e.jsxs("div",{role:"listbox","aria-label":"Agents",className:"flex flex-col gap-0.5",children:[z&&C&&e.jsx("div",{"data-agent-row-new":"",children:e.jsx(ke,{title:C.name,trailing:e.jsx("span",{className:"text-[10px] font-semibold text-accent",children:"new"}),meta:C.description||void 0,selected:!0,onSelect:()=>{}})}),J.length===0&&!z?e.jsx("div",{className:"px-3 py-1 text-xs text-fg-faint italic",children:"no agent personas found"}):J.map(d=>{const T=!z&&d.name===(k==null?void 0:k.name),I=T&&X,v=w===d.name;return e.jsx("div",{"data-agent-row":d.name,className:"group",children:e.jsx(ke,{title:d.name,selected:T,onSelect:()=>Z(d.name),meta:d.description||void 0,trailing:e.jsxs("span",{className:"flex items-center gap-1.5",children:[I&&e.jsx("span",{className:"text-[10px] font-semibold text-accent",children:"unsaved"}),!I&&d.overridingProjects.length>0&&e.jsx("span",{title:ts(d),children:e.jsxs(We,{tone:"dim",children:[d.overridingProjects.length," override",d.overridingProjects.length>1?"s":""]})}),e.jsx("span",{"data-testid":"agent-row-model",className:"font-mono",children:d.model??"inherit"}),v?e.jsxs("span",{className:"flex items-center gap-1",onClick:V=>V.stopPropagation(),children:[e.jsx("button",{type:"button",onClick:()=>ee(d.name),disabled:P,title:`Delete ${d.name}`,className:"text-[10px] font-semibold text-red-400 hover:text-red-300",children:"confirm"}),e.jsx("button",{type:"button",onClick:()=>S(null),title:"Cancel",className:"text-[10px] text-fg-faint hover:text-fg",children:"cancel"})]}):e.jsx("button",{type:"button",onClick:V=>{V.stopPropagation(),S(d.name)},title:`Delete ${d.name}`,"aria-label":`Delete ${d.name}`,className:"opacity-0 group-hover:opacity-100 focus-visible:opacity-100 text-fg-faint hover:text-red-400 transition-opacity",children:"×"})]})})},d.name)})]})]});return e.jsx("div",{className:"flex flex-col h-full min-h-0",children:e.jsx(Ce,{list:ne,detail:C?e.jsx(Gn,{obj:C,set:p,saved:k,dirty:X,isNew:z,busy:P,confirmDelete:y,setConfirmDelete:h,onDuplicate:c,onRevert:b,onSave:R,onDelete:U,onDropOverride:te,projects:j,selected:_,onSelect:L,onSaveOverride:B}):e.jsx(Y,{title:"select an agent"})})})}const as=r.memo(ss),ls={"claude-md":"system-prompt",settings:"settings",mcp:"extensions",skills:"extensions",plugins:"extensions",agents:"agent-library"},os={skills:"Add skill",mcp:"Add MCP server",plugins:"Add plugin"},ce=t=>t??void 0;async function Oe(t){try{return await t()}catch{return null}}function is(){const t=oe(),[n,s]=r.useState({claudeMd:null,settings:null}),l=r.useRef(0),o=t?`${t}/.claude/CLAUDE.md`:null,i=t?`${t}/.claude/settings.json`:null,a=r.useCallback(()=>{if(!o||!i)return;const m=++l.current;Promise.all([Oe(()=>Wt(o)),Oe(()=>Vt(i))]).then(([g,f])=>{m===l.current&&s({claudeMd:g,settings:f})})},[o,i]);return r.useEffect(()=>(a(),()=>{l.current++}),[a]),ae([o,i],a),n}const rs=()=>Kt({scope:"home",cwd:null,api:window.api});function cs({initialTab:t="claude-md"}){const[n,s]=r.useState(t),[l,o]=r.useState(!1),[i,a]=r.useState(!1),[m,g]=r.useState({scope:"user",cwd:null}),f=sn(),{personas:x}=Se(),u=is(),y=Pt(Tt),h=r.useMemo(()=>At(y),[y]),w=ye(N=>N.panelTabHint);r.useEffect(()=>{if(!w||w.id!=="claude-config")return;const[N,F]=w.tab.split(":");Pe(N)&&(s(N),o(!1)),ye.setState({panelTabHint:N==="settings"&&F?{id:"settings",tab:F}:null})},[w]);const S=r.useCallback(N=>{s(N),o(!1)},[]),P=r.useCallback(()=>o(!1),[]),E=r.useCallback(()=>o(!0),[]),O=r.useCallback(N=>{g(N),o(!0)},[]),A=r.useCallback(()=>a(N=>!N),[]),j=r.useCallback(N=>{Pe(N.tab)&&(S(N.tab),le.getState().set(N.tab,N.id))},[S]),D=Dt({load:rs,loadKey:"home",onChoose:j}),L=r.useMemo(()=>{const N={"claude-md":Rt(u.claudeMd),settings:{count:ce(u.settings)},mcp:{count:ce(f.mcp),attention:h},skills:{count:ce(f.skills)},plugins:{count:ce(f.plugins)},agents:{count:ce(x==null?void 0:x.length)}};return mt.map(F=>({...F,...N[F.key]}))},[u.claudeMd,u.settings,f.mcp,f.skills,f.plugins,x,h]),_=pt[ls[n]],M=n==="skills"||n==="mcp"||n==="plugins"?n:null;return e.jsxs("div",{className:"h-full w-full flex flex-col bg-bg text-fg","data-testid":"home-claude-config",children:[e.jsx(It,{eyebrow:"CLAUDE CODE · GLOBAL",title:"Claude config",scopePath:"~/.claude",tabs:L,activeKey:n,onSelect:S,onLearn:A,...D.bandProps,searchPanel:e.jsx(Ot,{...D.panelProps,tabs:L})}),i&&_&&e.jsx("div",{className:"shrink-0 border-b border-line bg-bg-elev px-7 py-4 max-h-[40vh] overflow-y-auto","data-testid":"home-claude-config-learn",children:e.jsx(gt,{content:_})}),e.jsxs("div",{className:"flex-1 min-h-0 px-8 py-6","data-testid":`home-claude-config-panel-${n}`,children:[n==="claude-md"&&e.jsx(rn,{}),n==="settings"&&e.jsx(Ft,{scope:"user"}),n==="mcp"&&e.jsx(_t,{onAdd:O,scope:"user"}),n==="skills"&&e.jsx(Bt,{onAdd:E,scope:"user"}),n==="plugins"&&e.jsx(Ln,{onAdd:E,onJump:S}),n==="agents"&&e.jsx(as,{})]}),M&&e.jsxs(xt,{open:l,onClose:P,title:os[M],keyVals:[],children:[M==="skills"&&e.jsx(Ut,{}),M==="mcp"&&e.jsx(Ht,{scope:m.scope,cwd:m.cwd}),M==="plugins"&&e.jsx(Gt,{})]})]})}const xs=r.memo(cs);export{xs as HomeClaudeConfig};
@@ -1 +1 @@
1
- import{ay as e}from"./index-CgCxpunJ.js";function n({toolbar:s,footer:l,children:r}){return e.jsxs("div",{className:"h-full flex flex-col",children:[s&&e.jsx("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-2 text-xs",children:s}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:r}),l&&e.jsx("div",{className:"shrink-0 border-t border-line bg-bg-elev",children:l})]})}export{n as P};
1
+ import{aB as e}from"./index-C-d0DCre.js";function n({toolbar:s,footer:l,children:r}){return e.jsxs("div",{className:"h-full flex flex-col",children:[s&&e.jsx("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-1.5 flex items-center gap-2 text-xs",children:s}),e.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:r}),l&&e.jsx("div",{className:"shrink-0 border-t border-line bg-bg-elev",children:l})]})}export{n as P};
@@ -0,0 +1,26 @@
1
+ import{aR as o,ba as A,aB as e,ao as _t,aV as Bt,a9 as he,an as Ut,bl as at,bb as rt,m as Ne,bq as Kt,L as Wt,r as Ht,p as Vt,bg as Gt,C as Ke,ac as We,aC as Yt}from"./index-C-d0DCre.js";import{q as ot,d as qt,D as zt,H as fe,J as Xt,E as Jt,w as Qt,v as Zt,G as es,m as ts,a as ss,h as ns,j as as,k as rs,M as os,C as ls,I as is,S as ds,n as cs,o as He}from"./Skills-BpGRKOcY.js";import{s as ms}from"./ViewTabs-C0PRZx4_.js";import{V as us}from"./VoiceButton-D2rMurNg.js";import"./monaco-editor-BsIlgG7c.js";import"./Panel-Csyd9HbD.js";import"./TiptapBody-DSU3769X.js";const Ve=["bg-accent","bg-sage-dark","bg-honey","bg-fg-dim","bg-fg-faint","bg-hive-teal","bg-butter","bg-delta-bad"],lt=864e5,xs="MEMORY.md",Ge=2e3,Me=s=>s.replace(/\.md$/,"");function it(s,t,n,d){var y,x,m;const i=new Map(((t==null?void 0:t.entries)??[]).map(c=>[c.name,c])),a=new Set(((y=t==null?void 0:t.index)==null?void 0:y.orphans)??[]),u=new Map;for(const c of(n==null?void 0:n.clusters)??[])for(const h of c.memberSlugs)u.has(h)||u.set(h,c.id);const g=s.filter(c=>c.name!==xs),p=new Map;for(const c of g){const h=Me(c.name),k=((x=i.get(c.name))==null?void 0:x.outLinks)??((m=i.get(h))==null?void 0:m.outLinks)??[];for(const v of k){const S=Me(v),b=p.get(S)??[];b.includes(h)||b.push(h),p.set(S,b)}}return g.map(c=>{const h=Me(c.name),k=i.get(c.name)??i.get(h),v=(k==null?void 0:k.deadRefs)??[],S=(k==null?void 0:k.danglingLinks)??[],b=(k==null?void 0:k.stale)??!1;return{name:c.name,slug:h,path:c.path,description:(k==null?void 0:k.description)??"",bytes:c.bytes,mtimeMs:c.mtimeMs,ageDays:Math.floor((d-c.mtimeMs)/lt),stale:b,staleReasons:(k==null?void 0:k.reasons)??[],ageOnlyStale:b&&v.length===0,deadRefs:v,movedRefs:(k==null?void 0:k.movedRefs)??[],broken:v.length>0||S.length>0,danglingLinks:S,outLinks:(k==null?void 0:k.outLinks)??[],inLinks:p.get(h)??[],notIndexed:a.has(c.name)||a.has(h),clusterId:u.get(h)??null,type:(k==null?void 0:k.type)??null,originSessionId:(k==null?void 0:k.originSessionId)??null}})}function ps(s,t){const n=new Set(t.filter(d=>d.stale).map(d=>d.slug));return((s==null?void 0:s.clusters)??[]).map((d,i)=>({id:d.id,name:d.name,summary:d.summary,memberSlugs:d.memberSlugs,linkCount:d.links.length,retireCount:d.links.filter(a=>/retire/i.test(a.label??"")).length,staleCount:d.memberSlugs.filter(a=>n.has(a)).length,dotClass:Ve[i%Ve.length]}))}function fs(s,t,n){const d=t.trim().toLowerCase(),i=d?s.filter(a=>a.slug.toLowerCase().includes(d)||a.description.toLowerCase().includes(d)):s;return n===void 0?i:i.slice(0,n)}function pe(s,t,n){let d;return t==="ask"||t==="clusters"||t==="archived"?[]:(t==="all"?d=s:t==="stale"?d=s.filter(i=>i.stale):t==="broken"?d=s.filter(i=>i.broken):t==="recent"?d=s.filter(i=>Date.now()-i.mtimeMs<=7*lt):t==="unindexed"?d=s.filter(i=>i.notIndexed):t==="cluster:unclustered"?d=s.filter(i=>i.clusterId===null):t.startsWith("cluster:")?d=s.filter(i=>i.clusterId===t.slice(8)):d=s,fs(d,n))}function hs(s,t){const n=[...s];return t==="recent"?n.sort((d,i)=>i.mtimeMs-d.mtimeMs):t==="name"?n.sort((d,i)=>d.slug<i.slug?-1:d.slug>i.slug?1:0):n.sort((d,i)=>i.bytes-d.bytes),n}function gs(s){return{all:s.length,stale:pe(s,"stale","").length,broken:pe(s,"broken","").length,recent:pe(s,"recent","").length,unindexed:pe(s,"unindexed","").length}}function dt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"untitled_memory"}function bs(s,t){const n=s===""?[]:s.split(`
2
+ `),d=t===""?[]:t.split(`
3
+ `);if(n.length>Ge||d.length>Ge)return[...n.map(x=>({sign:"−",text:x})),...d.map(x=>({sign:"+",text:x}))];const i=n.length,a=d.length,u=Array.from({length:i+1},()=>new Array(a+1).fill(0));for(let x=i-1;x>=0;x--)for(let m=a-1;m>=0;m--)u[x][m]=n[x]===d[m]?u[x+1][m+1]+1:Math.max(u[x+1][m],u[x][m+1]);const g=[];let p=0,y=0;for(;p<i&&y<a;)n[p]===d[y]?(p++,y++):u[p+1][y]>=u[p][y+1]?g.push({sign:"−",text:n[p++]}):g.push({sign:"+",text:d[y++]});for(;p<i;)g.push({sign:"−",text:n[p++]});for(;y<a;)g.push({sign:"+",text:d[y++]});return g}const K=s=>s instanceof Error?s.message:String(s);function Ye(s){const t=/^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/.exec(s);return t?{front:t[0],body:s.slice(t[0].length)}:{front:"",body:s}}function ys(s){return s.split(`
4
+ `).map(t=>t.trim()).find(t=>t.length>0)??""}function ks(s,t){const n=s.kind==="agent"?s.agent:null,d=n?`${n.name}|${n.memoryScope??""}`:"",i=n!==null&&n.memoryScope===null,a=o.useMemo(()=>i?null:n&&n.memoryScope?{agent:{name:n.name,scope:n.memoryScope},...t?{cwd:t}:{}}:{workspace:ot(t),...t?{cwd:t}:{}},[d,i,t]),u=n===null,[g,p]=o.useState(!0),[y,x]=o.useState([]),[m,c]=o.useState(null),[h,k]=o.useState(null),[v,S]=o.useState(!1),[b,$]=o.useState(""),[W,z]=o.useState(!0),[ae,I]=o.useState([]),[D,R]=o.useState([]),[E,re]=o.useState({}),[X,V]=o.useState(()=>Date.now()),oe=o.useRef(a);oe.current=a;const O=o.useCallback(async()=>{if(!a){x([]),c(null),k(null),I([]),$(""),p(!1);return}try{const l=await window.api.memory.list(a);if(oe.current!==a)return;x(l.entries??[]),$(l.dir??""),z(l.autoMemoryEnabled!==!1),l.error&&A.error(`Memory list failed: ${l.error}`);const[j,w]=await Promise.all([window.api.memory.stale(a).catch(C=>(A.error(`Memory staleness check failed: ${K(C)}`),null)),window.api.memory.listArchived(a).catch(()=>({names:[],error:null}))]);if(oe.current!==a)return;c(j),I(w.names??[]),V(Date.now())}catch(l){A.error(`Memory list failed: ${K(l)}`)}finally{p(!1)}},[a]);o.useEffect(()=>{p(!0),k(null),O(),a&&u&&a.workspace&&window.api.memory.aggregate(a.workspace,!1,t??void 0).then(l=>{oe.current===a&&k(l)}).catch(l=>A.error(`Memory clusters failed: ${K(l)}`))},[O]),o.useEffect(()=>{let l=!1;return(async()=>{try{const{agents:j}=await window.api.memory.agents(t??void 0);if(l)return;R(j);const w={};await Promise.all(j.filter(C=>C.memoryScope).map(async C=>{const F=await window.api.memory.list({agent:{name:C.name,scope:C.memoryScope},...t?{cwd:t}:{}});w[C.name]=(F.entries??[]).filter(L=>L.name!=="MEMORY.md").length})),l||re(w)}catch(j){l||A.error(`Memory agents failed: ${K(j)}`)}})(),()=>{l=!0}},[t]),o.useEffect(()=>{if(!b)return;const l=b;window.api.config.watch([l]);const j=window.api.config.onChanged(({path:w})=>{(w===l||w.startsWith(l+"/"))&&O()});return()=>{j(),window.api.config.unwatch([l])}},[b,O]);const _=o.useMemo(()=>it(y,m,h,X),[y,m,h,X]),me=o.useMemo(()=>ps(h,_),[h,_]),Ce=o.useMemo(()=>({generatedAt:(h==null?void 0:h.generatedAt)??null,running:v}),[h,v]),B=o.useCallback(async l=>{if(!a)return null;try{const j=await window.api.memory.read(l,a);return j.error?(A.error(`Memory read failed: ${j.error}`),null):j.content}catch(j){return A.error(`Memory read failed: ${K(j)}`),null}},[a]),M=o.useCallback(async(l,j)=>{try{const w=await j();return w.ok?(await O(),!0):(A.error(`${l} failed: ${w.error??"unknown error"}`),!1)}catch(w){return A.error(`${l} failed: ${K(w)}`),!1}},[O]),J=o.useCallback(async(l,j)=>{if(!a)return!1;const w=await B(l);if(w===null)return!1;const{front:C}=Ye(w);return M("Memory save",()=>window.api.memory.write(l,C+j,a))},[a,B,M]),G=o.useCallback(async(l,j)=>a?M("Memory save",()=>window.api.memory.write(l,j,a)):!1,[a,M]),H=o.useCallback(async(l,j)=>{if(!a)return null;const w=dt(l),C=ys(j);if(!await M("Memory create",()=>window.api.memory.create(w,C,a)))return null;const L=`---
5
+ name: ${w}
6
+ description: ${C}
7
+ ---
8
+
9
+ ${j}
10
+ `;return await M("Memory create",()=>window.api.memory.write(w,L,a))?w:null},[a,M]),le=o.useCallback(async l=>{var F,L;if(!a)return null;const j=await B(l);if(j===null||!await M("Memory delete",()=>window.api.memory.delete(l,a)))return null;const C=((L=(F=Ye(j).front.match(/^description:\s*(.*)$/m))==null?void 0:F[1])==null?void 0:L.trim())??"";return async()=>{await M("Memory undo",()=>window.api.memory.create(l,C,a))&&await M("Memory undo",()=>window.api.memory.write(l,j,a))}},[a,B,M]),Q=o.useCallback(l=>a?M("Memory archive",()=>window.api.memory.archive(l,a)):Promise.resolve(!1),[a,M]),ie=o.useCallback(l=>a?M("Memory restore",()=>window.api.memory.restore(l,a)):Promise.resolve(!1),[a,M]),ue=o.useCallback(l=>a?M("Memory verify",()=>window.api.memory.verify(l,a)):Promise.resolve(!1),[a,M]),de=o.useCallback(async(l,j)=>{if(!a)return!1;const w=await B(l);if(w===null)return!1;const C=w.split(`[[${j}]]`).join(j);return M("Memory link removal",()=>window.api.memory.write(l,C,a))},[a,B,M]),ge=o.useCallback(async()=>{if(!(!a||!u||!a.workspace)){S(!0);try{const l=await window.api.memory.aggregate(a.workspace,!0,t??void 0);l.error?A.error(`Memory clustering failed: ${l.error}`):k(l)}catch(l){A.error(`Memory clustering failed: ${K(l)}`)}finally{S(!1)}}},[a,u,t]),Z=o.useCallback(async(l,j)=>{const w=C=>({ok:!1,answer:"",citations:[],error:C});if(!a)return w("no memory store");try{const C=await window.api.memory.ask({question:l,target:a,contextName:j});return C.ok||A.error(`Memory ask failed: ${C.error??"unknown error"}`),C}catch(C){return A.error(`Memory ask failed: ${K(C)}`),w(K(C))}},[a]),Y=o.useCallback(async l=>{const j=w=>({ok:!1,action:"keep",summary:"",reason:"",content:"",fold:null,error:w});if(!a)return j("no memory store");try{const w=await window.api.memory.proposeFix({name:l,target:a});return w.ok||A.error(`Memory fix failed: ${w.error??"unknown error"}`),w}catch(w){return A.error(`Memory fix failed: ${K(w)}`),j(K(w))}},[a]),ee=o.useMemo(()=>({refresh:O,read:B,saveBody:J,saveFile:G,create:H,remove:le,archive:Q,restore:ie,verify:ue,removeLink:de,regenerateClusters:ge,ask:Z,proposeFix:Y}),[O,B,J,G,H,le,Q,ie,ue,de,ge,Z,Y]);return{loading:g,target:a,dir:b,autoMemoryEnabled:W,rows:_,clusters:me,clustersMeta:Ce,index:m==null?void 0:m.index,archived:ae,agents:D,agentCounts:E,actions:ee}}const vs={recent:"name",name:"size",size:"recent"},js={recent:"Recent",name:"Name",size:"Size"},Ee="text-[9.5px] font-semibold tracking-[.06em] px-[5px] py-px rounded-[3px]",ws="h-7 px-2.5 rounded-full border text-[12.5px] font-medium flex items-center gap-1.5 whitespace-nowrap",Ns=[{key:"all",label:"All",tone:"bg-butter/40 text-honey-dark"},{key:"stale",label:"Stale",tone:"bg-butter/40 text-honey-dark"},{key:"broken",label:"Broken",tone:"bg-accent-muted/30 text-accent-dark"},{key:"recent",label:"This week",tone:""},{key:"unindexed",label:"Unindexed",tone:""},{key:"archived",label:"Archived",tone:""},{key:"clusters",label:"Clusters",tone:""},{key:"ask",label:"Ask",tone:""}];function Cs(s,t){if(s==="ask")return"+";if(s==="clusters")return String(t.clusterCount);if(s==="archived")return String(t.archivedCount);const n=t.counts[s];return s==="unindexed"&&n===0?"✓":String(n)}function Ss(s){return`${_t(s.bytes)} · ${s.ageDays>0?`${s.ageDays}d ago`:"just now"}`}const $s=o.memo(function(t){return e.jsxs("div",{"data-testid":"mx-list",className:"flex flex-col min-h-0 bg-bg-elev border-r border-rule-structural",children:[e.jsxs("div",{className:"flex flex-col gap-3 px-4 pt-[18px] pb-3",children:[e.jsx(qt,{eyebrow:"MEMORY FOLDER",badge:e.jsx("span",{"data-testid":"mx-list-folder-count",children:`${t.folder.count} files`}),path:t.folder.path||"—",children:e.jsxs("label",{className:"flex items-center gap-2 h-8 px-2.5 rounded-[8px] bg-bg-elev text-[12.5px]",children:[e.jsx("span",{className:"text-fg-faint",children:"Scope"}),e.jsx("select",{"data-testid":"mx-list-scope","aria-label":"Memory scope",value:t.scopeKey,onChange:n=>t.onScopeKey(n.target.value),className:"flex-1 min-w-0 bg-transparent outline-none font-medium text-fg cursor-pointer",children:t.scopeOptions.map(n=>e.jsx("option",{value:n.key,children:n.label},n.key))})]})}),e.jsx("div",{"data-testid":"mx-list-chips",className:"flex flex-wrap gap-1.5",children:Ns.filter(n=>n.key!=="archived"||t.archivedCount>0).map(n=>{const d=t.view===n.key||n.key==="clusters"&&t.view.startsWith("cluster:");return e.jsxs("button",{type:"button","data-testid":`mx-chip-${n.key}`,"aria-pressed":d,onClick:()=>t.onView(n.key),className:`${ws} ${n.tone?`${n.tone} border-transparent`:"border-rule-structural text-fg"} ${d?"ring-1 ring-fg-faint":""}`,children:[e.jsx("span",{children:n.label}),e.jsx("span",{className:"font-mono text-[11px]",children:Cs(n.key,t)})]},n.key)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-serif text-[15px] min-w-0 overflow-hidden text-ellipsis whitespace-nowrap",children:t.title}),e.jsx("span",{className:"text-[12px] text-fg-dim",children:t.rows.length}),e.jsx("span",{className:"flex-1"}),e.jsx("button",{type:"button","data-testid":"mx-list-new",onClick:t.onNew,className:"text-[12px] font-medium h-[26px] px-[10px] border border-rule-structural rounded-[5px] bg-bg-hi text-fg flex-none hover:border-fg",children:"+ New"})]}),e.jsxs("div",{className:"flex gap-[6px] items-center",children:[e.jsx("input",{"data-testid":"mx-list-filter",value:t.query,onChange:n=>t.onQuery(n.target.value),placeholder:"Filter by name or content…",className:"flex-1 min-w-0 h-7 border border-rule-structural rounded-[5px] px-[9px] text-[12px] text-fg bg-bg-hi outline-none"}),e.jsx("button",{type:"button","data-testid":"mx-list-sort",onClick:()=>t.onSort(vs[t.sort]),className:"h-7 px-[9px] border border-rule-structural rounded-[5px] flex items-center text-[12px] text-fg whitespace-nowrap hover:border-fg-faint",children:`${js[t.sort]} ⇅`})]})]}),e.jsxs("div",{className:"overflow-auto flex-1 px-4 pb-4 flex flex-col gap-0.5",children:[t.rows.map(n=>{const d=t.selected===n.name;return e.jsxs("div",{role:"option","aria-selected":d,"data-testid":`mx-list-row-${n.name}`,onClick:()=>t.onSelect(n.name),className:`px-3 py-2.5 rounded-xl border cursor-pointer flex flex-col gap-0.5 ${d?"bg-bg-hi border-line shadow-sm":"border-transparent hover:bg-bg-hi/60"}`,children:[e.jsxs("div",{className:"flex items-center gap-[7px]",children:[e.jsx("span",{className:`w-[7px] h-[7px] rounded-[2px] flex-none ${t.clusterDot(n.clusterId)}`}),e.jsx("span",{className:`text-[13px] flex-1 min-w-0 overflow-hidden text-ellipsis whitespace-nowrap ${d?"font-semibold":"font-medium"}`,children:n.slug}),n.stale&&e.jsx("span",{className:`${Ee} bg-butter/40 text-honey-dark`,children:"STALE"}),n.broken&&!n.stale&&e.jsx("span",{className:`${Ee} bg-accent-muted/30 text-accent-dark`,children:"BROKEN"}),n.notIndexed&&e.jsx("span",{className:`${Ee} bg-rule-inner text-fg-dim`,children:"NOT INDEXED"})]}),e.jsx("div",{className:"font-mono text-[10.5px] text-fg-dim pl-[14px]",children:Ss(n)})]},n.name)}),t.empty&&t.rows.length===0&&e.jsxs("div",{"data-testid":"mx-list-empty",className:"px-[18px] py-10 flex flex-col gap-2 items-start",children:[e.jsx("span",{className:"font-serif text-[17px] text-fg",children:t.empty.title}),e.jsx("span",{className:"text-[12.5px] leading-normal text-fg-dim",children:t.empty.body}),e.jsx("button",{type:"button",onClick:t.empty.onAction,className:"mt-[6px] text-[12px] font-medium h-7 px-3 border border-rule-structural rounded-[5px] bg-bg-hi text-fg",children:t.empty.action})]})]})]})}),ct={update:{label:"UPDATE",apply:"Apply update",hint:"Writes the file · undoable"},delete:{label:"ARCHIVE",apply:"Archive",hint:"Moves to .archive · undoable"},keep:{label:"KEEP",apply:"Mark verified",hint:"Touches the file, clears age staleness"},fold:{label:"FOLD",apply:"Copy for an Epic",hint:"Memory stays until the doc change lands"}},qe="grid grid-cols-[20px_1fr] px-[18px] py-1.5 font-mono text-xs leading-normal border-t border-rule-inner",Ms=o.memo(function({fix:t,onApply:n,onEditFirst:d,onDiscard:i}){const a=ct[t.action];return e.jsxs("div",{"data-testid":"mx-suggestion",className:"mx-9 mt-6 max-w-[700px] border border-honey rounded-[12px] overflow-hidden bg-bg-hi shadow-sm",children:[e.jsxs("div",{className:"px-[18px] py-2.5 bg-butter/40 flex items-center gap-2 text-honey-dark",children:[e.jsx("span",{"aria-hidden":!0,className:"text-[13px]",children:"+"}),e.jsxs("span",{"data-testid":"mx-suggestion-head",className:"text-[11px] tracking-[.1em] font-semibold",children:["CLAUDE SUGGESTS · ",a.label]}),e.jsx("span",{className:"flex-1"}),e.jsx("span",{className:"text-[11.5px]",children:"one of keep · update · archive · fold"})]}),e.jsxs("div",{className:"px-[18px] py-3 flex flex-col gap-1",children:[e.jsx("span",{"data-testid":"mx-reader-summary",className:"text-[15px] font-semibold text-fg",children:t.summary}),t.reason&&e.jsx("span",{"data-testid":"mx-reader-reason",className:"text-[13px] leading-normal text-fg-dim",children:t.reason})]}),t.action==="fold"&&t.fold&&e.jsxs("div",{"data-testid":"mx-suggestion-fold",children:[e.jsxs("div",{className:"px-[18px] py-1.5 border-t border-rule-inner text-[11.5px] text-fg-dim font-mono break-all",children:[t.fold.target," · ",t.fold.anchor||"append at end"]}),t.fold.insert.split(`
11
+ `).map((u,g)=>e.jsxs("div",{className:`${qe} bg-sage/20 text-sage-dark`,children:[e.jsx("span",{children:"+"}),e.jsx("span",{className:"whitespace-pre-wrap break-words",children:u})]},g))]}),t.action==="update"&&e.jsx("div",{"data-testid":"mx-suggestion-diff",children:t.diff.map((u,g)=>e.jsxs("div",{className:`${qe} ${u.sign==="−"?"bg-accent-muted/30 text-accent-dark":u.sign==="+"?"bg-sage/20 text-sage-dark":"text-fg-dim"}`,children:[e.jsx("span",{children:u.sign}),e.jsx("span",{className:"whitespace-pre-wrap break-words",children:u.text})]},g))}),e.jsxs("div",{className:"flex gap-2 px-[18px] py-3 border-t border-rule-structural items-center",children:[e.jsx("button",{type:"button","data-testid":"mx-reader-apply",onClick:n,className:"text-[13.5px] font-semibold h-9 px-4 rounded-[9px] bg-accent text-bg-hi hover:bg-accent/90",children:a.apply}),t.action==="update"&&e.jsx("button",{type:"button","data-testid":"mx-reader-edit-first",onClick:d,className:"text-[13.5px] font-semibold h-9 px-3.5 rounded-[9px] border border-fg text-fg",children:"Edit first"}),e.jsx("button",{type:"button","data-testid":"mx-reader-discard",onClick:i,className:"text-[13.5px] font-medium h-9 px-3.5 rounded-[9px] border border-rule-structural text-fg",children:"Discard"}),e.jsx("span",{className:"flex-1"}),e.jsx("span",{className:"text-[12.5px] text-fg-dim",children:a.hint})]})]})}),Es="text-xs font-medium h-[26px] px-2.5 border border-rule-structural rounded-[5px] bg-bg text-fg hover:border-fg",ze="h-[30px] px-3 text-[13px] font-medium rounded-[7px]",ve="px-2.5 py-[7px] rounded-[5px] text-left text-[12.5px] hover:bg-bg-elev",As="max-w-[640px] text-sm leading-[1.65] text-fg flex flex-col gap-3 [&_p]:m-0 [&_h4]:mt-1.5 [&_h4]:mb-0 [&_h4]:text-[11px] [&_h4]:tracking-[.08em] [&_h4]:font-semibold [&_h4]:text-accent [&_code]:font-mono [&_code]:text-[12.5px] [&_code]:bg-bg-elev [&_code]:px-1 [&_code]:rounded-[3px] [&_ul]:m-0 [&_ul]:pl-5 [&_ul]:list-disc [&_ol]:m-0 [&_ol]:pl-5 [&_ol]:list-decimal";function Ds(s){return s<1024?`${s} B`:`${(s/1024).toFixed(1)} KB`}function Rs(s){return s<=0?"just now":`${s}d ago`}function Ls(s,t){const n=[t];return s.type&&n.push(s.type),n.push(Ds(s.bytes),`modified ${Rs(s.ageDays)}`),s.originSessionId&&n.push(`session ${s.originSessionId.slice(0,8)}`),n.join(" · ").toUpperCase()}function Ts(s){const t=/^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/.exec(s);return(t?s.slice(t[0].length):s).trim()}function Is(s){return s.replace(/^\*\*Why:\*\*[ \t]*/gim,`#### WHY
12
+
13
+ `).replace(/^\*\*How to apply:\*\*[ \t]*/gim,`#### HOW TO APPLY
14
+
15
+ `)}const Os=o.memo(function(t){const{row:n,fix:d}=t,[i,a]=o.useState(!1),u=o.useMemo(()=>t.content===null||t.editing?"":Bt(Is(Ts(t.content))),[t.content,t.editing]),g=p=>()=>{a(!1),p()};return e.jsxs("div",{"data-testid":"mx-reader",className:"flex flex-col flex-1 min-w-0 min-h-0",children:[e.jsxs("div",{"data-testid":"mx-reader-header",className:"shrink-0 px-9 pt-6 pb-5 border-b border-rule-structural flex items-end gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{"data-testid":"mx-reader-eyebrow",className:"flex items-center gap-2 text-[11px] font-semibold tracking-[0.1em] text-fg-faint",children:[e.jsx("span",{className:`w-[7px] h-[7px] rounded-sm shrink-0 ${t.clusterDot}`}),e.jsx("span",{className:"truncate",children:Ls(n,t.clusterName)})]}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-2.5 min-w-0",children:[e.jsx("span",{"data-testid":"mx-reader-title",className:"min-w-0 [overflow-wrap:anywhere] font-mono text-[27px] font-semibold tracking-[-0.015em] text-fg",children:n.slug}),t.editing?e.jsx("span",{"data-testid":"mx-reader-pill",className:"shrink-0 text-xs font-semibold px-2 py-0.5 rounded-full bg-butter/50 text-honey-dark",children:t.editingSuggestion?"Editing Claude's update":"Editing"}):!t.archived&&d.state==="proposed"?e.jsx("span",{"data-testid":"mx-reader-pill",className:"shrink-0 text-xs font-semibold px-2 py-0.5 rounded-full bg-butter/50 text-honey-dark",children:"Suggestion ready"}):null]})]}),!t.archived&&e.jsxs("div",{className:"shrink-0 flex items-center gap-2",children:[e.jsxs("div",{role:"group","aria-label":"View",className:"flex p-[3px] rounded-[10px] bg-bg-elev border border-rule-structural",children:[e.jsx("button",{type:"button","data-testid":"mx-reader-mode-read","aria-pressed":!t.editing,onClick:t.editing?t.onRead:void 0,className:`${ze} ${t.editing?"text-fg-dim hover:text-fg":"bg-bg-hi text-fg shadow-sm"}`,children:"Read"}),e.jsx("button",{type:"button","data-testid":"mx-reader-edit","aria-pressed":!!t.editing,disabled:t.content===null,onClick:t.editing?void 0:t.onEdit,className:`${ze} ${t.editing?"bg-bg-hi text-fg shadow-sm":"text-fg-dim hover:text-fg"} disabled:opacity-50`,children:"Edit"})]}),!t.editing&&!n.stale&&d.state==="idle"&&e.jsx("button",{type:"button","data-testid":"mx-reader-fix",title:"Uses Claude",onClick:t.onFix,className:"h-[38px] px-4 rounded-[10px] bg-accent text-bg-hi hover:bg-accent/90 text-[13.5px] font-semibold",children:"+ Review with Claude"}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button","data-testid":"mx-reader-more","aria-label":"More actions",onClick:()=>a(p=>!p),className:"h-[38px] w-[38px] rounded-[10px] border border-rule-structural bg-bg-hi text-fg hover:border-fg",children:"⋯"}),i&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`fixed inset-0 ${he.dialog}`,onClick:()=>a(!1)}),e.jsxs("div",{className:`absolute right-0 top-11 w-[200px] ${he.dialog} bg-bg-hi border border-rule-structural rounded-[7px] shadow-lg p-1 flex flex-col text-fg`,children:[e.jsx("button",{type:"button",className:ve,onClick:g(t.onCopyPath),children:"Copy path"}),e.jsx("button",{type:"button",className:ve,onClick:g(t.onReveal),children:"Reveal in folder"}),e.jsx("div",{className:"h-px bg-rule-inner mx-1.5 my-1"}),e.jsx("button",{type:"button",className:ve,onClick:g(t.onArchive),children:"Archive"}),e.jsx("button",{type:"button",className:`${ve} text-accent`,onClick:g(t.onAskDelete),children:"Delete…"})]})]})]})]})]}),t.editing?e.jsx("div",{"data-testid":"mx-reader-editor",className:"flex-1 min-h-0 flex flex-col px-9 py-6",children:t.editor}):e.jsxs(e.Fragment,{children:[t.archived&&e.jsxs("div",{className:"mx-9 mt-3 px-3 py-2.5 rounded-md bg-bg-elev flex items-center gap-2.5 text-[12.5px] text-fg-dim",children:[e.jsx("span",{className:"flex-1",children:"Archived — read-only. Claude no longer loads this memory."}),e.jsx("button",{type:"button","data-testid":"mx-reader-restore",onClick:t.onRestore,className:Es,children:"Restore"})]}),!t.archived&&n.stale&&d.state==="idle"&&e.jsxs("div",{"data-testid":"mx-reader-stale",className:"mx-9 mt-3 px-3 py-2.5 rounded-md bg-butter/40 text-honey-dark flex gap-2.5 items-center text-[12.5px]",children:[e.jsxs("div",{className:"flex-1 flex flex-col gap-0.5",children:[e.jsx("b",{className:"font-semibold",children:t.appliedStill?`Applied — still flagged: ${n.staleReasons[0]??"needs review"}`:`Stale — ${n.staleReasons[0]??"needs review"}`}),n.deadRefs.length>0&&e.jsx("span",{className:"font-mono text-[11px]",children:n.deadRefs.join(" · ")})]}),e.jsx("span",{className:"text-[11px]",children:"uses Claude"}),e.jsx("button",{type:"button","data-testid":"mx-reader-fix",onClick:t.onFix,className:"text-xs font-medium h-[26px] px-2.5 rounded-[5px] bg-fg text-bg",children:"Fix with assistant"}),n.ageOnlyStale&&e.jsx("button",{type:"button","data-testid":"mx-reader-verify",onClick:t.onVerify,className:"text-xs font-medium h-[26px] px-2.5 rounded-[5px] border border-honey text-honey-dark",children:"Mark verified"})]}),!t.archived&&d.state==="checking"&&e.jsxs("div",{className:"mx-9 mt-3 p-3 rounded-md border border-dashed border-honey bg-butter/20 text-[12.5px] text-honey-dark flex items-center gap-2.5",children:[e.jsx("span",{className:"font-mono text-accent",children:"●○○"}),"Assistant is checking ",n.deadRefs.length>0?`${n.deadRefs.length} references`:"this memory"," against the repo…"]}),!t.archived&&d.state==="proposed"&&e.jsx(Ms,{fix:d,onApply:t.onApplyFix,onEditFirst:t.onEditFirst,onDiscard:t.onDiscardFix}),n.broken&&!n.stale&&e.jsx("div",{className:"mx-9 mt-3 px-3 py-2.5 rounded-md bg-accent-muted/30 text-[12.5px] text-accent-dark",children:"Broken reference — a link or path in this memory points at nothing. See the red items in Links."}),n.notIndexed&&e.jsx("div",{className:"mx-9 mt-3 px-3 py-2.5 rounded-md bg-butter/40 text-[12.5px] text-honey-dark",children:"Claude won't load this — it has no line in MEMORY.md."}),e.jsx("div",{className:"flex-1 overflow-auto px-9 pt-6 pb-[22px]",children:t.content===null?e.jsx("div",{className:"text-xs text-fg-faint",children:"Loading…"}):e.jsxs("div",{className:As,children:[n.description&&e.jsx("p",{className:"font-serif text-[17px] leading-normal text-fg",children:n.description}),e.jsx("div",{className:"contents",dangerouslySetInnerHTML:{__html:u}})]})})]})]})});function Fs({mode:s,name:t,title:n,onTitle:d,body:i,onBody:a,onSave:u,onCancel:g,saving:p,dirty:y,path:x,onRevert:m,changedFrom:c}){if(s==="none")return e.jsxs("div",{"data-testid":"mx-editor-none",className:"flex-1 flex flex-col items-center justify-center text-center gap-1.5 p-10",children:[e.jsx("div",{className:"font-serif text-[18px] text-fg",children:"No memory selected"}),e.jsx("div",{className:"text-[13px] text-fg-dim",children:"Pick one from the list, or press /."})]});if(s==="edit")return e.jsx("div",{"data-testid":"mx-editor",className:"flex-1 min-h-0 flex flex-col",children:e.jsx(zt,{path:x??`${t??"memory"}.md`,value:i,onChange:a,onSave:()=>{!p&&y&&u()},onRevert:m,dirty:y,changedFrom:c,defaultMode:"document"},x??t??"")});const h=p,k=v=>{(v.metaKey||v.ctrlKey)&&v.key.toLowerCase()==="s"?(v.preventDefault(),h||u()):v.key==="Escape"&&(v.preventDefault(),g())};return e.jsxs("div",{"data-testid":"mx-editor",className:"flex-1 min-h-0 flex flex-col",onKeyDown:k,children:[e.jsxs("div",{className:"flex items-center gap-2 px-[22px] pt-3.5 pb-3 border-b border-rule-structural",children:[e.jsx("h2",{className:"flex-1 min-w-0 truncate font-mono text-[15px] font-medium text-fg",children:"New memory"}),e.jsx("button",{type:"button","data-testid":"mx-editor-cancel",onClick:g,className:"h-7 px-3 rounded-[5px] border border-rule-structural bg-bg text-xs font-medium text-fg",children:"Cancel"}),e.jsx("button",{type:"button","data-testid":"mx-editor-save",disabled:h,onClick:u,className:"h-7 px-3.5 rounded-[5px] bg-accent text-white text-xs font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:"Save"})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex flex-col gap-2.5 px-[22px] py-4",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("label",{htmlFor:"mx-editor-name",className:"text-[11px] tracking-[.06em] font-semibold text-fg-faint",children:"NAME"}),e.jsx("input",{id:"mx-editor-name","data-testid":"mx-editor-name",value:n,onChange:v=>d(v.target.value),placeholder:"e.g. deploy freeze fridays",className:"h-8 px-2.5 rounded-[5px] border border-rule bg-bg-hi font-mono text-[13px] font-normal text-fg outline-none"}),n.trim()!==""&&e.jsxs("div",{className:"font-mono text-[11px] text-fg-faint",children:["→ ",dt(n),".md"]})]}),e.jsx("textarea",{"data-testid":"mx-editor-body",value:i,onChange:v=>a(v.target.value),spellCheck:!1,className:"flex-1 min-h-0 w-full resize-none px-3.5 py-3 rounded-md border border-rule bg-bg-hi font-mono text-[13px] leading-[1.7] text-fg outline-none"}),e.jsx("div",{className:"flex items-center gap-2 text-[11.5px] text-fg-faint",children:e.jsx("span",{children:"Markdown. Frontmatter is added on save. Saving marks the memory verified."})})]})]})}const Ae=o.memo(Fs);function Ps(s){const t=Math.max(0,Math.round(s/1e3));return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function _s({elapsedMs:s,evidence:t}){const[n,d]=o.useState(!1);return e.jsxs("div",{"data-testid":"mx-links-checked",className:"flex flex-col gap-2 px-4 py-3.5 rounded-[14px] border border-rule-inner bg-bg-hi",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{"aria-hidden":!0,className:"w-[7px] h-[7px] rounded-full bg-sage-dark shrink-0"}),e.jsxs("span",{className:`${ne} flex-1`,children:["CHECKED IN ",Ps(s)]}),t.length>0&&e.jsxs("button",{type:"button","data-testid":"mx-links-evidence","aria-expanded":n,onClick:()=>d(i=>!i),className:"text-[12px] font-medium text-accent hover:text-fg",children:["Evidence ",n?"▴":"▾"]})]}),n&&e.jsx("ul",{"data-testid":"mx-links-evidence-list",className:"m-0 pl-4 list-disc text-[12px] leading-normal text-fg-dim",children:t.map(i=>e.jsx("li",{className:"break-words",children:i},i))})]})}const ne="text-[11px] tracking-[.1em] font-semibold text-fg-faint",Bs="flex flex-col gap-0.5 px-3.5 py-2.5 rounded-[10px] cursor-pointer bg-bg-hi border text-left hover:border-fg-faint";function je({testid:s,slug:t,sub:n,dangling:d,onClick:i}){return e.jsxs("button",{type:"button","data-testid":s,onClick:i,className:`${Bs} ${d?"border-accent-muted":"border-rule-inner"}`,children:[e.jsx("span",{className:`font-mono text-[12.5px] font-medium break-all ${d?"text-accent":"text-fg"}`,children:t}),e.jsx("span",{className:`text-[10.5px] ${d?"text-accent":"text-fg-dim"}`,children:n})]})}const Us=o.memo(function({row:t,onOpen:n,onRemoveLink:d,onAskAbout:i,onUpdatePath:a,onReviewPath:u,onCheck:g,checkBusy:p,editing:y,editingSuggestion:x,check:m}){return e.jsx("aside",{"data-testid":"mx-links",className:"px-5 py-6 flex flex-col gap-[18px] overflow-auto",children:t&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col gap-[6px]",children:[e.jsxs("span",{className:ne,children:["LINKS TO · ",t.outLinks.length]}),t.outLinks.map(c=>{const h=t.danglingLinks.includes(c);return e.jsx(je,{testid:`mx-link-out-${c}`,slug:c,dangling:h,sub:h?"missing · click to remove link":"wikilink",onClick:()=>h?d(c):n(c)},c)}),t.outLinks.length===0&&e.jsx("span",{className:"text-[12px] text-fg-dim",children:"No outgoing links."})]}),t.movedRefs.length+t.deadRefs.length>0&&e.jsxs("div",{className:"flex flex-col gap-[6px]",children:[e.jsxs("span",{className:ne,children:["PATHS · ",t.movedRefs.length+t.deadRefs.length]}),t.movedRefs.map((c,h)=>e.jsx(je,{testid:`mx-path-moved-${h}`,slug:c.from,dangling:!1,sub:`moved to ${c.to} · click to update`,onClick:()=>a({from:c.from,to:c.to})},`moved-${c.from}`)),t.deadRefs.map((c,h)=>e.jsx(je,{testid:`mx-path-dead-${h}`,slug:c,dangling:!0,sub:"not found anywhere · review with assistant",onClick:u},`dead-${c}`))]}),e.jsxs("div",{className:"flex flex-col gap-[6px]",children:[e.jsxs("span",{className:ne,children:["LINKED FROM · ",t.inLinks.length]}),t.inLinks.map(c=>e.jsx(je,{testid:`mx-link-in-${c}`,slug:c,dangling:!1,sub:"wikilink",onClick:()=>n(c)},c)),t.inLinks.length===0&&e.jsx("span",{className:"text-[12px] text-fg-dim",children:"Nothing links here yet."})]}),y&&x?e.jsxs("div",{"data-testid":"mx-links-started",className:"flex flex-col gap-1.5 px-4 py-3.5 rounded-[14px] border border-honey/60 bg-butter/20 text-[12.5px] leading-normal text-fg",children:[e.jsx("span",{className:`${ne} uppercase !text-honey-dark`,children:"Started from Claude's update"}),e.jsx("span",{children:"The suggested change is already in the editor, and the lines it touched are marked. Change anything before you save."}),e.jsx("span",{className:"text-fg-dim",children:"Revert goes back to the file on disk."})]}):y?e.jsxs("div",{"data-testid":"mx-links-editing",className:"flex flex-col gap-1.5 px-4 py-3.5 rounded-[14px] border border-dashed border-rule-structural text-[12px] leading-normal text-fg-dim",children:[e.jsx("span",{className:ne,children:"EDITING THE FILE ON DISK"}),e.jsxs("span",{children:["Keep the frontmatter lines (name, description, type). Save writes"," ",e.jsx("span",{className:"font-mono break-all",children:t.name}),"."]})]}):m?e.jsx(_s,{elapsedMs:m.elapsedMs,evidence:m.evidence}):e.jsxs("div",{"data-testid":"mx-links-askclaude",className:"flex flex-col gap-2 px-4 py-3.5 rounded-[14px] border border-honey/50 bg-butter/30",children:[e.jsx("span",{className:`${ne} !text-honey-dark`,children:"ASK CLAUDE"}),e.jsx("span",{className:"font-serif text-[17px] leading-snug text-fg",children:"Is this memory still accurate?"}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("button",{type:"button","data-testid":"mx-links-check",disabled:p,onClick:g,className:"h-8 px-3 rounded-[8px] bg-accent text-bg-hi hover:bg-accent/90 text-[13px] font-semibold disabled:opacity-50 disabled:cursor-not-allowed",children:"Check against the repo"}),e.jsx("button",{type:"button","data-testid":"mx-links-ask",onClick:i,className:"text-[12px] text-honey-dark hover:text-fg",children:"Ask a question…"})]})]})]})})}),Ks=["What changed this week?","Find contradictions","Summarize stale memories","remember …"],Ws=["Is this still accurate?","What links here?","Summarize it"],Hs=/^remember\b[\s:,-]*/i,Xe="text-xs font-medium h-[26px] px-2.5 rounded-[5px] bg-fg text-bg",Vs=s=>s.charAt(0).toUpperCase()+s.slice(1),Gs=o.memo(function({rows:t,context:n,onClearContext:d,onAsk:i,onOpen:a,onReverify:u,onDraft:g}){const[p,y]=o.useState(""),[x,m]=o.useState(!1),[c,h]=o.useState(null),k=async()=>{const b=p.trim();if(!b||x)return;if(/^remember\b/i.test(b)){h({kind:"draft",question:b,text:Vs(b.replace(Hs,""))}),y("");return}m(!0);let $=null;try{$=await i(b,n)}catch{$=null}m(!1),!(!$||!$.ok)&&(h({kind:"answer",question:b,answer:$.answer,citations:$.citations}),y(""))},v=(c==null?void 0:c.kind)==="answer"?c.citations.map(b=>({slug:b,row:t.find($=>$.slug===b||$.name===b)})):[],S=v.filter(b=>{var $;return($=b.row)==null?void 0:$.stale}).length;return e.jsxs("div",{"data-testid":"mx-ask",className:"flex flex-col h-full min-h-0",children:[e.jsxs("div",{className:"px-7 py-4 border-b border-rule-structural flex items-center gap-2.5",children:[e.jsx("span",{className:"font-serif text-[20px]",children:"Ask"}),e.jsx("span",{className:"text-xs text-fg-dim flex-1",children:"Search and edit this scope's memories in plain language. Answers cite the files they used."}),n&&e.jsxs("span",{"data-testid":"mx-ask-context",className:"flex items-center gap-1.5 pl-2 pr-1 py-[3px] border border-rule rounded-[5px] bg-bg-elev text-xs",children:["About ",e.jsx("span",{className:"font-mono text-[11.5px]",children:n}),e.jsx("button",{"aria-label":"Clear context",onClick:d,className:"px-1.5 text-fg-dim hover:text-accent",children:"×"})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto px-7 py-6 flex flex-col gap-5 max-w-[820px]",children:[!c&&!x&&e.jsxs("div",{className:"my-auto flex flex-col gap-1.5 text-fg-dim text-[13px]",children:[e.jsx("span",{className:"font-serif text-[20px] text-fg",children:"What do you want to know?"}),e.jsx("span",{children:'Ask about a symptom, a file or a past decision, or start with "remember" to save something new.'})]}),c&&e.jsx("div",{className:"self-end max-w-[520px] px-3.5 py-2.5 rounded-[10px] bg-fg text-bg text-[14px]",children:c.question}),(c==null?void 0:c.kind)==="answer"&&e.jsxs("div",{className:"flex flex-col gap-2.5 text-[14px] leading-[1.65] text-fg max-w-[680px]",children:[e.jsx("p",{className:"m-0",children:c.answer}),e.jsx("div",{className:"flex flex-wrap gap-1.5 items-center",children:v.map((b,$)=>{var W;return e.jsxs("button",{"data-testid":`mx-ask-cite-${b.slug}`,onClick:()=>{var z;return a(((z=b.row)==null?void 0:z.name)??b.slug)},className:"flex items-center gap-1.5 px-[9px] py-1 border border-rule-structural rounded-[5px] bg-bg text-xs hover:border-fg",children:[e.jsxs("span",{className:"font-mono text-[10.5px] text-accent",children:["[",$+1,"]"]}),e.jsx("span",{children:b.slug}),b.row&&e.jsxs("span",{className:"text-fg-dim",children:[b.row.ageDays,"d"]}),((W=b.row)==null?void 0:W.stale)&&e.jsx("span",{className:"text-[9.5px] font-semibold px-1 rounded-[3px] bg-butter/40 text-honey-dark",children:"STALE"})]},b.slug)})}),S>0&&e.jsxs("div",{className:"px-3 py-2.5 rounded-md bg-butter/40 text-[12.5px] text-fg flex items-center gap-2.5",children:[e.jsxs("span",{className:"flex-1",children:[S," of these ",S===1?"is":"are"," flagged stale. Re-verify against the current code?"]}),e.jsx("button",{onClick:u,className:Xe,children:"Re-verify"})]})]}),(c==null?void 0:c.kind)==="draft"&&e.jsxs("div",{className:"max-w-[560px] border border-rule rounded-lg bg-bg-hi p-3.5 flex flex-col gap-2",children:[e.jsx("span",{"data-testid":"mx-ask-draft",className:"text-[10px] tracking-[.08em] text-sage-dark font-semibold",children:"DRAFT MEMORY · NOT SAVED YET"}),e.jsx("span",{className:"font-serif text-base",children:c.text}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>g(c.text),className:`${Xe} h-7 px-3`,children:"Review draft"}),e.jsx("span",{className:"text-xs text-fg-dim self-center",children:"Opens it in the editor before anything is written"})]})]}),x&&e.jsx("span",{className:"text-xs text-fg-dim",children:"Thinking…"})]}),e.jsxs("div",{className:"px-7 pt-3 pb-4 border-t border-rule-structural flex flex-col gap-2.5",children:[e.jsx("div",{className:"flex gap-1.5 flex-wrap items-center",children:(n?Ws:Ks).map(b=>e.jsx("button",{onClick:()=>y(b),className:"px-2.5 py-1 border border-rule-structural rounded-[14px] text-xs text-fg-dim hover:bg-bg-elev",children:b},b))}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{"data-testid":"mx-ask-input",value:p,onChange:b=>y(b.target.value),onKeyDown:b=>{b.key==="Enter"&&k()},placeholder:"Ask, or say “remember …” to add a memory",className:"flex-1 h-11 border border-rule rounded-md bg-bg-hi px-3 text-[13px] text-fg focus:outline-none focus:border-fg-faint"}),e.jsx(us,{}),e.jsx("button",{"data-testid":"mx-ask-send",onClick:()=>void k(),disabled:x,className:"h-11 px-4 rounded-md bg-accent text-white text-[13px] font-medium disabled:opacity-40",children:"Send"}),e.jsx("span",{className:"text-[10px] text-fg-faint",children:"uses Claude"})]})]})]})}),Je="text-xs font-medium h-[26px] px-2.5 border border-rule-structural rounded-[5px] bg-bg text-fg hover:border-fg disabled:opacity-50 disabled:cursor-default",Qe="text-[11px] text-fg-faint",Ys=o.memo(function({clusters:t,rows:n,generatedAt:d,running:i,unclusteredCount:a,available:u,onRegenerate:g,onOpenCluster:p,onOpen:y}){const x=o.useMemo(()=>new Map(n.map(m=>[m.slug,m])),[n]);return u?d===null&&t.length===0?e.jsxs("div",{"data-testid":"mx-clusters",className:"flex-1 flex flex-col items-center justify-center gap-2 p-6 text-center",children:[e.jsx("div",{className:"font-serif text-[20px] text-fg",children:"No clusters yet"}),e.jsx("button",{type:"button","data-testid":"mx-clusters-regenerate",className:Je,disabled:i,onClick:g,children:i?"Generating…":"Generate"}),e.jsx("span",{className:Qe,children:"uses Claude · up to 3 min"})]}):e.jsxs("div",{"data-testid":"mx-clusters",className:"flex-1 min-w-0 min-h-0 flex flex-col",children:[e.jsxs("div",{className:"px-6 py-4 border-b border-rule-structural flex items-center gap-2.5",children:[e.jsx("span",{className:"font-serif text-[20px] text-fg",children:"Clusters"}),e.jsxs("span",{className:"text-xs text-fg-dim",children:["Generated ",Ut(d,Date.now())," from shared references and links"]}),e.jsx("span",{className:"flex-1"}),a>0&&e.jsxs("span",{className:"text-xs text-honey-dark px-2 py-0.5 rounded bg-butter/40",children:[a," unclustered"]}),e.jsx("button",{type:"button","data-testid":"mx-clusters-regenerate",className:Je,disabled:i,onClick:g,children:i?"Generating…":"Regenerate"}),e.jsx("span",{className:Qe,children:"uses Claude"})]}),e.jsx("div",{className:"flex-1 overflow-auto px-6 py-[18px] grid grid-cols-2 gap-4 content-start",children:t.map(m=>e.jsxs("div",{"data-testid":`mx-cluster-${m.id}`,className:"bg-bg-hi border border-rule-structural rounded-lg p-4 flex flex-col gap-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`w-[9px] h-[9px] rounded-[2px] shrink-0 ${m.dotClass}`}),e.jsx("span",{className:"font-serif text-[17px] text-fg min-w-0 flex-1",children:m.name}),e.jsxs("button",{type:"button","data-testid":`mx-cluster-open-${m.id}`,className:"text-xs text-accent hover:text-fg",onClick:()=>p(m.id),children:["Open ",m.memberSlugs.length," →"]})]}),e.jsx("span",{className:"text-[12.5px] leading-normal text-fg-dim",children:m.summary}),e.jsx("div",{className:"flex flex-wrap gap-[5px] items-center",children:m.memberSlugs.map(c=>{const h=x.get(c);return e.jsx("button",{type:"button",className:`font-mono text-[11px] px-[7px] py-[3px] rounded border border-rule-inner text-fg hover:border-fg ${h!=null&&h.stale?"bg-butter/40":"bg-bg"}`,onClick:()=>y((h==null?void 0:h.name)??`${c}.md`),children:c},c)})}),e.jsxs("div",{className:"flex gap-3.5 text-[11.5px] text-fg-dim border-t border-rule-inner pt-[9px]",children:[e.jsxs("span",{children:[m.linkCount," links"]}),e.jsxs("span",{children:[m.retireCount," retires"]}),e.jsxs("span",{className:"text-honey-dark",children:[m.staleCount," stale"]})]})]},m.id))})]}):e.jsx("div",{"data-testid":"mx-clusters",className:"flex-1 p-6 text-[13px] text-fg-dim",children:"Clusters are available for workspace memory."})}),De="text-[12.5px] font-medium h-8 px-3 rounded-[5px] cursor-pointer text-fg";function qs({open:s,name:t,inbound:n,onArchive:d,onCancel:i,onConfirm:a}){return o.useEffect(()=>{if(!s)return;const u=g=>{g.key==="Escape"&&i()};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[s,i]),s?e.jsxs("div",{"data-testid":"mx-delete-dialog",children:[e.jsx("div",{className:`absolute inset-0 ${he.dialog} bg-fg/30`,onClick:i}),e.jsxs("div",{className:`absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-[440px] ${he.dialog} bg-bg-hi border border-rule rounded-[10px] shadow-lg p-5 flex flex-col gap-3`,children:[e.jsx("span",{className:"font-serif text-[20px] text-fg",children:"Delete this memory?"}),e.jsxs("span",{className:"font-mono text-[12.5px] text-fg",children:[t,".md"]}),n>0&&e.jsxs("div",{className:"px-3 py-[10px] rounded-[6px] bg-accent-muted/30 text-[12.5px] leading-normal text-accent-dark",children:[n," memories link here. Those links will show as broken until removed."]}),e.jsx("span",{className:"text-[12.5px] text-fg-dim",children:"The file is removed from disk. You can undo for a few seconds afterwards. To keep it out of sessions without deleting it, use Archive."}),e.jsxs("div",{className:"flex gap-2 justify-end mt-1",children:[e.jsx("button",{type:"button",onClick:d,className:`${De} border border-rule mr-auto`,children:"Archive instead"}),e.jsx("button",{type:"button",onClick:i,className:`${De} border border-rule bg-bg`,children:"Cancel"}),e.jsx("button",{type:"button","data-testid":"mx-delete-confirm",onClick:a,className:`${De} border-0 px-[14px] bg-accent text-white`,children:"Delete"})]})]})]}):null}const zs=6e3;function Xs({message:s,onUndo:t,onClose:n}){return o.useEffect(()=>{if(s===null)return;const d=setTimeout(n,zs);return()=>clearTimeout(d)},[s]),s===null?null:e.jsxs("div",{"data-testid":"mx-undo-bar",className:`absolute bottom-[22px] left-1/2 -translate-x-1/2 ${he.dialog} flex items-center gap-[14px] py-[10px] pl-4 pr-3 rounded-lg bg-fg text-bg text-[13px] shadow-lg whitespace-nowrap`,children:[e.jsx("span",{children:s}),t&&e.jsx("button",{type:"button","data-testid":"mx-undo",onClick:t,className:"font-semibold text-accent-muted hover:text-white",children:"Undo"}),e.jsx("button",{type:"button",onClick:n,"aria-label":"Dismiss",className:"text-fg-faint hover:text-white px-1",children:"×"})]})}const mt="sm.memoryTab.scope",q="agent:",Re=`One-line summary of the fact or rule.
16
+
17
+ **Why:**
18
+
19
+ **How to apply:**`,P={state:"idle",diff:[],summary:"",action:"update",reason:"",fold:null,elapsedMs:0},Le=(s,t)=>`${s} ${t}${s===1?"":"s"}`;function Js(s){const t=[`Verdict: ${ct[s.action].label.toLowerCase()}`];if(s.action==="update"){const n=s.diff.filter(i=>i.sign==="−").length,d=s.diff.filter(i=>i.sign==="+").length;t.push(`${Le(n,"line")} removed · ${Le(d,"line")} added`)}return s.action==="fold"&&s.fold&&(t.push(`${Le(s.fold.insert.split(`
20
+ `).length,"line")} into ${s.fold.target}`),t.push(s.fold.anchor?`After: ${s.fold.anchor}`:"Appended at the end")),t}const Ze=s=>s.replace(/\.md$/,""),et=s=>s?s.split(/[\\/]/).filter(Boolean).pop()??s:"workspace";function tt(s){const t=/^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/.exec(s);return(t?s.slice(t[0].length):s).replace(/^\s*\n/,"")}const Qs=s=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Zs(s,t,n){return s.replace(new RegExp("`"+Qs(t)+"(:\\d+)?`","g"),(d,i)=>"`"+n+(i??"")+"`")}function en(){try{const s=localStorage.getItem(mt);return s&&s.startsWith(q)?s:"workspace"}catch{return"workspace"}}function tn({cwd:s}){const[t,n]=o.useState(en),[d,i]=o.useState([]),a=o.useMemo(()=>{if(!t.startsWith(q))return"workspace";const x=t.slice(q.length);return d.some(m=>m.name===x)?t:"workspace"},[t,d]),u=o.useMemo(()=>{if(a==="workspace")return{kind:"workspace"};const x=d.find(m=>m.name===a.slice(q.length));return x?{kind:"agent",agent:x}:{kind:"workspace"}},[a]),g=o.useCallback(x=>{const m=x.kind==="agent"?`${q}${x.agent.name}`:"workspace";try{localStorage.setItem(mt,m)}catch{}n(m)},[]),p=o.useCallback(x=>{x.length>0&&i(x)},[]),y=fe(x=>x.tab);return o.useEffect(()=>{y==="memory"&&a!=="workspace"&&g({kind:"workspace"})},[y,a,g]),e.jsx(sn,{scope:u,cwd:s,onScope:g,onAgents:p},a)}function sn({scope:s,cwd:t,onScope:n,onAgents:d}){var Be;const i=ks(s,t),{actions:a,rows:u,clusters:g}=i,p=s.kind==="agent"?s.agent:null,y=p!==null&&p.memoryScope===null,x=p?p.name:et(t),[m,c]=o.useState("all"),[h,k]=o.useState(null),[v,S]=o.useState("read"),[b,$]=o.useState(""),[W,z]=o.useState("recent"),[ae,I]=o.useState(null),[D,R]=o.useState(P),[E,re]=o.useState(""),[X,V]=o.useState(!1),[oe,O]=o.useState(null),[_,me]=o.useState(null),[Ce,B]=o.useState(null),[M,J]=o.useState(""),[G,H]=o.useState(""),[le,Q]=o.useState(""),[ie,ue]=o.useState(!1),[de,ge]=o.useState(null);o.useEffect(()=>{d(i.agents)},[i.agents,d]);const Z=o.useMemo(()=>i.archived.map(r=>({name:r,slug:Ze(r),path:`${i.dir}/${r}`,description:"",bytes:0,mtimeMs:0,ageDays:0,stale:!1,staleReasons:[],ageOnlyStale:!1,deadRefs:[],movedRefs:[],broken:!1,danglingLinks:[],outLinks:[],inLinks:[],notIndexed:!1,clusterId:null,type:null,originSessionId:null})),[i.archived,i.dir]),Y=m!=="ask"&&m!=="clusters",ee=o.useMemo(()=>{if(m==="archived"){const r=b.trim().toLowerCase();return Z.filter(f=>!r||f.slug.toLowerCase().includes(r))}return hs(pe(u,m,b),W)},[m,u,Z,b,W]),l=o.useMemo(()=>u.find(r=>r.name===h)??Z.find(r=>r.name===h)??null,[u,Z,h]),j=l!==null&&!u.some(r=>r.name===l.name),w=o.useCallback(r=>{var f;return((f=g.find(N=>N.id===r))==null?void 0:f.dotClass)??"bg-rule"},[g]),C=r=>{var f;return((f=g.find(N=>N.id===r))==null?void 0:f.name)??"Unclustered"},F=o.useCallback(r=>{k(r),S("read"),V(!1),R(P),O(null),I(null)},[]),L=o.useCallback(r=>{c(r),$(""),I(null),R(P),V(!1),S(f=>f==="edit"||f==="new"?"read":f)},[]);o.useEffect(()=>{var r;i.loading||!Y||v==="new"||l&&ee.some(f=>f.name===l.name)||k(((r=ee[0])==null?void 0:r.name)??null)},[i.loading,Y,v,l,ee]);const te=l&&!j?l.name:null,pt=l==null?void 0:l.mtimeMs;o.useEffect(()=>{if(!te)return;let r=!0;return a.read(te).then(f=>{r&&ge({name:te,text:f})}),()=>{r=!1}},[te,pt,a.read]);const U=j?"":de&&de.name===te?de.text:null,T=(r,f)=>me({message:r,undo:f}),Se=(r="")=>{y||((m==="ask"||m==="clusters")&&c("all"),k(null),J(""),H(r),Q(""),R(P),I(null),S("new"))},Te=r=>{L("all"),F(r)},ft=r=>{const f=u.find(N=>N.slug===r);f?F(f.name):A.error(`${r} is not in this scope`)},ht=()=>{U!==null&&(H(U),Q(U),V(!1),S("edit"))},gt=()=>{U===null||D.state!=="proposed"||D.action!=="update"||(H(E),Q(U),V(!0),S("edit"))},be=v==="edit"&&G!==le,Ie=fe(r=>r.tab),ye=fe(r=>r.id),Oe=fe(r=>r.clear);o.useEffect(()=>{if(Ie!=="memory"||!ye||p||i.loading)return;const r=ye.startsWith("memory:")?ye.slice(7):null,f=r?u.find(N=>N.path===r):void 0;f&&(!be||window.confirm("Discard unsaved changes to this memory?"))&&(L("all"),F(f.name)),Oe()},[Ie,ye,p,i.loading,u,be,L,F,Oe]);const bt=async()=>{if(!l)return;const r=await a.read(l.name);r!==null&&(H(r),Q(r),V(!1))},Fe=()=>{be&&!window.confirm("Discard unsaved changes to this memory?")||(V(!1),S("read"))},Pe=async()=>{if(!ie){ue(!0);try{if(v==="new"){const r=await a.create(M,G);if(!r)return;const f=r.endsWith(".md")?r:`${r}.md`;L("all"),F(f),T(`Created ${Ze(f)}`)}else if(v==="edit"&&l){const r=l,f=le,N=X;if(!await a.saveFile(r.name,G))return;S("read"),V(!1),N?(R(P),O(r.slug),T(`Applied edited fix to ${r.slug}`,()=>{a.saveFile(r.name,f)})):T(`Saved ${r.slug}`)}}finally{ue(!1)}}},yt=()=>{S("read"),l||k(null)},$e=async()=>{if(!l||U===null)return;const r=l;R({...P,state:"checking"});const f=performance.now(),N=await a.proposeFix(r.name);if(!N.ok){R(P);return}re(N.content),R({state:"proposed",diff:N.action==="update"?bs(U,N.content):[],summary:N.summary,action:N.action,reason:N.reason,fold:N.fold,elapsedMs:performance.now()-f})},kt=async()=>{if(!l||U===null)return;const r=l;if(D.action==="delete"){if(!await a.archive(r.name))return;R(P),T(`Archived ${r.slug}`,()=>{a.restore(r.name)})}else if(D.action==="keep"){if(!await a.verify(r.name))return;R(P),T(`Marked ${r.slug} verified`)}else if(D.action==="fold"){if(!D.fold)return;const{target:f,anchor:N,insert:ce}=D.fold,ke=`Fold memory ${r.slug} into ${f}.
21
+ Insert after the line: ${N||"(append at end)"}
22
+ ---
23
+ ${ce}
24
+ ---
25
+ Tread lightly: add only these lines, do not restructure the doc. Once committed, archive the memory ${r.slug} from the Memory page.
26
+ Memory file: ${r.path}`,Ue=await window.api.clipboard.writeText(ke);if(!Ue.ok){A.error(`Copy failed: ${Ue.error??"unknown error"}`);return}R(P),T("Fold copied — paste it into a New Epic")}else{const f=U;if(!await a.saveBody(r.name,tt(E)))return;R(P),O(r.slug),T(`Applied fix to ${r.slug}`,()=>{a.saveFile(r.name,f)})}},vt=async()=>{if(!l)return;const r=l;await a.verify(r.name)&&T(`Marked ${r.slug} verified`)},_e=async()=>{if(!l)return;const r=l;I(null),await a.archive(r.name)&&T(`Archived ${r.slug}`,()=>{a.restore(r.name)})},jt=async()=>{if(!l)return;const r=l;await a.restore(r.name)&&T(`Restored ${r.slug}`)},wt=async()=>{if(!l)return;const r=l;I(null);const f=await a.remove(r.name);if(!f)return;const N=r.inLinks.length;T(`Deleted ${r.slug}${N>0?` · ${N} inbound links now broken`:""}`,()=>{f()})},Nt=async()=>{if(!l)return;const r=await window.api.clipboard.writeText(l.path);r.ok?T("Path copied"):A.error(`Copy failed: ${r.error??"unknown error"}`)},Ct=()=>{l&&window.api.shell.open({as:"revealPath",path:l.path})},St=async r=>{if(!l)return;const f=l;await a.removeLink(f.name,r)&&T(`Dead link removed from ${f.slug}`)},$t=async r=>{if(!l)return;const f=l;try{const N=await a.read(f.name);if(N===null)return;const ce=tt(N),ke=Zs(ce,r.from,r.to);if(ke===ce){A.error(`${r.from} is not referenced in backticks in ${f.slug}`),await a.refresh();return}if(!await a.saveBody(f.name,ke))return;T(`Updated ${r.from} → ${r.to} in ${f.slug}`,()=>{a.saveBody(f.name,ce)})}catch(N){A.error(`Path update failed: ${N instanceof Error?N.message:String(N)}`)}},Mt=()=>{l&&(B(l.slug),L("ask"))},Et=r=>{var f;return r?((f=u.find(N=>N.slug===r))==null?void 0:f.name)??`${r}.md`:void 0},At=o.useMemo(()=>D.state==="proposed"?{elapsedMs:D.elapsedMs,evidence:Js(D)}:null,[D]),Dt=o.useMemo(()=>gs(u),[u]),Rt=o.useMemo(()=>u.filter(r=>r.clusterId===null).length,[u]),Lt=o.useMemo(()=>new Set(u.map(r=>r.slug)),[u]),Tt=o.useMemo(()=>[{key:"workspace",label:`Workspace · ${et(t)}`},...i.agents.map(r=>({key:`${q}${r.name}`,label:`Subagent · ${r.name}${r.memoryScope?"":" (off)"}`}))],[i.agents,t]),It=p?`${q}${p.name}`:"workspace",Ot=o.useCallback(r=>{const f=r.startsWith(q)?i.agents.find(N=>N.name===r.slice(q.length)):void 0;n(f?{kind:"agent",agent:f}:{kind:"workspace"})},[i.agents,n]),Ft=m.startsWith("cluster:")?m==="cluster:unclustered"?"Unclustered":((Be=g.find(r=>r.id===m.slice(8)))==null?void 0:Be.name)??"Cluster":{all:"All memories",ask:"Ask",clusters:"Clusters",stale:"Stale",broken:"Broken references",recent:"Changed this week",unindexed:"Not in index",archived:"Archived"}[m]??"All memories";let xe=null;ee.length===0&&(y?xe={title:`${x} has no persistent memory`,body:"Add `memory: project` (or user/local) to its frontmatter in the Agent Library to turn it on.",action:"Back to workspace",onAction:()=>n({kind:"workspace"})}:b.trim()?xe={title:`No memories match “${b}”`,body:"Filter checks names and descriptions in this view.",action:"Clear filter",onAction:()=>$("")}:u.length===0&&m==="all"?xe={title:`${x} has no memories yet`,body:"They appear when this subagent saves one, or add one now.",action:"+ New memory",onAction:()=>Se(Re)}:xe={title:"All clear",body:m==="stale"?"Nothing is stale in this scope.":"Nothing in this view.",action:"Back to all memories",onAction:()=>L("all")});const Pt=!i.autoMemoryEnabled;return e.jsxs("div",{"data-testid":"mx-shell",className:"relative h-full flex flex-col bg-bg text-fg leading-[normal]",children:[Pt&&e.jsx("div",{"data-testid":"mx-auto-off",className:"shrink-0 w-full px-6 py-2 bg-butter/40 text-honey-dark text-[12.5px]",children:"Auto memory is off — Claude Code is not reading or writing any of these files."}),e.jsxs("div",{className:`flex-1 min-h-0 grid ${Y?"grid-cols-[316px_minmax(0,1fr)_268px]":"grid-cols-[316px_minmax(0,1fr)]"}`,children:[e.jsx($s,{title:Ft,rows:Y?ee:[],clusterDot:w,selected:h,onSelect:F,query:b,onQuery:$,sort:W,onSort:z,onNew:()=>Se(Re),empty:Y?xe:null,folder:{count:u.length,path:i.dir},scopeOptions:Tt,scopeKey:It,onScopeKey:Ot,view:m,onView:L,counts:Dt,clusterCount:g.length,archivedCount:i.archived.length}),m==="ask"&&e.jsx("div",{className:"min-w-0 min-h-0 flex",children:e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(Gs,{rows:u,context:Ce,onClearContext:()=>B(null),onAsk:(r,f)=>a.ask(r,Et(f)),onOpen:Te,onReverify:()=>L("stale"),onDraft:r=>Se(r)})})}),m==="clusters"&&e.jsx("div",{className:"min-w-0 min-h-0 flex",children:e.jsx(Ys,{clusters:g,rows:u,generatedAt:i.clustersMeta.generatedAt,running:i.clustersMeta.running,unclusteredCount:Rt,available:!p,onRegenerate:()=>{a.regenerateClusters()},onOpenCluster:r=>L(`cluster:${r}`),onOpen:Te})}),Y&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-col min-w-0 min-h-0",children:v==="new"?e.jsx(Ae,{mode:"new",name:null,title:M,onTitle:J,body:G,onBody:H,onSave:()=>{Pe()},onCancel:yt,saving:ie,dirty:M.trim()!==""||G!==Re}):l?e.jsx(Os,{row:l,content:U,clusterName:C(l.clusterId),clusterDot:w(l.clusterId),archived:j,editing:v==="edit",editingSuggestion:v==="edit"&&X,editor:v==="edit"?e.jsx(Ae,{mode:"edit",name:l.slug,path:l.path,title:"",onTitle:J,body:G,onBody:H,onSave:()=>{Pe()},onCancel:Fe,onRevert:()=>{bt()},changedFrom:X?le:void 0,saving:ie,dirty:be}):void 0,onRead:Fe,onEdit:ht,onCopyPath:()=>{Nt()},onReveal:Ct,onArchive:()=>{_e()},onRestore:()=>{jt()},onAskDelete:()=>I("delete"),fix:D,appliedStill:oe===l.slug&&l.stale,onFix:()=>{$e()},onApplyFix:()=>{kt()},onEditFirst:gt,onDiscardFix:()=>R(P),onVerify:()=>{vt()}}):e.jsx(Ae,{mode:"none",name:null,title:"",onTitle:J,body:"",onBody:H,onSave:()=>{},onCancel:()=>{},saving:!1,dirty:!1})}),e.jsx(Us,{row:j||v==="new"?null:l,known:Lt,onOpen:ft,onRemoveLink:r=>{St(r)},onUpdatePath:r=>{$t(r)},onReviewPath:()=>{$e()},onAskAbout:Mt,onCheck:()=>{$e()},checkBusy:D.state!=="idle"||U===null,editing:v==="edit",editingSuggestion:v==="edit"&&X,check:v==="edit"?null:At})]})]}),e.jsx(qs,{open:ae==="delete"&&l!==null,name:(l==null?void 0:l.slug)??"",inbound:(l==null?void 0:l.inLinks.length)??0,onArchive:()=>{_e()},onCancel:()=>I(null),onConfirm:()=>{wt()}}),e.jsx(Xs,{message:(_==null?void 0:_.message)??null,onUndo:_!=null&&_.undo?()=>{const r=_.undo;me(null),r==null||r()}:void 0,onClose:()=>me(null)})]})}function nn(){const s=at(),t=rt();return s?e.jsx(tn,{cwd:(t==null?void 0:t.cwd)??null}):e.jsx(Ne,{title:"loading…"})}const an=o.memo(nn),rn=[{key:"memory",label:"Memory",icon:"memory"},{key:"claude-md",label:"CLAUDE.md",icon:"system-prompt"},{key:"settings",label:"Settings",icon:"settings"},{key:"mcp",label:"MCP",icon:"mcp"},{key:"skills",label:"Skills",icon:"skills"}],ut=rn,st=s=>ut.some(t=>t.key===s);function xt(s,t){return{claudeMd:[`${s}/CLAUDE.md`,`${s}/CLAUDE.local.md`],settings:{project:`${s}/.claude/settings.json`,local:`${s}/.claude/settings.local.json`},mcp:`${s}/.mcp.json`,skillsDir:`${s}/.claude/skills`,commandsDir:`${s}/.claude/commands`,memoryDir:t}}const on={memoryDir:null,memory:null,memoryAttention:!1,claudeMd:null,settings:{project:null,local:null},mcp:null,skills:null},nt=s=>!!s&&typeof s=="object"&&!Array.isArray(s);async function se(s){try{return await s()}catch{return null}}async function ln(s){const t={workspace:ot(s),cwd:s},n=await se(()=>window.api.memory.list(t)),d=xt(s,(n==null?void 0:n.dir)??null),[i,a,u,g,p,y]=await Promise.all([se(async()=>(await Promise.all(d.claudeMd.map(cs))).reduce((x,m)=>x+m,0)),se(()=>He(d.settings.project)),se(()=>He(d.settings.local)),se(async()=>{const x=await window.api.config.readJson(d.mcp);if(x.error)throw new Error(x.error);const m=nt(x.data)?x.data.mcpServers:void 0;return nt(m)?Object.keys(m).length:0}),se(async()=>{const[x,m]=await Promise.all([Yt(d.skillsDir),window.api.config.listDir(d.commandsDir,{filesOnly:!0})]);if(x.errors[0])throw new Error(x.errors[0].error);const c=m.ok?m.entries.filter(h=>h.name.endsWith(".md")).length:0;return x.entries.length+c}),se(async()=>{if(!n||n.error)return!1;const x=await window.api.memory.stale(t);return it(n.entries??[],x,null,Date.now()).some(m=>m.stale||m.broken)})]);return{memoryDir:(n==null?void 0:n.dir)??null,memory:n&&!n.error?n.entries.length:null,memoryAttention:y??!1,claudeMd:i,settings:{project:a,local:u},mcp:g,skills:p}}function dn(s){const[t,n]=o.useState(null),d=o.useRef(0),i=o.useCallback(()=>{if(!s)return;const g=++d.current;ln(s).then(p=>{g===d.current&&n({cwd:s,counts:p})})},[s]);o.useEffect(()=>(i(),()=>{d.current++}),[i]);const a=t&&t.cwd===s?t.counts:on,u=s?xt(s,a.memoryDir):null;return Gt(u?[...u.claudeMd,u.settings.project,u.settings.local,u.mcp,u.skillsDir,u.commandsDir,u.memoryDir]:[],i,{depth:1}),a}const we=s=>s??void 0;function cn({home:s,cwd:t,scope:n,onScopeChange:d}){const i=o.useMemo(()=>({project:Ke.resolve("project",s,t),local:Ke.resolve("local",s,t)}),[s,t]),a=o.useMemo(()=>{const y=[];return i.project&&y.push({path:i.project,label:"Project · shared via git",eyebrow:"PROJECT INSTRUCTIONS"}),i.local&&y.push({path:i.local,label:"Local · this machine only",eyebrow:"LOCAL INSTRUCTIONS"}),y},[i]),u=o.useCallback(y=>d(y===i.local?"local":"project"),[i.local,d]),g=o.useMemo(()=>({title:n==="local"?"No private notes for this project yet.":"Nothing tells Claude how this repo works yet.",body:n==="local"?`Claude loads this file into every session started in ${We(t)} on this machine. It stays out of git.`:`It loads this file into every session started in ${We(t)} — and so does anyone who clones the repo.`}),[n,t]),p=i[n];return p?e.jsx("div",{"data-testid":"project-claude-md",className:"flex flex-col h-full min-h-0",children:e.jsx(ls,{home:s,scope:"project",roots:a,activeRoot:p,onSelectRoot:u,empty:g,moreMenu:({importSelected:y})=>e.jsx(is,{path:p,disabled:y})})}):e.jsx(Ne,{title:"loading…"})}function mn({scope:s,onScopeChange:t}){return e.jsx("div",{className:"flex flex-col h-full min-h-0",children:e.jsx(ds,{scope:s,onScopeChange:t})})}function un(){var R;const s=at(),t=((R=rt())==null?void 0:R.cwd)??null,[n,d]=o.useState("memory"),[i,a]=o.useState("project"),[u,g]=o.useState("project"),[p,y]=o.useState(null),[x,m]=o.useState(!1),c=dn(t),h=Xt(Jt),k=o.useMemo(()=>Qt(h),[h]),v=o.useCallback(E=>{d(E),y(null)},[]);Kt("memory",E=>{st(E)&&v(E)});const S=o.useCallback(E=>y(E),[]),b=o.useCallback(()=>y(null),[]),$=o.useCallback(()=>m(E=>!E),[]),W=o.useCallback(E=>{st(E.tab)&&(v(E.tab),fe.getState().set(E.tab,E.id))},[v]),z=o.useCallback(()=>Zt({scope:"project",cwd:t,api:window.api}),[t]),ae=es({load:z,loadKey:t??"",onChoose:W}),I=o.useMemo(()=>{const E={memory:{count:we(c.memory),attention:c.memoryAttention},"claude-md":ts(c.claudeMd),settings:{count:we(c.settings[u])},mcp:{count:we(c.mcp),attention:k},skills:{count:we(c.skills)}};return ut.map(re=>({...re,...E[re.key]}))},[c,u,k]);if(!s)return e.jsx(Ne,{title:"loading…"});if(!t)return e.jsx(Ne,{title:"no active project",hint:"open a project tab to edit its CLAUDE.md, settings, MCP servers, skills and memory"});const D=Wt.memory;return e.jsxs("div",{className:"flex flex-col h-full min-h-0 bg-bg text-fg","data-testid":"project-claude-config",children:[e.jsx(ss,{eyebrow:"CLAUDE CODE · PROJECT",title:"Claude config",scopePath:ms(t,s),tabs:I,activeKey:n,onSelect:v,onLearn:$,...ae.bandProps,searchPanel:e.jsx(ns,{...ae.panelProps,tabs:I})}),x&&D&&e.jsx("div",{className:"shrink-0 border-b border-line bg-bg-elev px-7 py-4 max-h-[40vh] overflow-y-auto","data-testid":"project-claude-config-learn",children:e.jsx(Ht,{content:D})}),e.jsxs("div",{className:"flex-1 min-h-0","data-testid":`project-claude-config-panel-${n}`,children:[n==="memory"&&e.jsx(an,{}),n==="claude-md"&&e.jsx(cn,{home:s,cwd:t,scope:i,onScopeChange:a}),n==="settings"&&e.jsx(mn,{scope:u,onScopeChange:g}),n==="mcp"&&e.jsx(as,{scope:"project",onAdd:S}),n==="skills"&&e.jsx(rs,{scope:"project"})]}),e.jsx(Vt,{open:p!==null,onClose:b,title:"Add MCP server",keyVals:[],children:p&&e.jsx(os,{scope:p.scope,cwd:p.cwd})})]})}const kn=o.memo(un);export{kn as ProjectClaudeConfig};