claude-code-session-manager 0.136.1 → 0.137.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 (44) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/assets/{AgentLibrary-DsJcjUSt.js → AgentLibrary-DV0DTZDC.js} +1 -1
  3. package/dist/assets/{AppSettings-DS_d4o5R.js → AppSettings-l7NTc0yu.js} +1 -1
  4. package/dist/assets/{Button-CVbZqtPJ.js → Button-Cmfkgjfa.js} +1 -1
  5. package/dist/assets/{DocumentEditorPane-C4G5oeng.js → DocumentEditorPane-MTljV-Uw.js} +1 -1
  6. package/dist/assets/{Extensions-ifcqZDuK.js → Extensions-Cc1Q_8id.js} +2 -2
  7. package/dist/assets/{History-CBFAmFB7.js → History-CFo-1DHo.js} +1 -1
  8. package/dist/assets/{Library-DlUH_fFF.js → Library-C_ibFiOx.js} +1 -1
  9. package/dist/assets/{ListDetail-DrzkqaSM.js → ListDetail-ByULG209.js} +1 -1
  10. package/dist/assets/{Panel-Bjr5sT2j.js → Panel-BuInRmA0.js} +1 -1
  11. package/dist/assets/ProjectClaudeConfig-yqqVtHY7.js +25 -0
  12. package/dist/assets/{ProvenanceBadge-Dlq0DSL2.js → ProvenanceBadge-CJvnQReI.js} +1 -1
  13. package/dist/assets/{Scheduler-CdwNo2AT.js → Scheduler-B7sn2mUw.js} +1 -1
  14. package/dist/assets/{Settings-BMy1KcDY.js → Settings-DRRSJksU.js} +1 -1
  15. package/dist/assets/{SkillReferenceGraph-CqngCjO5.js → SkillReferenceGraph-DwV0Ueyc.js} +1 -1
  16. package/dist/assets/{Skills-DCoKjG_1.js → Skills-DVYHA9gV.js} +1 -1
  17. package/dist/assets/{SourceChip-mjf4AO7V.js → SourceChip-DfJ5_5rV.js} +1 -1
  18. package/dist/assets/{SystemPrompt-BDv0OwoH.js → SystemPrompt-f11wGllK.js} +1 -1
  19. package/dist/assets/{TiptapBody-BdPKStNP.js → TiptapBody-Bl8hDhhS.js} +1 -1
  20. package/dist/assets/{Toggle-CaLQyunk.js → Toggle-DaxeFDFp.js} +1 -1
  21. package/dist/assets/{ViewTabs-DVLIAjik.js → ViewTabs-DRtgFKRw.js} +1 -1
  22. package/dist/assets/{VoiceButton-CUXKeY0C.js → VoiceButton-DJx-jY4r.js} +1 -1
  23. package/dist/assets/{historyTotals-07_oiLDE.js → historyTotals-Cgjm5q24.js} +1 -1
  24. package/dist/assets/{index-CgSMvkqr.js → index-iQ6pdyuS.js} +3 -3
  25. package/dist/index.html +1 -1
  26. package/dist-web/app.js +334 -334
  27. package/package.json +1 -1
  28. package/plugins/CLAUDE.md +1 -0
  29. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  30. package/plugins/session-manager-dev/skills/builder/SKILL.md +1 -0
  31. package/plugins/session-manager-dev/skills/send-feedback/SKILL.md +2 -0
  32. package/scripts/scheduler-mcp-server.cjs +46 -2
  33. package/src/main/build-info.json +4 -4
  34. package/src/main/lib/CLAUDE.md +2 -0
  35. package/src/main/lib/feedback-remote/crossProjectReply.cjs +81 -14
  36. package/src/main/lib/feedback-remote/localAdminHttp.cjs +14 -1
  37. package/src/main/lib/memoryRefResolve.cjs +64 -2
  38. package/src/main/lib/memoryStale.cjs +111 -18
  39. package/src/main/memoryAssist.cjs +23 -7
  40. package/src/main/memoryTool.cjs +58 -5
  41. package/src/main/promptSessionsIpc.cjs +1 -1
  42. package/src/main/templates/PRD_AUTHORING.md +3 -1
  43. package/src/preload/api.d.ts +2 -0
  44. package/dist/assets/ProjectClaudeConfig-BEJAWpS2.js +0 -25
@@ -0,0 +1,25 @@
1
+ import{aO as o,b7 as M,ay as e,a7 as U,ak as Dt,aS as Rt,aj as Tt,L as Pt,bh as et,b8 as tt,m as we,bm as It,C as _t,H as Ot,bb as te}from"./index-iQ6pdyuS.js";import{V as Me}from"./ViewTabs-DRtgFKRw.js";import{S as me}from"./SourceChip-DfJ5_5rV.js";import{S as st,M as Ft}from"./Library-C_ibFiOx.js";import{D as Bt}from"./DocumentEditorPane-MTljV-Uw.js";import{V as Ut}from"./VoiceButton-DJx-jY4r.js";import{Settings as Wt}from"./Settings-DRRSJksU.js";import{a as Kt,S as Vt}from"./Skills-DVYHA9gV.js";import"./monaco-editor-BsIlgG7c.js";import"./Button-Cmfkgjfa.js";import"./Panel-BuInRmA0.js";import"./claude-settings-schema-COigsajx.js";import"./ListDetail-ByULG209.js";import"./ProvenanceBadge-CJvnQReI.js";import"./Toggle-DaxeFDFp.js";function nt(s){return!s||!s.trim()?"default":s.replace(/[^a-zA-Z0-9]/g,"-")}const Be=["bg-accent","bg-sage-dark","bg-honey","bg-fg-dim","bg-fg-faint","bg-hive-teal","bg-butter","bg-delta-bad"],at=864e5,Ht="MEMORY.md",Ue=2e3,Ee=s=>s.replace(/\.md$/,"");function zt(s,t,n,l){var y,v,h;const u=new Map(((t==null?void 0:t.entries)??[]).map(a=>[a.name,a])),i=new Set(((y=t==null?void 0:t.index)==null?void 0:y.orphans)??[]),f=new Map;for(const a of(n==null?void 0:n.clusters)??[])for(const x of a.memberSlugs)f.has(x)||f.set(x,a.id);const c=s.filter(a=>a.name!==Ht),d=new Map;for(const a of c){const x=Ee(a.name),p=((v=u.get(a.name))==null?void 0:v.outLinks)??((h=u.get(x))==null?void 0:h.outLinks)??[];for(const w of p){const S=Ee(w),j=d.get(S)??[];j.includes(x)||j.push(x),d.set(S,j)}}return c.map(a=>{const x=Ee(a.name),p=u.get(a.name)??u.get(x),w=(p==null?void 0:p.deadRefs)??[],S=(p==null?void 0:p.danglingLinks)??[],j=(p==null?void 0:p.stale)??!1;return{name:a.name,slug:x,path:a.path,description:(p==null?void 0:p.description)??"",bytes:a.bytes,mtimeMs:a.mtimeMs,ageDays:Math.floor((l-a.mtimeMs)/at),stale:j,staleReasons:(p==null?void 0:p.reasons)??[],ageOnlyStale:j&&w.length===0,deadRefs:w,movedRefs:(p==null?void 0:p.movedRefs)??[],broken:w.length>0||S.length>0,danglingLinks:S,outLinks:(p==null?void 0:p.outLinks)??[],inLinks:d.get(x)??[],notIndexed:i.has(a.name)||i.has(x),clusterId:f.get(x)??null,type:(p==null?void 0:p.type)??null,originSessionId:(p==null?void 0:p.originSessionId)??null}})}function Gt(s,t){const n=new Set(t.filter(l=>l.stale).map(l=>l.slug));return((s==null?void 0:s.clusters)??[]).map((l,u)=>({id:l.id,name:l.name,summary:l.summary,memberSlugs:l.memberSlugs,linkCount:l.links.length,retireCount:l.links.filter(i=>/retire/i.test(i.label??"")).length,staleCount:l.memberSlugs.filter(i=>n.has(i)).length,dotClass:Be[u%Be.length]}))}function rt(s,t,n){const l=t.trim().toLowerCase(),u=l?s.filter(i=>i.slug.toLowerCase().includes(l)||i.description.toLowerCase().includes(l)):s;return n===void 0?u:u.slice(0,n)}function ue(s,t,n){let l;return t==="ask"||t==="clusters"||t==="archived"?[]:(t==="all"?l=s:t==="stale"?l=s.filter(u=>u.stale):t==="broken"?l=s.filter(u=>u.broken):t==="recent"?l=s.filter(u=>Date.now()-u.mtimeMs<=7*at):t==="unindexed"?l=s.filter(u=>u.notIndexed):t==="cluster:unclustered"?l=s.filter(u=>u.clusterId===null):t.startsWith("cluster:")?l=s.filter(u=>u.clusterId===t.slice(8)):l=s,rt(l,n))}function ot(s,t){const n=[...s];return t==="recent"?n.sort((l,u)=>u.mtimeMs-l.mtimeMs):t==="name"?n.sort((l,u)=>l.slug<u.slug?-1:l.slug>u.slug?1:0):n.sort((l,u)=>u.bytes-l.bytes),n}function Yt(s){return{all:s.length,stale:ue(s,"stale","").length,broken:ue(s,"broken","").length,recent:ue(s,"recent","").length,unindexed:ue(s,"unindexed","").length}}function lt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"untitled_memory"}function qt(s,t){const n=s===""?[]:s.split(`
2
+ `),l=t===""?[]:t.split(`
3
+ `);if(n.length>Ue||l.length>Ue)return[...n.map(v=>({sign:"−",text:v})),...l.map(v=>({sign:"+",text:v}))];const u=n.length,i=l.length,f=Array.from({length:u+1},()=>new Array(i+1).fill(0));for(let v=u-1;v>=0;v--)for(let h=i-1;h>=0;h--)f[v][h]=n[v]===l[h]?f[v+1][h+1]+1:Math.max(f[v+1][h],f[v][h+1]);const c=[];let d=0,y=0;for(;d<u&&y<i;)n[d]===l[y]?(d++,y++):f[d+1][y]>=f[d][y+1]?c.push({sign:"−",text:n[d++]}):c.push({sign:"+",text:l[y++]});for(;d<u;)c.push({sign:"−",text:n[d++]});for(;y<i;)c.push({sign:"+",text:l[y++]});return c}const O=s=>s instanceof Error?s.message:String(s);function We(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 Xt(s){return s.split(`
4
+ `).map(t=>t.trim()).find(t=>t.length>0)??""}function Qt(s,t){const n=s.kind==="agent"?s.agent:null,l=n?`${n.name}|${n.memoryScope??""}`:"",u=n!==null&&n.memoryScope===null,i=o.useMemo(()=>u?null:n&&n.memoryScope?{agent:{name:n.name,scope:n.memoryScope},...t?{cwd:t}:{}}:{workspace:nt(t),...t?{cwd:t}:{}},[l,u,t]),f=n===null,[c,d]=o.useState(!0),[y,v]=o.useState([]),[h,a]=o.useState(null),[x,p]=o.useState(null),[w,S]=o.useState(!1),[j,$]=o.useState(""),[T,W]=o.useState(!0),[ne,fe]=o.useState([]),[Q,A]=o.useState([]),[K,L]=o.useState({}),[he,Ne]=o.useState(()=>Date.now()),Z=o.useRef(i);Z.current=i;const P=o.useCallback(async()=>{if(!i){v([]),a(null),p(null),fe([]),$(""),d(!1);return}try{const b=await window.api.memory.list(i);if(Z.current!==i)return;v(b.entries??[]),$(b.dir??""),W(b.autoMemoryEnabled!==!1),b.error&&M.error(`Memory list failed: ${b.error}`);const[m,k]=await Promise.all([window.api.memory.stale(i).catch(C=>(M.error(`Memory staleness check failed: ${O(C)}`),null)),window.api.memory.listArchived(i).catch(()=>({names:[],error:null}))]);if(Z.current!==i)return;a(m),fe(k.names??[]),Ne(Date.now())}catch(b){M.error(`Memory list failed: ${O(b)}`)}finally{d(!1)}},[i]);o.useEffect(()=>{d(!0),p(null),P(),i&&f&&i.workspace&&window.api.memory.aggregate(i.workspace,!1,t??void 0).then(b=>{Z.current===i&&p(b)}).catch(b=>M.error(`Memory clusters failed: ${O(b)}`))},[P]),o.useEffect(()=>{let b=!1;return(async()=>{try{const{agents:m}=await window.api.memory.agents(t??void 0);if(b)return;A(m);const k={};await Promise.all(m.filter(C=>C.memoryScope).map(async C=>{const Y=await window.api.memory.list({agent:{name:C.name,scope:C.memoryScope},...t?{cwd:t}:{}});k[C.name]=(Y.entries??[]).filter(_=>_.name!=="MEMORY.md").length})),b||L(k)}catch(m){b||M.error(`Memory agents failed: ${O(m)}`)}})(),()=>{b=!0}},[t]),o.useEffect(()=>{if(!j)return;const b=j;window.api.config.watch([b]);const m=window.api.config.onChanged(({path:k})=>{(k===b||k.startsWith(b+"/"))&&P()});return()=>{m(),window.api.config.unwatch([b])}},[j,P]);const I=o.useMemo(()=>zt(y,h,x,he),[y,h,x,he]),ae=o.useMemo(()=>Gt(x,I),[x,I]),Ce=o.useMemo(()=>({generatedAt:(x==null?void 0:x.generatedAt)??null,running:w}),[x,w]),R=o.useCallback(async b=>{if(!i)return null;try{const m=await window.api.memory.read(b,i);return m.error?(M.error(`Memory read failed: ${m.error}`),null):m.content}catch(m){return M.error(`Memory read failed: ${O(m)}`),null}},[i]),E=o.useCallback(async(b,m)=>{try{const k=await m();return k.ok?(await P(),!0):(M.error(`${b} failed: ${k.error??"unknown error"}`),!1)}catch(k){return M.error(`${b} failed: ${O(k)}`),!1}},[P]),J=o.useCallback(async(b,m)=>{if(!i)return!1;const k=await R(b);if(k===null)return!1;const{front:C}=We(k);return E("Memory save",()=>window.api.memory.write(b,C+m,i))},[i,R,E]),V=o.useCallback(async(b,m)=>{if(!i)return null;const k=lt(b),C=Xt(m);if(!await E("Memory create",()=>window.api.memory.create(k,C,i)))return null;const _=`---
5
+ name: ${k}
6
+ description: ${C}
7
+ ---
8
+
9
+ ${m}
10
+ `;return await E("Memory create",()=>window.api.memory.write(k,_,i))?k:null},[i,E]),z=o.useCallback(async b=>{var Y,_;if(!i)return null;const m=await R(b);if(m===null||!await E("Memory delete",()=>window.api.memory.delete(b,i)))return null;const C=((_=(Y=We(m).front.match(/^description:\s*(.*)$/m))==null?void 0:Y[1])==null?void 0:_.trim())??"";return async()=>{await E("Memory undo",()=>window.api.memory.create(b,C,i))&&await E("Memory undo",()=>window.api.memory.write(b,m,i))}},[i,R,E]),ge=o.useCallback(b=>i?E("Memory archive",()=>window.api.memory.archive(b,i)):Promise.resolve(!1),[i,E]),re=o.useCallback(b=>i?E("Memory restore",()=>window.api.memory.restore(b,i)):Promise.resolve(!1),[i,E]),oe=o.useCallback(b=>i?E("Memory verify",()=>window.api.memory.verify(b,i)):Promise.resolve(!1),[i,E]),le=o.useCallback(async(b,m)=>{if(!i)return!1;const k=await R(b);if(k===null)return!1;const C=k.split(`[[${m}]]`).join(m);return E("Memory link removal",()=>window.api.memory.write(b,C,i))},[i,R,E]),ee=o.useCallback(async()=>{if(!(!i||!f||!i.workspace)){S(!0);try{const b=await window.api.memory.aggregate(i.workspace,!0,t??void 0);b.error?M.error(`Memory clustering failed: ${b.error}`):p(b)}catch(b){M.error(`Memory clustering failed: ${O(b)}`)}finally{S(!1)}}},[i,f,t]),be=o.useCallback(async(b,m)=>{const k=C=>({ok:!1,answer:"",citations:[],error:C});if(!i)return k("no memory store");try{const C=await window.api.memory.ask({question:b,target:i,contextName:m});return C.ok||M.error(`Memory ask failed: ${C.error??"unknown error"}`),C}catch(C){return M.error(`Memory ask failed: ${O(C)}`),k(O(C))}},[i]),G=o.useCallback(async b=>{const m=k=>({ok:!1,action:"keep",summary:"",reason:"",content:"",fold:null,error:k});if(!i)return m("no memory store");try{const k=await window.api.memory.proposeFix({name:b,target:i});return k.ok||M.error(`Memory fix failed: ${k.error??"unknown error"}`),k}catch(k){return M.error(`Memory fix failed: ${O(k)}`),m(O(k))}},[i]),ie=o.useMemo(()=>({refresh:P,read:R,saveBody:J,create:V,remove:z,archive:ge,restore:re,verify:oe,removeLink:le,regenerateClusters:ee,ask:be,proposeFix:G}),[P,R,J,V,z,ge,re,oe,le,ee,be,G]);return{loading:c,target:i,dir:j,autoMemoryEnabled:T,rows:I,clusters:ae,clustersMeta:Ce,index:h==null?void 0:h.index,archived:ne,agents:Q,agentCounts:K,actions:ie}}const Zt={user:"user — all projects",project:"project — shared via git",local:"local — this machine only"},se="text-[10px] tracking-[.08em] font-semibold text-fg-faint",it="flex items-center gap-2 h-7 px-2.5 rounded-[5px] text-[13px] cursor-pointer hover:bg-muteband text-left w-full";function Ke(s,t){return s.memoryScope===null?"off":String(t[s.name]??0)}function Ae({id:s,label:t,count:n,dot:l,active:u,mono:i,onClick:f,check:c}){return e.jsxs("button",{type:"button","data-testid":`mx-nav-${s}`,onClick:f,className:`${it} ${u?"bg-bg font-semibold text-fg":"text-fg-dim"}`,children:[e.jsx("span",{className:`w-[7px] h-[7px] rounded-sm shrink-0 ${l||"bg-transparent"}`}),e.jsx("span",{className:`flex-1 min-w-0 truncate ${i?"font-mono text-xs":""}`,children:t}),n!==void 0&&e.jsx("span",{className:`font-mono text-[11px] ${c&&n===0?"text-sage-dark":u?"text-fg":"text-fg-faint"}`,children:c&&n===0?"✓":n})]})}function Ve({label:s,value:t,max:n,tone:l}){const u=Math.min(100,Math.round(t/Math.max(1,n)*100));return e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsxs("span",{className:"font-mono text-[10px] text-fg-faint",children:[s," ",t,"/",n]}),e.jsx("div",{className:"h-1 rounded-full bg-bg-muteband overflow-hidden",children:e.jsx("div",{className:`h-full ${l}`,style:{width:`${u}%`}})})]})}const Jt=o.memo(function(t){var v,h;const[n,l]=o.useState(!1),u=o.useRef(null),i=t.scope.kind==="agent";o.useEffect(()=>{if(!n)return;const a=p=>{p.key==="Escape"&&l(!1)},x=p=>{u.current&&!u.current.contains(p.target)&&l(!1)};return document.addEventListener("keydown",a),document.addEventListener("mousedown",x),()=>{document.removeEventListener("keydown",a),document.removeEventListener("mousedown",x)}},[n]);const f=a=>{l(!1),t.onScope(a)},c=(a,x,p,w,S)=>e.jsx(Ae,{id:a,label:x,dot:p,count:w,check:S,active:t.view===a,onClick:()=>t.onView(a)}),d=t.scope.kind==="agent"?t.scope.agent:null,y=(v=t.index)!=null&&v.overBudget?"bg-accent":(h=t.index)!=null&&h.nearBudget?"bg-honey":"bg-sage-dark";return e.jsxs("nav",{"data-testid":"mx-nav",className:"w-[232px] shrink-0 flex flex-col gap-4 bg-bg-elev border-r border-rule-structural px-2.5 py-3.5 overflow-y-auto",children:[e.jsxs("div",{ref:u,className:"relative",children:[e.jsxs("button",{type:"button","data-testid":"mx-scope-card",onClick:()=>l(a=>!a),className:"w-full flex flex-col gap-0.5 px-2.5 py-2 border border-rule-structural rounded-md bg-bg cursor-pointer text-left hover:border-fg-faint",children:[e.jsx("span",{className:se,children:d?"SUBAGENT":"WORKSPACE"}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"font-mono text-xs text-fg flex-1 min-w-0 truncate",children:d?d.name:t.workspaceName}),e.jsx("span",{className:"text-[10px] text-fg-faint",children:"▾"})]}),e.jsx("span",{className:"font-mono text-[10px] text-fg-faint truncate",children:d?d.agentFile:t.workspacePath}),d&&d.memoryScope&&e.jsx("span",{className:"text-[10.5px] text-fg-faint",children:Zt[d.memoryScope]})]}),n&&e.jsxs("div",{"data-testid":"mx-scope-menu",className:`absolute left-0 right-0 top-full mt-1 ${U.dialog} bg-bg-hi border border-rule-structural rounded-[7px] shadow-lg p-1 flex flex-col`,children:[e.jsxs("button",{type:"button",onClick:()=>f({kind:"workspace"}),className:"flex items-center gap-2 px-2 py-1.5 rounded-[5px] text-left hover:bg-bg-elev",children:[e.jsx("span",{className:"w-3 text-[11px] text-sage-dark",children:d?"":"✓"}),e.jsxs("span",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"font-mono text-xs text-fg truncate",children:t.workspaceName}),e.jsx("span",{className:"text-[10.5px] text-fg-faint",children:"workspace"})]}),e.jsx("span",{className:"font-mono text-[11px] text-fg-faint",children:t.workspaceCount})]}),t.agents.map(a=>e.jsxs("button",{type:"button",onClick:()=>f({kind:"agent",agent:a}),className:"flex items-center gap-2 px-2 py-1.5 rounded-[5px] text-left hover:bg-bg-elev",children:[e.jsx("span",{className:"w-3 text-[11px] text-sage-dark",children:(d==null?void 0:d.name)===a.name?"✓":""}),e.jsxs("span",{className:"flex flex-col flex-1 min-w-0",children:[e.jsx("span",{className:"font-mono text-xs text-fg truncate",children:a.name}),e.jsxs("span",{className:"text-[10.5px] text-fg-faint",children:["subagent",a.memoryScope?` · ${a.memoryScope}`:""]})]}),e.jsx("span",{className:"font-mono text-[11px] text-fg-faint",children:Ke(a,t.agentCounts)})]},a.name))]})]}),e.jsxs("div",{className:"flex flex-col gap-px",children:[e.jsx("div",{className:`px-2.5 pb-1.5 ${se}`,children:"BROWSE"}),c("all","All memories","",t.counts.all),c("ask","Ask",""),c("clusters","Clusters","",t.clusters.length)]}),e.jsxs("div",{className:"flex flex-col gap-px",children:[e.jsx("div",{className:`px-2.5 pb-1.5 ${se}`,children:"REVIEW"}),c("stale","Stale","bg-honey",t.counts.stale,!0),c("broken","Broken references","bg-accent",t.counts.broken,!0),c("recent","Changed this week","",t.counts.recent),c("unindexed","Not in index","",t.counts.unindexed,!0),t.archivedCount>0&&c("archived","Archived","",t.archivedCount)]}),!i&&e.jsxs("div",{className:"flex flex-col gap-px",children:[e.jsx("div",{className:`px-2.5 pb-1.5 ${se}`,children:"CLUSTERS"}),t.clusters.map(a=>e.jsx(Ae,{id:`cluster:${a.id}`,label:a.name,dot:a.dotClass,count:t.clusterCounts[a.id]??0,active:t.view===`cluster:${a.id}`,onClick:()=>t.onView(`cluster:${a.id}`)},a.id)),t.unclusteredCount>0&&e.jsx(Ae,{id:"cluster:unclustered",label:"Unclustered",dot:"bg-rule",count:t.unclusteredCount,active:t.view==="cluster:unclustered",onClick:()=>t.onView("cluster:unclustered")})]}),t.agents.length>0&&e.jsxs("div",{className:"flex flex-col gap-px",children:[e.jsx("div",{className:`px-2.5 pb-1.5 ${se}`,children:"SUBAGENT SCOPES"}),t.agents.map(a=>e.jsxs("button",{type:"button","data-testid":`mx-nav-agent:${a.name}`,onClick:()=>t.onScope({kind:"agent",agent:a}),className:`${it} text-fg-dim ${(d==null?void 0:d.name)===a.name?"bg-bg font-semibold":""}`,children:[e.jsx("span",{className:"font-mono text-xs flex-1 truncate",children:a.name}),e.jsx("span",{className:"font-mono text-[11px] text-fg-faint",children:Ke(a,t.agentCounts)})]},a.name))]}),t.index&&e.jsxs("div",{"data-testid":"mx-index-footer",className:"mt-auto flex flex-col gap-1.5 pt-3 border-t border-rule-inner",children:[e.jsx("span",{className:se,children:"MEMORY.md"}),e.jsx(Ve,{label:"lines",value:t.index.lines,max:t.index.maxLines,tone:y}),e.jsx(Ve,{label:"KB",value:Math.round(t.index.bytes/1024),max:Math.round(t.index.maxBytes/1024),tone:y}),t.index.dangling.length>0&&e.jsxs("span",{className:"text-[10.5px] text-accent-dark",children:[t.index.dangling.length," index lines point at missing files"]})]})]})}),es={recent:"name",name:"size",size:"recent"},ts={recent:"Recent",name:"Name",size:"Size"},Le="text-[9.5px] font-semibold tracking-[.06em] px-[5px] py-px rounded-[3px]";function ss(s){return`${Dt(s.bytes)} · ${s.ageDays>0?`${s.ageDays}d ago`:"just now"}`}const ns=o.memo(function(t){return e.jsxs("div",{"data-testid":"mx-list",className:"flex flex-col min-h-0 border-r border-rule-structural",children:[e.jsxs("div",{className:"flex flex-col gap-[10px] px-[14px] pt-[14px] pb-[10px] border-b border-rule-structural",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-serif text-lg 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(es[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:`${ts[t.sort]} ⇅`})]})]}),e.jsxs("div",{className:"overflow-auto flex-1 p-[6px]",children:[t.rows.map(n=>e.jsxs("div",{"data-testid":`mx-list-row-${n.name}`,onClick:()=>t.onSelect(n.name),className:`px-[10px] py-2 rounded-md cursor-pointer flex flex-col gap-[3px] hover:bg-bg-elev ${t.selected===n.name?"bg-muteband":""}`,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] font-medium flex-1 min-w-0 overflow-hidden text-ellipsis whitespace-nowrap",children:n.slug}),n.stale&&e.jsx("span",{className:`${Le} bg-butter/40 text-honey-dark`,children:"STALE"}),n.broken&&!n.stale&&e.jsx("span",{className:`${Le} bg-accent-muted/30 text-accent-dark`,children:"BROKEN"}),n.notIndexed&&e.jsx("span",{className:`${Le} bg-rule-inner text-fg-dim`,children:"NOT INDEXED"})]}),e.jsx("div",{className:"text-[11.5px] text-fg-dim pl-[14px] overflow-hidden text-ellipsis whitespace-nowrap",children:n.description}),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})]})]})]})}),De="text-xs font-medium h-[26px] px-2.5 border border-rule-structural rounded-[5px] bg-bg text-fg hover:border-fg",ye="px-[7px] py-0.5 rounded bg-bg-elev",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",He={update:{apply:"Apply",hint:"Writes the file"},delete:{apply:"Archive",hint:"Moves to .archive — undoable"},keep:{apply:"Mark verified",hint:"Touches the file, clears age staleness"},fold:{apply:"Copy for an Epic",hint:"Memory stays until the doc change lands"}};function rs(s){var t;return s.action==="delete"?"Suggested: archive this memory":s.action==="fold"?`Suggested: move into ${((t=s.fold)==null?void 0:t.target)??"a doc"}`:s.action==="keep"?"Looks accurate — keep":"Suggested update"}function os(s){return s<1024?`${s} B`:`${(s/1024).toFixed(1)} KB`}function ls(s){return s<=0?"just now":`${s}d ago`}function is(s){const t=/^---\r?\n[\s\S]*?\r?\n---[ \t]*(?:\r?\n|$)/.exec(s);return(t?s.slice(t[0].length):s).trim()}function cs(s){return s.replace(/^\*\*Why:\*\*[ \t]*/gim,`#### WHY
11
+
12
+ `).replace(/^\*\*How to apply:\*\*[ \t]*/gim,`#### HOW TO APPLY
13
+
14
+ `)}const ds=o.memo(function(t){const{row:n,fix:l}=t,[u,i]=o.useState(!1),f=o.useMemo(()=>t.content===null||t.mode!=="read"?"":Rt(cs(is(t.content))),[t.content,t.mode]),c=d=>()=>{i(!1),d()};return e.jsxs("div",{"data-testid":"mx-reader",className:"flex flex-col flex-1 min-w-0 min-h-0",children:[e.jsxs("div",{className:"px-[22px] pt-3.5 pb-3 border-b border-rule-structural flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-fg-dim",children:[e.jsx("span",{className:`w-[7px] h-[7px] rounded-sm ${t.clusterDot}`}),e.jsx("span",{children:t.clusterName}),e.jsx("span",{className:"flex-1"}),!t.archived&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex border border-rule-structural rounded-[5px] overflow-hidden",children:[e.jsx("button",{type:"button","data-testid":"mx-reader-mode-read",onClick:()=>t.onMode("read"),className:`px-2.5 py-[3px] text-fg ${t.mode==="read"?"bg-muteband":""}`,children:"Read"}),e.jsx("button",{type:"button","data-testid":"mx-reader-mode-source",onClick:()=>t.onMode("source"),className:`px-2.5 py-[3px] text-fg border-l border-rule-structural ${t.mode==="source"?"bg-muteband":""}`,children:"Source"})]}),e.jsx("button",{type:"button","data-testid":"mx-reader-edit",onClick:t.onEdit,className:De,children:"Edit"}),e.jsxs("div",{className:"relative",children:[e.jsx("button",{type:"button","data-testid":"mx-reader-more",onClick:()=>i(d=>!d),className:`${De} !px-2`,children:"⋯"}),u&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`fixed inset-0 ${U.dialog}`,onClick:()=>i(!1)}),e.jsxs("div",{className:`absolute right-0 top-8 w-[200px] ${U.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:c(t.onCopyPath),children:"Copy path"}),e.jsx("button",{type:"button",className:ve,onClick:c(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:c(t.onArchive),children:"Archive"}),e.jsx("button",{type:"button",className:`${ve} text-accent`,onClick:c(t.onAskDelete),children:"Delete…"})]})]})]})]})]}),e.jsx("div",{className:"font-mono text-[18px] font-medium text-fg break-all",children:n.slug}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-[11.5px] text-fg-dim",children:[n.type&&e.jsxs("span",{className:ye,children:["type · ",n.type]}),e.jsx("span",{className:ye,children:os(n.bytes)}),e.jsxs("span",{className:ye,children:["modified ",ls(n.ageDays)]}),n.originSessionId&&e.jsxs("span",{className:`${ye} font-mono text-[10.5px]`,children:["session ",n.originSessionId.slice(0,8)]})]})]}),!t.archived&&!n.stale&&l.state==="idle"&&e.jsxs("div",{className:"mx-[22px] mt-3 flex items-center gap-2 text-[11px] text-fg-dim",children:[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] border border-rule-structural text-fg hover:border-fg",children:"Review with assistant"}),e.jsx("span",{children:"uses Claude"})]}),t.archived&&e.jsxs("div",{className:"mx-[22px] 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:De,children:"Restore"})]}),!t.archived&&n.stale&&l.state==="idle"&&e.jsxs("div",{"data-testid":"mx-reader-stale",className:"mx-[22px] 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&&l.state==="checking"&&e.jsxs("div",{className:"mx-[22px] 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&&l.state==="proposed"&&e.jsxs("div",{className:"mx-[22px] mt-3 border border-honey rounded-md overflow-hidden bg-bg-hi",children:[e.jsx("div",{className:"px-3 py-[9px] bg-butter/40 text-[12.5px] text-honey-dark font-semibold",children:rs(l)}),e.jsxs("div",{className:"px-3 py-2 text-[12.5px] text-fg flex flex-col gap-0.5",children:[e.jsx("span",{"data-testid":"mx-reader-summary",children:l.summary}),l.reason&&e.jsx("span",{"data-testid":"mx-reader-reason",className:"text-fg-dim",children:l.reason})]}),l.action==="fold"&&l.fold&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"px-3 py-1.5 border-t border-rule-inner text-[11.5px] text-fg-dim font-mono break-all",children:[l.fold.target," · ",l.fold.anchor||"append at end"]}),l.fold.insert.split(`
15
+ `).map((d,y)=>e.jsxs("div",{className:"grid grid-cols-[20px_1fr] px-3 py-1.5 font-mono text-xs leading-normal border-t border-rule-inner bg-sage/20 text-sage-dark",children:[e.jsx("span",{children:"+"}),e.jsx("span",{className:"whitespace-pre-wrap break-words",children:d})]},y))]}),l.action==="update"&&l.diff.map((d,y)=>e.jsxs("div",{className:`grid grid-cols-[20px_1fr] px-3 py-1.5 font-mono text-xs leading-normal border-t border-rule-inner ${d.sign==="−"?"bg-accent-muted/30 text-accent-dark":d.sign==="+"?"bg-sage/20 text-sage-dark":"text-fg-dim"}`,children:[e.jsx("span",{children:d.sign}),e.jsx("span",{className:"whitespace-pre-wrap break-words",children:d.text})]},y)),e.jsxs("div",{className:"flex gap-2 px-3 py-2.5 border-t border-rule-structural items-center",children:[e.jsx("button",{type:"button","data-testid":"mx-reader-apply",onClick:t.onApplyFix,className:"text-xs font-medium h-7 px-3 rounded-[5px] bg-fg text-bg",children:He[l.action].apply}),e.jsx("button",{type:"button","data-testid":"mx-reader-discard",onClick:t.onDiscardFix,className:"text-xs font-medium h-7 px-3 rounded-[5px] border border-rule text-fg",children:"Discard"}),e.jsx("span",{className:"flex-1"}),e.jsx("span",{className:"text-[11.5px] text-fg-dim",children:He[l.action].hint})]})]}),n.broken&&!n.stale&&e.jsx("div",{className:"mx-[22px] 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-[22px] 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-[22px] pt-4 pb-[22px]",children:t.content===null?e.jsx("div",{className:"text-xs text-fg-faint",children:"Loading…"}):t.mode==="source"?e.jsx("pre",{className:"m-0 px-4 py-3.5 bg-fg text-bg-elev rounded-md font-mono text-xs leading-[1.7] whitespace-pre-wrap",children:t.content}):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:f}})]})}),e.jsx("div",{className:"px-[22px] py-2 border-t border-rule-structural font-mono text-[10.5px] text-fg-dim whitespace-nowrap overflow-hidden text-ellipsis",children:n.path})]})});function xs({mode:s,name:t,title:n,onTitle:l,body:u,onBody:i,onSave:f,onCancel:c,saving:d,dirty:y}){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 /."})]});const v=d||s==="edit"&&!y,h=a=>{(a.metaKey||a.ctrlKey)&&a.key.toLowerCase()==="s"?(a.preventDefault(),v||f()):a.key==="Escape"&&(a.preventDefault(),c())};return e.jsxs("div",{"data-testid":"mx-editor",className:"flex-1 min-h-0 flex flex-col",onKeyDown:h,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:s==="new"?"New memory":`Editing ${t??""}`}),e.jsx("button",{type:"button","data-testid":"mx-editor-cancel",onClick:c,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:v,onClick:f,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:[s==="new"&&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:a=>l(a.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:["→ ",lt(n),".md"]})]}),e.jsx("textarea",{"data-testid":"mx-editor-body",value:u,onChange:a=>i(a.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.jsxs("div",{className:"flex items-center gap-2 text-[11.5px] text-fg-faint",children:[e.jsx("span",{children:`Markdown. Frontmatter is ${s==="new"?"added":"kept"} on save. Saving marks the memory verified.`}),y&&s==="edit"&&e.jsx("span",{className:"text-accent font-semibold",children:"unsaved"})]})]})]})}const ze=o.memo(xs),Re="text-[10px] tracking-[.08em] font-semibold text-fg-dim",ms="flex flex-col gap-px px-2 py-[6px] rounded-[5px] cursor-pointer bg-bg border text-left hover:border-fg-faint";function je({testid:s,slug:t,sub:n,dangling:l,onClick:u}){return e.jsxs("button",{type:"button","data-testid":s,onClick:u,className:`${ms} ${l?"border-accent-muted":"border-rule-inner"}`,children:[e.jsx("span",{className:`text-[12px] font-medium overflow-hidden text-ellipsis whitespace-nowrap ${l?"text-accent":""}`,children:t}),e.jsx("span",{className:`text-[10.5px] ${l?"text-accent":"text-fg-dim"}`,children:n})]})}const us=o.memo(function({row:t,onOpen:n,onRemoveLink:l,onAskAbout:u,onUpdatePath:i,onReviewPath:f}){return e.jsx("aside",{"data-testid":"mx-links",className:"bg-bg-elev border-l border-rule-structural px-[14px] py-4 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:Re,children:["LINKS TO · ",t.outLinks.length]}),t.outLinks.map(c=>{const d=t.danglingLinks.includes(c);return e.jsx(je,{testid:`mx-link-out-${c}`,slug:c,dangling:d,sub:d?"missing · click to remove link":"wikilink",onClick:()=>d?l(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:Re,children:["PATHS · ",t.movedRefs.length+t.deadRefs.length]}),t.movedRefs.map((c,d)=>e.jsx(je,{testid:`mx-path-moved-${d}`,slug:c.from,dangling:!1,sub:`moved to ${c.to} · click to update`,onClick:()=>i({from:c.from,to:c.to})},`moved-${c.from}`)),t.deadRefs.map((c,d)=>e.jsx(je,{testid:`mx-path-dead-${d}`,slug:c,dangling:!0,sub:"not found anywhere · review with assistant",onClick:f},`dead-${c}`))]}),e.jsxs("div",{className:"flex flex-col gap-[6px]",children:[e.jsxs("span",{className:Re,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."})]}),e.jsxs("button",{type:"button","data-testid":"mx-links-ask",onClick:u,className:"mt-auto flex flex-col gap-[6px] p-[10px] border border-dashed border-rule rounded-[6px] cursor-pointer text-left hover:border-fg",children:[e.jsx("span",{className:"text-[12px] text-fg",children:"Ask about this memory"}),e.jsx("span",{className:"h-7 border border-rule-structural rounded-[5px] bg-bg-hi px-2 flex items-center text-[11.5px] text-fg-dim",children:"Is this still accurate?"})]})]})})}),ps=["What changed this week?","Find contradictions","Summarize stale memories","remember …"],fs=["Is this still accurate?","What links here?","Summarize it"],hs=/^remember\b[\s:,-]*/i,Ge="text-xs font-medium h-[26px] px-2.5 rounded-[5px] bg-fg text-bg",gs=s=>s.charAt(0).toUpperCase()+s.slice(1),bs=o.memo(function({rows:t,context:n,onClearContext:l,onAsk:u,onOpen:i,onReverify:f,onDraft:c}){const[d,y]=o.useState(""),[v,h]=o.useState(!1),[a,x]=o.useState(null),p=async()=>{const j=d.trim();if(!j||v)return;if(/^remember\b/i.test(j)){x({kind:"draft",question:j,text:gs(j.replace(hs,""))}),y("");return}h(!0);let $=null;try{$=await u(j,n)}catch{$=null}h(!1),!(!$||!$.ok)&&(x({kind:"answer",question:j,answer:$.answer,citations:$.citations}),y(""))},w=(a==null?void 0:a.kind)==="answer"?a.citations.map(j=>({slug:j,row:t.find($=>$.slug===j||$.name===j)})):[],S=w.filter(j=>{var $;return($=j.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:l,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:[!a&&!v&&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.'})]}),a&&e.jsx("div",{className:"self-end max-w-[520px] px-3.5 py-2.5 rounded-[10px] bg-fg text-bg text-[14px]",children:a.question}),(a==null?void 0:a.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:a.answer}),e.jsx("div",{className:"flex flex-wrap gap-1.5 items-center",children:w.map((j,$)=>{var T;return e.jsxs("button",{"data-testid":`mx-ask-cite-${j.slug}`,onClick:()=>{var W;return i(((W=j.row)==null?void 0:W.name)??j.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:j.slug}),j.row&&e.jsxs("span",{className:"text-fg-dim",children:[j.row.ageDays,"d"]}),((T=j.row)==null?void 0:T.stale)&&e.jsx("span",{className:"text-[9.5px] font-semibold px-1 rounded-[3px] bg-butter/40 text-honey-dark",children:"STALE"})]},j.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:f,className:Ge,children:"Re-verify"})]})]}),(a==null?void 0:a.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:a.text}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>c(a.text),className:`${Ge} 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"})]})]}),v&&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?fs:ps).map(j=>e.jsx("button",{onClick:()=>y(j),className:"px-2.5 py-1 border border-rule-structural rounded-[14px] text-xs text-fg-dim hover:bg-bg-elev",children:j},j))}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{"data-testid":"mx-ask-input",value:d,onChange:j=>y(j.target.value),onKeyDown:j=>{j.key==="Enter"&&p()},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(Ut,{}),e.jsx("button",{"data-testid":"mx-ask-send",onClick:()=>void p(),disabled:v,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"})]})]})]})}),Ye="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:l,running:u,unclusteredCount:i,available:f,onRegenerate:c,onOpenCluster:d,onOpen:y}){const v=o.useMemo(()=>new Map(n.map(h=>[h.slug,h])),[n]);return f?l===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:Ye,disabled:u,onClick:c,children:u?"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 ",Tt(l,Date.now())," from shared references and links"]}),e.jsx("span",{className:"flex-1"}),i>0&&e.jsxs("span",{className:"text-xs text-honey-dark px-2 py-0.5 rounded bg-butter/40",children:[i," unclustered"]}),e.jsx("button",{type:"button","data-testid":"mx-clusters-regenerate",className:Ye,disabled:u,onClick:c,children:u?"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(h=>e.jsxs("div",{"data-testid":`mx-cluster-${h.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 ${h.dotClass}`}),e.jsx("span",{className:"font-serif text-[17px] text-fg min-w-0 flex-1",children:h.name}),e.jsxs("button",{type:"button","data-testid":`mx-cluster-open-${h.id}`,className:"text-xs text-accent hover:text-fg",onClick:()=>d(h.id),children:["Open ",h.memberSlugs.length," →"]})]}),e.jsx("span",{className:"text-[12.5px] leading-normal text-fg-dim",children:h.summary}),e.jsx("div",{className:"flex flex-wrap gap-[5px] items-center",children:h.memberSlugs.map(a=>{const x=v.get(a);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 ${x!=null&&x.stale?"bg-butter/40":"bg-bg"}`,onClick:()=>y((x==null?void 0:x.name)??`${a}.md`),children:a},a)})}),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:[h.linkCount," links"]}),e.jsxs("span",{children:[h.retireCount," retires"]}),e.jsxs("span",{className:"text-honey-dark",children:[h.staleCount," stale"]})]})]},h.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."})});function vs({open:s,rows:t,clusterDot:n,onPick:l,onAsk:u,onClose:i}){const[f,c]=o.useState(""),[d,y]=o.useState(0);if(o.useEffect(()=>{s&&(c(""),y(0))},[s]),!s)return null;const v=rt(ot(t,"recent"),f,6),h=v.length,a=p=>{p===h?u(f):l(v[p].name)},x=p=>{p.key==="ArrowDown"?(p.preventDefault(),y(w=>Math.min(w+1,h))):p.key==="ArrowUp"?(p.preventDefault(),y(w=>Math.max(w-1,0))):p.key==="Enter"?(p.preventDefault(),a(Math.min(d,h))):p.key==="Escape"&&(p.preventDefault(),i())};return e.jsxs("div",{"data-testid":"mx-palette",children:[e.jsx("div",{className:`absolute inset-0 ${U.dialog} bg-fg/30`,onClick:i}),e.jsxs("div",{className:`absolute left-1/2 top-[84px] -translate-x-1/2 w-[580px] ${U.dialog} bg-bg-hi border border-rule rounded-[10px] shadow-2xl overflow-hidden`,children:[e.jsx("input",{"data-testid":"mx-palette-input",autoFocus:!0,value:f,onChange:p=>{c(p.target.value),y(0)},onKeyDown:x,placeholder:"Search memories or ask a question…",className:"w-full h-[50px] border-0 border-b border-rule-inner px-[18px] text-[15px] text-fg bg-transparent outline-none"}),e.jsxs("div",{className:"p-[6px] flex flex-col max-h-[380px] overflow-auto",children:[v.map((p,w)=>e.jsxs("div",{"data-testid":"mx-palette-row",onClick:()=>a(w),onMouseEnter:()=>y(w),className:`flex items-center gap-[9px] px-3 py-2 rounded-[6px] cursor-pointer ${w===d?"bg-bg-deep":""}`,children:[e.jsx("span",{className:`w-[7px] h-[7px] rounded-[2px] flex-none ${n(p.clusterId)}`}),e.jsx("span",{className:"font-mono text-[12.5px] text-fg flex-none",children:p.slug}),e.jsx("span",{className:"text-[12px] text-fg-dim overflow-hidden text-ellipsis whitespace-nowrap",children:p.description})]},p.name)),e.jsxs("div",{"data-testid":"mx-palette-ask",onClick:()=>a(h),onMouseEnter:()=>y(h),className:`flex items-center gap-[9px] px-3 py-[10px] mt-1 border-t border-rule-inner cursor-pointer text-[13px] text-accent ${d===h?"bg-bg-deep":""}`,children:[e.jsx("span",{className:"font-mono text-[11px]",children:"↵"}),"Ask “",f,"” …",e.jsx("span",{className:"flex-1"}),e.jsx("span",{className:"text-[11px] text-fg-dim",children:"opens Ask"})]})]}),e.jsxs("div",{className:"px-[14px] py-2 border-t border-rule-inner text-[11px] text-fg-dim flex gap-[14px]",children:[e.jsx("span",{children:"↑↓ move"}),e.jsx("span",{children:"↵ open"}),e.jsx("span",{children:"esc close"})]})]})]})}const Te="text-[12.5px] font-medium h-8 px-3 rounded-[5px] cursor-pointer text-fg";function js({open:s,name:t,inbound:n,onArchive:l,onCancel:u,onConfirm:i}){return o.useEffect(()=>{if(!s)return;const f=c=>{c.key==="Escape"&&u()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[s,u]),s?e.jsxs("div",{"data-testid":"mx-delete-dialog",children:[e.jsx("div",{className:`absolute inset-0 ${U.dialog} bg-fg/30`,onClick:u}),e.jsxs("div",{className:`absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-[440px] ${U.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:l,className:`${Te} border border-rule mr-auto`,children:"Archive instead"}),e.jsx("button",{type:"button",onClick:u,className:`${Te} border border-rule bg-bg`,children:"Cancel"}),e.jsx("button",{type:"button","data-testid":"mx-delete-confirm",onClick:i,className:`${Te} border-0 px-[14px] bg-accent text-white`,children:"Delete"})]})]})]}):null}const ks=6e3;function ws({message:s,onUndo:t,onClose:n}){return o.useEffect(()=>{if(s===null)return;const l=setTimeout(n,ks);return()=>clearTimeout(l)},[s]),s===null?null:e.jsxs("div",{"data-testid":"mx-undo-bar",className:`absolute bottom-[22px] left-1/2 -translate-x-1/2 ${U.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 ct="sm.memoryTab.scope",pe="agent:",Pe=`One-line summary of the fact or rule.
16
+
17
+ **Why:**
18
+
19
+ **How to apply:**`,F={state:"idle",diff:[],summary:"",action:"update",reason:"",fold:null},Xe=s=>s.replace(/\.md$/,""),Qe=s=>s?s.split(/[\\/]/).filter(Boolean).pop()??s:"workspace";function ke(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 Ns=s=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function Cs(s,t,n){return s.replace(new RegExp("`"+Ns(t)+"(:\\d+)?`","g"),(l,u)=>"`"+n+(u??"")+"`")}function Ss(){try{const s=localStorage.getItem(ct);return s&&s.startsWith(pe)?s:"workspace"}catch{return"workspace"}}function $s({cwd:s}){const[t,n]=o.useState(Ss),[l,u]=o.useState([]),[i,f]=o.useState(0),c=o.useMemo(()=>{if(!t.startsWith(pe))return"workspace";const h=t.slice(pe.length);return l.some(a=>a.name===h)?t:"workspace"},[t,l]),d=o.useMemo(()=>{if(c==="workspace")return{kind:"workspace"};const h=l.find(a=>a.name===c.slice(pe.length));return h?{kind:"agent",agent:h}:{kind:"workspace"}},[c]),y=o.useCallback(h=>{const a=h.kind==="agent"?`${pe}${h.agent.name}`:"workspace";try{localStorage.setItem(ct,a)}catch{}n(a)},[]),v=o.useCallback(h=>{h.length>0&&u(h)},[]);return e.jsx(Ms,{scope:d,cwd:s,onScope:y,onAgents:v,wsCount:i,onWsCount:f},c)}function Ms({scope:s,cwd:t,onScope:n,onAgents:l,wsCount:u,onWsCount:i}){var Fe;const f=Qt(s,t),{actions:c,rows:d,clusters:y}=f,v=s.kind==="agent"?s.agent:null,h=v!==null&&v.memoryScope===null,a=v?v.name:Qe(t),[x,p]=o.useState("all"),[w,S]=o.useState(null),[j,$]=o.useState("read"),[T,W]=o.useState(""),[ne,fe]=o.useState("recent"),[Q,A]=o.useState(null),[K,L]=o.useState(F),[he,Ne]=o.useState(""),[Z,P]=o.useState(null),[I,ae]=o.useState(null),[Ce,R]=o.useState(null),[E,J]=o.useState(""),[V,z]=o.useState(""),[ge,re]=o.useState(""),[oe,le]=o.useState(!1),[ee,be]=o.useState(null);o.useEffect(()=>{l(f.agents)},[f.agents,l]),o.useEffect(()=>{!v&&!f.loading&&i(d.length)},[v,f.loading,d.length,i]);const G=o.useMemo(()=>f.archived.map(r=>({name:r,slug:Xe(r),path:`${f.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})),[f.archived,f.dir]),ie=x!=="ask"&&x!=="clusters",b=o.useMemo(()=>{if(x==="archived"){const r=T.trim().toLowerCase();return G.filter(g=>!r||g.slug.toLowerCase().includes(r))}return ot(ue(d,x,T),ne)},[x,d,G,T,ne]),m=o.useMemo(()=>d.find(r=>r.name===w)??G.find(r=>r.name===w)??null,[d,G,w]),k=m!==null&&!d.some(r=>r.name===m.name),C=o.useCallback(r=>{var g;return((g=y.find(N=>N.id===r))==null?void 0:g.dotClass)??"bg-rule"},[y]),Y=r=>{var g;return((g=y.find(N=>N.id===r))==null?void 0:g.name)??"Unclustered"},_=o.useCallback(r=>{S(r),$("read"),L(F),P(null),A(null)},[]),B=o.useCallback(r=>{p(r),W(""),A(null),L(F),$(g=>g==="edit"||g==="new"?"read":g)},[]);o.useEffect(()=>{var r;f.loading||!ie||j==="new"||m&&b.some(g=>g.name===m.name)||S(((r=b[0])==null?void 0:r.name)??null)},[f.loading,ie,j,m,b]);const ce=m&&!k?m.name:null,xt=m==null?void 0:m.mtimeMs;o.useEffect(()=>{if(!ce)return;let r=!0;return c.read(ce).then(g=>{r&&be({name:ce,text:g})}),()=>{r=!1}},[ce,xt,c.read]);const q=k?"":ee&&ee.name===ce?ee.text:null;o.useEffect(()=>{const r=g=>{var X,xe;if(g.key!=="/"||g.metaKey||g.ctrlKey||g.altKey)return;const N=g.target,H=((X=N==null?void 0:N.tagName)==null?void 0:X.toLowerCase())??"";H==="input"||H==="textarea"||N!=null&&N.isContentEditable||(xe=N==null?void 0:N.closest)!=null&&xe.call(N,".monaco-editor")||(g.preventDefault(),A("palette"))};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[]);const D=(r,g)=>ae({message:r,undo:g}),Se=(r="")=>{h||((x==="ask"||x==="clusters")&&p("all"),S(null),J(""),z(r),re(""),L(F),A(null),$("new"))},$e=r=>{B("all"),_(r)},mt=r=>{const g=d.find(N=>N.slug===r);g?_(g.name):M.error(`${r} is not in this scope`)},ut=()=>{if(q===null)return;const r=ke(q);z(r),re(r),$("edit")},pt=async()=>{if(!oe){le(!0);try{if(j==="new"){const r=await c.create(E,V);if(!r)return;const g=r.endsWith(".md")?r:`${r}.md`;B("all"),_(g),D(`Created ${Xe(g)}`)}else if(j==="edit"&&m){if(!await c.saveBody(m.name,V))return;$("read"),D(`Saved ${m.slug}`)}}finally{le(!1)}}},ft=()=>{$("read"),m||S(null)},Ie=async()=>{if(!m||q===null)return;const r=m;L({...F,state:"checking"});const g=await c.proposeFix(r.name);if(!g.ok){L(F);return}Ne(g.content),L({state:"proposed",diff:g.action==="update"?qt(q,g.content):[],summary:g.summary,action:g.action,reason:g.reason,fold:g.fold})},ht=async()=>{if(!m||q===null)return;const r=m;if(K.action==="delete"){if(!await c.archive(r.name))return;L(F),D(`Archived ${r.slug}`,()=>{c.restore(r.name)})}else if(K.action==="keep"){if(!await c.verify(r.name))return;L(F),D(`Marked ${r.slug} verified`)}else if(K.action==="fold"){if(!K.fold)return;const{target:g,anchor:N,insert:H}=K.fold,X=`Fold memory ${r.slug} into ${g}.
20
+ Insert after the line: ${N||"(append at end)"}
21
+ ---
22
+ ${H}
23
+ ---
24
+ Tread lightly: add only these lines, do not restructure the doc. Once committed, archive the memory ${r.slug} from the Memory page.
25
+ Memory file: ${r.path}`,xe=await window.api.clipboard.writeText(X);if(!xe.ok){M.error(`Copy failed: ${xe.error??"unknown error"}`);return}L(F),D("Fold copied — paste it into a New Epic")}else{const g=ke(q);if(!await c.saveBody(r.name,ke(he)))return;L(F),P(r.slug),D(`Applied fix to ${r.slug}`,()=>{c.saveBody(r.name,g)})}},gt=async()=>{if(!m)return;const r=m;await c.verify(r.name)&&D(`Marked ${r.slug} verified`)},_e=async()=>{if(!m)return;const r=m;A(null),await c.archive(r.name)&&D(`Archived ${r.slug}`,()=>{c.restore(r.name)})},bt=async()=>{if(!m)return;const r=m;await c.restore(r.name)&&D(`Restored ${r.slug}`)},yt=async()=>{if(!m)return;const r=m;A(null);const g=await c.remove(r.name);if(!g)return;const N=r.inLinks.length;D(`Deleted ${r.slug}${N>0?` · ${N} inbound links now broken`:""}`,()=>{g()})},vt=async()=>{if(!m)return;const r=await window.api.clipboard.writeText(m.path);r.ok?D("Path copied"):M.error(`Copy failed: ${r.error??"unknown error"}`)},jt=()=>{m&&window.api.shell.open({as:"revealPath",path:m.path})},kt=async r=>{if(!m)return;const g=m;await c.removeLink(g.name,r)&&D(`Dead link removed from ${g.slug}`)},wt=async r=>{if(!m)return;const g=m;try{const N=await c.read(g.name);if(N===null)return;const H=ke(N),X=Cs(H,r.from,r.to);if(X===H){M.error(`${r.from} is not referenced in backticks in ${g.slug}`),await c.refresh();return}if(!await c.saveBody(g.name,X))return;D(`Updated ${r.from} → ${r.to} in ${g.slug}`,()=>{c.saveBody(g.name,H)})}catch(N){M.error(`Path update failed: ${N instanceof Error?N.message:String(N)}`)}},Nt=()=>{m&&(R(m.slug),B("ask"))},Ct=r=>{var g;return r?((g=d.find(N=>N.slug===r))==null?void 0:g.name)??`${r}.md`:void 0},St=o.useMemo(()=>Yt(d),[d]),$t=o.useMemo(()=>{const r={};for(const g of d)g.clusterId&&(r[g.clusterId]=(r[g.clusterId]??0)+1);return r},[d]),Oe=o.useMemo(()=>d.filter(r=>r.clusterId===null).length,[d]),Mt=o.useMemo(()=>new Set(d.map(r=>r.slug)),[d]),Et=x.startsWith("cluster:")?x==="cluster:unclustered"?"Unclustered":((Fe=y.find(r=>r.id===x.slice(8)))==null?void 0:Fe.name)??"Cluster":{all:"All memories",stale:"Stale",broken:"Broken references",recent:"Changed this week",unindexed:"Not in index",archived:"Archived"}[x]??"All memories";let de=null;b.length===0&&(h?de={title:`${a} 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"})}:T.trim()?de={title:`No memories match “${T}”`,body:"Filter checks names and descriptions in this view.",action:"Clear filter",onAction:()=>W("")}:d.length===0&&x==="all"?de={title:`${a} has no memories yet`,body:"They appear when this subagent saves one, or add one now.",action:"+ New memory",onAction:()=>Se(Pe)}:de={title:"All clear",body:x==="stale"?"Nothing is stale in this scope.":"Nothing in this view.",action:"Back to all memories",onAction:()=>B("all")});const At=!f.autoMemoryEnabled,Lt=Pt.memory;return e.jsxs("div",{"data-testid":"mx-shell",className:"relative h-full flex flex-col bg-bg text-fg leading-[normal]",children:[e.jsxs("div",{className:"relative shrink-0 flex items-center gap-3 px-6 py-4 border-b border-rule-structural",children:[e.jsxs("div",{className:"flex items-baseline gap-3 pt-1",children:[e.jsx("span",{className:"text-[11px] tracking-[.08em] font-medium text-fg-dim",children:"CONFIGURE"}),e.jsx("span",{className:"font-serif text-[28px] leading-none",children:"Memory"}),e.jsx("span",{className:"text-xs text-fg-dim",children:"Claude Code's own memory files · stored on this machine"})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("button",{type:"button","data-testid":"mx-search-trigger",onClick:()=>A("palette"),className:"flex items-center gap-2 h-[30px] px-2.5 border border-rule-structural rounded-md bg-bg-elev w-[300px] text-xs text-fg-dim hover:border-fg-faint",children:[e.jsx("span",{children:"Search all memories, or ask a question…"}),e.jsx("span",{className:"flex-1"}),e.jsx("span",{className:"font-mono text-[10px] px-[5px] py-px border border-rule-structural rounded-[3px] text-fg-dim",children:"/"})]}),e.jsx("button",{type:"button","data-testid":"mx-learn",onClick:()=>A(r=>r==="learn"?null:"learn"),className:`text-[11px] tracking-[.08em] font-semibold px-1 py-1.5 hover:text-fg ${Q==="learn"?"text-fg":"text-accent"}`,children:"LEARN"}),Q==="learn"&&e.jsxs("div",{"data-testid":"mx-learn-popover",className:`absolute right-5 top-[58px] w-[360px] ${U.dialog} bg-bg-hi border border-rule-structural rounded-lg shadow-2xl p-4 flex flex-col gap-2.5 text-[13px] leading-[1.55] text-fg`,children:[e.jsx("span",{className:"font-serif text-[17px]",children:"How memory works"}),e.jsx("span",{children:Lt.intro}),e.jsx("div",{className:"flex justify-end",children:e.jsx("button",{type:"button","data-testid":"mx-learn-close",onClick:()=>A(null),className:"text-xs font-medium h-7 px-3 rounded-[5px] bg-fg text-bg",children:"Got it"})})]})]}),At&&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 flex-1 min-h-0",children:[e.jsx(Jt,{scope:s,agents:f.agents,agentCounts:f.agentCounts,workspaceName:Qe(t),workspacePath:t??"",workspaceCount:v?u:d.length,onScope:n,view:x,onView:B,counts:St,clusters:y,clusterCounts:$t,unclusteredCount:Oe,archivedCount:f.archived.length,index:f.index}),e.jsxs("main",{className:"flex-1 min-w-0 min-h-0 flex",children:[x==="ask"&&e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx(bs,{rows:d,context:Ce,onClearContext:()=>R(null),onAsk:(r,g)=>c.ask(r,Ct(g)),onOpen:$e,onReverify:()=>B("stale"),onDraft:r=>Se(r)})}),x==="clusters"&&e.jsx(ys,{clusters:y,rows:d,generatedAt:f.clustersMeta.generatedAt,running:f.clustersMeta.running,unclusteredCount:Oe,available:!v,onRegenerate:()=>{c.regenerateClusters()},onOpenCluster:r=>B(`cluster:${r}`),onOpen:$e}),ie&&e.jsxs("div",{className:"flex-1 min-w-0 min-h-0 grid grid-cols-[316px_minmax(0,1fr)_236px]",children:[e.jsx(ns,{title:Et,rows:b,clusterDot:C,selected:w,onSelect:_,query:T,onQuery:W,sort:ne,onSort:fe,onNew:()=>Se(Pe),empty:de}),e.jsx("div",{className:"flex flex-col min-w-0 min-h-0",children:j==="edit"||j==="new"?e.jsx(ze,{mode:j,name:(m==null?void 0:m.slug)??null,title:E,onTitle:J,body:V,onBody:z,onSave:()=>{pt()},onCancel:ft,saving:oe,dirty:j==="new"?E.trim()!==""||V!==Pe:V!==ge}):m?e.jsx(ds,{row:m,content:q,clusterName:Y(m.clusterId),clusterDot:C(m.clusterId),archived:k,mode:j,onMode:$,onEdit:ut,onCopyPath:()=>{vt()},onReveal:jt,onArchive:()=>{_e()},onRestore:()=>{bt()},onAskDelete:()=>A("delete"),fix:K,appliedStill:Z===m.slug&&m.stale,onFix:()=>{Ie()},onApplyFix:()=>{ht()},onDiscardFix:()=>L(F),onVerify:()=>{gt()}}):e.jsx(ze,{mode:"none",name:null,title:"",onTitle:J,body:"",onBody:z,onSave:()=>{},onCancel:()=>{},saving:!1,dirty:!1})}),e.jsx(us,{row:k||j==="new"?null:m,known:Mt,onOpen:mt,onRemoveLink:r=>{kt(r)},onUpdatePath:r=>{wt(r)},onReviewPath:()=>{Ie()},onAskAbout:Nt})]})]})]}),e.jsx(vs,{open:Q==="palette",rows:d,clusterDot:C,onPick:$e,onAsk:()=>{R(null),B("ask")},onClose:()=>A(null)}),e.jsx(js,{open:Q==="delete"&&m!==null,name:(m==null?void 0:m.slug)??"",inbound:(m==null?void 0:m.inLinks.length)??0,onArchive:()=>{_e()},onCancel:()=>A(null),onConfirm:()=>{yt()}}),e.jsx(ws,{message:(I==null?void 0:I.message)??null,onUndo:I!=null&&I.undo?()=>{const r=I.undo;ae(null),r==null||r()}:void 0,onClose:()=>ae(null)})]})}function Es(){const s=et(),t=tt();return s?e.jsx($s,{cwd:(t==null?void 0:t.cwd)??null}):e.jsx(we,{title:"loading…"})}const As=o.memo(Es);function Ls({cwd:s}){const[t,n]=o.useState(!1),[l,u]=o.useState(!1),[i,f]=o.useState(!1),[c,d]=o.useState(!1);o.useEffect(()=>{var x,p;let a=!1;return n(!1),Promise.resolve((p=(x=window.api.promptSessions)==null?void 0:x.getWorktreeDisabled)==null?void 0:p.call(x,{cwd:s})).then(w=>{a||(u((w==null?void 0:w.disabled)??!1),f((w==null?void 0:w.disabled)??!1),n(!0))},()=>{a||n(!0)}),()=>{a=!0}},[s]);const y=t&&i!==l,v=()=>{var a,x;d(!0),Promise.resolve((x=(a=window.api.promptSessions)==null?void 0:a.setWorktreeDisabled)==null?void 0:x.call(a,{cwd:s,disabled:i})).then(p=>{u((p==null?void 0:p.disabled)??i),f((p==null?void 0:p.disabled)??i)}).catch(p=>M.error(p instanceof Error?p.message:String(p))).finally(()=>d(!1))},h=()=>f(l);return e.jsxs("div",{"data-testid":"settings-epic-isolation",className:"border-b border-line bg-bg-elev px-3 py-2.5 text-[11.5px] leading-snug",children:[e.jsxs("label",{className:"flex items-start gap-2",children:[e.jsx("input",{type:"checkbox",checked:i,disabled:!t||c,onChange:a=>f(a.target.checked),"data-testid":"settings-epic-isolation-checkbox",className:"mt-0.5"}),e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-fg",children:"Disable Epic worktree isolation for this project"}),e.jsxs("span",{className:"block text-fg-dim",children:["Off by default — each active Epic runs in its own isolated ",e.jsx("code",{children:"git worktree"})," (branch"," ",e.jsx("code",{children:"sm-epic/<id>"}),"), merged back to main at an explicit checkpoint. Turning this on makes every new Epic in this project run directly in the shared working tree instead, same as before this feature existed."]})]})]}),y&&e.jsx(st,{dirty:y,busy:c,onSave:v,onRevert:h})]})}const dt=[{key:"memory",label:"Memory"},{key:"claude-md",label:"CLAUDE.md"},{key:"settings",label:"Settings"},{key:"mcp",label:"MCP"},{key:"skills",label:"Skills"}],Ze=[{key:"project",label:"Project"},{key:"local",label:"Local"}],Ds=s=>dt.some(t=>t.key===s),Rs=s=>`${s}/session-manager-operations/prompt-sessions/epic-worktree-config.json`,Ts={project:{title:"Project instructions",body:"This is the real <project>/CLAUDE.md on disk, normally checked into git. The claude CLI loads it into every session started in this project, for anyone who clones it."},local:{title:"Local instructions",body:"This is the real <project>/CLAUDE.local.md on disk: your own notes for this project on this machine, kept out of git. The claude CLI loads it alongside CLAUDE.md."}},Ps="changed on disk since it was loaded. Revert reloads it",Je=s=>s instanceof Error?s.message:String(s);function Is(s){const[t,n]=o.useState(null);return o.useEffect(()=>{if(!s)return;let l=!0;return Promise.resolve().then(()=>window.api.memory.list({workspace:nt(s),cwd:s})).then(u=>{l&&u.dir&&n({cwd:s,dir:u.dir})}).catch(()=>{}),()=>{l=!1}},[s]),t&&t.cwd===s?t.dir:null}function _s({path:s,scope:t}){const n=te(x=>x.files[s]),l=te(x=>x.loadText),u=te(x=>x.setDraft),i=te(x=>x.saveText),f=te(x=>x.watchFile),c=te(x=>x.unwatchFile),[d,y]=o.useState(null);o.useEffect(()=>(l(s,!0).catch(x=>M.error(`Couldn't read ${s}: ${Je(x)}`)),f(s),()=>{c(s)}),[s,l,f,c]);const v=o.useCallback(async()=>{y(null);const x=await i(s);x.ok||y(x.error==="conflict"?Ps:x.error??"save failed")},[s,i]),h=o.useCallback(()=>{y(null),l(s).catch(x=>M.error(`Couldn't read ${s}: ${Je(x)}`))},[s,l]);if(!n)return e.jsx(we,{title:"loading…"});const a=Ts[t];return e.jsxs("div",{"data-testid":"project-claude-md",className:"flex flex-col h-full min-h-0",children:[e.jsxs("div",{className:"shrink-0 border-b border-line bg-bg-elev px-3 py-2 text-[11.5px] leading-snug",children:[e.jsx("span",{className:"font-semibold text-fg",children:a.title}),e.jsx("span",{className:"mx-1.5 text-fg-faint",children:"·"}),e.jsx("span",{className:"text-fg-dim",children:a.body})]}),n.loadError&&e.jsx("div",{role:"alert",className:"shrink-0 border-b border-line px-3 py-1.5 text-[11px] text-red-400",children:n.loadError}),e.jsx("div",{className:"flex-1 min-h-0",children:e.jsx(Bt,{path:s,value:n.draftRaw,defaultMode:"split",onChange:x=>{y(null),u(s,x)},onSave:()=>{v()}})}),e.jsx("div",{className:"shrink-0 border-t border-line",children:e.jsx(st,{dirty:n.dirty,busy:n.busy,parseError:d,lastSavedAt:n.lastSavedAt,leading:n.exists?null:e.jsx("span",{children:"file will be created on save"}),onSave:()=>{v()},onRevert:h})})]})}function Os({cwd:s,scope:t}){return e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsxs("div",{"data-testid":"project-claude-config-epic-isolation",className:"shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-line bg-bg-elev px-3 pt-2 pb-1.5 text-[11px] text-fg-dim",children:[e.jsx("span",{className:"font-semibold text-fg",children:"Epic isolation"}),e.jsx("span",{className:"truncate",children:"Session Manager's own setting for this project, not a settings.json key"}),e.jsx(me,{path:Rs(s)})]}),e.jsx(Ls,{cwd:s})]}),e.jsx("div",{className:"flex-1 min-h-0",children:e.jsx(Wt,{scope:t})})]})}function Fs(){var w;const s=et(),t=((w=tt())==null?void 0:w.cwd)??null,[n,l]=o.useState("memory"),[u,i]=o.useState("project"),[f,c]=o.useState("project"),[d,y]=o.useState(null),v=Is(t),h=o.useCallback(S=>{l(S),y(null)},[]);It("memory",S=>{Ds(S)&&h(S)});const a=o.useCallback(S=>y(S),[]),x=o.useCallback(()=>y(null),[]);if(!s)return e.jsx(we,{title:"loading…"});if(!t)return e.jsx(we,{title:"no active project",hint:"open a project tab to edit its CLAUDE.md, settings, MCP servers, skills and memory"});const p=_t.resolve(u,s,t);return e.jsxs("div",{className:"flex flex-col h-full min-h-0","data-testid":"project-claude-config",children:[e.jsxs("div",{"data-testid":"project-claude-config-toolbar",className:"shrink-0 flex items-center gap-3 min-w-0 px-3 py-1.5 border-b border-line",children:[e.jsx(Me,{options:dt,active:n,onChange:h}),n==="claude-md"&&e.jsx(Me,{options:Ze,active:u,onChange:i}),n==="settings"&&e.jsx(Me,{options:Ze,active:f,onChange:c}),n==="memory"&&v&&e.jsx(me,{path:v,note:"Open this project's memory folder"}),n==="claude-md"&&p&&e.jsx(me,{path:p}),n==="mcp"&&e.jsx(me,{path:`${t}/.mcp.json`,keyPath:["mcpServers"]}),n==="skills"&&e.jsx(me,{path:`${t}/.claude/skills`,note:`Open ${t}/.claude/skills/`})]}),e.jsxs("div",{className:"flex-1 min-h-0",children:[n==="memory"&&e.jsx(As,{}),n==="claude-md"&&p&&e.jsx(_s,{path:p,scope:u},p),n==="settings"&&e.jsx(Os,{cwd:t,scope:f}),n==="mcp"&&e.jsx(Kt,{scope:"project",onAdd:a}),n==="skills"&&e.jsx(Vt,{scope:"project"})]}),e.jsx(Ot,{open:d!==null,onClose:x,title:"Add MCP server",keyVals:[],children:d&&e.jsx(Ft,{scope:d.scope,cwd:d.cwd})})]})}const tn=o.memo(Fs);export{tn as ProjectClaudeConfig};
@@ -1 +1 @@
1
- import{ad as P,bh as M,aO as x,ay as s,a7 as R,B as G,c as T}from"./index-CgSMvkqr.js";import{a as E,C as _,c as j,b as B}from"./Library-DlUH_fFF.js";const O=e=>`${e}/.claude/session-manager/provenance.json`;function I(e){if(!e||typeof e!="object")return{};const t={};for(const[n,o]of Object.entries(e))(o==="anthropic"||o==="community"||o==="local")&&(t[n]=o);return t}const D=P((e,t)=>({overrides:{},loaded:!1,loading:!1,home:null,load:async n=>{const o=t();if(!(o.home===n&&(o.loaded||o.loading))){e({home:n,loading:!0});try{const a=await window.api.config.readJson(O(n)),d=a.exists?I(a.data):{};e(h=>({overrides:{...d,...h.overrides},loaded:!0,loading:!1}))}catch{e({loaded:!0,loading:!1})}}},setOverride:async(n,o)=>{const a={...t().overrides};o===null?delete a[n]:a[n]=o,e({overrides:a});const d=t().home;if(d)try{await window.api.config.writeJson(O(d),a)}catch{}}})),i=e=>(e??"").toLowerCase().trim(),$=new Set,L=new Set;for(const e of B){const t=e.official?$:L;t.add(i(e.id)),t.add(i(e.name))}const K=new Set(j.filter(e=>e.official).flatMap(e=>[i(e.id),i(e.name)])),H=new Set(j.filter(e=>!e.official).flatMap(e=>[i(e.id),i(e.name)])),J=new Set(_.flatMap(e=>[i(e.id),i(e.name)])),V=new Set(E.flatMap(e=>[i(e.id),i(e.name)])),z=new Set(E.map(e=>e.command.trim())),U=new Set(["security-review","pr-comments","release-notes","add-dir","code-review","simplify"]),Z=/(@anthropic-ai\/|anthropic\.com|github\.com\/anthropics)/i,q=/(^|\s)(npx|uvx|pipx|bunx|mcp-remote|deno\s+run|docker\s+run)(\s|$)/i;function F(e){return[e.command,...e.args??[],e.url,e.repository,e.homepage].filter(Boolean).join(" ").toLowerCase()}const l=e=>({provenance:"anthropic",reason:e}),C=e=>({provenance:"community",reason:e});function Q(e,t,n){switch(e){case"mcp":return $.has(t)?l("official MCP server (catalog)"):L.has(t)?C("third-party server (catalog)"):null;case"skill":case"command":return K.has(t)?l("official Anthropic skill (catalog)"):H.has(t)?C("third-party skill (catalog)"):null;case"plugin":return null;case"subagent":return J.has(t)?l("bundled Anthropic subagent (catalog)"):null;case"hook":return V.has(t)||n&&z.has(n.trim())?l("bundled hook (catalog)"):null}}function W(e,t){return e.repository?"has a source repository":e.homepage?"has a homepage":e.url?"remote endpoint":q.test(t)?"installed from a package registry":null}function X(e){const t=i(e.name),n=F(e),o=Q(e.type,t,e.command);if(o)return o;if((e.type==="command"||e.type==="skill")&&U.has(t))return l("built-in Claude Code command");if(Z.test(n))return l("Anthropic package or repo");const a=W(e,n);return a?C(a):{provenance:"local",reason:"no external source — assumed self-created"}}function Y(e,t,n){return`${e}:${t??"-"}:${n}`}const c={anthropic:"Anthropic",community:"Community",local:"Local"},N={anthropic:"accent",community:"warn",local:"dim"},ee=["anthropic","community","local"];function oe({input:e,scope:t,interactive:n=!0,className:o=""}){const a=M(),{overrides:d,load:h,setOverride:k}=D(),[b,m]=x.useState(!1),v=x.useRef(null);x.useEffect(()=>{a&&h(a)},[a,h]),x.useEffect(()=>{if(!b)return;const r=w=>{v.current&&!v.current.contains(w.target)&&m(!1)},g=w=>{w.key==="Escape"&&m(!1)};return window.addEventListener("mousedown",r),window.addEventListener("keydown",g),()=>{window.removeEventListener("mousedown",r),window.removeEventListener("keydown",g)}},[b]);const y=Y(e.type,t??null,e.name),u=X(e),p=d[y],f=p??u.provenance,S=p?`Origin manually set to ${c[f]} — auto-detected ${c[u.provenance]} (${u.reason})`:`Auto-detected ${c[f]}: ${u.reason}`,A=s.jsxs(T,{tone:N[f],title:S,className:`${n?"cursor-pointer hover:brightness-125":""} ${o}`,children:[c[f],p&&s.jsx("span",{className:"w-1 h-1 rounded-full bg-current opacity-70","aria-hidden":!0})]});return n?s.jsxs("span",{ref:v,className:"relative inline-flex",children:[s.jsx("button",{type:"button",onClick:r=>{r.stopPropagation(),m(g=>!g)},className:"inline-flex","aria-label":`Origin: ${c[f]}. Click to change.`,children:A}),b&&s.jsxs("span",{className:`absolute ${R.dialog} top-full right-0 mt-1 min-w-[7.5rem] rounded-md border border-line bg-bg-elev shadow-lg py-1 text-left`,onClick:r=>r.stopPropagation(),children:[s.jsx("span",{className:"block px-2 pb-1 text-[10px] uppercase tracking-wide text-fg-faint",children:"Mark origin as"}),ee.map(r=>s.jsxs("button",{type:"button",onClick:()=>{k(y,r),m(!1)},className:`flex w-full items-center gap-2 px-2 py-1 text-[12px] hover:bg-bg-hi/60 ${f===r?"text-fg":"text-fg-dim"}`,children:[s.jsx("span",{className:`w-2 h-2 rounded-full border ${G[N[r]]}`,"aria-hidden":!0}),c[r],p===r&&s.jsx("span",{className:"ml-auto text-[10px] text-fg-faint",children:"set"})]},r)),s.jsx("div",{className:"my-1 border-t border-line"}),s.jsxs("button",{type:"button",onClick:()=>{k(y,null),m(!1)},disabled:!p,className:"flex w-full items-center gap-2 px-2 py-1 text-[12px] text-fg-dim hover:bg-bg-hi/60 disabled:opacity-40 disabled:hover:bg-transparent",title:`Revert to auto-detection (${c[u.provenance]})`,children:["Auto-detect",s.jsx("span",{className:"ml-auto text-[10px] text-fg-faint",children:c[u.provenance]})]})]})]}):A}export{c as P,oe as a,X as c,Y as p,D as u};
1
+ import{ad as P,bh as M,aO as x,ay as s,a7 as R,B as G,c as T}from"./index-iQ6pdyuS.js";import{a as E,C as _,c as j,b as B}from"./Library-C_ibFiOx.js";const O=e=>`${e}/.claude/session-manager/provenance.json`;function I(e){if(!e||typeof e!="object")return{};const t={};for(const[n,o]of Object.entries(e))(o==="anthropic"||o==="community"||o==="local")&&(t[n]=o);return t}const D=P((e,t)=>({overrides:{},loaded:!1,loading:!1,home:null,load:async n=>{const o=t();if(!(o.home===n&&(o.loaded||o.loading))){e({home:n,loading:!0});try{const a=await window.api.config.readJson(O(n)),d=a.exists?I(a.data):{};e(h=>({overrides:{...d,...h.overrides},loaded:!0,loading:!1}))}catch{e({loaded:!0,loading:!1})}}},setOverride:async(n,o)=>{const a={...t().overrides};o===null?delete a[n]:a[n]=o,e({overrides:a});const d=t().home;if(d)try{await window.api.config.writeJson(O(d),a)}catch{}}})),i=e=>(e??"").toLowerCase().trim(),$=new Set,L=new Set;for(const e of B){const t=e.official?$:L;t.add(i(e.id)),t.add(i(e.name))}const K=new Set(j.filter(e=>e.official).flatMap(e=>[i(e.id),i(e.name)])),H=new Set(j.filter(e=>!e.official).flatMap(e=>[i(e.id),i(e.name)])),J=new Set(_.flatMap(e=>[i(e.id),i(e.name)])),V=new Set(E.flatMap(e=>[i(e.id),i(e.name)])),z=new Set(E.map(e=>e.command.trim())),U=new Set(["security-review","pr-comments","release-notes","add-dir","code-review","simplify"]),Z=/(@anthropic-ai\/|anthropic\.com|github\.com\/anthropics)/i,q=/(^|\s)(npx|uvx|pipx|bunx|mcp-remote|deno\s+run|docker\s+run)(\s|$)/i;function F(e){return[e.command,...e.args??[],e.url,e.repository,e.homepage].filter(Boolean).join(" ").toLowerCase()}const l=e=>({provenance:"anthropic",reason:e}),C=e=>({provenance:"community",reason:e});function Q(e,t,n){switch(e){case"mcp":return $.has(t)?l("official MCP server (catalog)"):L.has(t)?C("third-party server (catalog)"):null;case"skill":case"command":return K.has(t)?l("official Anthropic skill (catalog)"):H.has(t)?C("third-party skill (catalog)"):null;case"plugin":return null;case"subagent":return J.has(t)?l("bundled Anthropic subagent (catalog)"):null;case"hook":return V.has(t)||n&&z.has(n.trim())?l("bundled hook (catalog)"):null}}function W(e,t){return e.repository?"has a source repository":e.homepage?"has a homepage":e.url?"remote endpoint":q.test(t)?"installed from a package registry":null}function X(e){const t=i(e.name),n=F(e),o=Q(e.type,t,e.command);if(o)return o;if((e.type==="command"||e.type==="skill")&&U.has(t))return l("built-in Claude Code command");if(Z.test(n))return l("Anthropic package or repo");const a=W(e,n);return a?C(a):{provenance:"local",reason:"no external source — assumed self-created"}}function Y(e,t,n){return`${e}:${t??"-"}:${n}`}const c={anthropic:"Anthropic",community:"Community",local:"Local"},N={anthropic:"accent",community:"warn",local:"dim"},ee=["anthropic","community","local"];function oe({input:e,scope:t,interactive:n=!0,className:o=""}){const a=M(),{overrides:d,load:h,setOverride:k}=D(),[b,m]=x.useState(!1),v=x.useRef(null);x.useEffect(()=>{a&&h(a)},[a,h]),x.useEffect(()=>{if(!b)return;const r=w=>{v.current&&!v.current.contains(w.target)&&m(!1)},g=w=>{w.key==="Escape"&&m(!1)};return window.addEventListener("mousedown",r),window.addEventListener("keydown",g),()=>{window.removeEventListener("mousedown",r),window.removeEventListener("keydown",g)}},[b]);const y=Y(e.type,t??null,e.name),u=X(e),p=d[y],f=p??u.provenance,S=p?`Origin manually set to ${c[f]} — auto-detected ${c[u.provenance]} (${u.reason})`:`Auto-detected ${c[f]}: ${u.reason}`,A=s.jsxs(T,{tone:N[f],title:S,className:`${n?"cursor-pointer hover:brightness-125":""} ${o}`,children:[c[f],p&&s.jsx("span",{className:"w-1 h-1 rounded-full bg-current opacity-70","aria-hidden":!0})]});return n?s.jsxs("span",{ref:v,className:"relative inline-flex",children:[s.jsx("button",{type:"button",onClick:r=>{r.stopPropagation(),m(g=>!g)},className:"inline-flex","aria-label":`Origin: ${c[f]}. Click to change.`,children:A}),b&&s.jsxs("span",{className:`absolute ${R.dialog} top-full right-0 mt-1 min-w-[7.5rem] rounded-md border border-line bg-bg-elev shadow-lg py-1 text-left`,onClick:r=>r.stopPropagation(),children:[s.jsx("span",{className:"block px-2 pb-1 text-[10px] uppercase tracking-wide text-fg-faint",children:"Mark origin as"}),ee.map(r=>s.jsxs("button",{type:"button",onClick:()=>{k(y,r),m(!1)},className:`flex w-full items-center gap-2 px-2 py-1 text-[12px] hover:bg-bg-hi/60 ${f===r?"text-fg":"text-fg-dim"}`,children:[s.jsx("span",{className:`w-2 h-2 rounded-full border ${G[N[r]]}`,"aria-hidden":!0}),c[r],p===r&&s.jsx("span",{className:"ml-auto text-[10px] text-fg-faint",children:"set"})]},r)),s.jsx("div",{className:"my-1 border-t border-line"}),s.jsxs("button",{type:"button",onClick:()=>{k(y,null),m(!1)},disabled:!p,className:"flex w-full items-center gap-2 px-2 py-1 text-[12px] text-fg-dim hover:bg-bg-hi/60 disabled:opacity-40 disabled:hover:bg-transparent",title:`Revert to auto-detection (${c[u.provenance]})`,children:["Auto-detect",s.jsx("span",{className:"ml-auto text-[10px] text-fg-faint",children:c[u.provenance]})]})]})]}):A}export{c as P,oe as a,X as c,Y as p,D as u};
@@ -1,4 +1,4 @@
1
- import{aV as Ce,aH as ie,am as Ee,b2 as xs,ar as Se,al as ue,ap as te,b7 as H,bo as Le,bn as pe,br as _t,aO as f,aj as xe,bx as ms,ay as t,d as Ve,I as me,L as bt,q as bs,K as ge,v as ws,W as vs,f as js,Y as Ns,b1 as ys,bl as st,be as ks,aZ as Ss,ag as wt,aF as Tt,bw as $e,S as Fe,aM as _e,b as nt,b0 as at,V as Ot,z as Lt,p as Ft,r as $s,n as rt,N as it,O as Cs,h as re,i as B,an as qt,bp as Ps,aN as Ds,y as As,aQ as Bt,bA as Ht,_ as Rs,aT as Ue,aI as vt,bf as jt,m as ye,G as Nt,aX as yt,l as Ms,b5 as Is,a5 as Es,w as Gt,X as _s,bs as kt,a$ as Ts}from"./index-CgSMvkqr.js";import{f as Os,a as Ls,s as Fs}from"./historyTotals-07_oiLDE.js";import"./monaco-editor-BsIlgG7c.js";function qs(e){const s=new Map(e.map(i=>[i.slug,i])),n=new Map,a=new Set,d=[];function l(i){n.set(i,1),d.push(i);const r=s.get(i);for(const o of(r==null?void 0:r.dependsOn)??[]){if(!s.has(o))continue;const c=n.get(o);if(c===1){const p=d.indexOf(o);for(let u=p;u<d.length;u++)a.add(d[u])}else c===void 0&&l(o)}d.pop(),n.set(i,2)}for(const i of e)n.has(i.slug)||l(i.slug);return a}function Bs(e,s){return(e.dependsOn??[]).map(n=>{const a=s.get(n);return a?{slug:n,status:a.status,missing:!1,needsReview:a.status==="needs_review"}:{slug:n,status:null,missing:!0,needsReview:!1}})}function Hs(e,s,n){const a=new Set(e.map(c=>c.slug)),d=new Set;for(const c of e)for(const p of c.dependsOn??[])a.has(p)&&d.add(p);const l=new Map,i=[];for(const c of e){const p=n.has(c.slug)?void 0:(c.dependsOn??[]).find(u=>a.has(u)&&!n.has(u));p?(l.has(p)||l.set(p,[]),l.get(p).push(c)):i.push(c)}const r=(c,p)=>c.slug.localeCompare(p.slug);i.sort(r);for(const c of l.values())c.sort(r);function o(c,p,u){const h=Bs(c,s),x=n.has(c.slug);u.add(c.slug);const m=x?[]:(l.get(c.slug)??[]).filter(w=>!u.has(w.slug)).map(w=>o(w,p+1,u));return u.delete(c.slug),{row:c,depth:p,children:m,blockers:h,blocked:h.some(w=>!w.missing&&w.status!=="completed"),hasNeedsReviewBlocker:h.some(w=>w.needsReview),hasMissingDep:h.some(w=>w.missing),cycle:x,parallelEligible:(c.dependsOn??[]).length===0&&!d.has(c.slug)}}return i.map(c=>o(c,0,new Set))}function Wt(e,s,n){const a=new Map((n??e).map(c=>[c.slug,c])),d=qs(e),l=[],i=new Map,r=new Map;for(const c of e){const p=Ce(c,s),u=p.epicId??"__none__";i.has(u)||(l.push(u),i.set(u,[]),r.set(u,{epicId:p.epicId,label:p.known&&p.label?p.label:p.epicId?`Epic ${p.epicId.slice(0,12)}…`:"No Epic",known:p.known})),i.get(u).push(c)}const o=l.map(c=>{const p=r.get(c),u=i.get(c),h=Hs(u,a,d),x={};for(const m of u){const w=m.status??"unknown";x[w]=(x[w]??0)+1}return{epicId:p.epicId,label:p.label,known:p.known,nodes:h,counts:x,total:u.length}});return o.sort((c,p)=>c.epicId===null?1:p.epicId===null?-1:c.known!==p.known?c.known?-1:1:c.label.localeCompare(p.label)),o}function qe(e){const s=[],n=a=>{s.push(a);for(const d of a.children)n(d)};for(const a of e)n(a);return s}function Je(e){return String(e??"").replace(/^\d+-/,"")}function Te(e){const s=new Set,n=new Map;for(const a of e){s.add(a.slug);const d=Je(a.slug),l=n.get(d);l?l.push(a.slug):n.set(d,[a.slug])}return e.map(a=>{const d=a.dependsOn;if(!d||d.length===0)return a;let l=!1;const i=d.map(r=>{if(s.has(r))return r;const o=n.get(Je(r));return o&&o.length===1?(l=!0,o[0]):r});return l?{...a,dependsOn:i}:a})}const Gs=15e4,Xe=e=>e==="completed"||e==="skipped",ke=e=>e==="running"||e==="investigating",Vt=e=>e==="failed"||e==="needs_review"||e==="quarantined",Ws=e=>e==="failed"||e==="needs_review"||e==="quarantined";function Ut(e){if(e<=5e3)return"~now";if(e<6e4)return`~${Math.round(e/1e3)}s`;const s=Math.round(e/6e4);return s<60?`~${s}m`:`~${Math.floor(s/60)}h${String(s%60).padStart(2,"0")}m`}function zt(e,s){const n=e.estimateMinutes?e.estimateMinutes*6e4:null;return n?`${Math.min(99,Math.floor(s/n*100))}%`:Ee(s)}function Vs(e){let s=0,n=0;for(const a of e)if(a.status==="completed"&&a.startedAt&&a.finishedAt){const d=Date.parse(a.finishedAt)-Date.parse(a.startedAt);d>0&&(s+=d,n++)}return n===0?Gs:s/n}function Oe(e){const s=ie(e);return s===null?1/0:Number(s)}function Ze(e,s){const n=Oe(e.slug)-Oe(s.slug);return n!==0&&!Number.isNaN(n)?n:e.slug.localeCompare(s.slug)}function Us(e){let s=0;for(const n of e.statusHistory??[])n.to==="pending"&&n.from!==null&&s++;return s}function zs(e){return e.some(n=>ke(n.status))?"active":e.every(n=>Xe(n.status))?"done":e.filter(n=>n.status!=="quarantined").length===0?"draft":"queued"}function Qs(e,s,n,a){switch(e){case"done":return`${s.doneCount}/${s.rows.length} done`;case"running":return`${s.runningCount} running · ${n}`;case"held":return`${s.heldCount} held`;case"blocked":return`${s.blockedCount+a} blocked`;default:return`${n} ready`}}function Ys(e,s){return e._firstNum!==s._firstNum?e._firstNum<s._firstNum?-1:1:e._firstSlug.localeCompare(s._firstSlug)}function Ks(e,s){const n=new Map(e.map(l=>[l.row.slug,l.row.slug])),a=l=>{for(;n.get(l)!==l;)n.set(l,n.get(n.get(l))),l=n.get(l);return l};for(const l of e)for(const i of l.row.dependsOn??[])s.has(i)&&n.set(a(l.row.slug),a(i));const d=new Map;for(const l of e){const i=a(l.row.slug),r=d.get(i);r?r.push(l):d.set(i,[l])}return[...d.values()]}function Js(e,s){if(e.length>0&&e.every(n=>!!n.row.planId)){const n=new Map;for(const a of e){const d=n.get(a.row.planId);d?d.push(a):n.set(a.row.planId,[a])}return[...n.values()]}return Ks(e,s)}function Xs(e,s,n,a){const d=[],l=[e];for(a.add(e.row.slug);l.length>0;){const i=l.pop();d.push(i);for(const r of i.row.dependsOn??[])if(n.has(r)&&!a.has(r)){a.add(r);const o=s.get(r);o&&l.push(o)}}return d}function Zs(e,s){const n=new Map(e.map(r=>[r.row.slug,r])),a=new Set,d=[],l=e.filter(r=>Je(r.row.slug).startsWith("validate-")).sort((r,o)=>Ze({slug:r.row.slug},{slug:o.row.slug}));for(const r of l)a.has(r.row.slug)||d.push({nodes:Xs(r,n,s,a),validateSlug:r.row.slug});const i=e.filter(r=>!a.has(r.row.slug));if(i.length>0){const r=new Set(i.map(o=>o.row.slug));for(const o of Js(i,r))d.push({nodes:o,validateSlug:null})}return d}function en(e){return e.replace(/^validate[\s:-]*/i,"").trim()}function lt(e,s){if(e.length===0)return[];const n=Te(e),a=s.now??Date.now(),d=s.avgDurationMs??Vs(n),l=Math.max(1,s.concurrency??1),i=new Map(n.map(u=>[u.slug,u])),r=u=>u.status==="pending"&&(u.dependsOn??[]).every(h=>i.get(h)===void 0||i.get(h).status==="completed"),o=new Map;n.filter(r).sort(Ze).forEach((u,h)=>o.set(u.slug,h));const c=Wt(n,s.sessions,n),p=[];for(const u of c){const h=qe(u.nodes),x=new Set(h.map(S=>S.row.slug)),m=new Map(h.map(S=>[S.row.slug,S])),w=[];for(const S of Zs(h,x)){const y=S.nodes,O=new Set(y.map(j=>j.row.slug)),k=new Map,E=new Set,D=j=>{const $=m.get(j);return($.row.dependsOn??[]).filter(q=>O.has(q)&&!($.cycle&&m.get(q).cycle))},P=j=>{const $=k.get(j);if($!==void 0)return $;if(E.has(j))return 0;E.add(j);let q=0;for(const W of D(j))q=Math.max(q,P(W));return E.delete(j),k.set(j,q+1),q+1};for(const j of y)P(j.row.slug);const T=y.map(j=>{const $=j.row,q=($.dependsOn??[]).filter(W=>x.has(W));return{slug:$.slug,title:$.title,status:$.status,stage:k.get($.slug),prdNumber:ie($.slug),rowKind:"dep",rowTrailing:"",cycle:j.cycle,estimateMinutes:$.estimateMinutes??null,deps:q,crossEpicDeps:($.dependsOn??[]).filter(W=>!x.has(W)),blockers:j.blockers,job:$}});T.sort(Ze);const K=T.reduce((j,$)=>Math.max(j,$.stage),0),V=new Map;for(const j of T){const $=j.job,q=m.get(j.slug),W=$.status;let U;if(Xe(W)){const g=$.startedAt&&$.finishedAt?Date.parse($.finishedAt)-Date.parse($.startedAt):NaN;U={kind:"done",trailing:g>0?Ee(g):"",held:!1,blocked:!1}}else if(ke(W)){const g=$.startedAt?Math.max(0,a-Date.parse($.startedAt)):null;U={kind:"running",trailing:g===null?"":zt($,g),held:!1,blocked:!1}}else if(W==="failed")U={kind:"failed",trailing:"failed",held:!1,blocked:!1};else if(W==="needs_review")U={kind:"review",trailing:"review",held:!1,blocked:!1};else if(W==="quarantined")U={kind:"quarantined",trailing:"quarantined",held:!1,blocked:!1};else{const g=q.blockers.filter(v=>!v.missing&&v.status!=="completed");if(g.length>0){const v=g.some(C=>Ws(C.status)),A=g[0].slug;U={kind:"dep",trailing:`←${ie(A)??A}`,held:!v,blocked:v}}else if($.heldReason)U={kind:"gate",trailing:"gate",held:!0,blocked:!1};else{const v=Us($),A=o.get($.slug)??0;U=v>0?{kind:"retry",trailing:`${v} ${v===1?"retry":"retries"}`,held:!1,blocked:!1}:{kind:"eta",trailing:Ut(A*d/l),held:!1,blocked:!1}}}V.set(j.slug,U)}const z=[];for(let j=1;j<=K;j++){const $=T.filter(_=>_.stage===j),q=$.find(_=>{const Z=V.get(_.slug).kind;return _.status==="pending"&&(Z==="eta"||Z==="retry")});if(q){const _=V.get(q.slug);_.kind="next",_.trailing="next"}let W=0,U=0,g=0,v=0,A=0,C=0;for(const _ of $){const Z=V.get(_.slug);_.rowKind=Z.kind,_.rowTrailing=Z.trailing,Xe(_.status)?W++:ke(_.status)?U++:_.status==="pending"?(A++,Z.held&&g++,Z.blocked&&v++):Vt(_.status)&&C++}const M=W===$.length?"done":U>0?"running":v+C>0?"blocked":g>0?"held":"pending",L={n:j,rows:$,doneCount:W,runningCount:U,heldCount:g,blockedCount:v};z.push({...L,state:M,summary:Qs(M,L,A,C)})}let J=0;for(const j of T){const $=j.estimateMinutes?j.estimateMinutes*6e4:d;if(j.status==="pending")J+=$;else if(ke(j.status)){const q=j.job.startedAt?Math.max(0,a-Date.parse(j.job.startedAt)):0;J+=Math.max(0,$-q)}}const X=T.reduce((j,$)=>Math.min(j,Oe($.slug)),1/0),se=T.reduce((j,$)=>Math.max(j,Oe($.slug)),-1/0),Y=u.known?xs(u.label).title:u.label,R=S.validateSlug?T.find(j=>j.slug===S.validateSlug):void 0,F=R&&en(R.title)||Y;w.push({epicId:u.epicId,waveIndex:0,index:0,label:F,epicLabel:Y,validateSlug:S.validateSlug,width:z.reduce((j,$)=>Math.max(j,$.rows.length),0),status:zs(T),prdCount:T.length,stageCount:K,doneCount:z.reduce((j,$)=>j+$.doneCount,0),runningCount:z.reduce((j,$)=>j+$.runningCount,0),heldCount:z.reduce((j,$)=>j+$.heldCount,0),blockedCount:z.reduce((j,$)=>j+$.blockedCount,0),etaMs:J/l,stages:z,_firstNum:X,_lastNum:se,_firstSlug:T[0].slug})}w.sort(Ys),w.forEach((S,y)=>{S.waveIndex=y+1});const N=w.filter(S=>S.validateSlug===null);N.forEach((S,y)=>{N.length>1&&(S.label=`${S.label} · plan ${y+1}/${N.length}`)});for(const S of w)p.push(S)}return p.sort((u,h)=>{if(u._lastNum!==h._lastNum)return u._lastNum>h._lastNum?-1:1;const x=(u.epicId??"").localeCompare(h.epicId??"");return x!==0?x:u.waveIndex-h.waveIndex}),p.map(({_firstNum:u,_lastNum:h,_firstSlug:x,...m},w)=>({...m,index:w+1}))}function tn(e,s=Date.now()){const n=Te(e),a=new Map(n.map(x=>[x.slug,x])),d=new Date(s).toDateString();let l=0,i=0,r=0,o=0,c=0,p=0,u=0;for(const x of n)x.status==="pending"?(i++,(x.dependsOn??[]).every(w=>a.get(w)===void 0||a.get(w).status==="completed")&&l++):ke(x.status)?u++:x.status==="failed"?r++:x.status==="needs_review"?o++:x.status==="quarantined"?c++:x.status==="completed"&&x.finishedAt&&new Date(Date.parse(x.finishedAt)).toDateString()===d&&p++;let h=null;if(r+o+c>0){for(const x of lt(n,{sessions:{},now:s}))for(const m of x.stages)if(m.rows.some(w=>Vt(w.status))){(h===null||m.n<h)&&(h=m.n);break}}return{readyNow:l,totalQueued:i,heldByDeps:i-l,needsYou:r+o+c,needsYouStage:h,failedCount:r,needsReviewCount:o,doneToday:p,inFlight:u}}function sn(e){const s=new Map;for(const o of e.stages)for(const c of o.rows)s.set(c.slug,c);const n=o=>{var c;return((c=s.get(o))==null?void 0:c.cycle)===!0},a=new Map,d=new Set,l=(o,c)=>o.chain.length!==c.chain.length?o.chain.length>c.chain.length:o.est!==c.est?o.est>c.est:o.chain.join("\0")<c.chain.join("\0"),i=o=>{const c=a.get(o);if(c)return c;const p=s.get(o),u=p.estimateMinutes??0;if(d.has(o))return{chain:[o],est:u};d.add(o);let h=null;for(const m of p.deps){if(!s.has(m)||p.cycle&&n(m))continue;const w=i(m);(!h||l(w,h))&&(h=w)}d.delete(o);const x=h?{chain:[...h.chain,o],est:h.est+u}:{chain:[o],est:u};return a.set(o,x),x};let r=null;for(const o of s.keys()){const c=i(o);(!r||l(c,r))&&(r=c)}return r?r.chain:[]}const nn=300*6e4,an={five_hour:"5-hour",session:"5-hour",weekly_all:"weekly",weekly:"weekly"};function rn(e){return an[e]??e.replace(/_/g," ")}function Qt({snap:e,now:s,avgDurationMs:n,runningJobs:a}){const{config:d,jobs:l,paused:i,nextReset:r,utilization:o,utilizationWindow:c,effectiveConcurrency:p}=e;let u=0,h=0;for(const y of l)y.status==="pending"?u++:y.status==="completed"&&h++;const x=a.length,m=u+x,w=(p==null?void 0:p.cap)??5;if(x>0){const y=a.reduce((P,T)=>(P.startedAt??"")<(T.startedAt??"")?P:T),O=y.startedAt?s-Date.parse(y.startedAt):0,k=h+x,E=h+m,D=x>1?` · ${x}/${w} parallel`:"";return{kind:"running",line1:`Running ${k}/${E}${D} · ${Se(O)}`,line2:x===1?y.title:a.map(P=>P.title).join(", "),tooltip:a.map(P=>`${P.slug} (g${P.parallelGroup})`).join("; ")}}if(i){const y=i.resumeAt?Date.parse(i.resumeAt)-s:null;return{kind:"paused",line1:{rate_limit:"Paused — tokens exhausted",auth:"Paused — authentication failed",network:"Paused — network unreachable",reset_failure:"Paused — billing data unavailable",manual:"Paused — manual (you paused the queue)"}[i.reason]??`Paused — ${i.reason}`,line2:i.reason==="auth"?"Run `claude` in any terminal to refresh credentials, then Resume":y!==null&&y>0?`auto-resume ${ue(Date.parse(i.resumeAt))} (in ${te(y)})`:i.resumeAt?"resuming…":"no auto-resume scheduled",tooltip:i.resumeAt??"",action:{label:"Resume",onClick:()=>window.api.schedule.resume(),title:"Clear the pause and resume queue immediately"}}}if(m===0)return{kind:"idle",line1:"No work queued",line2:null};if((d.firePolicy??"when-available")==="manual")return{kind:"manual",line1:`Manual · ${u} pending`,line2:"click Fire next batch now to fire",action:{label:"Fire next batch now",onClick:()=>window.api.schedule.forceTick().then(H.fromOutcome).catch(()=>H.error("Failed to fire batch")),title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress."}};const S=d.utilizationThreshold??90;if(o==null)return{kind:"auto-soon",line1:`Auto · ${u} pending`,line2:"checking token availability…"};if(o>=S){const y=r?Date.parse(r)-s:null,O=c?rn(c):null,k=y===null||Number.isNaN(y)||y>nn,E=y&&y>0?`resets ${ue(Date.parse(r))} (in ${te(y)})`:null;let D;return k?D=`${O??"binding"} window — long hold${E?`, ${E}`:", reset time unknown"}`:D=E?`${O?`${O} window `:""}next ${E}`:"will fire when usage drops",{kind:"auto-throttled",line1:`Auto · throttled (util ${o.toFixed(0)}% ≥ ${S}%)`,line2:D}}return{kind:"auto-soon",line1:`Auto · ${u} pending · util ${o.toFixed(0)}%`,line2:"fires within 2 min (poll cycle)"}}const ln=15e3,on=new Set(["failed","needs_review","quarantined"]);function dn(e){for(let s=e.parentElement;s;s=s.parentElement){const n=getComputedStyle(s).overflowY;if(n==="auto"||n==="scroll")return s}return null}function St(){const s=Array.from(document.querySelectorAll("[data-job-row]")).find(a=>on.has(a.dataset.jobStatus??""));if(!s)return;const n=dn(s);n&&Ss(n,s,{block:"nearest",behavior:"smooth"})}function cn(e,s){var n;switch(e.kind){case"paused":return`paused: scheduler is paused (${e.reason??"manual"})`;case"launch-blocked":return`launch-blocked: ${e.agentType} jobs can't launch${(n=e.block)!=null&&n.kind?` (${e.block.kind})`:""}`;case"idle":return"idle: 0 pending";case"saturated":{const a=s!=null?`, oldest ${te(s)}`:"";return`saturated: ${e.totalSlots??"?"} slot(s) busy${a}`}case"blocked":{const a=e.blockedChains.length;return`blocked: ${e.pending} pending, ${e.dispatchable} dispatchable — ${a} chain${a===1?"":"s"} stuck behind a failed/skipped dependency`}case"stalled":return`stalled: no dispatch attempt in ${e.idleMs!=null?te(e.idleMs):"?"} with ${e.dispatchable} dispatchable`;case"running":default:return`running: ${e.runningCount} in flight, ${e.pending} pending`}}function un(e){const[s,n]=f.useState(null),a=st(),d=ks(),l=a&&d;return f.useEffect(()=>{if(!l)return;let i=!0,r=!1,o=!1;const c=()=>{r||(r=!0,window.api.schedule.queueHealth(e).then(u=>{r=!1,o=!1,i&&n(u)},u=>{r=!1,!o&&(o=!0,H.error(`Queue health refresh failed: ${u instanceof Error?u.message:String(u)}`))}))};c();const p=setInterval(c,ln);return()=>{i=!1,clearInterval(p)}},[e,l]),s}const pn={running:{dot:"bg-sage",text:"text-sage-dark"},paused:{dot:"bg-amber-500",text:"text-amber-600"},idle:{dot:"bg-fg-faint",text:"text-fg-faint"}};function fn(e,s,n){return e==="paused"||e==="launch-blocked"?"paused":e==="running"||e==="saturated"?"running":e?"idle":s?"paused":n>0?"running":"idle"}const ze="px-2.5 py-1.5 rounded border border-line text-[12.5px] font-medium text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap";function hn(e,s,n,a){var d;if(e==="agent"){const l=((d=a==null?void 0:a.cwd)==null?void 0:d.split("/").filter(Boolean).pop())||"another session",i=a!=null&&a.reason?` — "${a.reason}"`:"",r=s?new Date(s).getTime()-n:null,o=r==null?"":r>0?` — auto-resumes in ${te(r)}`:" — auto-resume pending";return`Paused by an agent in ${l}${i}${o}. Click Resume to restart now.`}if(e==="auth")return"Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume.";if(e==="rate_limit"){if(s){const l=new Date(s).getTime()-n;return l>0?`Paused for rate limit — resumes in ${te(l)}`:"Paused for rate limit — resume pending"}return"Paused for rate limit"}return e==="network"?"Paused: billing endpoint unreachable for 30+ min.":e==="manual"?"Scheduler paused manually — no new jobs start; running jobs continue. Click Resume to restart.":`Scheduler paused (${e})`}function gn({now:e}){const s=Le(p=>p.snapshot);if(!s)return null;const n=s.paused,a=Object.entries(s.launchBlocks??{}),d=Object.entries(s.launchMitigations??{}),l=(n==null?void 0:n.reason)==="auth"||(n==null?void 0:n.reason)==="network",i="flex items-start gap-3 border-b px-0 py-1.5 text-[12.5px]",r="bg-red-950/10 border-red-700/30 text-red-800",o="bg-amber-400/10 border-amber-600/30 text-amber-700",c="shrink-0 px-2 py-0.5 rounded border border-current/40 hover:bg-white/20 text-[12px] font-medium";return t.jsxs(t.Fragment,{children:[n&&t.jsxs("div",{"data-testid":"pause-banner",className:`${i} ${l?r:o}`,children:[t.jsx("span",{className:"flex-1 leading-snug",children:hn(n.reason,n.resumeAt,e,n.by)}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),className:c,children:"Resume"})]}),a.map(([p,u])=>t.jsxs("div",{"data-testid":"launch-block-banner",className:`${i} ${r}`,children:[t.jsxs("div",{className:"flex-1 leading-snug min-w-0",children:[t.jsxs("div",{className:"font-medium",children:["Launches for ",t.jsx("span",{className:"font-mono",children:p})," jobs are failing before any work starts",u.httpStatus?` (HTTP ${u.httpStatus}, ${u.kind})`:` (${u.kind})`,u.exhausted?" — held until the Claude CLI version changes or you press Retry now.":u.until?` — next automatic probe ${new Date(u.until).getTime()>e?`in ${te(new Date(u.until).getTime()-e)}`:"on the next tick"}.`:"."]}),t.jsx("div",{className:"opacity-80",children:u.hint}),t.jsxs("div",{className:"font-mono text-[11.5px] opacity-70 truncate",title:u.message,children:[u.attempts," failed probe",u.attempts===1?"":"s",u.claudeVersion?` · CLI ${u.claudeVersion}`:"",u.lastSlug?` · last: ${u.lastSlug}`:""," · ",u.message]})]}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),className:c,children:"Retry now"})]},`launch-block-${p}`)),d.map(([p,u])=>t.jsx("div",{"data-testid":"launch-mitigation-banner",className:`${i} ${o}`,children:t.jsxs("div",{className:"flex-1 leading-snug min-w-0",children:[t.jsxs("div",{className:"font-medium",children:[t.jsx("span",{className:"font-mono",children:p})," jobs are running in degraded mode"," ","(",t.jsx("span",{className:"font-mono",children:Object.entries(u.env).map(([h,x])=>`${h}=${x}`).join(" ")}),")",u.claudeVersion?` since CLI ${u.claudeVersion}`:"","."]}),t.jsx("div",{className:"opacity-80",children:u.hint})]})},`launch-mitigation-${p}`))]})}function xn({scopeCwd:e,subView:s,onSubView:n,filterText:a,onFilterText:d,planMode:l,onPlanMode:i,planToolsRef:r}){const o=Le(C=>C.snapshot),c=pe(C=>C.sessions),p=un(e),u=_t(),[h,x]=f.useState(()=>Date.now()),[m,w]=f.useState("—");f.useEffect(()=>{const C=setInterval(()=>x(Date.now()),3e4);return()=>clearInterval(C)},[]),f.useEffect(()=>{let C=!0;return Os(30).then(M=>{if(!C||!M.ok||!M.data)return;const L=new Date,_=Be=>String(Be).padStart(2,"0"),Z=`${L.getFullYear()}-${_(L.getMonth()+1)}-${_(L.getDate())}`;w(Ls(Fs(M.data,{day:Z})))}),()=>{C=!1}},[]);const N=f.useMemo(()=>((o==null?void 0:o.jobs)??[]).filter(C=>!e||C.cwd===e),[o,e]),S=f.useMemo(()=>tn(N,h),[N,h]),y=f.useMemo(()=>{const C=lt(N,{sessions:c,now:h}),M=L=>C.filter(_=>_.status===L).length;return{active:M("active"),queued:M("queued"),draft:M("draft")}},[N,c,h]),O=f.useMemo(()=>{const C=new Date(h).toDateString(),M=[];for(const L of N)if(L.status==="completed"&&L.startedAt&&L.finishedAt&&new Date(Date.parse(L.finishedAt)).toDateString()===C){const _=Date.parse(L.finishedAt)-Date.parse(L.startedAt);_>0&&M.push(_)}return M.length?Math.round(M.reduce((L,_)=>L+_,0)/M.length/6e4):null},[N,h]);if(!o)return null;const k=p&&!p.unknown?p.verdict??null:null,E=p&&!p.unknown?p.slots??null:null,D=o.paused,P=fn((k==null?void 0:k.kind)??null,!!D,S.inFlight),T=pn[P],K=N.filter(C=>C.status==="pending").length,V=N.filter(C=>C.status==="running").length,z=Qt({snap:{...o,jobs:N},now:h,avgDurationMs:0,runningJobs:N.filter(C=>C.status==="running")}),J=p!=null&&p.unknown?`Queue health: unknown — ${p.reason??"state unavailable"}`:k?cn(k,(p==null?void 0:p.oldestRunningAgeMs)??null):"queue health loading…",X=xe(o.lastRunAt?Date.parse(o.lastRunAt):null,h),se=p!=null&&p.lastDispatchAttemptAt?xe(Date.parse(p.lastDispatchAttemptAt),h):"never",Y=[J,z.line1,k?`dispatchable ${k.dispatchable} · needs_review ${k.needsReviewCount}`:null,(p==null?void 0:p.oldestRunningAgeMs)!=null?`oldest running ${te(p.oldestRunningAgeMs)} (any project)`:null,`last batch fired ${X} (lastRunAt — advances only when a job launches)`,`last dispatch attempt ${se} (advances on every driver evaluation)`].filter(Boolean).join(`
1
+ import{aV as Ce,aH as ie,am as Ee,b2 as xs,ar as Se,al as ue,ap as te,b7 as H,bo as Le,bn as pe,br as _t,aO as f,aj as xe,bx as ms,ay as t,d as Ve,I as me,L as bt,q as bs,K as ge,v as ws,W as vs,f as js,Y as Ns,b1 as ys,bl as st,be as ks,aZ as Ss,ag as wt,aF as Tt,bw as $e,S as Fe,aM as _e,b as nt,b0 as at,V as Ot,z as Lt,p as Ft,r as $s,n as rt,N as it,O as Cs,h as re,i as B,an as qt,bp as Ps,aN as Ds,y as As,aQ as Bt,bA as Ht,_ as Rs,aT as Ue,aI as vt,bf as jt,m as ye,G as Nt,aX as yt,l as Ms,b5 as Is,a5 as Es,w as Gt,X as _s,bs as kt,a$ as Ts}from"./index-iQ6pdyuS.js";import{f as Os,a as Ls,s as Fs}from"./historyTotals-Cgjm5q24.js";import"./monaco-editor-BsIlgG7c.js";function qs(e){const s=new Map(e.map(i=>[i.slug,i])),n=new Map,a=new Set,d=[];function l(i){n.set(i,1),d.push(i);const r=s.get(i);for(const o of(r==null?void 0:r.dependsOn)??[]){if(!s.has(o))continue;const c=n.get(o);if(c===1){const p=d.indexOf(o);for(let u=p;u<d.length;u++)a.add(d[u])}else c===void 0&&l(o)}d.pop(),n.set(i,2)}for(const i of e)n.has(i.slug)||l(i.slug);return a}function Bs(e,s){return(e.dependsOn??[]).map(n=>{const a=s.get(n);return a?{slug:n,status:a.status,missing:!1,needsReview:a.status==="needs_review"}:{slug:n,status:null,missing:!0,needsReview:!1}})}function Hs(e,s,n){const a=new Set(e.map(c=>c.slug)),d=new Set;for(const c of e)for(const p of c.dependsOn??[])a.has(p)&&d.add(p);const l=new Map,i=[];for(const c of e){const p=n.has(c.slug)?void 0:(c.dependsOn??[]).find(u=>a.has(u)&&!n.has(u));p?(l.has(p)||l.set(p,[]),l.get(p).push(c)):i.push(c)}const r=(c,p)=>c.slug.localeCompare(p.slug);i.sort(r);for(const c of l.values())c.sort(r);function o(c,p,u){const h=Bs(c,s),x=n.has(c.slug);u.add(c.slug);const m=x?[]:(l.get(c.slug)??[]).filter(w=>!u.has(w.slug)).map(w=>o(w,p+1,u));return u.delete(c.slug),{row:c,depth:p,children:m,blockers:h,blocked:h.some(w=>!w.missing&&w.status!=="completed"),hasNeedsReviewBlocker:h.some(w=>w.needsReview),hasMissingDep:h.some(w=>w.missing),cycle:x,parallelEligible:(c.dependsOn??[]).length===0&&!d.has(c.slug)}}return i.map(c=>o(c,0,new Set))}function Wt(e,s,n){const a=new Map((n??e).map(c=>[c.slug,c])),d=qs(e),l=[],i=new Map,r=new Map;for(const c of e){const p=Ce(c,s),u=p.epicId??"__none__";i.has(u)||(l.push(u),i.set(u,[]),r.set(u,{epicId:p.epicId,label:p.known&&p.label?p.label:p.epicId?`Epic ${p.epicId.slice(0,12)}…`:"No Epic",known:p.known})),i.get(u).push(c)}const o=l.map(c=>{const p=r.get(c),u=i.get(c),h=Hs(u,a,d),x={};for(const m of u){const w=m.status??"unknown";x[w]=(x[w]??0)+1}return{epicId:p.epicId,label:p.label,known:p.known,nodes:h,counts:x,total:u.length}});return o.sort((c,p)=>c.epicId===null?1:p.epicId===null?-1:c.known!==p.known?c.known?-1:1:c.label.localeCompare(p.label)),o}function qe(e){const s=[],n=a=>{s.push(a);for(const d of a.children)n(d)};for(const a of e)n(a);return s}function Je(e){return String(e??"").replace(/^\d+-/,"")}function Te(e){const s=new Set,n=new Map;for(const a of e){s.add(a.slug);const d=Je(a.slug),l=n.get(d);l?l.push(a.slug):n.set(d,[a.slug])}return e.map(a=>{const d=a.dependsOn;if(!d||d.length===0)return a;let l=!1;const i=d.map(r=>{if(s.has(r))return r;const o=n.get(Je(r));return o&&o.length===1?(l=!0,o[0]):r});return l?{...a,dependsOn:i}:a})}const Gs=15e4,Xe=e=>e==="completed"||e==="skipped",ke=e=>e==="running"||e==="investigating",Vt=e=>e==="failed"||e==="needs_review"||e==="quarantined",Ws=e=>e==="failed"||e==="needs_review"||e==="quarantined";function Ut(e){if(e<=5e3)return"~now";if(e<6e4)return`~${Math.round(e/1e3)}s`;const s=Math.round(e/6e4);return s<60?`~${s}m`:`~${Math.floor(s/60)}h${String(s%60).padStart(2,"0")}m`}function zt(e,s){const n=e.estimateMinutes?e.estimateMinutes*6e4:null;return n?`${Math.min(99,Math.floor(s/n*100))}%`:Ee(s)}function Vs(e){let s=0,n=0;for(const a of e)if(a.status==="completed"&&a.startedAt&&a.finishedAt){const d=Date.parse(a.finishedAt)-Date.parse(a.startedAt);d>0&&(s+=d,n++)}return n===0?Gs:s/n}function Oe(e){const s=ie(e);return s===null?1/0:Number(s)}function Ze(e,s){const n=Oe(e.slug)-Oe(s.slug);return n!==0&&!Number.isNaN(n)?n:e.slug.localeCompare(s.slug)}function Us(e){let s=0;for(const n of e.statusHistory??[])n.to==="pending"&&n.from!==null&&s++;return s}function zs(e){return e.some(n=>ke(n.status))?"active":e.every(n=>Xe(n.status))?"done":e.filter(n=>n.status!=="quarantined").length===0?"draft":"queued"}function Qs(e,s,n,a){switch(e){case"done":return`${s.doneCount}/${s.rows.length} done`;case"running":return`${s.runningCount} running · ${n}`;case"held":return`${s.heldCount} held`;case"blocked":return`${s.blockedCount+a} blocked`;default:return`${n} ready`}}function Ys(e,s){return e._firstNum!==s._firstNum?e._firstNum<s._firstNum?-1:1:e._firstSlug.localeCompare(s._firstSlug)}function Ks(e,s){const n=new Map(e.map(l=>[l.row.slug,l.row.slug])),a=l=>{for(;n.get(l)!==l;)n.set(l,n.get(n.get(l))),l=n.get(l);return l};for(const l of e)for(const i of l.row.dependsOn??[])s.has(i)&&n.set(a(l.row.slug),a(i));const d=new Map;for(const l of e){const i=a(l.row.slug),r=d.get(i);r?r.push(l):d.set(i,[l])}return[...d.values()]}function Js(e,s){if(e.length>0&&e.every(n=>!!n.row.planId)){const n=new Map;for(const a of e){const d=n.get(a.row.planId);d?d.push(a):n.set(a.row.planId,[a])}return[...n.values()]}return Ks(e,s)}function Xs(e,s,n,a){const d=[],l=[e];for(a.add(e.row.slug);l.length>0;){const i=l.pop();d.push(i);for(const r of i.row.dependsOn??[])if(n.has(r)&&!a.has(r)){a.add(r);const o=s.get(r);o&&l.push(o)}}return d}function Zs(e,s){const n=new Map(e.map(r=>[r.row.slug,r])),a=new Set,d=[],l=e.filter(r=>Je(r.row.slug).startsWith("validate-")).sort((r,o)=>Ze({slug:r.row.slug},{slug:o.row.slug}));for(const r of l)a.has(r.row.slug)||d.push({nodes:Xs(r,n,s,a),validateSlug:r.row.slug});const i=e.filter(r=>!a.has(r.row.slug));if(i.length>0){const r=new Set(i.map(o=>o.row.slug));for(const o of Js(i,r))d.push({nodes:o,validateSlug:null})}return d}function en(e){return e.replace(/^validate[\s:-]*/i,"").trim()}function lt(e,s){if(e.length===0)return[];const n=Te(e),a=s.now??Date.now(),d=s.avgDurationMs??Vs(n),l=Math.max(1,s.concurrency??1),i=new Map(n.map(u=>[u.slug,u])),r=u=>u.status==="pending"&&(u.dependsOn??[]).every(h=>i.get(h)===void 0||i.get(h).status==="completed"),o=new Map;n.filter(r).sort(Ze).forEach((u,h)=>o.set(u.slug,h));const c=Wt(n,s.sessions,n),p=[];for(const u of c){const h=qe(u.nodes),x=new Set(h.map(S=>S.row.slug)),m=new Map(h.map(S=>[S.row.slug,S])),w=[];for(const S of Zs(h,x)){const y=S.nodes,O=new Set(y.map(j=>j.row.slug)),k=new Map,E=new Set,D=j=>{const $=m.get(j);return($.row.dependsOn??[]).filter(q=>O.has(q)&&!($.cycle&&m.get(q).cycle))},P=j=>{const $=k.get(j);if($!==void 0)return $;if(E.has(j))return 0;E.add(j);let q=0;for(const W of D(j))q=Math.max(q,P(W));return E.delete(j),k.set(j,q+1),q+1};for(const j of y)P(j.row.slug);const T=y.map(j=>{const $=j.row,q=($.dependsOn??[]).filter(W=>x.has(W));return{slug:$.slug,title:$.title,status:$.status,stage:k.get($.slug),prdNumber:ie($.slug),rowKind:"dep",rowTrailing:"",cycle:j.cycle,estimateMinutes:$.estimateMinutes??null,deps:q,crossEpicDeps:($.dependsOn??[]).filter(W=>!x.has(W)),blockers:j.blockers,job:$}});T.sort(Ze);const K=T.reduce((j,$)=>Math.max(j,$.stage),0),V=new Map;for(const j of T){const $=j.job,q=m.get(j.slug),W=$.status;let U;if(Xe(W)){const g=$.startedAt&&$.finishedAt?Date.parse($.finishedAt)-Date.parse($.startedAt):NaN;U={kind:"done",trailing:g>0?Ee(g):"",held:!1,blocked:!1}}else if(ke(W)){const g=$.startedAt?Math.max(0,a-Date.parse($.startedAt)):null;U={kind:"running",trailing:g===null?"":zt($,g),held:!1,blocked:!1}}else if(W==="failed")U={kind:"failed",trailing:"failed",held:!1,blocked:!1};else if(W==="needs_review")U={kind:"review",trailing:"review",held:!1,blocked:!1};else if(W==="quarantined")U={kind:"quarantined",trailing:"quarantined",held:!1,blocked:!1};else{const g=q.blockers.filter(v=>!v.missing&&v.status!=="completed");if(g.length>0){const v=g.some(C=>Ws(C.status)),A=g[0].slug;U={kind:"dep",trailing:`←${ie(A)??A}`,held:!v,blocked:v}}else if($.heldReason)U={kind:"gate",trailing:"gate",held:!0,blocked:!1};else{const v=Us($),A=o.get($.slug)??0;U=v>0?{kind:"retry",trailing:`${v} ${v===1?"retry":"retries"}`,held:!1,blocked:!1}:{kind:"eta",trailing:Ut(A*d/l),held:!1,blocked:!1}}}V.set(j.slug,U)}const z=[];for(let j=1;j<=K;j++){const $=T.filter(_=>_.stage===j),q=$.find(_=>{const Z=V.get(_.slug).kind;return _.status==="pending"&&(Z==="eta"||Z==="retry")});if(q){const _=V.get(q.slug);_.kind="next",_.trailing="next"}let W=0,U=0,g=0,v=0,A=0,C=0;for(const _ of $){const Z=V.get(_.slug);_.rowKind=Z.kind,_.rowTrailing=Z.trailing,Xe(_.status)?W++:ke(_.status)?U++:_.status==="pending"?(A++,Z.held&&g++,Z.blocked&&v++):Vt(_.status)&&C++}const M=W===$.length?"done":U>0?"running":v+C>0?"blocked":g>0?"held":"pending",L={n:j,rows:$,doneCount:W,runningCount:U,heldCount:g,blockedCount:v};z.push({...L,state:M,summary:Qs(M,L,A,C)})}let J=0;for(const j of T){const $=j.estimateMinutes?j.estimateMinutes*6e4:d;if(j.status==="pending")J+=$;else if(ke(j.status)){const q=j.job.startedAt?Math.max(0,a-Date.parse(j.job.startedAt)):0;J+=Math.max(0,$-q)}}const X=T.reduce((j,$)=>Math.min(j,Oe($.slug)),1/0),se=T.reduce((j,$)=>Math.max(j,Oe($.slug)),-1/0),Y=u.known?xs(u.label).title:u.label,R=S.validateSlug?T.find(j=>j.slug===S.validateSlug):void 0,F=R&&en(R.title)||Y;w.push({epicId:u.epicId,waveIndex:0,index:0,label:F,epicLabel:Y,validateSlug:S.validateSlug,width:z.reduce((j,$)=>Math.max(j,$.rows.length),0),status:zs(T),prdCount:T.length,stageCount:K,doneCount:z.reduce((j,$)=>j+$.doneCount,0),runningCount:z.reduce((j,$)=>j+$.runningCount,0),heldCount:z.reduce((j,$)=>j+$.heldCount,0),blockedCount:z.reduce((j,$)=>j+$.blockedCount,0),etaMs:J/l,stages:z,_firstNum:X,_lastNum:se,_firstSlug:T[0].slug})}w.sort(Ys),w.forEach((S,y)=>{S.waveIndex=y+1});const N=w.filter(S=>S.validateSlug===null);N.forEach((S,y)=>{N.length>1&&(S.label=`${S.label} · plan ${y+1}/${N.length}`)});for(const S of w)p.push(S)}return p.sort((u,h)=>{if(u._lastNum!==h._lastNum)return u._lastNum>h._lastNum?-1:1;const x=(u.epicId??"").localeCompare(h.epicId??"");return x!==0?x:u.waveIndex-h.waveIndex}),p.map(({_firstNum:u,_lastNum:h,_firstSlug:x,...m},w)=>({...m,index:w+1}))}function tn(e,s=Date.now()){const n=Te(e),a=new Map(n.map(x=>[x.slug,x])),d=new Date(s).toDateString();let l=0,i=0,r=0,o=0,c=0,p=0,u=0;for(const x of n)x.status==="pending"?(i++,(x.dependsOn??[]).every(w=>a.get(w)===void 0||a.get(w).status==="completed")&&l++):ke(x.status)?u++:x.status==="failed"?r++:x.status==="needs_review"?o++:x.status==="quarantined"?c++:x.status==="completed"&&x.finishedAt&&new Date(Date.parse(x.finishedAt)).toDateString()===d&&p++;let h=null;if(r+o+c>0){for(const x of lt(n,{sessions:{},now:s}))for(const m of x.stages)if(m.rows.some(w=>Vt(w.status))){(h===null||m.n<h)&&(h=m.n);break}}return{readyNow:l,totalQueued:i,heldByDeps:i-l,needsYou:r+o+c,needsYouStage:h,failedCount:r,needsReviewCount:o,doneToday:p,inFlight:u}}function sn(e){const s=new Map;for(const o of e.stages)for(const c of o.rows)s.set(c.slug,c);const n=o=>{var c;return((c=s.get(o))==null?void 0:c.cycle)===!0},a=new Map,d=new Set,l=(o,c)=>o.chain.length!==c.chain.length?o.chain.length>c.chain.length:o.est!==c.est?o.est>c.est:o.chain.join("\0")<c.chain.join("\0"),i=o=>{const c=a.get(o);if(c)return c;const p=s.get(o),u=p.estimateMinutes??0;if(d.has(o))return{chain:[o],est:u};d.add(o);let h=null;for(const m of p.deps){if(!s.has(m)||p.cycle&&n(m))continue;const w=i(m);(!h||l(w,h))&&(h=w)}d.delete(o);const x=h?{chain:[...h.chain,o],est:h.est+u}:{chain:[o],est:u};return a.set(o,x),x};let r=null;for(const o of s.keys()){const c=i(o);(!r||l(c,r))&&(r=c)}return r?r.chain:[]}const nn=300*6e4,an={five_hour:"5-hour",session:"5-hour",weekly_all:"weekly",weekly:"weekly"};function rn(e){return an[e]??e.replace(/_/g," ")}function Qt({snap:e,now:s,avgDurationMs:n,runningJobs:a}){const{config:d,jobs:l,paused:i,nextReset:r,utilization:o,utilizationWindow:c,effectiveConcurrency:p}=e;let u=0,h=0;for(const y of l)y.status==="pending"?u++:y.status==="completed"&&h++;const x=a.length,m=u+x,w=(p==null?void 0:p.cap)??5;if(x>0){const y=a.reduce((P,T)=>(P.startedAt??"")<(T.startedAt??"")?P:T),O=y.startedAt?s-Date.parse(y.startedAt):0,k=h+x,E=h+m,D=x>1?` · ${x}/${w} parallel`:"";return{kind:"running",line1:`Running ${k}/${E}${D} · ${Se(O)}`,line2:x===1?y.title:a.map(P=>P.title).join(", "),tooltip:a.map(P=>`${P.slug} (g${P.parallelGroup})`).join("; ")}}if(i){const y=i.resumeAt?Date.parse(i.resumeAt)-s:null;return{kind:"paused",line1:{rate_limit:"Paused — tokens exhausted",auth:"Paused — authentication failed",network:"Paused — network unreachable",reset_failure:"Paused — billing data unavailable",manual:"Paused — manual (you paused the queue)"}[i.reason]??`Paused — ${i.reason}`,line2:i.reason==="auth"?"Run `claude` in any terminal to refresh credentials, then Resume":y!==null&&y>0?`auto-resume ${ue(Date.parse(i.resumeAt))} (in ${te(y)})`:i.resumeAt?"resuming…":"no auto-resume scheduled",tooltip:i.resumeAt??"",action:{label:"Resume",onClick:()=>window.api.schedule.resume(),title:"Clear the pause and resume queue immediately"}}}if(m===0)return{kind:"idle",line1:"No work queued",line2:null};if((d.firePolicy??"when-available")==="manual")return{kind:"manual",line1:`Manual · ${u} pending`,line2:"click Fire next batch now to fire",action:{label:"Fire next batch now",onClick:()=>window.api.schedule.forceTick().then(H.fromOutcome).catch(()=>H.error("Failed to fire batch")),title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress."}};const S=d.utilizationThreshold??90;if(o==null)return{kind:"auto-soon",line1:`Auto · ${u} pending`,line2:"checking token availability…"};if(o>=S){const y=r?Date.parse(r)-s:null,O=c?rn(c):null,k=y===null||Number.isNaN(y)||y>nn,E=y&&y>0?`resets ${ue(Date.parse(r))} (in ${te(y)})`:null;let D;return k?D=`${O??"binding"} window — long hold${E?`, ${E}`:", reset time unknown"}`:D=E?`${O?`${O} window `:""}next ${E}`:"will fire when usage drops",{kind:"auto-throttled",line1:`Auto · throttled (util ${o.toFixed(0)}% ≥ ${S}%)`,line2:D}}return{kind:"auto-soon",line1:`Auto · ${u} pending · util ${o.toFixed(0)}%`,line2:"fires within 2 min (poll cycle)"}}const ln=15e3,on=new Set(["failed","needs_review","quarantined"]);function dn(e){for(let s=e.parentElement;s;s=s.parentElement){const n=getComputedStyle(s).overflowY;if(n==="auto"||n==="scroll")return s}return null}function St(){const s=Array.from(document.querySelectorAll("[data-job-row]")).find(a=>on.has(a.dataset.jobStatus??""));if(!s)return;const n=dn(s);n&&Ss(n,s,{block:"nearest",behavior:"smooth"})}function cn(e,s){var n;switch(e.kind){case"paused":return`paused: scheduler is paused (${e.reason??"manual"})`;case"launch-blocked":return`launch-blocked: ${e.agentType} jobs can't launch${(n=e.block)!=null&&n.kind?` (${e.block.kind})`:""}`;case"idle":return"idle: 0 pending";case"saturated":{const a=s!=null?`, oldest ${te(s)}`:"";return`saturated: ${e.totalSlots??"?"} slot(s) busy${a}`}case"blocked":{const a=e.blockedChains.length;return`blocked: ${e.pending} pending, ${e.dispatchable} dispatchable — ${a} chain${a===1?"":"s"} stuck behind a failed/skipped dependency`}case"stalled":return`stalled: no dispatch attempt in ${e.idleMs!=null?te(e.idleMs):"?"} with ${e.dispatchable} dispatchable`;case"running":default:return`running: ${e.runningCount} in flight, ${e.pending} pending`}}function un(e){const[s,n]=f.useState(null),a=st(),d=ks(),l=a&&d;return f.useEffect(()=>{if(!l)return;let i=!0,r=!1,o=!1;const c=()=>{r||(r=!0,window.api.schedule.queueHealth(e).then(u=>{r=!1,o=!1,i&&n(u)},u=>{r=!1,!o&&(o=!0,H.error(`Queue health refresh failed: ${u instanceof Error?u.message:String(u)}`))}))};c();const p=setInterval(c,ln);return()=>{i=!1,clearInterval(p)}},[e,l]),s}const pn={running:{dot:"bg-sage",text:"text-sage-dark"},paused:{dot:"bg-amber-500",text:"text-amber-600"},idle:{dot:"bg-fg-faint",text:"text-fg-faint"}};function fn(e,s,n){return e==="paused"||e==="launch-blocked"?"paused":e==="running"||e==="saturated"?"running":e?"idle":s?"paused":n>0?"running":"idle"}const ze="px-2.5 py-1.5 rounded border border-line text-[12.5px] font-medium text-fg-dim hover:text-fg hover:bg-bg-hi disabled:opacity-40 disabled:cursor-not-allowed whitespace-nowrap";function hn(e,s,n,a){var d;if(e==="agent"){const l=((d=a==null?void 0:a.cwd)==null?void 0:d.split("/").filter(Boolean).pop())||"another session",i=a!=null&&a.reason?` — "${a.reason}"`:"",r=s?new Date(s).getTime()-n:null,o=r==null?"":r>0?` — auto-resumes in ${te(r)}`:" — auto-resume pending";return`Paused by an agent in ${l}${i}${o}. Click Resume to restart now.`}if(e==="auth")return"Scheduler paused: Claude sign-in expired or invalid. Restart the app or re-run `claude login`, then Resume.";if(e==="rate_limit"){if(s){const l=new Date(s).getTime()-n;return l>0?`Paused for rate limit — resumes in ${te(l)}`:"Paused for rate limit — resume pending"}return"Paused for rate limit"}return e==="network"?"Paused: billing endpoint unreachable for 30+ min.":e==="manual"?"Scheduler paused manually — no new jobs start; running jobs continue. Click Resume to restart.":`Scheduler paused (${e})`}function gn({now:e}){const s=Le(p=>p.snapshot);if(!s)return null;const n=s.paused,a=Object.entries(s.launchBlocks??{}),d=Object.entries(s.launchMitigations??{}),l=(n==null?void 0:n.reason)==="auth"||(n==null?void 0:n.reason)==="network",i="flex items-start gap-3 border-b px-0 py-1.5 text-[12.5px]",r="bg-red-950/10 border-red-700/30 text-red-800",o="bg-amber-400/10 border-amber-600/30 text-amber-700",c="shrink-0 px-2 py-0.5 rounded border border-current/40 hover:bg-white/20 text-[12px] font-medium";return t.jsxs(t.Fragment,{children:[n&&t.jsxs("div",{"data-testid":"pause-banner",className:`${i} ${l?r:o}`,children:[t.jsx("span",{className:"flex-1 leading-snug",children:hn(n.reason,n.resumeAt,e,n.by)}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),className:c,children:"Resume"})]}),a.map(([p,u])=>t.jsxs("div",{"data-testid":"launch-block-banner",className:`${i} ${r}`,children:[t.jsxs("div",{className:"flex-1 leading-snug min-w-0",children:[t.jsxs("div",{className:"font-medium",children:["Launches for ",t.jsx("span",{className:"font-mono",children:p})," jobs are failing before any work starts",u.httpStatus?` (HTTP ${u.httpStatus}, ${u.kind})`:` (${u.kind})`,u.exhausted?" — held until the Claude CLI version changes or you press Retry now.":u.until?` — next automatic probe ${new Date(u.until).getTime()>e?`in ${te(new Date(u.until).getTime()-e)}`:"on the next tick"}.`:"."]}),t.jsx("div",{className:"opacity-80",children:u.hint}),t.jsxs("div",{className:"font-mono text-[11.5px] opacity-70 truncate",title:u.message,children:[u.attempts," failed probe",u.attempts===1?"":"s",u.claudeVersion?` · CLI ${u.claudeVersion}`:"",u.lastSlug?` · last: ${u.lastSlug}`:""," · ",u.message]})]}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),className:c,children:"Retry now"})]},`launch-block-${p}`)),d.map(([p,u])=>t.jsx("div",{"data-testid":"launch-mitigation-banner",className:`${i} ${o}`,children:t.jsxs("div",{className:"flex-1 leading-snug min-w-0",children:[t.jsxs("div",{className:"font-medium",children:[t.jsx("span",{className:"font-mono",children:p})," jobs are running in degraded mode"," ","(",t.jsx("span",{className:"font-mono",children:Object.entries(u.env).map(([h,x])=>`${h}=${x}`).join(" ")}),")",u.claudeVersion?` since CLI ${u.claudeVersion}`:"","."]}),t.jsx("div",{className:"opacity-80",children:u.hint})]})},`launch-mitigation-${p}`))]})}function xn({scopeCwd:e,subView:s,onSubView:n,filterText:a,onFilterText:d,planMode:l,onPlanMode:i,planToolsRef:r}){const o=Le(C=>C.snapshot),c=pe(C=>C.sessions),p=un(e),u=_t(),[h,x]=f.useState(()=>Date.now()),[m,w]=f.useState("—");f.useEffect(()=>{const C=setInterval(()=>x(Date.now()),3e4);return()=>clearInterval(C)},[]),f.useEffect(()=>{let C=!0;return Os(30).then(M=>{if(!C||!M.ok||!M.data)return;const L=new Date,_=Be=>String(Be).padStart(2,"0"),Z=`${L.getFullYear()}-${_(L.getMonth()+1)}-${_(L.getDate())}`;w(Ls(Fs(M.data,{day:Z})))}),()=>{C=!1}},[]);const N=f.useMemo(()=>((o==null?void 0:o.jobs)??[]).filter(C=>!e||C.cwd===e),[o,e]),S=f.useMemo(()=>tn(N,h),[N,h]),y=f.useMemo(()=>{const C=lt(N,{sessions:c,now:h}),M=L=>C.filter(_=>_.status===L).length;return{active:M("active"),queued:M("queued"),draft:M("draft")}},[N,c,h]),O=f.useMemo(()=>{const C=new Date(h).toDateString(),M=[];for(const L of N)if(L.status==="completed"&&L.startedAt&&L.finishedAt&&new Date(Date.parse(L.finishedAt)).toDateString()===C){const _=Date.parse(L.finishedAt)-Date.parse(L.startedAt);_>0&&M.push(_)}return M.length?Math.round(M.reduce((L,_)=>L+_,0)/M.length/6e4):null},[N,h]);if(!o)return null;const k=p&&!p.unknown?p.verdict??null:null,E=p&&!p.unknown?p.slots??null:null,D=o.paused,P=fn((k==null?void 0:k.kind)??null,!!D,S.inFlight),T=pn[P],K=N.filter(C=>C.status==="pending").length,V=N.filter(C=>C.status==="running").length,z=Qt({snap:{...o,jobs:N},now:h,avgDurationMs:0,runningJobs:N.filter(C=>C.status==="running")}),J=p!=null&&p.unknown?`Queue health: unknown — ${p.reason??"state unavailable"}`:k?cn(k,(p==null?void 0:p.oldestRunningAgeMs)??null):"queue health loading…",X=xe(o.lastRunAt?Date.parse(o.lastRunAt):null,h),se=p!=null&&p.lastDispatchAttemptAt?xe(Date.parse(p.lastDispatchAttemptAt),h):"never",Y=[J,z.line1,k?`dispatchable ${k.dispatchable} · needs_review ${k.needsReviewCount}`:null,(p==null?void 0:p.oldestRunningAgeMs)!=null?`oldest running ${te(p.oldestRunningAgeMs)} (any project)`:null,`last batch fired ${X} (lastRunAt — advances only when a job launches)`,`last dispatch attempt ${se} (advances on every driver evaluation)`].filter(Boolean).join(`
2
2
  `),R=o.utilization,F=o.pollHealth,j=F!=null&&!F.lastPollOk,$=ms(o.utilizationWindow),q=o.nextReset?Date.parse(o.nextReset):null,W=q?q>h?te(q-h):"soon":"—",U=(u==null?void 0:u.total)??5,g=(u==null?void 0:u.envOverride)===!0,v=o.config.firePolicy??"when-available",A=K===0&&V===0;return t.jsxs("div",{"data-testid":"scheduler-top-bands",className:"shrink-0 px-[18px]",children:[t.jsxs(Ve,{height:40,testId:"queue-health-header",className:"gap-3",children:[t.jsx("h1",{className:"m-0 font-serif text-[21px] font-semibold leading-none tracking-tight text-fg",children:"Scheduler"}),t.jsx("span",{className:"w-px h-[20px] bg-rule-structural","aria-hidden":"true"}),t.jsxs("span",{className:`inline-flex items-center gap-1.5 text-[12.5px] font-medium ${T.text}`,"data-testid":"scheduler-state-word","data-state":P,children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${T.dot}`,"aria-hidden":"true"}),P]}),t.jsxs("span",{className:"font-mono text-[12px] text-fg-faint whitespace-nowrap","data-testid":"scheduler-meta",children:[S.inFlight," in flight · ",S.heldByDeps," held · last batch ",X]}),t.jsxs(me,{title:Y,testId:"scheduler-verdict-info",popoverTestId:"scheduler-info-popover",children:[t.jsx("pre",{className:"m-0 mb-2 whitespace-pre-wrap font-mono text-[11.5px] text-fg-dim",children:Y}),bt.scheduler&&t.jsx(bs,{content:bt.scheduler})]}),t.jsxs("span",{className:"ml-auto flex items-center gap-2",children:[t.jsx("button",{type:"button",onClick:()=>window.api.schedule.rescan().then(H.fromOutcome).catch(()=>H.error("Failed to rescan")),title:"Re-scan the prds/ folder. Use when you've added or edited PRDs on disk and want the queue to reflect them immediately.",className:ze,children:"Refresh"}),D?t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resume(),title:"Clear the pause and resume queue immediately",className:ze,children:"Resume"}):t.jsx("button",{type:"button",onClick:()=>window.api.schedule.pause(),title:"Stop NEW dispatch. Running jobs are not killed.",className:ze,children:"Pause"}),t.jsx("button",{type:"button",onClick:()=>window.api.schedule.forceTick().then(H.fromOutcome).catch(()=>H.error("Failed to fire batch")),disabled:A,title:"Bypasses the billing-usage poll. Use when the meter is rate-limited or you want immediate progress.",className:"px-3 py-1.5 rounded bg-accent text-white text-[12.5px] font-semibold whitespace-nowrap disabled:opacity-40 disabled:cursor-not-allowed hover:opacity-90",children:"Fire next batch"})]})]}),t.jsx(gn,{now:h}),t.jsxs(Ve,{height:70,testId:"scheduler-kpi-band",children:[t.jsx(ge,{testId:"kpi-window",label:$?`${$} used`:"Window used",info:j?`Billing poll failing — this reading may be outdated (last good reading ${xe(F.lastPollAt,h)}). Machine-wide ${$??"binding"} window.`:`Share of the machine-wide ${$??"binding"} billing window consumed — the window closest to its limit.`,value:R==null?"—":`${Math.round(R)}%`,sub:`resets in ${W}`,third:t.jsx(ws,{pct:R??0,tone:j?"bg-amber-500":"bg-accent"})}),t.jsx(ge,{testId:"kpi-slots",label:"Slots",info:`Machine-wide session pool (${(E==null?void 0:E.source)==="env"?"SM_SESSION_SLOTS override":"Home tab cap"}), not scoped to this project`,value:E?`${E.inUse}/${E.total}`:"—",sub:"in use",third:E?t.jsx(vs,{filled:E.inUse,total:E.total}):null}),t.jsx(ge,{testId:"kpi-ready",label:"Ready now",info:"Pending rows whose dependsOn chain is fully satisfied right now",value:S.readyNow,sub:`of ${S.totalQueued} queued`,third:`${S.heldByDeps} held by deps`}),S.needsYou>0?t.jsx(ge,{testId:"kpi-needs-you",label:"Needs you",value:t.jsx("button",{type:"button","data-testid":"kpi-needs-you-jump",onClick:St,className:"font-semibold text-accent hover:underline",title:"Scroll to the first failed / needs-review / quarantined row",children:S.needsYou}),sub:t.jsx("button",{type:"button",onClick:St,className:"hover:underline",children:S.needsYouStage!=null?`blocking stage ${S.needsYouStage}`:"need attention"}),third:[S.failedCount>0&&`${S.failedCount} failed`,S.needsReviewCount>0&&`${S.needsReviewCount} needs review`,S.needsYou-S.failedCount-S.needsReviewCount>0&&`${S.needsYou-S.failedCount-S.needsReviewCount} quarantined`].filter(Boolean).join(" · ")}):t.jsx(ge,{testId:"kpi-needs-you",label:"Needs you",value:t.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[15px]",children:[t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-sage","aria-hidden":"true"}),"all clear"]}),third:"0 failed · 0 needs review"}),t.jsx(ge,{testId:"kpi-done",label:"Done today",value:S.doneToday,sub:O!=null?`avg ${O}m`:"avg —",third:t.jsx("span",{"data-testid":"kpi-done-spend",children:m})}),t.jsx(ge,{testId:"kpi-concurrency",label:"Concurrency",info:"Start-jobs policy, concurrency cap and utilization threshold",infoTestId:"kpi-concurrency-info",infoAlignRight:!0,infoContent:t.jsxs("label",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-fg",children:"Start jobs"}),t.jsxs("select",{"data-testid":"kpi-fire-policy",value:v,onChange:C=>window.api.schedule.setConfig({firePolicy:C.target.value}),className:"border border-line bg-bg-hi rounded px-1 py-0.5 text-[12px] text-fg-dim",title:"when-available: poll usage and fire when tokens are below threshold. manual: only on Run now.","aria-label":"Start jobs policy",children:[t.jsx("option",{value:"when-available",children:"when available"}),t.jsx("option",{value:"manual",children:"manually"})]})]}),value:t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(Ns,{value:U,min:0,max:(u==null?void 0:u.max)??10,disabled:g,onChange:C=>{ys(C).catch(M=>{H.error(`Could not set session slots: ${M instanceof Error?M.message:String(M)}`)})},title:g?"pinned by SM_SESSION_SLOTS — unset the env var to edit":"Machine-wide claude -p session slots, shared with chat runs"}),g&&t.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-amber-600 bg-amber-400/10 border border-amber-400/30 rounded px-1 py-0",title:"Pinned by SM_SESSION_SLOTS — unset the env var to edit",children:"env"})]}),sub:"at once",third:v==="when-available"?t.jsxs("span",{children:["pause above"," ",t.jsx(js,{value:o.config.utilizationThreshold??90,min:0,max:100,testId:"kpi-threshold",title:"Holds new dispatches when the highest of the 5-hour and weekly usage windows is at/above this percent (when-available policy only). Not the executor rate-limit pause — click to edit",onCommit:C=>window.api.schedule.setConfig({utilizationThreshold:C})})]}):null})]}),t.jsxs(Ve,{height:30,testId:"scheduler-plans-toolbar",className:"gap-3",children:[t.jsx("span",{className:"text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:"Plans"}),t.jsxs("span",{className:"font-mono text-[12px] text-fg-faint whitespace-nowrap","data-testid":"scheduler-plans-meta",children:[y.active," active · ",y.queued," queued · ",y.draft," draft · ",N.length," PRDs"]}),t.jsxs("span",{className:"ml-auto flex items-center gap-3",children:[t.jsx("span",{ref:r,className:"contents","data-testid":"scheduler-plan-tools"}),t.jsx("input",{type:"text",value:a,onChange:C=>d(C.target.value),placeholder:"filter PRDs…","aria-label":"Filter PRDs by title, slug, or project","data-testid":"scheduler-filter-input",className:"w-[180px] bg-bg-hi border border-line rounded px-2 py-0.5 text-[12px] text-fg placeholder:text-fg-faint focus:outline-none focus:border-fg-faint"}),t.jsx("span",{className:"inline-flex border border-line rounded overflow-hidden",role:"group","aria-label":"Plan view mode",children:[["graph","Graph"],["list","List"],["critical","Critical path"]].map(([C,M])=>t.jsx("button",{type:"button","data-testid":`plan-mode-${C}`,"aria-pressed":l===C&&s==="queue",onClick:()=>{i(C),n("queue")},className:`px-2 py-0.5 text-[12px] ${l===C&&s==="queue"?"bg-bg-elev font-semibold text-fg":"text-fg-dim hover:text-fg"}`,children:M},C))}),t.jsx("span",{className:"w-px h-[16px] bg-rule-structural","aria-hidden":"true"}),[["prds","PRDs","Authored PRD source files on disk — edit, lint, archive, or queue them."],["history","History","The last 50 completed and failed jobs."],["machine","Machine","Machine-wide config that applies to every project — not this project’s live queue."]].map(([C,M,L])=>t.jsx("button",{type:"button",onClick:()=>n(C),"aria-pressed":s===C,title:L,className:`text-[12.5px] ${s===C?"font-semibold text-fg":"text-fg-faint hover:text-fg-dim"}`,children:M},C))]})]})]})}function Yt({options:e,value:s,onChange:n,pillPadding:a="px-3 py-1.5"}){return t.jsx("div",{className:"flex gap-1.5 flex-wrap",children:e.map(d=>{const l=d.value===s;return t.jsxs("button",{type:"button",onClick:()=>n(d.value),className:`rounded-full ${a} text-[12.5px] border transition-colors ${l?"bg-accent text-white border-accent font-semibold":"bg-bg-hi text-fg-dim border-line hover:border-fg-faint font-medium"}`,children:[d.label,d.count!==void 0&&t.jsxs("span",{children:[" ",d.count]})]},d.value)})})}function Kt(e,s=60){const n=e.trim();return n.length<=s?n:`${n.slice(0,s-1)}…`}function mn(e){return qe([e]).filter(s=>s.children.length===0).map(s=>s.row.slug)}function Jt(e){return e.nodes.map(s=>({rootSlug:s.row.slug,label:s.row.title||s.row.slug,terminals:mn(s)}))}function bn(e){const s=new Map;for(const n of e){const a=Jt(n);n.nodes.forEach((d,l)=>{const i=a.filter((r,o)=>o!==l);for(const r of qe([d]))s.set(r.row.slug,i)})}return s}function Xt({job:e,headChoices:s}){const[n,a]=f.useState(!1),d=f.useCallback((l,i)=>{a(!0),window.api.schedule.setPrdDisposition({slug:e.slug,cwd:e.cwd??void 0,disposition:l,dependsOn:i}).then(H.fromOutcome).catch(()=>H.error("Failed to change disposition")).finally(()=>a(!1))},[e.slug,e.cwd]);return e.disposition!=="append"&&s.length===0?null:t.jsxs("select",{"data-testid":"job-row-disposition-control",disabled:n,value:"",onChange:l=>{const i=l.target.value;if(i==="__new-head__")d("new-head");else if(i){const r=s.find(o=>o.rootSlug===i);r&&d("append",r.terminals)}},className:"text-[13px] font-semibold text-fg-dim hover:text-fg bg-transparent border border-line/60 rounded px-1.5 py-0.5 cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed",title:"Change this wave's relationship to the rest of the Epic's plan",children:[t.jsx("option",{value:"",disabled:!0,children:"change disposition…"}),e.disposition==="append"&&t.jsx("option",{value:"__new-head__",children:"promote to new head"}),s.map(l=>t.jsxs("option",{value:l.rootSlug,children:["attach behind: ",Kt(l.label,40)]},l.rootSlug))]})}function wn(e,s,n=null){if(s.length===0||e.length===0)return e;const a=new Set,d=new Set;for(const i of e){a.add(i.slug);for(const r of wt(i))d.add(r)}const l=[];for(const i of s)i.archived!==!0||a.has(i.slug)||n&&i.cwd!==n||wt(i).some(r=>d.has(r))&&(a.add(i.slug),l.push({slug:i.slug,title:i.title,cwd:i.cwd,parallelGroup:i.parallelGroup,estimateMinutes:i.estimateMinutes,bodyPreview:"",status:i.archivedStatus??"completed",runId:null,startedAt:null,finishedAt:null,exitCode:null,error:null,dependsOn:i.dependsOn??void 0,sourcePromptId:i.sourcePromptId??null,epicId:i.epicId??null,synthetic:!0}));return l.length===0?e:[...e,...l]}const vn=[],jn=new Set(["failed","needs_review","quarantined"]);function Nn(e){switch(e.status){case"completed":case"skipped":return"bg-sage";case"running":case"investigating":return"bg-accent";case"failed":return"bg-accent";case"needs_review":return"bg-butter";case"quarantined":return"bg-butter/60";default:return e.rowKind==="eta"||e.rowKind==="next"||e.rowKind==="retry"?"border border-fg-faint bg-transparent":"bg-fg-faint/40"}}function yn(e){switch(e.status){case"running":case"investigating":return"bg-butter/10";case"failed":return"bg-accent/10";case"needs_review":return"bg-butter/25";default:return""}}function kn(e){switch(e.rowKind){case"running":case"dep":case"failed":return"text-accent";case"review":return"text-butter font-semibold";default:return"text-fg-faint"}}function Sn({row:e,elapsedMs:s,listIndex:n,onFocused:a,headChoices:d=vn}){const[l,i]=f.useState(!1),r=e.job,o=s!==null&&e.rowKind==="running"?zt(r,s):e.rowTrailing,c=e.status==="completed"||e.status==="skipped",p=e.rowKind==="dep"&&e.blockers.some(h=>!h.missing&&h.status!==null&&jn.has(h.status)),u=c||p;return t.jsxs("div",{role:"listitem","data-testid":"prd-row","data-slug":e.slug,className:"border-t border-rule-inner first:border-t-0",children:[t.jsxs("button",{type:"button","data-job-row":!0,"data-job-status":r.status,"data-job-index":n,onClick:()=>i(h=>!h),onFocus:()=>a(n),"aria-expanded":l,"aria-label":`${e.prdNumber?`PRD ${e.prdNumber}, `:""}${r.title}, ${r.status}${o?`, ${o}`:""}`,title:r.title,className:`w-full h-[31px] py-1 px-2 text-left flex items-center gap-1.5 hover:bg-bg/40 focus:outline-none focus:ring-1 focus:ring-accent focus:ring-inset ${yn(e)}`,children:[t.jsx("span",{"aria-hidden":"true",className:`shrink-0 w-[7px] h-[7px] rounded-full ${Nn(e)}`}),t.jsx("span",{className:"shrink-0 font-mono text-[10.5px] text-fg-faint w-[30px]",children:e.prdNumber?`#${e.prdNumber}`:""}),t.jsx("span",{className:`flex-1 min-w-0 truncate text-[12.5px] leading-tight ${u?"text-fg-faint":"text-fg font-medium"}`,children:r.title}),t.jsx("span",{"data-testid":"prd-row-trailing",className:`shrink-0 font-mono text-[10.5px] ${kn(e)}`,children:o})]}),l&&t.jsx($n,{row:e,elapsedMs:s,headChoices:d})]})}const Zt=f.memo(Sn);function $n({row:e,elapsedMs:s,headChoices:n}){const a=e.job,[d,l]=f.useState(!1),i=pe(x=>x.sessions),r=f.useMemo(()=>Ce(a,i),[a,i]),o=r.known&&r.epicId?i[r.epicId]:null,c=f.useCallback(x=>Tt(x),[]),p="font-mono text-[11.5px] text-fg-dim leading-snug break-words",u="text-[12px] font-semibold bg-transparent border-0 cursor-pointer p-0",h=a.error?a.error.split(`
3
3
  `)[0]:null;return t.jsxs("div",{"data-testid":"prd-row-detail",className:"px-3 py-2 bg-bg-elev/50 border-t border-rule-inner flex flex-col gap-1",children:[t.jsxs("div",{className:p,children:[a.status.replace(/_/g," "),a.exitCode!==null&&` · exit ${a.exitCode}`,a.verifierVerdict&&` · ${$e(a.verifierVerdict)}`,a.startedAt&&` · started ${ue(Date.parse(a.startedAt))}`,a.finishedAt&&` · finished ${ue(Date.parse(a.finishedAt))}`,s===null&&e.rowTrailing&&e.rowKind==="done"?` · took ${e.rowTrailing}`:""]}),e.cycle&&t.jsxs("div",{className:`${p} text-accent`,"data-testid":"job-row-cycle-warning",children:["⚠ dependsOn cycle — ",e.blockers.map(x=>x.slug).join(" ↔ ")||"self-referencing"]}),!e.cycle&&e.blockers.length>0&&t.jsxs("div",{className:p,"data-testid":"job-row-blockers",children:["depends on ",e.blockers.map(x=>`${x.slug} (${x.missing?"missing":(x.status??"unknown").replace(/_/g," ")})`).join(", ")]}),a.status==="pending"&&a.heldReason&&t.jsxs("div",{className:`${p} text-amber-400/90`,"data-testid":"job-row-held-reason",children:["held · ",a.heldReason]}),h&&t.jsx("div",{className:`${p} text-accent/80`,children:h}),!a.synthetic&&t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pt-0.5",children:[o&&t.jsx("button",{type:"button","data-testid":"job-row-prompt-session-link",title:o.goalText,onClick:()=>c(o.id),className:`${u} text-accent hover:text-accent/80`,children:"view epic →"}),a.runId&&t.jsx("button",{type:"button",onClick:()=>l(!0),className:`${u} text-fg-dim hover:text-fg`,children:"view log →"}),a.status==="quarantined"&&t.jsx("button",{type:"button","data-testid":"job-row-adopt-prd",title:"Stamp this PRD's provenance so the scheduler will run it — no unstamped PRD runs automatically.",onClick:()=>{window.api.schedule.adoptPrd(a.slug).then(H.fromOutcome).catch(()=>H.error("Failed to adopt PRD"))},className:`${u} text-accent hover:text-accent/80`,children:"adopt PRD →"}),a.status!=="pending"&&a.status!=="running"&&a.status!=="quarantined"&&t.jsx("button",{type:"button",onClick:()=>window.api.schedule.resetJob(a.slug,a.cwd??void 0),className:`${u} text-fg-dim hover:text-fg`,children:"reset to pending →"}),a.disposition&&(a.status==="pending"||a.status==="quarantined")&&t.jsx(Xt,{job:a,headChoices:n})]}),d&&a.runId&&t.jsx(Fe,{runId:a.runId,slug:a.slug,title:a.title||a.slug,onClose:()=>l(!1)})]})}const ce=190,Cn=7,Pn=5,Dn=[],es=e=>e==="completed"||e==="skipped",ts=e=>e==="running"||e==="investigating",ss=e=>e==="failed"||e==="needs_review"||e==="quarantined";function Ae(e){return ts(e.status)?0:ss(e.status)?1:es(e.status)?3:2}const An={done:"text-sage",running:"text-accent",held:"text-fg-faint",pending:"text-fg-faint",blocked:"text-butter"},Rn={done:"bg-sage",running:"bg-accent",held:"bg-fg-faint/50",pending:"bg-fg-faint/50",blocked:"bg-butter"};function Mn(e,s){return e.every(n=>es(n.status))?`+${e.length} done`:e.every(n=>n.rowKind==="dep"&&n.blockers.some(a=>!a.missing&&a.status!==null&&ss(a.status)))?`+${e.length} blocked`:`+${e.length} in stage ${s}`}function In({stage:e,epicId:s,now:n,hidden:a,indexBySlug:d,headChoicesBySlug:l,onRowFocused:i}){const[r,o]=f.useState(!1),c=f.useMemo(()=>e.rows.filter(k=>!(a.has(k.slug)&&(k.status==="completed"||k.status==="failed"))).map((k,E)=>({r:k,i:E})).sort((k,E)=>Ae(k.r)-Ae(E.r)||k.i-E.i).map(k=>k.r),[e.rows,a]),p=f.useMemo(()=>c.filter(k=>Ae(k)<=1).length,[c]),u=Math.max(e.state==="done"?Pn:Cn,p),h=r?c:c.slice(0,u),x=r?[]:c.slice(u),m=c.find(k=>k.status==="failed"),w=c.find(k=>k.status==="needs_review"),N=p>0&&(m!==void 0||w!==void 0),S=h.reduce((k,E,D)=>Ae(E)<=1?D:k,-1),y=k=>t.jsx(Zt,{row:k,elapsedMs:ts(k.status)&&k.job.startedAt?n-Date.parse(k.job.startedAt):null,listIndex:d.get(k.slug)??0,onFocused:i,headChoices:l.get(k.slug)??Dn},k.slug),O="flex-1 min-w-0 truncate h-[24px] text-[11.5px] font-medium text-fg-dim hover:text-fg border border-rule-structural rounded-sm bg-transparent cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed";return t.jsxs("div",{"data-testid":"stage-column","data-stage":e.n,style:{width:ce},className:"shrink-0 border-l border-rule-structural first:border-l-0 flex flex-col self-stretch",children:[t.jsxs("div",{className:"h-[30px] shrink-0 flex items-center gap-1.5 px-2 border-b border-rule-inner","data-testid":"stage-header",children:[t.jsx("span",{"aria-hidden":"true",className:`w-[7px] h-[7px] rounded-full shrink-0 ${Rn[e.state]}`}),t.jsxs("span",{className:`text-[10px] font-semibold uppercase tracking-wide ${An[e.state]}`,children:["Stage ",e.n]}),e.state==="blocked"&&t.jsx(me,{title:"Rows in this stage are failed / need review / are quarantined, or wait on one that is."}),t.jsx("span",{"data-testid":"stage-summary",className:"ml-auto font-mono text-[10.5px] text-fg-dim truncate",children:e.summary})]}),t.jsx("div",{role:"presentation",children:h.map((k,E)=>t.jsxs("div",{children:[y(k),N&&E===S&&t.jsxs("div",{"data-testid":"stage-attention-actions",className:"flex gap-1.5 px-2 py-1.5 border-t border-rule-inner",children:[m&&t.jsxs("button",{type:"button","data-testid":"stage-retry",title:`Reset ${m.slug} to pending`,onClick:()=>{window.api.schedule.resetJob(m.slug,m.job.cwd??void 0).then(D=>{D.ok||H.error(D.error??`Failed to reset ${m.slug}`)}).catch(()=>H.error(`Failed to reset ${m.slug}`))},className:O,children:["Retry ",m.prdNumber?`#${m.prdNumber}`:m.slug]}),w&&t.jsxs("button",{type:"button","data-testid":"stage-review",disabled:!s,title:s?"Open the authoring Epic — a needs_review PRD is a question routed back to it":"No authoring Epic recorded for this plan",onClick:()=>{s&&Tt(s)},className:O,children:["Review ",w.prdNumber?`#${w.prdNumber}`:w.slug]})]})]},k.slug))}),(x.length>0||r&&c.length>u)&&t.jsx("button",{type:"button","data-testid":"stage-footer","aria-expanded":r,onClick:()=>o(k=>!k),className:"mt-auto h-[26px] border-t border-rule-inner font-mono text-[11px] text-fg-faint hover:text-fg-dim bg-transparent cursor-pointer",children:r?"show less ▴":`${Mn(x,e.n)} ▾`})]})}const we=6,Qe=4,Ie=4,$t=12,Ct=5,ns=2,Pt=4,En={done:"bg-sage",running:"bg-accent",attention:"bg-butter",failed:"bg-red-600",pending:"bg-fg-faint/50"};function _n(e){return e==="completed"||e==="skipped"?"done":e==="running"||e==="investigating"?"running":e==="failed"?"failed":e==="needs_review"||e==="quarantined"?"attention":"pending"}function Tn(e){const s=[],n=[],a=[];let d=Ct;for(const l of e){const i=Math.max(1,Math.ceil(l.rows.length/Ie));n.push(d),a.push(i*we),l.rows.forEach((r,o)=>{s.push({x:d+Math.floor(o/Ie)*we,y:ns+o%Ie*we,tone:_n(r.status),title:`${r.prdNumber?`#${r.prdNumber}`:r.slug} ${r.title} — ${r.status}`})}),d+=i*we+$t}return{dots:s,stageX:n,stageW:a,width:Math.max(0,d-$t)+Ct}}function ve(e,s){return e.findIndex(n=>n.rows.some(a=>s(a.status)))}const et=e=>e==="running"||e==="investigating",tt=e=>e==="failed"||e==="needs_review"||e==="quarantined";function On({stages:e,first:s,perView:n,onSeek:a}){const d=f.useMemo(()=>Tn(e),[e]),l=f.useMemo(()=>ve(e,et)>=0,[e]),i=f.useMemo(()=>ve(e,tt)>=0,[e]),r=f.useRef(!1),o=e.length,c=Math.min(o-1,s+n-1),p=d.stageX[Math.min(s,o-1)]??0,u=(d.stageX[c]??0)+(d.stageW[c]??0),h=m=>{const w=m.currentTarget.getBoundingClientRect(),N=m.clientX-w.left;let S=0;for(let y=0;y<o;y++)d.stageX[y]<=N&&(S=y);a(Math.max(0,Math.min(o-1,S-Math.floor(n/2))))},x="px-2 h-[20px] text-[11.5px] disabled:opacity-40 disabled:cursor-not-allowed";return t.jsxs("div",{"data-testid":"plan-minimap",className:"h-[28px] flex items-center gap-3 px-3 border-t border-rule-inner",children:[t.jsxs("span",{className:"shrink-0 flex items-center gap-1 text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:["Whole graph",t.jsx(me,{title:"Every PRD in this plan as one dot, grouped by stage. The rust box is the range of stages shown below — drag it to scroll."})]}),t.jsxs("div",{"data-testid":"plan-minimap-dots",role:"presentation",className:"relative shrink min-w-0 overflow-hidden cursor-ew-resize touch-none",style:{width:d.width,height:Ie*we-(we-Qe)+2*ns},onPointerDown:m=>{var w,N;r.current=!0,(N=(w=m.currentTarget).setPointerCapture)==null||N.call(w,m.pointerId),h(m)},onPointerMove:m=>{r.current&&h(m)},onPointerUp:()=>{r.current=!1},onPointerCancel:()=>{r.current=!1},children:[d.dots.map((m,w)=>t.jsx("span",{title:m.title,"data-tone":m.tone,className:`absolute rounded-[1px] ${En[m.tone]}`,style:{left:m.x,top:m.y,width:Qe,height:Qe}},w)),t.jsx("span",{"data-testid":"plan-minimap-brush","aria-hidden":"true",className:"absolute top-0 bottom-0 border border-accent bg-accent/10 rounded-[2px] pointer-events-none",style:{left:p-Pt,width:u-p+2*Pt}})]}),t.jsxs("span",{className:"ml-auto shrink-0 font-mono text-[11.5px] text-fg-faint","data-testid":"plan-minimap-range",children:["stages ",Math.min(s+1,o),"–",c+1," of ",o]}),t.jsxs("span",{className:"shrink-0 inline-flex border border-line rounded overflow-hidden",role:"group","aria-label":"Jump the stage window",children:[t.jsx("button",{type:"button","data-testid":"minimap-running",disabled:!l,title:l?"Scroll to the lowest stage with a running PRD":"No stage has a running PRD",onClick:()=>a(ve(e,et)),className:`${x} text-fg-dim hover:text-fg`,children:"Running"}),t.jsx("button",{type:"button","data-testid":"minimap-blockers",disabled:!i,title:i?"Scroll to the lowest stage with a failed / needs-review / quarantined PRD":"No stage has a failed, needs-review or quarantined PRD",onClick:()=>a(ve(e,tt)),className:`${x} text-fg-dim hover:text-fg border-l border-line`,children:"Blockers"})]})]})}const Ln=148;function Fn({stages:e,onSeek:s}){if(e.length===0)return null;const n=e[0].n,a=e[e.length-1].n;return t.jsxs("div",{"data-testid":"further-stages",style:{width:Ln},className:"shrink-0 border-l border-rule-structural flex flex-col",children:[t.jsxs("div",{className:"h-[30px] shrink-0 flex items-center px-2 border-b border-rule-inner text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:["Stage ",n,"–",a]}),t.jsxs("div",{className:"h-[22px] shrink-0 flex items-center gap-1 px-2 text-[10.5px] font-semibold uppercase tracking-wide text-fg-faint",children:["Further stages",t.jsx(me,{title:"Stages beyond the visible window. Click one to scroll the stage columns to it."})]}),e.map(d=>{const l=d.rows.length===0?0:d.doneCount/d.rows.length*100;return t.jsxs("button",{type:"button","data-testid":"further-stage-row","data-stage":d.n,title:`${d.summary} — scroll to stage ${d.n}`,onClick:()=>s(d.n-1),className:"h-[26px] px-2 flex items-center gap-2 border-t border-rule-inner bg-transparent hover:bg-bg-hi cursor-pointer text-left",children:[t.jsxs("span",{className:"font-mono text-[10.5px] text-fg-dim w-[50px] whitespace-nowrap shrink-0",children:["stage ",d.n]}),t.jsx("span",{role:"progressbar","aria-valuenow":d.doneCount,"aria-valuemin":0,"aria-valuemax":d.rows.length,className:"flex-1 h-[4px] rounded-sm bg-rule-inner overflow-hidden",children:t.jsx("span",{className:"block h-full bg-sage",style:{width:`${l}%`}})})]},d.n)})]})}const qn=[],Bn=e=>e==="running"||e==="investigating";function Hn(e){const s=sn(e),n=new Map,a=new Map;for(const r of e.stages){a.set(r.n,r.rows.length);for(const o of r.rows)n.set(o.slug,o)}const d=new Map;let l=0;const i=[];for(const r of s){const o=n.get(r);l+=o.estimateMinutes??0,d.set(o.stage,(d.get(o.stage)??0)+1),i.push({row:o,totalMinutes:l,othersInStage:0})}for(const r of i)r.othersInStage=(a.get(r.row.stage)??0)-(d.get(r.row.stage)??0);return i}function Gn({plan:e,now:s,indexBySlug:n,headChoicesBySlug:a,onRowFocused:d}){const l=f.useMemo(()=>Hn(e),[e]);return t.jsx("div",{"data-testid":"critical-path",className:"border-t border-rule-structural max-w-[640px]",children:l.map(({row:i,totalMinutes:r,othersInStage:o})=>t.jsxs("div",{"data-testid":"critical-entry","data-slug":i.slug,children:[t.jsxs("div",{className:"flex items-start",children:[t.jsx("div",{className:"flex-1 min-w-0",children:t.jsx(Zt,{row:i,elapsedMs:Bn(i.status)&&i.job.startedAt?s-Date.parse(i.job.startedAt):null,listIndex:n.get(i.slug)??0,onFocused:d,headChoices:a.get(i.slug)??qn})}),t.jsxs("span",{"data-testid":"critical-est",className:"shrink-0 h-[31px] px-3 flex items-center gap-2 font-mono text-[11.5px] text-fg-faint border-t border-rule-inner",children:[t.jsx("span",{title:"estimateMinutes",children:i.estimateMinutes?`${i.estimateMinutes}m`:"—"}),t.jsxs("span",{className:"text-fg-dim",title:"Running total along the chain",children:["Σ ",r,"m"]})]})]}),o>0&&t.jsxs("div",{"data-testid":"critical-others",className:"h-[22px] px-3 flex items-center font-mono text-[11.5px] text-fg-faint border-t border-rule-inner",children:["stage ",i.stage," · +",o," not on the critical path"]})]},i.slug))})}const Dt=1,At=1350,Wn={active:"border-l-accent",queued:"border-l-rule-structural",done:"border-l-sage",draft:"border-l-fg-faint/40 border-dashed"},Vn={active:{label:"ACTIVE",cls:"bg-accent text-white border border-accent"},queued:{label:"QUEUED",cls:"text-fg-dim border border-fg-faint"},done:{label:"DONE",cls:"text-sage-dark border border-sage"},draft:{label:"DRAFT",cls:"text-fg-faint border border-dashed border-fg-faint"}},Un=e=>String(e).padStart(2,"0");function zn({plan:e}){const s=Math.max(1,e.prdCount),n=e.doneCount/s*100,a=e.runningCount/s*100;return t.jsxs("span",{"data-testid":"plan-progress",role:"progressbar","aria-valuenow":e.doneCount,"aria-valuemin":0,"aria-valuemax":e.prdCount,className:"flex w-[160px] h-[5px] rounded-sm overflow-hidden bg-rule-inner shrink-0",children:[t.jsx("span",{className:"h-full bg-sage",style:{width:`${n}%`}}),t.jsx("span",{className:"h-full bg-accent",style:{width:`${a}%`}})]})}function Qn({plan:e,mode:s="graph",now:n,hidden:a,indexBySlug:d,headChoicesBySlug:l,onRowFocused:i,onOpenPrds:r}){var se,Y;const[o,c]=f.useState(e.status==="active"||e.status==="queued"),[p,u]=f.useState(!1),h=f.useRef(null),[x,m]=f.useState(0),[w,N]=f.useState(At),S=f.useMemo(()=>{const R=ve(e.stages,et);return R>=0?R:Math.max(0,ve(e.stages,tt))},[e.stages]);f.useLayoutEffect(()=>{if(!o)return;const R=h.current,F=(R==null?void 0:R.clientWidth)||At,j=Math.max(0,Math.min(S,e.stageCount-Math.max(1,Math.ceil(F/ce))));R!=null&&R.clientWidth&&N(R.clientWidth),R&&(R.scrollLeft=j*ce),m(j)},[o]);const y=f.useMemo(()=>{let R=null;for(const F of e.stages)for(const j of F.rows){if(!j.job.runId)continue;const $=j.job.finishedAt?Date.parse(j.job.finishedAt):0;(!R||$>R.at)&&(R={runId:j.job.runId,slug:j.slug,title:j.title,at:$})}return R},[e.stages]),O=_e((Y=(se=e.stages[0])==null?void 0:se.rows[0])==null?void 0:Y.job.cwd)??"—",k=Vn[e.status],E=Math.max(1,Math.ceil(w/ce)),D=Math.max(0,Math.min(x-Dt,e.stageCount)),P=Math.min(e.stageCount,x+E+Dt),T=R=>{const F=Math.max(0,Math.min(e.stageCount-1,R));h.current&&(h.current.scrollLeft=F*ce),m(F)},K=Math.min(e.stageCount,x+E),V=R=>{const F=R.currentTarget,j=Math.floor(F.scrollLeft/ce);j!==x&&m(j),F.clientWidth&&F.clientWidth!==w&&N(F.clientWidth)},z="h-[24px] px-3 text-[12px] font-medium text-fg border border-rule-structural rounded-sm bg-transparent hover:bg-bg-hi cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed shrink-0",J=(()=>{switch(e.status){case"active":return t.jsx("button",{type:"button","data-testid":"plan-action",title:"Pauses the WHOLE scheduler (machine-wide) — there is no per-plan pause.",onClick:()=>{window.api.schedule.pause().catch(()=>H.error("Failed to pause the scheduler"))},className:z,children:"Pause plan"});case"queued":return t.jsx("button",{type:"button","data-testid":"plan-action",title:"Fires the next scheduler batch machine-wide (force tick) — it does not target this plan.",onClick:()=>{window.api.schedule.forceTick().then(H.fromOutcome).catch(()=>H.error("Failed to fire the next batch"))},className:z,children:"Run now"});case"done":return t.jsx("button",{type:"button","data-testid":"plan-action",disabled:!y,title:y?`Open the run log of ${y.slug}, the plan's last run`:"No run log recorded for this plan",onClick:()=>u(!0),className:z,children:"View run"});case"draft":return t.jsx("button",{type:"button","data-testid":"plan-action",title:"Open the PRDs sub-view on this plan's first PRD (the PRDs view has no per-Epic filter).",onClick:()=>{var R,F;return r==null?void 0:r(((F=(R=e.stages[0])==null?void 0:R.rows[0])==null?void 0:F.slug)??null)},className:z,children:"Schedule…"})}})(),X=e.etaMs>0?` · ${Ut(e.etaMs)} left`:"";return t.jsxs("section",{"data-testid":"plan-band","data-epic-id":e.epicId??"","data-plan-status":e.status,className:`border-l-[3px] ${Wn[e.status]} border-b border-rule-structural`,children:[t.jsxs("div",{className:"h-[32px] flex items-center gap-2.5 px-3","data-testid":"plan-header",children:[t.jsx("button",{type:"button","aria-expanded":o,"aria-label":o?"Collapse plan":"Expand plan","data-testid":"plan-toggle",onClick:()=>c(R=>!R),className:"shrink-0 w-[14px] text-[11px] text-fg-faint hover:text-fg bg-transparent border-0 cursor-pointer p-0",children:o?"▾":"▸"}),t.jsx("span",{className:"font-mono text-[11.5px] text-fg-faint shrink-0",children:Un(e.index)}),t.jsx("span",{className:"font-serif text-[15px] font-bold text-fg truncate shrink-0 max-w-[320px]",title:e.epicLabel!==e.label?`${e.label} — ${e.epicLabel}`:e.label,"data-testid":"plan-label",children:e.label}),t.jsx("span",{"data-testid":"plan-chip",className:`shrink-0 rounded-sm px-1.5 py-[1px] text-[10px] font-bold tracking-wide ${k.cls}`,children:k.label}),t.jsx("span",{"aria-hidden":"true",className:"shrink-0 w-px h-[16px] bg-rule-structural"}),t.jsx("span",{className:"font-mono text-[11.5px] text-fg-faint truncate min-w-0","data-testid":"plan-meta",children:e.validateSlug!=null&&e.epicLabel!==e.label?t.jsxs(t.Fragment,{children:[O," · ",e.epicLabel," · ",e.prdCount," PRD",e.prdCount===1?"":"s"," · ",e.width," wide · ",e.stageCount," stage",e.stageCount===1?"":"s"]}):t.jsxs(t.Fragment,{children:[O," · ",e.prdCount," PRD",e.prdCount===1?"":"s",e.width>1?` · ${e.width} wide`:""," · ",e.stageCount," stage",e.stageCount===1?"":"s"]})}),t.jsx(me,{title:`${e.doneCount} done · ${e.runningCount} running · ${e.heldCount} held · ${e.blockedCount} blocked`}),t.jsxs("span",{className:"ml-auto font-mono text-[11.5px] text-fg-dim shrink-0","data-testid":"plan-progress-label",children:[e.doneCount,"/",e.prdCount,X]}),t.jsx(zn,{plan:e}),J]}),o&&s==="critical"&&t.jsx(Gn,{plan:e,now:n,indexBySlug:d,headChoicesBySlug:l,onRowFocused:i}),o&&s!=="critical"&&e.status==="active"&&t.jsx(On,{stages:e.stages,first:x,perView:E,onSeek:T}),o&&s!=="critical"&&t.jsxs("div",{className:"flex border-t border-rule-structural",children:[t.jsxs("div",{ref:h,"data-testid":"plan-stages",onScroll:V,className:"flex flex-1 min-w-0 overflow-x-auto",children:[D>0&&t.jsx("div",{"aria-hidden":"true",className:"shrink-0",style:{width:D*ce}}),e.stages.slice(D,P).map(R=>t.jsx(In,{stage:R,epicId:e.epicId,now:n,hidden:a,indexBySlug:d,headChoicesBySlug:l,onRowFocused:i},R.n)),P<e.stageCount&&t.jsx("div",{"aria-hidden":"true",className:"shrink-0",style:{width:(e.stageCount-P)*ce}})]}),t.jsx(Fn,{stages:e.stages.slice(K),onSeek:T})]}),p&&y&&t.jsx(Fe,{runId:y.runId,slug:y.slug,title:y.title||y.slug,onClose:()=>u(!1)})]})}function Yn({section:e,children:s}){const[n,a]=f.useState(!0),d=Object.entries(e.counts).map(([l,i])=>`${i} ${l.replace(/_/g," ")}`).join(" · ");return t.jsxs("div",{className:"border-t border-line","data-testid":"backlog-epic-section","data-epic-id":e.epicId??"",children:[t.jsxs("button",{type:"button",onClick:()=>a(l=>!l),className:"w-full flex items-center gap-2.5 px-[18px] py-2.5 bg-bg-elev/60 hover:bg-bg-elev text-left","aria-expanded":n,title:e.label,children:[t.jsx("span",{className:`text-fg-faint inline-flex shrink-0 transition-transform duration-150 ${n?"rotate-90":""}`,"aria-hidden":"true",children:t.jsx(nt,{name:"chevron",size:12})}),t.jsx("span",{className:"font-serif text-[14.5px] font-semibold text-fg truncate","data-testid":"backlog-epic-label",children:e.label}),t.jsxs("span",{className:"font-mono text-[11px] text-fg-faint shrink-0",children:[e.total," PRD",e.total===1?"":"s"]}),t.jsx("span",{className:"font-mono text-[11px] text-fg-faint truncate",children:d})]}),n&&s]})}const Kn=[],Jn=[],Xn={depth:0,blockers:Kn,blocked:!1,hasNeedsReviewBlocker:!1,hasMissingDep:!1,cycle:!1,parallelEligible:!1};function Zn(e){return e.missing?`${e.slug} (missing)`:e.needsReview?`${e.slug} (needs review)`:`${e.slug} (${(e.status??"unknown").replace(/_/g," ")})`}function ea(e){return e.missing?"text-accent":e.needsReview?"text-butter font-semibold":e.status==="completed"?"text-sage":"text-amber-400/90"}function ta({job:e,eta:s,elapsedMs:n,avgDurationMs:a,listIndex:d,onFocused:l,hold:i,backlog:r=Xn,headChoices:o=Jn}){const[c,p]=f.useState(!1),[u,h]=f.useState(!1),x=pe(P=>P.sessions),m=f.useMemo(()=>Ce(e,x),[e,x]),w=m.known&&m.epicId?x[m.epicId]:null,N=f.useCallback(P=>{at(P),window.dispatchEvent(new CustomEvent("sm:navigate",{detail:"terminal"}))},[]),S=e.status==="running",y=e.status==="failed";let O=null;S&&n!==null?O=`${Ee(n)} elapsed`:e.status==="completed"&&e.startedAt&&e.finishedAt?O=`took ${Se(Date.parse(e.finishedAt)-Date.parse(e.startedAt))}`:s&&(O=s);const k=e.error??null,E=y&&k?k.split(`
4
4
  `)[0]:e.status==="needs_review"&&e.verifierVerdict?$e(e.verifierVerdict):null,D=S&&n!==null?Math.min(.99,n/a):0;return t.jsxs("div",{role:"listitem",className:"border-t border-line",children:[t.jsxs("button",{type:"button","data-job-row":!0,"data-job-status":e.status,"data-job-index":d,"data-depth":r.depth,onClick:()=>p(P=>!P),onFocus:()=>l(d),style:r.depth>0?{paddingLeft:18+r.depth*20}:void 0,className:`w-full text-left grid grid-cols-[116px_1fr_auto_auto] items-center gap-4 px-[18px] py-3.5 hover:bg-bg/40 focus:outline-none focus:ring-1 focus:ring-accent focus:ring-inset ${c?"bg-bg-elev/40":""}`,"aria-expanded":c,"aria-label":`${ie(e.slug)?`PRD ${ie(e.slug)}, `:""}${e.title}, ${e.status}${O?`, ${O}`:""}`,title:e.title,children:[t.jsx(Ot,{status:e.status}),t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-baseline gap-2 text-[14.5px] font-medium text-fg leading-snug",children:[ie(e.slug)&&t.jsx(Lt,{n:ie(e.slug)}),e.title,t.jsx(Ft,{leaked:e.leakedDescendants}),t.jsx($s,{count:e.leftoverCount,truncated:e.leftoverPathsTruncated,salvagePatch:e.salvagePatch}),r.parallelEligible&&t.jsx("span",{"data-testid":"job-row-parallel-eligible",title:"No dependsOn, and nothing in this Epic depends on it — can run any time a slot is free",className:"text-[10px] font-semibold uppercase tracking-wide text-sage/90 bg-sage/10 border border-sage/30 rounded px-1.5 py-0.5",children:"parallel"})]}),r.cycle&&t.jsxs("div",{className:"text-[12.5px] mt-0.5 text-accent font-mono","data-testid":"job-row-cycle-warning",children:["⚠ dependsOn cycle — ",r.blockers.map(P=>P.slug).join(" ↔ ")||"self-referencing"]}),!r.cycle&&r.blockers.length>0&&t.jsxs("div",{className:"text-[12.5px] mt-0.5 font-mono","data-testid":"job-row-blockers",children:[t.jsx("span",{className:r.blocked||r.hasMissingDep?"text-amber-400/90":"text-fg-faint",children:r.blocked||r.hasMissingDep?"blocked by ":"depends on "}),r.blockers.map((P,T)=>t.jsxs("span",{className:ea(P),children:[T>0&&", ",Zn(P)]},P.slug))]}),E&&t.jsx("div",{className:`text-[12.5px] mt-0.5 ${y?"text-accent/80":"text-fg-faint"}`,children:E}),i&&t.jsx("div",{className:"text-[12.5px] mt-0.5 text-amber-400/90 font-mono","data-testid":"job-row-hold",children:i.dep?t.jsxs(t.Fragment,{children:["held · waiting on ",i.dep," (",i.depStatus,")"]}):t.jsxs(t.Fragment,{children:["held · ",i.reason??"launch blocked"]})}),!i&&e.status==="pending"&&e.heldReason&&t.jsxs("div",{className:"text-[12.5px] mt-0.5 text-amber-400/90 font-mono","data-testid":"job-row-held-reason",children:["held · ",e.heldReason]}),t.jsx(rt,{epicId:m.epicId,label:m.label?Kt(m.label):null,onOpen:N,testId:"job-row-prompt-session-chip",className:"mt-0.5"})]}),t.jsx(it,{cwd:e.cwd}),t.jsxs("span",{className:"inline-flex items-center gap-2.5 font-mono text-xs text-fg-faint shrink-0",children:[t.jsx(Cs,{status:e.status,overrun:e.overrun}),O,t.jsx("span",{className:`text-fg-faint inline-flex transition-transform duration-150 ${c?"rotate-90":""}`,"aria-hidden":"true",children:t.jsx(nt,{name:"chevron",size:14})})]})]}),S&&!c&&t.jsx("div",{className:"h-1 bg-line mx-[18px] mb-3 rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-accent transition-all duration-1000",style:{width:`${Math.max(4,D*100)}%`}})}),c&&t.jsxs("div",{className:"px-[18px] py-5 grid grid-cols-[repeat(auto-fit,minmax(160px,1fr))] gap-5 bg-bg-elev/50 border-t border-line",children:[t.jsxs(re,{label:"Status",children:[t.jsx(B,{k:"result",v:e.exitCode!==null?`exit ${e.exitCode}`:"—"}),t.jsx(B,{k:"state",v:e.status.replace(/_/g," ")}),e.verifierVerdict&&t.jsx(B,{k:"verdict",v:$e(e.verifierVerdict)}),e.leakedDescendants&&e.leakedDescendants.length>0&&t.jsx(B,{k:"leaked",v:qt(e.leakedDescendants),wrap:!0}),e.leftoverCount!=null&&e.leftoverCount>0&&t.jsx(B,{k:"uncommitted",v:`${e.leftoverCount} file${e.leftoverCount===1?"":"s"}${e.leftoverPathsTruncated?"+":""}: ${(e.leftoverPaths??[]).join(", ")}${e.salvagePatch?` — salvaged to ${e.salvagePatch}`:""}`,wrap:!0}),k&&t.jsx(B,{k:"error",v:k.split(`