@codemem/server 0.46.2 → 0.46.3

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.
package/static/app.js CHANGED
@@ -115,4 +115,4 @@ ${t}
115
115
  `:t}function _q(e){const[t,n]=T(!1);return at(()=>{const r=uo(_.feedQuery),i=e.current?.querySelector(".feed-detail"),o=()=>{const c=i?_S(i):"";n(!!(r&&c.toLowerCase().includes(r)))};o();const s=i?.querySelectorAll(".feed-observation-context");return s?.forEach(c=>{c.addEventListener("toggle",o)}),()=>{s?.forEach(c=>{c.removeEventListener("toggle",o)})}}),t}function wS(e){return e==="shared"?"shared":e==="private"?"private":"unknown"}function wq(e,t,n){const r=String(e.visibility||n.visibility||"").trim(),i=If(e),o=String(e.trust_state||n.trust_state||"").trim(),s=String(e.workspace_kind||n.workspace_kind||"").trim(),c=lF(e.origin_source||n.origin_source),l=["Observer","Session summary"].includes(c)?"":c,d=uF(e,n);let u="";return!i&&o!=="trusted"&&(u=o?sF(o):"Trust unknown"),{actor:dF(e),createdAtRaw:e.created_at||e.created_at_utc,device:d,detailId:`feed-detail-${t.rowKey.replace(/[^a-zA-Z0-9_-]/g,"-")}`,hasSupplementalDetail:!!(t.files.length||s||l||d),memoryId:Number(e.id||e.memory_id||0),originSource:l,ownedBySelf:i,project:String(e.project||"").trim(),relative:nA(e.created_at||e.created_at_utc),trustLabel:u,visibility:r,workspaceKind:s}}function Sq(e){const[t,n]=T(_.newItemKeys.has(e));return q(()=>{if(!t)return;const r=window.setTimeout(()=>{_.newItemKeys.delete(e),n(!1)},700);return()=>window.clearTimeout(r)},[t,e]),t}function Cq(e){const[t,n]=T(_.itemExpandState.get(e)!==!1);return{cardRef:D(null),expanded:t,isNew:Sq(e),setExpanded:n}}function Rq(e,t){const n=e.current?.querySelector(".feed-disclosure")===document.activeElement;at(()=>{n&&!t&&document.activeElement===document.body&&e.current?.focus()},[e,n,t])}async function Iq(e){e.setSelectedVisibility(e.nextVisibility),e.setSavingVisibility(!0);try{const t=await pk(e.memoryId,e.nextVisibility);t?.item&&(e.onReplace(t.item),e.onViewRefresh()),Y(e.nextVisibility==="shared"?"Shared with synced peers":"Only you can see this")}catch(t){e.setSelectedVisibility(e.previousVisibility),Y(t instanceof Error?t.message:"Failed to save visibility.","warning")}finally{e.setSavingVisibility(!1)}}async function kq(e){try{return(await Ts()).filter(t=>t&&t!==e)}catch{return[]}}function Nq(e,t){const n=t.length>80?`${t.slice(0,79).trimEnd()}…`:t;return e?`Move "${n}" from "${e}" to another project. Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`:`Assign a project to "${n}". Pick an existing project or type a new name. Every memory in the same session will be reassigned together.`}async function Pq(e){const t=await gf({title:"Assign to project",description:Nq(e.currentProject,e.title),initialValue:e.currentProject,placeholder:"Pick one or type a new project name",suggestions:e.suggestions,confirmLabel:"Move",cancelLabel:"Cancel",validate:r=>{const i=r.trim();return i?i===e.currentProject?"Already assigned to this project.":null:"Enter a project name."}});if(t==null)return;const n=t.trim();if(!(!n||n===e.currentProject)){e.setMovingProject(!0);try{const r=await fk(e.memoryId,n),i=Number(r.moved_memory_count||1);Y(i>1?`Moved ${i} memories from this session to "${r.project}".`:`Moved to "${r.project}".`),await e.onReload(),e.onViewRefresh()}catch(r){Y(r instanceof Error?r.message:"Failed to move memory.","warning")}finally{e.setMovingProject(!1)}}}async function Tq(e){const t=e.title.length>80?`${e.title.slice(0,79).trimEnd()}…`:e.title;if(await wn({autoFocusAction:"cancel",title:"Forget this memory?",description:`Forgetting "${t}". This removes the memory from active results. The underlying record remains soft-deleted for audit and sync safety.`,confirmLabel:"Forget memory",cancelLabel:"Keep memory",tone:"danger"})){e.setDeletingMemory(!0);try{await mk(e.memoryId),e.onRemove(e.memoryId),e.onViewRefresh(),await e.onReload(),Y("Memory forgotten and removed from the active feed.")}catch(n){Y(n instanceof Error?n.message:"Failed to forget memory.","warning")}finally{e.setDeletingMemory(!1)}}}function Aq(e){const[t,n]=T(!1),[r,i]=T(!1),[o,s]=T(!1),c=String(e.item.project||"").trim(),l=String(e.model.displayTitle||"this memory").trim();return{deletingMemory:r,movingProject:o,savingVisibility:t,forget:()=>Tq({memoryId:e.memoryId,onReload:e.onReload,onRemove:e.onRemove,onViewRefresh:e.onViewRefresh,setDeletingMemory:i,title:l}),moveProject:async()=>Pq({currentProject:c,memoryId:e.memoryId,onReload:e.onReload,onViewRefresh:e.onViewRefresh,setMovingProject:s,suggestions:await kq(c),title:l}),saveVisibility:d=>Iq({memoryId:e.memoryId,nextVisibility:d,onReplace:e.onReplace,onViewRefresh:e.onViewRefresh,previousVisibility:e.selectedVisibility,setSavingVisibility:n,setSelectedVisibility:e.setSelectedVisibility})}}function Eq(e){return h("div",{className:"feed-title title",dangerouslySetInnerHTML:{__html:cw(e.model.displayTitle,_.feedQuery)}})}function xq(e){return!e.searchMatch||e.renderedSearchMatch?null:h("div",{className:"feed-search-match"},h("span",{className:"feed-search-match-label"},`${e.searchMatch.label} match`),h("span",{dangerouslySetInnerHTML:{__html:cw(e.searchMatch.excerpt,_.feedQuery)}}))}function Dq(e){const{details:t}=e,n=t.memoryId>0?h(Oa,{label:`Memory database id ${t.memoryId}`,side:"top"},h(On,{label:`#${t.memoryId}`,variant:"memory-id"})):null;return h("div",{className:"feed-meta-line"},t.project?h("span",{className:"feed-project"},t.project):h("span",null,"No project"),h(Oa,{label:tA(t.createdAtRaw),side:"top"},h("span",{className:"feed-age mono"},t.relative)),h(On,{label:t.actor,variant:t.ownedBySelf?"mine":"author"}),h(On,{label:e.visibilityKnown?e.selectedVisibility:"Visibility unknown",variant:e.visibilityKnown?e.selectedVisibility:"unknown"}),n,t.trustLabel?h(On,{label:t.trustLabel,variant:"trust"}):null)}function jq(e){return e.length?h("div",{className:"feed-files"},e.map((t,n)=>h("span",{className:"feed-file",key:`${String(t)}-${n}`},String(t)))):null}function Lq(e){const t=[e.workspaceKind?h(On,{label:`Workspace ${e.workspaceKind}`,variant:"workspace"}):null,e.originSource?h(On,{label:e.originSource,variant:"source"}):null,e.device?h(On,{label:e.device,variant:"device"}):null].filter(Boolean);return t.length?h("div",{className:"feed-expanded-provenance"},t):null}function SS(e,t,n="feed-pack-facts"){return e.length?h("div",{className:n},h("div",{className:"feed-pack-facts-label"},t),EB(e)):null}function Oq(e){const{body:t,facts:n,narrative:r}=e.model.content;if(!e.model.isSessionSummary&&n.length){const i=r||t;return h(G,null,SS(n,"Key points","feed-pack-facts feed-observation-points"),i?h("details",{className:"feed-observation-context"},h("summary",{"aria-label":`Full context for ${e.model.displayTitle}`},"Full context"),Zf(i,"feed-body narrative")):null)}return h(G,null,r?Zf(r,"feed-body narrative"):null,t?Zf(t,"feed-body narrative"):null,SS(n,"Facts included in pack"))}function $q(e){return!e.expanded||!e.hasDisclosure?null:h("section",{"aria-label":`${e.model.displayTitle} content`,className:"feed-detail",id:e.details.detailId},Oq(e),jq(e.model.files),Lq(e.details))}function Mq(e){return h("div",{className:"feed-card-body"},Eq(e),!e.expanded&&e.hasDisclosure?h("div",{className:"feed-collapsed-note"},"Memory content collapsed"):null,xq(e),Dq(e),$q(e),Bq(e))}function Fq(e){if(!e.details.ownedBySelf||e.details.memoryId<=0)return null;const t=`feed-visibility-${e.details.memoryId}`,n=[...e.visibilityKnown?[]:[{disabled:!0,label:"Unknown",value:"unknown"}],{label:"Only me",value:"private"},{label:"Synced peers",value:"shared"}];return h("label",{className:"feed-visibility-label",htmlFor:t},h("span",{className:"sr-only"},"Visible to"),h(Jn,{ariaLabel:`Who can see ${e.model.displayTitle}`,contentClassName:"sync-radix-select-content feed-visibility-content",disabled:e.savingVisibility||!e.visibilityKnown,id:t,itemClassName:"sync-radix-select-item",onValueChange:r=>{const i=r==="shared"?"shared":"private";e.onSaveVisibility(i)},options:n,triggerClassName:"sync-radix-select-trigger feed-visibility-select",value:e.visibilityKnown?e.selectedVisibility:"unknown",viewportClassName:"sync-radix-select-viewport"}))}function Bq(e){return e.model.tags.length?h("footer",{className:"feed-card-footer"},h("div",{"aria-label":"Tags",className:"feed-tags"},e.model.tags.map((t,n)=>h(_y,{key:`${String(t)}-${n}`,tag:t})))):null}function qq(e){const t=Fq(e),n=e.details.ownedBySelf&&e.details.memoryId>0?h(bq,{assignProjectDisabled:e.movingProject,disabled:e.deletingMemory,onAssignProject:()=>{e.onMoveProject()},onForget:()=>{e.onForget()},title:e.model.displayTitle}):null;return h("div",{className:"feed-card-side"},h("div",{className:"feed-card-side-top"},t,e.hasDisclosure?h(Oa,{label:e.expanded?"Collapse memory":"Expand memory",side:"top"},h("button",{"aria-controls":e.details.detailId,"aria-expanded":e.expanded,"aria-label":e.expanded?"Collapse memory":"Expand memory",className:"feed-disclosure",onClick:e.onToggleDetail,type:"button"},h("svg",{"aria-hidden":"true",className:"feed-disclosure-icon",viewBox:"0 0 16 16"},h("path",{d:"m3.5 6 4.5 4 4.5-4",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"1.7"})))):null,n))}function Uq(e){return h("article",{className:`feed-item ${e.model.displayKind}${e.isNew?" new-item":""}`.trim(),"data-key":e.model.rowKey,ref:e.cardRef,tabIndex:-1},h("div",{className:"feed-kind-rail"},h(Ue,{variant:"kind",tone:e.model.displayKind},e.model.displayKind.replace(/_/g," "))),Mq(e),qq(e))}function Gq(e){return uo(_.feedQuery)&&e.displayTitle.toLowerCase().includes(uo(_.feedQuery))?null:gF(e,_.feedQuery)}function Hq(e){const[t,n]=T(wS(e));return q(()=>{n(wS(e))},[e]),{selectedVisibility:t,setSelectedVisibility:n,visibilityKnown:e==="private"||e==="shared"}}function Vq({item:e,onReplace:t,onRemove:n,onViewRefresh:r,onReload:i}){const o=aw(e),s=wq(e,o,ll(e.metadata_json)),c=Cq(o.rowKey),l=Gq(o),d=_q(c.cardRef),u=Hq(s.visibility),p=Aq({item:e,memoryId:s.memoryId,model:o,onReload:i,onRemove:n,onReplace:t,onViewRefresh:r,selectedVisibility:u.selectedVisibility,setSelectedVisibility:u.setSelectedVisibility}),f=!!(o.content.searchText||s.hasSupplementalDetail);Rq(c.cardRef,f);const m=()=>{if(!f)return;const v=!c.expanded;_.itemExpandState.set(o.rowKey,v),c.setExpanded(v)};return Uq({cardRef:c.cardRef,deletingMemory:p.deletingMemory,details:s,expanded:c.expanded,hasDisclosure:f,isNew:c.isNew,model:o,movingProject:p.movingProject,onForget:p.forget,onMoveProject:p.moveProject,onSaveVisibility:p.saveVisibility,onToggleDetail:m,savingVisibility:p.savingVisibility,searchMatch:l,renderedSearchMatch:d,selectedVisibility:u.selectedVisibility,visibilityKnown:u.visibilityKnown})}function Kq({index:e}){const t=[["w-85","w-65"],["w-85","w-40"],["w-65","w-85"]],[n,r]=t[e%t.length];return h("div",{className:"feed-skeleton-item","aria-hidden":"true"},h("div",{className:"feed-skeleton-banner"}),h("div",{className:"feed-skeleton-body"},h("div",{className:`feed-skeleton-line ${n}`}),h("div",{className:`feed-skeleton-line ${r}`}),h("div",{className:"feed-skeleton-footer"},h("div",{className:"feed-skeleton-chip w-36"}),h("div",{className:"feed-skeleton-chip w-56"}),h("div",{className:"feed-skeleton-chip"}))))}function CS(e){document.getElementById(e)?.click()}function Rl(){CS("tabBtn-health"),queueMicrotask(()=>document.getElementById("healthSystemCard")?.focus())}function zq(e){kb("all"),hp("all");const t=document.getElementById("projectFilter");if(t){t.value="",t.dispatchEvent(new Event("change",{bubbles:!0})),queueMicrotask(()=>t.focus());return}_.currentProject="",e.updateFeedView(!0),e.loadFeedData().catch(()=>{})}function Wq(){const e=_.feedProcessingStatus;if(e.kind==="pending"){const t=e.count===1?"event":"events";return{actions:[{label:"Open Health",run:Rl}],detail:"Captured work is queued. Memories will appear after processing finishes.",status:!0,title:`Processing ${e.count} ${t}.`}}return e.kind==="paused"?{actions:[{label:"Open Health",run:Rl}],detail:"New activity will not be captured until raw-event capture is enabled.",status:!0,title:"Capture is paused."}:e.kind==="unavailable"?{actions:[{label:"Open Health",run:Rl}],detail:"The Feed is connected, but processing status could not be checked.",status:!0,title:"Processing status is unavailable."}:{actions:[{label:"Open Settings",run:()=>CS("settingsButton")},{label:"Open Health",run:Rl}],detail:"Use codemem while you work. Captured memories and session summaries will appear here.",title:"No memories yet."}}function Jq(e){const t=_.feedQuery.trim();return t?{actions:[{label:"Clear search",run:()=>{e.updateFeedQuery(""),queueMicrotask(()=>document.getElementById("feedSearch")?.focus())}}],detail:"Try a broader search or clear the search to see all memories.",title:`No memories match “${t}”.`}:_.feedTypeFilter!=="all"||_.feedScopeFilter!=="all"||_.currentProject?{actions:[{label:"Clear filters",run:()=>zq(e)}],detail:"Clear the Feed and project filters to see memories from every scope.",title:"No memories match the current filters."}:Wq()}function Yq({ops:e}){const t=Jq(e);return h("div",{className:"small feed-empty-state",role:t.status?"status":void 0},h("strong",null,t.title),h("div",null,t.detail),h("div",{className:"feed-empty-actions"},t.actions.map(n=>h("button",{className:"settings-button",key:n.label,onClick:n.run,type:"button"},n.label))))}function Qq({items:e,loadingText:t,ops:n}){return t?h("div",{className:"feed-skeleton",role:"status","aria-label":t},[0,1,2,3].map(r=>h(Kq,{index:r,key:`skeleton-${r}`}))):e.length?h(G,null,e.map(r=>h(Vq,{item:r,key:Pt(r),onReplace:n.replaceFeedItem,onRemove:n.removeFeedItem,onViewRefresh:()=>n.updateFeedView(!0),onReload:n.loadFeedData}))):h(Yq,{ops:n})}function RS({id:e,active:t,options:n,onSelect:r}){return h("div",{className:"feed-toggle",id:e},n.map(({value:i,label:o})=>{const s=i===t;return h("button",{"aria-pressed":s?"true":"false",className:`toggle-button${s?" active":""}`,"data-filter":i,key:i,onClick:()=>r(i),type:"button"},o)}))}function IS(e){document.getElementById(e)?.click()}function am(e){document.querySelector(e)?.focus()}function Xq(){IS("tabBtn-health"),queueMicrotask(()=>am("#healthSystemCard"))}function Zq(){const e=document.querySelector(".feed-item button.feed-title");e?.getAttribute("aria-expanded")!=="true"&&e?.click(),e?.focus(),e&&li("inspect")}function eU(){am("#feedSearch")}function tU(e){return[{id:"capture",label:"Capture a memory",actionLabel:"Check capture health",action:Xq},{id:"inspect",label:"Inspect its details",actionLabel:"Inspect first memory",action:Zq,actionAvailable:e},{id:"find",label:"Find it again",actionLabel:"Search memories",action:eU},{id:"scope",label:"Choose project scope",actionLabel:"Choose a project",action:()=>am("#projectFilter")},{id:"settings-health",label:"Check settings or health",actionLabel:"Open Settings",action:()=>IS("settingsButton")}]}function nU({completed:e,hasMemories:t,onAction:n}){return a("ol",{className:"first-run-guide-list",children:tU(t).map(r=>{const i=e.has(r.id);return a("li",{className:i?"is-complete":void 0,children:[a("span",{className:"first-run-guide-status",children:[a("span",{"aria-hidden":"true",children:i?"✓":"○"}),a("span",{children:[a("strong",{children:r.label}),a("span",{className:"small",children:i?"Completed":"Pending"})]})]}),!i&&r.actionAvailable!==!1?a("button",{className:"settings-button",onClick:()=>n(r),type:"button",children:r.actionLabel}):null]},r.id)})})}function rU({hasMemories:e,hasQueuedEvents:t}){const[n,r]=T(Da),[i,o]=T(""),[s,c]=T(!1);if(at(()=>{c(document.querySelector(".feed-item button.feed-title")!==null)}),q(()=>{const d=()=>{const p=Da();r(p),o(`${p.completed.length} of 5 getting started steps completed.`)},u=p=>{p.key==="codemem-first-run-guide-v1"&&d()};return window.addEventListener(Nf,d),window.addEventListener("storage",u),()=>{window.removeEventListener(Nf,d),window.removeEventListener("storage",u)}},[]),q(()=>{(e||t)&&li("capture")},[e,t]),!wF(n))return null;const l=new Set(n.completed);return a("section",{"aria-labelledby":"firstRunGuideTitle",className:"first-run-guide",id:"firstRunGuide",tabIndex:-1,children:[a("div",{className:"first-run-guide-header",children:[a("div",{children:[a("h2",{id:"firstRunGuideTitle",children:"Getting started"}),a("p",{children:"Confirm capture works, then learn where to inspect and find memories."})]}),a("button",{className:"settings-button",onClick:()=>bF(),type:"button",children:"Skip getting started"})]}),a(nU,{completed:l,hasMemories:s,onAction:d=>{d.action(),o(`Ready: ${d.actionLabel}.`)}}),a("div",{"aria-live":"polite",className:"sr-only",role:"status",children:i})]})}function iU({text:e}){return h("div",{"aria-live":"polite",className:"section-meta",id:"feedMeta",role:"status"},e)}function oU({query:e,onQuery:t}){return h("input",{"aria-label":"Search memories",className:"feed-search",id:"feedSearch",onInput:n=>{t(String(n.currentTarget.value||""))},placeholder:"Search title, body, tags…",type:"search",value:e})}function aU(e,t){return!e&&!t}function sU({inspectorOpen:e,items:t,loadingText:n,onInspectorToggle:r,ops:i}){return h("div",{className:"feed-controls"},h(iU,{text:n||QF(t.length,i.hasMorePages())}),h("div",{className:"feed-controls-right"},h(oU,{query:_.feedQuery,onQuery:i.updateFeedQuery}),h(RS,{active:_.feedScopeFilter,id:"feedScopeToggle",onSelect:o=>{o!==_.feedScopeFilter&&(hp(o),i.loadFeedData().catch(()=>{}))},options:[{value:"all",label:"All"},{value:"mine",label:"My memories"},{value:"theirs",label:"Other people"}]}),h(RS,{active:_.feedTypeFilter,id:"feedTypeToggle",onSelect:o=>{o!==_.feedTypeFilter&&(kb(o),i.updateFeedView())},options:[{value:"all",label:"All"},{value:"observations",label:"Observations"},{value:"summaries",label:"Summaries"}]}),h("button",{"aria-controls":"contextInspectorPanel","aria-expanded":e,className:"settings-button feed-inspector-button",id:"contextInspectorToggle",onClick:r,type:"button"},e?"Hide Context Inspector":"Context Inspector")))}function cU({errorText:e,items:t,loadingText:n,ops:r}){const i=e?h("div",{className:"small feed-empty-state",role:"alert"},h("strong",null,e),h("div",null,"Check the viewer connection, then retry the Feed."),h("button",{className:"settings-button",onClick:()=>{r.loadFeedData().catch(()=>{})},type:"button"},"Retry")):null;return t.length===0&&i?i:h(G,null,i,h(Qq,{items:t,loadingText:n,ops:r}))}function lU({errorText:e,items:t,loadingText:n,ops:r}){const[i,o]=T(!1);return h(G,null,h(sU,{inspectorOpen:i,items:t,loadingText:n,onInspectorToggle:()=>{o(c=>!c)},ops:r}),h(XF,{open:i}),aU(n,_.viewerReconnectOpen)?h(rU,{hasMemories:t.length>0,hasQueuedEvents:_.feedProcessingStatus.kind==="pending"}):null,h("div",{className:"feed-list",id:"feedList"},h(cU,{errorText:e,items:t,loadingText:n,ops:r})))}function kS(e){return _.feedTypeFilter==="observations"?e.filter(t=>!dl(t,ll(t?.metadata_json))):_.feedTypeFilter==="summaries"?e.filter(t=>dl(t,ll(t?.metadata_json))):e}function dU(e){const t=e.map(n=>`${iw(n)}:${JSON.stringify(n)}`);return`${_.feedTypeFilter}|${_.feedScopeFilter}|${_.currentProject}|${_.viewerActorId??""}|${sa(_.feedQuery)}|${t.join("|")}`}var NS="",Wa=0,Ja=0,go=!0,yo=!0,Il=null,uU=0,Cr=null,PS=!1,TS=!1,Ya=0,sm="all",AS="",Qa=null,bo="",c4=250;function ES(e){NS=e,sm=_.feedScopeFilter,AS=_.feedQuery.trim(),bo="",Ya+=1,Wa=0,Ja=0,go=!0,yo=!0,_.lastFeedItems=[],_.pendingFeedItems=null,_.lastFeedFilteredCount=0,_.lastFeedSignature="",_.newItemKeys.clear()}function cm(){return go||yo}function pU(e){const t=Pt(e);_.lastFeedItems=_.lastFeedItems.map(n=>Pt(n)===t?e:n)}function fU(e){const t=new Set,n=r=>{const i=Number(r.id||r.memory_id||0)!==e;return i||t.add(Pt(r)),i};_.lastFeedItems=_.lastFeedItems.filter(n),Array.isArray(_.pendingFeedItems)&&(_.pendingFeedItems=_.pendingFeedItems.filter(n));for(const r of t){_.newItemKeys.delete(r),_.itemExpandState.delete(r);for(const i of Array.from(_.itemExpandState.keys()))i.startsWith(`${r}:`)&&_.itemExpandState.delete(i)}}function xS(e,t){return kS(e).some(n=>vF(n,t))&&li("find"),e.sort((n,r)=>new Date(r.created_at||0).getTime()-new Date(n.created_at||0).getTime())}async function mU(){if(!cm())return;const e=Ya;if(Il===e)return;const t=_.currentProject||"",n=_.feedQuery.trim(),r=Wa,i=Ja;Il=e;try{const[o,s]=await Promise.all([go?Hh(t,{limit:20,offset:r,scope:_.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:r}}),yo?Vh(t,{limit:50,offset:i,scope:_.feedScopeFilter,q:n||void 0}):Promise.resolve({items:[],pagination:{has_more:!1,next_offset:i}})]);if(e!==Ya||t!==(_.currentProject||"")||n!==_.feedQuery.trim())return;const c=s.items||[],l=o.items||[],d=n?l:l.filter(f=>!rw(f));_.lastFeedFilteredCount+=l.length-d.length,yo=ul(s,c.length,50),go=ul(o,l.length,20),Ja=pl(s,i+c.length),Wa=pl(o,r+l.length);const u=xS([...c,...d],n),p=ow(_.lastFeedItems,u);_.lastFeedItems=p,Cn()}finally{Il===e&&(Il=null)}}function DS(){_.activeTab==="feed"&&(Qa||Cr||cm()&&CF()&&mU())}var hU={replaceFeedItem:pU,removeFeedItem:fU,updateFeedView:e=>Cn(e),loadFeedData:()=>um(),updateFeedQuery:e=>gU(e),hasMorePages:cm};function lm(e,t){const n=document.getElementById("tab-feed");if(!n)return!1;WF(n,h(lU,{errorText:t?.errorText,items:e,loadingText:t?.loadingText,ops:hU}));const r=globalThis.lucide;return r&&!t?.loadingText&&r.createIcons(),!0}function dm(e="Loading selected project..."){lm([],{loadingText:e})}function vU(){zF(),lm(_.lastFeedItems,_.lastFeedItems.length||_.lastFeedSignature?void 0:{loadingText:"Loading memories…"}),PS||(window.addEventListener("scroll",()=>{DS()},{passive:!0}),PS=!0),TS||(document.getElementById("tab-feed")?.addEventListener("click",e=>{e.target?.closest(".feed-item button.feed-title")&&li("inspect")}),TS=!0)}function gU(e){if(e===_.feedQuery)return;const t=_.feedQuery.trim();_.feedQuery=e,e.trim()!==t&&(ES(_.currentProject||""),dm("Searching memories…"),Qa&&clearTimeout(Qa),Qa=setTimeout(()=>{Qa=null,um().catch(()=>{})},250))}function Cn(e=!1){if(!document.getElementById("tab-feed"))return;const t=window.scrollY,n=kS(_.lastFeedItems),r=dU(n),i=e||r!==_.lastFeedSignature;_.lastFeedSignature=r,i&&lm(n,{errorText:bo||void 0}),window.scrollTo({top:t}),_.viewerReconnectOpen||DS()}function jS(e,t,n,r){return LS(e,t)&&e===Ya&&n===(_.currentProject||"")&&r===_.feedQuery.trim()}function LS(e,t){return Cr?.generation===e&&Cr.requestId===t}async function um(e={}){const t=_.currentProject||"",n=_.feedScopeFilter!==sm,r=_.feedQuery.trim(),i=r!==AS;(t!==NS||n||i)&&(ES(t),dm(i?"Searching memories…":void 0));const o=Ya,s=++uU;Cr={generation:o,requestId:s};const c=!!bo;c&&(bo="",_.lastFeedItems.length>0?Cn(!0):dm(r?"Searching memories…":void 0));try{const[u,p]=await Promise.all([Hh(t,{limit:20,offset:0,scope:_.feedScopeFilter,q:r||void 0,signal:e.signal}),Vh(t,{limit:50,offset:0,scope:_.feedScopeFilter,q:r||void 0,signal:e.signal})]);if(e.signal?.aborted||!jS(o,s,t,r))return;const f=p.items||[],m=u.items||[],v=r?m:m.filter(w=>!rw(w)),b=m.length-v.length,g=xS([...f,...v],r),y=pF(_.lastFeedItems,g),S=_.lastFeedItems;if(RF(y,S)&&S.length>0){const w=new Set(S.map(Pt));y.forEach(R=>{w.has(Pt(R))||_.newItemKeys.add(Pt(R))})}_.pendingFeedItems=null,_.lastFeedItems=y,bo="",_.lastFeedFilteredCount=Math.max(_.lastFeedFilteredCount,b),yo=ul(p,f.length,50),go=ul(u,m.length,20),Ja=Math.max(Ja,pl(p,f.length)),Wa=Math.max(Wa,pl(u,m.length)),sm=_.feedScopeFilter,Cr?.generation===o&&Cr.requestId===s&&(Cr=null),Cn(c)}catch(l){if(e.signal?.aborted)return;throw jS(o,s,t,r)&&(go=!1,yo=!1,bo="Feed unavailable. Refresh and try again.",Cn(!0)),l}finally{LS(o,s)&&(Cr=null)}}function l4(e){return e}function yU(e){const t=new Date(e.periodStart),n=new Date(e.periodEnd),r=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric"}),i=new Intl.DateTimeFormat(void 0,{month:"short",day:"numeric",year:"numeric"});return t.getFullYear()===n.getFullYear()?[r.format(t),i.format(n)]:[i.format(t),i.format(n)]}function bU(e,t){const n=100*e/t,r=Math.round(n);return n>0&&r===0?"<1%":n<100&&r===100?">99%":`${r}%`}function _U(e){if(e.freshEvaluations===0)return[{label:"Recalls checked",value:0,tooltip:"No automatic recalls were checked for repeated memories in this period.",icon:"activity"},{label:"Not checked",value:e.unmeasuredAttempts,tooltip:`Codemem could not check ${e.unmeasuredAttempts.toLocaleString()} automatic recalls for repeated memories, so savings are unknown.`,icon:"circle-help"}];const t=bU(e.evaluationsWithDuplicates,e.freshEvaluations),n=e.missingRetainedMetadata>0||e.invalidRetainedMetadata>0||e.packMetadataGaps>0;return[{label:"Recalls with repeats",value:t,tooltip:`Codemem removed repeated memories from ${e.evaluationsWithDuplicates.toLocaleString()} of ${e.freshEvaluations.toLocaleString()} automatic recalls.`,icon:"filter"},{label:"Memories skipped",value:e.duplicatesOmitted,tooltip:`Codemem left out ${e.duplicatesOmitted.toLocaleString()} memories that were already in your conversation, out of ${e.candidateItems.toLocaleString()} considered.`,icon:"minus-circle"},{label:"Repeated tokens removed",value:`~${aa(e.estimatedTokensAvoided)}`,tooltip:`About ${e.estimatedTokensAvoided.toLocaleString()} tokens were left out because they repeated information already in your conversation.`,icon:"trending-down"},{label:"Recalls checked",value:e.freshEvaluations,tooltip:`Codemem checked ${e.freshEvaluations.toLocaleString()} automatic recalls for repeated memories. ${e.unmeasuredAttempts.toLocaleString()} more could not be checked.${n?" Some results may be incomplete.":""}`,icon:"activity"}]}function wU(e){if(!e||e.availability==="unavailable")return h("p",{class:"section-meta"},"Automatic recall details aren’t available. Update Codemem and refresh this page.");const[t,n]=yU(e);return h(G,null,h("div",{class:"grid-2 automatic-recall-grid"},_U(e).map(r=>h(OS,{...r,key:`${r.label}-${r.icon}`}))),h("p",{class:"automatic-recall-meta"},h("time",{dateTime:e.periodStart},t),"–",h("time",{dateTime:e.periodEnd},n),` · Based on up to ${e.windowLimit.toLocaleString()} recent automatic recalls across all projects.${e.freshEvaluations===0?" No recalls were checked, so savings are unknown.":""}`))}function SU(e,t){e&&(ke(h(ml,null,h("details",{class:"automatic-recall"},h("summary",null,"Automatic recall"),h("section",{"aria-label":"Automatic recall measurements"},wU(Kh(t))))),e),Xa())}function _o(e,t){return t.error?`${e} ${t.error}`:e}function kl(e,t){return t.recommended_action?`${e} ${t.recommended_action}`:e}function CU(e){return e.unavailable?{label:"Update check unavailable",title:kl(_o("Could not check for updates.",e),e),tone:"badge-offline"}:e.install_kind==="repo-dev"?{label:`Source build · ${e.current_version}`,title:kl(_o(`Running from repository source. Package metadata version: ${e.current_version}. Registry releases do not describe the checked-out source revision.`,e),e),tone:"health-update-source"}:e.channel?e.latest_version?e.update_available?{label:`Update available · ${e.latest_version}`,title:_o(`Codemem ${e.latest_version} is available. Installed version: ${e.current_version}.`,e),tone:"badge-online",showCopy:!!e.recommended_action}:{label:`Up to date · ${e.current_version}`,title:_o(`Codemem ${e.current_version} is up to date. You are running the latest ${e.channel==="latest"?"stable":e.channel} release.`,e),tone:"badge-online"}:{label:"Update check unavailable",title:kl(_o("Could not check for updates.",e),e),tone:"badge-offline"}:{label:"Unsupported channel",title:kl(_o("The installed version is not on a supported release channel.",e),e),tone:"badge-offline"}}function RU({command:e}){return h("code",{class:"health-update-command",id:"healthUpdateCommand"},e)}function IU({status:e}){const t=CU(e),n=t.tone!=="badge-online"||e.stale||!!e.error,r=e.stale?`${t.title} ${e.error?`This result is stale because a fresh check failed: ${e.error}`:"This result is cached and may be stale."}`:t.title;let i=null;function o(){!e.recommended_action||!i||Yi(e.recommended_action,i)}return h("section",{class:"health-update-banner",role:"status","aria-atomic":"true","aria-label":"Codemem update status"},h("i",{"aria-hidden":"true","data-lucide":"circle-arrow-up",class:"health-update-icon"}),h(Ue,{variant:"badge",tone:t.tone,title:t.title},t.label),n?h("span",{class:"health-update-detail"},r):null,t.showCopy&&e.recommended_action?h(RU,{command:e.recommended_action}):null,e.stale?h(Ue,{variant:"badge",title:e.error?`This result is stale because a fresh check failed: ${e.error}`:"This result is cached and may be stale."},"Cached"):null,t.showCopy&&e.recommended_action?h("button",{"aria-describedby":"healthUpdateCommand",class:"settings-button health-update-copy-button",onClick:o,ref:s=>{i=s},title:e.recommended_action,type:"button"},"Copy command"):null)}function kU(e,t){e&&(e.hidden=!t,ke(t?h(IU,{status:t}):null,e))}function NU({label:e,value:t,detail:n,icon:r,className:i,title:o,loading:s}){const c=h("div",{class:`stat${i?` ${i}`:""}${o?" has-tooltip":""}`},r?h("span",{class:"health-icon-slot",key:`${r}-${s?"loading":"static"}`},h("i",{"aria-hidden":"true","data-lucide":r,class:`stat-icon${s?" health-loading-icon":""}`})):null,h("div",{class:"stat-content"},h("div",{class:"value"},t),h("div",{class:"label"},e),n?h("div",{class:"small"},n):null));return o?h(Oa,{label:o},c):c}function PU({item:e}){let t=null,n=null;const r=e.actionLabel||"Run";async function i(){if(!(!e.action||!t)){t.disabled=!0,t.textContent="Running…";try{await e.action(t)}catch{}t.disabled=!1,t.textContent=r}}function o(){!e.command||!n||Yi(e.command,n)}return h("div",{class:"health-action"},h("div",{class:"health-action-text"},e.label,e.command?h("span",{class:"health-action-command"},e.command):null),h("div",{class:"health-action-buttons"},e.action?h("button",{class:"settings-button",onClick:i,ref:s=>{t=s}},r):null,e.command?h("button",{class:"settings-button health-action-copy",onClick:o,ref:s=>{n=s}},"Copy"):null))}function TU(e){return typeof e=="number"?e.toLocaleString():e==null?"n/a":String(e)}function OS({label:e,value:t,icon:n,tooltip:r}){const i=h("div",{class:`stat${r?" has-tooltip":""}`,tabIndex:r?0:void 0},h("i",{"data-lucide":n,class:"stat-icon"}),h("div",{class:"stat-content"},h("div",{class:"value"},TU(t)),h("div",{class:"label"},e)));return r?h(Oa,{label:r},i):i}function $S(e,t){e&&ke(h(ml,null,t.map(n=>h(OS,{...n,key:`${n.label}-${n.icon}`}))),e)}function Nl(e,t){e&&ke(h(G,null,t),e)}function Xa(){const e=globalThis.lucide;e&&typeof e.createIcons=="function"&&e.createIcons()}function AU({label:e,value:t,state:n,title:r}){return h("div",{class:"health-tile",title:r},h("span",{class:"health-tile-label"},e),h("span",{class:"health-tile-value"},h(rn,{state:n,size:6}),t))}function MS(e,t,n){e&&ke(h(ml,null,h("div",{class:"health-tile-grid"},t.map(r=>h(AU,{...r,key:r.key}))),n.length?h("div",{class:"grid-2 health-maintenance-grid"},n.map(r=>h(NU,{...r,key:r.key??r.label}))):null),e)}function EU({label:e,message:t,stale:n,state:r,statusClass:i}){return h("div",{class:"health-status-summary"},h(rn,{state:r,size:8}),h("div",{class:"health-status-copy"},h("strong",{class:`health-status-word ${i}`},e),h("div",{class:"health-status-meta"},h("div",{class:"section-meta",id:"healthMeta",role:"status","aria-live":"polite","aria-atomic":"true"},h("span",{class:"sr-only"},`${e} · `),t,n?h("span",{class:"sr-only"}," · Stale data"):null),n?h(Ue,{variant:"badge"},"Stale data"):null)))}function FS(e,t){e&&ke(h(EU,t),e)}function BS(e,t){if(e){if(!t.length){e.hidden=!0,ke(null,e);return}e.hidden=!1,ke(h(G,null,t.slice(0,3).map((n,r)=>h(PU,{item:n,key:`${n.label}-${r}`}))),e)}}var qS="codemem-settings-advanced",pm="gpt-6-luna",US="claude-4.5-haiku",xU=[{value:"observer",label:"Connection"},{value:"queue",label:"Processing"},{value:"sync",label:"Device Sync"}],Pl={claudeCommand:"claude_command",codexCommand:"codex_command",observerProvider:"observer_provider",observerModel:"observer_model",observerTierRoutingEnabled:"observer_tier_routing_enabled",observerSimpleModel:"observer_simple_model",observerSimpleTemperature:"observer_simple_temperature",observerReasoningEffort:"observer_reasoning_effort",observerReasoningSummary:"observer_reasoning_summary",observerRichModel:"observer_rich_model",observerRichTemperature:"observer_rich_temperature",observerRichReasoningEffort:"observer_rich_reasoning_effort",observerRichReasoningSummary:"observer_rich_reasoning_summary",observerRichMaxOutputTokens:"observer_rich_max_output_tokens",observerRuntime:"observer_runtime",observerAuthSource:"observer_auth_source",observerAuthFile:"observer_auth_file",observerAuthCommand:"observer_auth_command",observerAuthTimeoutMs:"observer_auth_timeout_ms",observerAuthCacheTtlS:"observer_auth_cache_ttl_s",observerHeaders:"observer_headers",observerMaxChars:"observer_max_chars",packObservationLimit:"pack_observation_limit",packSessionLimit:"pack_session_limit",rawEventsSweeperIntervalS:"raw_events_sweeper_interval_s",syncEnabled:"sync_enabled",syncHost:"sync_host",syncPort:"sync_port",syncInterval:"sync_interval_s",syncMdns:"sync_mdns",syncCoordinatorUrl:"sync_coordinator_url",syncCoordinatorGroup:"sync_coordinator_group",syncCoordinatorTimeout:"sync_coordinator_timeout_s",syncCoordinatorPresenceTtl:"sync_coordinator_presence_ttl_s"},DU=new Set(["claude_command","codex_command","observer_base_url","observer_auth_file","observer_auth_command","observer_headers","sync_coordinator_url"]),jU={claudeCommand:"",codexCommand:"",observerProvider:"",observerModel:"",observerTierRoutingEnabled:!1,observerSimpleModel:"",observerSimpleTemperature:"",observerReasoningEffort:"",observerReasoningSummary:"",observerRichModel:"",observerRichTemperature:"",observerRichReasoningEffort:"",observerRichReasoningSummary:"",observerRichMaxOutputTokens:"",observerRuntime:"api_http",observerAuthSource:"auto",observerAuthFile:"",observerAuthCommand:"",observerAuthTimeoutMs:"",observerAuthCacheTtlS:"",observerHeaders:"",observerMaxChars:"",packObservationLimit:"",packSessionLimit:"",rawEventsSweeperIntervalS:"",syncEnabled:!1,syncHost:"",syncPort:"",syncInterval:"",syncMdns:!1,syncCoordinatorUrl:"",syncCoordinatorGroup:"",syncCoordinatorTimeout:"",syncCoordinatorPresenceTtl:""};function fm(e){return String(e||"").replace(/_/g," ")}function Tl(e){const t=e.filter(n=>typeof n=="string"&&n.trim());return t.length===0?"":t.length===1?t[0]:t.length===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[t.length-1]}`}function LU(e){switch(e){case"anthropic_consumer":return"OAuth (Claude Max/Pro)";case"codex_consumer":return"OAuth (ChatGPT subscription)";case"sdk_client":return"API key";case"api_direct":return"Direct API key";case"opencode_v2":return"OpenCode account";case"claude_sidecar":return"Local Claude session";case"codex_sidecar":return"Local Codex session";case"opencode_run":return"OpenCode sidecar";default:return e||"none"}}function OU(e){const t=[];return e.oauth&&t.push("OAuth"),e.api_key&&t.push("API key"),e.env_var&&t.push("env var"),t.length?t.join(", "):"none"}function $U(e){if(typeof e!="string"||!e.trim())return"Unknown time";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}var MU=["opencode","claude","codex","pi"];function GS(){return Tl([...MU])}function FU(){try{return globalThis.localStorage?.getItem(qS)==="1"}catch{return!1}}function BU(e){try{globalThis.localStorage?.setItem(qS,e?"1":"0")}catch{}}function Gt(e,t){return typeof e=="object"&&e!==null&&Object.hasOwn(e,t)}function Ce(e,t,n){if(Gt(t,n))return t[n];if(Gt(e,n))return e[n]}function Pe(e){return e==null?"":String(e)}function Al(e){if(typeof e=="boolean")return e;if(typeof e=="number")return e!==0;if(typeof e=="string"){const t=e.trim().toLowerCase();if(!t||["0","false","no","off"].includes(t))return!1;if(["1","true","yes","on"].includes(t))return!0}return!!e}function qU(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function UU(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function Ye(e){const t=e.trim();return t===""?"":t}function GU(e,t,n){return n?{model:n,source:"Configured"}:e==="claude_sidecar"?{model:US,source:"Recommended (local Claude session)"}:e==="codex_sidecar"?{model:pm,source:"Recommended (local Codex session)"}:t==="anthropic"?{model:US,source:"Recommended (Anthropic provider)"}:t==="opencode"?{model:`opencode/${pm}`,source:"Recommended (OpenCode Zen provider)"}:t&&t!=="openai"?{model:"provider default",source:"Recommended (provider default)"}:{model:pm,source:"Recommended (direct API)"}}function HU(e,t){const n=e??{};switch(t){case"claude_command":{const r=n.claude_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(o=>{if(typeof o!="string")return;const s=o.trim();s&&i.push(s)}),i}case"codex_command":{const r=n.codex_command;if(!Array.isArray(r))return[];const i=[];return r.forEach(o=>{if(typeof o!="string")return;const s=o.trim();s&&i.push(s)}),i}case"observer_provider":case"observer_model":case"observer_simple_model":case"observer_reasoning_effort":case"observer_reasoning_summary":case"observer_rich_model":case"observer_rich_reasoning_effort":case"observer_rich_reasoning_summary":case"observer_auth_file":case"sync_host":case"sync_coordinator_url":case"sync_coordinator_group":return Ye(Pe(n[t]));case"observer_runtime":return Ye(Pe(n.observer_runtime));case"observer_auth_source":return Ye(Pe(n.observer_auth_source));case"observer_auth_command":{const r=n.observer_auth_command;return Array.isArray(r)?r.filter(i=>typeof i=="string"):[]}case"observer_headers":{const r=n.observer_headers;if(!r||typeof r!="object"||Array.isArray(r))return{};const i={};return Object.entries(r).forEach(([o,s])=>{typeof o=="string"&&o.trim()&&typeof s=="string"&&(i[o.trim()]=s)}),i}case"observer_auth_timeout_ms":case"observer_max_chars":case"observer_simple_temperature":case"observer_rich_temperature":case"observer_rich_max_output_tokens":case"pack_observation_limit":case"pack_session_limit":case"raw_events_sweeper_interval_s":case"sync_port":case"sync_interval_s":{if(!Gt(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r!==0?r:""}case"sync_coordinator_timeout_s":case"sync_coordinator_presence_ttl_s":{if(!Gt(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)&&r>0?r:""}case"observer_auth_cache_ttl_s":{if(!Gt(n,t))return"";const r=Number(n[t]);return Number.isFinite(r)?r:""}case"sync_enabled":case"sync_mdns":case"observer_tier_routing_enabled":return Al(n[t]);default:return Gt(n,t)?n[t]:""}}function VU(e,t,n){const r={...e};return Object.keys(n).forEach(i=>{Gt(r,i)&&(r[i]=HU(t,i))}),r}function mm(e,t){let n=e.events_global;return t&&(n=e.events_filtered??e.events),n.find(r=>r.event==="pack")??null}var HS="scope_id_backfill",KU=new Set(["error","needs_attention","stopped","degraded","stale","offline-peers","rebootstrapping"]),zU=new Set(["starting","stopping"]),WU={"offline-peers":"Offline peers",needs_attention:"Needs attention",rebootstrapping:"Rebootstrapping"};function VS(){const e=document.getElementById("healthDot");e&&(e.className="health-dot status-unknown",e.title="Open Health to check status");const t=document.getElementById("metaLine");t&&Nl(t,"")}function JU(){const e=document.getElementById("healthGrid"),t=document.getElementById("healthStatus");return!e||!t?null:{healthGrid:e,healthStatus:t,healthActions:document.getElementById("healthActions"),healthDot:document.getElementById("healthDot")}}function YU(e,t){const n=[`${e} ${e===1?"issue":"issues"}`];return e>0&&t.length>0&&n.push(t.join(", ")),n.join(" · ")}function QU(e){return e==="status-healthy"?"online":e==="status-degraded"?"degraded":e==="status-attention"?"attention":"unknown"}function XU(e,t){return e>=60?{label:"Attention",className:"status-attention"}:e>=25?{label:"Degraded",className:"status-degraded"}:t?{label:"Stale",className:"status-unknown"}:{label:"Healthy",className:"status-healthy"}}function ZU(e){return WU[e]??by(e)}function e2(e){const t=new Map,n=new Set(e.map(r=>r.peer_device_id));for(const r of _.lastSyncAttempts){if(!r||typeof r!="object")continue;const i=r,o=i.peer_device_id;if(typeof o!="string"||!n.has(o)||t.has(o))continue;const s=typeof i.finished_at=="string"?Date.parse(i.finished_at):NaN,c=Date.now()-s;!Number.isFinite(c)||c<0||c>6e5||t.set(o,i.status==="error")}return new Set([...t].filter(([,r])=>r).map(([r])=>r))}function KS(e,t){return[...new Set(e.filter(t).map(n=>n.name||n.peer_name||n.display_name||"").map(n=>n.trim().slice(0,60)).filter(Boolean))].sort((n,r)=>n.localeCompare(r))}function t2(e,t){return e.status?.recent_failed_attempt===!0||e.status?.peer_state==="degraded"||!!e.has_error||!!(e.peer_device_id&&t.has(e.peer_device_id))}function n2(e,t){return t.size>0||e.some(n=>n.status?.recent_failed_attempt===!0)}function r2(){const e=_.lastSyncStatus??{},t=String(e.daemon_state||"unknown"),n=t==="disabled"||e.enabled===!1,r=Array.isArray(_.lastSyncPeers)?_.lastSyncPeers:[],i=e2(r),o=Gi(e.last_sync_at||e.last_sync_at_utc||null);return{syncState:t,syncIssueCode:e.daemon_issue_code??null,syncStateLabel:ZU(t),syncDisabled:n,syncOfflinePeers:t==="offline-peers",syncNoPeers:!n&&r.length===0,syncAgeSeconds:o,syncLooksStale:o!==null&&o>7200,syncRecentlyOk:o!==null&&o<=300,syncHasRecentFailedAttempt:n2(r,i),syncProblemPeers:KS(r,s=>t2(s,i)),syncOfflinePeersNames:KS(r,s=>s.status?.peer_state==="offline")}}function i2(e,t,n){const r=mm(t,t.events_filtered!=null),i=t.recent_packs[0]?.created_at??null,o=r?Fu(r.total_tokens_saved,r.total_tokens_read):"n/a",s=e.maintenance_jobs;return{maintenanceJobs:s,scopeBackfillJob:s.find(c=>c.kind===HS),hasFailedMaintenance:s.some(c=>c.status==="failed"),hasLowTagCoverage:e.database.active_memory_items>0&&e.database.tags_coverage<.7,rawPending:n.pending,erroredBatches:e.reliability?.counts.errored_batches??0,hasReliability:e.reliability!==void 0,flushSuccessRate:e.reliability?.rates.flush_success_rate??1,droppedRate:e.reliability?.rates.dropped_event_rate??0,reductionLabel:o,reductionPercent:iA(o),hasPackUsage:r!==null,lastPackAt:i,packAgeSeconds:Gi(i),...r2(),hasBacklog:n.pending>=200}}function Ke(e,t,n){e.score+=t,e.drivers.push(n)}function o2(e,t){t.rawPending>=1e3?Ke(e,40,"high raw-event backlog"):t.rawPending>=200&&Ke(e,24,"growing raw-event backlog"),t.erroredBatches>0&&t.rawPending>=200&&Ke(e,t.erroredBatches>=5?10:6,"batch errors during backlog pressure"),t.flushSuccessRate<.95&&Ke(e,20,"lower flush success"),t.droppedRate>.02?Ke(e,24,"high dropped-event rate"):t.droppedRate>.005&&Ke(e,10,"non-trivial dropped-event rate")}function a2(e,t){t.syncState==="error"&&Ke(e,36,t.syncIssueCode==="coordinator_timeout"?"coordinator sync requests timed out":"background sync failed"),t.syncState==="needs_attention"&&Ke(e,40,"sync needs manual attention"),t.syncState==="stopped"&&Ke(e,22,"sync daemon stopped"),t.syncState==="stale"&&Ke(e,20,"sync daemon stale"),t.syncState==="rebootstrapping"&&Ke(e,20,"sync daemon rebootstrapping"),t.syncState==="degraded"&&(!t.syncRecentlyOk||t.syncHasRecentFailedAttempt||t.syncProblemPeers.length>0)&&Ke(e,t.syncRecentlyOk?26:20,"sync with paired devices failed"),t.syncState==="ok"&&t.syncHasRecentFailedAttempt&&Ke(e,26,"sync with paired devices failed")}function s2(e,t){if(t.syncOfflinePeers){Ke(e,4,"all peers currently offline"),t.syncLooksStale&&Ke(e,4,"offline peers and sync not recent");return}if(t.syncLooksStale){Ke(e,26,"sync looks stale");return}t.syncAgeSeconds!==null&&t.syncAgeSeconds>1800&&Ke(e,12,"sync not recent")}function c2(e){const t={score:0,drivers:[]};return o2(t,e),e.hasLowTagCoverage&&Ke(t,8,"low tag coverage"),e.hasFailedMaintenance&&Ke(t,30,"maintenance job failed"),!e.syncDisabled&&(!e.syncNoPeers||e.syncState==="error")&&(a2(t,e),s2(t,e)),e.reductionPercent!==null&&e.reductionPercent<10&&Ke(t,8,"low retrieval reduction"),e.packAgeSeconds!==null&&e.packAgeSeconds>86400&&Ke(t,12,"memory pack activity is old"),t}function l2(e){const t=Number(e.progress?.current||0),n=typeof e.progress?.total=="number"?e.progress.total:null,r=String(e.progress?.unit||"items");if(!n||n<=0)return`${t.toLocaleString()} ${r}`;const i=Math.round(100*t/n);return`${t.toLocaleString()}/${n.toLocaleString()} ${r} (${i}%)`}function d2(e){const t=l2(e),n=String(e.title||"Maintenance"),r=e.kind===HS;let i=t,o=r?"One-time upgrade backfill; totals include memories and replication ops":void 0,s="loader",c=r?`${n} in progress; inspect with codemem maintenance status`:`${n} in progress`;return e.status==="failed"?(i="Failed",o=String(e.error||"unknown error").trim(),s="alert-triangle",c=`Error: ${e.error||"unknown"}`):e.status==="completed"&&(i="Complete",o=r?`${t} · one-time Sharing-domain upgrade finished`:t,s="check-circle",c=`${n} finished`),{key:String(e.kind||e.title||"background-maintenance"),label:String(e.title||e.kind||"Background maintenance"),value:i,detail:o,icon:s,className:e.status==="failed"?"status-attention":void 0,title:c}}function u2(e){if(!e.hasReliability)return Qe("pipeline","Pipeline",`${e.rawPending>0?`${e.rawPending.toLocaleString()} pending · `:""}Reliability unknown`,e.rawPending>0?"degraded":"unknown","Raw-event queue pressure and flush reliability");const t=e.flushSuccessRate<.95||e.droppedRate>.005;if(e.rawPending===0&&!t)return Qe("pipeline","Pipeline","Queue clear","online","Raw-event queue pressure and flush reliability");const n=e.rawPending>0?`${e.rawPending.toLocaleString()} pending · `:"";return e.droppedRate>.02?Qe("pipeline","Pipeline",`${n}Events dropped`,"attention","Raw-event queue pressure and flush reliability"):t?Qe("pipeline","Pipeline",`${n}Reliability degraded`,"degraded","Raw-event queue pressure and flush reliability"):Qe("pipeline","Pipeline",`${e.rawPending.toLocaleString()} pending`,"degraded","Raw-event queue pressure and flush reliability")}function p2(e){return e.syncDisabled?Qe("sync","Sync","Off","unknown","Daemon state and sync recency"):e.syncState==="unknown"?Qe("sync","Sync","Unknown","unknown","Daemon state and sync recency"):e.syncNoPeers&&e.syncState!=="error"?Qe("sync","Sync","No peers","unknown","Daemon state and sync recency"):e.syncState==="ok"&&e.syncHasRecentFailedAttempt?Qe("sync","Sync","Degraded","degraded","Daemon state and sync recency"):e.syncState==="degraded"&&e.syncRecentlyOk&&!e.syncHasRecentFailedAttempt&&e.syncProblemPeers.length===0?Qe("sync","Sync","Syncing","online","Daemon state and sync recency"):KU.has(e.syncState)?Qe("sync","Sync",e.syncStateLabel,"degraded","Daemon state and sync recency"):zU.has(e.syncState)?Qe("sync","Sync",e.syncStateLabel,"unknown","Daemon state and sync recency"):e.syncLooksStale?Qe("sync","Sync","Stale","degraded","Daemon state and sync recency"):Qe("sync","Sync","On","online","Daemon state and sync recency")}function f2(e){if(!e.hasPackUsage)return Qe("retrieval","Retrieval","No packs yet","unknown","Reduction from memory reuse across recent usage");if(e.reductionPercent===null)return Qe("retrieval","Retrieval","Unknown","unknown","Reduction is unavailable for the recorded pack usage");const t=e.reductionPercent!==null&&e.reductionPercent<10;return Qe("retrieval","Retrieval",e.reductionLabel,t?"degraded":"online","Reduction from memory reuse across recent usage")}function m2(e){if(!e.lastPackAt)return Qe("freshness","Data freshness",e.hasPackUsage?"Unknown":"No packs yet","unknown","Recency is unknown when pack usage exists outside the recent activity window");if(e.packAgeSeconds===null)return Qe("freshness","Data freshness","Unknown","unknown","The last memory pack timestamp is unavailable");const t=e.packAgeSeconds!==null&&e.packAgeSeconds>86400;return Qe("freshness","Data freshness",oa(e.packAgeSeconds),t?"degraded":"online","Recency of last memory pack activity")}function Qe(e,t,n,r,i){return{key:e,label:t,value:n,state:r,title:i}}function h2(e){return[u2(e),p2(e),f2(e),m2(e)]}function v2(e){return e.hasBacklog?[{label:"Pipeline needs attention. Check queue health first.",command:"codemem db raw-events-status",action:t=>ur({subsystem:"capture",trigger:t}),actionLabel:"View diagnostics"},{label:`Then retry failed batches for impacted sessions (${GS()}).`,command:"codemem db raw-events-retry"}]:e.syncState==="stopped"?[{label:"Sync daemon is stopped. Start the background service.",command:"codemem serve start"}]:e.syncDisabled||e.syncNoPeers&&e.syncState!=="error"?[]:e.syncState==="degraded"&&e.syncRecentlyOk&&!e.syncHasRecentFailedAttempt&&e.syncProblemPeers.length===0?[]:["error","degraded","offline-peers","stale","needs_attention"].includes(e.syncState)||e.syncState==="ok"&&e.syncHasRecentFailedAttempt||e.syncLooksStale?b2(e):[]}function zS(e){const t=e.slice(0,2).join(", ");return e.length>2?`${t} +${e.length-2} more`:t}function g2(e,t){return e.syncIssueCode==="coordinator_timeout"?"Coordinator sync requests timed out. Check the coordinator connection.":e.syncIssueCode==="coordinator_error"?"Coordinator enrollment failed. Review sync diagnostics before retrying.":`Background sync reported an unresolved error.${t?` Check sync with ${t}.`:""}`}function y2(e){const t=zS(e.syncProblemPeers);if(e.syncState==="error")return g2(e,t);if(e.syncState==="offline-peers"){const n=zS(e.syncOfflinePeersNames);return`All paired devices are offline${n?`: ${n}`:""}. Check those devices' connections.`}return e.syncState==="degraded"||e.syncState==="ok"&&e.syncHasRecentFailedAttempt?t?`Sync with ${t} is failing. Other devices may still sync.`:"Some device sync attempts are failing.":e.syncState==="needs_attention"?"Sync requires manual attention.":"Paired devices have not synced recently."}function b2(e){return[{label:y2(e),command:"codemem sync doctor",action:t=>ur({subsystem:"sync",trigger:t}),actionLabel:"View diagnostics"}]}function _2(e,t){!t||e.length>=3||e.push({label:"Background maintenance failed. Review recent safe failure evidence.",command:"codemem maintenance status",action:n=>ur({severity:"error",subsystem:"maintenance",trigger:n}),actionLabel:"View diagnostics"})}function w2(e){const t=v2(e);_2(t,e.hasFailedMaintenance),e.hasLowTagCoverage&&t.length<2&&t.push({label:"Tag coverage is low. Preview backfill impact.",command:"codemem db backfill-tags --dry-run"});const n=e.scopeBackfillJob?.status!=="completed";return e.scopeBackfillJob&&n&&t.length<3&&t.push({label:"Sharing-domain upgrade backfill is expected one-time work. Inspect progress if startup feels busy.",command:"codemem maintenance status"}),t}function WS(e,t){e&&(e.className=`health-dot ${t.className}`,e.title=t.label)}function S2(e,t,n,r,i){const o=w2(t),s=t.maintenanceJobs.map(d2);WS(e.healthDot,r),MS(e.healthGrid,h2(t),s),BS(e.healthActions,o),FS(e.healthStatus,{label:r.label,message:YU(n.drivers.length,n.drivers),stale:i,state:QU(r.className),statusClass:r.className}),Xa()}function hm(){const e=JU();if(!e)return;kU(document.getElementById("healthUpdateBanner"),_.lastUpdateStatus);const t=Bn(_.healthStats),n=Bn(_.healthUsage,_.currentProject),r=Bn(_.healthRawEvents);if(!t||!n||!r){C2(e);return}const i=i2(t,n,r),o=c2(i),s=[_.healthStats,_.healthUsage,_.healthRawEvents].some(c=>Ic(c));S2(e,i,o,XU(o.score,s),s)}function C2(e){const t=[_.healthStats,_.healthUsage,_.healthRawEvents],n=t.some(c=>c.status==="failed"),r=t.some(c=>c.status==="loading"),i=r&&!n;let o="Not loaded",s="Open or refresh Health to load status.";n?(o="Unavailable",s="Some health data failed to load. Refresh Health to try again."):r&&(o="Loading",s="Loading health data…"),MS(e.healthGrid,[],[]),BS(e.healthActions,[]),FS(e.healthStatus,{label:o,message:s,stale:!1,state:i?"syncing":"unknown",statusClass:"status-unknown"}),WS(e.healthDot,{label:o,className:"status-unknown"}),Xa()}function R2(){const e=document.getElementById("sessionGrid"),t=document.getElementById("sessionMeta");if(!e||!t)return;const n=Bn(_.healthUsage,_.currentProject),r=Bn(_.healthSession,_.currentProject),{latestPack:i,packCount:o,packLine:s}=I2(n),c=i?.created_at||"",l=c?`Last pack: ${lr(c)}`:"",d=_.currentProject?"Project":"All projects",u=k2(r,_.healthSession.status==="failed"),p=P2(i,o),f=N2(n,r)?"Showing stale data":"";Nl(t,[d,s,l,u,f].filter(Boolean).join(" · ")),$S(e,p),Xa()}function I2(e){if(!e)return{latestPack:null,packCount:null,packLine:"Pack totals unavailable"};const t=e.events.find(n=>n.event==="pack")?.count??0;return{latestPack:e.recent_packs[0]??null,packCount:t,packLine:t?`${t} packs`:"No packs yet"}}function k2(e,t){return e?`${e.total.toLocaleString()} stored items`:t?"Stored-item totals unavailable":""}function N2(e,t){return!!e&&Ic(_.healthUsage,_.currentProject)||!!t&&Ic(_.healthSession,_.currentProject)}function P2(e,t){const n=e?.metadata_json||{},r=e?.tokens_read??0,i=e?.tokens_saved??0,o=n.exact_duplicates_collapsed??0,s=Fu(i,r);let c="n/a";return e&&(c=n.exact_dedupe_enabled?"On":"Off"),[{label:"Last pack savings",value:e?`${aa(i)} (${s})`:"n/a",tooltip:e?`Estimate: ${i.toLocaleString()} saved`:void 0,icon:"trending-up"},{label:"Last pack size",value:e?aa(r):"n/a",tooltip:e?`Estimate: ${r.toLocaleString()} injected`:void 0,icon:"package"},{label:"Last pack deduped",value:e?o.toLocaleString():"n/a",icon:"copy-check"},{label:"Exact dedupe",value:c,icon:"shield-check"},{label:"Packs",value:t??"n/a",icon:"archive"}]}function T2(e,t,n){if(t>0){e.push({label:"Raw events pending",value:t,tooltip:"Pending raw events waiting to be flushed",icon:"activity"});return}n>0&&e.push({label:"Raw sessions",value:n,tooltip:"Sessions with pending raw events",icon:"inbox"})}function A2(){const e=document.getElementById("statsGrid"),t=document.getElementById("metaLine");if(!e)return;const n=Bn(_.healthStats),r=Bn(_.healthUsage,_.currentProject),i=Bn(_.healthRawEvents),o=n?.database,s=_.currentProject,c=r?.totals_filtered??null,l=!!(s&&c),d=r?mm(r,!1):null,u=r?mm(r,l):null,p=i?.sessions??0,f=i?.pending??0,m=l&&d?`
116
116
  Global: ${d.total_tokens_read.toLocaleString()} estimated injected`:"",v=l&&d?`
117
117
  Global: ${d.total_tokens_saved.toLocaleString()} estimated saved`:"",b=[{label:l?"Savings (project)":"Savings",value:u?aa(u.total_tokens_saved):"n/a",tooltip:u?`Estimated tokens saved by reusing compressed memories: ${u.total_tokens_saved.toLocaleString()}${v}`:"Usage data is unavailable",icon:"trending-up"},{label:l?"Injected (project)":"Injected",value:u?aa(u.total_tokens_read):"n/a",tooltip:u?`Estimated tokens injected into context (pack size): ${u.total_tokens_read.toLocaleString()}${m}`:"Usage data is unavailable",icon:"book-open"},{label:l?"Reduction (project)":"Reduction",value:u?Fu(u.total_tokens_saved,u.total_tokens_read):"n/a",tooltip:u?`Estimated percent reduction from reuse. Factor: ${rA(u.total_tokens_saved,u.total_tokens_read)}.${m}${v}`:"Usage data is unavailable",icon:"percent"},{label:l?"Work investment (project)":"Work investment",value:"n/a",tooltip:"Work-investment data is unavailable",icon:"pencil"},{label:"Active memories",value:o?.active_memory_items??"n/a",icon:"check-circle"},{label:"Embedding coverage",value:o?yy(o.vector_coverage):"n/a",tooltip:"Share of active memories with embeddings",icon:"layers"},{label:"Tag coverage",value:o?yy(o.tags_coverage):"n/a",tooltip:"Share of active memories with tags",icon:"tag"}];i&&T2(b,f,p),$S(e,b),t&&E2(t,o,s),Xa()}function E2(e,t,n){if(!t){Nl(e,x2(_.healthStats,"Database metrics"));return}const r=n?` · project: ${n}`:"",i=Ic(_.healthStats)?" · showing stale data":"",o=aA(t.path);Nl(e,`DB: ${o} · ${sA(t.size_bytes)}${r}${i}`)}function x2(e,t){return e.status==="loading"?`Loading ${t.toLowerCase()}…`:e.status==="failed"?`${t} failed to load`:`${t} not loaded`}var JS=0,vi=null;function El(){vi?.cancel()}function D2(e){if(_.activeTab!=="health"||_.lastUpdateStatus&&!_.lastUpdateStatus.unavailable||vi||e.signal?.aborted)return;const t=xd(),n={cancel:()=>{vi===n&&(vi=null,t.abort(),t.dispose(),e.signal?.removeEventListener("abort",n.cancel))}};vi=n,e.signal?.addEventListener("abort",n.cancel,{once:!0}),Go(xN({signal:t.signal}),t.signal).then(i=>r(i),i=>r(DN(i)));function r(i){vi===n&&(vi=null,t.dispose(),e.signal?.removeEventListener("abort",n.cancel),_.activeTab==="health"&&(_.lastUpdateStatus=i,hm()))}}async function j2(e={}){const t=_.viewerActorId,n=await yk(e);e.signal?.aborted||(_.viewerActorId=n.identity.actor_id,t!==_.viewerActorId&&Cn(!0))}async function L2(e={}){const t=++JS,n=_.currentProject;_.healthStats=Rc(_.healthStats),_.healthUsage=Rc(_.healthUsage,n),_.healthSession=Rc(_.healthSession,n),_.healthRawEvents=Rc(_.healthRawEvents),Za();const r=()=>!e.signal?.aborted&&t===JS;D2(e),await Promise.all([xl(Tk(e)).then(i=>{r()&&(_.healthStats=Dl(_.healthStats,i),Za())}),xl(Ak(n,e)).then(i=>{r()&&(_.healthUsage=Dl(_.healthUsage,i,n),Za())}),xl(Ek(n,e)).then(i=>{r()&&(_.healthSession=Dl(_.healthSession,i,n),Za())}),xl(xk(n,e)).then(i=>{r()&&(_.healthRawEvents=Dl(_.healthRawEvents,i),Za())})])}function Za(){A2(),SU(document.getElementById("automaticRecallStats"),Bn(_.healthStats)?.automatic_recall),R2(),hm()}async function xl(e){try{return{ok:!0,data:await e}}catch(t){return{ok:!1,error:t instanceof Error?t.message:"Health request failed"}}}function Dl(e,t,n=""){return"data"in t?K0(t.data,Date.now(),n):z0(e,t.error)}function vm(e,t){return`legacy-team-setup-item-error-${e}-${t}`}function YS(e){return[...e].sort((t,n)=>+(n.decision==="unresolved")-+(t.decision==="unresolved"))}function QS(e){return[...e].sort((t,n)=>+(n.resolution==="unresolved")-+(t.resolution==="unresolved"))}var O2={unresolved:"Needs a decision",included:"Included in this Team",excluded:"Excluded from this Team",removed:"Removed from this Team"};function XS(e,t){return t?e.identityChoices.find(n=>n.identityRef===t)?.displayName??"Unavailable person":null}function $2(e){return e.targetIdentityRef??e.existingIdentityRef??""}function M2({blocked:e,blockedDescriptionId:t,blockedDeviceRefs:n,busy:r,detail:i,device:o,index:s,onAssign:c,onClear:l,onDecision:d}){const u=Xt(),p=`${u}-identity`,f=`${u}-evidence`,m=`${u}-assignment-help`,v=$2(o),b=o.targetIdentityRef??"",[g,y]=T(v);q(()=>y(v),[v]);const S=i.identityChoices.some(x=>x.identityRef===g),w=XS(i,o.existingIdentityRef),R=XS(i,o.suggestedIdentityRef),k=n?.has(o.deviceRef)??!1,N=e||k||r,j=N||!o.actions.assignIdentity.enabled,E=o.actions.assignIdentity.blockedReason==="assignment_evidence_inactive",F=!!g&&!S,A=!o.actions.include.enabled||E||F||!b||g!==b,M=N||A,O=j||!g||E||F||g===b,H=!o.enabled||A,V=e?t:k?vm("device",o.deviceRef):void 0,W=[f,H?m:void 0,V].filter(Boolean).join(" "),$=[f,V].filter(Boolean).join(" "),C=o.decision==="unresolved";return a("fieldset",{"aria-busy":r?"true":"false",className:`legacy-team-device-row${C?" legacy-team-setup-row-needs-attention":""}`,id:`legacy-team-device-row-${s}`,tabIndex:C?-1:void 0,children:[a("legend",{children:o.displayName}),C?a("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,a("div",{className:"small legacy-team-device-evidence",id:f,children:[a("span",{children:o.enabled?"Current Team device":"Device no longer active on this Team"}),w?a("span",{children:["Current assignment: ",w,o.verifiedEvidenceKind==="active_assignment"?" · verified active assignment":""]}):null,!w&&R?a("span",{children:["Suggested person: ",R]}):null,a("span",{children:["Decision: ",O2[o.decision]]})]}),a("label",{htmlFor:p,children:"Person using this device"}),a("select",{"aria-describedby":W,className:"feed-search legacy-team-device-select",disabled:j,id:p,onChange:x=>y(x.currentTarget.value),value:g,children:[a("option",{value:"",children:"Choose a person"}),g&&!S?a("option",{value:g,children:"Current server assignment"}):null,i.identityChoices.map(x=>a("option",{value:x.identityRef,children:x.displayName},x.identityRef))]}),o.enabled?F?a("p",{className:"small",id:m,children:"This person is no longer available. Choose an available person and save the assignment before including this device."}):E?a("p",{className:"small",id:m,children:"This assignment is inactive. Reconcile this device in Devices or exclude it from this Team."}):!g||!b||g!==b?a("p",{className:"small",id:m,children:g?"Save the selected person assignment before including this device.":"Choose and save a person assignment before including this device."}):null:a("p",{className:"small",id:m,children:"Inactive devices can only be removed from this Team."}),a("div",{className:"legacy-team-device-actions",children:[a("button",{"aria-describedby":W,"aria-disabled":O?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{O||c(o,g)},type:"button",children:"Save assignment"}),o.enabled?a(G,{children:[a("button",{"aria-describedby":W,"aria-disabled":M?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{M||d(o,"included",b)},type:"button",children:"Include"}),a("button",{"aria-describedby":$,"aria-disabled":N||!o.actions.exclude.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!N&&o.actions.exclude.enabled&&d(o,"excluded")},type:"button",children:"Exclude"})]}):a("button",{"aria-describedby":$,"aria-disabled":N||!o.actions.remove.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!N&&o.actions.remove.enabled&&d(o,"removed")},type:"button",children:"Remove"}),o.decision!=="unresolved"?a("button",{"aria-describedby":$,"aria-disabled":N||!o.actions.clearDecision.enabled?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!N&&o.actions.clearDecision.enabled&&l(o)},type:"button",children:"Clear decision"}):null]})]})}function F2(e){const t=YS(e.detail.devices);return a("section",{"aria-labelledby":"legacy-team-setup-step-devices",children:[a("h3",{id:"legacy-team-setup-step-devices",tabIndex:-1,children:"Review devices"}),a("p",{children:[e.detail.unresolvedDeviceCount.toLocaleString()," of"," ",e.detail.candidate.deviceCount.toLocaleString()," Team devices still need a decision."]}),a("div",{className:"legacy-team-device-list",children:t.map((n,r)=>h(M2,{...e,busy:e.busyDeviceRefs.has(n.deviceRef),device:n,index:r,key:n.deviceRef}))})]})}function B2(e,t){return e.resolvedProjectRef?t.get(e.resolvedProjectRef)??"Unavailable Project":null}function q2({blocked:e,blockedDescriptionId:t,blockedProjectRefs:n,busy:r,index:i,onMap:o,presentationName:s,project:c}){const l=Xt(),d=`${l}-mapping`,u=`${l}-help`,p=c.resolvedProjectRef??"",f=zr(c.mappingChoices.map(W=>({canonicalId:W.resolvedProjectRef,displayName:W.displayName}))),m=[...new Set(c.mappingChoices.map(W=>W.resolvedProjectRef))],v=[...m].sort((W,$)=>W<$?-1:W>$?1:0),b=new Map(v.map((W,$)=>[W,`project-choice-${$+1}`])),g=new Map(c.mappingChoices.map(W=>[W.resolvedProjectRef,W])),y=m.flatMap(W=>{const $=g.get(W);return $?[{...$,label:f.get(W)??$.displayName,token:b.get(W)??""}]:[]}),S=y.find(W=>W.resolvedProjectRef===p)?.token??"",w=JSON.stringify(v),[R,k]=T(S);q(()=>k(S),[S,w]);const N=y.find(W=>W.token===R)?.resolvedProjectRef,j=n?.has(c.projectRef)??!1,E=c.actions.map.blockedReason==="mapping_unavailable",F=c.actions.map.enabled&&!R,A=e||j||r||!c.actions.map.enabled,M=A||!N||N===p,O=B2(c,f),H=[E||F?u:void 0,e?t:j?vm("project",c.projectRef):void 0].filter(Boolean).join(" "),V=c.resolution==="unresolved";return a("fieldset",{"aria-busy":r?"true":"false",className:`legacy-team-project-row${V?" legacy-team-setup-row-needs-attention":""}`,id:`legacy-team-project-row-${i}`,tabIndex:V?-1:void 0,children:[a("legend",{children:s}),a("div",{className:"legacy-team-project-row-content",children:[V?a("span",{className:"legacy-team-setup-status",children:"Needs attention"}):null,c.resolution==="deterministic"?a("p",{className:"small",children:"Mapped automatically from matching Project evidence."}):a(G,{children:[a("p",{className:"small",children:O?`Saved mapping: ${O}`:"This Project still needs a mapping."}),a("label",{htmlFor:d,children:"Canonical Project"}),a("select",{"aria-describedby":H||void 0,className:"feed-search legacy-team-project-select",disabled:A,id:d,onChange:W=>k(W.currentTarget.value),value:R,children:[a("option",{value:"",children:"Choose a Project"}),y.map(W=>a("option",{value:W.token,children:W.label},W.resolvedProjectRef))]}),E?a("p",{className:"small",id:u,children:"No safe Project mapping is available. Refresh after Project evidence changes."}):F?a("p",{className:"small",id:u,children:"Choose and save one of the server-provided Project mappings."}):null,a("button",{"aria-describedby":H||void 0,"aria-disabled":M?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{!M&&N&&o(c,N)},type:"button",children:"Save mapping"})]})]})]})}function U2(e){const t=QS(e.detail.projects),n=zr(t.map(o=>({canonicalId:o.projectRef,displayName:o.displayName}))),r=e.detail.projects.filter(o=>o.resolution==="deterministic").length,i=Math.max(e.detail.candidate.projectCount,e.detail.projects.length,e.detail.unresolvedProjectCount);return a("section",{"aria-labelledby":"legacy-team-setup-step-projects",children:[a("h3",{id:"legacy-team-setup-step-projects",tabIndex:-1,children:"Review Projects"}),a("p",{children:e.detail.unresolvedProjectCount===0?`All ${i.toLocaleString()} Team Projects are mapped.`:`${e.detail.unresolvedProjectCount.toLocaleString()} of ${i.toLocaleString()} Team Projects need attention.`}),r>0?a("p",{className:"small",children:"Review the automatic mappings below before continuing."}):null,a("div",{className:"legacy-team-project-list",children:t.map((o,s)=>a(q2,{blocked:e.blocked,blockedDescriptionId:e.blockedDescriptionId,blockedProjectRefs:e.blockedProjectRefs,busy:e.busyProjectRefs.has(o.projectRef),index:s,onMap:e.onMap,presentationName:n.get(o.projectRef)??o.displayName,project:o},o.projectRef))}),e.detail.unresolvedProjectCount===0?a("div",{className:"legacy-team-setup-next-action",children:[a("p",{className:"small",id:"legacy-team-project-continue-help",children:"Continue to review the exact people, devices, and Projects that will receive access."}),a("button",{"aria-describedby":["legacy-team-project-continue-help",e.blocked?e.blockedDescriptionId:null].filter(Boolean).join(" "),"aria-disabled":e.blocked?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{e.blocked||e.onContinue()},type:"button",children:"Continue to Review"})]}):null]})}var es={add:"Add",update:"Update",remove:"Remove"},G2=10;function ht(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function gm(e,t,n,r){const i=new Map;for(const o of e){const s=t(o),c=r(o),l=`${c}:${cr(s)}`,d=n(o),u=i.get(l)??{displayName:s,kind:c,projectRefs:new Set,changeCount:0};u.projectRefs.add(d),u.changeCount+=1,i.set(l,u)}return[...i.values()]}function ym(e,t){return e.kind==="legacy_default_sharing"?`${e.displayName} — default scope`:e.projectRefs.size>1?`${e.displayName} — ${ht(e.projectRefs.size,t)}`:e.displayName}function ts({empty:e,exactItemName:t,exactItems:n,summaryItems:r,title:i}){const o=!!(r&&r.length<n.length),s=o&&n.length>G2;return a("section",{children:[a("h4",{children:i}),n.length>0?a(G,{children:[o&&r?a("ul",{className:"legacy-team-setup-delta-summary",children:r.map((c,l)=>a("li",{children:c},`${i}-summary-${l}`))}):null,s?a("details",{children:[a("summary",{children:["Show all ",ht(n.length,`exact ${t}`)]}),a(ZS,{items:n,title:i})]}):a(ZS,{items:n,title:i})]}):a("p",{className:"small",children:e})]})}function ZS({items:e,title:t}){return a("ul",{className:"legacy-team-setup-exact-list",children:e.map((n,r)=>a("li",{children:n},`${t}-${r}`))})}function H2({blocked:e,blockedDescriptionId:t,detail:n,finishing:r,onFinish:i}){const o=n.accessDelta,s=JSON.stringify([n.attemptId,n.finishDigest,n.accessDeltaDigest,n.viewerAccessDeltaDigest]),[c,l]=T(null),d=c===s,u=e||!d,p=[d?null:"legacy-team-setup-confirmation-label",e?t:null].filter(Boolean).join(" "),f=o.teamChanges.map(C=>{const x=C.fromDeviceEligibilityMode==="person_all_devices"?"all devices assigned to each person":C.fromDeviceEligibilityMode==="reviewed_allowlist"?"the reviewed device list":"no existing device policy";return`${es[C.change]} ${C.teamDisplayName}: change device access from ${x} to the reviewed device list.`}),m=o.membershipChanges.map(C=>`${es[C.change]} ${C.identityDisplayName} ${C.change==="remove"?"from":"to"} ${C.teamDisplayName}.`),v=zr([...n.projects.map(C=>({canonicalId:C.projectRef,displayName:C.displayName})),...o.projectChanges.map(C=>({canonicalId:C.projectRef,displayName:C.projectDisplayName}))]),b=o.projectChanges.flatMap(C=>[...C.fromResolvedProjectRef&&C.fromResolvedProjectDisplayName?[{canonicalProjectRef:C.fromCanonicalProjectRef,resolvedProjectRef:C.fromResolvedProjectRef,displayName:C.fromResolvedProjectDisplayName}]:[],...C.toResolvedProjectRef&&C.toResolvedProjectDisplayName?[{canonicalProjectRef:C.toCanonicalProjectRef,resolvedProjectRef:C.toResolvedProjectRef,displayName:C.toResolvedProjectDisplayName}]:[]]),g=zr(b.map(C=>({canonicalId:C.canonicalProjectRef??C.resolvedProjectRef,displayName:C.displayName}))),y=new Map(b.map(C=>[C.resolvedProjectRef,g.get(C.canonicalProjectRef??C.resolvedProjectRef)??C.displayName])),S=zr([...n.projects.flatMap(C=>C.canonicalProjectRef?[{canonicalId:C.canonicalProjectRef,displayName:C.displayName}]:[]),...[...o.recipientChanges,...o.deviceAccessChanges].filter(C=>C.canonicalProjectKind==="project").map(C=>({canonicalId:C.canonicalProjectRef,displayName:C.canonicalProjectDisplayName}))]),w=o.projectChanges.map(C=>`${es[C.change]} ${v.get(C.projectRef)??C.projectDisplayName}: ${C.fromResolvedProjectRef?y.get(C.fromResolvedProjectRef)??C.fromResolvedProjectDisplayName??"no Project":"no Project"} to ${C.toResolvedProjectRef?y.get(C.toResolvedProjectRef)??C.toResolvedProjectDisplayName??"no Project":"no Project"}.`),R=o.recipientChanges.map(C=>C.canonicalProjectKind==="legacy_default_sharing"?`${C.change==="remove"?"Stop":"Start"} using legacy default sharing for ${C.recipientDisplayName}.`:`${es[C.change]} ${C.recipientDisplayName} ${C.change==="remove"?"from":"as"} a recipient for ${S.get(C.canonicalProjectRef)??C.canonicalProjectDisplayName}.`),k=o.deviceAccessChanges.map(C=>C.canonicalProjectKind==="legacy_default_sharing"?`${C.deviceDisplayName} ${C.change==="remove"?"stops":"starts"} inheriting legacy default sharing.`:`${es[C.change]} ${C.deviceDisplayName} access ${C.change==="remove"?"from":"to"} ${S.get(C.canonicalProjectRef)??C.canonicalProjectDisplayName}.`),N=o.teamChanges.length+o.membershipChanges.length+o.projectChanges.length+o.recipientChanges.length+o.deviceAccessChanges.length,j=gm(o.projectChanges,C=>C.projectDisplayName,C=>C.projectRef,()=>"project"),E=gm(o.recipientChanges,C=>C.canonicalProjectDisplayName,C=>C.canonicalProjectRef,C=>C.canonicalProjectKind),F=gm(o.deviceAccessChanges,C=>C.canonicalProjectDisplayName,C=>C.canonicalProjectRef,C=>C.canonicalProjectKind),A=n.devices.filter(C=>C.decision==="included").length,M=[ht(o.teamChanges.length,"Team policy change"),ht(o.membershipChanges.length,"membership change"),ht(o.projectChanges.length,"Project change"),ht(o.recipientChanges.length,"recipient change"),ht(o.deviceAccessChanges.length,"device-access change")],O=`${ht(n.projects.length,"Project")} included; ${ht(A,"included device")}.`,H=Math.max(n.candidate.projectCount,n.projects.length),V=new Set(o.deviceAccessChanges.map(C=>C.deviceRef)).size,W=[...o.teamChanges,...o.membershipChanges,...o.projectChanges,...o.recipientChanges,...o.deviceAccessChanges].filter(C=>C.change==="remove").length,$=o.teamChanges.length===0&&o.membershipChanges.length===0&&o.projectChanges.length===0&&o.recipientChanges.length>0&&o.recipientChanges.every(C=>C.change==="remove"&&C.canonicalProjectKind==="legacy_default_sharing")&&o.deviceAccessChanges.every(C=>C.change==="remove"&&C.canonicalProjectKind==="legacy_default_sharing")?`No new access will be added. This removes legacy default sharing for ${n.candidate.displayName}.${V>0?` ${ht(V,"device")} will stop receiving memories shared only through that default.`:""} Project-scoped access is unchanged across ${ht(H,"reviewed Project")}.`:`${ht(N,"server-confirmed access change")} will be applied atomically; ${ht(W,"removal")} ${W===1?"is":"are"} included.`;return a("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[a("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),a("p",{children:"Review every server-confirmed access change before activating this Team."}),a("section",{"aria-label":"Access review summary",className:"legacy-team-setup-review-summary",children:[a("p",{className:"legacy-team-setup-net-effect",children:[a("strong",{children:"Net effect:"})," ",$]}),a("p",{children:[a("strong",{children:ht(N,"exact access change")})," to review."]}),a("ul",{children:M.map(C=>a("li",{children:C},C))}),a("p",{className:"small",children:["Scope: ",O]})]}),a("div",{className:"legacy-team-setup-delta",children:[a(ts,{empty:"No Team policy changes.",exactItemName:"Team policy change",exactItems:f,title:"Team policy"}),a(ts,{empty:"No membership changes.",exactItemName:"membership change",exactItems:m,title:"Memberships"}),a(ts,{empty:"No Project mapping changes.",exactItemName:"Project change",exactItems:w,summaryItems:j.map(C=>`${ym(C,"reviewed Project")}, ${ht(C.changeCount,"Project change")}`),title:"Projects"}),a(ts,{empty:"No recipient changes.",exactItemName:"recipient change",exactItems:R,summaryItems:E.map(C=>`${ym(C,"canonical Project")}, ${ht(C.changeCount,"recipient change")}`),title:"Recipients"}),a(ts,{empty:"No device access changes.",exactItemName:"device-access change",exactItems:k,summaryItems:F.map(C=>`${ym(C,"canonical Project")}, ${ht(C.changeCount,"device-access change")}`),title:"Device access"})]}),a("label",{className:"legacy-team-setup-confirmation",id:"legacy-team-setup-confirmation-label",children:[a("input",{"aria-disabled":e?"true":void 0,"aria-describedby":e?t:void 0,checked:d,onClick:C=>{e&&C.preventDefault()},onChange:C=>{if(e){C.currentTarget.checked=d;return}l(C.currentTarget.checked?s:null)},type:"checkbox"}),a("span",{children:"I reviewed every access change above and approve activating this Team."})]}),r?a("p",{"aria-live":"polite",className:"legacy-team-setup-finish-progress",role:"status",children:[a("span",{"aria-hidden":"true",className:"legacy-team-setup-spinner"}),"Checking the latest Team roster and applying all reviewed changes atomically. No partial changes will be kept if this cannot finish."]}):null,a("button",{"aria-describedby":p||void 0,"aria-disabled":u?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{u||i(n)},type:"button",children:r?"Finishing Team setup…":"Finish Team setup"})]})}function V2(e){let t=null;return async n=>{try{const r=await K2(n,e,()=>t,i=>{t=i});return{status:"success",generation:n.generation,id:n.id,kind:n.kind,view:r}}catch(r){let i,o;try{i=await z2(n,e,r)}catch(s){o=s}return n.kind==="load"&&!n.refresh&&!n.completionOnly&&r instanceof Me&&r.errorCode==="team_setup_confirmation_stale"&&i&&i.state!=="unavailable"?{status:"success",generation:n.generation,id:n.id,kind:n.kind,view:i}:{status:"failure",generation:n.generation,id:n.id,kind:n.kind,cause:r,...o?{recoveryCause:o}:{},...i?{recoveredView:i}:{}}}}}async function K2(e,t,n,r){switch(e.kind){case"load":return e.refresh?t.refreshCandidate(e.candidateRef):t.loadDetail(e.candidateRef);case"assign_device":return t.saveAssignment(e.candidateRef,e.deviceRef,e.input);case"decide_device":return t.saveDecision(e.candidateRef,e.deviceRef,e.input);case"clear_device":return t.clearDecision(e.candidateRef,e.deviceRef,e.input);case"map_project":return t.saveProjectMapping(e.candidateRef,e.projectRef,e.input);case"refresh":return t.refreshCandidate(e.candidateRef);case"finish":await t.finish(e.candidateRef,e.input);return;case"completion_refresh":{const i=n();if(i?.attemptId===e.attemptId&&i.candidateRef===e.candidateRef){await i.promise;return}const o=Promise.resolve().then(()=>t.onCompleted());r({attemptId:e.attemptId,candidateRef:e.candidateRef,promise:o});try{await o}finally{n()?.promise===o&&r(null)}return}default:throw new Error(`Unhandled Team setup effect: ${String(e)}`)}}async function z2(e,t,n){if(e.kind!=="completion_refresh"&&!(!(n instanceof Me)||!gi(n.errorCode))){if(e.kind==="load"&&!e.refresh&&!e.completionOnly&&n.errorCode==="team_setup_confirmation_stale")return t.loadDetail(e.candidateRef);if(e.kind!=="load")return t.loadDetail(e.candidateRef)}}function gi(e){return["team_setup_roster_changed","team_setup_assignment_changed","team_setup_conflict","team_setup_confirmation_stale"].includes(e)}function eC(e,t){return{id:e,targetId:`legacy-team-setup-step-${t}`}}function W2(e,t,n){return nC(e,n>=0?`${t==="devices"?"legacy-team-device-row":"legacy-team-project-row"}-${n}`:`legacy-team-setup-step-${t}`)}function tC(e,t){return nC(e,t.recovery||t.hasError?"legacy-team-setup-retry":`legacy-team-setup-step-${t.step}`)}function nC(e,t){return{id:e,targetId:t}}var bm="Team setup changed since it was last reviewed. Reload the latest details to continue.",rC="Team device details are temporarily unavailable. Check the coordinator connection and settings, then refresh.",iC="Team device details are temporarily unavailable. Check the coordinator connection and settings, then retry loading.",J2="Team device details were unavailable, so setup was not finished and no changes were applied. Check the coordinator connection and settings, then refresh.",Y2="This device's Project history is too large to finish setup here, so no changes were applied. Retry from a device with less history, or contact support.",oC="Team setup completion could not be checked. Check the coordinator connection and settings, then retry.",aC="Team setup could not be confirmed, and no local changes were applied. Retry to check whether setup completed.",Q2="Another device completed this Team with different reviewed details. Retry to load the completed setup.",X2="The completed Team setup could not be verified. Retry, then check the coordinator connection and settings if the problem continues.";function Z2(){return{status:"closed",generation:0}}function _m(e,t){switch(t.type){case"open":return e.status==="open"&&Xn(e)?e:eG(e.generation+1,t.candidateRef);case"close":return e.status==="open"&&Xn(e)?e:{status:"closed",generation:e.generation+1};case"close_blocked":case"open_blocked":return e.status==="open"?{...e,message:t.message}:e;case"navigate":return tG(e,t.step);case"blocked_navigation":return jl(e,t.step,t.message);case"retry":return nG(e);case"refresh":return iG(e,"refresh","Refreshing Team setup from the latest server state.");case"assign_device":return wm(e,t,"assign_device");case"decide_device":return wm(e,t,"decide_device");case"clear_device":return wm(e,t,"clear_device");case"map_project":return rG(e,t);case"finish":return oG(e);case"command_started":return RG(e,t.id,n=>({...n,status:"running"}));case"effect_outcome":return aG(e,t.outcome);case"focus_applied":return e.status==="open"&&e.focus?.id===t.id?{...e,focus:null}:e;default:return t}}function eG(e,t){return Rr({status:"open",generation:e,candidateRef:t,view:null,step:"devices",projectsVisitedAttemptId:null,commands:[],nextCommandId:1,errors:[],message:"",focus:null,nextFocusId:1},{kind:"load",candidateRef:t,refresh:!1,focusOnOutcome:!1})}function tG(e,t){if(e.status!=="open"||e.step==="completed"||t==="completed")return e;if(t==="projects"&&e.view?.unresolvedDeviceCount)return jl(e,"devices","Finish the device decisions before mapping Projects.");if(t==="review"&&e.view?.unresolvedDeviceCount)return jl(e,"devices","Finish the device decisions before reviewing access.");if(t==="review"&&e.view?.unresolvedProjectCount)return jl(e,"projects","Finish the Project mappings before reviewing access.");const n=t==="projects"&&e.view?e.view.attemptId:e.projectsVisitedAttemptId;return{...e,step:t,projectsVisitedAttemptId:n,focus:eC(e.nextFocusId,t),nextFocusId:e.nextFocusId+1}}function jl(e,t,n){if(e.status!=="open"||e.step==="completed"||!e.view)return e;const r=t==="devices"?YS(e.view.devices).findIndex(i=>i.decision==="unresolved"):QS(e.view.projects).findIndex(i=>i.resolution==="unresolved");return{...e,step:t,projectsVisitedAttemptId:t==="projects"?e.view.attemptId:e.projectsVisitedAttemptId,message:n,focus:W2(e.nextFocusId,t,r),nextFocusId:e.nextFocusId+1}}function nG(e){if(e.status!=="open"||e.step==="completed"||ns(e)||Xn(e))return e;const t=Ll(e)??e.errors.find(r=>r.retry),n=t?.retry??"load";return Rr(e,{kind:"load",candidateRef:e.candidateRef,refresh:n==="refresh",completionOnly:n==="completion",readOnlyRecovery:n==="load"&&t?.readOnlyRetry===!0,focusOnOutcome:!0})}function wm(e,t,n){if(e.status!=="open"||e.step==="completed"||!Sm(e.view)||Ll(e)||ns(e)||Xn(e))return e;const r=e.view.devices.find(c=>c.deviceRef===t.deviceRef);if(!r||!(t.type==="assign_device"?r.actions.assignIdentity:t.type==="clear_device"?r.actions.clearDecision:t.decision==="included"?r.actions.include:t.decision==="excluded"?r.actions.exclude:r.actions.remove).enabled)return e;const i={candidateRef:e.candidateRef,deviceRef:t.deviceRef},o=n==="assign_device"&&t.type==="assign_device"?{kind:n,...i,input:{attemptId:e.view.attemptId,targetIdentityRef:t.targetIdentityRef,expectation:r.expectation}}:n==="clear_device"&&t.type==="clear_device"?{kind:n,...i,input:{attemptId:e.view.attemptId}}:t.type==="decide_device"?{kind:"decide_device",...i,input:t.decision==="included"&&t.targetIdentityRef?{attemptId:e.view.attemptId,decision:"included",expectedTargetIdentityRef:t.targetIdentityRef}:{attemptId:e.view.attemptId,decision:t.decision}}:null;if(!o||t.type==="decide_device"&&t.decision==="included"&&!t.targetIdentityRef)return e;const s=t.type==="assign_device"?`Saving the assignment for ${r.displayName}.`:t.type==="clear_device"?`Clearing the decision for ${r.displayName}.`:`Saving the decision for ${r.displayName}.`;return Rr(yi(e,{kind:"device",itemRef:t.deviceRef}),o,s)}function rG(e,t){if(e.status!=="open"||e.step==="completed"||!Sm(e.view)||Ll(e)||ns(e)||Xn(e))return e;const n=e.view.projects.find(r=>r.projectRef===t.projectRef);return!n?.actions.map.enabled||!n.mappingChoices.some(r=>r.resolvedProjectRef===t.resolvedProjectRef)?e:Rr(yi(e,{kind:"project",itemRef:t.projectRef}),{kind:"map_project",candidateRef:e.candidateRef,projectRef:t.projectRef,input:{attemptId:e.view.attemptId,resolvedProjectRef:t.resolvedProjectRef}},`Saving the mapping for ${n.displayName}.`)}function iG(e,t,n){return e.status!=="open"||e.step==="completed"||!e.view?.actions.refresh.enabled||ns(e)||Xn(e)?e:Rr(yi(e,{kind:"global"}),{kind:t,candidateRef:e.candidateRef},n)}function oG(e){return e.status!=="open"||e.step==="completed"||e.view?.state!=="ready_to_finish"||e.commands.length||e.errors.length>0?e:Rr(yi(e,{kind:"global"}),{kind:"finish",candidateRef:e.candidateRef,attemptId:e.view.attemptId,input:{attemptId:e.view.attemptId,finishDigest:e.view.finishDigest,confirmedAccessDeltaDigest:e.view.accessDeltaDigest,confirmedViewerAccessDeltaDigest:e.view.viewerAccessDeltaDigest}},"Finishing Team setup.")}function Rr(e,t,n=e.message){const r=`${e.generation}:${e.nextCommandId}`;return{...e,commands:[...e.commands,{...t,generation:e.generation,id:r,status:"pending"}],nextCommandId:e.nextCommandId+1,message:n}}function aG(e,t){if(e.status!=="open"||e.generation!==t.generation)return e;const n=e.commands.find(i=>i.id===t.id);if(!n)return e;const r={...e,commands:e.commands.filter(i=>i.id!==t.id)};return n.kind==="load"&&(n.completionOnly||n.readOnlyRecovery)&&t.status==="success"&&t.view?.state!=="completed"?sC(r,n,{status:"failure",generation:t.generation,id:t.id,kind:n.kind,cause:new Me(409,"team_setup_confirmation_stale")}):t.status==="failure"?sC(r,n,t):n.kind==="completion_refresh"?{...r,message:"Team setup complete. Sharing and Projects are up to date."}:n.kind==="finish"?cG(r,n.attemptId):t.view?cC({...CG(r,n),message:sG(n,e.view)},t.view,n.kind==="load"&&n.focusOnOutcome):r}function sG(e,t){if(e.kind==="refresh")return"Team setup refreshed.";if(e.kind==="load")return"";if("deviceRef"in e){const n=t?.devices.find(r=>r.deviceRef===e.deviceRef)?.displayName;return n?`${n} saved.`:"Device saved."}if("projectRef"in e){const n=t?.projects.find(r=>r.projectRef===e.projectRef)?.displayName;return n?`${n} saved.`:"Project mapping saved."}return""}function sC(e,t,n){if(t.kind==="completion_refresh")return{...e,message:"Team setup complete. Sharing or Projects could not be refreshed; use that view's Refresh control."};const r=n.recoveredView?cC(e,n.recoveredView,!1):e;if(n.recoveredView?.state==="completed")return r;const i=t.kind==="load"&&!t.refresh&&n.recoveredView?.state==="unavailable",o=lG(t,i&&n.recoveredView?.state==="unavailable"?new Me(409,n.recoveredView.unavailableReason):n.cause,i?void 0:n.recoveryCause),s={...r,errors:[...yi(r,o.scope).errors,o],message:""};return t.kind!=="load"||!t.focusOnOutcome?s:{...s,focus:tC(s.nextFocusId,{hasError:!0,recovery:s.view?.state==="unavailable",step:s.step}),nextFocusId:s.nextFocusId+1}}function cC(e,t,n){const r=wG(t,e.projectsVisitedAttemptId===t.attemptId),i=r==="projects"?t.attemptId:e.projectsVisitedAttemptId,o=t.state==="unavailable"?[{scope:{kind:"global"},message:SG(t.unavailableReason),retry:"refresh"}]:t.state==="completed"?[]:e.errors.filter(l=>{if(l.scope.kind==="device"){const d=l.scope.itemRef;return t.devices.some(u=>u.deviceRef===d)}if(l.scope.kind==="project"){const d=l.scope.itemRef;return t.projects.some(u=>u.projectRef===d)}return!1});let s={...e,view:t,step:r,projectsVisitedAttemptId:i,errors:o,message:t.state==="completed"?"Team setup complete. Sharing and Projects are refreshing.":e.message};const c=o.some(l=>l.scope.kind==="global"||l.scope.kind==="load");return(n||r!==e.step)&&(s={...s,focus:tC(s.nextFocusId,{hasError:c,recovery:t.state==="unavailable",step:r}),nextFocusId:s.nextFocusId+1}),t.state==="completed"&&!pC(s,t.attemptId)&&(s=Rr(s,{kind:"completion_refresh",candidateRef:s.candidateRef,attemptId:t.attemptId})),s}function cG(e,t){let n={...e,step:"completed",message:"Team setup complete. Sharing and Projects are refreshing.",focus:eC(e.nextFocusId,"completed"),nextFocusId:e.nextFocusId+1};return pC(n,t)||(n=Rr(n,{kind:"completion_refresh",candidateRef:n.candidateRef,attemptId:t})),n}function lG(e,t,n){const r=t instanceof Me&&gi(t.errorCode),i=t instanceof Me&&t.errorCode==="team_setup_roster_unavailable",{completionCode:o,message:s,terminalRecoveryCode:c}=yG({command:e,cause:t,recoveryCause:n,changed:r,rosterUnavailable:i}),l=c?null:vG(e,t,n),d=r||i||o!==null,u=mG(e,t,n,{changed:r,rosterUnavailable:i,terminalRecovery:c!==null}),p=dG(e,t,n,u);return{scope:uG(e,{globalError:d}),message:l??s,hideStaleView:!!l||e.kind==="load"&&e.completionOnly||p,readOnlyRetry:p,retry:u}}function dG(e,t,n,r){return e.kind!=="load"||r!=="load"?!1:e.readOnlyRecovery?!0:t instanceof Me&&t.errorCode==="team_setup_confirmation_stale"&&!!n}function uG(e,t){return t.globalError?{kind:"global"}:e.kind==="assign_device"||e.kind==="decide_device"||e.kind==="clear_device"?{kind:"device",itemRef:e.deviceRef}:e.kind==="map_project"?{kind:"project",itemRef:e.projectRef}:e.kind==="load"?{kind:"load"}:{kind:"global"}}function pG(e,t,n){const r=n instanceof Me&&n.errorCode==="team_setup_confirmation_stale",i=t instanceof Me&&t.errorCode==="team_setup_confirmation_stale";return!i&&!r?null:e.kind==="load"&&!e.refresh&&i&&n&&(!(n instanceof Me)||!gi(n.errorCode))?"load":e.kind==="load"&&e.refresh?"completion":"refresh"}function fG(e,t){return e.kind!=="load"||!e.readOnlyRecovery||e.refresh||e.completionOnly?null:t instanceof Me&&gi(t.errorCode)?"refresh":"load"}function mG(e,t,n,r){if(e.kind==="load"&&n instanceof Me&&Ol(n.errorCode)!==null)return"completion";if(r.terminalRecovery)return e.kind==="load"?"completion":"load";const i=pG(e,t,n);if(i)return i;if(e.kind==="load"&&e.completionOnly)return hG(t);const o=fG(e,t);return o||(r.changed||r.rosterUnavailable||e.kind==="refresh"||e.kind==="load"&&e.refresh?"refresh":"load")}function hG(e){return e instanceof Me&&gi(e.errorCode)?"refresh":"completion"}function vG(e,t,n){return e.kind!=="load"||e.refresh||!(t instanceof Me)||t.errorCode!=="team_setup_confirmation_stale"||!n?null:n instanceof Me&&n.errorCode==="team_setup_roster_unavailable"?iC:n instanceof Me&&n.errorCode==="team_setup_completion_unavailable"?oC:n instanceof Me&&gi(n.errorCode)?bm:"The current Team setup could not be loaded. Retry to check the latest details."}function gG(e,t){return e.kind==="load"&&e.readOnlyRecovery?iC:e.kind!=="finish"?rC:t instanceof Me&&t.reason==="local_candidate_scan_budget_exceeded"?Y2:J2}function yG(e){const{command:t,cause:n,recoveryCause:r,changed:i,rosterUnavailable:o}=e,s=n instanceof Me?Ol(n.errorCode):null,c=_G(r instanceof Me?Ol(r.errorCode):null),l=c??s,d=l==="team_setup_completion_unavailable"&&t.kind==="finish"?bG(n):dC(l);return c?{completionCode:l,message:d??lC(t.kind),terminalRecoveryCode:c}:i?{completionCode:l,message:bm,terminalRecoveryCode:c}:o?{completionCode:l,message:gG(t,n),terminalRecoveryCode:c}:{completionCode:l,message:d??lC(t.kind),terminalRecoveryCode:c}}function bG(e){return e instanceof Me&&e.reason==="coordinator_route_missing"?`${aC} The coordinator may be running an older version.`:aC}function _G(e){return e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function lC(e){switch(e){case"load":return"Team setup details are temporarily unavailable. Retry to load the latest details.";case"assign_device":case"decide_device":case"clear_device":return"This device change could not be saved. Reload the latest details before trying again.";case"map_project":return"This Project mapping could not be saved. Reload the latest details before trying again.";case"refresh":return"Team setup could not be refreshed. Retry to load the latest server details.";case"finish":return"Team setup could not be finished. Reload the latest details before trying again.";case"completion_refresh":return"Team setup completed, but dependent views could not be refreshed.";default:return e}}function wG(e,t){return e.state==="completed"?"completed":e.unresolvedDeviceCount>0?"devices":!t&&e.projects.length>0||e.unresolvedProjectCount>0?"projects":"review"}function Sm(e){return e?.state==="reviewing"||e?.state==="ready_to_finish"}function Xn(e){return e.commands.some(t=>t.kind==="load"&&t.refresh||["refresh","assign_device","decide_device","clear_device","map_project","finish"].includes(t.kind))}function ns(e){return e.commands.some(t=>["load","refresh","finish"].includes(t.kind))}function Ll(e){return e.errors.find(t=>t.scope.kind==="global"||t.scope.kind==="load")??null}function SG(e){if(gi(e))return bm;if(e==="team_setup_roster_unavailable")return rC;const t=dC(Ol(e));return t||(e==="team_setup_incomplete"?"Team setup needs refreshed server details before review can continue.":"Team setup details are temporarily unavailable. Refresh to load the latest server state.")}function Ol(e){return e==="team_setup_completion_unavailable"||e==="team_setup_completion_conflict"||e==="team_setup_completion_invalid"?e:null}function dC(e){return e==="team_setup_completion_unavailable"?oC:e==="team_setup_completion_conflict"?Q2:e==="team_setup_completion_invalid"?X2:null}function uC(e){return e.kind==="global"||e.kind==="load"}function yi(e,t){const n=uC(t);return{...e,errors:e.errors.filter(r=>n?!uC(r.scope):r.scope.kind!==t.kind?!0:!("itemRef"in t)||!("itemRef"in r.scope)?!1:r.scope.itemRef!==t.itemRef)}}function CG(e,t){return t.kind==="assign_device"||t.kind==="decide_device"||t.kind==="clear_device"?yi(e,{kind:"device",itemRef:t.deviceRef}):t.kind==="map_project"?yi(e,{kind:"project",itemRef:t.projectRef}):{...e,errors:[]}}function RG(e,t,n){return e.status==="open"?{...e,commands:e.commands.map(r=>r.id===t?n(r):r)}:e}function pC(e,t){return e.commands.some(n=>n.kind==="completion_refresh"&&n.attemptId===t)}var IG={role:"list"},kG={role:"listitem"};function NG(e,t){return e?.state==="unavailable"||t?.retry==="refresh"||(t?.scope.kind==="load"||t?.hideStaleView===!0)&&!!e}function PG(e){const t=e.session,n=t.view,r=Ll(t),i=t.commands.some(w=>w.kind==="load"),o=ns(t)||Xn(t),s=t.commands.some(w=>w.kind==="finish"),c=NG(n,r),l=r!=null&&(!n||c),d=!Sm(n)||o||!!r,u=[r?"legacy-team-setup-error":null,o?"legacy-team-setup-operation-status":null,n?.state==="unavailable"?"legacy-team-setup-refresh":null].filter(Boolean).join(" ")||void 0,p=n?`Set up ${n.candidate.displayName}`:"Set up Team",f=t.errors.filter(w=>w.scope.kind==="device"||w.scope.kind==="project"),m=f.length>0,v=f.some(w=>w.retry==="refresh"),b=new Set(f.flatMap(w=>w.scope.kind==="device"?[w.scope.itemRef]:[])),g=new Set(f.flatMap(w=>w.scope.kind==="project"?[w.scope.itemRef]:[])),y=new Set(t.commands.flatMap(w=>"deviceRef"in w?[w.deviceRef]:[])),S=new Set(t.commands.flatMap(w=>"projectRef"in w?[w.projectRef]:[]));return a(Ln,{ariaDescribedby:"legacy-team-setup-description",ariaLabelledby:"legacy-team-setup-title",contentClassName:"modal legacy-team-setup-dialog",contentId:"legacyTeamSetupDialog",onCloseAutoFocus:e.onCloseAutoFocus,onOpenAutoFocus:e.onOpenAutoFocus,onOpenChange:w=>{w||e.onClose()},open:!0,overlayClassName:"modal-backdrop",overlayId:"legacyTeamSetupDialogBackdrop",children:a("div",{"aria-busy":o?"true":"false",className:"modal-card legacy-team-setup-card",children:[a("div",{className:"modal-header",children:[a("div",{id:"legacy-team-setup-title",tabIndex:-1,children:a(ju,{children:p})}),a(Hr,{ariaDisabled:o,ariaLabel:`Close ${p}`,onClick:e.onClose})]}),a("div",{className:"modal-body legacy-team-setup-body",children:[a("p",{className:"small",id:"legacy-team-setup-description",children:"Review device ownership and Project access before this Team can be used for sharing."}),i&&!n?a("p",{role:"status",children:"Loading the latest Team setup details…"}):null,r?a("div",{className:"legacy-team-setup-error legacy-team-setup-recovery",id:"legacy-team-setup-global-error",children:[l?a("strong",{children:"Current setup details are unavailable"}):null,a("p",{"aria-live":"assertive",id:"legacy-team-setup-error",role:"alert",children:r.message}),a("button",{"aria-busy":o?"true":void 0,"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-retry",onClick:()=>{o||e.onRetry()},type:"button",children:i?r.retry==="refresh"?"Refreshing…":"Retrying…":r.retry==="refresh"?"Retry loading current setup":"Retry"})]}):null,m?a("div",{className:"legacy-team-setup-error",id:"legacy-team-setup-item-errors",children:[f.map(w=>a("p",{"aria-live":"assertive",id:"itemRef"in w.scope?vm(w.scope.kind,w.scope.itemRef):void 0,role:"alert",children:w.message},"itemRef"in w.scope?`${w.scope.kind}:${w.scope.itemRef}`:w.scope.kind)),a("button",{"aria-busy":o?"true":void 0,"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",id:"legacy-team-setup-item-retry",onClick:()=>{o||e.onRetry()},type:"button",children:i?v?"Refreshing…":"Retrying…":v?"Refresh Team setup":"Retry"})]}):null,n?a(G,{children:[t.step!=="completed"&&!l?a(TG,{onNavigate:e.onNavigate,step:t.step,unresolvedDeviceCount:n.unresolvedDeviceCount,unresolvedProjectCount:n.unresolvedProjectCount}):null,i?a("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-refresh-status",role:"status",children:"Refreshing Team setup details…"}):null,a("p",{"aria-live":"polite",className:"small",id:"legacy-team-setup-operation-status",role:"status",children:t.message}),l?null:t.step==="devices"?a(F2,{blocked:d,blockedDescriptionId:u,blockedDeviceRefs:b,busyDeviceRefs:y,detail:n,onAssign:e.onAssign,onClear:e.onClear,onDecision:e.onDecide}):t.step==="projects"?a(U2,{blocked:d,blockedDescriptionId:u,blockedProjectRefs:g,busyProjectRefs:S,detail:n,onContinue:()=>e.onNavigate("review"),onMap:e.onMap}):t.step==="review"&&n.state==="ready_to_finish"?a(H2,{blocked:d||m,blockedDescriptionId:m?"legacy-team-setup-item-errors":u,detail:n,finishing:s,onFinish:e.onFinish}):a(AG,{busy:o,canFinish:n.state==="ready_to_finish",onRefresh:e.onRefresh,recoveryRequired:c,step:t.step})]}):null]}),a("div",{className:"modal-footer legacy-team-setup-actions",children:a("button",{"aria-disabled":o?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:e.onClose,type:"button",children:"Close"})})]})})}function TG(e){const t=e.unresolvedDeviceCount>0,n=e.unresolvedProjectCount>0;return a(G,{children:[a("ol",{...IG,"aria-label":"Team setup steps",className:"legacy-team-setup-steps",children:[{label:"Devices",step:"devices"},{label:"Projects",step:"projects"},{label:"Review",step:"review"}].map((i,o)=>{const s=i.step==="projects"?t:i.step==="review"?t||n:!1,c=s?t?"legacy-team-setup-block-devices":"legacy-team-setup-block-projects":void 0;return h("li",{...kG,className:"legacy-team-setup-step",key:i.step},a("span",{"aria-hidden":"true",className:"legacy-team-setup-step-number",children:o+1}),a("button",{"aria-current":e.step===i.step?"step":void 0,"aria-describedby":c,"aria-disabled":s?"true":void 0,"aria-label":`Step ${o+1}: ${i.label}`,className:"settings-button legacy-team-setup-target",onClick:()=>e.onNavigate(i.step),type:"button",children:i.label}))})}),t?a("p",{className:"small",id:"legacy-team-setup-block-devices",children:"Finish the device decisions before mapping Projects or reviewing access."}):null,n?a("p",{className:"small",id:"legacy-team-setup-block-projects",children:"Finish the Project mappings before reviewing access."}):null]})}function AG(e){return e.step==="completed"?a("section",{"aria-labelledby":"legacy-team-setup-step-completed",children:[a("h3",{id:"legacy-team-setup-step-completed",tabIndex:-1,children:"Team setup complete"}),a("p",{children:"This Team is ready for Project sharing."})]}):e.step!=="review"?null:a("section",{"aria-labelledby":"legacy-team-setup-step-review",children:[a("h3",{id:"legacy-team-setup-step-review",tabIndex:-1,children:"Review and finish"}),a("p",{children:e.canFinish?"The server has confirmed that this Team is ready for final review.":"Final review is waiting for the latest setup details."}),a("p",{className:"small",children:"Next setup action: review the access summary before finishing."}),!e.canFinish&&!e.recoveryRequired?a("button",{"aria-busy":e.busy?"true":void 0,"aria-disabled":e.busy?"true":void 0,className:"settings-button legacy-team-setup-target",onClick:()=>{e.busy||e.onRefresh()},type:"button",children:"Refresh Team setup"}):null]})}var EG={clearDecision:rN,finish:aN,loadDetail:eN,onCompleted:()=>{},refreshCandidate:oN,saveAssignment:tN,saveDecision:nN,saveProjectMapping:iN},Cm="codemem:open-legacy-team-setup";function fC(e){if(!e)return!1;const t={candidateRef:e,handled:!1,returnFocus:document.activeElement instanceof HTMLElement?document.activeElement:null};return window.dispatchEvent(new CustomEvent(Cm,{detail:t})),t.handled}function xG(e){if(!e?.isConnected||e.tabIndex<0||e.matches(":disabled")||e.closest('[hidden], [inert], [aria-hidden="true"]'))return!1;for(let t=e;t;t=t.parentElement){const n=window.getComputedStyle(t);if(n.display==="none"||n.visibility==="hidden"||n.visibility==="collapse")return!1}return!0}function DG({dependencies:e}){const[t,n]=T(Z2),r=D(null),i=be(()=>V2(e),[e]),o=l=>{n(d=>_m(d,l))};return at(()=>{const l=d=>{const u=d;u.detail.handled=!0,r.current=u.detail.returnFocus,n(p=>p.status==="open"&&Xn(p)?_m(p,{type:"open_blocked",message:"Wait for the current Team setup change to finish before opening another Team."}):_m(p,{type:"open",candidateRef:u.detail.candidateRef}))};return window.addEventListener(Cm,l),()=>{window.removeEventListener(Cm,l)}},[]),q(()=>{if(t.status==="open")for(const l of t.commands.filter(d=>d.status==="pending"))o({type:"command_started",id:l.id}),i(l).then(d=>o({type:"effect_outcome",outcome:d}))},[i,t]),q(()=>{if(t.status!=="open"||!t.focus)return;const l=document.getElementById(t.focus.targetId)??document.getElementById("legacy-team-setup-title");l&&(l.focus(),o({type:"focus_applied",id:t.focus.id}))},[t]),t.status==="closed"?null:a(PG,{session:t,onAssign:(l,d)=>o({type:"assign_device",deviceRef:l.deviceRef,targetIdentityRef:d}),onClear:l=>o({type:"clear_device",deviceRef:l.deviceRef}),onClose:()=>{if(Xn(t)){o({type:"close_blocked",message:"Team setup will stay open while this change saves. Close it after saving finishes."});return}o({type:"close"})},onCloseAutoFocus:l=>LG(l,r),onDecide:(l,d,u)=>{if(d==="included"&&!u){o({type:"open_blocked",message:`Save a person assignment before including ${l.displayName}.`});return}o({type:"decide_device",deviceRef:l.deviceRef,decision:d,...u?{targetIdentityRef:u}:{}})},onFinish:()=>o({type:"finish"}),onMap:(l,d)=>o({type:"map_project",projectRef:l.projectRef,resolvedProjectRef:d}),onNavigate:l=>o({type:"navigate",step:l}),onOpenAutoFocus:jG,onRefresh:()=>o({type:"refresh"}),onRetry:()=>o({type:"retry"})})}var jG=e=>{const t=document.getElementById("legacy-team-setup-title");t&&(e.preventDefault(),t.focus())};function LG(e,t){e.preventDefault();const n=document.querySelector('.tab-btn[aria-current="page"]');(xG(t.current)?t.current:n)?.focus(),t.current=null}function OG(e,t={}){const n={...EG,...t};ke(a(DG,{dependencies:n}),e)}function Rm(e,t){return`${e}-${Array.from(t,n=>(n.codePointAt(0)??0).toString(16).padStart(6,"0")).join("")||"empty"}`}function $l(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function wo(e){return e.identity_source!=="unmapped"&&!$l(e)}function mC(e){if(!e)return"—";const t=new Date(e);return Number.isNaN(t.getTime())?e:t.toLocaleString()}function $G(e){return e.git_remote||e.repository_identity||e.cwd||""}function MG(e){return e==="git_repository"?"git repository":e.replaceAll("_"," ")}function Im(e,t){const n=e.kind==="team_default"?`${e.label||"Untitled Space"} (default)`:e.label||"Untitled Space";return t.some(r=>r.scope_id!==e.scope_id&&(r.label||"Untitled Space")===(e.label||"Untitled Space"))?`${n} · Space ID ${e.scope_id}`:n}function Ml(e,t){if(!e)return"—";if(t.scopeLabels[e])return t.scopeLabels[e];for(const n of t.scopeGroups){const r=n.scopes.find(i=>i.scope_id===e);if(r)return`${Im(r,n.scopes)} · ${n.label}`}return"Unknown Space"}function hC(e,t){return e?t.scopeGroups.some(n=>n.scopes.some(r=>r.scope_id===e)):!1}function vC(e,t,n){for(const r of[t,e.suggested_scope_id,e.resolved_scope_id])if(hC(r,n))return r??"";return e.resolved_scope_id||""}function gC(e,t){return $l(e)?"From other devices":Ml(e.resolved_scope_id,t)}function FG(e){switch(e){case"exact_mapping":return"assigned to a Space";case"pattern_mapping":return"assigned by matching rule";case"explicit_override":return"manually assigned";default:return"stays on this device"}}function BG(e){const t=e.person.display_name;switch(e.lifecycle.state){case"waiting_for_acceptance":return`Invitation sent to ${t}`;case"active":return`Shared with ${t}`;case"waiting_for_device":return`Sharing with ${t}`;case"needs_attention":return`Sharing with ${t} needs attention`;case"revoking":return`Removing sharing with ${t}`;case"revoked":return`Previously shared with ${t}`;case"cancelled":return`Invitation to ${t} cancelled`;default:return`Setting up sharing with ${t}`}}function km(e){return(e.guardrail_warnings??[]).filter(t=>t.severity==="warning").length}function qG(e){const t=[];return(km(e)>0||e.statuses.includes("needs_attention"))&&t.push({label:"Needs attention",tone:"badge-offline"}),e.statuses.includes("suggested")&&t.push({label:"Suggested"}),e.statuses.includes("legacy_review")&&t.push({label:"Older shared data",tone:"badge-offline"}),$l(e)&&t.push({label:"From another device"}),e.identity_source==="unmapped"&&t.push({label:"No stable identity",tone:"badge-offline"}),t}function UG(e,t){return[["Workspace identity",e.workspace_identity],["Repository identity",e.repository_identity],["Project",e.project],["CWD",e.cwd],["Git remote",e.git_remote],["Git branch",e.git_branch],["Current Space",gC(e,t)],["Suggested Space",e.suggested_scope_id?Ml(e.suggested_scope_id,t):null],["Advanced: current Space ID",e.resolved_scope_id],["Advanced: suggested Space ID",e.suggested_scope_id],["Suggestion reason",e.suggestion_reason],["Sessions",e.session_count],["Memories",e.memory_count??"count unavailable"]]}function GG({code:e}){return a("strong",{children:[{basename_collision_review:"Name collision",broad_org_domain_pattern:"Broad mapping",home_directory_org_domain_pattern:"Broad mapping",scope_reassignment_old_copies:"Previous copies",unknown_project_local_only:"Current behavior"}[e]??"Review item",": "]})}function HG({model:e}){const{project:t}=e;return t.sharing?.length?a("div",{className:"settings-note project-sharing-summary",children:[a("strong",{children:"Project sharing"}),a("ul",{"aria-label":`People sharing ${t.display_project}`,children:t.sharing.map(n=>a("li",{children:[a("strong",{children:BG(n)})," — ",n.lifecycle.label,"."," ",n.lifecycle.explanation]},n.person.actor_id))})]}):null}function VG({model:e}){const t=e.project.worktrees??[];return t.length<2?null:a("div",{className:"settings-note",children:[a("strong",{children:"Worktrees"}),a("ul",{"aria-label":`Worktrees for ${e.project.display_project}`,children:t.map(n=>a("li",{children:n.cwd},n.cwd))})]})}function KG({model:e,view:t}){const{project:n}=e,r=$l(n),i=(n.guardrail_warnings??[]).filter(o=>o.severity==="warning");return a(G,{children:[a("div",{className:"project-inventory-domain",children:gC(n,t)}),a("div",{className:"project-inventory-meta",children:[r?"source-owned project":FG(n.resolution_reason)," ·"," ",MG(n.identity_source)," · ",mC(n.latest_session_at)]}),a(HG,{model:e}),a(VG,{model:e}),r?a("div",{className:"settings-note",children:"Read-only here. Change it on the source device."}):null,n.identity_source==="unmapped"?a("div",{className:"settings-note",children:"Stays on this device until it has a path, git remote, or workspace id."}):null,n.suggested_scope_id&&n.suggested_scope_id!==n.resolved_scope_id?a("div",{className:"settings-note project-suggestion-note",children:n.suggestion_reason?`Suggestion: ${n.suggestion_reason}`:`Suggestion: assign this project to ${Ml(n.suggested_scope_id,t)}.`}):null,i.length>0?a("div",{className:"settings-note project-attention-note",children:["Needs attention: ",i.map(o=>o.message).join(" ")]}):null,a("dl",{className:"project-detail-grid",children:UG(n,t).map(([o,s])=>a("div",{className:"project-detail-pair",children:[a("dt",{children:o}),a("dd",{children:s==null||s===""?"—":String(s)})]},o))})]})}function zG(e){const{callbacks:t,currentAssignable:n,model:r,scopeId:i,selectRef:o,setScopeId:s,view:c}=e,{project:l}=r,d=Rm("project-domain",r.key),u=!i||i===l.resolved_scope_id&&!n,p=l.suggested_scope_id&&i===l.suggested_scope_id?"Confirm suggestion":"Save Space";return a(G,{children:[a("label",{className:"sr-only",htmlFor:d,children:["Space for ",l.display_project]}),a("select",{className:"project-domain-select",id:d,onBlur:t.onSpaceSelectBlur,onChange:f=>{s(f.currentTarget.value),t.setProjectScopeDraft(l.workspace_identity,f.currentTarget.value)},ref:o,value:i,children:[!n&&l.resolved_scope_id?a("option",{disabled:!0,value:l.resolved_scope_id,children:[Ml(l.resolved_scope_id,c)," — not assignable"]}):null,c.scopeGroups.map(f=>a("optgroup",{label:f.label,children:f.scopes.map(m=>a("option",{value:m.scope_id,children:Im(m,f.scopes)},m.scope_id))},f.key))]}),a("button",{className:"settings-button",disabled:u,onClick:()=>{t.saveProjectScope(l.workspace_identity,i)},type:"button",children:p})]})}function WG({callbacks:e,model:t}){const{project:n}=t;return a(G,{children:[a("button",{className:"settings-button",onClick:()=>{e.keepProjectLocal(n.workspace_identity)},type:"button",children:"Keep local-only"}),a("button",{className:"settings-button",disabled:n.mapping_id==null||n.resolution_reason!=="exact_mapping",onClick:()=>{e.removeProjectScope(n.workspace_identity)},type:"button",children:"Remove mapping"}),a("button",{className:"settings-button",disabled:n.session_count===0,title:n.session_count===0?"No sessions are available to reassign for this saved mapping.":void 0,onClick:()=>{e.reassignProject(n.workspace_identity)},type:"button",children:"Change project…"}),a("button",{className:"settings-button danger",disabled:(n.memory_count??0)===0,onClick:()=>{e.forgetProject(n.workspace_identity)},type:"button",children:"Forget local memories…"})]})}function JG({callbacks:e,confirmationActionRef:t,model:n}){const r=n.pendingConfirmation;return r?a("div",{className:"settings-note project-guardrail-confirmation project-space-guardrail-confirmation",role:"alert",children:[a("strong",{children:"Confirmation required before saving this Space."}),a("p",{children:"Codemem can save this change after you acknowledge the checks below. Verify the workspace details, then confirm to complete the save."}),a("ul",{children:r.warnings.map(i=>a("li",{children:[a(GG,{code:i.code}),a("span",{children:i.message})]},`${i.code}:${i.message}`))}),a("button",{className:"settings-button",onClick:()=>{e.confirmProjectScope(n.project.workspace_identity)},ref:t,type:"button",children:"I understand, save Space"}),a("button",{className:"settings-button",onClick:()=>e.cancelProjectScopeConfirmation(n.project.workspace_identity),type:"button",children:"Cancel"})]}):null}function YG({callbacks:e,confirmationActionRef:t,model:n}){const r=n.pendingForgetConfirmation;if(!r)return null;const i=r.localOwnedMemoryCount===1?"memory":"memories",o=r.peerOwnedMemoryCount===1?"memory":"memories";return a("div",{className:"settings-note project-guardrail-confirmation",role:"alert",children:[a("strong",{children:"Confirm project memory cleanup."}),a("p",{children:[r.localOwnedMemoryCount.toLocaleString()," locally owned ",i," will be forgotten. ",r.peerOwnedMemoryCount.toLocaleString()," peer-owned ",o," will be left unchanged."]}),a("p",{children:"Use this only to clean up wrongly attributed local project inventory; it forgets actual local memories on this device."}),a("button",{className:"settings-button danger",onClick:()=>{e.forgetProject(n.project.workspace_identity,{confirmed:!0})},ref:t,type:"button",children:"I understand, forget local memories"}),a("button",{className:"settings-button",onClick:()=>e.cancelProjectForgetConfirmation(n.project.workspace_identity),type:"button",children:"Cancel"})]})}function QG(e){const{callbacks:t,model:n,view:r}=e,{project:i}=n,o=wo(i),s=o&&i.memory_count!=null&&!i.guardrail_warnings.some(c=>c.requires_confirmation);return a("div",{className:"project-inventory-actions",children:[s?a("button",{className:"settings-button",disabled:!r.shareInventoryReady,onClick:()=>t.shareProject(i.workspace_identity),title:r.shareInventoryReady?void 0:"The complete project list is unavailable.",type:"button",children:"Share"}):null,o?a(G,{children:[a(zG,{...e}),a(WG,{callbacks:t,model:n}),a(JG,{callbacks:t,confirmationActionRef:e.confirmationActionRef,model:n}),a(YG,{callbacks:t,confirmationActionRef:e.confirmationActionRef,model:n})]}):null]})}function XG(e){const{model:t,onOpenChange:n,open:r,view:i}=e,{project:o}=t,s=wo(o),[c,l]=T(()=>vC(o,t.draftScopeId,i));q(()=>{l(vC(o,t.draftScopeId,i))},[t.draftScopeId,o,i]);const d=i.scopeGroups.some(u=>u.scopes.some(p=>p.scope_id===o.resolved_scope_id));return a("tr",{className:"project-inventory-details-row",children:a("td",{className:"project-inventory-details-cell",colSpan:7,children:a("details",{className:"project-inventory-details",onToggle:u=>n(u.currentTarget.open),open:r,children:[a("summary",{"data-project-focus-key":`admin:${s}:${o.workspace_identity}`,children:[a("span",{children:"Details"}),km(o)>0?a("span",{className:"badge badge-offline",children:["Needs attention · ",km(o)]}):null]}),a("div",{className:"project-inventory-details-body",children:[a(KG,{model:t,view:i}),a(QG,{...e,currentAssignable:d,scopeId:c,setScopeId:l})]})]})})})}function ZG(e,t,n){if(n.length===0)return null;if(e==="Home")return n[0]??null;if(e==="End")return n.at(-1)??null;const r=Math.max(0,n.indexOf(t));return e==="ArrowDown"?n[(r+1)%n.length]??null:e==="ArrowUp"?n[(r-1+n.length)%n.length]??null:null}function eH({actions:e,close:t,dismiss:n,enabled:r,itemRefs:i,label:o,menuId:s}){return a("div",{"aria-label":o,className:"feed-menu-panel project-row-menu-panel",id:s,onKeyDown:l=>{if(l.key==="Tab"){n();return}if(l.key==="Escape"){l.preventDefault(),t();return}const d=i.current.indexOf(document.activeElement),u=ZG(l.key,d,r);u!=null&&(l.preventDefault(),i.current[u]?.focus())},role:"menu",children:e.map((l,d)=>a("button",{className:`feed-menu-item${l.danger?" danger":""}`,disabled:l.disabled,onClick:()=>{t(),l.onSelect()},ref:u=>{i.current[d]=u},role:"menuitem",tabIndex:-1,type:"button",children:l.label},l.label))})}function yC({actions:e,label:t}){const[n,r]=T(!1),i=D("first"),o=D([]),s=Xt(),c=D(null),l=D(null),d=e.flatMap((m,v)=>m.disabled?[]:[v]),u=()=>{r(!1),queueMicrotask(()=>l.current?.focus())},p=()=>r(!1);return q(()=>{if(!n)return;const m=i.current==="last"?d.at(-1):d[0];queueMicrotask(()=>(m==null?l.current:o.current[m])?.focus());const v=b=>{c.current?.contains(b.target)||r(!1)};return document.addEventListener("pointerdown",v),()=>document.removeEventListener("pointerdown",v)},[n]),a("div",{className:"project-row-menu",ref:c,children:[a("button",{"aria-controls":s,"aria-expanded":n,"aria-haspopup":"menu","aria-label":t,className:"feed-menu-trigger","data-state":n?"open":"closed",onClick:()=>{i.current="first",r(m=>!m)},onKeyDown:m=>{m.key!=="ArrowDown"&&m.key!=="ArrowUp"||(m.preventDefault(),i.current=m.key==="ArrowUp"?"last":"first",r(!0))},ref:l,type:"button",children:"⋯"}),n?a(eH,{actions:e,close:u,dismiss:p,enabled:d,itemRefs:o,label:t,menuId:s}):null]})}function tH(e){const t=[{disabled:!e.canAssign,label:"Space assignment…",onSelect:e.onOpenSpaceAssignment},{disabled:!e.canChangeProject,label:"Change project…",onSelect:e.onChangeProject},{disabled:!e.canAssign,label:"Keep local-only",onSelect:e.onKeepLocal},...e.canRemoveMapping?[{label:"Remove mapping",onSelect:e.onRemoveMapping}]:[],{danger:!0,disabled:!e.canForget,label:"Forget local memories…",onSelect:e.onForget}];return a(yC,{actions:t,label:`More actions for ${e.label}`})}function nH({label:e,onOpenSpaceAssignment:t}){return a(yC,{actions:[{label:"Space assignment for all…",onSelect:t}],label:`More actions for ${e}`})}function bC({available:e,cluster:t=!1,recipients:n}){if(!e)return a("span",{className:"project-recipient-status tertiary",children:"Unavailable"});if(n.length===0)return a("span",{className:"project-recipient-status tertiary",children:"Not shared"});const r=n.slice(0,2),i=n.length-r.length;return a("div",{className:"project-recipient-summary",children:[a("ul",{"aria-label":"Active recipients",className:"project-recipient-chips",children:[r.map(o=>a("li",{className:`project-recipient-chip project-recipient-chip-${o.kind.toLowerCase()}`,children:[o.kind,": ",o.displayName]},o.key)),i>0?a("li",{className:"project-recipient-chip",children:["+",i]}):null]}),t?a("span",{className:"project-recipient-status",children:[n.length," recipients"]}):null]})}function rH({model:e,view:t}){const{project:n}=e;return a(G,{children:[a("td",{className:"project-inventory-cell project-inventory-number","data-label":"Memories",children:(n.memory_count??0).toLocaleString()}),a("td",{className:"project-inventory-cell project-inventory-number","data-label":"Sessions",children:n.session_count.toLocaleString()}),a("td",{className:"project-inventory-cell project-inventory-latest","data-label":"Last activity",children:mC(n.latest_session_at)}),a("td",{className:"project-inventory-cell project-inventory-shared","data-label":"Shared with",children:a(bC,{available:t.recipientPolicyReady,recipients:e.recipients})})]})}function iH({callbacks:e,model:t,onOpenDetails:n,view:r}){const{project:i}=t;return!wo(i)&&!t.manageable?a("td",{className:"project-inventory-cell project-inventory-row-actions"}):a("td",{className:"project-inventory-cell project-inventory-row-actions",children:[t.manageable?a("button",{"aria-label":`Update sharing for ${i.display_project}`,className:"settings-button project-recipient-action project-selection-target","data-project-focus-key":`manage:${i.workspace_identity}`,disabled:!r.selection.ready,onClick:()=>e.manageRecipients([i.workspace_identity]),type:"button",children:"Update sharing"}):null,wo(i)?a(tH,{canAssign:!0,canChangeProject:i.session_count>0,canForget:(i.memory_count??0)>0,canRemoveMapping:i.mapping_id!=null&&i.resolution_reason==="exact_mapping",label:i.display_project,onChangeProject:()=>{e.reassignProject(i.workspace_identity)},onForget:()=>{e.forgetProject(i.workspace_identity)},onKeepLocal:()=>{e.keepProjectLocal(i.workspace_identity)},onOpenSpaceAssignment:n,onRemoveMapping:()=>{e.removeProjectScope(i.workspace_identity)}}):null]})}function oH(e){const{callbacks:t,child:n,model:r,titleId:i,view:o}=e,{project:s}=r,c=$G(s);return a("tr",{className:`project-inventory-row-header project-inventory-table-row${n?" project-inventory-child-row":""}`,children:[a("td",{className:"project-inventory-cell project-inventory-select-cell",children:r.manageable?a("label",{className:"project-selection-control project-selection-target",children:[a("input",{"aria-label":`Select ${s.display_project} for recipient sharing`,checked:r.selected,className:"project-selection-checkbox","data-project-focus-key":`select:${s.workspace_identity}`,onChange:()=>t.toggleSelection([s.workspace_identity]),type:"checkbox"}),a("span",{className:"sr-only",children:["Select ",s.display_project," for recipient sharing"]})]}):null}),a("th",{className:"project-inventory-cell project-inventory-project-cell",scope:"row",children:[a("strong",{className:"project-inventory-title",id:i,children:s.display_project}),c?a("span",{className:"project-inventory-signal mono small tertiary",children:c}):null,a("div",{className:"project-inventory-badges",children:qG(s).map(l=>a(Ue,{tone:l.tone,variant:"badge",children:l.label},l.label))})]}),a(rH,{model:r,view:o}),a(iH,{...e})]})}function _C({callbacks:e,child:t=!1,clusterKey:n,model:r,view:i}){const{project:o}=r,[s,c]=T(r.detailsOpen),l=D(null),d=D(null),u=v=>{c(v),e.setProjectDetailsOpen(r.detailKey,v)};q(()=>{r.detailsOpen&&c(!0)},[r.detailsOpen]);const p=!!(r.pendingConfirmation||r.pendingForgetConfirmation);q(()=>{p&&(u(!0),queueMicrotask(()=>d.current?.focus()))},[p]);const f=()=>{u(!0),queueMicrotask(()=>l.current?.focus())},m=Rm("project-title",r.detailKey);return a("tbody",{"aria-labelledby":m,className:`project-inventory-row${t?" project-inventory-child":""}`,"data-project-cluster-key":n,"data-project-repairable":String(wo(o)),"data-project-workspace-identity":o.workspace_identity,children:[a(oH,{callbacks:e,child:t,model:r,onOpenDetails:f,titleId:m,view:i}),a(XG,{callbacks:e,confirmationActionRef:d,model:r,onOpenChange:u,open:s,selectRef:l,view:i})]})}function aH(e){const t=e.projects.filter(o=>wo(o.project)),n=t.flatMap(o=>(o.project.guardrail_warnings??[]).filter(s=>s.requires_confirmation).map(s=>({project:o,warning:s}))),r=new Set(t.map(o=>o.project.suggested_scope_id).filter(o=>!!o)),i=new Set(t.map(o=>o.project.resolved_scope_id));return{assignable:t,blocking:n,hasMixed:r.size>1||i.size>1,memoryCount:e.projects.reduce((o,s)=>o+(s.project.memory_count??0),0),sessionCount:e.projects.reduce((o,s)=>o+s.project.session_count,0),warningTotal:e.projects.reduce((o,s)=>o+(s.project.guardrail_warnings??[]).filter(c=>c.severity==="warning").length,0)}}function sH(e){const t=D(null);return q(()=>{t.current&&(t.current.indeterminate=e.selectedProjectIds.length>0&&e.selectedProjectIds.length<e.projectIds.length)},[e.projectIds.length,e.selectedProjectIds.length]),t}function cH({model:e,summary:t,view:n}){return a(G,{children:[a("td",{className:"project-inventory-cell project-inventory-number","data-label":"Memories",children:t.memoryCount.toLocaleString()}),a("td",{className:"project-inventory-cell project-inventory-number","data-label":"Sessions",children:t.sessionCount.toLocaleString()}),a("td",{className:"project-inventory-cell project-inventory-latest","data-label":"Last activity",children:"—"}),a("td",{className:"project-inventory-cell project-inventory-shared","data-label":"Shared with",children:a(bC,{available:n.recipientPolicyReady,cluster:!0,recipients:e.recipients})})]})}function lH({callbacks:e,model:t,onOpenAssignment:n,summary:r,view:i}){return a("td",{className:"project-inventory-cell project-inventory-row-actions",children:[t.projectIds.length>0?a("button",{"aria-label":`Manage sharing for ${t.label}`,className:"settings-button project-recipient-action project-selection-target",disabled:!i.selection.ready,onClick:()=>e.manageRecipients(t.projectIds),type:"button",children:"Manage sharing"}):null,r.assignable.length>0?a(nH,{label:t.label,onOpenSpaceAssignment:n}):null]})}function dH(e){const{callbacks:t,model:n,onToggleWorktrees:r,summary:i,titleId:o,worktreesOpen:s}=e,c=sH(n),l=e.view.rows.filter(p=>p.kind==="cluster"&&p.label===n.label),d=l.length>1?` (group ${l.findIndex(p=>p.key===n.key)+1} of ${l.length})`:"",u=n.projectIds.length>0&&n.selectedProjectIds.length===n.projectIds.length;return a("tr",{className:"project-inventory-row-header project-inventory-table-row",children:[a("td",{className:"project-inventory-cell project-inventory-select-cell",children:n.projectIds.length>0?a("label",{className:"project-selection-control project-selection-target",children:[a("input",{"aria-label":`Select all identities for ${n.label}`,checked:u,className:"project-selection-checkbox",onChange:()=>t.toggleSelection(n.projectIds),ref:c,type:"checkbox"}),a("span",{className:"sr-only",children:["Select all identities for ",n.label]})]}):null}),a("th",{className:"project-inventory-cell project-inventory-project-cell",scope:"row",children:[a("strong",{className:"project-inventory-title",id:o,children:n.label}),a("div",{className:"project-inventory-badges",children:[a(Ue,{variant:"badge",children:[n.projects.length," worktrees"]}),a("button",{"aria-expanded":s,"aria-label":`${s?"Hide":"Show"} worktrees for ${n.label}${d}`,className:"settings-button project-worktrees-toggle",onClick:p=>{s&&p.currentTarget.focus(),r()},type:"button",children:s?"Hide worktrees":"Show worktrees"}),i.warningTotal>0?a(Ue,{tone:"badge-offline",variant:"badge",children:["Needs attention · ",i.warningTotal]}):null]})]}),a(cH,{...e}),a(lH,{...e})]})}function uH(e){const{callbacks:t,model:n,scopeId:r,selectRef:i,setScopeId:o,summary:s,view:c}=e;if(s.assignable.length===0){const d=n.projects.every(u=>u.project.read_only)?"These project identities were received from other devices. Change project or Space assignments on their source devices.":"These project identities cannot be bulk assigned until they have stable local identities. Expand each identity for details.";return a("div",{className:"settings-note",children:d})}const l=hC(r,c);return a(G,{children:[a("select",{"aria-label":`Space for ${n.label} group`,className:"project-domain-select",onBlur:t.onSpaceSelectBlur,onChange:d=>{o(d.currentTarget.value),t.setClusterScopeDraft(n.key,d.currentTarget.value)},ref:i,value:r,children:[a("option",{value:"",children:"Choose Space…"}),c.scopeGroups.map(d=>a("optgroup",{label:d.label,children:d.scopes.map(u=>a("option",{value:u.scope_id,children:Im(u,d.scopes)},u.scope_id))},d.key))]}),a("button",{className:"settings-button",disabled:!l||s.blocking.length>0,onClick:()=>{t.saveClusterScope(n.key,r)},type:"button",children:["Save Space for ",s.assignable.length," ",s.assignable.length===1?"identity":"identities"]})]})}function pH({summary:e}){return e.blocking.length>0?a("div",{className:"settings-note project-attention-note",children:["One or more identities in this group need individual review before bulk assignment.",a("ul",{children:e.blocking.map(({project:t,warning:n})=>a("li",{children:[a("strong",{children:["Blocked identity: ",t.project.workspace_identity]})," —"," ",n.message]},`${t.key}:${n.code}`))})]}):e.hasMixed?a("div",{className:"settings-note project-attention-note",children:"This group has mixed suggestions or current Spaces. Choose a Space explicitly before bulk assignment."}):null}function fH(e){const{onOpenChange:t,open:n,summary:r}=e;return a("tr",{className:"project-inventory-details-row project-inventory-cluster-details-row",children:a("td",{className:"project-inventory-details-cell",colSpan:7,children:a("details",{className:"project-inventory-details",onToggle:i=>t(i.currentTarget.open),open:n,children:[a("summary",{children:[a("span",{children:"Advanced Space assignment"}),r.warningTotal>0?a("span",{className:"badge badge-offline",children:["Needs attention · ",r.warningTotal]}):null]}),a("div",{className:"project-inventory-details-body",children:a("div",{className:"project-inventory-actions",children:[a(uH,{...e}),a(pH,{summary:r})]})})]})})})}function mH(e){const{callbacks:t,model:n}=e,[r,i]=T(n.detailsOpen),[o,s]=T(n.draftScopeId??""),c=D(null);q(()=>{n.detailsOpen&&i(!0)},[n.detailsOpen]),q(()=>s(n.draftScopeId??""),[n.draftScopeId]);const l=aH(n),d=f=>{i(f),t.setClusterDetailsOpen(n.key,f)},u=()=>{d(!0),queueMicrotask(()=>c.current?.focus())},p=Rm("project-cluster-title",n.key);return a(G,{children:[a("tbody",{"aria-labelledby":p,className:"project-inventory-row project-inventory-cluster","data-project-cluster-key":n.key,children:[a(dH,{...e,onOpenAssignment:u,onToggleWorktrees:()=>t.setClusterWorktreesOpen(n.key,!n.worktreesOpen),summary:l,titleId:p,worktreesOpen:n.worktreesOpen}),a(fH,{...e,onOpenChange:d,open:r,scopeId:o,selectRef:c,setScopeId:s,summary:l})]}),n.worktreesOpen?n.projects.map(f=>a(_C,{callbacks:t,child:!0,clusterKey:n.key,model:f,view:e.view},`${f.project.read_only?"received":"local"}:${f.key}`)):null]})}function hH({callbacks:e,error:t,view:n}){return t?a("div",{className:"settings-note",role:"status",children:t}):n.rows.length===0?a("div",{className:"settings-note",children:"No matching projects"}):a("table",{className:"project-inventory-table",children:[a("caption",{className:"sr-only",children:"Projects"}),a("thead",{children:a("tr",{className:"project-inventory-table-header project-inventory-table-row",children:[a("th",{scope:"col",children:a("span",{className:"sr-only",children:"Select"})}),a("th",{scope:"col",children:"Project"}),a("th",{scope:"col",children:"Memories"}),a("th",{scope:"col",children:"Sessions"}),a("th",{scope:"col",children:"Last activity"}),a("th",{scope:"col",children:"Shared with"}),a("th",{scope:"col",children:a("span",{className:"sr-only",children:"Actions"})})]})}),n.rows.map(r=>r.kind==="cluster"?a(mH,{callbacks:e,model:r,view:n},r.key):a(_C,{callbacks:e,model:r,view:n},r.detailKey))]})}function vH(e,t,n,r){ke(a(hH,{callbacks:n,error:r,view:t}),e)}function gH(e){if(e?.contains(document.activeElement)&&document.activeElement instanceof HTMLButtonElement)return document.activeElement.dataset.teamSetupCandidateRef}function yH(e,t,n){if(t){for(const r of e.querySelectorAll("button"))if(r.dataset.teamSetupCandidateRef===t){r.focus();return}n()}}function bH(e,t){const n=document.createElement("div");n.className="project-inventory-actions";const r=document.createElement("strong");if(r.textContent=e.displayName,n.appendChild(r),!t)return n;const i=document.createElement("button");return i.setAttribute("aria-label",`Finish setting up ${e.displayName}`),i.className="settings-button",i.type="button",i.textContent="Finish setting up this Team",i.dataset.teamSetupCandidateRef=e.candidateRef,i.addEventListener("click",()=>t(e.candidateRef)),n.appendChild(i),n}function _H(e,t){const n=document.createElement("section");n.className="card project-team-setup-entry",n.dataset.teamSetupSignature=JSON.stringify(e.candidates.map(o=>[o.candidateRef,o.displayName]));const r=document.createElement("h2");r.textContent="Finish setting up this Team";const i=document.createElement("p");i.className="section-meta",i.textContent="Tell Codemem who uses each device before using this Team for Project sharing.",n.append(r,i);for(const o of e.candidates)n.appendChild(bH(o,t.onOpenTeamSetup));return n}function wH(e,t,n){const r=t?.candidates??[],i=e.querySelector(":scope > .project-team-setup-entry");i?.querySelector(".project-team-setup-status")?.remove();const o=gH(i);if(r.length===0){i?.remove(),e.hidden=e.querySelector(":scope > .project-recipient-policy-review-content")?.hidden!==!1,o&&n.onFocusFallback();return}if(!t)return;const s=JSON.stringify(r.map(l=>[l.candidateRef,l.displayName]));if(i?.dataset.teamSetupSignature===s){e.hidden=!1;return}i?.remove(),e.hidden=!1;const c=_H(t,n);e.appendChild(c),yH(c,o,n.onFocusFallback)}function wC(e){const t=e.querySelector(":scope > .project-team-setup-entry");if(!t)return;let n=t.querySelector(".project-team-setup-status");n||(n=document.createElement("p"),n.className="section-meta project-team-setup-status",n.setAttribute("role","status"),t.appendChild(n)),n.textContent="Team setup status is temporarily unavailable. The previous Team setup status is being shown.",e.hidden=!1}var Zn=new Set,Fl=new Set,rs=new EventTarget,is=new Set,SC=100,At="";function So(e,t,n){n?e.add(t):e.delete(t),rs.dispatchEvent(new Event("change"))}function CC(e,t){const[n,r]=T(e.has(t));return q(()=>{const i=()=>r(e.has(t));return rs.addEventListener("change",i),i(),()=>rs.removeEventListener("change",i)},[e,t]),n}function SH(){const[e,t]=T(()=>new Set(Zn));return q(()=>{const n=()=>t(new Set(Zn));return rs.addEventListener("change",n),n(),()=>rs.removeEventListener("change",n)},[]),e}function CH(e){const t=new Map;for(const n of e){const r=`${n.projectGroup.identity}\0${n.conditionCode}`,i=t.get(r);if(i){i.items.push(n);continue}t.set(r,{key:r,displayName:n.projectGroup.displayName,items:[n]})}return[...t.values()]}function RC(e,t){return e.options.find(n=>n.decision===t)}function RH(e){const t=e.items[0];return RC(t,t.recommendedDecision)?.label??t.recommendedDecision.replaceAll("_"," ")}function IC(e){return[...new Map(e.map(t=>[t.id,t.label])).values()]}function Nm(e,t){return e.items.flatMap(n=>{const r=RC(n,t);return r?[r]:[]})}function IH(e){const t=new Map;for(const n of e)for(const r of n.preview.projects){const i=t.get(r.canonicalIdentity)??0;t.set(r.canonicalIdentity,Math.max(i,n.preview.affectedMemoryCount))}return[...t.values()].reduce((n,r)=>n+r,0)}function kC(e){const t=IC(e.flatMap(n=>n.preview.projects.map(r=>({id:r.canonicalIdentity,label:`${r.displayName} — ${r.canonicalIdentity}`}))));return{devices:IC(e.flatMap(n=>n.preview.effectiveDevices.map(r=>({id:r.deviceId,label:`${r.displayName} (${r.assignment})`})))),memoryCount:IH(e),projects:t}}function Ir(e,t,n=`${t}s`){return`${e.toLocaleString()} ${e===1?t:n}`}function kH(e){return e==="unassigned_effective_device"?"Set up Identity or devices first":"Choose recipients first (Update sharing, below)"}async function NH(e){try{return await fN(e),{stale:!1,failed:!1}}catch(t){if(!(t instanceof Zh))throw t;return is.add(e.reviewItemId),{stale:!0,failed:!1}}}function PH(e,t){if(t.status==="stale"){is.add(t.reviewItemId),e.stale=!0;return}t.status!=="applied"&&(e.failed=!0)}async function NC(e){const t={failed:!1,stale:!1};for(let n=0;n<e.length;n+=SC){const r=e.slice(n,n+SC),i=await mN(r);for(const o of i.results)PH(t,o)}return t}async function TH(e,t){const n=PC(e,t),r=n[0];return n.length===1&&r?NH(r):NC(n)}function PC(e,t){return e.items.map(n=>({decision:t,reviewItemId:n.reviewItemId,sourceFingerprint:n.sourceFingerprint}))}function AH(e,t){if(t.failed)return"Some items did not update. Try again.";if(t.stale)return"Changed since loaded. Check the refreshed choices.";for(const n of e.items)is.delete(n.reviewItemId);return"Applied"}function Bl(e,t){return e instanceof Error?e.message:t}function os(e,t){const n=Nm(e,t);return n.length!==e.items.length||n.some(r=>r.preview.requiresDecisionInput)}function EH({options:e}){const{devices:t,memoryCount:n,projects:r}=kC(e);return a("div",{className:"recipient-policy-preview",children:[a("strong",{children:["Affected: ",Ir(r.length,"Project")," ·"," ",Ir(n,"memory","memories")," · ",Ir(t.length,"device")]}),a("div",{className:"recipient-policy-preview-list",children:[a("strong",{children:"Projects and paths"}),a("ul",{children:r.map(i=>a("li",{children:i},i))})]}),t.length>0?a("div",{className:"recipient-policy-preview-list",children:[a("strong",{children:"Devices"}),a("ul",{children:t.map(i=>a("li",{children:i},i))})]}):null]})}async function TC(e,t){try{await e.onRefresh?.()}catch(n){const r=Bl(n,"Unable to refresh review items.");At=`${At} Refresh failed: ${r}`,t(At)}}function xH(e,t,n,r){const i=CC(Zn,e.key);async function o(){const s=t.current;if(!(i||os(e,s)||Zn.has(e.key))){So(Zn,e.key,!0),At="Applying…",n(At);try{try{At=AH(e,await TH(e,s))}catch(c){At=Bl(c,"Unable to apply decision. Try again.")}n(At),await TC(r,n)}finally{So(Zn,e.key,!1)}}}return{apply:o,pending:i}}function DH(e){const t=e.items[0],n=kC(Nm(e,t.recommendedDecision)),r=[`Suggested: ${RH(e)}`,Ir(n.memoryCount,"memory","memories"),Ir(n.devices.length,"device")];return e.items.length>1&&r.push(Ir(e.items.length,"worktree")),r.join(" · ")}function jH({blocked:e,group:t,onSelectedChange:n,pending:r,selected:i,stale:o}){const s=t.items[0],c=`Select ${t.displayName}: ${s.finding} (${s.projectGroup.identity})`;return a("div",{className:"recipient-policy-review-summary",children:[a("div",{className:"recipient-policy-review-name",children:[a("label",{className:"recipient-policy-review-selection",children:a("input",{"aria-label":c,checked:i,disabled:r||e,onChange:l=>n(l.currentTarget.checked),type:"checkbox"})}),a("strong",{children:t.displayName}),s.projectGroup.identity!==t.displayName?a("span",{className:"mono small recipient-policy-review-identity",children:s.projectGroup.identity}):null]}),a("div",{className:"small recipient-policy-review-meta",children:[DH(t),o?a(Ue,{variant:"badge",tone:"badge-offline",children:"Changed since loaded"}):null]})]})}function LH(e){return a(G,{children:[a("select",{"aria-label":`Decision for ${e.group.displayName}`,className:"recipient-policy-review-select","data-review-control":"decision",disabled:e.pending,onChange:t=>e.onDecisionChange(t.currentTarget.value),value:e.decision,children:e.group.items[0].options.map(t=>a("option",{value:t.decision,children:t.label},t.decision))}),a("div",{className:"recipient-policy-review-actions",children:[a("button",{className:"settings-save","data-review-control":"apply",disabled:e.pending||e.blocked,onClick:e.onApply,ref:e.applyButtonRef,type:"button",children:e.pending?"Applying…":"Apply"}),a("button",{"aria-controls":e.detailsId,"aria-expanded":e.detailsOpen,className:"settings-button",onClick:e.onDetailsToggle,type:"button",children:"Details"})]})]})}function OH({detailsId:e,group:t,open:n,requiresInput:r,selected:i,stale:o}){const s=t.items[0];return a("div",{className:"settings-note recipient-policy-review-details",hidden:!n,id:e,children:[a("div",{children:[s.finding," — ",s.reason]}),o?a("div",{children:"Changed since loaded. Check the refreshed choices."}):null,a("div",{className:"recipient-policy-deferred",hidden:!r,children:kH(s.conditionCode)}),a(EH,{options:i})]})}function $H({decision:e,group:t,onDecisionChange:n,onSelectedChange:r,onStatus:i,options:o,selected:s}){const c=`recipient-policy-details-${Xt()}`,[l,d]=T(!1),u=D(e),p=D(null);u.current=e;const f=Nm(t,e),{apply:m,pending:v}=xH(t,u,i,o),b=os(t,e),g=f.some(S=>S.preview.requiresDecisionInput),y=t.items.some(S=>is.has(S.reviewItemId));return a("article",{className:"recipient-policy-review-item","data-review-group":t.key,children:[a(jH,{blocked:b,group:t,onSelectedChange:r,pending:v,selected:s,stale:y}),a(LH,{applyButtonRef:p,blocked:b,decision:e,detailsId:c,detailsOpen:l,group:t,onApply:()=>{m()},onDecisionChange:S=>{u.current=S,p.current&&(p.current.disabled=os(t,S)),n(S)},onDetailsToggle:()=>d(S=>!S),pending:v}),a(OH,{detailsId:c,group:t,open:l,requiresInput:g,selected:f,stale:y})]})}function MH(e){const t=D(null);return q(()=>{t.current&&(t.current.indeterminate=e.selectedCount>0&&!e.allSelected)},[e.allSelected,e.selectedCount]),a("div",{className:"recipient-policy-review-bulk",children:[a("label",{className:"recipient-policy-review-select-all",children:[a("input",{"aria-label":"Select all actionable sharing decisions",checked:e.allSelected,disabled:e.applying||e.actionableCount===0,onChange:n=>e.onSelectAll(n.currentTarget.checked),ref:t,type:"checkbox"}),a("span",{children:"Select all actionable"})]}),a("span",{className:"small recipient-policy-review-selection-count",children:[e.selectedCount," selected · ",e.actionableCount," actionable"]}),a("div",{className:"recipient-policy-review-bulk-actions",children:[a("button",{className:"settings-button",disabled:e.applying||e.applySelectedBlocked||e.selectedCount===0,onClick:e.onApplySelected,type:"button",children:e.applying?"Applying…":`Apply selected (${e.selectedCount})`}),a("button",{className:"settings-save",disabled:e.applying||e.applyAllBlocked||e.actionableCount===0,onClick:e.onApplyAll,type:"button",children:e.applying?"Applying…":`Apply all (${e.actionableCount})`})]})]})}function FH(e){return Object.fromEntries(e.map(t=>[t.key,t.items[0].recommendedDecision]))}function BH(e,t){if(t.failed)return"Some decisions did not update. Check the refreshed list and try again.";if(t.stale)return"Some decisions changed since loaded. Check the refreshed choices.";for(const n of e)for(const r of n.items)is.delete(r.reviewItemId);return`Applied ${Ir(e.length,"decision")}`}async function qH(e,t){return NC(e.flatMap(n=>PC(n,t[n.key]??n.items[0].recommendedDecision)))}function UH({item:e,options:t}){const n=`recipient-policy-blocked-details-${Xt()}`,r=`recipient-policy-repair-help-${Xt()}`,[i,o]=T(!1),s=CC(Fl,e.blockedItemId),c=!!(t.onRepair&&(t.isRepairAvailable?.(e.repair)??!0));async function l(){if(!(!t.onRepair||Fl.has(e.blockedItemId))){So(Fl,e.blockedItemId,!0);try{await t.onRepair(e.repair)}finally{So(Fl,e.blockedItemId,!1)}}}return a("article",{className:"recipient-policy-review-item recipient-policy-blocked-item",children:[a("div",{className:"recipient-policy-review-summary",children:[a("div",{className:"recipient-policy-review-name",children:[a("strong",{children:e.finding}),a(Ue,{variant:"badge",tone:"badge-offline",children:"Blocked"})]}),a("div",{className:"small recipient-policy-review-meta",children:["Owner: ",e.ownerLabel]})]}),a("div",{"aria-hidden":"true"}),a("div",{className:"recipient-policy-review-actions",children:[c?a("button",{"aria-describedby":r,className:"settings-button",disabled:s,onClick:()=>{l()},type:"button",children:e.repair.label}):a("span",{className:"small",children:"Repair in Projects"}),a("button",{"aria-controls":n,"aria-expanded":i,className:"settings-button",onClick:()=>o(d=>!d),type:"button",children:"Details"})]}),a("div",{className:"settings-note recipient-policy-review-details",hidden:!i,id:n,children:[a("div",{children:e.reason}),a("div",{id:r,children:e.repairAction})]})]})}function GH(e){const[t,n]=T(()=>FH(e)),r=D(t),[i,o]=T(()=>new Set),s=m=>t[m.key]??m.items[0].recommendedDecision,c=e.filter(m=>!os(m,s(m))),l=c.filter(m=>i.has(m.key));function d(m,v){r.current={...r.current,[m.key]:v},n(r.current),os(m,v)&&u(m.key,!1)}function u(m,v){o(b=>{const g=new Set(b);return v?g.add(m):g.delete(m),g})}function p(m){o(m?new Set(c.map(v=>v.key)):new Set)}function f(m){o(v=>{const b=new Set(v);for(const g of m)b.delete(g.key);return b})}return{actionableGroups:c,allSelected:c.length>0&&l.length===c.length,clearSelected:f,decisionFor:s,decisionsRef:r,selectAll:p,selectedGroups:l,selectedKeys:i,setDecision:d,setGroupSelected:u}}function HH(e,t,n,r){const[i,o]=T(!1),s=D(!1);async function c(l){if(!(s.current||l.length===0||l.some(d=>Zn.has(d.key)))){s.current=!0,o(!0);for(const d of l)So(Zn,d.key,!0);At=`Applying ${Ir(l.length,"decision")}…`,n(At);try{try{const d=await qH(l,e.current);At=BH(l,d),!d.failed&&!d.stale&&r(l)}catch(d){At=Bl(d,"Unable to apply decisions. Try again.")}n(At),await TC(t,n)}finally{for(const d of l)So(Zn,d.key,!1);s.current=!1,o(!1)}}}return{apply:c,applying:i}}function VH({options:e,review:t}){const n=CH(t.reviewItems),[r,i]=T(At),o=GH(n),s=SH(),c=HH(o.decisionsRef,e,i,o.clearSelected);return a("section",{className:"card recipient-policy-review","aria-labelledby":"recipientPolicyReviewTitle",children:[a("div",{className:"recipient-policy-review-header",children:[a("h2",{id:"recipientPolicyReviewTitle",children:["Sharing decisions ",a("span",{className:"recipient-policy-review-count",children:n.length})]}),a(Ue,{variant:"badge",tone:"badge-offline",children:"Unapplied"})]}),a("div",{className:"section-meta recipient-policy-review-status",role:"status","aria-live":"polite",children:r}),n.length>0?a(G,{children:[a(MH,{actionableCount:o.actionableGroups.length,allSelected:o.allSelected,applyAllBlocked:o.actionableGroups.some(l=>s.has(l.key)),applySelectedBlocked:o.selectedGroups.some(l=>s.has(l.key)),applying:c.applying,onApplyAll:()=>{c.apply(o.actionableGroups)},onApplySelected:()=>{c.apply(o.selectedGroups)},onSelectAll:o.selectAll,selectedCount:o.selectedGroups.length}),a("div",{className:"recipient-policy-review-list recipient-policy-review-decisions",children:n.map(l=>a($H,{decision:o.decisionFor(l),group:l,onDecisionChange:d=>o.setDecision(l,d),onSelectedChange:d=>o.setGroupSelected(l.key,d),onStatus:i,options:e,selected:o.selectedKeys.has(l.key)},l.key))})]}):null,t.blockedItems.length>0?a("section",{className:"recipient-policy-review-section recipient-policy-review-blocked",children:[a("h3",{children:["Blocked repairs"," ",a("span",{className:"recipient-policy-review-count",children:t.blockedItems.length})]}),a("div",{className:"recipient-policy-review-list",children:t.blockedItems.map(l=>a(UH,{item:l,options:e},l.blockedItemId))})]}):null]})}function KH(e,t,n={}){if(t.reviewItems.length===0&&t.blockedItems.length===0){ke(null,e),e.hidden=!0;return}e.hidden=!1,ke(a(VH,{options:n,review:t}),e)}function zH(e,t){e.hidden=!1,ke(a("section",{className:"card recipient-policy-review",children:[a("h2",{children:"Sharing decisions"}),a("p",{className:"settings-note project-attention-note",role:"status",children:Bl(t,"Unable to load sharing decisions. Try again.")})]}),e)}var AC=[["","All projects"],["needs_attention","Needs attention"],["suggested","Has suggestion"],["local_only","Stays on this device"],["received","From other devices"],["explicitly_mapped","Already assigned"],["legacy_review","Older shared data"],["unmapped","Missing project identity"]],_t=null,Jt=0,as=250,WH=100,Pm=[],ss=new Set,cs=new Set,ls=new Set,ds=new Map,us=new Map,kr=new Map,ps=new Map,Co=new Map,ql=!1,Ro=new Map,fs=!1,bi=!1,Tm=0,EC=null,er=0,ms=0,Io=null,hs=null,Et=new Set,Ul={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},ko=Ul,Gl=!1,Am=!1,No=!1,xC,Nr={projects:[],total:0,offset:0,has_more:!1},DC=new Set;function Xe(){if(DC.size===0)return;const e=BC();for(const t of DC)t(e)}function JH(e=!1,t={}){if(!e&&hs)return hs;const n=rv(t).then(r=>({ok:!0,summary:r})).catch(()=>({ok:!1}));return hs=n,n.then(()=>{hs===n&&(hs=null)}),n}function Em(e){return JH(e.awaitTeamSetupSummary===!0||e.requireTeamSetupSummary===!0,e)}function Ae(e){return document.getElementById(e)}function Po(e){return e.read_only===!0&&e.read_only_reason==="peer_received"}function Hl(e){return e.identity_source!=="unmapped"&&!Po(e)}function jC(e){return Hl(e)&&e.memory_count!=null&&e.guardrail_warnings.every(t=>!t.requires_confirmation)}function YH(e){return`${Po(e)?"peer-received":"local"}:${e.workspace_identity}`}function QH(e){const t=Ro.get(e.workspace_identity);(!t||Po(t)&&!Po(e))&&Ro.set(e.workspace_identity,e)}function XH(e){return[...new Set(e.map(t=>t.workspace_identity))].sort()}function _i(){const e=Et.size,t=Ae("projectsShareSelected");t&&(t.textContent=e===0?"Add Teams or Identities":`Add Teams or Identities (${e})`,t.disabled=e===0||!bi||!Gl,t.classList.add("project-selection-target"));const n=Ae("projectsSelectionStatus");n&&(n.setAttribute("role","status"),n.setAttribute("aria-live","polite"),n.textContent=`${e.toLocaleString()} Project${e===1?"":"s"} selected.`),Pr()}function ZH(e){const t=e.every(n=>Et.has(n));for(const n of e)t?Et.delete(n):Et.add(n);_i(),Xe()}function LC(e){const t=new Set(e),n=new Map(ko.teams.filter(o=>o.status==="active").map(o=>[o.teamId,o.displayName])),r=new Map(ko.identities.filter(o=>o.status==="active"||o.status==="pending").map(o=>[o.identityId,o.displayName])),i=new Map;for(const o of ko.projectRecipients)if(!(o.status!=="active"||!t.has(o.canonicalProjectIdentity)))if(o.recipientKind==="team"){const s=n.get(o.teamId);s&&i.set(`team:${o.teamId}`,{key:`team:${o.teamId}`,kind:"Team",displayName:s})}else{const s=r.get(o.identityId);s&&i.set(`identity:${o.identityId}`,{key:`identity:${o.identityId}`,kind:"Identity",displayName:s})}return[...i.values()].sort((o,s)=>`${o.kind}:${o.displayName}`.localeCompare(`${s.kind}:${s.displayName}`))}function vs(e){return e.git_remote?`git:${e.git_remote}`:e.project?`project:${e.project}`:`identity:${e.workspace_identity}`}function eV(e){return e.project||e.display_project||"Unnamed Project"}function OC(e){const t=String(e||"").trim();return t?_.lastProjectCoordinatorAdminGroups.find(n=>String(n.group_id||"").trim()===t&&!n.archived_at)?.display_name||"Team details unavailable":null}function tV(){return new Set(_.lastProjectCoordinatorAdminGroups.filter(e=>!e.archived_at).map(e=>String(e.group_id||"").trim()).filter(Boolean))}function nV(e){return!fs||e.authority_type!=="coordinator"||!e.group_id?!1:!tV().has(String(e.group_id).trim())}function Vl(){const e=document.activeElement;return e instanceof HTMLSelectElement&&e.classList.contains("project-domain-select")}function rV(){ql&&(ql=!1,_t?.())}async function iV(){let e;try{const t=await Dd();e=t&&typeof t=="object"?t:null}catch{_.lastProjectCoordinatorAdminGroups=[],fs=!1;return}if(e?.readiness!=="ready"||!e.has_admin_secret){_.lastProjectCoordinatorAdminGroups=[],fs=!1;return}try{const t=await Bh(!1);_.lastProjectCoordinatorAdminGroups=Array.isArray(t?.items)?t.items:[],fs=!0}catch{_.lastProjectCoordinatorAdminGroups=[],fs=!1}}function oV(e){const t=e.kind==="team_default"?`${e.label||"Untitled Space"} (default)`:e.label||"Untitled Space",n=OC(e.group_id);return n?`${t} · Team: ${n}`:e.authority_type==="local"?`${t} · Local device`:e.authority_type==="coordinator"?`${t} · Coordinator Space`:`${t} · ${e.authority_type||"Other"} Space`}function aV(){return Pm.filter(e=>e.scope_id!=="legacy-shared-review"&&!nV(e))}function sV(e){const t=OC(e.group_id);return t?`Team: ${t}`:e.authority_type==="local"?"Local device":e.authority_type==="coordinator"?"Coordinator Spaces":"Other Spaces"}function cV(e){return e.group_id?`team:${e.group_id}`:`${e.authority_type||"other"}:${e.kind||"space"}`}function lV(){const e=new Map;for(const t of aV()){const n=cV(t),r=sV(t),i=e.get(n)??{label:r,scopes:[]};e.set(n,{label:i.label,scopes:[...i.scopes,t]})}return[...e.entries()].map(([t,n])=>({key:t,...n}))}async function xm(e,t,n=[]){try{await _N({...e.mapping_id&&e.resolution_reason==="exact_mapping"?{id:e.mapping_id}:{},...n.length>0?{confirmed_guardrail_tokens:n}:{},project_pattern:e.display_project,scope_id:t,workspace_identity:e.workspace_identity}),kr.delete(e.workspace_identity),ds.delete(e.workspace_identity),Xe(),Y("Space assignment updated. Device access unchanged."),_t?.()}catch(r){if(r instanceof Pi){kr.set(e.workspace_identity,{requiredGuardrailTokens:r.requiredGuardrailTokens,scopeId:t,warnings:r.guardrailWarnings}),Pr(),Xe(),_t?.();return}Y(r instanceof Error?r.message:"Unable to update project Space.","warning")}}async function dV(e,t){const n=e.filter(Hl);if(n.length!==0)try{await wN({mappings:n.map(r=>({...r.mapping_id&&r.resolution_reason==="exact_mapping"?{id:r.mapping_id}:{},project_pattern:r.display_project,scope_id:t,workspace_identity:r.workspace_identity}))}),Y(`Updated ${n.length} project identit${n.length===1?"y":"ies"}. Device access unchanged.`),us.delete(vs(n[0])),Xe(),_t?.()}catch(r){Y(uV(r),"warning")}}function uV(e){return e instanceof Pi?"One or more identities in this group need review before bulk assignment. Expand the group and save those identities directly.":e instanceof Error?e.message:"Unable to update project Spaces."}async function pV(e){if(e.mapping_id!=null)try{await SN(e.mapping_id,ps.get(e.mapping_id)??[]),ps.delete(e.mapping_id),kr.delete(e.workspace_identity),ds.delete(e.workspace_identity),Xe(),Y("Project Space assignment removed. The next fallback now applies."),_t?.()}catch(t){if(t instanceof Pi){ps.set(e.mapping_id,t.requiredGuardrailTokens),Y(`${t.guardrailWarnings[0]?.message??"Review the fallback access change."} Select Remove again to confirm.`,"warning");return}ps.delete(e.mapping_id),Y(t instanceof Error?t.message:"Unable to remove project Space assignment.","warning")}}async function fV(e,t={}){const n=t.confirmed===!0;try{const r=Co.get(e.workspace_identity),i=await RN({...n&&r?{confirmation_token:r.confirmationToken}:{},confirmed:n,workspace_identity:e.workspace_identity});Co.delete(e.workspace_identity),Xe(),Y(`Forgot ${i.forgotten_memory_count.toLocaleString()} local memor${i.forgotten_memory_count===1?"y":"ies"}. ${i.peer_owned_memory_count.toLocaleString()} peer-owned memor${i.peer_owned_memory_count===1?"y was":"ies were"} left unchanged.`),_t?.()}catch(r){if(r instanceof Qh){Co.set(e.workspace_identity,{confirmationToken:r.preview.confirmation_token,localOwnedMemoryCount:r.preview.local_owned_memory_count,peerOwnedMemoryCount:r.preview.peer_owned_memory_count}),Pr(),Xe(),_t?.();return}Y(r instanceof Error?r.message:"Unable to forget project memories.","warning")}}async function $C(e){if(e.identity_source==="unmapped")return;const t=String(e.project||e.display_project||"").trim();let n=[];try{n=(await Ts()).filter(i=>i&&i!==t)}catch{}const r=await gf({cancelLabel:"Cancel",confirmLabel:"Change project",description:`This will update ${e.session_count} session${e.session_count===1?"":"s"} and ${e.memory_count??0} memor${e.memory_count===1?"y":"ies"} by changing the stored project. Space assignment stays unchanged.`,initialValue:t,placeholder:"Project name",suggestions:n,title:"Change project",validate:i=>{const o=i.trim();return o?o===t?"Already assigned to this project.":null:"Enter a project name."}});if(r!=null)try{const i=await CN({project:r.trim(),workspace_identity:e.workspace_identity});Y(`Changed project to ${i.project} for ${i.moved_session_count} session${i.moved_session_count===1?"":"s"}.`),_t?.()}catch(i){Y(i instanceof Error?i.message:"Unable to change project.","warning")}}async function mV(e){const t=Ro.get(e);if(t&&!Po(t))return{offset:Jt,project:t};try{let n=0,r=0;for(;;){const i=await Ho({limit:as,offset:n,q:e});r+=1;const o=i.projects.find(c=>c.workspace_identity===e&&!Po(c));if(o)return{offset:i.offset,project:o};if(!i.has_more||i.limit<=0)return null;const s=i.offset+i.limit;if(s<=n||r>=WH)return null;n=s}}catch{return null}}function Dm(e){const t=[...document.querySelectorAll("[data-project-workspace-identity]")].find(c=>c.dataset.projectWorkspaceIdentity===e&&c.dataset.projectRepairable==="true");if(!t)return!1;const n=t.querySelector(".project-inventory-details");if(!n)return!1;const r=t.dataset.projectClusterKey,i=r?[...document.querySelectorAll(".project-inventory-cluster")].find(c=>c.dataset.projectClusterKey===r):null,o=i?.querySelector(".project-inventory-details");if(o){o.open=!0;const c=i?.dataset.projectClusterKey;c&&cs.add(c)}n.open=!0;const s=t.dataset.projectRowKey;return s&&ss.add(s),n.scrollIntoView?.({block:"center",behavior:"smooth"}),n.querySelector("summary")?.focus(),!0}function MC(){return{generation:er,search:Ae("projectsSearch")?.value??"",status:Ae("projectsStatusFilter")?.value??"",offset:Jt}}function hV(e){return er!==e.generation||(Ae("projectsSearch")?.value??"")!==e.search||(Ae("projectsStatusFilter")?.value??"")!==e.status||Jt!==e.offset}async function vV(e){const{project:t}=e;if(Dm(t.workspace_identity)||(ls.add(vs(t)),Pr(),Xe(),Dm(t.workspace_identity)))return;const n=Ae("projectsSearch"),r=Ae("projectsStatusFilter"),i=MC(),o=t.workspace_identity;n&&(n.value=o),r&&(r.value=""),Jt=e.offset;const s=er;await To(),!Dm(t.workspace_identity)&&(er!==s||n&&n.value!==o||r&&r.value!==""||Jt!==e.offset||(n&&(n.value=i.search),r&&(r.value=i.status),Jt=i.offset,await To(),Y("Project administration could not be opened. Refresh Projects and try again.","warning")))}async function gV(e){if(Vl()){Y("Finish the open Space assignment, then try Repair again.","warning");return}const t=MC(),n=await mV(e.projectIdentity);if(hV(t))return;if(Vl()){Y("Finish the open Space assignment, then try Repair again.","warning");return}if(!n){Y("This Project is not visible in the current inventory. Refresh Projects, then try Repair again.","warning");return}const{project:r}=n;if(e.kind==="reassign_project"){if(r.identity_source==="unmapped"||r.session_count===0){Y("This Project cannot be reassigned yet because it has no local sessions with stable source evidence.","warning");return}await $C(r);return}await vV(n)}function yV(e){const t=er,n=(Io?.catch(()=>{})??Promise.resolve()).then(async()=>{if(er===t)try{await gV(e)}catch(r){Y(r instanceof Error?r.message:"Unable to repair this Project.","warning")}});return Io=n,n.then(()=>{Io===n&&(Io=null)},()=>{Io===n&&(Io=null)}),n}function bV(e){const t=new Map;for(const n of e){const r=vs(n);t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function FC(e){const t=$u(e),n=Hl(e),r=YH(e),i=n?kr.get(e.workspace_identity):void 0,o=n?Co.get(e.workspace_identity):void 0;return{kind:"project",key:r,detailKey:r,project:e,manageable:t,selected:t&&Et.has(e.workspace_identity),shareEligible:jC(e),shareReady:bi,detailsOpen:ss.has(r),draftScopeId:n?ds.get(e.workspace_identity)??null:null,pendingConfirmation:i?{requiredGuardrailTokens:[...i.requiredGuardrailTokens],scopeId:i.scopeId,warnings:[...i.warnings]}:null,pendingForgetConfirmation:o?{...o}:null,recipients:n?LC([e.workspace_identity]):[]}}function _V(e){if(e.length===1)return FC(e[0]);const t=vs(e[0]),n=XH(e.filter($u));return{kind:"cluster",key:t,label:eV(e[0]),projects:e.map(FC),projectIds:n,selectedProjectIds:n.filter(r=>Et.has(r)),worktreesOpen:ls.has(t),detailsOpen:cs.has(t),draftScopeId:us.get(t)??null,recipients:LC(n)}}function BC(){const e=[...Et].sort();return{rows:bV(Nr.projects).map(_V),recipientPolicyReady:Am,shareInventoryReady:bi,scopeLabels:Object.fromEntries(Pm.map(t=>[t.scope_id,oV(t)])),selection:{projectIds:e,count:e.length,ready:bi&&Gl},pagination:{offset:Nr.offset,limit:as,total:Nr.total,hasMore:Nr.has_more},scopeGroups:lV().map(t=>({key:t.key,label:t.label,scopes:[...t.scopes]})),statusOptions:AC.map(([t,n])=>({label:n,value:t}))}}function qC(){document.getElementById("projectsInventorySkeleton")?.remove()}function wV(e){if(e.total===0)return"0 projects";const t=Math.min(e.offset+e.projects.length,e.total);return`${e.total.toLocaleString()} projects · ${e.offset+1}–${t}`}function Pr(e){if(!No)return;const t=Ae("projectsInventoryList");t&&vH(t,BC(),$V,e)}function UC(e){No=!0,Nr={projects:[...e.projects],total:e.total,offset:e.offset,has_more:e.has_more};const t=Ae("projectsInventoryMeta"),n=Ae("projectsInventoryList");if(!t||!n)return;qC(),Ro.clear();for(const o of e.projects)QH(o);Pr(),t.textContent=wV(e);const r=Ae("projectsPrevPage"),i=Ae("projectsNextPage");r&&(r.disabled=e.offset===0),i&&(i.disabled=!e.has_more),_i(),Xe()}function SV(e,t,n){iV().then(()=>{if(t===Tm&&jm(n)){if(Vl()){Xe();return}UC(e)}})}async function CV(e={}){const t=new Map;let n=0;for(;;){const r=await Ho({limit:250,offset:n,signal:e.signal});for(const i of r.projects)t.set(i.workspace_identity,i);if(!r.has_more)break;n+=r.limit}return[...t.values()]}function GC(){return{query:Ae("projectsSearch")?.value.trim()??"",status:Ae("projectsStatusFilter")?.value??"",offset:Jt}}function jm(e){const t=GC();return t.query===e.query&&t.status===e.status&&t.offset===e.offset}function RV(e,t){return Ho({limit:as,offset:t.offset,q:t.query||void 0,status:t.status||void 0,signal:e.signal})}function HC(e,t,n){const r=Ae("recipientPolicyManagementMount");r&&vy(r,nc(e),t,{loadError:n,onCommitted:i=>{i.status==="applied"&&Et.clear(),_i(),Xe(),_t?.()}})}function IV(e){const t=e.querySelector(":scope > .project-recipient-policy-review-content");if(t)return t;const n=document.createElement("div");return n.className="project-recipient-policy-review-content",e.prepend(n),n}function VC(e,t){wH(e,t,{onOpenTeamSetup:xC,onFocusFallback:()=>Ae("projectsSearch")?.focus()})}function To(e={}){const t=OV(e);return EC=t,t}async function KC(e,t){return e.signal?.aborted?!1:!e.awaitTeamSetupSummary&&!e.requireTeamSetupSummary?EC??!1:(await t,!1)}function Kl(e,t){return!t.signal?.aborted&&e===Tm}function zl(e){return e.awaitTeamSetupSummary===!0||e.requireTeamSetupSummary===!0}async function kV(e){if(!zl(e))return!0;const t=await Em(e);return e.signal?.aborted?!1:!e.requireTeamSetupSummary||t.ok}async function NV(e){if(ql=!0,!zl(e))return!0;const t=++ms,n=await Em(e);if(e.signal?.aborted||t!==ms)return!1;const r=Ae("recipientPolicyReviewMount");return n.ok?(r&&VC(r,n.summary),!0):(r&&wC(r),!e.requireTeamSetupSummary)}function PV(e){return zl(e.options)?e.teamSetupSummaryPromise.then(t=>!Kl(e.loadGeneration,e.options)||e.entryLoadGeneration!==ms?!1:e.requiredLoadSucceeded&&(!e.options.requireTeamSetupSummary||t.ok)):e.requiredLoadSucceeded}async function TV(e,t){return zl(e)&&await t,!1}function AV(e){const t=Ae("recipientPolicyReviewMount");if(!t)return;const n=IV(t);"review"in e?KH(n,e.review,{isRepairAvailable:r=>!r.projectIdentity.startsWith("unmapped:"),onRefresh:async()=>{await To()},onRepair:yV}):zH(n,e.error),t.hidden=n.hidden&&!t.querySelector(".project-team-setup-entry")}async function EV(e,t){const[n,r,i,o,s]=await Promise.all([RV(e,t),hN(e),CV(e).then(c=>({ok:!0,projects:c})).catch(()=>({ok:!1,projects:[]})),pN(e).then(c=>({ok:!0,review:c})).catch(c=>({ok:!1,error:c})),qd(e).then(c=>({ok:!0,intent:c})).catch(c=>({ok:!1,error:c}))]);return{intentResult:s,recipientPolicyReview:o,result:n,settings:r,shareInventory:i}}function xV(e){if(!e.ok)return;const t=new Set(nc(e.projects).map(n=>n.canonicalProjectIdentity));for(const n of Et)t.has(n)||Et.delete(n)}function DV(e,t,n){const{intentResult:r,recipientPolicyReview:i,result:o,settings:s,shareInventory:c}=e;Pm=s.scopes,bi=c.ok,Gl=r.ok,Am=r.ok,ko=r.ok?r.intent:Ul,xV(c);const l=Ae("projectShareFlowMount");return l&&Cy(l,c.projects,{inventoryError:!c.ok}),AV(i),HC(c.projects,ko,!c.ok||!r.ok),UC(o),SV(o,t,n),c.ok&&"review"in i&&r.ok}function jV(e){e.teamSetupSummaryPromise.then(t=>{if(!Kl(e.loadGeneration,e.options)||e.entryLoadGeneration!==ms)return;const n=Ae("recipientPolicyReviewMount");if(n){if(!t.ok){wC(n);return}VC(n,t.summary)}})}function LV(e,t){No=!0,Ro.clear(),Nr={projects:[],total:0,offset:Jt,has_more:!1},bi=!1,Gl=!1,Am=!1,ko=Ul;const n=Ae("projectShareFlowMount");n&&Cy(n,[],{inventoryError:!0}),HC([],Ul,!0),_i(),Xe(),qC(),t.textContent="Project inventory failed to load.",Pr(e instanceof Error?e.message:"Unable to load project inventory.")}async function OV(e){const t=Ae("projectsInventoryMeta"),n=Ae("projectsInventoryList");if(!t||!n)return kV(e);if(Vl())return NV(e);ql=!1;const r=++Tm,i=GC();No||_i(),(!No||!t.textContent?.trim())&&(t.textContent="Loading project inventory…");let o=null;try{const s=++ms;o=Em(e);const c=await EV(e,i);if(!Kl(r,e))return KC(e,o);if(!jm(i))return!1;const l=DV(c,r,i);return jV({entryLoadGeneration:s,loadGeneration:r,options:e,teamSetupSummaryPromise:o}),PV({entryLoadGeneration:s,loadGeneration:r,options:e,requiredLoadSucceeded:l,teamSetupSummaryPromise:o})}catch(s){return Kl(r,e)?jm(i)?(LV(s,t),TV(e,o)):!1:KC(e,o)}}function wi(e){return Ro.get(e)??Nr.projects.find(t=>t.workspace_identity===e)??null}var $V={toggleSelection(e){ZH(e)},shareProject(e){const t=wi(e);!t||!jC(t)||!bi||ic([t.workspace_identity])},manageRecipients(e){const t=[...new Set(e)].sort();if(t.length!==0){if(t.length===1){na({mode:"project-manage",projectId:t[0]});return}for(const n of t)Et.add(n);_i(),Xe(),na({mode:"project-add",projectIds:t})}},setProjectDetailsOpen(e,t){t?ss.add(e):ss.delete(e),Xe()},setClusterDetailsOpen(e,t){t?cs.add(e):cs.delete(e),Xe()},setClusterWorktreesOpen(e,t){t?ls.add(e):ls.delete(e),Pr(),Xe()},setProjectScopeDraft(e,t){ds.set(e,t),kr.delete(e),Pr(),Xe(),_t?.()},setClusterScopeDraft(e,t){t?us.set(e,t):us.delete(e),Xe()},async saveProjectScope(e,t){const n=wi(e);n&&await xm(n,t)},async saveClusterScope(e,t){const n=Nr.projects.filter(r=>vs(r)===e).filter(Hl);n.length>0&&await dV(n,t)},async removeProjectScope(e){const t=wi(e);t&&await pV(t)},async keepProjectLocal(e){const t=wi(e);t&&await xm(t,"local-default")},async reassignProject(e){const t=wi(e);t&&await $C(t)},async forgetProject(e,t={}){const n=wi(e);n&&await fV(n,t)},async confirmProjectScope(e){const t=wi(e),n=kr.get(e);!t||!n||await xm(t,n.scopeId,n.requiredGuardrailTokens)},cancelProjectScopeConfirmation(e){kr.delete(e),Xe(),_t?.()},cancelProjectForgetConfirmation(e){Co.delete(e),Xe(),_t?.()},onSpaceSelectBlur(){rV()}};function MV(e,t={}){_t=e,xC=t.onOpenTeamSetup,Et.clear(),ss.clear(),cs.clear(),ls.clear(),ds.clear(),us.clear(),kr.clear(),ps.clear(),Co.clear(),No=!1;const n=Ae("projectsStatusFilter");n&&n.options.length===0&&n.append(...AC.map(([o,s])=>new Option(s,o)));const r=()=>{er+=1,Jt=0,_t?.()};Ae("projectsSearch")?.addEventListener("input",r),n?.addEventListener("change",r),Ae("projectsPrevPage")?.addEventListener("click",()=>{er+=1,Jt=Math.max(0,Jt-as),_t?.()}),Ae("projectsNextPage")?.addEventListener("click",()=>{er+=1,Jt+=as,_t?.()});const i=Ae("projectsShareSelected");i&&i.dataset.recipientPolicyBound!=="true"&&(i.dataset.recipientPolicyBound="true",i.addEventListener("click",()=>{Et.size!==0&&na({mode:"project-add",projectIds:[...Et].sort()})})),_i()}function Lm(e,t){const n=e.trim();if(!n)return[];const r=JSON.parse(n);if(!Array.isArray(r)||r.some(o=>typeof o!="string"))throw new Error(`${t.label} must be a JSON string array`);if(!t.normalize&&!t.requireNonEmpty)return r;const i=t.normalize?r.map(o=>o.trim()):r;if(t.requireNonEmpty&&i.some(o=>o.trim()===""))throw new Error(`${t.label} cannot contain empty command tokens`);return i}function FV(e){const t=e.trim();if(!t)return{};const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))throw new Error("observer headers must be a JSON object");const r={};for(const[i,o]of Object.entries(n)){if(typeof i!="string"||!i.trim()||typeof o!="string")throw new Error("observer headers must map string keys to string values");r[i.trim()]=o}return r}function BV(e){const{values:t,touchedKeys:n,baseline:r}=e,i=e.allowUntouchedParseErrors===!0;let o=[];try{o=Lm(t.claudeCommand,{label:"claude command",normalize:!0,requireNonEmpty:!0})}catch(R){if(!i||n.has("claude_command"))throw R;const k=r.claude_command;o=Array.isArray(k)?k.filter(N=>typeof N=="string").map(N=>N.trim()).filter(N=>N.length>0):[]}let s=[];try{s=Lm(t.codexCommand,{label:"codex command",normalize:!0,requireNonEmpty:!0})}catch(R){if(!i||n.has("codex_command"))throw R;const k=r.codex_command;s=Array.isArray(k)?k.filter(N=>typeof N=="string").map(N=>N.trim()).filter(N=>N.length>0):[]}let c=[];try{c=Lm(t.observerAuthCommand,{label:"observer auth command"})}catch(R){if(!i||n.has("observer_auth_command"))throw R;const k=r.observer_auth_command;c=Array.isArray(k)?k.filter(N=>typeof N=="string"):[]}let l={};try{l=FV(t.observerHeaders)}catch(R){if(!i||n.has("observer_headers"))throw R;const k=r.observer_headers;k&&typeof k=="object"&&!Array.isArray(k)&&Object.entries(k).forEach(([N,j])=>{typeof N=="string"&&N.trim()&&typeof j=="string"&&(l[N]=j)})}const d=t.observerAuthCacheTtlS.trim(),u=t.observerSimpleTemperature.trim(),p=t.observerRichTemperature.trim(),f=t.observerRichMaxOutputTokens.trim(),m=t.rawEventsSweeperIntervalS.trim(),v=d===""?"":Number(d),b=u===""?"":Number(u),g=p===""?"":Number(p),y=f===""?"":Number(f),S=Number(m),w=m===""?"":S;if(d!==""&&!Number.isFinite(v))throw new Error("observer auth cache ttl must be a number");if(u!==""&&(typeof b!="number"||!Number.isFinite(b)||b<0))throw new Error("simple tier temperature must be a non-negative number");if(p!==""&&(typeof g!="number"||!Number.isFinite(g)||g<0))throw new Error("rich tier temperature must be a non-negative number");if(f!==""&&(typeof y!="number"||!Number.isFinite(y)||y<=0||!Number.isInteger(y)))throw new Error("rich tier max output tokens must be a positive integer");if(m!==""&&(!Number.isFinite(S)||S<=0))throw new Error("raw-event sweeper interval must be a positive number");return{claude_command:o,codex_command:s,observer_provider:Ye(t.observerProvider),observer_model:Ye(t.observerModel),observer_tier_routing_enabled:t.observerTierRoutingEnabled,observer_simple_model:Ye(t.observerSimpleModel),observer_simple_temperature:b,observer_reasoning_effort:Ye(t.observerReasoningEffort),observer_reasoning_summary:Ye(t.observerReasoningSummary),observer_rich_model:Ye(t.observerRichModel),observer_rich_temperature:g,observer_rich_reasoning_effort:Ye(t.observerRichReasoningEffort),observer_rich_reasoning_summary:Ye(t.observerRichReasoningSummary),observer_rich_max_output_tokens:y,observer_runtime:Ye(t.observerRuntime),observer_auth_source:Ye(t.observerAuthSource||"auto")||"auto",observer_auth_file:Ye(t.observerAuthFile),observer_auth_command:c,observer_auth_timeout_ms:Number(t.observerAuthTimeoutMs||0)||"",observer_auth_cache_ttl_s:v,observer_headers:l,observer_max_chars:Number(t.observerMaxChars||0)||"",pack_observation_limit:Number(t.packObservationLimit||0)||"",pack_session_limit:Number(t.packSessionLimit||0)||"",raw_events_sweeper_interval_s:w,sync_enabled:t.syncEnabled,sync_host:Ye(t.syncHost),sync_port:Number(t.syncPort||0)||"",sync_interval_s:Number(t.syncInterval||0)||"",sync_mdns:t.syncMdns,sync_coordinator_url:Ye(t.syncCoordinatorUrl),sync_coordinator_group:Ye(t.syncCoordinatorGroup),sync_coordinator_timeout_s:Number(t.syncCoordinatorTimeout||0)||"",sync_coordinator_presence_ttl_s:Number(t.syncCoordinatorPresenceTtl||0)||""}}function qV(e){return e.resolved_observer_runtime||Pe(Ce(e.config,e.effective,"observer_runtime"))||"api_http"}function zC(e){return Gt(e.config,"observer_tier_routing_enabled")||Gt(e.env_overrides,"observer_tier_routing_enabled")}function UV(e){const t=e.config||{},n=e.effective||{},r=e.observer_apply?.active?.tierRoutingEnabled;return e.observer_apply?.state==="active"&&!zC(e)&&typeof r=="boolean"?r:Al(Ce(t,n,"observer_tier_routing_enabled"))}function GV(e){const t=e.config||{},n=e.effective||{},r=Ce(t,n,"observer_headers"),i=r&&typeof r=="object"&&!Array.isArray(r)?Object.fromEntries(Object.entries(r).filter(([p,f])=>typeof p=="string"&&p.trim()&&typeof f=="string")):{},o=Ce(t,n,"claude_command"),s=Array.isArray(o)?o.filter(p=>typeof p=="string"):[],c=Ce(t,n,"codex_command"),l=Array.isArray(c)?c.filter(p=>typeof p=="string"):[],d=Ce(t,n,"observer_auth_command"),u=Array.isArray(d)?d.filter(p=>typeof p=="string"):[];return{claudeCommand:s.length?JSON.stringify(s,null,2):"",codexCommand:l.length?JSON.stringify(l,null,2):"",observerProvider:Pe(Ce(t,n,"observer_provider")),observerModel:Pe(Ce(t,n,"observer_model")),observerTierRoutingEnabled:UV(e),observerSimpleModel:Pe(Ce(t,n,"observer_simple_model")),observerSimpleTemperature:Pe(Ce(t,n,"observer_simple_temperature")),observerReasoningEffort:Pe(Ce(t,n,"observer_reasoning_effort")),observerReasoningSummary:Pe(Ce(t,n,"observer_reasoning_summary")),observerRichModel:Pe(Ce(t,n,"observer_rich_model")),observerRichTemperature:Pe(Ce(t,n,"observer_rich_temperature")),observerRichReasoningEffort:Pe(Ce(t,n,"observer_rich_reasoning_effort")),observerRichReasoningSummary:Pe(Ce(t,n,"observer_rich_reasoning_summary")),observerRichMaxOutputTokens:Pe(Ce(t,n,"observer_rich_max_output_tokens")),observerRuntime:qV(e),observerAuthSource:Pe(Ce(t,n,"observer_auth_source"))||"auto",observerAuthFile:Pe(Ce(t,n,"observer_auth_file")),observerAuthCommand:u.length?JSON.stringify(u,null,2):"",observerAuthTimeoutMs:Pe(Ce(t,n,"observer_auth_timeout_ms")),observerAuthCacheTtlS:Pe(Ce(t,n,"observer_auth_cache_ttl_s")),observerHeaders:Object.keys(i).length?JSON.stringify(i,null,2):"",observerMaxChars:Pe(Ce(t,n,"observer_max_chars")),packObservationLimit:Pe(Ce(t,n,"pack_observation_limit")),packSessionLimit:Pe(Ce(t,n,"pack_session_limit")),rawEventsSweeperIntervalS:Pe(Ce(t,n,"raw_events_sweeper_interval_s")),syncEnabled:Al(Ce(t,n,"sync_enabled")),syncHost:Pe(Ce(t,n,"sync_host")),syncPort:Pe(Ce(t,n,"sync_port")),syncInterval:Pe(Ce(t,n,"sync_interval_s")),syncMdns:Al(Ce(t,n,"sync_mdns")),syncCoordinatorUrl:Pe(Ce(t,n,"sync_coordinator_url")),syncCoordinatorGroup:Pe(Ce(t,n,"sync_coordinator_group")),syncCoordinatorTimeout:Pe(Ce(t,n,"sync_coordinator_timeout_s")),syncCoordinatorPresenceTtl:Pe(Ce(t,n,"sync_coordinator_presence_ttl_s"))}}function HV(e,t){if(e.observerTierRoutingEnabled)return"Tiered routing is enabled: simple/rich model selection lives in Connection.";const n=GU(e.observerRuntime.trim()||"api_http",e.observerProvider.trim(),Ye(e.observerModel));return`${["observer_model","observer_provider","observer_runtime"].some(r=>Gt(t,r))?"Env override":n.source}: ${n.model}`}function VV(e){return e.observerTierRoutingEnabled?"Base model fallback":"Model"}function KV(e){return e.observerTierRoutingEnabled?"Tiered routing is enabled, so Connection controls the simple/rich models. This base model is only a fallback, and explicit settings override built-in defaults.":"Leave blank to use a recommended model for your selected mode/provider."}function zV(e){return e.observerTierRoutingEnabled?"Tiered routing is active. Use this only as a fallback while Connection controls simple/rich model selection and explicit tier settings override built-in defaults.":"Default: `gpt-6-luna` for Direct API (including pi-derived API-key providers) or Local Codex session, or `claude-4.5-haiku` for Local Claude session."}function WV(e){return!e}function JV(e,t,n){return t.has(e)||n.has(e)}function YV(e){return`${e} is read-only in the viewer for security. Edit the config file or environment instead.`}var z={previouslyFocused:null,baseline:{},effectiveConfig:{},resolvedObserverRuntime:null,observerRuntimeByAuthSource:{},observerRuntimeAfterAuthOverrideRemoval:{},observerAutomaticRuntimeByAuthSource:{},observerApply:null,observerTierRoutingExplicit:!1,observerModelDefaults:null,restartRequiredKeys:new Set,envOverrides:{},touchedKeys:new Set,shellMounted:!1,protectedKeys:new Set,startPolling:null,refresh:null,hideTooltip:null},xt=mc({open:!1,activeTab:"observer",dirty:!1,renderState:{effectiveText:"",isSaving:!1,observerStatus:null,overridesVisible:!1,pathText:"Config path: n/a",providers:[],statusText:"Ready",values:{...jU}},showAdvanced:FU()});function Ht(){return xt.value}function gs(e){xt.value={...xt.value,...e}}function QV(){z.hideTooltip?.()}function Tr(e){gs({renderState:{...xt.value.renderState,...e}})}function WC(e){Tr({values:{...xt.value.renderState.values,...e}})}function JC(e){gs({activeTab:["observer","queue","sync"].includes(e)?e:"observer"})}function Wl(e){gs({dirty:e})}function Jl(e){gs({open:e})}function XV(e){BU(e),gs({showAdvanced:e})}function YC(){return Ht().open}function QC(e){return JV(e,z.protectedKeys,DU)}function Om(e={}){const t=BV({values:Ht().renderState.values,touchedKeys:z.touchedKeys,baseline:z.baseline,allowUntouchedParseErrors:e.allowUntouchedParseErrors});return z.touchedKeys.has("observer_runtime")||(t.observer_runtime=z.baseline.observer_runtime),t}function XC(e){const t=_.feedProcessingStatus,n=ZV(e);_.feedProcessingStatus=n,(t.kind!==n.kind||t.kind==="pending"&&n.kind==="pending"&&t.count!==n.count)&&Cn(!0),Tr({observerStatus:e&&typeof e=="object"?e:null})}function ZV(e){if(!e||typeof e!="object")return{kind:"unavailable"};const t=e,n=Number(t.queue?.pending);return Number.isFinite(n)&&n>0?{kind:"pending",count:Math.floor(n)}:t.capture_enabled===!1?{kind:"paused"}:{kind:"ready"}}function eK(e,t){return e&&typeof e=="object"&&Object.keys(e).length>0?t?"Fields show configuration-resolved values. Runtime behavior may apply automatic provider defaults. Environment settings supply some fields.":"Fields show configuration-resolved values. The current connection and models are shown separately while changes apply.":"Effective values are unavailable. Reload Settings; if this persists, restart the viewer and inspect its configuration."}function tK(e){z.resolvedObserverRuntime=e.resolved_observer_runtime??null,z.observerRuntimeByAuthSource=e.observer_runtime_by_auth_source??{},z.observerRuntimeAfterAuthOverrideRemoval=e.observer_runtime_after_auth_override_removal??{},z.observerAutomaticRuntimeByAuthSource=e.observer_automatic_runtime_by_auth_source??{}}function nK(e){if(!e||typeof e!="object")return;const t=e,n=t.defaults||{},r=t.config||{},i=t.env_overrides&&typeof t.env_overrides=="object"?t.env_overrides:{},o=Array.isArray(t.protected_keys)?t.protected_keys.filter(c=>typeof c=="string"&&c.trim().length>0):[],s=GV(t);z.envOverrides=i,z.effectiveConfig={...r,...t.effective},tK(t),z.observerApply=t.observer_apply??null,z.observerTierRoutingExplicit=zC(t),z.observerModelDefaults=t.observer_model_defaults??null,z.restartRequiredKeys=new Set(t.restart_required_keys??[]),z.protectedKeys=new Set(o),_.configDefaults=n,_.configPath=t.path||"",z.touchedKeys=new Set,Tr({effectiveText:eK(t.effective,Object.keys(i).length>0),overridesVisible:Object.keys(i).length>0,pathText:_.configPath?`Config path: ${_.configPath}`:"Config path: n/a",providers:qU(t.providers),statusText:"No unsaved changes",values:s});try{const c=Om({allowUntouchedParseErrors:!0});z.baseline=VU(c,r,i),z.baseline.observer_runtime=Ye(Pe(r.observer_runtime))}catch{z.baseline={}}Wl(!1)}async function rK(e={}){if(Ht().open)return;const[t,n]=await Promise.allSettled([Fh(e),Mh(e)]);e.signal?.aborted||(t.status==="fulfilled"&&nK(t.value),XC(n.status==="fulfilled"?n.value:null))}function ZC(e){if(!e)return"Not available";const t=e.reasoningEffort?` · ${e.reasoningEffort} reasoning`:"";return`${e.provider} · ${e.model}${t}`}function iK({active:e}){return a("details",{className:"settings-note observer-routing-details",children:[a("summary",{children:"Models in use"}),e.tierRoutingEnabled?a("dl",{className:"observer-routing-list",children:[a("div",{children:[a("dt",{children:"Simple requests"}),a("dd",{children:ZC(e.simple)})]}),a("div",{children:[a("dt",{children:"Rich requests"}),a("dd",{children:ZC(e.rich)})]})]}):a("dl",{className:"observer-routing-list",children:a("div",{children:[a("dt",{children:"All requests"}),a("dd",{children:[e.provider," · ",e.model]})]})})]})}function oK({status:e,onRetry:t,onRefresh:n}){return e?a(G,{children:[e.active?a(iK,{active:e.active}):null,e.state==="applying"?a("div",{role:"status",children:"Applying observer settings. New events will wait."}):null,e.state==="failed"?a("div",{role:"alert",children:[e.message??"Observer settings were saved but are not active."," ",a("button",{className:"settings-button",onClick:t,type:"button",children:"Retry applying observer settings"})]}):null,e.state!=="active"?a("button",{className:"settings-link-button",onClick:n,type:"button",children:"Check observer status"}):null]}):null}function aK({onOpenDiagnostics:e}){return e?a("button",{className:"settings-button",onClick:()=>e({severity:"error",subsystem:"observer"}),type:"button",children:"View observer diagnostics"}):null}function sK({available:e,method:t}){const n=Object.entries(e??{}).filter(([,r])=>r&&typeof r=="object");return!n.length||["codex_sidecar","claude_sidecar","opencode_v2"].includes(t??"")?null:a("details",{className:"status-credentials",children:[a("summary",{children:"API keys and saved sign-ins"}),a("ul",{children:n.map(([r,i])=>a("li",{children:[r,": ",OU(i)]},r))})]})}function cK({failure:e,onOpenDiagnostics:t}){return a("div",{className:"status-issue",children:[a("div",{className:"status-label",children:"Latest processing issue"}),a("div",{className:"status-issue-message",children:typeof e.error_message=="string"&&e.error_message.trim()?e.error_message.trim():"Raw-event processing failed."}),a("div",{className:"status-issue-meta",children:[[typeof e.observer_provider=="string"?e.observer_provider.trim():"",typeof e.observer_model=="string"&&e.observer_model.trim()?`→ ${e.observer_model.trim()}`:"",typeof e.observer_runtime=="string"&&e.observer_runtime.trim()?`(${e.observer_runtime.trim()})`:""].filter(Boolean).join(" ").replace(/\s+/g," ").trim(),`Last failure ${$U(e.updated_at)}`,typeof e.attempt_count=="number"&&Number.isFinite(e.attempt_count)?`Attempts ${e.attempt_count}`:""].filter(Boolean).join(" · ")}),typeof e.impact=="string"&&e.impact.trim()?a("div",{className:"status-issue-impact",children:e.impact.trim()}):null,a(aK,{onOpenDiagnostics:t})]})}function lK({status:e,onOpenDiagnostics:t}){if(!e)return a("div",{id:"observerStatusBanner",className:"observer-status-banner",hidden:!0});const n=e.active,r=n?.auth?.token_present===!1&&(n.runtime==="api_key"||n.auth.method==="none");return a("div",{id:"observerStatusBanner",className:"observer-status-banner",children:[e.latest_failure?a(cK,{failure:e.latest_failure,onOpenDiagnostics:t}):null,a("div",{className:"status-active",children:[a("span",{className:"status-label",children:"Current connection"}),a("span",{children:n?a(G,{children:[String(n.provider||"unknown"),n.model?` · ${String(n.model)}`:""," ·"," ",LU(n.auth?.method||"none")]}):"Waiting for the first session"})]}),r?a("div",{className:"status-token-warning",children:"No Direct API key detected. Check your credentials."}):null,a(sK,{available:e.available_credentials,method:n?.auth?.method})]})}function eR(e,t){const n=t.getBoundingClientRect(),r=8,i=8,o=e.offsetWidth,s=e.offsetHeight;let c=n.left+n.width/2-o/2;c=Math.max(r,Math.min(c,globalThis.innerWidth-o-r));let l=n.bottom+i;l+s>globalThis.innerHeight-r&&(l=n.top-s-i),l=Math.max(r,l),e.style.left=`${Math.round(c)}px`,e.style.top=`${Math.round(l)}px`}function ys(e){return e instanceof Element?e.closest(".help-icon[data-tooltip]"):null}function dK(e){if(!e)return[];const t=["button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])","[href]",'[tabindex]:not([tabindex="-1"])'].join(",");return Array.from(e.querySelectorAll(t)).filter(n=>{const r=n;return!r.hidden&&r.offsetParent!==null})}function uK(){const e=nt("settingsModal");(dK(e)[0]||e)?.focus()}function pK(){const[e,t]=T({anchor:null,content:"",visible:!1}),n=D(null);return q(()=>{const r=u=>{const p=u.dataset.tooltip?.trim();p&&t({anchor:u,content:p,visible:!0})},i=()=>{t(u=>!u.visible&&!u.anchor&&!u.content?u:{anchor:null,content:"",visible:!1})},o=u=>{const p=ys(u.target);p&&r(p)},s=u=>{const p=ys(u.target);if(!p)return;const f=u.relatedTarget;f instanceof Element&&p.contains(f)||i()},c=u=>{const p=ys(u.target);p&&r(p)},l=u=>{ys(u.target)&&i()},d=u=>{const p=ys(u.target);p&&(u.preventDefault(),t(f=>{if(f.anchor===p&&f.visible)return{anchor:null,content:"",visible:!1};const m=p.dataset.tooltip?.trim()||"";return m?{anchor:p,content:m,visible:!0}:f}))};return document.addEventListener("pointerover",o),document.addEventListener("pointerout",s),document.addEventListener("focusin",c),document.addEventListener("focusout",l),document.addEventListener("click",d),()=>{document.removeEventListener("pointerover",o),document.removeEventListener("pointerout",s),document.removeEventListener("focusin",c),document.removeEventListener("focusout",l),document.removeEventListener("click",d)}},[]),at(()=>{if(!e.visible||!e.anchor||!n.current)return;const r=requestAnimationFrame(()=>{n.current&&e.anchor&&eR(n.current,e.anchor)});return()=>{cancelAnimationFrame(r)}},[e.anchor,e.content,e.visible]),q(()=>{if(!e.visible||!e.anchor)return;const r=()=>{n.current&&e.anchor&&eR(n.current,e.anchor)};return globalThis.addEventListener("resize",r),document.addEventListener("scroll",r,!0),()=>{globalThis.removeEventListener("resize",r),document.removeEventListener("scroll",r,!0)}},[e.anchor,e.visible]),{tooltipPortal:be(()=>typeof document>"u"?null:fn(a("div",{className:`help-tooltip${e.visible?" visible":""}`,hidden:!e.visible,ref:n,children:e.content}),document.body),[e.content,e.visible]),setTooltip:t}}function fK({DialogContent:e,onClose:t}){const{open:n}=xt.value,{tooltipPortal:r,setTooltip:i}=pK();q(()=>{const s=()=>i({anchor:null,content:"",visible:!1});return z.hideTooltip=s,()=>{z.hideTooltip===s&&(z.hideTooltip=null)}},[]),q(()=>{n&&globalThis.lucide?.createIcons?.()},[n]);const o=re(()=>{z.startPolling&&z.refresh&&t(z.startPolling,z.refresh)},[t]);return a(G,{children:[a(Ln,{ariaDescribedby:"settingsDescription",ariaLabelledby:"settingsTitle",contentClassName:"modal",contentId:"settingsModal",onCloseAutoFocus:s=>{s.preventDefault()},onOpenAutoFocus:s=>{s.preventDefault(),uK()},onOpenChange:s=>{if(s){Jl(!0);return}o()},open:n,overlayClassName:"modal-backdrop",overlayId:"settingsBackdrop",children:a(e,{})}),r]})}function tR(e){return{controlId:e,existingData:"Stored memories stay unchanged; no backfill runs.",scope:"Queued and future model requests on this device",stage:"Observation processing",timing:"After viewer restart"}}function $m(e){return{controlId:e,existingData:"Stored memories stay unchanged; no reprocessing runs.",scope:"Queued and future events on this device",stage:"Observation processing",timing:"After viewer restart"}}function nR(e){return{controlId:e,existingData:"Stored memories and existing packs stay unchanged; the value is saved only.",scope:"No current effect",stage:"Saved setting",timing:"Not used when Codemem creates context packs"}}function Rn(e,t){return{controlId:e,existingData:"Existing memories are not reprocessed locally, but eligible memories may be sent to or received from trusted peers.",scope:t,stage:"Device sync",timing:"After viewer restart"}}function mK(e){return{controlId:e,existingData:"Stored memories stay unchanged. Local Claude and Codex sessions authenticate through their CLI logins instead.",scope:"No effect while Connection mode uses a local Claude or Codex session",stage:"Sidecar authentication",timing:"Not used by local Claude or Codex sessions"}}var hK=new Set(["observerAuthSource","observerAuthTimeoutMs","observerAuthCacheTtlS"]);function Yl(e){return e==="claude_sidecar"||e==="codex_sidecar"}var vK=Object.fromEntries([...["observerProvider","observerModel","observerRuntime","observerMaxChars","observerAuthSource","observerAuthTimeoutMs","observerAuthCacheTtlS"].map(tR),...["observerTierRoutingEnabled","observerSimpleModel","observerSimpleTemperature","observerReasoningEffort","observerReasoningSummary","observerRichModel","observerRichTemperature","observerRichReasoningEffort","observerRichReasoningSummary","observerRichMaxOutputTokens"].map($m),nR("packObservationLimit"),nR("packSessionLimit"),{controlId:"rawEventsSweeperIntervalS",existingData:"Processed events stay unchanged; no backfill runs.",scope:"Background queue on this viewer",stage:"Queue processing",timing:"Immediately after save"},Rn("syncEnabled","Future sync cycles on this device"),Rn("syncInterval","Future sync cycles on this device"),Rn("syncHost","Incoming peer connections to this device"),Rn("syncPort","Incoming peer connections to this device"),Rn("syncMdns","Advertise this device on the local network; this does not scan for peers"),Rn("syncCoordinatorGroup","Fallback coordinator discovery when no coordinator group list is configured"),Rn("syncCoordinatorTimeout","Future coordinator requests"),Rn("syncCoordinatorPresenceTtl","Future coordinator presence checks")].map(e=>[e.controlId,e]));function Mm(e,t={}){let n=vK[e];if(!n)return;const r=Fm(t.observerRuntime);if(hK.has(e)&&Yl(r))return mK(e);if(n=bK(e,r)??n,n.scope==="No current effect")return n;const i=Pl[e],o=i?z.envOverrides[i]:void 0;return typeof o!="string"||!o.trim()?n:{...n,timing:`After removing ${o.trim()} and restarting the viewer`}}function bs(e=xt.value.renderState.values.observerRuntime){return z.envOverrides.observer_runtime?!!String(z.effectiveConfig.observer_runtime??"").trim():z.touchedKeys.has("observer_runtime")?!!e?.trim():!!String(z.baseline.observer_runtime??"").trim()}function Fm(e){const t=z.envOverrides.observer_runtime,n=Ar("observerRuntime",e),r=z.touchedKeys.has("observer_runtime")&&n!==z.baseline.observer_runtime;if(r&&!n&&!t){const o=Ql(Ar("observerAuthSource"));return z.observerAutomaticRuntimeByAuthSource[o]||"api_http"}if(t||!r){const o=gK();if(o)return o;if(z.resolvedObserverRuntime)return z.resolvedObserverRuntime}const i=String(n??"").trim().toLowerCase();return["api_key","opencode_v2"].includes(i)||Yl(i)?i:"api_http"}function gK(){if(!z.touchedKeys.has("observer_auth_source"))return;const e=Ql(Ar("observerAuthSource"));return z.observerRuntimeByAuthSource[e]}function yK(e){return z.envOverrides.observer_auth_source?!0:z.touchedKeys.has("observer_runtime")&&e!==z.baseline.observer_runtime&&!z.envOverrides.observer_runtime?e?.trim()?!1:Object.values(z.observerAutomaticRuntimeByAuthSource).includes("api_http"):Object.values(z.observerRuntimeByAuthSource).includes("api_http")}function Ar(e,t){const n=Pl[e];return n&&z.envOverrides[n]?z.effectiveConfig[n]:t??xt.value.renderState.values[e]}function Ao(e,t){return{controlId:e,existingData:"Stored memories stay unchanged; this value is saved only.",scope:"No current effect",stage:"Saved setting",timing:t}}function bK(e,t){const n=Yl(t),r=String(Ar("observerProvider"));if(e==="observerProvider"&&n&&bs())return Ao(e,"Local Claude and Codex sessions select their own provider");if(e==="observerModel")return wK(t,r);const i=Ql(Ar("observerAuthSource"));if(e==="observerAuthTimeoutMs"&&!["auto","command"].includes(i))return Ao(e,"Only command authentication uses this timeout");if(e==="observerAuthCacheTtlS"&&!["file","command"].includes(i))return Ao(e,"Only explicit file or command authentication uses this cache");if(/Temperature$/.test(e))return CK(e,t,rR(e,r));if(/Reasoning(Effort|Summary)$/.test(e)||e==="observerRichMaxOutputTokens")return RK(e,n);if(e==="syncEnabled"&&!_K(Ar(e)))return{...Rn(e,"Stop future peer transfers on this device"),existingData:"Stored memories remain. Disabling sync does not retract copies already replicated to peers."};if(e==="syncHost"||e==="syncPort")return{...Rn(e,"Incoming connections and newly generated pairing addresses"),timing:"Pairing payloads change immediately after save; restart the viewer before sharing or using them so the listener uses the new address"}}function Ql(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return["auto","env","file","command","none"].includes(t)?t:"auto"}function _K(e){return typeof e=="boolean"?e:typeof e!="string"?!1:["1","true","yes","on"].includes(e.trim().toLowerCase())}function wK(e,t){const n="observerModel",r=Ar("observerTierRoutingEnabled");return(r===!0||r==="true"||r==="1")&&SK(e,t)?Ao(n,"Tier models or built-in tier defaults take precedence over the base model"):{...tR(n),scope:"Requests that use the base model, including tiers that fall back to it",timing:"After viewer restart, only where no tier model or built-in tier default takes precedence"}}function rR(e,t){const n=e.startsWith("observerSimple")?"observer_simple_provider":"observer_rich_provider",r=String(z.effectiveConfig[n]??"").trim().toLowerCase(),i=t.trim().toLowerCase();return["openai","anthropic"].includes(r)?r:["openai","anthropic"].includes(i)?i:r||i}function SK(e,t){return e==="claude_sidecar"?!0:["observerSimpleModel","observerRichModel"].every(n=>String(Ar(n)??"").trim()?!0:e==="codex_sidecar"?!1:["openai","anthropic"].includes(rR(n,t)))}function CK(e,t,n){return Yl(t)||n==="anthropic"?Ao(e,"Anthropic and local Claude/Codex sessions do not send sampling temperature"):{...$m(e),scope:"Only tier requests whose transport sends sampling temperature; OpenAI reasoning requests omit it",timing:"After viewer restart, only when the selected transport and reasoning mode support temperature"}}function RK(e,t){if(t)return Ao(e,"Local Claude and Codex sessions do not use these API tuning fields");const n=e==="observerRichMaxOutputTokens"?"Rich-tier API requests whose transport consumes the output-token limit; unsupported transports ignore it":"OpenAI Responses requests only; other transports ignore reasoning fields";return{...$m(e),scope:n,timing:"After viewer restart, only when the effective request transport consumes this setting"}}function iR({controlId:e,existingData:t,scope:n,stage:r}){return a("details",{className:"settings-outcome","data-settings-outcome-for":e,children:[a("summary",{children:"Change details"}),a("div",{className:"settings-outcome-details",children:[a("span",{children:[a("strong",{children:"Affects:"})," ",r]}),a("span",{children:[a("strong",{children:"Scope:"})," ",n]}),a("span",{children:[a("strong",{children:"Existing data:"})," ",t]})]})]})}function IK({scope:e,stage:t,timing:n}){return e==="No current effect"||t==="Sidecar authentication"?a("div",{className:"settings-effect-note small",children:["Inactive · ",n]}):/only/i.test(e)?a("div",{className:"settings-effect-note small",children:e}):null}function kK(e,t){const n=z.envOverrides[e];if(n)return n;if(t==="Sidecar authentication"&&!bs())return z.envOverrides.observer_auth_source}function NK(){const e=Ql(z.touchedKeys.has("observer_auth_source")?xt.value.renderState.values.observerAuthSource:z.baseline.observer_auth_source);return(z.observerRuntimeAfterAuthOverrideRemoval[e]??z.observerRuntimeByAuthSource[e])==="api_http"}function PK({configKey:e,...t}){const{scope:n,stage:r,timing:i}=t,o=kK(e,r),s=n==="No current effect"||r==="Sidecar authentication";if(typeof o!="string"||!o.trim())return a(G,{children:[a(IK,{...t}),a(iR,{...t})]});let c="Remove that environment setting and restart the viewer to apply changes here.";const l=z.envOverrides.observer_auth_source;return r==="Sidecar authentication"&&!bs(xt.value.renderState.values.observerRuntime)&&NK()&&typeof l=="string"&&l.trim()?c=`Inactive for the current connection · ${i}. Remove ${[...new Set([l.trim(),o.trim()])].join(" and ")} and restart the viewer to use the saved authentication settings. The connection may change after removal.`:s&&(c=`Inactive · ${i}. Removing the environment setting does not activate this field for the current connection.`),a(G,{children:[a("div",{className:"settings-env-note small",children:["Controlled by ",o.trim(),". ",c]}),a(iR,{...t})]})}function oR({controlId:e,existingData:t,scope:n,stage:r,timing:i}){const o=Pl[e];if(o?.startsWith("observer_"))return a(PK,{configKey:o,controlId:e,existingData:t,scope:n,stage:r,timing:i});let s=i;return i==="After viewer restart"?s="Change details":i.startsWith("After removing ")?s=`Environment-controlled · ${i}`:n==="No current effect"||r==="Sidecar authentication"?s=`Inactive · ${i}`:i.startsWith("After viewer restart,")&&(s="Change details"),a("details",{className:"settings-outcome","data-settings-outcome-for":e,children:[a("summary",{children:s}),a("div",{className:"settings-outcome-details",children:[a("span",{children:[a("strong",{children:"Affects:"})," ",r]}),a("span",{children:[a("strong",{children:"Scope:"})," ",n]}),a("span",{children:[a("strong",{children:"Takes effect:"})," ",i]}),a("span",{children:[a("strong",{children:"Existing data:"})," ",t]})]})]})}function aR(e,t){for(const n of pn(e)){if(!n||typeof n!="object"||!("props"in n))continue;const r=n.props;if(typeof r.id=="string"&&Mm(r.id,t))return r.id;const i=aR(r.children,t);if(i)return i}}function Ee({children:e,className:t="field",hidden:n=!1,id:r}){const i={observerRuntime:xt.value.renderState.values.observerRuntime},o=aR(e,i),s=o?Mm(o,i):void 0;return a("div",{className:t,hidden:n,id:r,children:[e,s?a(oR,{...s}):null]})}function sR(e,t,n,r){if(!t)return"";if(e.observerRuntime==="claude_sidecar")return n?t[n].anthropic??t.claude:t.claude;if(e.observerRuntime==="codex_sidecar")return n&&(e.observerModel.trim()||t[n].openai)||t.codex;const i=AK(e,t);return n?TK(e,t,n,i,r):t.base[i]??""}function TK(e,t,n,r,i){const o=i?.trim().toLowerCase(),s=t[n][o??""]?o:r;return t[n][s??""]||e.observerModel.trim()||t.base[o||r]||""}function AK(e,t){const n=e.observerProvider.trim().toLowerCase();if(n)return n;const r=e.observerModel.trim().toLowerCase(),i=r.split("/")[0]??"";return Object.hasOwn(t.base,i)?i:r.startsWith("claude")?"anthropic":"openai"}var Xl=null;function EK(){if(Xl&&Date.now()-Xl.loadedAt<6e4)return Xl.promise;const e=fetch("/api/observer-model-catalog").then(t=>t.json()).then(t=>Array.isArray(t.models)?t.models:[]).catch(()=>[]);return Xl={loadedAt:Date.now(),promise:e},e}function cR({id:e,values:t,provider:n}){const r=t[e];let i=n?.trim().toLowerCase()||t.observerProvider;t.observerRuntime==="codex_sidecar"?i="openai":t.observerRuntime==="claude_sidecar"&&(i="anthropic");const[o,s]=T([]);q(()=>{let d=!0;return EK().then(u=>{d&&s(u)}),()=>{d=!1}},[]);const c=i||(r.startsWith("claude")?"anthropic":"openai"),l=o.filter(d=>d.provider===c);return a(G,{children:[a("datalist",{id:`${e}-catalog`,children:l.map(d=>a("option",{value:d.model},`${d.provider}:${d.model}`))}),l.length?a("div",{className:"small",children:"OpenCode model list; account access is not verified."}):null]})}function Zl({checked:e,className:t,disabled:n=!1,hidden:r=!1,id:i,label:o,onCheckedChange:s}){const c=`${i}Label`,l=Mm(i);return a("div",{className:t?`field-checkbox settings-switch-row ${t}`:"field-checkbox settings-switch-row",hidden:r,children:[a("label",{className:"settings-switch-copy",htmlFor:i,id:c,children:o}),a(oo,{"aria-labelledby":c,checked:e,className:"settings-switch",disabled:n,id:i,onCheckedChange:s,thumbClassName:"settings-switch-thumb"}),l?a(oR,{...l}):null]})}function lR({values:e,onTextInput:t,getObserverModelLabel:n,getObserverModelTooltip:r,modelDefaults:i}){const o=e.observerTierRoutingEnabled;return a(Ee,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerModel",children:o?"Fallback model":n()}),a("button",{"aria-label":"About model defaults",className:"help-icon","data-tooltip":r(),type:"button",children:"?"})]}),a(_e,{id:"observerModel",list:"observerModel-catalog",onInput:t("observerModel"),placeholder:sR(e,i),value:e.observerModel}),o?a("div",{className:"small",children:"Used only when a tier has no selected or built-in model."}):null,["api_http","api_key","opencode_v2"].includes(e.observerRuntime)?a(cR,{id:"observerModel",values:e}):null]})}function dR({tier:e,values:t,onTextInput:n,tierProviders:r,modelDefaults:i}){const o=e==="simple"?"observerSimpleModel":"observerRichModel",s=e==="simple"?"Simple model":"Rich model",c=e==="simple"?"Used for shorter, simpler requests.":"Used for larger or more involved requests.";return a(Ee,{children:[a("label",{htmlFor:o,children:s}),a(_e,{id:o,list:`${o}-catalog`,onInput:n(o),placeholder:sR(t,i,e,r?.[e]),value:t[o]}),a("div",{className:"small",children:c}),["api_http","api_key","opencode_v2"].includes(t.observerRuntime)?a(cR,{id:o,values:t,provider:r?.[e]}):null]})}function xK(e){const{values:t,onSwitchInput:n,hiddenUnlessAdvanced:r}=e,i=t.observerTierRoutingEnabled,o=t.observerModel.trim().length>0;return a("div",{className:"settings-group observer-model-settings",children:[a("h3",{className:"settings-group-title",children:"Models"}),a(Zl,{checked:i,className:"field",id:"observerTierRoutingEnabled",label:"Use simple and rich models",onCheckedChange:n("observerTierRoutingEnabled")}),i?a(G,{children:[a(dR,{tier:"simple",...e}),a(dR,{tier:"rich",...e}),o||!r()?a("details",{className:"observer-fallback-details",children:[a("summary",{children:o?"Fallback model · Custom value set":"Fallback model (optional)"}),a(lR,{...e})]}):null]}):a(lR,{...e})]})}function ed({children:e,hidden:t=!1}){return a("div",{className:"settings-note",hidden:t,children:e})}function DK({runtime:e,onSelectValueChange:t}){let n="Keeps your existing connection rules until you choose a connection below.";e==="claude_sidecar"?n="Uses your local Claude CLI login. Claude chooses the provider.":e==="codex_sidecar"?n="Uses your local Codex CLI login. Codex chooses the provider.":e==="opencode_v2"?n="Uses the selected provider account in OpenCode. OpenCode must be running.":e==="api_key"&&(n="Uses an API key for the selected provider. Does not use subscription sign-ins.");const r=[{label:"Automatic (detect connection)",value:"automatic"},{label:"OpenCode account",value:"opencode_v2"},{label:"API key",value:"api_key"},{label:"Local Claude session",value:"claude_sidecar"},{label:"Local Codex session",value:"codex_sidecar"}];return e==="api_http"&&r.unshift({label:"Existing API connection (legacy)",value:"api_http"}),a(Ee,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerRuntime",children:"Connection mode"}),a("button",{"aria-label":"About connection mode",className:"help-icon","data-tooltip":"Choose which account handles model requests. An explicit connection never falls back to another account.",type:"button",children:"?"})]}),a(Jn,{ariaLabel:"Connection mode",contentClassName:"settings-select-content",id:"observerRuntime",itemClassName:"settings-select-item",onValueChange:i=>t("observerRuntime")(i==="automatic"?"":i),options:r,triggerClassName:"settings-select-trigger",value:e,viewportClassName:"settings-select-viewport"}),a("div",{className:"small",children:n})]})}function jK({value:e,providerOptions:t,onSelectValueChange:n}){const r={anthropic:"Anthropic",opencode:"OpenCode",openai:"OpenAI"};return a(Ee,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerProvider",children:"Model provider"}),a("button",{"aria-label":"About model provider",className:"help-icon","data-tooltip":"Choose where model requests are sent. Pi setup can also derive a provider and model from an API-key provider.",type:"button",children:"?"})]}),a(Jn,{ariaLabel:"Model provider",contentClassName:"settings-select-content",id:"observerProvider",itemClassName:"settings-select-item",onValueChange:n("observerProvider"),options:[{label:"Auto (infer provider)",value:""},...t.map(i=>({...i,label:r[i.value]??i.label}))],placeholder:"Auto (infer provider)",triggerClassName:"settings-select-trigger",value:e,viewportClassName:"settings-select-viewport"}),a("div",{className:"small",children:"Use auto unless you need to pin a provider."})]})}function LK({values:e,runtime:t,explicit:n,providerOptions:r,onSelectValueChange:i}){return a(G,{children:[a(DK,{runtime:n?t:"automatic",onSelectValueChange:i}),!n||!(t==="claude_sidecar"||t==="codex_sidecar")?a(jK,{value:e.observerProvider,providerOptions:r,onSelectValueChange:i}):null]})}function OK(e){return e==="claude_sidecar"||e==="codex_sidecar"}function $K(e){return OK(e)||e==="opencode_v2"}function MK({values:e,effectiveObserverRuntime:t=e.observerRuntime,hasExplicitObserverRuntime:n=!0,allowAutomaticAuthChanges:r=!1,tierProviders:i,modelDefaults:o,observerMaxCharsDefault:s,providerOptions:c,showAuthFile:l,showAuthCommand:d,hiddenUnlessAdvanced:u,onTextInput:p,onSelectValueChange:f,onSwitchInput:m,getObserverModelLabel:v,getObserverModelTooltip:b,protectedConfigHelp:g,observerStatusBannerSlot:y}){return a(G,{children:[a("p",{className:"small observer-panel-intro",children:["Shared across ",GS(),"."]}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Connection"}),a(LK,{values:e,providerOptions:c,onSelectValueChange:f,runtime:t,explicit:n}),a(Ee,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"codexCommand",children:"Codex command (JSON argv)"}),a(co,{disabled:!0,id:"codexCommand",placeholder:'["codex"]',rows:2,value:e.codexCommand}),a("div",{className:"small",children:g("codex_command")})]}),a(Ee,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"claudeCommand",children:"Claude command (JSON argv)"}),a(co,{disabled:!0,id:"claudeCommand",placeholder:'["claude"]',rows:2,value:e.claudeCommand}),a("div",{className:"small",children:g("claude_command")})]}),a(Ee,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"observerMaxChars",children:"Request size limit (chars)"}),a(_e,{id:"observerMaxChars",min:"1",onInput:p("observerMaxChars"),type:"number",value:e.observerMaxChars}),a("div",{className:"small",id:"observerMaxCharsHint",children:s?`Default: ${s}`:""})]})]}),a(xK,{values:{...e,observerRuntime:t},tierProviders:i,modelDefaults:o,hiddenUnlessAdvanced:u,onTextInput:p,onSwitchInput:m,getObserverModelLabel:v,getObserverModelTooltip:b}),y,a("div",{className:"settings-group",hidden:$K(t)&&!r,children:[a("h3",{className:"settings-group-title",children:"API credentials"}),a(Ee,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerAuthSource",children:"Credential source"}),a("button",{"aria-label":"About authentication method",className:"help-icon","data-tooltip":"Choose how credentials are resolved: environment, file, command, or none.",type:"button",children:"?"})]}),a(Jn,{ariaLabel:"Authentication method",contentClassName:"settings-select-content",id:"observerAuthSource",itemClassName:"settings-select-item",onValueChange:f("observerAuthSource"),options:[{label:"auto (default)",value:"auto"},{label:"env",value:"env"},{label:"file",value:"file"},{label:"command",value:"command"},{label:"none",value:"none"}],triggerClassName:"settings-select-trigger",value:e.observerAuthSource,viewportClassName:"settings-select-viewport"}),a("div",{className:"small",children:"API keys are read from your config or environment. File and command sources use the saved protected settings below."})]}),a(Ee,{hidden:!l,id:"observerAuthFileField",children:[a("label",{htmlFor:"observerAuthFile",children:"Token file path"}),a(_e,{disabled:!0,id:"observerAuthFile",placeholder:"~/.codemem/work-token.txt",value:e.observerAuthFile}),a("div",{className:"small",children:g("observer_auth_file")})]}),a(Ee,{hidden:!d,id:"observerAuthCommandField",children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerAuthCommand",children:"Token command"}),a("button",{"aria-label":"About token command",className:"help-icon","data-tooltip":"Runs this command and uses stdout as the token. JSON argv only, no shell parsing.",type:"button",children:"?"})]}),a(co,{disabled:!0,id:"observerAuthCommand",placeholder:'["iap-auth", "--audience", "gateway"]',rows:3,value:e.observerAuthCommand}),a("div",{className:"small",children:g("observer_auth_command")})]}),a("div",{className:"small",hidden:!d,id:"observerAuthCommandNote",children:'Command format: JSON string array, e.g. `["iap-auth", "--audience", "gateway"]`.'}),a(ed,{hidden:u(),children:"These advanced credential overrides only matter when you need custom command timing, cached tokens, or extra request headers."}),a(Ee,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"observerAuthTimeoutMs",children:"Token command timeout (ms)"}),a(_e,{id:"observerAuthTimeoutMs",min:"1",onInput:p("observerAuthTimeoutMs"),type:"number",value:e.observerAuthTimeoutMs})]}),a(Ee,{className:"field settings-advanced",hidden:u(),children:[a("label",{htmlFor:"observerAuthCacheTtlS",children:"Token cache time (s)"}),a(_e,{id:"observerAuthCacheTtlS",min:"0",onInput:p("observerAuthCacheTtlS"),type:"number",value:e.observerAuthCacheTtlS})]}),a(Ee,{className:"field settings-advanced",hidden:u(),children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"observerHeaders",children:"Request headers (JSON)"}),a("button",{"aria-label":"About request headers",className:"help-icon","data-tooltip":"Optional extra headers. Supports templates like ${auth.token}, ${auth.type}, ${auth.source}.",type:"button",children:"?"})]}),a(co,{disabled:!0,id:"observerHeaders",placeholder:'{"Authorization":"Bearer ${auth.token}"}',rows:4,value:e.observerHeaders}),a("div",{className:"small",children:g("observer_headers")})]})]})]})}function uR({detail:e,title:t}){return a("div",{className:"settings-section-intro",children:[a("div",{className:"settings-section-intro-title",children:t}),a("div",{className:"small settings-section-intro-detail",children:e})]})}function FK({values:e,showTieredRouting:t,hiddenUnlessAdvanced:n,onTextInput:r}){return a(G,{children:[a(uR,{detail:"Adjust background processing and, if needed, advanced model request controls. Choose models in Connection.",title:"Background processing"}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Processing"}),a(Ee,{children:[a("div",{className:"field-label",children:[a("label",{htmlFor:"rawEventsSweeperIntervalS",children:"Background processing interval (seconds)"}),a("button",{"aria-label":"About background processing interval",className:"help-icon","data-tooltip":"How often codemem checks for queued events to process in the background.",type:"button",children:"?"})]}),a(_e,{id:"rawEventsSweeperIntervalS",min:"1",onInput:r("rawEventsSweeperIntervalS"),type:"number",value:e.rawEventsSweeperIntervalS}),a("div",{className:"small",children:"How often codemem checks for queued raw events in the background."})]})]}),a("div",{className:"settings-group settings-advanced",hidden:!t||n(),children:[a("h3",{className:"settings-group-title",children:"Model tuning"}),a("div",{className:"small",children:"These controls apply only when the selected connection supports them."}),a("div",{children:[a("h4",{children:"Simple tier"}),a(Ee,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerSimpleTemperature",children:"Temperature"}),a(_e,{id:"observerSimpleTemperature",min:"0",onInput:r("observerSimpleTemperature"),step:"0.1",type:"number",value:e.observerSimpleTemperature})]})]}),a("div",{className:"settings-advanced",hidden:!t||n(),children:[a("h4",{children:"Shared reasoning defaults"}),a("div",{className:"small",children:"Applied to OpenAI Responses requests in both tiers unless a rich-tier override is set."}),a(Ee,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningEffort",children:"Reasoning effort"}),a(_e,{id:"observerReasoningEffort",onInput:r("observerReasoningEffort"),placeholder:"leave empty for provider default",value:e.observerReasoningEffort})]}),a(Ee,{className:"field settings-advanced",children:[a("label",{htmlFor:"observerReasoningSummary",children:"Reasoning summary"}),a(_e,{id:"observerReasoningSummary",onInput:r("observerReasoningSummary"),placeholder:"leave empty for provider default",value:e.observerReasoningSummary})]})]}),a("div",{children:[a("h4",{children:"Rich tier"}),a(Ee,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichTemperature",children:"Temperature"}),a(_e,{id:"observerRichTemperature",min:"0",onInput:r("observerRichTemperature"),step:"0.1",type:"number",value:e.observerRichTemperature})]}),a(Ee,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningEffort",children:"Reasoning effort override"}),a(_e,{id:"observerRichReasoningEffort",onInput:r("observerRichReasoningEffort"),placeholder:"inherits shared reasoning effort",value:e.observerRichReasoningEffort})]}),a(Ee,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichReasoningSummary",children:"Reasoning summary override"}),a(_e,{id:"observerRichReasoningSummary",onInput:r("observerRichReasoningSummary"),placeholder:"inherits shared reasoning summary",value:e.observerRichReasoningSummary})]}),a(Ee,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"observerRichMaxOutputTokens",children:"Max output tokens"}),a(_e,{id:"observerRichMaxOutputTokens",min:"1",onInput:r("observerRichMaxOutputTokens"),step:"1",type:"number",value:e.observerRichMaxOutputTokens})]})]})]}),a("div",{className:"settings-group settings-advanced",hidden:n(),children:[a("h3",{className:"settings-group-title",children:"Pack limits"}),a(ed,{hidden:n(),children:"Most users can keep these defaults. Change them only when you need smaller or larger default context packs."}),a(Ee,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packObservationLimit",children:"Observation limit"}),a(_e,{id:"packObservationLimit",min:"1",onInput:r("packObservationLimit"),type:"number",value:e.packObservationLimit}),a("div",{className:"small",children:"Default number of observations to include in a pack."})]}),a(Ee,{className:"field settings-advanced",hidden:n(),children:[a("label",{htmlFor:"packSessionLimit",children:"Session summary limit"}),a(_e,{id:"packSessionLimit",min:"1",onInput:r("packSessionLimit"),type:"number",value:e.packSessionLimit}),a("div",{className:"small",children:"Default number of session summaries to include in a pack."})]})]})]})}function BK({values:e,hiddenUnlessAdvanced:t,onTextInput:n,onSwitchInput:r,protectedConfigHelp:i}){return a(G,{children:[a(uR,{detail:"Choose whether this device syncs at all, how often it checks peers, and which coordinator group it should join.",title:"Device sync"}),a("div",{className:"settings-group",children:[a("h3",{className:"settings-group-title",children:"Device Sync"}),a(Zl,{checked:e.syncEnabled,className:"field",id:"syncEnabled",label:"Enable sync",onCheckedChange:r("syncEnabled")}),a(Ee,{children:[a("label",{htmlFor:"syncInterval",children:"Sync interval (seconds)"}),a(_e,{id:"syncInterval",min:"10",onInput:n("syncInterval"),type:"number",value:e.syncInterval}),a("div",{className:"small",children:"How often this device checks for sync work when sync is enabled."})]}),a(Ee,{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncHost",children:"Sync host"}),a(_e,{id:"syncHost",onInput:n("syncHost"),placeholder:"127.0.0.1",value:e.syncHost})]}),a(Ee,{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncPort",children:"Sync port"}),a(_e,{id:"syncPort",min:"1",onInput:n("syncPort"),type:"number",value:e.syncPort})]}),a(Zl,{checked:e.syncMdns,className:"field settings-advanced",hidden:t(),id:"syncMdns",label:"Enable mDNS discovery",onCheckedChange:r("syncMdns")}),a("div",{className:"field",children:[a("label",{htmlFor:"syncCoordinatorUrl",children:"Coordinator URL"}),a(_e,{disabled:!0,id:"syncCoordinatorUrl",placeholder:"https://coord.example.com",value:e.syncCoordinatorUrl}),a("div",{className:"small",children:i("sync_coordinator_url")})]}),a(Ee,{children:[a("label",{htmlFor:"syncCoordinatorGroup",children:"Coordinator group"}),a(_e,{id:"syncCoordinatorGroup",onInput:n("syncCoordinatorGroup"),placeholder:"team-alpha",value:e.syncCoordinatorGroup}),a("div",{className:"small",children:"Discovery namespace for peers using the same coordinator."})]}),a("div",{className:"field settings-advanced",hidden:t(),children:a(ed,{hidden:t(),children:"These network overrides are for unusual local-network setups. Leave them alone unless you know this device needs non-default sync discovery or coordinator timing."})}),a(Ee,{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncCoordinatorTimeout",children:"Coordinator timeout (seconds)"}),a(_e,{id:"syncCoordinatorTimeout",min:"1",onInput:n("syncCoordinatorTimeout"),type:"number",value:e.syncCoordinatorTimeout})]}),a(Ee,{className:"field settings-advanced",hidden:t(),children:[a("label",{htmlFor:"syncCoordinatorPresenceTtl",children:"Presence TTL (seconds)"}),a(_e,{id:"syncCoordinatorPresenceTtl",min:"1",onInput:n("syncCoordinatorPresenceTtl"),type:"number",value:e.syncCoordinatorPresenceTtl})]})]})]})}function qK({panelProps:e,activeTab:t,showAdvanced:n,renderState:r,settingsDirty:i,restartRequired:o=!1,onClose:s,onSave:c,onActiveTabChange:l,onAdvancedToggle:d,onShowGettingStarted:u,observerStatusBannerSlot:p}){const f=!i||r.isSaving,m=i&&!r.isSaving&&!r.statusText.startsWith("Save failed")?"Unsaved changes":r.statusText;return a("form",{className:"modal-card",onKeyDown:v=>Ta(v,{onSubmit:c,disabled:f}),onSubmit:v=>v.preventDefault(),children:[a("div",{className:"modal-header",children:[a("h2",{id:"settingsTitle",children:"Settings"}),a(Hr,{ariaLabel:"Close settings",className:"modal-close-button",onClick:s})]}),a("div",{className:"modal-body",children:[a("div",{className:"small",id:"settingsDescription",children:"Tune how codemem connects, processes work, and syncs with other devices."}),a("div",{className:"settings-advanced-toolbar",children:[a(Zl,{checked:n,id:"settingsAdvancedToggle",label:"Show advanced controls",onCheckedChange:d}),a("button",{"aria-label":"About advanced controls",className:"help-icon","data-tooltip":"Advanced controls include JSON fields, tuning values, and network overrides.",type:"button",children:a("i",{"aria-hidden":"true","data-lucide":"help-circle"})})]}),a(ed,{hidden:!n,children:"Advanced controls are visible. Leave JSON fields, tuning values, and network overrides alone unless you are debugging or matching a known deployment setup."}),a(Tp,{ariaLabel:"Settings sections",listClassName:"settings-tabs",onValueChange:l,tabs:xU,triggerClassName:"settings-tab",value:t,children:[a(Xr,{className:"settings-panel",forceMount:!0,value:"observer",children:a(MK,{...e,observerStatusBannerSlot:p})}),a(Xr,{className:"settings-panel",forceMount:!0,value:"queue",children:a(FK,{...e})}),a(Xr,{className:"settings-panel",forceMount:!0,value:"sync",children:a(BK,{...e})})]}),a("details",{className:"settings-config-details",children:[a("summary",{children:"Configuration details"}),a("div",{className:"small mono",id:"settingsPath",children:r.pathText}),a("div",{className:"settings-note",hidden:!r.overridesVisible,id:"settingsOverrides",children:"Some values are controlled outside this screen and take priority."})]})]}),a("div",{className:"modal-footer",children:[a("div",{className:"settings-footer-copy",children:[a("div",{"aria-live":"polite",className:"small",id:"settingsStatus",children:m}),i&&o?a("div",{role:"status",className:"small settings-restart-required",children:"Restart required"}):null,a("button",{className:"settings-link-button",onClick:u,type:"button",children:"Show getting started"})]}),a("button",{className:"settings-save","data-primary-action":"true",disabled:f,id:"settingsSave",onClick:c,type:"button",children:r.isSaving?"Saving…":"Save changes"})]})]})}function pR(e){const{current:t,baseline:n,envOverrides:r,touchedKeys:i,isProtected:o}=e,s={};Object.entries(t).forEach(([l,d])=>{o(l)||Gt(r,l)&&!i.has(l)||UU(d,n[l])||(s[l]=d)});const c="observer_tier_routing_enabled";return(["observer_runtime","observer_provider","observer_model","observer_auth_source"].some(l=>Gt(s,l))||i.has(c))&&typeof t[c]=="boolean"&&!Gt(r,c)&&!o(c)&&(s[c]=t[c]),s}function UK(e){const t=s=>{const c=Pl[s];c&&e.getTouchedKeys().add(c)},n=(s,c)=>{t(s),e.updateFormState({[s]:c}),e.onValuesChanged?.(),e.setDirty(!0)};return{markFieldTouched:t,updateField:n,onTextInput:s=>c=>{n(s,c.currentTarget.value)},onSelectValueChange:s=>c=>{n(s,c)},onSwitchInput:s=>c=>{n(s,c)}}}function GK(e,t,n,r){return r||t.length>0||n.length>0||e.sync?.ok===!1}function HK(e){return Array.isArray(e.applying_keys)&&e.applying_keys.length>0}function VK(e){const t=e?.effects,n=t&&typeof t=="object"&&!Array.isArray(t)?t:{},r=Array.isArray(n.hot_reloaded_keys)?n.hot_reloaded_keys.map(f=>fm(String(f))):[],i=Array.isArray(n.live_applied_keys)?n.live_applied_keys.map(f=>fm(String(f))):[],o=Array.isArray(n.restart_required_keys)?n.restart_required_keys.map(f=>fm(String(f))):[],s=HK(n),c=Array.isArray(n.warnings)?n.warnings.filter(f=>typeof f=="string"&&f.trim().length>0):[],l=Array.isArray(n.manual_actions)?n.manual_actions:[],d=n.sync&&typeof n.sync=="object"?n.sync:{},u=[];r.length&&u.push(`Applied now: ${Tl(r)}.`),i.length&&u.push(`Live settings updated: ${Tl(i)}.`),s&&u.push("Observer settings saved. Applying them now; new events will wait."),d.attempted&&typeof d.message=="string"&&d.message?u.push(`Sync: ${d.message}.`):Array.isArray(d.affected_keys)&&d.affected_keys.length&&typeof d.reason=="string"&&d.reason&&u.push(`Sync: ${d.reason}.`),o.length&&u.push(`Restart required for ${Tl(o)}. Run: codemem serve restart`),c.forEach(f=>{u.push(f)}),l.forEach(f=>{f&&typeof f.command=="string"&&f.command.trim()&&u.push(`If needed: ${f.command}.`)}),u.length||u.push("Saved.");const p=GK(n,o,c,s);return{message:u.join(" "),type:p?"warning":"success"}}function KK(){return[["observer_runtime","observerRuntime"],["observer_provider","observerProvider"],["observer_model","observerModel"],["observer_auth_source","observerAuthSource"]].some(([e,t])=>z.touchedKeys.has(e)&&Ye(xt.value.renderState.values[t])!==z.baseline[e])}function fR(){const e=z.observerApply;if(!e)return;const t=e.active?.tierRoutingEnabled;e.state!=="active"||typeof t!="boolean"||z.observerTierRoutingExplicit||z.touchedKeys.has("observer_tier_routing_enabled")||KK()||(z.baseline.observer_tier_routing_enabled=t,WC({observerTierRoutingEnabled:t}))}function mR(e){if(!e||typeof e!="object")return;const t=e.observer_apply;!t||!["active","applying","failed"].includes(t.state)||(z.observerApply=t,fR(),Tr({}))}function zK(){try{const e=pR({current:Om({allowUntouchedParseErrors:!0}),baseline:z.baseline,envOverrides:z.envOverrides,touchedKeys:z.touchedKeys,isProtected:QC});return Object.keys(e).some(t=>z.restartRequiredKeys.has(t)&&!(t in z.envOverrides))}catch{return!1}}var WK=()=>HV({...Ht().renderState.values,observerRuntime:bs()?Fm():"api_http"},z.envOverrides),JK=()=>VV(Ht().renderState.values),YK=()=>KV(Ht().renderState.values),QK=()=>zV(Ht().renderState.values),XK=()=>WV(Ht().showAdvanced),{onTextInput:ZK,onSelectValueChange:ez,onSwitchInput:tz}=UK({getTouchedKeys:()=>z.touchedKeys,getValues:()=>Ht().renderState.values,updateFormState:WC,setDirty:e=>Wl(e),onValuesChanged:fR});async function nz(){try{mR(await YI())}catch{Y("Observer settings could not be applied. Retry from Settings.","warning")}}async function rz(){try{mR(await Fh()),XC(await Mh())}catch{Y("Observer status could not be refreshed. Try again.","warning")}}function iz(){const e=xt.value.renderState.observerStatus,t=z.observerApply;return a(G,{children:[a(lK,{status:e,onOpenDiagnostics:az}),a(oK,{status:t,onRetry:()=>{nz()},onRefresh:()=>{rz()}})]})}function oz(){!z.startPolling||!z.refresh||(Eo(z.startPolling,z.refresh),!Ht().open&&(_F(),document.getElementById("tabBtn-feed")?.click(),SF()))}function az(e){if(!z.startPolling||!z.refresh||(Eo(z.startPolling,z.refresh),Ht().open))return;const t=Sc("settingsButton");queueMicrotask(()=>ur({...e,trigger:t}))}function sz(){return{simple:String(z.effectiveConfig.observer_simple_provider??"").trim(),rich:String(z.effectiveConfig.observer_rich_provider??"").trim()}}function cz(){const e=xt.value,t=e.renderState.values,n=Array.from(new Set(e.renderState.providers.concat(t.observerProvider?[t.observerProvider]:[]))).sort((i,o)=>i.localeCompare(o)).map(i=>({label:i,value:i})),r={values:t,effectiveObserverRuntime:Fm(t.observerRuntime),hasExplicitObserverRuntime:bs(t.observerRuntime),allowAutomaticAuthChanges:yK(t.observerRuntime),tierProviders:sz(),observerMaxCharsDefault:String(_.configDefaults?.observer_max_chars||""),modelDefaults:z.observerModelDefaults??void 0,providerOptions:n,showAuthFile:t.observerAuthSource==="file",showAuthCommand:t.observerAuthSource==="command",showTieredRouting:t.observerTierRoutingEnabled,hiddenUnlessAdvanced:XK,onTextInput:ZK,onSelectValueChange:ez,onSwitchInput:tz,getObserverModelLabel:JK,getObserverModelTooltip:YK,getObserverModelDescription:QK,getObserverModelHint:WK,protectedConfigHelp:YV};return a(qK,{panelProps:r,activeTab:e.activeTab,showAdvanced:e.showAdvanced,renderState:e.renderState,settingsDirty:e.dirty,restartRequired:zK(),onClose:()=>{z.startPolling&&z.refresh&&Eo(z.startPolling,z.refresh)},onSave:()=>{z.startPolling&&z.refresh&&uz(z.startPolling,z.refresh)},onActiveTabChange:JC,onAdvancedToggle:XV,onShowGettingStarted:oz,observerStatusBannerSlot:a(iz,{})})}function lz(){return a(fK,{DialogContent:cz,onClose:Eo})}function dz(){const e=nt("settingsDialogMount");e&&ke(a(lz,{}),e)}function hR(){nt("settingsDialogMount")&&(z.shellMounted||(dz(),z.shellMounted=!0))}function vR(e){li("settings-health"),z.shellMounted||hR(),Jl(!0),z.previouslyFocused=document.activeElement,e()}function Eo(e,t){if(Ht().dirty&&!globalThis.confirm("Discard unsaved changes?")){Jl(!0);return}Jl(!1),QV(),(z.previouslyFocused&&typeof z.previouslyFocused.focus=="function"?z.previouslyFocused:Sc("settingsButton"))?.focus(),z.previouslyFocused=null,z.touchedKeys=new Set,e(),t()}async function uz(e,t){if(!Ht().renderState.isSaving){Tr({isSaving:!0,statusText:"Saving changes…"});try{const n=Om({allowUntouchedParseErrors:!0}),r=pR({current:n,baseline:z.baseline,envOverrides:z.envOverrides,touchedKeys:z.touchedKeys,isProtected:QC});if(Object.keys(r).length===0){Tr({isSaving:!1,statusText:"No unsaved changes"}),Wl(!1),Eo(e,t);return}const i=await QI(r),o=VK(i);Tr({isSaving:!1,statusText:"Saved changes"}),Wl(!1),Eo(e,t),Y(o.message,o.type)}catch(n){const r=n instanceof Error?n.message:"unknown error";Tr({isSaving:!1,statusText:`Save failed: ${r}`})}}}function pz(e,t,n){z.startPolling=t,z.refresh=n,hR(),Sc("settingsButton")?.addEventListener("click",()=>vR(e))}function fz(e){e.dataset.syncRenderRoot="preact"}function mz(){const e=document.getElementById("tab-sync");e&&(e.dataset.syncRenderBoundary="preact-hybrid")}function dt(e,t){fz(e),ke(t,e)}function xo(e){e.dataset.syncRenderRoot==="preact"&&ke(null,e)}function hz(e){const t=Object.values(e||{}).map(n=>!n||typeof n!="object"?"":String(n.last_ping_at||"").trim()).filter(Boolean).sort();return t[t.length-1]??null}function vz(e){return typeof e=="object"&&e!==null}function gz(e,t){return _.pairingCommandRaw="",{payloadText:e,hintText:t}}function yz(e){if(!vz(e))return gz("Pairing not available","Enable sync and retry.");const t=e,n={...t,addresses:Array.isArray(t.addresses)?t.addresses:[]},r=JSON.stringify(n),i=`echo '${btoa(r)}' | base64 -d | codemem sync pair --accept-file -`;return _.pairingCommandRaw=i,{payloadText:i,hintText:"Copy this command and run it on the other device. Use --include/--exclude to control which projects sync."}}function bz(){return{title:"Diagnostics still loading.",detail:"Wait a moment for local sync status. If it stays blank, refresh the page or check whether sync is enabled on this device."}}function _z(){return{title:"Diagnostics unavailable right now.",detail:"The viewer could not load sync status. Refresh this page, or check that the local codemem sync service is reachable before retrying."}}function wz(){const e=_.lastSyncStatus;return{title:"No recent sync attempts yet.",detail:e?.daemon_state==="disabled"||e?.enabled===!1?"Turn on sync in Settings → Device Sync first. Recent attempts will appear here after this device can actually run sync work.":"Trigger a sync pass or pair another device to generate activity here when you need low-level troubleshooting."}}function Sz(){return{title:"Recent attempts unavailable right now.",detail:"Attempt history could not be loaded because sync diagnostics failed. Refresh the page after local sync status is reachable again."}}function Cz(e,t){return e==="offline-peers"&&t?"Some recent failures may have happened before all peers went offline. Sync will resume automatically when a peer becomes reachable.":""}function Rz({items:e}){return a(G,{children:e.map((t,n)=>a("div",{class:"stat",children:a("div",{class:"stat-content",children:[a("div",{class:"value",children:t.value}),a("div",{class:"label",children:t.label})]})},`${t.label}-${n}`))})}function Iz({attempts:e,note:t}){return a(G,{children:[t?a("div",{class:"small",children:t}):null,e.map((n,r)=>a("div",{class:"diag-line",children:[a("div",{class:"left",children:[a("div",{children:[n.peerLabel," — ",n.status]}),n.detail?a("div",{class:"small",children:n.detail}):null,n.actionHref&&n.actionLabel?a("a",{class:"small",href:n.actionHref,children:n.actionLabel}):null,n.action?a("button",{className:"settings-button small",onClick:i=>n.action?.(i.currentTarget),type:"button",children:"View sync diagnostics"}):null]}),a("div",{class:"right",children:n.startedAt})]},`${n.startedAt}-${n.peerLabel}-${r}`))]})}function gR({text:e}){return a(G,{children:e})}function kz({title:e,detail:t}){return a("div",{class:"sync-empty-state",children:[a("strong",{children:e}),a("span",{children:t})]})}function Nz(e,t){if(!t.length){xo(e);return}dt(e,a(Rz,{items:t}))}function Pz(e,t,n){if(!t.length){xo(e);return}dt(e,a(Iz,{attempts:t,note:n}))}function Si(e,t){dt(e,a(kz,{...t}))}function yR(e,t,n){dt(e,a(gR,{text:n.payloadText})),t&&dt(t,a(gR,{text:n.hintText}))}function bR({open:e,onOpenChange:t,triggerId:n,triggerClassName:r,closedLabel:i,openLabel:o,contentId:s,contentClassName:c,contentHost:l=null,children:d}){const u=D(null),p=D(null),f=D(!1);at(()=>{u.current&&(u.current.id=n,u.current.setAttribute("aria-controls",s)),p.current&&(p.current.id=s)},[s,n,e]),q(()=>{if(!e){f.current=!1;return}f.current||(f.current=!0,queueMicrotask(()=>{p.current?.querySelector('button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])')?.focus()}))},[e]);const m=a(Ca,{forceMount:!0,asChild:!0,children:a("div",{ref:p,id:s,className:c,hidden:!e,children:d})});return a(Sa,{open:e,onOpenChange:t,children:[a(Op,{asChild:!0,children:a("button",{ref:u,type:"button",className:r,id:n,"aria-controls":s,children:e?o:i})}),l?fn(m,l):m]})}function Tz({open:e,onOpenChange:t}){return a(bR,{open:e,onOpenChange:t,triggerId:"syncToggleAdmin",triggerClassName:"sync-toggle-admin",closedLabel:"Set up a new team instead…",openLabel:"Hide team setup",contentId:"syncInvitePanel",children:[a("h3",{className:"settings-group-title",style:{marginTop:"12px"},children:"Create a team"}),a("div",{className:"section-meta",children:"Generate an invite to share with teammates."}),a("div",{className:"actor-create-row",children:[a("label",{htmlFor:"syncInviteGroup",className:"sr-only",children:"Team name"}),a(_e,{className:"peer-scope-input",id:"syncInviteGroup",placeholder:"Team name (e.g. my-team)",type:"text"}),a("label",{htmlFor:"syncInvitePolicy",className:"sr-only",children:"Join policy"}),a("div",{className:"sync-radix-select-host sync-actor-select-host",id:"syncInvitePolicyMount"}),a("div",{className:"sync-ttl-group",children:[a("label",{htmlFor:"syncInviteTtl",children:"Expires in"}),a(_e,{className:"peer-scope-input",defaultValue:"24",id:"syncInviteTtl",min:"1",style:{width:"64px"},type:"number"}),a("span",{children:"hours"})]}),a("button",{className:"settings-button",id:"syncCreateInviteButton",type:"button",children:"Create invite"})]}),a("label",{htmlFor:"syncInviteOutput",className:"sr-only",children:"Generated invite"}),a(co,{className:"feed-search",id:"syncInviteOutput",placeholder:"Invite will appear here",readOnly:!0,hidden:!0}),a("div",{className:"peer-meta",id:"syncInviteAdminHint"}),a("div",{className:"peer-meta",id:"syncInviteWarnings",hidden:!0})]})}function Az({contentHost:e,open:t,onOpenChange:n}){return a(bR,{open:t,onOpenChange:n,triggerId:"syncPairingToggle",triggerClassName:"settings-button",closedLabel:"Show pairing command",openLabel:"Hide pairing command",contentId:"syncPairing",contentClassName:"pairing-card",contentHost:e,children:[a("div",{className:"peer-title",children:[a("strong",{children:"Pairing command"}),a("div",{className:"peer-actions",children:a("button",{className:"settings-button",id:"pairingCopy",type:"button",children:"Copy command"})})]}),a("div",{className:"pairing-body",children:a("pre",{id:"pairingPayload",style:{userSelect:"all"}})}),a("div",{className:"peer-meta",id:"pairingHint"})]})}function Ez(e,t){dt(e,a(Tz,{...t}))}function xz(e,t){dt(e,a(Az,{...t}))}function ce(e){return String(e??"").trim()}function Dz(e){return ce(e).replace(/\s+/g," ").toLowerCase()}function jz(e){const t=ce(e);return t?t.slice(0,8):"Unnamed device"}function _R(e){return ce(e?.last_error).toLowerCase()}function wR(e){return e.includes("401")&&e.includes("unauthorized")}function SR(e){return["timeout","connection refused","unreachable","aborted","all addresses failed"].some(t=>e.includes(t))}var Lz={scope_filter:"sharing-domain membership",visibility_filter:"visibility",project_filter:"project filter"};function CR(e){return e.device?.needs_local_approval?{state:"needs-your-approval",badgeLabel:"Needs your approval",description:"Another device already approved this pairing. Approve it here to finish the connection on both sides.",actionLabel:"Approve on this device"}:e.device?.waiting_for_peer_approval?{state:"waiting-for-other-device",badgeLabel:"Waiting on other device",description:"You already approved this pairing here. The other device still needs to approve this one before sync can work both ways.",actionLabel:null}:{state:"none",badgeLabel:null,description:null,actionLabel:null}}function Oz(e){const t=CR(e),n=ce(e.device?.device_id),r=Number(e.device?.address_count??0),i=Array.isArray(e.device?.addresses)&&e.device.addresses.some(o=>ce(o))||Number.isFinite(r)&&r>0;return!n||e.device?.stale||e.hasAmbiguousCoordinatorGroup?!1:e.pairedLocally?t.state==="needs-your-approval":i}function Bm(e){const t=Array.isArray(e?.items)?e.items:[];if(!t.length)return{ok:!0,message:"Sync pass completed with no eligible devices.",warning:!1};const n=t.filter(i=>i&&i.ok===!1),r=t.filter(i=>Math.max(0,Number(i.opsSkipped??0))>0);if(!n.length){if(r.length){const i=r.reduce((s,c)=>s+Math.max(0,Number(c.opsSkipped??0)),0),o=Bz(r.map(s=>s.skipped_out??null));return{ok:!0,message:`${i.toLocaleString()} outbound op${i===1?" was":"s were"} filtered: ${o}. No payload was sent for filtered data.`,warning:!0}}return{ok:!0,message:`Sync pass finished for ${t.length} device${t.length===1?"":"s"}.`,warning:!1}}return n.filter(i=>RR(i)==="trust").length===n.length?{ok:!1,message:"This device no longer has two-way trust with the peer. Pair it again from the other device, or remove the stale local record if it should be gone.",warning:!0}:n.filter(i=>RR(i)==="scope").length===n.length?{ok:!1,message:"Sync ran, but the peer is not authorized for one or more Spaces. Review legacy Space access for this device in Coordinator Administration, then sync again.",warning:!0}:n.length<t.length?{ok:!1,message:`${n.length} of ${t.length} device sync attempts failed. Open the affected device cards for the specific errors.`,warning:!0}:{ok:!1,message:ce(n[0]?.error)||"Sync failed for at least one device.",warning:!0}}function RR(e){if(e.failureCategory)return e.failureCategory;const t=Array.isArray(e.perScopeResults)?e.perScopeResults.filter(r=>r&&r.ok===!1).map(r=>r.failureCategory).filter(r=>!!r):[];if(t.length)return new Set(t).size===1?t[0]:"other";const n=ce(e.error);return $z(n)?"trust":Mz(n)?"scope":null}function $z(e){const t=e.toLowerCase();return t.includes("401")&&t.includes("unauthorized")}function Mz(e){const t=e.toLowerCase();return!!(t.includes("scope_rejected")||t.includes("missing_scope")||t.includes("stale_epoch")||t.includes("scope_inactive"))}function Fz(e){const t=ce(e?.reason);return Lz[t]??(t.replaceAll("_"," ")||"sync filters")}function Bz(e){const t=new Map;for(const n of e){const r=Fz(n),i=Math.max(0,Number(n?.skipped_count??0));i!==0&&t.set(r,(t.get(r)??0)+i)}return t.size?Array.from(t.entries()).sort((n,r)=>r[1]-n[1]||n[0].localeCompare(r[0])).map(([n,r])=>`${r.toLocaleString()} by ${n}`).join(", "):"sync filters"}function IR(e){const t=ce(e.localName);if(t)return t;const n=ce(e.coordinatorName);return n||jz(ce(e.deviceId))}function qz(e){const t=ce(e.localName),n=ce(e.coordinatorName);return t||n?!1:!!ce(e.deviceId)}function Uz(e){const t=Math.max(0,Number(e?.recent_ops?.in??0)),n=Math.max(0,Number(e?.recent_ops?.out??0));return t>0&&n>0?"bidirectional":n>0?"publishing":t>0?"subscribed":"none"}function _s(e){const t=ce(e?.status?.peer_state);if(t==="offline"||t==="stale")return"offline";const n=_R(e);return wR(n)?"needs-repair":SR(n)?"offline":e?.has_error||t==="degraded"?"needs-repair":t==="online"||e?.status?.fresh?"connected":"waiting"}function Do(e){const t=e?.status||{},n=ce(t.peer_state),r=_R(e),i=ce(t.sync_status)==="ok"||ce(t.ping_status)==="ok";return n==="offline"||n==="stale"?{state:"offline",badgeLabel:"Offline",description:"This device was paired before, but it is offline right now.",isWarning:!0}:wR(r)?{state:"needs-repairing",badgeLabel:"Needs re-pairing",description:"This device no longer accepts this one. Pair again from the other device, or remove this local record if it no longer belongs here.",isWarning:!0}:SR(r)?{state:"offline",badgeLabel:"Offline",description:"This device is saved here, but none of its last known addresses are responding right now.",isWarning:!0}:i||n==="online"?{state:"mutual-trust",badgeLabel:"Two-way trust",description:"Both devices trust each other and sync can run in both directions.",isWarning:!1}:e?.has_error||n==="degraded"?{state:"needs-review",badgeLabel:"Needs review",description:"This device has a sync problem that needs review before you trust the current state again.",isWarning:!0}:{state:"trusted-by-you",badgeLabel:"Waiting on other device",description:"This device is already trusted here. Finish setup on the other device before sync can run both ways.",isWarning:!1}}var Gz={missing_scope:"Missing scope id",sender_not_member:"Sender not a scope member",receiver_not_member:"Receiver not a scope member",stale_epoch:"Stale or revoked membership",scope_mismatch:"Scope mismatch",visibility_filter:"Visibility filter",project_filter:"Project filter"};function Hz(e){const t=e?.scope_rejections,n=Math.max(0,Number(t?.total??0));if(!t||n===0)return{total:0,badgeLabel:null,reasons:[],lastAt:null};const r=[];for(const[i,o]of Object.entries(t.by_reason??{})){const s=Math.max(0,Number(o??0));if(s===0)continue;const c=i;r.push({reason:c,label:Gz[c]??i,count:s})}return r.sort((i,o)=>o.count-i.count||i.label.localeCompare(o.label)),{total:n,badgeLabel:n===1?"1 sync rejection":`${n.toLocaleString()} sync rejections`,reasons:r,lastAt:t.last_at??null}}function kR(e){return Array.isArray(e)?e.map(t=>ce(t)).filter(t=>!!t):[]}function NR(e,t){if(e.length===0)return t;const n=e.slice(0,3).join(", "),r=e.length-3;return r>0?`${n} +${r.toLocaleString()} more`:n}function td(e,t){return e?e.replaceAll("_"," "):t}function Vz(e){const t=(Array.isArray(e.authorized_scopes)?e.authorized_scopes:[]).map(r=>{const i=ce(r.scope_id),o=ce(r.label);if(!i&&!o)return null;const s=o||"Untitled Space",c=[td(ce(r.kind),"user"),td(ce(r.authority_type),"local"),`${td(ce(r.role),"member")} role`].filter(Boolean).join(" · ");return{scopeId:i||s,label:s,detail:c}}).filter(r=>r!=null),n=t.length;return{total:n,badgeLabel:n===1?"1 Space":n>1?`${n} Spaces`:"No Space access",isWarning:n===0,domains:t,emptyMessage:"No Space access grants exist for this device yet. Advanced project filters cannot send data by themselves."}}function PR(e){const t=(Array.isArray(e.per_scope_sync)?e.per_scope_sync:[]).map(n=>{const r=ce(n.scope_id),i=ce(n.label);if(!r&&!i)return null;const o=i||"Untitled Space",s=ce(n.last_applied_cursor),c=ce(n.last_acked_cursor),l=n.bootstrapped===!0||s?"received":"pending",d=td(ce(n.authority_type),"local"),u=Number(n.membership_epoch??0),p=[`Scope id: ${r||"unknown"}`,`${d} authority`,Number.isFinite(u)?`membership epoch ${u}`:null,s?`last applied ${s}`:null,c?`last acknowledged ${c}`:null].filter(f=>!!f).join(" · ");return{scopeId:r||o,label:o,status:l,badgeLabel:l==="received"?"Received":"Pending",detail:p}}).filter(n=>n!=null);return{total:t.length,rows:t,emptyMessage:"No per-Space sync progress is available yet. Run sync after both devices have Space access."}}var Kz=["personal","private","home","mine","me"],zz=["oss","open source","opensource","community","public"],Wz=["work","client"],Jz=["local","legacy","review"];function Yz(e){return[e.scope_id,e.label,e.kind,e.authority_type].map(t=>ce(t)??"").join(" ").toLowerCase()}function Qz(e){return[e.scope_id,e.label,e.kind].map(t=>ce(t)??"").join(" ").toLowerCase()}function TR(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qm(e,t){const n=Yz(e);return t.some(r=>{const i=TR(r.toLowerCase());return new RegExp(`(^|[^a-z0-9])${i}([^a-z0-9]|$)`).test(n)})}function AR(e){return qm(e,Kz)||qm(e,zz)}function Xz(e){const t=Qz(e);return Jz.some(n=>{const r=TR(n.toLowerCase());return new RegExp(`(^|[^a-z0-9])${r}([^a-z0-9]|$)`).test(t)})}function Zz(e){return!AR(e)&&(!Xz(e)||qm(e,Wz))}function eW(e){const t=Array.isArray(e.authorized_scopes)?e.authorized_scopes:[];if(!(ce(e.discovered_via_group_id)||ce(e.discovered_via_coordinator_id))||t.length===0)return{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""};const n=t.some(AR),r=t.some(Zz);return!n||r?{badgeLabel:null,detail:"",isVisible:!1,message:"",title:""}:{badgeLabel:"Review Space fit",detail:"Team discovery helps find the device, and advanced project filters only narrow already-authorized Spaces. Neither one grants missing work/client Space access.",isVisible:!0,message:"This Team-discovered device has personal or OSS Space access, but no separate work/client-like Space access. If this device is meant for work/client sync, grant that Space explicitly before treating sync as validated.",title:"Check this device's Space access"}}function tW(e,t){const n=e.map(r=>r.trim()).filter(Boolean);return n.length>0&&!n.includes("*")||t.length>0}function nW(e){const t=kR(e?.effective_include),n=kR(e?.effective_exclude),r=e?.inherits_global?"Global defaults":"Device override",i=`Include filter: ${NR(t,"all projects")}`,o=`Exclude filter: ${NR(n,"no exclusions")}`,s=tW(t,n);return{hasAdvancedFilters:s,statusLabel:s?"Advanced filters active":"No advanced filters",sourceLabel:r,includeLabel:i,excludeLabel:o,summary:`${r}. ${i}; ${o}.`,note:"Advanced filters only narrow data after Space access; they never grant access to another Space."}}function rW(e){const t=new Map;return(Array.isArray(e)?e:[]).forEach(n=>{const r=ce(n?.display_name),i=ce(n?.actor_id),o=Dz(r);if(!r||!i||!o)return;const s=t.get(o)??{displayName:r,actorIds:[],includesLocal:!1};s.actorIds=[...s.actorIds,i],s.includesLocal=s.includesLocal||!!n?.is_local,t.set(o,s)}),[...t.values()].filter(n=>n.actorIds.length>1).sort((n,r)=>n.displayName.localeCompare(r.displayName))}function ER(e){const t=Array.isArray(e.actors)?e.actors:[],n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.duplicatePeople)?e.duplicatePeople:[],i=new Map;n.forEach(s=>{const c=ce(s?.actor_id);c&&i.set(c,(i.get(c)??0)+1)});const o=new Set;return r.forEach(s=>{s.includesLocal&&s.actorIds.forEach(c=>{const l=t.find(d=>ce(d?.actor_id)===c);!l||l.is_local||(i.get(c)??0)>0||o.add(c)})}),{visibleActors:t.filter(s=>!o.has(ce(s?.actor_id))),hiddenLocalDuplicateCount:o.size}}var iW=new Set(["pending_setup","waiting_for_acceptance","provisioning","initial_sync","waiting_for_device","revoking"]),oW=new Set(["pending","verifying","waiting"]);function aW(e){return(Array.isArray(e?.groups)?e.groups.map(t=>ce(t)).filter(Boolean):[]).join(", ")||"none"}function sW(e){return ce(e?.projects?.[0]?.display_name)||"the shared Project"}function cW(e,t){return t?.discovered_devices?.some(n=>n.needs_local_approval||n.waiting_for_peer_approval)?!0:e.some(n=>{const r=Do(n).state;return r==="trusted-by-you"||r==="needs-repairing"})}function lW(e,t){return t?.enabled!==!0||t.daemon_state!=="ok"||t.daemon_running===!1?!1:e.some(n=>n.status?.sync_status==="ok"&&Do(n).state==="mutual-trust"&&!PR(n).rows.some(r=>r.status==="pending"))}function dW(e){return e.some(t=>ce(t.status?.peer_state)==="online"&&Do(t).state==="mutual-trust")}function uW(e,t){return t?.daemon_state==="offline-peers"||t?.daemon_state==="stale"||t?.daemon_state==="degraded"?!0:e.some(n=>{const r=ce(n.status?.peer_state),i=Do(n).state;return n.has_error===!0&&i!=="needs-repairing"||i==="offline"||i==="needs-review"||r==="offline"||r==="stale"||r==="degraded"})}function pW(e){if(e?.daemon_running===!1)return!0;const t=e?.daemon_state;return t!==void 0&&t!=="ok"&&t!=="offline-peers"&&t!=="stale"&&t!=="degraded"}function fW(e){return{status:e.status,coordinator:e.coordinator,peers:Array.isArray(e.peers)?e.peers:[],operations:Array.isArray(e.shareOperations)?e.shareOperations:[],reconciliationItems:Array.isArray(e.reconciliation?.items)?e.reconciliation.items:[],shareOperationsLoadError:e.shareOperationsLoadError===!0,label:aW(e.coordinator)}}function mW(e){if(e.status?.enabled===!1||e.coordinator?.sync_enabled===!1)return{state:"disabled",badgeLabel:"Sync off",meta:`Team: ${e.label}. Coordinator presence does not move Project data while sync is off.`,nextAction:"Open Settings and turn on sync before expecting Team or Project data to update."};if(e.shareOperationsLoadError)return{state:"needs-attention",badgeLabel:"Refresh needed",meta:`Team: ${e.label}. Device diagnostics are available, but Project sharing status could not be refreshed.`,nextAction:"Refresh Team sync to retry loading Project sharing status."};const t=e.operations.find(r=>r.lifecycle?.state==="needs_attention"),n=e.reconciliationItems.find(r=>r.state==="needs_attention");return t?{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${e.label}. A Project access update stopped and needs a retry.`,nextAction:"Retry the stopped Project access update below."}:n?{state:"needs-attention",badgeLabel:"Needs attention",meta:`Team: ${e.label}. A Project access reconciliation needs review.`,nextAction:"Open Sharing, review this Project's access decision, then sync again."}:null}function hW(e,t){if(e?.lifecycle?.state==="revoking")return`Keep both devices online, then sync again to finish removing future access for ${t}.`;const n=e?.lifecycle?.primary_action?.kind;return n==="retry_setup"?`Open Project sharing below and retry setup for ${t}.`:n==="copy_invite"?`Copy the invitation for ${t} and send it to the recipient.`:`Keep both devices online, then sync again to finish setup for ${t}.`}function vW(e){const t=e.operations.find(o=>{const s=o.lifecycle?.state;return s!==void 0&&iW.has(s)}),n=e.reconciliationItems.find(o=>{const s=o.state;return s!==void 0&&oW.has(s)});if(!t&&!n)return null;const r=t?sW(t):"the shared Project",i=t?.lifecycle?.state==="revoking";return{state:"pending-setup",badgeLabel:i?"Removal pending":"Setup pending",meta:i?`Team: ${e.label}. Future access removal for ${r} is still pending.`:`Team: ${e.label}. Exact-Project setup is still pending and data delivery is not confirmed.`,nextAction:hW(t,r)}}function gW(e){return pW(e.status)?{state:"needs-attention",badgeLabel:"Sync needs attention",meta:`Team: ${e.label}. The local sync service is not healthy, so Project data delivery is not confirmed.`,nextAction:"Review the sync status below, restart codemem if needed, then run Sync now again."}:cW(e.peers,e.coordinator)?{state:"trust-blocked",badgeLabel:"Pairing needed",meta:`Team: ${e.label}. A device still needs two-way trust before Project data can sync.`,nextAction:"Review the device below and finish pairing or approval on both devices."}:null}function yW(e){const t=ce(e.coordinator?.presence_status);if(t==="not_enrolled")return{state:"not-enrolled",badgeLabel:"Not enrolled",meta:`Team: ${e.label}. This device is not enrolled with the coordinator.`,nextAction:"Paste a Team invite below, or ask a Team admin to enroll this device."};if(t!=="posted"){const n=e.coordinator?.configured===!0;return{state:"unreachable",badgeLabel:n?"Unreachable":"Setup needed",meta:n?`Team: ${e.label}. The coordinator is not currently reachable and no healthy data-plane sync is confirmed.`:"Configure or join a Team before expecting Project data to sync.",nextAction:n?"Check the coordinator connection, then refresh Team sync.":"Paste a Team invite below, or set a coordinator URL in Settings → Device Sync."}}return null}function bW(e){return uW(e.peers,e.status)?{state:"reachable",badgeLabel:"Check devices",meta:`Team: ${e.label}. The coordinator is reachable, but one or more paired devices are offline or degraded.`,nextAction:"Bring the paired devices online, check their sync errors, then run Sync now again."}:e.coordinator?.sync_enabled===!0&&lW(e.peers,e.status)?{state:"healthy",badgeLabel:"Healthy",meta:`Team: ${e.label}. Sync is enabled and a trusted device has a healthy data-plane connection.`,nextAction:null}:dW(e.peers)?{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${e.label}. The coordinator and a paired device are reachable, but successful Project sync is not confirmed.`,nextAction:"Run Sync now, then review the device sync status below if delivery is still pending."}:{state:"reachable",badgeLabel:"Reachable",meta:`Team: ${e.label}. The coordinator is reachable, but healthy Project data sync is not confirmed.`,nextAction:"Pair and approve a device, then run Sync now to confirm data delivery."}}function xR(e){const t=fW(e);return mW(t)??vW(t)??gW(t)??yW(t)??bW(t)}function _W(e){return e.discovered?.stale?e.peer?_s(e.peer)!=="connected":!0:!1}function DR(e){return{id:`repair:${e.id}`,kind:"device-needs-repair",priority:10,title:e.title||`${e.name} needs attention`,summary:e.summary,actionLabel:"Open device",deviceId:e.id}}function wW(e){return{id:`review:${e.id}:${e.key||"default"}`,kind:"review-team-device",priority:20,title:`${e.name} is available to review`,summary:e.summary,actionLabel:"Open device",deviceId:e.id}}function SW(e){return{id:`name:${e.id}`,kind:"name-device",priority:30,title:`Name ${e.name}`,summary:e.summary,actionLabel:"Go to name field",deviceId:e.id}}function CW(e){const t=ce(e?.coordinator_url),n=Array.isArray(e?.groups)?e.groups:[];return t?n.some(r=>ce(r))?e?.sync_enabled===!1?{reason:"sync_disabled",message:"Enable sync before pairing team devices."}:null:{reason:"coordinator_groups_empty",message:"Join or configure a team before pairing team devices."}:{reason:"coordinator_url_missing",message:"Configure a coordinator URL before pairing team devices."}}function RW(e,t){const n=new Map,r=i=>{const o=n.get(i)??{deviceId:i,localName:"",coordinatorName:"",peer:null,discovered:null};return n.set(i,o),o};return e.forEach(i=>{const o=ce(i?.peer_device_id);if(!o)return;const s=r(o);s.peer=i,s.localName=ce(i?.name)}),t.forEach(i=>{const o=ce(i?.device_id);if(!o)return;const s=r(o);s.discovered=i,s.coordinatorName=ce(i?.display_name)}),[...n.values()]}function IW(e){return e.map(t=>({id:`duplicate:${t.actorIds.join(":")}`,kind:"possible-duplicate-person",priority:t.includesLocal?5:15,title:`Possible duplicate person: ${t.displayName}`,summary:t.includesLocal?"At least one entry is marked as you. Confirm whether these records represent the same person.":"Multiple people share this name. Confirm whether they should stay separate or be combined.",actionLabel:"Go to people",actorIds:t.actorIds}))}function kW(e,t){const n=ce(e.discovered?.fingerprint),r=ce(e.peer?.fingerprint);return!e.peer||!n||!r||n===r?null:DR({id:e.deviceId,name:t,title:`${t} needs review`,summary:"This device identity changed. Remove the older local record before reconnecting it."})}function NW(e,t){if(!e.peer)return[];const n=[],r=_s(e.peer),i=Do(e.peer);return r==="needs-repair"&&n.push(DR({id:e.deviceId,name:t,title:i.state==="needs-repairing"?`${t} needs re-pairing`:`${t} needs review`,summary:i.description||ce(e.peer.last_error)||"Sync needs review."})),i.state==="trusted-by-you"&&n.push(wW({id:e.deviceId,key:"other-device-trust",name:t,summary:"You accepted this device. Finish onboarding on the other device so it trusts this one too."})),qz({localName:e.localName,coordinatorName:e.coordinatorName,deviceId:e.deviceId})&&n.push(SW({id:e.deviceId,name:t,summary:"Give this device a friendly name so it is easier to recognize later."})),n}function PW(e){const t=IR({localName:e.localName,coordinatorName:e.coordinatorName,deviceId:e.deviceId}),n=kW(e,t);return n?[n]:NW(e,t)}function TW(e){const t=Array.isArray(e.actors)?e.actors:[],n=Array.isArray(e.peers)?e.peers:[],r=Array.isArray(e.coordinator?.discovered_devices)?e.coordinator.discovered_devices:[],i=RW(n,r),o=e.duplicatePersonDecisions??{},s=rW(t).filter(l=>!o[[...l.actorIds].sort().join("::")]),c=[...IW(s),...i.flatMap(PW)];return{primaryStatus:xR({status:e.status,coordinator:e.coordinator,peers:n,shareOperations:e.shareOperations,shareOperationsLoadError:e.shareOperationsLoadError,reconciliation:e.reconciliation}),summary:{connectedDeviceCount:n.filter(l=>_s(l)==="connected").length,seenOnTeamCount:r.length,offlineTeamDeviceCount:i.filter(l=>_W(l)).length},duplicatePeople:s,attentionItems:c.sort((l,d)=>l.priority-d.priority||l.title.localeCompare(d.title))}}var jR={actor:"person",actors:"people",actorAssignment:"person assignment",localActor:"you",peer:"device",peers:"devices",pairedLocally:"Connected on this device",discovered:"Seen on team",conflicts:"Needs review"};function Er(e){const t=document.getElementById(e);t&&t.remove()}var LR=!1;function AW(e){LR=e}var Um=!1;function EW(e){Um=e}var xW=new Set,Gm=new Set,Hm=new Set,OR="codemem-sync-duplicate-person-decisions";function DW(e){const t=String(e||"").trim();t&&(Gm.add(t),Hm.add(t),xW.add(t))}function Vm(e){const t=String(e||"").trim();return!!t&&Gm.has(t)}function jW(e){const t=String(e||"").trim();t&&Gm.delete(t)}function LW(e){const t=String(e||"").trim();return!t||!Hm.has(t)?!1:(Hm.delete(t),!0)}function Km(){try{const e=localStorage.getItem(OR);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function $R(e){try{localStorage.setItem(OR,JSON.stringify(e))}catch{}}function MR(e){return[...e].map(t=>String(t||"").trim()).filter(Boolean).sort().join("::")}function OW(){return Km()}function $W(e,t){const n=MR(e);if(!n)return;const r=Km();r[n]=t,$R(r)}function MW(e){const t=MR(e);if(!t)return;const n=Km();delete n[t],$R(n)}function FR(e){return e.replace(/\b(\d{1,3}\.\d{1,3})\.\d{1,3}\.\d{1,3}\b/g,"$1.#.#")}function BR(e){const t=String(e||"");return t?FR(t):""}function FW(e){if(!Array.isArray(e))return"";const t=Array.from(new Set(e.filter(Boolean)));return typeof t[0]=="string"?t[0]:""}function BW(e,t){const n=String(e?.relatedPeerDeviceId??"").trim();return n?t.some(r=>String(r?.peer_device_id??"").trim()===n):!1}function nd(e){if(!e||typeof e!="object")return"Unknown person";const t=String(e.display_name||"").trim();return t||String(e.actor_id||"Unknown person")}function zm(e){return!e||typeof e!="object"?"Unknown person":e.is_local?"You":nd(e)}function qW(e){return(Array.isArray(_.lastSyncPeers)?_.lastSyncPeers:[]).filter(t=>String(t?.actor_id||"")===e).length}function UW(){return ER({actors:_.lastSyncActors,peers:_.lastSyncPeers,duplicatePeople:_.lastSyncViewModel?.duplicatePeople}).visibleActors}function qR(e){return UW().filter(t=>String(t?.actor_id||"")!==e)}function GW(e,t){const n=qR(t).find(r=>String(r?.actor_id||"")===e);return!e||!n?"Choose which person should keep these devices.":`Merge into ${zm(n)}. Assigned devices move now; existing memories keep their current provenance.`}function Wm(e,t){if(e){if(e.textContent="",!t.length){e.hidden=!0;return}e.hidden=!1,t.slice(0,2).forEach(n=>{const r=wc("div","sync-action"),i=wc("div","sync-action-text");i.textContent=n.label,i.appendChild(wc("span","sync-action-command",n.command));const o=wc("button","settings-button sync-action-copy","Copy");o.addEventListener("click",()=>Yi(n.command,o)),r.append(i,o),e.appendChild(r)})}}function UR(e,t){return t&&e.error_redacted===!0}function HW(e){return e?{action:t=>ur({severity:"error",subsystem:"sync",trigger:t})}:{}}function GR(){const e=document.getElementById("syncAttempts");if(!e)return;const t=_.lastSyncAttempts,n=String(_.lastSyncStatus?.daemon_state||"").trim();if(!Array.isArray(t)||!t.length){Si(e,wz());return}const r=Cz(n,t.slice(0,5).some(o=>o.status==="error")),i=t.slice(0,5).map(o=>{const s=o.started_at||o.started_at_utc||"",c=String(o.peer_device_id||"").trim(),l=Array.isArray(_.lastSyncPeers)?_.lastSyncPeers.find(m=>String(m?.peer_device_id||"")===c):null,d=String(l?.name||"").trim()||(c?c.slice(0,8):"unknown"),u=o.status==="error",p=[],f=ba();if(u&&o.error){const m=String(o.error);p.push(f?FR(m):m),UR(o,f)&&p.push("Turn off Redact in Advanced diagnostics to reveal the full error.")}return!u&&(o.ops_in||o.ops_out)&&p.push(`${o.ops_in??0} in · ${o.ops_out??0} out`),!f&&o.address&&p.push(o.address),{status:o.status||"unknown",peerLabel:d,detail:p.join(" · "),startedAt:s?lr(s):"",...HW(u),...UR(o,f)?{actionHref:"#sync/diagnostics",actionLabel:"Open Advanced diagnostics Redact setting"}:{}}});Pz(e,i,r)}function VW(){const e=document.getElementById("syncPrimaryStatusDetail");e&&(e.textContent="");const t=document.getElementById("syncStatusGrid"),n=document.getElementById("syncAttempts"),r=document.getElementById("syncMeta"),i=document.getElementById("syncActions");t&&Si(t,_z()),n&&Si(n,Sz()),r&&(r.textContent="Advanced diagnostics are unavailable right now. Refresh the page first. If that still fails, verify the local sync service and retry once it responds again."),Wm(i,[])}function jo(e){const t=Number(e??0);return Number.isFinite(t)?t:0}function KW(e){const t=String(e?.state??"clear"),n=e?.stale_peer_rows??{},r=e?.access_cleanup_ops??{},i=jo(n.would_remove),o=jo(n.ambiguous),s=jo(r.applied),c=jo(r.source_authored);return t==="cleanup_pending"||i>0?`${i} pending removal`:t==="needs_review"||o>0?`${o} needs review`:t==="cleanup_applied"||s>0?`${s} applied`:t==="cleanup_announced"||c>0?`${c} announced`:"Clear"}function zW(e){if(e.syncNoPeers)return[{label:"State",value:"No peers"},{label:"Mode",value:"Ready to pair"},{label:"Pending events",value:e.pending},{label:"Last sync",value:"Waiting for first peer"}];let t="Disabled";return e.retentionEnabled&&(t="Enabled"),e.retentionEnabled&&e.retentionLastRunAt&&(t=`${e.retentionDeleted.toLocaleString()} ops last run (approx)`),[{label:"State",value:e.daemonStateLabel},{label:"Pending events",value:e.pending},{label:"Last sync",value:e.lastSync?`${oa(Gi(e.lastSync))} ago`:"never"},{label:"Last peer ping",value:e.lastPing?`${oa(Gi(e.lastPing))} ago`:"never"},{label:"Retention",value:t}]}function HR(){const e=document.getElementById("syncStatusGrid"),t=document.getElementById("syncMeta"),n=document.getElementById("syncActions");if(!e)return;Er("syncDiagSkeleton");const r=_.lastSyncStatus;if(!r){Si(e,bz()),Wm(n,[]),t&&(t.textContent="Loading advanced sync diagnostics…");return}const i=r.peers||{},o=r.ping||{},s=r.sync||{},c=r.last_sync_at||r.last_sync_at_utc||null,l=o.last_ping_at||r.last_ping_at||hz(i)||null,d=r.last_sync_error||"",u=r.last_ping_error||"",p=Number(r.pending||0),f=String(r.daemon_detail||""),m=String(r.daemon_state||"unknown"),v=r.retention||{},b=r.cleanup_diagnostics,g=b?.stale_peer_rows??{},y=jo(g.would_remove),S=jo(g.ambiguous),w=v.enabled===!0,R=Number(v.last_deleted_ops||0),k=v.last_run_at||null,N=String(v.last_error||""),j={needs_attention:"Needs attention","offline-peers":"Offline peers",rebootstrapping:"Rebootstrapping"}[m]??by(m),E=m==="disabled"||r.enabled===!1,F=Object.keys(i).length,A=!E&&F===0;if(t){let H;E?H=["Advanced sync is off on this device","Turn on sync in Settings → Device Sync when you want pairing payloads, peer status, and recent attempt details here"]:A?H=["Advanced sync is ready but idle","Pair another device from Devices, then return here for live peer status and recent attempts"]:H=[`Advanced state: ${j}`,`Peers: ${F}`,c?`Last sync: ${oa(Gi(c))} ago`:"Last sync: never"],m==="offline-peers"&&H.push("All peers are currently offline; sync will resume automatically"),f&&m==="stopped"&&H.push(`Detail: ${f}`),f&&(m==="needs_attention"||m==="rebootstrapping")&&H.push(`Detail: ${f}`),w&&H.push(k?`Retention last ran ${oa(Gi(k))} ago (approx oldest-first)`:"Retention enabled"),y>0?H.push(`${y.toLocaleString()} stale peer rows pending cleanup`):S>0&&H.push(`${S.toLocaleString()} stale peer rows retained because safe cleanup could not be proven`),t.textContent=H.join(" · ")}const M=E?[{label:"State",value:"Disabled"},{label:"Mode",value:"Optional"},{label:"Pending events",value:p},{label:"Last sync",value:"Not running"}]:zW({daemonStateLabel:j,lastPing:l,lastSync:c,pending:p,retentionDeleted:R,retentionEnabled:w,retentionLastRunAt:k,syncNoPeers:A});!E&&!A&&(d||u)&&M.push({label:[d,u].filter(Boolean).join(" · "),value:"Errors"}),!E&&!A&&s.seconds_since_last&&M.push({label:"Since last sync",value:`${s.seconds_since_last}s`}),!E&&!A&&o.seconds_since_last&&M.push({label:"Since last peer ping",value:`${o.seconds_since_last}s`}),!E&&w&&N&&M.push({label:N,value:"Retention"}),!E&&!A&&b&&M.push({label:"Cleanup",value:KW(b)}),Nz(e,M);const O=[];A||m==="offline-peers"||(m==="stopped"?(O.push({label:"Sync daemon is stopped. Start it.",command:"codemem serve start"}),O.push({label:"Run one sync pass now.",command:"codemem sync once"})):m==="needs_attention"?O.push({label:"Sync needs manual attention before reset can continue.",command:"codemem sync doctor"}):m==="rebootstrapping"?O.push({label:"Sync is rebuilding state in the background.",command:"codemem sync status"}):d||u||m==="error"?(O.push({label:"Sync reports errors. Restart now.",command:"codemem serve restart && codemem sync once"}),O.push({label:"Run doctor for the root cause.",command:"codemem sync doctor"})):!E&&!A&&p>0&&O.push({label:"Pending sync work detected. Run one pass now.",command:"codemem sync once"})),!E&&S>0?O.push({label:"Some stale peer rows were retained because cleanup was ambiguous.",command:"codemem sync doctor"}):!E&&y>0&&O.push({label:"Stale peer rows are eligible for cleanup. Run one sync pass now.",command:"codemem sync once"}),Wm(n,O)}var WW="syncRedactMount",JW="syncRedactLabel",VR=()=>{};function YW(e){VR=e}var Jm=()=>{};function Ym(){const e=document.getElementById("syncPairingDisclosureMount"),t=document.getElementById("syncPairingPanelMount");if(!e||!t)return;xz(e,{contentHost:t,open:_.syncPairingOpen,onOpenChange:r=>{if(tD(r),Ym(),r){const i=document.getElementById("pairingPayload"),o=document.getElementById("pairingHint");i&&yR(i,o,{payloadText:"Loading…",hintText:"Fetching pairing payload…"})}Jm()}});const n=document.getElementById("pairingCopy");n&&(n.onclick=async()=>{const r=_.pairingCommandRaw;r&&await Yi(r,n)})}function Qm(){Ym();const e=document.getElementById("pairingPayload"),t=document.getElementById("pairingHint");if(!e)return;yR(e,t,yz(_.pairingPayloadRaw));const n=document.getElementById("pairingCopy");n&&(n.disabled=!_.pairingCommandRaw)}function KR(){const e=document.getElementById(WW);e&&dt(e,h(oo,{"aria-labelledby":JW,checked:ba(),className:"sync-redact-switch",id:"syncRedact",onCheckedChange:t=>{nD(t),KR(),Jm(),HR(),VR(),GR(),Qm()},thumbClassName:"sync-redact-switch-thumb"}))}function QW(e){Jm=e,Ym(),KR()}var Ci=new Map,Xm=null,XW={operation_device_binding_missing:"The accepted device has not been linked yet.",operation_not_found:"This sharing operation is no longer available.",operation_scope_mismatch:"The invitation no longer matches the reviewed project access.",operation_state_invalid:"The invitation is no longer in a recoverable state.",reassign_capability_required:"A participating device must be updated before setup can continue."};function ZW(e){const t=e instanceof Error?e.message:String(e);return XW[t]??"Setup could not be retried. Review diagnostics for details."}function e3(e){const t=new Map;for(const n of e){const r=n.person.actor_id;t.set(r,[...t.get(r)??[],n])}return[...t.values()]}function t3(e){return[...new Map(e.flatMap(t=>t.devices).map(t=>[t.device_id,t])).values()]}function Zm(e){switch(e){case"waiting_for_acceptance":return"Invitation pending";case"active":return"Sharing";case"revoking":return"Removing sharing";case"revoked":return"Previously shared";case"cancelled":return"Invitation cancelled";default:return"Sharing setup"}}function n3({operation:e,onAdvance:t,onLoadOperation:n,onReload:r,copyText:i}){const[o,s]=T(!1),[c,l]=T(()=>Ci.get(e.operation_id)??null),d=D(null),u=e.lifecycle.primary_action;q(()=>{Xm!==e.operation_id||!d.current||(Xm=null,d.current.focus())},[c?.message,e.operation_id]);async function p(b){s(!0);try{let g=b;if(!g&&n){const S=(await n(e.operation_id)).lifecycle.primary_action;S?.kind==="copy_invite"&&(g=S.invite_link)}if(!g)throw new Error("Invitation is no longer available. Refresh the status.");await(i??(S=>navigator.clipboard.writeText(S)))(g);const y={message:"Invite copied.",tone:"success"};Ci.set(e.operation_id,y),l(y)}catch(g){const y={message:g instanceof Error?g.message:"Invite could not be copied.",tone:"warning"};Ci.set(e.operation_id,y),l(y)}finally{s(!1)}}async function f(){s(!0);try{const b=await t(e.operation_id),g=b.lifecycle.state==="active"?{message:"Setup complete.",tone:"success"}:b.lifecycle.state==="needs_attention"?{message:"Setup still needs attention.",tone:"warning"}:{message:`Retry started. ${b.lifecycle.label}.`,tone:"success"};Ci.set(e.operation_id,g),Xm=e.operation_id,l(g),await r()}catch(b){const g={message:ZW(b),tone:"warning"};Ci.set(e.operation_id,g),l(g),queueMicrotask(()=>d.current?.focus())}finally{s(!1)}}function m(){const b=e.projects.map(g=>g.project_id?.trim()).filter(g=>!!g);if(b.length!==e.projects.length){const g={message:"The original project selection is unavailable. Refresh Projects and try again.",tone:"warning"};Ci.set(e.operation_id,g),l(g);return}if(!ic(b,e.person.display_name)){const g={message:"Project sharing is unavailable. Refresh Projects and try again.",tone:"warning"};Ci.set(e.operation_id,g),l(g)}}function v(){if(u){if(u.kind==="copy_invite"){p(u.invite_link);return}if(u.kind==="retry_setup"){f();return}m()}}return a("section",{"aria-label":`${Zm(e.lifecycle.state)} operation`,className:"project-share-operation-card",children:[a("div",{className:"peer-scope-summary",children:Zm(e.lifecycle.state)}),a("ul",{"aria-label":`${Zm(e.lifecycle.state)} projects`,className:"peer-scope-chips",children:e.projects.map((b,g)=>a("li",{className:"peer-scope-chip",children:b.display_name},`${b.display_name}:${g}`))}),a("div",{className:"peer-scope-summary",children:e.lifecycle.label}),a("div",{className:"peer-meta",role:e.lifecycle.state==="needs_attention"?"alert":void 0,children:e.lifecycle.explanation}),u?a("div",{className:"peer-actions",children:a("button",{"aria-busy":o,className:"settings-button",disabled:o,type:"button",onClick:v,children:o?u.kind==="copy_invite"?"Copying…":"Retrying…":u.label})}):null,c?a("div",{ref:d,className:`settings-note ${c.tone==="warning"?"project-attention-note":""}`,role:"status",tabIndex:-1,children:c.message}):null]})}function r3({operations:e,...t}){const n=e[0].person,r=t3(e);return a("article",{"aria-label":`Project sharing with ${n.display_name}`,className:"peer-card project-share-person-group",children:[a("h3",{className:"device-row-name",children:n.display_name}),r.length>0?a("ul",{"aria-label":`Devices for ${n.display_name}`,className:"peer-scope-rejections-list",children:r.map(i=>a("li",{children:i.display_name},i.device_id))}):null,e.map(i=>a(n3,{operation:i,...t},i.operation_id))]})}function i3(e){return e.operations.length===0?null:a("div",{className:"project-share-person-groups",children:e3(e.operations).map(t=>a(r3,{...e,operations:t},t[0].person.actor_id))})}function o3(e,t){dt(e,a(i3,{...t}))}function zR({title:e,detail:t}){return a("div",{className:"sync-empty-state",role:"status","aria-live":"polite","aria-atomic":"true",children:[a("strong",{children:e}),a("span",{children:t})]})}function a3(e){return e<=0?"Represents you across your own devices.":`Represents you across your own devices. ${e} unresolved duplicate ${e===1?"entry is":"entries are"} hidden until reviewed in Needs attention.`}function s3({actor:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){const o=String(e.actor_id||""),s=nd(e),c=qW(o),l=qR(o),d=l.map(O=>String(O.actor_id||"")).join("|"),[u,p]=T(s),[f,m]=T(!1),[v,b]=T("Rename"),[g,y]=T(!1),[S,w]=T("Merge into selected person"),[R,k]=T(""),[N,j]=T(!1);q(()=>{p(s),m(!1),b("Rename"),y(!1),w("Merge into selected person"),k(""),j(!1)},[o,c,t,s,d]);const E=l.length?GW(R,o):"No other people are available yet. Create another person first if you need to merge duplicates.",F=[{label:"Merge into person",value:""},...l.map(O=>{const H=String(O.actor_id||"");return{label:O.is_local?zm(O):nd(O),value:H}})];async function A(){const O=u.trim();if(!O)return;m(!0),b("Saving…");let H=!1;try{await n(o,O),H=!0}catch{b("Retry rename")}finally{m(!1),H&&b("Rename")}}async function M(){if(!R)return;const O=l.find(V=>String(V.actor_id||"")===R);if(!O||!await wn({title:`Merge ${s} into ${nd(O)}?`,description:"Assigned devices move now, but older memories keep their current stamped provenance for now.",confirmLabel:"Merge people",cancelLabel:"Keep separate",tone:"danger"}))return;y(!0),w("Merging…");let H=!1;try{await r(R,o),H=!0}catch{w("Retry merge")}finally{y(!1),H&&w("Merge into selected person")}}return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:[a("div",{className:"actor-title",children:[a("strong",{children:zm(e)}),a("span",{className:`badge actor-badge${e.is_local?" local":""}`,title:e.is_local?a3(t):void 0,children:e.is_local?"You":`${c} device${c===1?"":"s"}`})]}),e.is_local?null:a("div",{className:"peer-meta",children:[c," assigned device",c===1?"":"s"]})]}),a("div",{className:"actor-actions",children:e.is_local?a("div",{className:"peer-meta",children:"Rename yourself in config"}):a(G,{children:[a(_e,{"aria-label":`Rename ${s}`,className:"peer-scope-input actor-name-input",disabled:f||g,type:"text",value:u,onInput:O=>p(O.currentTarget.value),onKeyDown:O=>Ta(O,{onSubmit:()=>{A()},disabled:f||g||!u.trim()})}),a("button",{type:"button",className:"settings-button","data-primary-action":"true",disabled:f||g,onClick:()=>{A()},children:v}),a("button",{type:"button",className:"settings-button danger",disabled:f||g,onClick:async()=>{await wn({title:`Remove ${s}?`,description:"This deactivates the person and unassigns their devices. Existing memories keep their current attribution.",confirmLabel:"Remove person",cancelLabel:"Keep",tone:"danger"})&&await i(o)},children:"Remove"}),a("button",{type:"button",className:"settings-button",disabled:f||g,onClick:()=>j(O=>!O),children:N?"Hide duplicate cleanup":"Show duplicate cleanup"}),N?a(G,{children:[a("div",{className:"peer-meta actor-merge-note",children:"Use this only when combining duplicate people into one."}),a("div",{className:"actor-merge-controls",children:[a(Jn,{ariaLabel:`Merge ${s} into another person`,contentClassName:"sync-radix-select-content sync-actor-select-content",disabled:g||l.length===0,itemClassName:"sync-radix-select-item",onValueChange:k,options:F,placeholder:"Merge into person",triggerClassName:"sync-radix-select-trigger sync-actor-select actor-merge-select",value:R,viewportClassName:"sync-radix-select-viewport"}),a("button",{type:"button",className:"settings-button",disabled:g||l.length===0||!R,onClick:()=>{M()},children:S})]}),a("div",{className:"peer-meta actor-merge-note",children:E})]}):null]})})]})}function c3({actors:e,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i}){return e.length?a(G,{children:e.map(o=>{const s=String(o.actor_id||o.display_name||o.is_local||"");return a(s3,{actor:o,hiddenLocalDuplicateCount:t,onRename:n,onMerge:r,onDeactivate:i},s)})}):a(zR,{detail:"Create a named person here for legacy provenance, then confirm device Identity ownership in Devices.",title:"No people set up yet."})}function l3(e,t){dt(e,a(c3,{...t}))}function d3(e){return e.filter(t=>String(t.origin_device_id||"").trim())}function u3(e){const t=e.find(n=>String(n.last_seen_at||"").trim());return t?.last_seen_at?`Detected from older synced memories. Latest memory: ${lr(String(t.last_seen_at).trim())}`:"Detected from older synced memories not yet attached to a current device."}function p3({devices:e}){return a(G,{children:u3(e)})}function f3(e){const t=String(e.origin_device_id||"").trim(),n=Number(e.memory_count||0);return{label:n>0?`${t} (${n} memories)`:t,value:t}}function m3(e){const t=d3(e.devices);if(!t.length){e.panel.hidden=!0,e.onValueChange(""),xo(e.mount),xo(e.meta);return}const n=t.map(f3),r=n.some(i=>i.value===e.value)?e.value:n[0]?.value||"";r!==e.value&&e.onValueChange(r),e.panel.hidden=!1,dt(e.mount,a(Jn,{ariaLabel:"Legacy device",contentClassName:"sync-radix-select-content sync-legacy-select-content",id:"syncLegacyDeviceSelect",itemClassName:"sync-radix-select-item",onValueChange:e.onValueChange,options:n,triggerClassName:"sync-radix-select-trigger sync-legacy-select",value:r,viewportClassName:"sync-radix-select-viewport"})),dt(e.meta,a(p3,{devices:t}))}function xr({feedback:e}){return e?.message?a("div",{className:`sync-inline-feedback ${e.tone}`,role:e.tone==="warning"?"alert":"status","aria-live":e.tone==="warning"?"assertive":"polite","aria-atomic":"true",children:e.message}):null}function h3(){return a("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor","stroke-linecap":"round","stroke-linejoin":"round","stroke-width":"2",viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",children:[a("title",{children:"Chevron"}),a("path",{d:"m9 18 6-6-6-6"})]})}function v3(e){switch(_s(e)){case"connected":return"online";case"offline":return"offline";case"needs-repair":return"attention";default:return"unknown"}}var rd=null,WR=0,eh=new Set;function JR(e){if(rd!==e){rd=e,WR+=1;for(const t of eh)t(WR)}}function g3(){const[,e]=T(0);return q(()=>(eh.add(e),()=>{eh.delete(e)}),[]),rd}var y3={bidirectional:{glyph:"↕",label:"Bidirectional sync in the last 24 hours"},publishing:{glyph:"↑",label:"Publishing only in the last 24 hours"},subscribed:{glyph:"↓",label:"Subscribed only in the last 24 hours"},none:null};function YR(e,t){if(!e)return"the selected Identity";const n=t.find(r=>r.actor_id===e);return String(n?.display_name||n?.actor_display_name||"the selected Identity")}function b3(e,t,n,r=!1,i=!1,o=!1){if(i)return{status:"unavailable",summary:"Authoritative Identity status is unavailable because the inventory is incomplete.",detail:"This installation has more device evidence than Advanced can safely classify. Ownership is not shown from a partial inventory.",actionLabel:"Review Identity inventory in Devices"};if(r||o&&!e)return{status:"unavailable",summary:"Authoritative Identity status is temporarily unavailable.",detail:"Refresh before relying on ownership details. Advanced actor_id values remain suggestions or provenance only.",actionLabel:"Review Identity in Devices"};if(e?.state==="configured")return{status:"configured",summary:`Authoritative Identity: ${YR(e.identityId,n)}.`,detail:"This result comes from an active identity_devices binding. Advanced actor_id values are not authoritative ownership.",actionLabel:"Review or rebind in Devices"};if(e?.state==="pairing_required")return{status:"pairing_required",summary:"Identity setup is blocked until pairing is complete.",detail:"Pairing establishes sync trust; it does not establish device ownership.",actionLabel:"Review setup in Devices"};if(e?.state==="conflicted")return{status:"conflicted",summary:"Identity ownership needs review.",detail:"Conflicting device evidence failed closed. Advanced actor_id values cannot resolve ownership.",actionLabel:"Review conflict in Devices"};const s=e?.suggestedIdentityId??t;return{status:e?.state??"unavailable",summary:s?`Suggested Identity: ${YR(s,n)}.`:"No authoritative Identity binding is configured.",detail:"sync_peers.actor_id is only a suggestion or hint until you confirm an identity_devices binding in Devices.",actionLabel:"Set up Identity in Devices"}}function _3(e){_.pendingDeviceIdentityFocus=e?.trim()||null,window.location.hash="devices"}function w3(e){return e?e.authorized?"Private same-person sync is limited to your personal Space. Team and org Spaces do not carry your private memories.":"Private same-person sync is blocked until this device is granted an allowed personal Space.":"Private same-person sync is limited to an allowed personal Space; team or org Spaces do not carry your private memories."}function S3(){window.location.hash="advanced/teams/administration"}function th(e=_.lastSyncCoordinatorAdminStatus){return e?.readiness==="ready"&&e.has_admin_secret===!0}function C3({peer:e,onRemove:t,onRename:n,onSync:r}){const i=String(e.peer_device_id||""),o=e.name||(i?i.slice(0,8):"unknown"),s=e.name||i||o,c=Do(e),l=y3[Uz(e)],d=e.status||{},u=Vz(e),p=Vm(i),f=p&&u.total===0,m=eW(e),v=Hz(e),b=PR(e),g=e.project_scope||{},y=nW(g),S=FW(e.addresses),w=Array.isArray(e.addresses)?Array.from(new Set(e.addresses.filter(Boolean).map(le=>String(le)))):[],R=Number(e.address_count??0),k=Number.isFinite(R)&&R>0?R:0,N=w.length?w.map(le=>ba()?BR(le):le).join(" · "):k>0?`${k} ${k===1?"address":"addresses"} hidden`:"No addresses",j=_.lastDeviceIdentityInventory?.items.find(le=>le.deviceId===i||le.evidenceDeviceIds.includes(i)),E=b3(j,String(e.actor_id||"")||null,_.lastSyncActors,_.deviceIdentityInventoryLoadError,_.lastDeviceIdentityInventory?.truncated===!0,_.lastDeviceIdentityInventory?.coordinatorEvidence.availability==="unavailable"),F=String(d.last_sync_at||d.last_sync_at_utc||""),A=String(d.last_ping_at||d.last_ping_at_utc||""),M=e.discovered_via_group_id?`Discovery: seen through coordinator group ${e.discovered_via_group_id}. Discovery helps find devices; Space access above decides data access.`:e.discovered_via_coordinator_id?`Discovery: seen through coordinator ${e.discovered_via_coordinator_id}. Discovery helps find devices; Space access above decides data access.`:null,O=LW(i),H=D(null),[V,W]=T(o),[$,C]=T(()=>_.syncPeerFeedbackById.get(i)??null),[x,B]=T(!1),[U,ne]=T("Save name"),[ae,te]=T(!1),[qe,fe]=T(!1),[$e,Ne]=T("Remove device");q(()=>{p&&u.total>0&&jW(i)},[u.total,i,p]),q(()=>{W(o),C(_.syncPeerFeedbackById.get(i)??null),B(!1),ne("Save name"),te(!1),fe(!1),Ne("Remove device")},[o,e.actor_id,i]),q(()=>{!O||!H.current||queueMicrotask(()=>H.current?.scrollIntoView({block:"center",behavior:window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth"}))},[O]);async function se(){if(!i)return;const le=V.trim();if(!le){const Ct={message:"Enter a friendly name for this device.",tone:"warning"};C(Ct),_.syncPeerFeedbackById.set(i,Ct),document.querySelector(`[data-device-name-input="${CSS.escape(i)}"]`)?.focus();return}B(!0),ne("Saving…");try{const Ct=await n(i,le);C(Ct),_.syncPeerFeedbackById.set(i,Ct),ne("Save name")}catch{ne("Retry")}finally{B(!1)}}async function we(){if(f){const le=th();if(!await wn({title:`Sync ${o} before advanced rule review?`,description:le?"This manual sync will use the current legacy Space access and advanced filters until you review them in Coordinator Administration.":"This manual sync will use the current legacy Space access and advanced filters until a coordinator operator reviews them in Coordinator Administration.",confirmLabel:"Sync anyway",cancelLabel:le?"Review legacy Team/Space setup first":"Cancel"}))return}te(!0);try{const le=await r(e,S);C(le),le&&_.syncPeerFeedbackById.set(i,le)}finally{te(!1)}}async function X(){if(!i||!await wn({title:`Remove device ${s}?`,description:"This removes the local record for this paired device on this machine.",confirmLabel:"Remove device",cancelLabel:"Keep device",tone:"danger"}))return;fe(!0),Ne("Removing…");let le=!1;try{await t(i,s),le=!0}catch{Ne("Retry remove")}finally{fe(!1),le&&Ne("Remove device")}}const ie=g3()===i&&i!=="",je=`device-drawer-${i||"unknown"}`,ue=v3(e),ut=F?`Sync: ${lr(F)}`:"Sync: never",ye=th(),Dt=`${ie?"Collapse":"Expand"} device ${o}`;return a(Sa,{asChild:!0,open:ie,onOpenChange:le=>{le?JR(i):rd===i&&JR(null)},children:a("div",{ref:H,className:"peer-card","data-peer-device-id":i||void 0,children:[a(Op,{asChild:!0,children:a("button",{"aria-label":Dt,className:"device-row-head device-row-head--trigger",type:"button",children:[a(rn,{state:ue}),a("span",{className:"device-row-name",title:i||void 0,children:o}),l?a("span",{"aria-label":l.label,className:"peer-direction",role:"img",title:l.label,children:l.glyph}):null,a("span",{className:"device-row-chips",children:[a("span",{className:`badge ${c.isWarning?"badge-offline":"badge-online"}`,children:c.badgeLabel}),f?a("span",{className:"badge actor-badge",children:"Review advanced rules"}):null,a("span",{className:`badge ${u.isWarning?"badge-offline":"actor-badge"}`,title:"Spaces are the hard access boundary; advanced filters only narrow inside them.",children:u.badgeLabel}),v.badgeLabel?a("span",{className:"badge badge-offline",title:"Inbound ops rejected by the sharing-domain scope gate. Expand for reason codes.",children:v.badgeLabel}):null,m.badgeLabel?a("span",{className:"badge badge-offline",title:"Review whether explicit Space access matches this device's intended role.",children:m.badgeLabel}):null,e.discovered_via_group_id?a("span",{className:"badge actor-badge",title:`Discovered through coordinator group ${e.discovered_via_group_id}`,children:`via ${e.discovered_via_group_id}`}):null]}),a("span",{className:"device-row-meta",children:ut}),a("span",{"aria-hidden":"true",className:"device-row-chevron",children:a(h3,{})})]})}),a(Ca,{"aria-label":`Device actions for ${o}`,className:"device-row-drawer",id:je,children:[a("div",{className:"peer-actions",children:[a("button",{type:"button",className:"settings-button",disabled:ae,onClick:()=>{we()},title:S?void 0:"Address details are hidden; sync will target this device by ID.",children:ae?"Syncing…":"Sync now"}),a("div",{className:"sync-labeled-field",children:[a("label",{className:"sync-labeled-field-caption",htmlFor:`device-name-${i||"unknown"}`,children:"Device name"}),a(_e,{"aria-label":`Friendly name for ${o}`,className:"peer-scope-input","data-device-name-input":i||void 0,disabled:x,id:`device-name-${i||"unknown"}`,placeholder:"Friendly device name",type:"text",value:V,onInput:le=>W(le.currentTarget.value)})]}),a("button",{type:"button",className:"settings-button",disabled:x,onClick:()=>{se()},children:U}),a("button",{type:"button",className:"settings-button danger",disabled:qe,onClick:()=>{X()},children:$e})]}),a("div",{className:"peer-scope",children:[O?a("div",{className:"peer-meta",children:ye?"Review this device's legacy Space access and advanced rules in Coordinator Administration if the defaults are too broad.":"A coordinator operator can review this device's legacy Space access and advanced rules in Coordinator Administration if the defaults are too broad."}):f?a("div",{className:"peer-meta",children:"Advanced rule review is still pending for this device."}):null,a("div",{className:"peer-scope-summary",children:"Device details"}),a("div",{className:"peer-addresses",children:N}),M?a("div",{className:"peer-meta",children:M}):null,a("div",{className:"peer-meta",children:[F?`Sync: ${lr(F)}`:"Sync: never",A?`Ping: ${lr(A)}`:"Ping: never"].join(" · ")}),a("div",{className:"peer-scope-summary",children:"Space access"}),a("div",{className:"peer-meta",children:u.total>0?"These Spaces are the hard access boundary for this device.":u.emptyMessage}),u.domains.length>0?a("ul",{className:"peer-scope-chips","aria-label":"Authorized Spaces",children:u.domains.map(le=>a("li",{className:"peer-scope-chip",title:le.detail,children:le.label},le.scopeId))}):null,m.isVisible?a("div",{className:"settings-note",role:"status",children:[a("strong",{children:m.title}),a("div",{children:m.message}),a("div",{children:m.detail})]}):null,a("div",{className:"peer-meta",children:y.note}),a("div",{className:"peer-scope-summary",children:"Space sync progress"}),a("div",{className:"peer-meta",children:b.total>0?"Per-Space progress for this device. Open details to see technical identifiers.":b.emptyMessage}),b.rows.length>0?a("ul",{className:"peer-scope-rejections-list","aria-label":"Per-Space sync progress",children:b.rows.map(le=>a("li",{title:le.detail,children:[a("span",{className:"peer-scope-rejection-label",children:le.label}),a("span",{className:`badge ${le.status==="received"?"badge-online":"actor-badge"}`,children:le.badgeLabel})]},le.scopeId))}):null,v.total>0?a("div",{className:"peer-scope-rejections","data-peer-rejection-count":v.total,children:[a("div",{className:"peer-scope-summary",children:"Sharing-rule rejections (24h)"}),a("div",{className:"peer-meta",children:"Inbound ops the local fail-closed gate refused. Diagnostics never expose op payloads."}),a("ul",{className:"peer-scope-rejections-list",children:v.reasons.map(le=>a("li",{children:[a("span",{className:"peer-scope-rejection-label",children:le.label}),a("span",{className:"peer-scope-rejection-count",children:le.count.toLocaleString()})]},le.reason))}),v.lastAt?a("div",{className:"peer-meta",children:["Last rejected ",lr(v.lastAt)]}):null]}):null,a("div",{className:"peer-scope-summary",children:"Authoritative Identity ownership"}),a("div",{className:"peer-meta",children:E.summary}),a("div",{className:"peer-meta",children:E.detail}),e.claimed_local_actor?a("div",{className:"peer-meta",children:w3(e.claimed_local_actor_scope)}):null,a("div",{className:"peer-actor-row",children:a("button",{type:"button",className:"settings-button",onClick:()=>_3(j?.deviceId??i),children:E.actionLabel})}),a("div",{className:"peer-scope-summary",children:"Advanced sharing rules"}),a("div",{className:"peer-meta",children:[y.statusLabel,". ",y.summary," ",y.note]}),ye?a("div",{className:"peer-actions",children:a("button",{type:"button",className:"settings-button",onClick:S3,children:"Open Coordinator Administration"})}):a("div",{className:"peer-meta",children:"Legacy Space access is managed in Coordinator Administration by a coordinator operator."}),a(xr,{feedback:$})]})]})]})})}function R3(e){const t=_.syncPeersSectionFeedback,n=_.lastSyncStatus,r=n?.daemon_state==="disabled"||n?.enabled===!1;return e.peers.length?a(G,{children:[a(xr,{feedback:t}),e.peers.map(i=>{const o=String(i.peer_device_id||i.name||"unknown-peer");return a(C3,{peer:i,...e},o)})]}):a(G,{children:[a(xr,{feedback:t}),a(zR,{detail:r?"Turn on sync in Settings → Device Sync first. Then use Invite a teammate or Paste an invite above to connect another device.":"Use Invite a teammate above to share a join code, or Paste an invite to enroll this device on an existing team.",title:"No teammates yet"})]})}function I3(e,t){dt(e,a(R3,{...t}))}var Dr=async()=>{},id="";function nh(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput");t&&(t.disabled=e),n&&(n.disabled=e)}function k3(e){Dr=e}function N3(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");if(!e)return;Er("syncActorsSkeleton"),nh(!1);const n=ER({actors:_.lastSyncActors,peers:_.lastSyncPeers,duplicatePeople:_.lastSyncViewModel?.duplicatePeople}),r=n.visibleActors;t&&(t.textContent=r.length?"Manage Identity names here. Confirm authoritative device ownership in Devices.":"No named people yet. Create an Identity here, then confirm device ownership in Devices.",n.hiddenLocalDuplicateCount>0&&(t.textContent+=` ${n.hiddenLocalDuplicateCount} unresolved duplicate ${n.hiddenLocalDuplicateCount===1?"entry is":"entries are"} hidden here until reviewed in Needs attention.`)),l3(e,{actors:r,hiddenLocalDuplicateCount:n.hiddenLocalDuplicateCount,onRename:async(i,o)=>{await TN(i,o),await Dr()},onMerge:async(i,o)=>{try{await uv(i,o),Y("People combined. Assigned devices moved to the selected person."),await Dr()}catch(s){throw Y(ct(s,"Failed to combine people."),"warning"),s}},onDeactivate:async i=>{try{await AN(i),Y("Person removed. Assigned devices have been unassigned."),await Dr()}catch(o){throw Y(ct(o,"Failed to remove person."),"warning"),o}}})}function P3(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta");nh(!0),t&&(t.textContent="People controls are temporarily unavailable. Refresh this page to retry. Device status and sync health are still available below while this recovers."),e&&Si(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. When the people endpoint responds again, named people will reload here."})}function T3(){const e=document.getElementById("syncProjectShareOperations");if(!e)return;o3(e,{operations:_.lastShareOperations,onAdvance:n=>bN(n),onLoadOperation:n=>yN(n),onReload:Dr});const t=document.getElementById("syncProjectShareOperationsMeta");t&&(t.textContent=_.shareOperationsLoadError?"Project sharing status could not be refreshed. Existing device diagnostics remain available below.":_.lastShareOperations.length>0?"Project access is grouped by Person. Devices appear after invitation acceptance.":"Share a project from Projects to invite a teammate.")}function rh(){const e=document.getElementById("syncPeers");if(!e)return;Er("syncPeersSkeleton");const t=_.lastSyncPeers,n=Array.isArray(t)?t:[];BW(_.syncPeersSectionFeedback,n)&&(_.syncPeersSectionFeedback=null),I3(e,{peers:n,onRename:async(r,i)=>{try{return await Yh(r,i),await Dr(),{message:"Device name saved.",tone:"success"}}catch(o){return{message:ct(o,"Failed to save device name."),tone:"warning"}}},onSync:async(r,i)=>{try{const o=String(r?.peer_device_id||""),s=await Gd({address:i,peerDeviceId:o||void 0}),c=Bm(s);let l;c.ok?o&&Vm(o)?l={message:`Triggered sync for ${r?.name||(o?o.slice(0,8):"unknown")}. ${th()?"Review legacy Space access and advanced rules in Coordinator Administration if this device needs tighter sharing.":"A coordinator operator can review legacy Space access and advanced rules in Coordinator Administration if this device needs tighter sharing."}`,tone:"warning"}:l={message:c.message,tone:"success"}:l={message:c.message,tone:"warning"};try{await Dr()}catch{l={message:"Sync started, but this view has not refreshed yet. Refresh the page or use Sync now again before retrying.",tone:"warning"}}return l}catch(o){return{message:ct(o,"Failed to trigger sync."),tone:"warning"}}},onRemove:async(r,i)=>{try{await Jh(r);const o={message:`Removed peer ${i}.`,tone:"success"};return _.syncPeerFeedbackById.delete(r),_.syncPeersSectionFeedback={...o,relatedPeerDeviceId:r},await Dr(),o}catch(o){return{message:ct(o,"Failed to remove peer. The local peer entry is still here."),tone:"warning"}}}})}function A3(){const e=document.getElementById("syncActorsList"),t=document.getElementById("syncActorsMeta"),n=document.getElementById("syncPeers");nh(!0),t&&(t.textContent="People and device details are unavailable right now. Refresh this page to retry once local sync status is reachable again."),e&&Si(e,{title:"People unavailable right now.",detail:"Refresh this page to retry. Named people will reload here once the local sync status endpoint responds again."}),n&&Si(n,{title:"Devices unavailable right now.",detail:"Refresh this page to retry. When sync is reachable again, paired devices will reload here so you can rename, inspect, or re-pair them."})}function QR(){const e=document.getElementById("syncLegacyClaims"),t=document.getElementById("syncLegacyDeviceSelectMount"),n=document.getElementById("syncLegacyClaimsMeta");if(!e||!t||!n)return;const r=Array.isArray(_.lastSyncLegacyDevices)?_.lastSyncLegacyDevices:[];m3({devices:r,meta:n,mount:t,onValueChange:i=>{i!==id&&(id=i,QR())},panel:e,value:id})}function E3(e){const t=document.getElementById("syncActorCreateButton"),n=document.getElementById("syncActorCreateInput"),r=document.getElementById("syncLegacyClaimButton");n?.addEventListener("keydown",i=>{Ta(i,{onSubmit:()=>t?.click(),disabled:!t||t.disabled})}),t?.addEventListener("click",async()=>{if(!t||!n)return;const i=String(n.value||"").trim();if(!i){Jr(n,"Enter a name for the person.");return}ga(n),t.disabled=!0,n.disabled=!0,t.textContent="Creating…";try{await PN(i),Y("Person created."),n.value="",await e()}catch(o){Y(ct(o,"Failed to create person."),"warning"),t.textContent="Retry",t.disabled=!1,n.disabled=!1;return}t.textContent="Create person",t.disabled=!1,n.disabled=!1}),r?.addEventListener("click",async()=>{const i=String(id||"").trim();if(!i||!r||!await wn({title:`Attach history from ${i}?`,description:"This updates legacy provenance so the older device history is attached to you on this device.",confirmLabel:"Attach history",cancelLabel:"Cancel",tone:"danger"}))return;r.disabled=!0;const o=r.textContent||"Attach device history";r.textContent="Attaching…";try{await EN(i),Y("Old device history attached to you."),await e()}catch(s){Y(ct(s,"Failed to attach old device history."),"warning"),r.textContent="Retry",r.disabled=!1;return}r.textContent=o,r.disabled=!1})}function x3(){return window.location.hash.replace(/^#/,"")==="sync/diagnostics"?"diagnostics":"main"}function ih(e=x3()){const t=document.getElementById("syncMainView"),n=document.getElementById("syncDiagnosticsView");!t||!n||(e==="diagnostics"?(t.hidden=!0,n.hidden=!1):(t.hidden=!1,n.hidden=!0))}var XR=!1;function D3(){XR||(XR=!0,window.addEventListener("hashchange",()=>{ih()}))}var In={invitePolicy:"auto_admit",loadSyncData:async()=>{}};function j3(e){In.loadSyncData=e}var L3=[{value:"auto_admit",label:"Auto-admit"},{value:"approval_required",label:"Approval required"}];function O3(){const e=document.getElementById("syncCreateInviteButton"),t=document.getElementById("syncInviteAdminHint");if(!e||!t)return;const n=_.lastSyncCoordinatorAdminStatus?.readiness;if(n==="ready"){e.disabled=!1,t.hidden=!1,t.textContent="Legacy Team/Space setup is ready. Technical controls are in Coordinator Administration.";return}const r=n==="partial"?"Finish legacy Team/Space setup before creating remote invites. Use Coordinator Administration to check what is missing.":"Configure a coordinator URL, group, and admin secret before creating remote invites. Use Coordinator Administration to finish legacy Team/Space setup.";e.disabled=!0,t.hidden=!1,t.textContent=r}function oh(){const e=document.getElementById("syncAdminDisclosureMount");e&&Ez(e,{open:LR,onOpenChange:t=>{AW(t),oh(),ad(),ah()}})}function ZR(){const e=document.getElementById("syncJoinPanel"),t=document.getElementById("syncJoinSection");!e||!t||e.parentElement!==t&&t.appendChild(e)}function ah(){const e=document.getElementById("syncInviteOutput"),t=document.getElementById("syncInviteWarnings");if(!e)return;const n=String(_.lastTeamInvite?.encoded||"").trim();if(e.value=n,e.hidden=!n,t){const r=Array.isArray(_.lastTeamInvite?.warnings)?_.lastTeamInvite.warnings:[];t.textContent=r.join(" · "),t.hidden=r.length===0}}function od(){const e=document.getElementById("syncJoinFeedback");if(!e)return;const t=_.syncJoinFlowFeedback;e.textContent=t?.message||"",e.hidden=!t?.message,e.setAttribute("role",t?.tone==="warning"?"alert":"status"),e.setAttribute("aria-live",t?.tone==="warning"?"assertive":"polite"),e.className=`peer-meta${t?` ${t.tone==="warning"?"sync-inline-feedback warning":"sync-inline-feedback success"}`:""}`}function ad(){const e=document.getElementById("syncInvitePolicyMount");e&&dt(e,h(Jn,{ariaLabel:"Join policy",contentClassName:"sync-radix-select-content sync-actor-select-content",id:"syncInvitePolicy",itemClassName:"sync-radix-select-item",onValueChange:t=>{const n=t==="approval_required"?"approval_required":"auto_admit";n!==In.invitePolicy&&(In.invitePolicy=n,ad())},options:L3,triggerClassName:"sync-radix-select-trigger sync-actor-select",value:In.invitePolicy,viewportClassName:"sync-radix-select-viewport"}))}function $3(e){const t=(e.projects??[]).map(n=>`${n.display_name} (${n.existing_memory_count} existing ${n.existing_memory_count===1?"memory":"memories"})`).join(", ");return`${e.inviter_name||"A teammate"} invited you${e.team_name?` through ${e.team_name}`:""} to share ${t||"selected projects"}.`}function M3(e){if(!e.length){Y("Invite created. Copy the text above and share it with your teammate.","success");return}const t=e.length===1?"1 warning":`${e.length} warnings`;Y(`Invite created. Copy it above and review ${t}.`,"warning")}function F3(e){const t=e;if(!(t.restart_required===!0||t.setup_state==="pending_inviter"||e.status==="pending_setup"))return{message:"Project invitation accepted.",tone:"success"};const n=typeof t.detail=="string"?t.detail.trim():"";let r="Project invitation accepted. Setup is still pending.";return t.restart_required===!0?r="Project invitation accepted. Restart codemem to finish setup.":t.setup_state==="pending_inviter"&&(r="Project invitation accepted. Waiting for the inviter to finish setup."),{message:n||r,tone:"warning"}}function B3(e){const t=e;if(t.type==="project_share")return F3(e);if(t.type==="pair"){const n=String(t.peer_device_id??"").trim();return{message:n?`Paired with device ${n.slice(0,8)}. It will appear in People & devices.`:"Paired the device. It will appear in People & devices.",tone:"success"}}return{message:e.status==="pending"?"Join request sent. Waiting for admin approval.":"Joined the team.",tone:"success"}}function q3(e,t){oh(),ad();const n=document.getElementById("syncNowButton"),r=document.getElementById("syncShareProjectsButton"),i=document.getElementById("syncCreateInviteButton"),o=document.getElementById("syncInviteGroup"),s=document.getElementById("syncInviteTtl"),c=document.getElementById("syncInviteOutput"),l=document.getElementById("syncJoinButton"),d=document.getElementById("syncJoinInvite"),u=document.getElementById("syncProjectInviteReview"),p=document.getElementById("syncProjectInviteContext"),f=document.getElementById("syncProjectInviteReviewHeading"),m=document.getElementById("syncRecipientName"),v=document.getElementById("syncRecipientDeviceName");let b="",g,y=0;const S=document.getElementById("syncPairingReview"),w=["syncPairingDeviceId","syncPairingFingerprint","syncPairingAddresses"].map(E=>document.getElementById(E)),R=()=>{S&&(S.hidden=!0);for(const E of w)E&&(E.textContent="")},k=E=>{if(!S||w.some(A=>!A))throw new Error("Pairing review unavailable. Refresh and try again.");const F=[E.device_id,E.fingerprint,E.addresses.join(`
118
- `)];w.forEach((A,M)=>{A&&(A.textContent=F[M]??"")}),S.hidden=!1,document.getElementById("syncPairingReviewHeading")?.focus()},N=(E,F)=>F===y&&d?.value.trim()===E;r?.addEventListener("click",()=>{ic()||Y("Project sharing is unavailable. Refresh Projects and try again.","warning")});const j=async(E,F)=>{const A=await Wh(E);return N(E,F)?(g=A.kind,A.kind==="pair"?(k(A),"other"):A.kind!=="project_share_invite"||!u||!m||!v?"other":(p&&(p.textContent=$3(A)),m.value=Hi(A.recipient_name),v.value=Hi(A.device_name),u.hidden=!1,b=E,l&&(l.textContent="Accept and start syncing"),f?.focus(),"project")):"stale"};d?.addEventListener("input",()=>{y+=1,d.value.trim()!==b&&(b="",g=void 0,u&&(u.hidden=!0),R(),l&&(l.textContent="Review invite"))}),i?.addEventListener("click",async()=>{if(!i||!o||!s||!c||i.disabled)return;const E=o.value.trim(),F=Number(s.value);let A=!0;if(E?ga(o):A=Jr(o,"Team name is required."),!F||F<1?A=Jr(s,"Must be at least 1 hour."):ga(s),!!A){i.disabled=!0,i.textContent="Creating…";try{const M=await Gh({group_id:E,policy:In.invitePolicy,ttl_hours:F||24});_.lastTeamInvite=M,ah(),c.value=String(M.encoded||""),c.hidden=!1,c.focus(),c.select(),M3(Array.isArray(M.warnings)?M.warnings:[])}catch(M){Y(ct(M,"Failed to create invite. Check the team name, invite lifetime, and coordinator reachability, then try again."),"warning"),i.textContent="Retry",i.disabled=!1;return}finally{i.disabled&&(i.disabled=!1,i.textContent="Create invite")}}}),d?.addEventListener("keydown",E=>{Ta(E,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d||l.disabled)return;const E=d.value.trim();if(!E){Jr(d,"Paste a team invite or pairing payload.");return}if(ga(d),b!==E){const A=y;l.disabled=!0;try{const M=await j(E,A);if(M==="project"||M==="stale")return}catch(M){if(!N(E,A))return;Jr(d,ct(M,"Could not review this invite or pairing payload. Check the pasted text and try again."));return}finally{l.disabled=!1}if(!N(E,A))return;b=E,l.textContent="Accept invite";return}const F=u&&!u.hidden?{recipient_name:m?.value.trim()??"",device_name:v?.value.trim()??""}:void 0;if(F){const A=M=>Hi(M)==="";if(A(F.recipient_name)){m&&Jr(m,"Enter a human-readable name using 120 characters or fewer.");return}if(A(F.device_name)){v&&Jr(v,"Enter a human-readable device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const A=await $d(E,F,g);_.lastTeamJoin=A;let M=B3(A);_.syncJoinFlowFeedback=M,od(),d.value="",y+=1,b="",g=void 0,R(),u&&(u.hidden=!0);try{await t()}catch(O){M={message:ct(O,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},_.syncJoinFlowFeedback=M,od()}}catch(A){_.syncJoinFlowFeedback={message:ct(A,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},od(),l.textContent="Retry",l.disabled=!1;return}finally{l.disabled&&(l.disabled=!1,l.textContent="Review invite")}}),n?.addEventListener("click",async()=>{if(n){n.disabled=!0,n.textContent="Syncing…";try{const E=await Gd(),F=Bm(E);Y(F.message,F.warning?"warning":void 0)}catch(E){Y(ct(E,"Failed to start sync. Retry once, then run codemem sync doctor if the problem keeps coming back."),"warning"),n.textContent="Retry",n.disabled=!1;return}n.disabled=!1,n.textContent="Sync now",e()}})}function U3({status:e}){return e.state==="disabled"?a("div",{className:"advanced-sync-status-label",children:[a(rn,{"aria-label":"Sync off",state:"unknown"}),a("strong",{className:"xl",children:"Sync is off"}),a(Ue,{tone:"badge-offline",variant:"badge",children:"Off"})]}):e.state==="healthy"?a("div",{className:"advanced-sync-status-label",children:[a(rn,{"aria-label":"Sync on",state:"online"}),a("strong",{className:"xl",children:"Sync is on"}),a(Ue,{tone:"badge-online",variant:"badge",children:"On"})]}):a("div",{className:"advanced-sync-status-label",children:[a(rn,{"aria-label":"Sync needs attention",state:"degraded"}),a("strong",{className:"xl",children:"Sync needs attention"}),a(Ue,{tone:"badge-offline",variant:"badge",children:"Attention"})]})}function sh({element:e,hidden:t=!1,restoreParent:n=null}){const r=D(null);return at(()=>{e&&(e.hidden=t)},[e,t]),at(()=>{const i=r.current;if(!(!i||!e))return e.parentElement!==i&&i.appendChild(e),()=>{!n||e.parentElement!==i||n.appendChild(e)}},[e,n]),a("div",{ref:r})}function G3({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:r}){return a(G,{children:[a("div",{className:"sync-action",children:a("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide team setup":"Set up a new team instead"})}),e?a(sh,{element:e,hidden:!t,restoreParent:n}):null]})}function H3({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,joinPanel:r,joinRestoreParent:i,onToggleInvitePanel:o,presenceStatus:s}){const c=s==="not_enrolled";return a(G,{children:[c?a(G,{children:[a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"Join this device"})}),r?a(sh,{element:r,hidden:!1,restoreParent:i}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}):a(G,{children:[r?a(sh,{element:r,hidden:!1,restoreParent:i}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),c?null:a(G3,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:o})]})}function sd({count:e,label:t}){return a("div",{className:"sync-section-heading",children:[a("div",{className:"sync-action-text sync-section-label",children:t}),e?a("span",{className:"badge actor-badge sync-section-count",children:e}):null]})}function V3({item:e,onAction:t}){const[n,r]=T(!1);return a("div",{className:"sync-action",children:[a("div",{className:"sync-action-text",children:[e.title,a("span",{className:"sync-action-command",children:e.summary})]}),a("button",{type:"button",className:"settings-button",disabled:n,onClick:async()=>{r(!0);try{await t(e)}finally{r(!1)}},children:e.actionLabel||"Review"})]})}function K3({request:e,onApprove:t,onDeny:n}){const[r,i]=T(null),[o,s]=T(null),[c,l]=T("Approve"),[d,u]=T("Deny");return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:a("div",{className:"actor-title",title:e.requestId||void 0,children:e.displayName})}),a("div",{className:"actor-actions",children:[a("button",{type:"button",className:"settings-button","aria-label":`${c} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("approve"),l("Approving…");try{s(await t(e)||null),l("Approve")}catch{l("Retry")}finally{i(null)}},children:c}),a("button",{type:"button",className:"settings-button","aria-label":`${d} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("deny"),u("Denying…");try{s(await n(e)||null),u("Deny")}catch{u("Retry")}finally{i(null)}},children:d})]}),a(xr,{feedback:o})]})}function z3({onReview:e,row:t}){const[n,r]=T(!1),[i,o]=T(null),s=t.actionLabel||"Pair with this device",[c,l]=T(s);return a(G,{children:[a("button",{"aria-label":`${c} for ${t.displayName}`,className:"settings-button",disabled:n,onClick:async()=>{r(!0),l("Pairing…"),o({message:`Pairing ${t.displayName}. Keep this page open while the device is approved and refreshed.`,tone:"success"});try{const d=await e(t)||null;o(d),l(d?.tone==="warning"?"Retry":t.actionLabel||s)}catch{o({message:`Pairing ${t.displayName} failed. Try again.`,tone:"warning"}),l("Retry")}finally{r(!1)}},type:"button",children:c}),a(xr,{feedback:i})]})}function W3({onInspect:e,onRemove:t,row:n}){const[r,i]=T(!1),[o,s]=T(null),[c,l]=T("Remove broken device record");return a(G,{children:[a("button",{"aria-label":`Open details for ${n.displayName}`,className:"settings-button",disabled:r,onClick:()=>e(n),type:"button",children:"Open device details"}),a("button",{"aria-label":`${c} for ${n.displayName}`,className:"settings-button danger",disabled:r,onClick:async()=>{i(!0),l("Removing…");try{s(await t(n)||null),l("Remove broken device record")}catch{l("Retry")}finally{i(!1)}},type:"button",children:c}),a(xr,{feedback:o})]})}function J3({row:e,onInspectConflict:t,onRemoveConflict:n,onReview:r}){return a("div",{className:"peer-card peer-card--padded","data-discovered-device-id":e.deviceId,children:[a("div",{className:"peer-title",children:[a("strong",{title:e.displayTitle||void 0,children:e.displayName}),a("span",{className:`badge actor-badge${e.availabilityLabel==="Offline"?"":" local"}`,children:e.availabilityLabel}),a("span",{className:"badge actor-badge",children:e.connectionLabel}),e.approvalBadgeLabel?a("span",{className:"badge actor-badge",children:e.approvalBadgeLabel}):null]}),a("div",{className:"peer-meta",children:e.note}),a("div",{className:"peer-actions",children:[e.mode==="accept"?a(z3,{onReview:r,row:e}):null,e.actionMessage?a("div",{className:"peer-meta",children:e.actionMessage}):null,e.mode==="paired"&&e.pairedMessage?a("div",{className:"peer-meta",children:e.pairedMessage}):null,e.mode==="conflict"?a(W3,{onInspect:t,onRemove:n,row:e}):null]})]})}function Y3(e){const t=e.actionItems.length>0,n=e.actionableCount>e.actionItems.length,r=t||n||e.primaryStatus.state!=="healthy";return a(G,{children:[r?a(sd,{label:"Needs attention"}):null,e.primaryStatus.nextAction?a("div",{className:"sync-action","data-primary-sync-state":e.primaryStatus.state,children:a("div",{className:"sync-action-text",children:[e.primaryStatus.badgeLabel,a("span",{className:"sync-action-command",children:e.primaryStatus.nextAction})]})}):null,t?e.actionItems.map(i=>a(V3,{item:i,onAction:e.onAttentionAction},i.id)):null,!t&&!n&&e.primaryStatus.state==="healthy"?a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"No urgent team work right now."})}):null]})}function Q3({children:e}){return e?a(G,{children:[a(sd,{label:"Add devices & teammates"}),e]}):null}function X3({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!_.syncDiscoveredFeedback?null:fn(a(G,{children:[a(sd,{count:t.length||void 0,label:"Devices waiting for review"}),a(xr,{feedback:_.syncDiscoveredFeedback}),t.map(o=>a(J3,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${o.deviceId}:${o.incomingRequestId}:${o.fingerprint}`))]}),e)}function Z3({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!_.syncJoinRequestsFeedback?null:fn(a(G,{children:[a(sd,{count:t.length||void 0,label:"Join requests to review"}),a(xr,{feedback:_.syncJoinRequestsFeedback}),t.map(i=>a(K3,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function eI(e){return a(G,{children:[a(Y3,{...e}),a(Q3,{children:e.children}),a(Z3,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),a(X3,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function tI(e){e&&(e.textContent="")}function cd(e){e instanceof HTMLElement&&(e.classList.remove("sync-attention-target"),e.offsetWidth,e.classList.add("sync-attention-target"),window.setTimeout(()=>e.classList.remove("sync-attention-target"),900))}function eJ(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function ws(){return eJ()?"auto":"smooth"}var ch="syncTeamActionsMount",tJ="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function nJ(e,t,n=!1){return e.length>1&&(!t||n)}function rJ(e,t,n){e.hidden=!1,e.textContent=n.badgeLabel,t.textContent=n.meta,n.state==="healthy"?e.className="sync-online-badge":n.state==="disabled"||n.state==="pending-setup"||n.state==="not-enrolled"||n.state==="reachable"?e.className="sync-online-badge sync-online-offline":e.className="sync-online-badge sync-online-error"}function iJ(e,t){const n=document.createElement("div");n.id=ch,e.appendChild(n),dt(n,h(eI,{actionItems:[],actionableCount:0,discoveredListMount:null,discoveredRows:[],joinRequestsMount:null,onApproveJoinRequest:async()=>null,onAttentionAction:async()=>{},onDenyJoinRequest:async()=>null,onInspectConflict:()=>{},onRemoveConflict:async()=>null,onReviewDiscoveredDevice:async()=>null,pendingJoinRequests:[],presenceStatus:"unknown",primaryStatus:t}))}function nI(e,t){const n=document.getElementById(ch);n&&(xo(n),n.remove()),tI(e),t.forEach(r=>{tI(r)})}function oJ(e){const t=document.getElementById("syncJoinPanel"),n=document.getElementById("syncJoinRequests"),r=document.getElementById("syncCoordinatorDiscovered"),i=document.getElementById("syncCoordinatorDiscoveredList");nI(e.actions,[n,i]),e.setupPanel.hidden=!1,t&&(t.hidden=!1),e.actions.hidden=!1,iJ(e.actions,e.primaryStatus),n&&(n.hidden=!0),r&&(r.hidden=!0)}function ld(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;oh(),ad(),ah(),od(),O3();const r=document.getElementById("syncInvitePanel"),i=document.getElementById("syncAdminSection"),o=document.getElementById("syncJoinPanel"),s=document.getElementById("syncJoinSection"),c=document.getElementById("syncJoinRequests"),l=document.getElementById("syncCoordinatorDiscovered"),d=document.getElementById("syncCoordinatorDiscoveredMeta"),u=document.getElementById("syncCoordinatorDiscoveredList");Er("syncTeamSkeleton"),ZR();const p=_.lastSyncCoordinator,f=sJ();aJ(f.primaryStatus);const m=()=>{const C=document.getElementById("manualDeviceIdentityControls");C instanceof HTMLDetailsElement&&(C.open=!0)},v=C=>{if(m(),C.kind==="possible-duplicate-person"){const ne=document.getElementById("syncActorsList");ne instanceof HTMLElement&&(ne.scrollIntoView({block:"center",behavior:ws()}),cd(ne));return}const x=String(C.deviceId||"").trim();if(!x)return;if(C.kind==="name-device"){const ne=document.querySelector(`[data-device-name-input="${CSS.escape(x)}"]`);if(ne instanceof HTMLInputElement){ne.scrollIntoView({block:"center",behavior:ws()}),ne.focus(),ne.select(),cd(ne);return}}const B=document.querySelector(`[data-peer-device-id="${CSS.escape(x)}"]`);if(B instanceof HTMLElement){B.scrollIntoView({block:"center",behavior:ws()}),cd(B);return}const U=document.querySelector(`[data-discovered-device-id="${CSS.escape(x)}"]`);U instanceof HTMLElement&&(U.scrollIntoView({block:"center",behavior:ws()}),cd(U))},b=async C=>{const x=Array.isArray(C.actorIds)?C.actorIds.map(te=>String(te||"").trim()).filter(Boolean):[],B=(Array.isArray(_.lastSyncActors)?_.lastSyncActors:[]).filter(te=>x.includes(String(te?.actor_id||"").trim()));if(B.length<2){Y("This duplicate review is outdated. Refresh the card and review the remaining people entries.","warning");return}const U=await b$({title:"Review possible duplicate people",summary:C.title.replace(/^Possible duplicate person:\s*/,""),actors:B.map(te=>({actorId:String(te?.actor_id||""),label:String(te?.display_name||te?.actor_id||"Unknown person"),isLocal:!!te?.is_local}))});if(U.action==="different-people"){$W(x,"different-people"),Y("Okay. I will keep these people separate on this device."),await In.loadSyncData();return}if(U.action!=="merge")return;const ne=B.find(te=>String(te?.actor_id||"")===U.primaryActorId),ae=B.find(te=>String(te?.actor_id||"")===U.secondaryActorId);if(!ne?.actor_id||!ae?.actor_id){Y("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await uv(String(ne.actor_id),String(ae.actor_id)),MW(x),Y(`Combined duplicate people into ${String(ne.display_name||ne.actor_id)}.`),await In.loadSyncData()}catch(te){try{await In.loadSyncData()}catch{}Y(ct(te,"Failed to combine these people."),"warning")}},g=async C=>await gf({title:"Pair with this device",description:"Choose a friendly name for this device before pairing it on this machine.",initialValue:C,placeholder:"Desk Mini",confirmLabel:"Pair",cancelLabel:"Cancel",validate:x=>x.trim()?null:"Enter a device name to pair this device."}),y=!!p?.configured,S=CW(p);e.title=y?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?rJ(w,e,f.primaryStatus):e.textContent=f.primaryStatus.meta,!y){oJ({actions:n,setupPanel:t,primaryStatus:f.primaryStatus});return}t.hidden=!0,n.hidden=!1;const R=String(p.presence_status||""),k=Array.isArray(_.lastSyncPeers)?_.lastSyncPeers:[],N=Array.isArray(f.attentionItems)?f.attentionItems:[],j=Array.isArray(p.discovered_devices)?p.discovered_devices:[],E=String(p.coordinator_url||"").trim(),F=j.map(C=>{const x=String(C.device_id||"").trim(),B=String(C.display_name||"").trim(),U=IR({coordinatorName:B,deviceId:x})||"Discovered device",ne=x&&U!==x?x:null,ae=String(C.fingerprint||"").trim(),te=String(C.incoming_reciprocal_request_id||"").trim(),qe=Array.isArray(C.groups)?C.groups.map(tr=>String(tr||"").trim()).filter(Boolean):[],fe=k.find(tr=>String(tr?.peer_device_id||"")===x),$e=nJ(qe,!!fe,C.needs_local_approval===!0),Ne=CR({device:C,pairedLocally:!!fe}),se=String(fe?.fingerprint||"").trim(),we=!!fe&&!!ae&&!!se&&se!==ae,X=_.pendingCoordinatorApprovalsByDeviceId.get(x),ie=C.needs_local_approval===!0&&X?.coordinatorUrl===E&&X?.incomingRequestId===te,je=ie?"approval-pending":C.needs_local_approval===!0?"needs-local-approval":"not-required",ue=!ie&&!S&&Oz({device:C,hasAmbiguousCoordinatorGroup:$e,pairedLocally:!!fe}),ut=Array.isArray(C.addresses)?C.addresses:[],ye=Number(C.address_count??0),Dt=Number.isFinite(ye)&&ye>0?ye:0,ot=lJ({pairedLocally:!!fe,device:C,addressCount:ut.length+Dt}),le=[ut.length?ut.map(tr=>ba()?BR(String(tr||"")):String(tr||"")).filter(Boolean).join(" · "):Dt>0?`${Dt} ${C.stale?"last-known":"fresh"} ${Dt===1?"address":"addresses"} hidden`:"No fresh addresses"];!ut.length&&ne&&le.push(`device id: ${x}`);let Ct=null,Ze=ue?"accept":"none",Is=null;we?Ze="conflict":ie?(Ct="Waiting for refreshed coordinator status. You do not need to approve again.",Ze="approval-pending"):S&&(!fe||Ne.state==="needs-your-approval")?(Ct=S.message,Ze="setup-blocked"):$e?(Ct="This device appears in multiple coordinator groups. Review legacy Team/Space setup before approving it here.",Ze="ambiguous"):ot?(Ct=ot.actionMessage,Ze=ot.mode):fe&&Vm(x)?(Ct="Review this device's legacy Space access and advanced rules in Coordinator Administration before you sync it.",Ze="scope-pending"):fe?.last_error?(le.push(`error: ${String(fe.last_error)}`),ue||(Ze="paired")):fe?.status?.peer_state?(le.push(`status: ${String(fe.status.peer_state)}`),ue||(Ze="paired")):fe&&!ue&&(Ze="paired"),Ze==="paired"&&(Is=dJ(Ne.state,Ne.description,fe?.last_error));const ks=uJ(we,!!fe);return{actionMessage:Ct,actionLabel:Ne.actionLabel||(fe?"Review device":"Pair with this device"),approvalBadgeLabel:ie?"Approval sent":Ne.badgeLabel,approvalState:je,availabilityLabel:C.stale?"Offline":"Available",connectionLabel:ks,coordinatorUrl:E,deviceId:x,displayName:U,displayTitle:ne,fingerprint:ae,groupId:qe[0]??"",incomingRequestId:te,mode:Ze,note:le.join(" · "),pairedMessage:Is}}),A=new Set(F.filter(C=>C.approvalState==="approval-pending").map(C=>C.deviceId)),M=N.filter(C=>!C.deviceId||!A.has(C.deviceId)),O=[],H=F.filter(C=>C.mode!=="paired"&&C.mode!=="none"&&C.mode!=="scope-pending"),V=F.filter(C=>C.mode==="accept"||C.mode==="scope-pending").length,W=M.length+O.length+V;l&&(l.hidden=H.length===0&&!_.syncDiscoveredFeedback),d&&(d.textContent=H.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=O.length===0&&!_.syncJoinRequestsFeedback),nI(n,[c,u]);const $=document.createElement("div");$.id=ch,n.appendChild($),dt($,h(eI,{actionItems:M,actionableCount:W,children:h(H3,{invitePanel:r,invitePanelOpen:Um,inviteRestoreParent:i,joinPanel:o,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(EW(!Um),ld())},presenceStatus:R}),discoveredListMount:u,discoveredRows:H,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async C=>{if(C.kind==="possible-duplicate-person"){await b(C);return}v(C)},onDenyJoinRequest:async()=>null,onInspectConflict:C=>{m();const x=document.querySelector(`[data-peer-device-id="${CSS.escape(C.deviceId)}"]`);if(x instanceof HTMLElement){x.scrollIntoView({block:"center",behavior:ws()}),Y(`Opened the conflicting local device record for ${C.displayName}.`,"warning");return}Y("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async C=>{if(!await wn({title:`Remove ${C.displayName}?`,description:"This deletes the broken local device record. You can review this device again after the screen refreshes.",confirmLabel:"Remove device record",cancelLabel:"Keep device record",tone:"danger"}))return null;try{await Jh(C.deviceId);const x={message:`Removed the broken local device record for ${C.displayName}. If it is still available, review it again from Next steps or Devices seen on team.`,tone:"success"};return _.syncDiscoveredFeedback=x,await In.loadSyncData(),x}catch(x){return{message:ct(x,"Failed to remove the broken local device record. The old local record is still present in People & devices."),tone:"warning"}}},onReviewDiscoveredDevice:async C=>{try{const x=await g(C.displayName);return x?await cJ(C,x):null}catch(x){return{message:ct(x,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:O,presenceStatus:R,primaryStatus:f.primaryStatus}))}function aJ(e){const t=document.getElementById("syncAdvancedStatusMount");t&&dt(t,h(U3,{status:e}));const n=document.getElementById("syncTurnOnButton");n&&(n.hidden=e.state!=="disabled");const r=document.getElementById("syncPrimaryStatusDetail");r&&(r.textContent=e.meta)}function sJ(){return _.lastSyncViewModel||{primaryStatus:xR({status:_.lastSyncStatus,coordinator:_.lastSyncCoordinator,peers:_.lastSyncPeers,shareOperations:_.lastShareOperations,shareOperationsLoadError:_.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]}}async function cJ(e,t){const n=e.approvalState==="needs-local-approval",r=e.deviceId.trim(),i=e.coordinatorUrl.trim(),o=e.groupId.trim(),s=e.incomingRequestId.trim();if(n&&(!r||!i||!o||!s))throw new Error("Device identity is incomplete. Refresh the screen and try approval again.");const c=await qk(e.deviceId,{fingerprint:e.fingerprint,expectedGroupId:o||void 0,expectedIncomingRequestId:n?s:void 0}),l=String(c?.name||e.displayName||"").trim()||e.displayName;n&&_.pendingCoordinatorApprovalsByDeviceId.set(r,{coordinatorUrl:i,incomingRequestId:s});const d=Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(p=>String(p?.peer_device_id||"").trim()!==e.deviceId):[];_.pendingAcceptedSyncPeers=[...d,{peer_device_id:e.deviceId,name:l,fingerprint:e.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],DW(e.deviceId);let u=n?{message:tJ,tone:"success"}:{message:`Step 1 complete on this device for ${e.displayName}. Finish onboarding on the other device so both sides trust each other for sync.`,tone:"success"};_.syncDiscoveredFeedback=u,n&&ld();try{t.trim()!==l.trim()&&(await Yh(e.deviceId,t.trim()),_.pendingAcceptedSyncPeers=_.pendingAcceptedSyncPeers.map(p=>String(p?.peer_device_id||"").trim()===e.deviceId?{...p,name:t.trim()}:p),n||(u={message:`Connected ${t.trim()} and saved its name.`,tone:"success"}))}catch(p){u={message:n?"Approval was sent, but naming did not finish. You do not need to approve again.":ct(p,"Device connected, but naming did not finish."),tone:"warning"}}_.syncDiscoveredFeedback=u;try{await In.loadSyncData()}catch(p){u={message:n?"Approval was sent. Confirmation may take up to 30 seconds, and you do not need to approve again.":ct(p,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},_.syncDiscoveredFeedback=u}return u}function lJ({pairedLocally:e,device:t,addressCount:n}){return e&&t.needs_local_approval!==!0?null:t.stale?{actionMessage:"Wait for a fresh coordinator presence update, then review this device again here.",mode:"stale"}:e||n>0?null:{actionMessage:"Wait for this device to publish a fresh address, then refresh and review it.",mode:"waiting-address"}}function dJ(e,t,n){if(e==="waiting-for-other-device")return t||"Waiting on the other device.";const r=String(n||"").toLowerCase();return r.includes("401")&&r.includes("unauthorized")?"Waiting for the other device to trust this one before sync can work.":null}function uJ(e,t){return e?jR.conflicts:t?jR.pairedLocally:"Not connected on this device"}function pJ(e){switch(e){case"cwd":return"Matched by folder";case"git_remote":return"Matched by git remote";case"workspace_id":return"Matched by workspace";case"project":return"Matched by project name";case"unmapped":return"Missing project identity";default:return`Matched by ${e.replace(/_/g," ")}`}}function Lo(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function rI(e){return Lo(e)?"Unclear project identity":e.displayProject}function Yt(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function fJ(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function mJ(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hJ(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function vJ(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function gJ(e){if(!e)return"date unavailable";const t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("en-US",{day:"numeric",month:"short",timeZone:"UTC",year:"numeric"}).format(t)}function yJ(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function bJ({group:e}){const t=e.memorySamples??[],n=t.length;return a("details",{className:"legacy-review-samples",children:[a("summary",{children:["Inspect affected memories",n?` (${n} sample${n===1?"":"s"})`:""]}),a("div",{className:"legacy-review-cleanup-note",children:"Showing representative memories from this project group before reassignment. Local memories can be reassigned; peer-owned memories stay in review on this device."}),t.length>0?a("ul",{className:"legacy-review-sample-list",children:t.map(r=>a("li",{className:"legacy-review-sample",children:[a("div",{className:"legacy-review-sample-title",children:r.title}),a("div",{className:"legacy-review-group-meta",children:[r.kind||"memory"," · ",gJ(r.updatedAt??r.createdAt)," ","·"," ",r.ownership==="local"?"local, reassignable":"peer-owned, stays in review"]}),r.bodyPreview?a("div",{className:"legacy-review-sample-body",children:r.bodyPreview}):null,a("div",{className:"legacy-review-group-meta mono",children:yJ(r)})]},r.id))}):a("div",{className:"legacy-review-cleanup-note",children:"No samples are available for this group. Refresh Sync and try again before reassigning."})]})}function iI(e,t,n){let r=(e instanceof Error?e.message:"Unable to reassign legacy review memories.").replace(/sharing domain/gi,"Space");return t&&(r=r.replace(new RegExp(`\\b${mJ(t)}\\b`,"g"),hJ(t,n))),r}function _J(e,t){const n=e.suggestedScopeId?t.find(r=>r.scopeId===e.suggestedScopeId)?.label:"";return[e.displayProject,e.identitySource,e.suggestedScopeId??"",n??"",e.suggestionReason??"",e.workspaceIdentity].join(" ").toLowerCase()}function wJ({item:e,onReview:t}){return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:[a("div",{className:"actor-title",children:[a("strong",{children:e.peerName}),a("span",{className:"badge actor-badge",children:["person: ",e.actorDisplayName||e.actorId]})]}),a("div",{className:"peer-meta",children:[e.shareableCount," share by default · ",e.privateCount," marked Only me ·"," ",e.scopeLabel]})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:t,children:"Review my memories in Feed"})})]})}function SJ({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],o=Object.fromEntries(r.map(C=>[C.workspaceIdentity,C.suggestedScopeId??""])),[s,c]=T({}),[l,d]=T({}),[u,p]=T(o),[f,m]=T({}),[v,b]=T("all"),[g,y]=T(""),[S,w]=T(null),R=r.length,k=e.totalGroupCount??R,N=r.filter(Lo).length,j=r.filter(C=>C.suggestedScopeId&&!Lo(C)&&Yt(C)).length,E=r.filter(C=>f[C.workspaceIdentity]&&Yt(C)).length,F=r.filter(C=>f[C.workspaceIdentity]&&Yt(C)&&!!u[C.workspaceIdentity]).length,A=r.filter(C=>{const x=Lo(C);return v==="suggested"&&(!C.suggestedScopeId||x)||v==="cleanup"&&!x||v==="no-suggestion"&&(C.suggestedScopeId||x)||v==="selected"&&!f[C.workspaceIdentity]?!1:!g.trim()||_J(C,i).includes(g.trim().toLowerCase())});async function M(C){const x=u[C.workspaceIdentity]||C.suggestedScopeId||"";if(!(!x||!t||S)){w(C.workspaceIdentity),d(B=>{const U={...B};return delete U[C.workspaceIdentity],U});try{const B=await t(C,x,!!s[C.workspaceIdentity],s[C.workspaceIdentity]?.confirmation_token);c(B?U=>({...U,[C.workspaceIdentity]:B}):U=>{const ne={...U};return delete ne[C.workspaceIdentity],ne})}catch(B){d(U=>({...U,[C.workspaceIdentity]:iI(B,x,i)}))}finally{w(null)}}}function O(C,x){p(B=>({...B,[C.workspaceIdentity]:x})),c(B=>{const U={...B};return delete U[C.workspaceIdentity],U}),d(B=>{const U={...B};return delete U[C.workspaceIdentity],U})}function H(C,x){m(B=>({...B,[C.workspaceIdentity]:x}))}function V(C){m(x=>({...x,...Object.fromEntries(A.filter(Yt).map(B=>[B.workspaceIdentity,C]))}))}function W(){m(C=>({...C,...Object.fromEntries(r.filter(x=>x.suggestedScopeId&&!Lo(x)&&Yt(x)).map(x=>[x.workspaceIdentity,!0]))}))}async function $(){if(!t||S||F===0)return;const C=r.filter(x=>f[x.workspaceIdentity]&&Yt(x)&&!!u[x.workspaceIdentity]);if(!C.every(x=>s[x.workspaceIdentity])){w("bulk");try{for(const x of C){if(s[x.workspaceIdentity])continue;const B=u[x.workspaceIdentity]||x.suggestedScopeId||"";if(B)try{const U=await t(x,B,!1);d(ne=>{const ae={...ne};return delete ae[x.workspaceIdentity],ae}),U&&c(ne=>({...ne,[x.workspaceIdentity]:U}))}catch(U){d(ne=>({...ne,[x.workspaceIdentity]:iI(U,B,i)}))}}}finally{w(null)}}}return a("div",{className:"legacy-review-card",children:[a("div",{className:"legacy-review-header",children:[a("div",{children:[a("div",{className:"actor-title",children:[a("strong",{children:"Legacy shared review"}),a("span",{className:"badge badge-offline",children:"Needs project review"})]}),a("div",{className:"peer-meta legacy-review-summary",children:[k.toLocaleString()," older"," ",k===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",R<k?` Showing ${R.toLocaleString()} projects; open Projects to review the rest.`:""]}),a("div",{className:"peer-meta legacy-review-warning",children:"Fix peer-owned projects on their source device. Reassignment updates future sync authorization; online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies."})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:n,children:"Manage all projects"})})]}),a("div",{className:"legacy-review-toolbar",children:[a("div",{className:"legacy-review-filter-row",children:[["all",`Showing ${R.toLocaleString()}`],["suggested",`Suggested ${j.toLocaleString()}`],["cleanup",`Needs cleanup ${N.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${F.toLocaleString()}`]].map(([C,x])=>a("button",{className:v===C?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>b(C),type:"button",children:x},C))}),a("div",{className:"legacy-review-bulk-row",children:[a("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:C=>y(C.currentTarget.value),placeholder:"Search project, signal, or destination…",value:g}),a("button",{className:"settings-button",onClick:()=>V(!0),type:"button",children:"Select visible"}),a("button",{className:"settings-button",onClick:W,type:"button",children:"Select suggested"}),a("button",{className:"settings-button",onClick:()=>V(!1),type:"button",children:"Clear visible"}),t&&i.length>0?a("button",{className:"settings-save",disabled:S!=null||F===0||r.filter(C=>f[C.workspaceIdentity]&&Yt(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity]),onClick:()=>{$()},type:"button",children:S==="bulk"?"Previewing…":`Preview ${F.toLocaleString()} selected`}):t&&E>0?a("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,F>0&&r.filter(C=>f[C.workspaceIdentity]&&Yt(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity])?a("span",{className:"legacy-review-cleanup-note",children:"Bulk actions only preview. Confirm each project individually to avoid partial reassignment."}):null]})]}),r.length>0?a("ul",{className:"legacy-review-groups","aria-label":"Legacy shared review project groups",children:A.map(C=>a("li",{className:"legacy-review-group",children:[a("div",{className:"legacy-review-group-main",children:[a("div",{className:"legacy-review-title-wrap",children:[a("input",{"aria-label":`Select ${rI(C)}`,checked:!!f[C.workspaceIdentity],className:"cm-checkbox",disabled:!Yt(C),onChange:x=>H(C,x.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:rI(C)}),a("div",{className:"legacy-review-group-meta",children:[pJ(C.identitySource),fJ(C,i)]}),Yt(C)?C.peerOwnedMemoryCount?a("div",{className:"legacy-review-cleanup-note",children:[(C.reassignableMemoryCount??C.memoryCount).toLocaleString()," ","local memor",(C.reassignableMemoryCount??C.memoryCount)===1?"y":"ies"," ","can be reassigned; ",C.peerOwnedMemoryCount.toLocaleString()," peer-owned memor",C.peerOwnedMemoryCount===1?"y":"ies"," will stay in review."]}):null:a("div",{className:"legacy-review-cleanup-note",children:"Peer-owned only. These older memories were received from another device, so this device cannot reassign them to a Space. Assign this project to a Space on the source device; after sync, this review should clear here."}),Lo(C)?a("div",{className:"legacy-review-cleanup-note",children:"Inspect or correct the project identity before assigning old shared data to a Space."}):null]})]}),a("span",{className:"legacy-review-count",children:[C.memoryCount.toLocaleString()," memor",C.memoryCount===1?"y":"ies"]})]}),C.suggestionReason?a("div",{className:"legacy-review-reason",children:C.suggestionReason}):null,l[C.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:l[C.workspaceIdentity]}):null,s[C.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:[s[C.workspaceIdentity].warning," This will reassign"," ",s[C.workspaceIdentity].reassignable_memory_count.toLocaleString()," of"," ",s[C.workspaceIdentity].memory_count.toLocaleString()," memories",s[C.workspaceIdentity].skipped_memory_count?`; ${s[C.workspaceIdentity].skipped_memory_count.toLocaleString()} peer-owned copies will be left unchanged`:"","."]}):null,a(bJ,{group:C}),i.length>0&&t&&Yt(C)?a("label",{className:"legacy-review-target",children:[a("span",{children:"Destination Space"}),a("select",{className:"peer-scope-input",disabled:S!=null,onChange:x=>O(C,x.currentTarget.value),value:u[C.workspaceIdentity]||"",children:[a("option",{value:"",children:"Choose Space…"}),i.map(x=>a("option",{value:x.scopeId,children:[x.label," · ",vJ(x.authorityType),x.scopeId===C.suggestedScopeId?" · suggested":""]},x.scopeId))]})]}):null,i.length>0&&t&&Yt(C)?a("div",{className:"legacy-review-actions",children:a("button",{type:"button",className:"settings-button",disabled:S!=null||!u[C.workspaceIdentity],onClick:()=>{M(C)},children:S===C.workspaceIdentity?s[C.workspaceIdentity]?"Reassigning…":"Previewing…":s[C.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},C.workspaceIdentity))}):null]})}function CJ({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(G,{children:[t?a(SJ,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(wJ,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function RJ(){hp("mine"),_.feedQuery="",window.location.hash="feed"}function IJ(){window.location.hash="projects"}async function kJ(e,t,n,r){try{const i=await IN({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return _.lastSyncLegacySharedReview=i.legacy_shared_review??null,Y(`Reassigned ${i.reassigned_memory_count.toLocaleString()} legacy review memor${i.reassigned_memory_count===1?"y":"ies"} to ${i.target_scope_label}.`),oI(),null}catch(i){if(i instanceof Xh)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw Y(o,"warning"),new Error(o)}}function oI(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewMeta"),n=document.getElementById("syncSharingReviewList");if(!e||!t||!n)return;const r=e.querySelector(".settings-group-title"),i=Array.isArray(_.lastSyncSharingReview)?_.lastSyncSharingReview:[],o=_.lastSyncLegacySharedReview,s=Math.max(0,Number(o?.memory_count??0)),c=o?.has_data?{groups:Array.isArray(o.groups)?o.groups.map(u=>{const p=u;return{displayProject:String(p.display_project||p.project||"Unknown project"),identitySource:String(p.identity_source||"unknown"),lastUpdatedAt:typeof p.last_updated_at=="string"?p.last_updated_at:null,memoryCount:Number(p.memory_count||0),memorySamples:Array.isArray(p.memory_samples)?p.memory_samples.map(f=>{const m=f,v=m.ownership==="peer"?"peer":"local";return{bodyPreview:typeof m.body_preview=="string"?m.body_preview:null,createdAt:typeof m.created_at=="string"?m.created_at:null,cwd:typeof m.cwd=="string"?m.cwd:null,gitRemote:typeof m.git_remote=="string"?m.git_remote:null,id:Number(m.id||0),kind:typeof m.kind=="string"?m.kind:null,ownership:v,project:typeof m.project=="string"?m.project:null,title:String(m.title||`Memory ${Number(m.id||0)}`),updatedAt:typeof m.updated_at=="string"?m.updated_at:null}}):[],peerOwnedMemoryCount:Number(p.peer_owned_memory_count||0),reassignableMemoryCount:Number(p.reassignable_memory_count||0),suggestedScopeId:typeof p.suggested_scope_id=="string"?p.suggested_scope_id:null,suggestionReason:typeof p.suggestion_reason=="string"?p.suggestion_reason:null,workspaceIdentity:String(p.workspace_identity||p.display_project||"unknown")}}):[],memoryCount:s,scopeId:String(o.scope_id||"legacy-shared-review"),totalGroupCount:Number(o.total_group_count||o.groups?.length||0),targetScopes:Array.isArray(o.target_scopes)?o.target_scopes.map(u=>{const p=u;return{authorityType:String(p.authority_type||"unknown"),label:String(p.label||p.scope_id||"Unknown domain"),scopeId:String(p.scope_id||"")}}).filter(u=>u.scopeId):[]}:null;if(!i.length&&!c){xo(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=_.currentProject?`current project (${_.currentProject})`:"all allowed projects";t.textContent=c?`Review conservative upgrade state before promoting historical shared data. Teammates receive memories from ${l} by default once Sharing-domain grants allow it.`:`Teammates receive memories from ${l} by default. Use Only me on a memory when it should stay local.`;const d=i.map(u=>({actorDisplayName:String(u.actor_display_name||u.actor_id||"unknown"),actorId:String(u.actor_id||"unknown"),peerName:String(u.peer_name||u.peer_device_id||"Device"),privateCount:Number(u.private_count||0),scopeLabel:String(u.scope_label||"All allowed projects"),shareableCount:Number(u.shareable_count||0)}));dt(n,h(CJ,{items:d,legacyReview:c,onLegacyReassign:kJ,onLegacyReview:IJ,onReview:RJ}))}var dd="";function NJ(e){if(!e)return;const t=String(e?.coordinator_url||"").trim(),n=!!(e.lookup_error||e.reciprocal_approval_error),r=Array.isArray(e?.discovered_devices)?e.discovered_devices:[],i=new Map;for(const o of r){const s=String(o.device_id||"").trim();s&&i.set(s,[...i.get(s)||[],o])}for(const[o,s]of _.pendingCoordinatorApprovalsByDeviceId){if(s.coordinatorUrl!==t){_.pendingCoordinatorApprovalsByDeviceId.delete(o);continue}if(n)continue;const c=i.get(o);c&&(c.some(l=>String(l.incoming_reciprocal_request_id||"").trim()===s.incomingRequestId&&l.needs_local_approval===!0)||_.pendingCoordinatorApprovalsByDeviceId.delete(o))}}function PJ(){return[..._.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var Ss=null,lh=0,dh=null,uh=0,ph=null,TJ=15e3;function aI(e){return`project:${e||""}|includeJoinRequests:false`}function AJ(e){const t=aI(e);return!Ss||Ss.key!==t||Date.now()>=Ss.expiresAtMs?null:Ss.payload}function EJ(e,t){Ss={key:aI(e),expiresAtMs:Date.now()+TJ,payload:t}}function xJ(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function DJ(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewList"),n=document.getElementById("syncSharingReviewMeta"),r=document.getElementById("syncLegacyClaims"),i=document.getElementById("syncLegacyClaimsMeta");e&&(e.hidden=!0),t&&(t.textContent=""),n&&(n.textContent=""),r&&(r.hidden=!0),i&&(i.textContent="")}async function jJ(e,t){if(_.activeTab==="health"&&!t.requireFreshSyncStatus){const r=AJ(e);if(r)return{payload:r,fetchedFreshSyncStatus:!1}}const n=!ba();return{payload:await Od(n,e,{includeJoinRequests:!1,signal:t.signal}),fetchedFreshSyncStatus:!0}}function LJ(e){return e.requiredSurface!=="all"?!0:e.actorLoadError||e.coordinatorAdminLoadError||e.shareOperationsLoadError?!1:!e.requiresDeviceIdentityInventory||!e.deviceIdentityInventoryLoadError}async function OJ(e){const t=OW();let n=null,r=null,i=_.lastDeviceIdentityInventory,o=_.lastShareOperations,s=!1,c=!1,l=_.deviceIdentityInventoryLoadError,d=!1;try{n=await Mk({signal:e.signal})}catch{s=!0}try{r=await Dd({signal:e.signal})}catch{c=!0}if(_.activeTab==="advanced"){l=!1;try{i=await Ud({signal:e.signal})}catch{l=!0}}try{const u=await dv({signal:e.signal});o=Array.isArray(u.items)?u.items:[]}catch{d=!0}return{actorsPayload:n,coordinatorAdminStatus:r,deviceIdentityInventory:i,shareOperations:o,actorLoadError:s,coordinatorAdminLoadError:c,deviceIdentityInventoryLoadError:l,shareOperationsLoadError:d,duplicatePersonDecisions:t}}function ud(e={}){const t=$J(++lh,{requiredSurface:e.requiredSurface??"all",requireFreshSyncStatus:e.requireFreshSyncStatus??!1,signal:e.signal});return dh=t,t}async function $J(e,t){try{const n=_.currentProject||"",{payload:r,fetchedFreshSyncStatus:i}=await jJ(n,t);if(t.signal?.aborted)return!1;const{actorsPayload:o,coordinatorAdminStatus:s,deviceIdentityInventory:c,shareOperations:l,actorLoadError:d,coordinatorAdminLoadError:u,deviceIdentityInventoryLoadError:p,shareOperationsLoadError:f,duplicatePersonDecisions:m}=await OJ(t);if(e!==lh)return dh??!1;if(t.signal?.aborted)return!1;const v=LJ({requiredSurface:t.requiredSurface,actorLoadError:d,coordinatorAdminLoadError:u,shareOperationsLoadError:f,requiresDeviceIdentityInventory:_.activeTab==="advanced",deviceIdentityInventoryLoadError:p});i&&EJ(n,xJ(r)),NJ(r.coordinator);const b=JSON.stringify([r,o,s,c,p,l,f,m,PJ()]);if(b===dd)return v;dd=b;const g=r.status&&typeof r.status=="object"?r.status:null;g&&(_.lastSyncStatus=g),Array.isArray(o?.items)?_.lastSyncActors=o.items:_.lastSyncActors=[];const y=Array.isArray(r.peers)?r.peers:[],S=new Set(y.map(R=>String(R?.peer_device_id||"").trim()).filter(Boolean)),w=Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(R=>{const k=String(R?.peer_device_id||"").trim();return k&&!S.has(k)}):[];return _.pendingAcceptedSyncPeers=w,_.lastSyncPeers=[...y,...w],p||(_.lastDeviceIdentityInventory=c),_.deviceIdentityInventoryLoadError=p,_.lastShareOperations=l,_.shareOperationsLoadError=f,_.lastSyncSharingReview=r.sharing_review||[],_.lastSyncLegacySharedReview=r.legacy_shared_review&&typeof r.legacy_shared_review=="object"?r.legacy_shared_review:null,_.lastSyncCoordinator=r.coordinator||null,_.lastSyncCoordinatorAdminStatus=s&&typeof s=="object"?s:null,_.lastSyncJoinRequests=Array.isArray(r.join_requests)?r.join_requests:[],_.lastSyncAttempts=r.attempts||[],_.lastSyncLegacyDevices=r.legacy_devices||[],_.lastSyncDuplicatePersonDecisions=m,_.lastSyncViewModel=TW({actors:_.lastSyncActors,peers:_.lastSyncPeers,coordinator:_.lastSyncCoordinator,status:g,shareOperations:_.lastShareOperations,shareOperationsLoadError:f,reconciliation:r.recipient_policy_reconciliation,duplicatePersonDecisions:_.lastSyncDuplicatePersonDecisions}),HR(),ld(),N3(),T3(),oI(),rh(),QR(),GR(),FJ(),d&&P3(),u&&(_.lastSyncCoordinatorAdminStatus=null,ld()),v}catch{return t.signal?.aborted?!1:e!==lh?dh??!1:(dd="",_.deviceIdentityInventoryLoadError=!0,MJ(),!1)}}function MJ(){Er("syncTeamSkeleton"),Er("syncActorsSkeleton"),Er("syncPeersSkeleton"),Er("syncDiagSkeleton"),DJ(),ZR();const e=document.getElementById("syncSetupPanel"),t=document.getElementById("syncJoinPanel");e&&(e.hidden=!1),t&&(t.hidden=!1),A3(),VW()}function FJ(){if(_.activeTab==="health"){hm();return}VS()}function BJ(){dd="",_.lastSyncPeers?.length&&rh()}async function pd(){await ud()}function qJ(e={}){const t=UJ(++uh,e.signal);return ph=t,t}async function UJ(e,t){try{const n=await Fk(!1,{signal:t});return t?.aborted?!1:e!==uh?ph??!1:(_.pairingPayloadRaw=n||null,Qm(),!0)}catch{return t?.aborted?!1:e!==uh?ph??!1:(_.pairingPayloadRaw=null,Qm(),!1)}}function GJ(e){mz(),nl(),j3(pd),k3(pd),YW(rh),q3(e,pd),E3(pd),QW(e),ih(),D3()}function HJ(e,t){const n=nt("runtimeLabel");n&&(n.textContent=t?`v${e} (${t})`:`v${e}`,n.title=t?`codemem ${e} (${t})`:`codemem ${e}`,n.hidden=!1)}async function VJ(){try{const e=await gk();if(!e?.version)return;HJ(e.version,"c176fa5")}catch{}}var fh=null,sI=1500,Cs=V0(),cI="codemem-legacy-upgrade-notice-dismissed",jr=null,cn=!1,fd=!1,mh=!1;function lI(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function dI(e){if(!e||typeof e!="object")return null;const t=e.legacy_shared_review??e;if(!t||typeof t!="object")return null;const n=t;if(n.has_data!==!0)return null;const r=Array.isArray(n.groups)?n.groups:[],i=lI(n.total_group_count,r.length),o=lI(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function uI(){try{return localStorage.getItem(cI)==="1"}catch{return!1}}function KJ(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(cI,"1")}catch{}}function zJ(e,t){e&&t?Qx(t):Xx()}function pI(e){!e||mh||uI()||(mh=!0,Uy(()=>zJ(!0,e)))}async function WJ(){if(!(mh||uI()))try{pI(dI(await Od(!1,"",{includeJoinRequests:!1})))}catch{}}function Ri(e,t){_.viewerReconnectOpen=e;const n=nt("viewerReconnectOverlay"),r=nt("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.",_.activeTab==="feed"&&Cn(!0))}async function hh(){try{return await vk(),!0}catch{return!1}}function vh(){return document.visibilityState!=="hidden"&&!YC()}function fI(){return`${_.activeTab}:${_.advancedSection}:${_.syncPairingOpen}`}function JJ(e){_.refreshQueued||e.surface!==fI()||!e.refreshSucceeded||!fd||cn||(fd=!1,zu("connection_restored"))}function mI(){if(cn)return;cn=!0,fd=!0,zu("connection_lost"),gh(),Uy(),Lr("error","(reconnecting)"),Ri(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await hh()){if(jr&&(clearTimeout(jr),jr=null),cn=!1,Ri(!0,"Viewer responded. Restoring your session…"),vh()){Lr("refreshing"),Rs();try{await gd()}catch{}}else Lr("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");cn||Ri(!1);return}Ri(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),jr=setTimeout(e,sI)};jr=setTimeout(e,sI)}function Lr(e,t){_.refreshState=e;const n=nt("refreshStatus");if(!n)return;n.dataset.refreshState=e;const r=o=>{const s=nt("refreshAnnouncer");!s||fh===e||(s.textContent=o,fh=e)};if(e==="refreshing"){n.textContent="refreshing…";return}if(e==="paused"){n.textContent="paused",r("Auto refresh paused.");return}if(e==="error"&&t==="(reconnecting)"){n.textContent="reconnecting…",r("Viewer reconnecting.");return}if(e==="error"){n.textContent="refresh failed",r("Refresh failed.");return}const i=t?` ${t}`:"";n.textContent=`updated ${new Date().toLocaleTimeString()}${i}`,fh=null}function gh(){El(),Cs.cancel(),Oo&&(clearTimeout(Oo),Oo=null),_.refreshQueued=!1,_.refreshTimer&&(clearInterval(_.refreshTimer),_.refreshTimer=null)}function hI(){gh(),Lr("paused")}function Rs(){_.refreshTimer||(_.refreshTimer=setInterval(()=>Or(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(gh(),Lr("paused","(tab hidden)")):!YC()&&!cn&&(Rs(),Or())});var md=!1;function vI(){const e=_.advancedSection==="sync",t=nt("advancedSyncContent"),n=nt("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=nt("advancedTabsMount");r&&$D(r,_.advancedSection,YJ),queueMicrotask(()=>{const i=window.location.hash.replace(/^#/,"");if(!e&&md){md=!1;const o=document.getElementById("advancedAdministrationDisclosure");o instanceof HTMLDetailsElement&&(o.open=!0),document.getElementById("coordinatorAdminHeading")?.focus()}ih(i==="sync/diagnostics"||i==="advanced/sync/diagnostics"?"diagnostics":"main")})}function YJ(e,t={}){Rb(e,!0),vI(),e==="teams"&&t.focusContent&&queueMicrotask(()=>document.getElementById("coordinatorAdminHeading")?.focus())}var QJ=oD();function gI(e){const t=new Set(J0(_.lastCoordinatorAdminStatus));Yr.forEach(r=>{const i=nt(`tab-${r}`);i&&(i.hidden=r!==e||!t.has(r))}),Yr.forEach(r=>{const i=nt(`tabBtn-${r}`);if(!i)return;i.hidden=!t.has(r);const o=r===e&&t.has(r);i.classList.toggle("active",o),o?i.setAttribute("aria-current","page"):i.removeAttribute("aria-current")});const n=nt(`tabBtn-${e}`);n&&QJ(n),e==="advanced"&&vI()}function kn(e,t={}){El(),Cs.cancel();const n=ya(e,_.lastCoordinatorAdminStatus);n==="advanced"&&Rb(t.advancedSection??mp()??_.advancedSection),Ib(n,t.canonicalHash?{canonicalHash:!0}:{}),n==="health"&&li("settings-health"),gI(n),Or()}function XJ(){window.addEventListener("codemem:navigate-advanced-sync",tY),Yr.forEach(e=>{nt(`tabBtn-${e}`)?.addEventListener("click",()=>kn(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),nt("syncTurnOnButton")?.addEventListener("click",()=>{JC("sync"),vR(hI)}),nt("advancedTeamSettingsLink")?.addEventListener("click",e=>{e.preventDefault(),Uu("teams"),kn("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),nt("advancedSharingLink")?.addEventListener("click",e=>{e.preventDefault(),Uu("invitations"),kn("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),window.addEventListener("hashchange",()=>{const e=fp();if(e){const t=mp();md=Cb(),kn(e,t?{advancedSection:t}:{}),e==="advanced"&&t==="teams"&&queueMicrotask(()=>document.getElementById("coordinatorAdminHeading")?.focus())}}),md=Cb(),kn(_.activeTab)}async function ZJ(){try{const e=await Ts();_.knownProjects=e,BJ();const t=up("projectFilter");if(!t)return;t.textContent="";const n=document.createElement("option");n.value="",n.textContent="All Projects",t.appendChild(n),e.forEach(r=>{const i=document.createElement("option");i.value=r,i.textContent=r,t.appendChild(i)})}catch{}}function eY(e){_.pendingDeviceIdentityFocus=e?.trim()||null,kn("devices",{canonicalHash:!0})}function tY(){kn("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("advancedSyncButton")?.focus())}var hd=UE({},{onOpenTeamSetup:fC,onReviewDevices:eY}),yI={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},yh=0,bh=null,Vt=null;async function nY(e={}){const t=[];let n=0;for(;;){const r=await Ho({limit:250,offset:n,signal:e.signal});if(t.push(...r.projects),!r.has_more)break;n+=r.limit}return nc(t)}function rY(){const e=new Map,t={unknown:0,offline:1,available:2},n=(r,i)=>{!r||t[i]<=t[e.get(r)??"unknown"]||e.set(r,i)};for(const r of _.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"unknown":"available");for(const r of _.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),o=_s(r);n(i,o==="connected"||o==="available"?"available":o==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function iY(){return _.lastSyncPeers.flatMap(e=>{const t=String(e.peer_device_id??"").trim();return t?[{deviceId:t,runtimeVersion:e.runtime_version??null,runtimeVersionObservedAt:e.runtime_version_observed_at??null}]:[]})}function bI(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:null}function oY(e){return _.lastSyncPeers.flatMap(t=>{const n=String(t.peer_device_id??"").trim();if(!n)return[];const r=t.has_error?"error":t.status?.sync_status,i=["ok","error","stale"].includes(r??"")?r:"unknown";return[{deviceId:n,paired:t.pinned===!0,status:i,lastSyncAt:t.last_sync_at??t.status?.last_sync_at??null,recentIn:bI(t.recent_ops?.in),recentOut:bI(t.recent_ops?.out),statusAvailable:e}]})}async function aY(e){try{const t=await Gd({peerDeviceId:e});if(t.items.length!==1||t.items[0]?.peer_device_id!==e)return{message:"This device is no longer paired here. Refresh Devices before retrying.",tone:"warning"};const n=Bm(t),r=await vd();return{message:r?n.message:`${n.message} Refresh Devices to see the latest sync status.`,tone:n.ok&&!n.warning&&r?"success":"warning"}}catch(t){return t instanceof Error&&/\bsync_disabled\b/.test(t.message)?{message:"Device sync is off. Turn it on in Settings → Device Sync, then try again.",tone:"warning"}:{message:ct(t,"Could not sync this device. Check its pairing and try again."),tone:"warning"}}}function sY(e){if(e==="advanced_sync"){kn("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}if(e==="sharing_teams"){kn("sharing",{canonicalHash:!0}),Uu("teams"),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus());return}kn(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function vd(e={}){const t=document.getElementById("devicesMount");if(!t||e.deferWhileRenaming&&document.activeElement?.closest(".devices-rename-form"))return Promise.resolve(!0);const n=dY(t,++yh,e);return bh=n,n}async function cY(){const[e,t]=await Promise.all([vd(),hd()]);return e&&t}function _I(){return{localDeviceId:_.lastSyncStatus?.device_id??void 0,onCommitted:cY,onNavigate:sY,onRetry:()=>{vd()},onSyncDevice:aY}}function lY(e){if(!Vt){cl(e,yI,{version:1,items:[]},[],[],{loadError:!0});return}cl(e,Vt.intent,Vt.reconciliation,Vt.projects,Vt.availability,{..._I(),coordinatorEnrollmentIssueCount:Vt.coordinatorEnrollmentIssueCount,inventory:Vt.inventory,inventoryUnavailable:Vt.inventoryUnavailable,peerRuntimeMetadata:Vt.peerRuntimeMetadata,peerSyncMetadata:Vt.peerSyncMetadata,refreshError:!0})}async function dY(e,t,n){Vt||cl(e,yI,{version:1,items:[]},[],[],{loading:!0});try{const[r,i,o,s,c]=await Promise.all([nY(n),qd(n),sN(n),Ud(n).then(f=>({inventory:f,unavailable:!1})).catch(()=>({inventory:Vt?.inventory,unavailable:!0})),ud({requiredSurface:"devices",signal:n.signal})]);if(n.signal?.aborted)return!1;if(t!==yh)return bh??!1;const l=rY(),d=iY(),u=oY(c),p=pv(_.lastSyncStatus);return!s.unavailable&&s.inventory&&(_.lastDeviceIdentityInventory=s.inventory),_.deviceIdentityInventoryLoadError=s.unavailable,cl(e,i,o,r,l,{..._I(),inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:p,peerRuntimeMetadata:d,peerSyncMetadata:u,syncStatusUnavailable:!c}),Vt={projects:r,intent:i,reconciliation:o,availability:l,peerRuntimeMetadata:d,peerSyncMetadata:u,inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:p},c}catch{return n.signal?.aborted?!1:t!==yh?bh??!1:(lY(e),!1)}}up("projectFilter")?.addEventListener("change",()=>{Cs.cancel(),El(),_.currentProject=up("projectFilter")?.value||"",li("scope"),Cn(!0),Or()});var Oo=null;async function uY(e){await Promise.all([j2({signal:e.signal}),rK({signal:e.signal}),Vx().catch(()=>{})])}function pY(e,t,n,r){if(t!=="health"&&VS(),t==="feed"){const s=Y$();e.push(J_(s,{signal:r.signal}),um({signal:r.signal}))}if(t==="projects"&&e.push(To({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="sharing"&&e.push(hd({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="devices"&&e.push(vd({deferWhileRenaming:!0,signal:r.signal}).then(n)),t==="health"&&e.push(L2({signal:r.signal}),ud({requiredSurface:"health",requireFreshSyncStatus:fd,signal:r.signal}).then(n)),t==="advanced"&&_.advancedSection==="sync"&&e.push(ud({signal:r.signal}).then(n)),t==="advanced"&&_.advancedSection==="teams"&&e.push(ol({deferWhileRenaming:!0,signal:r.signal}).then(n)),!_.syncPairingOpen)return;const i=t==="advanced"&&_.advancedSection==="sync",o=qJ({signal:r.signal});e.push(i?o.then(n):o)}async function Or(){cn||(Oo&&clearTimeout(Oo),Oo=setTimeout(()=>gd(),80))}async function fY(e,t){if(!t.isCurrent()&&!Oh(e))return;const n=await hh();t.isOwned()&&(n?Lr("error"):mI())}function mY(e){Cs.finish(e),_.refreshInFlight=!1,!(!_.refreshQueued||cn||!vh())&&(_.refreshQueued=!1,gd())}async function gd(){if(cn||!vh())return;if(_.refreshInFlight){_.refreshQueued=!0;return}_.refreshInFlight=!0;const e=Cs.begin();try{Lr("refreshing");const t=_.activeTab,n=fI(),r=[uY(e)];let i=!0;if(pY(r,t,s=>{i=i&&s},e),await Go(Promise.all(r),e.signal),!e.isCurrent()){if(Oh(e.signal.reason))throw e.signal.reason;return}pI(dI(_.lastSyncLegacySharedReview)),t==="feed"&&Cn(!0);const o=ya(_.activeTab,_.lastCoordinatorAdminStatus);o!==_.activeTab&&(El(),Ib(o)),gI(_.activeTab),Lr(i?"idle":"error"),JJ({refreshSucceeded:i,surface:n})}catch(t){await fY(t,e)}finally{mY(e)}}rD();var wI=document.getElementById("toastRoot");wI&&G0(wI);var SI=document.getElementById("diagnosticsDrawerMount");SI&&Hx(SI);var CI=document.getElementById("legacyTeamSetupMount");CI&&OG(CI,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(_.activeTab==="sharing"?(t=await To(n),e=await hd(n)):(e=await hd(n),t=await To(n)),!e||!t)throw new Error("team_setup_refresh_failed")}});var RI=document.getElementById("legacyUpgradeDialogMount");RI&&Yx(RI,{onDismiss:KJ,onReviewGroups:()=>{window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)},onReviewProjects:()=>{window.location.hash="projects"}}),aD(Sc("themeToggle")),Tb(gp()),XJ(),vU(),Kx(),MV(()=>Or(),{onOpenTeamSetup:fC}),GJ(()=>Or()),rM(),pz(hI,Rs,()=>Or()),ZJ(),nt("viewerReconnectRetry")?.addEventListener("click",async()=>{if(zu("reconnect_requested"),Ri(!0,"Checking whether the viewer server is back…"),!await hh()){mI();return}jr&&(clearTimeout(jr),jr=null),cn=!1,Ri(!0,"Viewer responded. Restoring your session…"),Rs();try{await gd()}catch{}cn||Ri(!1)}),VJ(),WJ(),Or(),Rs()})();
118
+ `)];w.forEach((A,M)=>{A&&(A.textContent=F[M]??"")}),S.hidden=!1,document.getElementById("syncPairingReviewHeading")?.focus()},N=(E,F)=>F===y&&d?.value.trim()===E;r?.addEventListener("click",()=>{ic()||Y("Project sharing is unavailable. Refresh Projects and try again.","warning")});const j=async(E,F)=>{const A=await Wh(E);return N(E,F)?(g=A.kind,A.kind==="pair"?(k(A),"other"):A.kind!=="project_share_invite"||!u||!m||!v?"other":(p&&(p.textContent=$3(A)),m.value=Hi(A.recipient_name),v.value=Hi(A.device_name),u.hidden=!1,b=E,l&&(l.textContent="Accept and start syncing"),f?.focus(),"project")):"stale"};d?.addEventListener("input",()=>{y+=1,d.value.trim()!==b&&(b="",g=void 0,u&&(u.hidden=!0),R(),l&&(l.textContent="Review invite"))}),i?.addEventListener("click",async()=>{if(!i||!o||!s||!c||i.disabled)return;const E=o.value.trim(),F=Number(s.value);let A=!0;if(E?ga(o):A=Jr(o,"Team name is required."),!F||F<1?A=Jr(s,"Must be at least 1 hour."):ga(s),!!A){i.disabled=!0,i.textContent="Creating…";try{const M=await Gh({group_id:E,policy:In.invitePolicy,ttl_hours:F||24});_.lastTeamInvite=M,ah(),c.value=String(M.encoded||""),c.hidden=!1,c.focus(),c.select(),M3(Array.isArray(M.warnings)?M.warnings:[])}catch(M){Y(ct(M,"Failed to create invite. Check the team name, invite lifetime, and coordinator reachability, then try again."),"warning"),i.textContent="Retry",i.disabled=!1;return}finally{i.disabled&&(i.disabled=!1,i.textContent="Create invite")}}}),d?.addEventListener("keydown",E=>{Ta(E,{onSubmit:()=>l?.click(),disabled:!l||l.disabled})}),l?.addEventListener("click",async()=>{if(!l||!d||l.disabled)return;const E=d.value.trim();if(!E){Jr(d,"Paste a team invite or pairing payload.");return}if(ga(d),b!==E){const A=y;l.disabled=!0;try{const M=await j(E,A);if(M==="project"||M==="stale")return}catch(M){if(!N(E,A))return;Jr(d,ct(M,"Could not review this invite or pairing payload. Check the pasted text and try again."));return}finally{l.disabled=!1}if(!N(E,A))return;b=E,l.textContent="Accept invite";return}const F=u&&!u.hidden?{recipient_name:m?.value.trim()??"",device_name:v?.value.trim()??""}:void 0;if(F){const A=M=>Hi(M)==="";if(A(F.recipient_name)){m&&Jr(m,"Enter a human-readable name using 120 characters or fewer.");return}if(A(F.device_name)){v&&Jr(v,"Enter a human-readable device name using 120 characters or fewer.");return}}l.disabled=!0,l.textContent="Accepting…";try{const A=await $d(E,F,g);_.lastTeamJoin=A;let M=B3(A);_.syncJoinFlowFeedback=M,od(),d.value="",y+=1,b="",g=void 0,R(),u&&(u.hidden=!0);try{await t()}catch(O){M={message:ct(O,"Accepted the invite, but this view has not refreshed yet."),tone:"warning"},_.syncJoinFlowFeedback=M,od()}}catch(A){_.syncJoinFlowFeedback={message:ct(A,"Failed to accept. Check that the invite or pairing payload is complete and current, then try again."),tone:"warning"},od(),l.textContent="Retry",l.disabled=!1;return}finally{l.disabled&&(l.disabled=!1,l.textContent="Review invite")}}),n?.addEventListener("click",async()=>{if(n){n.disabled=!0,n.textContent="Syncing…";try{const E=await Gd(),F=Bm(E);Y(F.message,F.warning?"warning":void 0)}catch(E){Y(ct(E,"Failed to start sync. Retry once, then run codemem sync doctor if the problem keeps coming back."),"warning"),n.textContent="Retry",n.disabled=!1;return}n.disabled=!1,n.textContent="Sync now",e()}})}function U3({status:e}){return e.state==="disabled"?a("div",{className:"advanced-sync-status-label",children:[a(rn,{"aria-label":"Sync off",state:"unknown"}),a("strong",{className:"xl",children:"Sync is off"}),a(Ue,{tone:"badge-offline",variant:"badge",children:"Off"})]}):e.state==="healthy"?a("div",{className:"advanced-sync-status-label",children:[a(rn,{"aria-label":"Sync on",state:"online"}),a("strong",{className:"xl",children:"Sync is on"}),a(Ue,{tone:"badge-online",variant:"badge",children:"On"})]}):a("div",{className:"advanced-sync-status-label",children:[a(rn,{"aria-label":"Sync needs attention",state:"degraded"}),a("strong",{className:"xl",children:"Sync needs attention"}),a(Ue,{tone:"badge-offline",variant:"badge",children:"Attention"})]})}function sh({element:e,hidden:t=!1,restoreParent:n=null}){const r=D(null);return at(()=>{e&&(e.hidden=t)},[e,t]),at(()=>{const i=r.current;if(!(!i||!e))return e.parentElement!==i&&i.appendChild(e),()=>{!n||e.parentElement!==i||n.appendChild(e)}},[e,n]),a("div",{ref:r})}function G3({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:r}){return a(G,{children:[a("div",{className:"sync-action",children:a("button",{type:"button",className:"settings-button",onClick:r,children:t?"Hide team setup":"Set up a new team instead"})}),e?a(sh,{element:e,hidden:!t,restoreParent:n}):null]})}function H3({invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,joinPanel:r,joinRestoreParent:i,onToggleInvitePanel:o,presenceStatus:s}){const c=s==="not_enrolled";return a(G,{children:[c?a(G,{children:[a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"Join this device"})}),r?a(sh,{element:r,hidden:!1,restoreParent:i}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}):a(G,{children:[r?a(sh,{element:r,hidden:!1,restoreParent:i}):null,a("div",{className:"peer-meta",id:"syncJoinFeedback",hidden:!0})]}),c?null:a(G3,{invitePanel:e,invitePanelOpen:t,inviteRestoreParent:n,onToggle:o})]})}function sd({count:e,label:t}){return a("div",{className:"sync-section-heading",children:[a("div",{className:"sync-action-text sync-section-label",children:t}),e?a("span",{className:"badge actor-badge sync-section-count",children:e}):null]})}function V3({item:e,onAction:t}){const[n,r]=T(!1);return a("div",{className:"sync-action",children:[a("div",{className:"sync-action-text",children:[e.title,a("span",{className:"sync-action-command",children:e.summary})]}),a("button",{type:"button",className:"settings-button",disabled:n,onClick:async()=>{r(!0);try{await t(e)}finally{r(!1)}},children:e.actionLabel||"Review"})]})}function K3({request:e,onApprove:t,onDeny:n}){const[r,i]=T(null),[o,s]=T(null),[c,l]=T("Approve"),[d,u]=T("Deny");return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:a("div",{className:"actor-title",title:e.requestId||void 0,children:e.displayName})}),a("div",{className:"actor-actions",children:[a("button",{type:"button",className:"settings-button","aria-label":`${c} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("approve"),l("Approving…");try{s(await t(e)||null),l("Approve")}catch{l("Retry")}finally{i(null)}},children:c}),a("button",{type:"button",className:"settings-button","aria-label":`${d} join request from ${e.displayName}`,disabled:r!==null,onClick:async()=>{i("deny"),u("Denying…");try{s(await n(e)||null),u("Deny")}catch{u("Retry")}finally{i(null)}},children:d})]}),a(xr,{feedback:o})]})}function z3({onReview:e,row:t}){const[n,r]=T(!1),[i,o]=T(null),s=t.actionLabel||"Pair with this device",[c,l]=T(s);return a(G,{children:[a("button",{"aria-label":`${c} for ${t.displayName}`,className:"settings-button",disabled:n,onClick:async()=>{r(!0),l("Pairing…"),o({message:`Pairing ${t.displayName}. Keep this page open while the device is approved and refreshed.`,tone:"success"});try{const d=await e(t)||null;o(d),l(d?.tone==="warning"?"Retry":t.actionLabel||s)}catch{o({message:`Pairing ${t.displayName} failed. Try again.`,tone:"warning"}),l("Retry")}finally{r(!1)}},type:"button",children:c}),a(xr,{feedback:i})]})}function W3({onInspect:e,onRemove:t,row:n}){const[r,i]=T(!1),[o,s]=T(null),[c,l]=T("Remove broken device record");return a(G,{children:[a("button",{"aria-label":`Open details for ${n.displayName}`,className:"settings-button",disabled:r,onClick:()=>e(n),type:"button",children:"Open device details"}),a("button",{"aria-label":`${c} for ${n.displayName}`,className:"settings-button danger",disabled:r,onClick:async()=>{i(!0),l("Removing…");try{s(await t(n)||null),l("Remove broken device record")}catch{l("Retry")}finally{i(!1)}},type:"button",children:c}),a(xr,{feedback:o})]})}function J3({row:e,onInspectConflict:t,onRemoveConflict:n,onReview:r}){return a("div",{className:"peer-card peer-card--padded","data-discovered-device-id":e.deviceId,children:[a("div",{className:"peer-title",children:[a("strong",{title:e.displayTitle||void 0,children:e.displayName}),a("span",{className:`badge actor-badge${e.availabilityLabel==="Offline"?"":" local"}`,children:e.availabilityLabel}),a("span",{className:"badge actor-badge",children:e.connectionLabel}),e.approvalBadgeLabel?a("span",{className:"badge actor-badge",children:e.approvalBadgeLabel}):null]}),a("div",{className:"peer-meta",children:e.note}),a("div",{className:"peer-actions",children:[e.mode==="accept"?a(z3,{onReview:r,row:e}):null,e.actionMessage?a("div",{className:"peer-meta",children:e.actionMessage}):null,e.mode==="paired"&&e.pairedMessage?a("div",{className:"peer-meta",children:e.pairedMessage}):null,e.mode==="conflict"?a(W3,{onInspect:t,onRemove:n,row:e}):null]})]})}function Y3(e){const t=e.actionItems.length>0,n=e.actionableCount>e.actionItems.length,r=t||n||e.primaryStatus.state!=="healthy";return a(G,{children:[r?a(sd,{label:"Needs attention"}):null,e.primaryStatus.nextAction?a("div",{className:"sync-action","data-primary-sync-state":e.primaryStatus.state,children:a("div",{className:"sync-action-text",children:[e.primaryStatus.badgeLabel,a("span",{className:"sync-action-command",children:e.primaryStatus.nextAction})]})}):null,t?e.actionItems.map(i=>a(V3,{item:i,onAction:e.onAttentionAction},i.id)):null,!t&&!n&&e.primaryStatus.state==="healthy"?a("div",{className:"sync-action",children:a("div",{className:"sync-action-text",children:"No urgent team work right now."})}):null]})}function Q3({children:e}){return e?a(G,{children:[a(sd,{label:"Add devices & teammates"}),e]}):null}function X3({mount:e,rows:t,onInspectConflict:n,onRemoveConflict:r,onReview:i}){return!e||!t.length&&!_.syncDiscoveredFeedback?null:fn(a(G,{children:[a(sd,{count:t.length||void 0,label:"Devices waiting for review"}),a(xr,{feedback:_.syncDiscoveredFeedback}),t.map(o=>a(J3,{row:o,onInspectConflict:n,onRemoveConflict:r,onReview:i},`${o.deviceId}:${o.incomingRequestId}:${o.fingerprint}`))]}),e)}function Z3({mount:e,requests:t,onApprove:n,onDeny:r}){return!e||!t.length&&!_.syncJoinRequestsFeedback?null:fn(a(G,{children:[a(sd,{count:t.length||void 0,label:"Join requests to review"}),a(xr,{feedback:_.syncJoinRequestsFeedback}),t.map(i=>a(K3,{request:i,onApprove:n,onDeny:r},i.requestId))]}),e)}function eI(e){return a(G,{children:[a(Y3,{...e}),a(Q3,{children:e.children}),a(Z3,{mount:e.joinRequestsMount,requests:e.pendingJoinRequests,onApprove:e.onApproveJoinRequest,onDeny:e.onDenyJoinRequest}),a(X3,{mount:e.discoveredListMount,rows:e.discoveredRows,onInspectConflict:e.onInspectConflict,onRemoveConflict:e.onRemoveConflict,onReview:e.onReviewDiscoveredDevice})]})}function tI(e){e&&(e.textContent="")}function cd(e){e instanceof HTMLElement&&(e.classList.remove("sync-attention-target"),e.offsetWidth,e.classList.add("sync-attention-target"),window.setTimeout(()=>e.classList.remove("sync-attention-target"),900))}function eJ(){return typeof window<"u"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches}function ws(){return eJ()?"auto":"smooth"}var ch="syncTeamActionsMount",tJ="Approval sent for this device. This screen may take up to 30 seconds to confirm two-way trust.";function nJ(e,t,n=!1){return e.length>1&&(!t||n)}function rJ(e,t,n){e.hidden=!1,e.textContent=n.badgeLabel,t.textContent=n.meta,n.state==="healthy"?e.className="sync-online-badge":n.state==="disabled"||n.state==="pending-setup"||n.state==="not-enrolled"||n.state==="reachable"?e.className="sync-online-badge sync-online-offline":e.className="sync-online-badge sync-online-error"}function iJ(e,t){const n=document.createElement("div");n.id=ch,e.appendChild(n),dt(n,h(eI,{actionItems:[],actionableCount:0,discoveredListMount:null,discoveredRows:[],joinRequestsMount:null,onApproveJoinRequest:async()=>null,onAttentionAction:async()=>{},onDenyJoinRequest:async()=>null,onInspectConflict:()=>{},onRemoveConflict:async()=>null,onReviewDiscoveredDevice:async()=>null,pendingJoinRequests:[],presenceStatus:"unknown",primaryStatus:t}))}function nI(e,t){const n=document.getElementById(ch);n&&(xo(n),n.remove()),tI(e),t.forEach(r=>{tI(r)})}function oJ(e){const t=document.getElementById("syncJoinPanel"),n=document.getElementById("syncJoinRequests"),r=document.getElementById("syncCoordinatorDiscovered"),i=document.getElementById("syncCoordinatorDiscoveredList");nI(e.actions,[n,i]),e.setupPanel.hidden=!1,t&&(t.hidden=!1),e.actions.hidden=!1,iJ(e.actions,e.primaryStatus),n&&(n.hidden=!0),r&&(r.hidden=!0)}function ld(){const e=document.getElementById("syncTeamMeta"),t=document.getElementById("syncSetupPanel"),n=document.getElementById("syncTeamActions");if(!e||!t||!n)return;oh(),ad(),ah(),od(),O3();const r=document.getElementById("syncInvitePanel"),i=document.getElementById("syncAdminSection"),o=document.getElementById("syncJoinPanel"),s=document.getElementById("syncJoinSection"),c=document.getElementById("syncJoinRequests"),l=document.getElementById("syncCoordinatorDiscovered"),d=document.getElementById("syncCoordinatorDiscoveredMeta"),u=document.getElementById("syncCoordinatorDiscoveredList");Er("syncTeamSkeleton"),ZR();const p=_.lastSyncCoordinator,f=sJ();aJ(f.primaryStatus);const m=()=>{const C=document.getElementById("manualDeviceIdentityControls");C instanceof HTMLDetailsElement&&(C.open=!0)},v=C=>{if(m(),C.kind==="possible-duplicate-person"){const ne=document.getElementById("syncActorsList");ne instanceof HTMLElement&&(ne.scrollIntoView({block:"center",behavior:ws()}),cd(ne));return}const x=String(C.deviceId||"").trim();if(!x)return;if(C.kind==="name-device"){const ne=document.querySelector(`[data-device-name-input="${CSS.escape(x)}"]`);if(ne instanceof HTMLInputElement){ne.scrollIntoView({block:"center",behavior:ws()}),ne.focus(),ne.select(),cd(ne);return}}const B=document.querySelector(`[data-peer-device-id="${CSS.escape(x)}"]`);if(B instanceof HTMLElement){B.scrollIntoView({block:"center",behavior:ws()}),cd(B);return}const U=document.querySelector(`[data-discovered-device-id="${CSS.escape(x)}"]`);U instanceof HTMLElement&&(U.scrollIntoView({block:"center",behavior:ws()}),cd(U))},b=async C=>{const x=Array.isArray(C.actorIds)?C.actorIds.map(te=>String(te||"").trim()).filter(Boolean):[],B=(Array.isArray(_.lastSyncActors)?_.lastSyncActors:[]).filter(te=>x.includes(String(te?.actor_id||"").trim()));if(B.length<2){Y("This duplicate review is outdated. Refresh the card and review the remaining people entries.","warning");return}const U=await b$({title:"Review possible duplicate people",summary:C.title.replace(/^Possible duplicate person:\s*/,""),actors:B.map(te=>({actorId:String(te?.actor_id||""),label:String(te?.display_name||te?.actor_id||"Unknown person"),isLocal:!!te?.is_local}))});if(U.action==="different-people"){$W(x,"different-people"),Y("Okay. I will keep these people separate on this device."),await In.loadSyncData();return}if(U.action!=="merge")return;const ne=B.find(te=>String(te?.actor_id||"")===U.primaryActorId),ae=B.find(te=>String(te?.actor_id||"")===U.secondaryActorId);if(!ne?.actor_id||!ae?.actor_id){Y("Could not determine which people to combine. Refresh People & devices and try the review again.","warning");return}try{await uv(String(ne.actor_id),String(ae.actor_id)),MW(x),Y(`Combined duplicate people into ${String(ne.display_name||ne.actor_id)}.`),await In.loadSyncData()}catch(te){try{await In.loadSyncData()}catch{}Y(ct(te,"Failed to combine these people."),"warning")}},g=async C=>await gf({title:"Pair with this device",description:"Choose a friendly name for this device before pairing it on this machine.",initialValue:C,placeholder:"Desk Mini",confirmLabel:"Pair",cancelLabel:"Cancel",validate:x=>x.trim()?null:"Enter a device name to pair this device."}),y=!!p?.configured,S=CW(p);e.title=y?String(p.coordinator_url||"").trim():"";const w=document.getElementById("syncOnlineBadge");if(w?rJ(w,e,f.primaryStatus):e.textContent=f.primaryStatus.meta,!y){oJ({actions:n,setupPanel:t,primaryStatus:f.primaryStatus});return}t.hidden=!0,n.hidden=!1;const R=String(p.presence_status||""),k=Array.isArray(_.lastSyncPeers)?_.lastSyncPeers:[],N=Array.isArray(f.attentionItems)?f.attentionItems:[],j=Array.isArray(p.discovered_devices)?p.discovered_devices:[],E=String(p.coordinator_url||"").trim(),F=j.map(C=>{const x=String(C.device_id||"").trim(),B=String(C.display_name||"").trim(),U=IR({coordinatorName:B,deviceId:x})||"Discovered device",ne=x&&U!==x?x:null,ae=String(C.fingerprint||"").trim(),te=String(C.incoming_reciprocal_request_id||"").trim(),qe=Array.isArray(C.groups)?C.groups.map(tr=>String(tr||"").trim()).filter(Boolean):[],fe=k.find(tr=>String(tr?.peer_device_id||"")===x),$e=nJ(qe,!!fe,C.needs_local_approval===!0),Ne=CR({device:C,pairedLocally:!!fe}),se=String(fe?.fingerprint||"").trim(),we=!!fe&&!!ae&&!!se&&se!==ae,X=_.pendingCoordinatorApprovalsByDeviceId.get(x),ie=C.needs_local_approval===!0&&X?.coordinatorUrl===E&&X?.incomingRequestId===te,je=ie?"approval-pending":C.needs_local_approval===!0?"needs-local-approval":"not-required",ue=!ie&&!S&&Oz({device:C,hasAmbiguousCoordinatorGroup:$e,pairedLocally:!!fe}),ut=Array.isArray(C.addresses)?C.addresses:[],ye=Number(C.address_count??0),Dt=Number.isFinite(ye)&&ye>0?ye:0,ot=lJ({pairedLocally:!!fe,device:C,addressCount:ut.length+Dt}),le=[ut.length?ut.map(tr=>ba()?BR(String(tr||"")):String(tr||"")).filter(Boolean).join(" · "):Dt>0?`${Dt} ${C.stale?"last-known":"fresh"} ${Dt===1?"address":"addresses"} hidden`:"No fresh addresses"];!ut.length&&ne&&le.push(`device id: ${x}`);let Ct=null,Ze=ue?"accept":"none",Is=null;we?Ze="conflict":ie?(Ct="Waiting for refreshed coordinator status. You do not need to approve again.",Ze="approval-pending"):S&&(!fe||Ne.state==="needs-your-approval")?(Ct=S.message,Ze="setup-blocked"):$e?(Ct="This device appears in multiple coordinator groups. Review legacy Team/Space setup before approving it here.",Ze="ambiguous"):ot?(Ct=ot.actionMessage,Ze=ot.mode):fe&&Vm(x)?(Ct="Review this device's legacy Space access and advanced rules in Coordinator Administration before you sync it.",Ze="scope-pending"):fe?.last_error?(le.push(`error: ${String(fe.last_error)}`),ue||(Ze="paired")):fe?.status?.peer_state?(le.push(`status: ${String(fe.status.peer_state)}`),ue||(Ze="paired")):fe&&!ue&&(Ze="paired"),Ze==="paired"&&(Is=dJ(Ne.state,Ne.description,fe?.last_error));const ks=uJ(we,!!fe);return{actionMessage:Ct,actionLabel:Ne.actionLabel||(fe?"Review device":"Pair with this device"),approvalBadgeLabel:ie?"Approval sent":Ne.badgeLabel,approvalState:je,availabilityLabel:C.stale?"Offline":"Available",connectionLabel:ks,coordinatorUrl:E,deviceId:x,displayName:U,displayTitle:ne,fingerprint:ae,groupId:qe[0]??"",incomingRequestId:te,mode:Ze,note:le.join(" · "),pairedMessage:Is}}),A=new Set(F.filter(C=>C.approvalState==="approval-pending").map(C=>C.deviceId)),M=N.filter(C=>!C.deviceId||!A.has(C.deviceId)),O=[],H=F.filter(C=>C.mode!=="paired"&&C.mode!=="none"&&C.mode!=="scope-pending"),V=F.filter(C=>C.mode==="accept"||C.mode==="scope-pending").length,W=M.length+O.length+V;l&&(l.hidden=H.length===0&&!_.syncDiscoveredFeedback),d&&(d.textContent=H.length?"Pair with a teammate's device to see it appear in People & devices and start syncing.":""),c&&(c.hidden=O.length===0&&!_.syncJoinRequestsFeedback),nI(n,[c,u]);const $=document.createElement("div");$.id=ch,n.appendChild($),dt($,h(eI,{actionItems:M,actionableCount:W,children:h(H3,{invitePanel:r,invitePanelOpen:Um,inviteRestoreParent:i,joinPanel:o,joinRestoreParent:s,onToggleInvitePanel:()=>{r&&(EW(!Um),ld())},presenceStatus:R}),discoveredListMount:u,discoveredRows:H,joinRequestsMount:c,onApproveJoinRequest:async()=>null,onAttentionAction:async C=>{if(C.kind==="possible-duplicate-person"){await b(C);return}v(C)},onDenyJoinRequest:async()=>null,onInspectConflict:C=>{m();const x=document.querySelector(`[data-peer-device-id="${CSS.escape(C.deviceId)}"]`);if(x instanceof HTMLElement){x.scrollIntoView({block:"center",behavior:ws()}),Y(`Opened the conflicting local device record for ${C.displayName}.`,"warning");return}Y("The conflicting local device record is not visible yet. Scroll to People & devices and try again.","warning")},onRemoveConflict:async C=>{if(!await wn({title:`Remove ${C.displayName}?`,description:"This deletes the broken local device record. You can review this device again after the screen refreshes.",confirmLabel:"Remove device record",cancelLabel:"Keep device record",tone:"danger"}))return null;try{await Jh(C.deviceId);const x={message:`Removed the broken local device record for ${C.displayName}. If it is still available, review it again from Next steps or Devices seen on team.`,tone:"success"};return _.syncDiscoveredFeedback=x,await In.loadSyncData(),x}catch(x){return{message:ct(x,"Failed to remove the broken local device record. The old local record is still present in People & devices."),tone:"warning"}}},onReviewDiscoveredDevice:async C=>{try{const x=await g(C.displayName);return x?await cJ(C,x):null}catch(x){return{message:ct(x,"Failed to review this device. Wait for a fresh presence update and try again."),tone:"warning"}}},pendingJoinRequests:O,presenceStatus:R,primaryStatus:f.primaryStatus}))}function aJ(e){const t=document.getElementById("syncAdvancedStatusMount");t&&dt(t,h(U3,{status:e}));const n=document.getElementById("syncTurnOnButton");n&&(n.hidden=e.state!=="disabled");const r=document.getElementById("syncPrimaryStatusDetail");r&&(r.textContent=e.meta)}function sJ(){return _.lastSyncViewModel||{primaryStatus:xR({status:_.lastSyncStatus,coordinator:_.lastSyncCoordinator,peers:_.lastSyncPeers,shareOperations:_.lastShareOperations,shareOperationsLoadError:_.shareOperationsLoadError}),summary:{connectedDeviceCount:0,seenOnTeamCount:0,offlineTeamDeviceCount:0},duplicatePeople:[],attentionItems:[]}}async function cJ(e,t){const n=e.approvalState==="needs-local-approval",r=e.deviceId.trim(),i=e.coordinatorUrl.trim(),o=e.groupId.trim(),s=e.incomingRequestId.trim();if(n&&(!r||!i||!o||!s))throw new Error("Device identity is incomplete. Refresh the screen and try approval again.");const c=await qk(e.deviceId,{fingerprint:e.fingerprint,expectedGroupId:o||void 0,expectedIncomingRequestId:n?s:void 0}),l=String(c?.name||e.displayName||"").trim()||e.displayName;n&&_.pendingCoordinatorApprovalsByDeviceId.set(r,{coordinatorUrl:i,incomingRequestId:s});const d=Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(p=>String(p?.peer_device_id||"").trim()!==e.deviceId):[];_.pendingAcceptedSyncPeers=[...d,{peer_device_id:e.deviceId,name:l,fingerprint:e.fingerprint,addresses:[],claimed_local_actor:!1,status:{peer_state:"degraded"},last_error:"Waiting for the other device to approve this one."}],DW(e.deviceId);let u=n?{message:tJ,tone:"success"}:{message:`Step 1 complete on this device for ${e.displayName}. Finish onboarding on the other device so both sides trust each other for sync.`,tone:"success"};_.syncDiscoveredFeedback=u,n&&ld();try{t.trim()!==l.trim()&&(await Yh(e.deviceId,t.trim()),_.pendingAcceptedSyncPeers=_.pendingAcceptedSyncPeers.map(p=>String(p?.peer_device_id||"").trim()===e.deviceId?{...p,name:t.trim()}:p),n||(u={message:`Connected ${t.trim()} and saved its name.`,tone:"success"}))}catch(p){u={message:n?"Approval was sent, but naming did not finish. You do not need to approve again.":ct(p,"Device connected, but naming did not finish."),tone:"warning"}}_.syncDiscoveredFeedback=u;try{await In.loadSyncData()}catch(p){u={message:n?"Approval was sent. Confirmation may take up to 30 seconds, and you do not need to approve again.":ct(p,"Device connected, but the screen did not refresh yet. Refresh this page before trying the next step."),tone:"warning"},_.syncDiscoveredFeedback=u}return u}function lJ({pairedLocally:e,device:t,addressCount:n}){return e&&t.needs_local_approval!==!0?null:t.stale?{actionMessage:"Wait for a fresh coordinator presence update, then review this device again here.",mode:"stale"}:e||n>0?null:{actionMessage:"Wait for this device to publish a fresh address, then refresh and review it.",mode:"waiting-address"}}function dJ(e,t,n){if(e==="waiting-for-other-device")return t||"Waiting on the other device.";const r=String(n||"").toLowerCase();return r.includes("401")&&r.includes("unauthorized")?"Waiting for the other device to trust this one before sync can work.":null}function uJ(e,t){return e?jR.conflicts:t?jR.pairedLocally:"Not connected on this device"}function pJ(e){switch(e){case"cwd":return"Matched by folder";case"git_remote":return"Matched by git remote";case"workspace_id":return"Matched by workspace";case"project":return"Matched by project name";case"unmapped":return"Missing project identity";default:return`Matched by ${e.replace(/_/g," ")}`}}function Lo(e){const t=e.displayProject.toLowerCase();return t.includes("fatal:")||t.includes("not a git repository")||t==="unknown project"||e.identitySource==="unmapped"}function rI(e){return Lo(e)?"Unclear project identity":e.displayProject}function Yt(e){return(e.reassignableMemoryCount??e.memoryCount)>0}function fJ(e,t){return e.suggestedScopeId?` · suggested ${t.find(n=>n.scopeId===e.suggestedScopeId)?.label||"Space"}`:""}function mJ(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hJ(e,t){return t.find(n=>n.scopeId===e)?.label||"selected Space"}function vJ(e){switch(e){case"coordinator":return"Team Space";case"local":return"Local Space";default:return"Other Space"}}function gJ(e){if(!e)return"date unavailable";const t=new Date(e);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("en-US",{day:"numeric",month:"short",timeZone:"UTC",year:"numeric"}).format(t)}function yJ(e){return e.gitRemote?e.gitRemote:e.cwd?e.cwd:e.project?e.project:"source identity unavailable"}function bJ({group:e}){const t=e.memorySamples??[],n=t.length;return a("details",{className:"legacy-review-samples",children:[a("summary",{children:["Inspect affected memories",n?` (${n} sample${n===1?"":"s"})`:""]}),a("div",{className:"legacy-review-cleanup-note",children:"Showing representative memories from this project group before reassignment. Local memories can be reassigned; peer-owned memories stay in review on this device."}),t.length>0?a("ul",{className:"legacy-review-sample-list",children:t.map(r=>a("li",{className:"legacy-review-sample",children:[a("div",{className:"legacy-review-sample-title",children:r.title}),a("div",{className:"legacy-review-group-meta",children:[r.kind||"memory"," · ",gJ(r.updatedAt??r.createdAt)," ","·"," ",r.ownership==="local"?"local, reassignable":"peer-owned, stays in review"]}),r.bodyPreview?a("div",{className:"legacy-review-sample-body",children:r.bodyPreview}):null,a("div",{className:"legacy-review-group-meta mono",children:yJ(r)})]},r.id))}):a("div",{className:"legacy-review-cleanup-note",children:"No samples are available for this group. Refresh Sync and try again before reassigning."})]})}function iI(e,t,n){let r=(e instanceof Error?e.message:"Unable to reassign legacy review memories.").replace(/sharing domain/gi,"Space");return t&&(r=r.replace(new RegExp(`\\b${mJ(t)}\\b`,"g"),hJ(t,n))),r}function _J(e,t){const n=e.suggestedScopeId?t.find(r=>r.scopeId===e.suggestedScopeId)?.label:"";return[e.displayProject,e.identitySource,e.suggestedScopeId??"",n??"",e.suggestionReason??"",e.workspaceIdentity].join(" ").toLowerCase()}function wJ({item:e,onReview:t}){return a("div",{className:"actor-row",children:[a("div",{className:"actor-details",children:[a("div",{className:"actor-title",children:[a("strong",{children:e.peerName}),a("span",{className:"badge actor-badge",children:["person: ",e.actorDisplayName||e.actorId]})]}),a("div",{className:"peer-meta",children:[e.shareableCount," share by default · ",e.privateCount," marked Only me ·"," ",e.scopeLabel]})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:t,children:"Review my memories in Feed"})})]})}function SJ({item:e,onReassign:t,onReview:n}){const r=e.groups??[],i=e.targetScopes??[],o=Object.fromEntries(r.map(C=>[C.workspaceIdentity,C.suggestedScopeId??""])),[s,c]=T({}),[l,d]=T({}),[u,p]=T(o),[f,m]=T({}),[v,b]=T("all"),[g,y]=T(""),[S,w]=T(null),R=r.length,k=e.totalGroupCount??R,N=r.filter(Lo).length,j=r.filter(C=>C.suggestedScopeId&&!Lo(C)&&Yt(C)).length,E=r.filter(C=>f[C.workspaceIdentity]&&Yt(C)).length,F=r.filter(C=>f[C.workspaceIdentity]&&Yt(C)&&!!u[C.workspaceIdentity]).length,A=r.filter(C=>{const x=Lo(C);return v==="suggested"&&(!C.suggestedScopeId||x)||v==="cleanup"&&!x||v==="no-suggestion"&&(C.suggestedScopeId||x)||v==="selected"&&!f[C.workspaceIdentity]?!1:!g.trim()||_J(C,i).includes(g.trim().toLowerCase())});async function M(C){const x=u[C.workspaceIdentity]||C.suggestedScopeId||"";if(!(!x||!t||S)){w(C.workspaceIdentity),d(B=>{const U={...B};return delete U[C.workspaceIdentity],U});try{const B=await t(C,x,!!s[C.workspaceIdentity],s[C.workspaceIdentity]?.confirmation_token);c(B?U=>({...U,[C.workspaceIdentity]:B}):U=>{const ne={...U};return delete ne[C.workspaceIdentity],ne})}catch(B){d(U=>({...U,[C.workspaceIdentity]:iI(B,x,i)}))}finally{w(null)}}}function O(C,x){p(B=>({...B,[C.workspaceIdentity]:x})),c(B=>{const U={...B};return delete U[C.workspaceIdentity],U}),d(B=>{const U={...B};return delete U[C.workspaceIdentity],U})}function H(C,x){m(B=>({...B,[C.workspaceIdentity]:x}))}function V(C){m(x=>({...x,...Object.fromEntries(A.filter(Yt).map(B=>[B.workspaceIdentity,C]))}))}function W(){m(C=>({...C,...Object.fromEntries(r.filter(x=>x.suggestedScopeId&&!Lo(x)&&Yt(x)).map(x=>[x.workspaceIdentity,!0]))}))}async function $(){if(!t||S||F===0)return;const C=r.filter(x=>f[x.workspaceIdentity]&&Yt(x)&&!!u[x.workspaceIdentity]);if(!C.every(x=>s[x.workspaceIdentity])){w("bulk");try{for(const x of C){if(s[x.workspaceIdentity])continue;const B=u[x.workspaceIdentity]||x.suggestedScopeId||"";if(B)try{const U=await t(x,B,!1);d(ne=>{const ae={...ne};return delete ae[x.workspaceIdentity],ae}),U&&c(ne=>({...ne,[x.workspaceIdentity]:U}))}catch(U){d(ne=>({...ne,[x.workspaceIdentity]:iI(U,B,i)}))}}}finally{w(null)}}}return a("div",{className:"legacy-review-card",children:[a("div",{className:"legacy-review-header",children:[a("div",{children:[a("div",{className:"actor-title",children:[a("strong",{children:"Legacy shared review"}),a("span",{className:"badge badge-offline",children:"Needs project review"})]}),a("div",{className:"peer-meta legacy-review-summary",children:[k.toLocaleString()," older"," ",k===1?"project needs":"projects need"," a Space. They contain"," ",e.memoryCount.toLocaleString()," older shared memories total; review the projects, not individual memories.",R<k?` Showing ${R.toLocaleString()} projects; open Projects to review the rest.`:""]}),a("div",{className:"peer-meta legacy-review-warning",children:"Fix peer-owned projects on their source device. Reassignment updates future sync authorization; online compatible peers should converge after syncing, but offline devices, backups, copied databases, malicious peers, or old versions may retain old copies."})]}),a("div",{className:"actor-actions",children:a("button",{type:"button",className:"settings-button",onClick:n,children:"Manage all projects"})})]}),a("div",{className:"legacy-review-toolbar",children:[a("div",{className:"legacy-review-filter-row",children:[["all",`Showing ${R.toLocaleString()}`],["suggested",`Suggested ${j.toLocaleString()}`],["cleanup",`Needs cleanup ${N.toLocaleString()}`],["no-suggestion","No suggestion"],["selected",`Selected ${F.toLocaleString()}`]].map(([C,x])=>a("button",{className:v===C?"settings-button legacy-filter active":"settings-button legacy-filter",onClick:()=>b(C),type:"button",children:x},C))}),a("div",{className:"legacy-review-bulk-row",children:[a("input",{"aria-label":"Search legacy project groups",className:"peer-scope-input legacy-review-search",onInput:C=>y(C.currentTarget.value),placeholder:"Search project, signal, or destination…",value:g}),a("button",{className:"settings-button",onClick:()=>V(!0),type:"button",children:"Select visible"}),a("button",{className:"settings-button",onClick:W,type:"button",children:"Select suggested"}),a("button",{className:"settings-button",onClick:()=>V(!1),type:"button",children:"Clear visible"}),t&&i.length>0?a("button",{className:"settings-save",disabled:S!=null||F===0||r.filter(C=>f[C.workspaceIdentity]&&Yt(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity]),onClick:()=>{$()},type:"button",children:S==="bulk"?"Previewing…":`Preview ${F.toLocaleString()} selected`}):t&&E>0?a("span",{className:"legacy-review-cleanup-note",children:"Add or join a Space before bulk reassignment."}):null,F>0&&r.filter(C=>f[C.workspaceIdentity]&&Yt(C)&&!!u[C.workspaceIdentity]).every(C=>s[C.workspaceIdentity])?a("span",{className:"legacy-review-cleanup-note",children:"Bulk actions only preview. Confirm each project individually to avoid partial reassignment."}):null]})]}),r.length>0?a("ul",{className:"legacy-review-groups","aria-label":"Legacy shared review project groups",children:A.map(C=>a("li",{className:"legacy-review-group",children:[a("div",{className:"legacy-review-group-main",children:[a("div",{className:"legacy-review-title-wrap",children:[a("input",{"aria-label":`Select ${rI(C)}`,checked:!!f[C.workspaceIdentity],className:"cm-checkbox",disabled:!Yt(C),onChange:x=>H(C,x.currentTarget.checked),type:"checkbox"}),a("div",{children:[a("div",{className:"legacy-review-group-title",children:rI(C)}),a("div",{className:"legacy-review-group-meta",children:[pJ(C.identitySource),fJ(C,i)]}),Yt(C)?C.peerOwnedMemoryCount?a("div",{className:"legacy-review-cleanup-note",children:[(C.reassignableMemoryCount??C.memoryCount).toLocaleString()," ","local memor",(C.reassignableMemoryCount??C.memoryCount)===1?"y":"ies"," ","can be reassigned; ",C.peerOwnedMemoryCount.toLocaleString()," peer-owned memor",C.peerOwnedMemoryCount===1?"y":"ies"," will stay in review."]}):null:a("div",{className:"legacy-review-cleanup-note",children:"Peer-owned only. These older memories were received from another device, so this device cannot reassign them to a Space. Assign this project to a Space on the source device; after sync, this review should clear here."}),Lo(C)?a("div",{className:"legacy-review-cleanup-note",children:"Inspect or correct the project identity before assigning old shared data to a Space."}):null]})]}),a("span",{className:"legacy-review-count",children:[C.memoryCount.toLocaleString()," memor",C.memoryCount===1?"y":"ies"]})]}),C.suggestionReason?a("div",{className:"legacy-review-reason",children:C.suggestionReason}):null,l[C.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:l[C.workspaceIdentity]}):null,s[C.workspaceIdentity]?a("div",{className:"legacy-review-confirmation",role:"alert",children:[s[C.workspaceIdentity].warning," This will reassign"," ",s[C.workspaceIdentity].reassignable_memory_count.toLocaleString()," of"," ",s[C.workspaceIdentity].memory_count.toLocaleString()," memories",s[C.workspaceIdentity].skipped_memory_count?`; ${s[C.workspaceIdentity].skipped_memory_count.toLocaleString()} peer-owned copies will be left unchanged`:"","."]}):null,a(bJ,{group:C}),i.length>0&&t&&Yt(C)?a("label",{className:"legacy-review-target",children:[a("span",{children:"Destination Space"}),a("select",{className:"peer-scope-input",disabled:S!=null,onChange:x=>O(C,x.currentTarget.value),value:u[C.workspaceIdentity]||"",children:[a("option",{value:"",children:"Choose Space…"}),i.map(x=>a("option",{value:x.scopeId,children:[x.label," · ",vJ(x.authorityType),x.scopeId===C.suggestedScopeId?" · suggested":""]},x.scopeId))]})]}):null,i.length>0&&t&&Yt(C)?a("div",{className:"legacy-review-actions",children:a("button",{type:"button",className:"settings-button",disabled:S!=null||!u[C.workspaceIdentity],onClick:()=>{M(C)},children:S===C.workspaceIdentity?s[C.workspaceIdentity]?"Reassigning…":"Previewing…":s[C.workspaceIdentity]?"I understand, reassign memories":"Preview reassignment"})}):null]},C.workspaceIdentity))}):null]})}function CJ({items:e,legacyReview:t,onLegacyReassign:n,onLegacyReview:r,onReview:i}){return a(G,{children:[t?a(SJ,{item:t,onReassign:n,onReview:r??i}):null,e.map(o=>a(wJ,{item:o,onReview:i},`${o.peerName}:${o.actorId}:${o.scopeLabel}`))]})}function RJ(){hp("mine"),_.feedQuery="",window.location.hash="feed"}function IJ(){window.location.hash="projects"}async function kJ(e,t,n,r){try{const i=await IN({...r?{confirmation_token:r}:{},confirmed_old_copies:n,scope_id:t,workspace_identity:e.workspaceIdentity});return _.lastSyncLegacySharedReview=i.legacy_shared_review??null,Y(`Reassigned ${i.reassigned_memory_count.toLocaleString()} legacy review memor${i.reassigned_memory_count===1?"y":"ies"} to ${i.target_scope_label}.`),oI(),null}catch(i){if(i instanceof Xh)return i.preview;const o=i instanceof Error?i.message:"Unable to reassign legacy review memories.";throw Y(o,"warning"),new Error(o)}}function oI(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewMeta"),n=document.getElementById("syncSharingReviewList");if(!e||!t||!n)return;const r=e.querySelector(".settings-group-title"),i=Array.isArray(_.lastSyncSharingReview)?_.lastSyncSharingReview:[],o=_.lastSyncLegacySharedReview,s=Math.max(0,Number(o?.memory_count??0)),c=o?.has_data?{groups:Array.isArray(o.groups)?o.groups.map(u=>{const p=u;return{displayProject:String(p.display_project||p.project||"Unknown project"),identitySource:String(p.identity_source||"unknown"),lastUpdatedAt:typeof p.last_updated_at=="string"?p.last_updated_at:null,memoryCount:Number(p.memory_count||0),memorySamples:Array.isArray(p.memory_samples)?p.memory_samples.map(f=>{const m=f,v=m.ownership==="peer"?"peer":"local";return{bodyPreview:typeof m.body_preview=="string"?m.body_preview:null,createdAt:typeof m.created_at=="string"?m.created_at:null,cwd:typeof m.cwd=="string"?m.cwd:null,gitRemote:typeof m.git_remote=="string"?m.git_remote:null,id:Number(m.id||0),kind:typeof m.kind=="string"?m.kind:null,ownership:v,project:typeof m.project=="string"?m.project:null,title:String(m.title||`Memory ${Number(m.id||0)}`),updatedAt:typeof m.updated_at=="string"?m.updated_at:null}}):[],peerOwnedMemoryCount:Number(p.peer_owned_memory_count||0),reassignableMemoryCount:Number(p.reassignable_memory_count||0),suggestedScopeId:typeof p.suggested_scope_id=="string"?p.suggested_scope_id:null,suggestionReason:typeof p.suggestion_reason=="string"?p.suggestion_reason:null,workspaceIdentity:String(p.workspace_identity||p.display_project||"unknown")}}):[],memoryCount:s,scopeId:String(o.scope_id||"legacy-shared-review"),totalGroupCount:Number(o.total_group_count||o.groups?.length||0),targetScopes:Array.isArray(o.target_scopes)?o.target_scopes.map(u=>{const p=u;return{authorityType:String(p.authority_type||"unknown"),label:String(p.label||p.scope_id||"Unknown domain"),scopeId:String(p.scope_id||"")}}).filter(u=>u.scopeId):[]}:null;if(!i.length&&!c){xo(n),e.hidden=!0;return}e.hidden=!1,r&&(r.textContent=c?"Sharing review":"What teammates will receive");const l=_.currentProject?`current project (${_.currentProject})`:"all allowed projects";t.textContent=c?`Review conservative upgrade state before promoting historical shared data. Teammates receive memories from ${l} by default once Sharing-domain grants allow it.`:`Teammates receive memories from ${l} by default. Use Only me on a memory when it should stay local.`;const d=i.map(u=>({actorDisplayName:String(u.actor_display_name||u.actor_id||"unknown"),actorId:String(u.actor_id||"unknown"),peerName:String(u.peer_name||u.peer_device_id||"Device"),privateCount:Number(u.private_count||0),scopeLabel:String(u.scope_label||"All allowed projects"),shareableCount:Number(u.shareable_count||0)}));dt(n,h(CJ,{items:d,legacyReview:c,onLegacyReassign:kJ,onLegacyReview:IJ,onReview:RJ}))}var dd="";function NJ(e){if(!e)return;const t=String(e?.coordinator_url||"").trim(),n=!!(e.lookup_error||e.reciprocal_approval_error),r=Array.isArray(e?.discovered_devices)?e.discovered_devices:[],i=new Map;for(const o of r){const s=String(o.device_id||"").trim();s&&i.set(s,[...i.get(s)||[],o])}for(const[o,s]of _.pendingCoordinatorApprovalsByDeviceId){if(s.coordinatorUrl!==t){_.pendingCoordinatorApprovalsByDeviceId.delete(o);continue}if(n)continue;const c=i.get(o);c&&(c.some(l=>String(l.incoming_reciprocal_request_id||"").trim()===s.incomingRequestId&&l.needs_local_approval===!0)||_.pendingCoordinatorApprovalsByDeviceId.delete(o))}}function PJ(){return[..._.pendingCoordinatorApprovalsByDeviceId].map(([e,t])=>[e,t.coordinatorUrl,t.incomingRequestId]).sort(([e],[t])=>e.localeCompare(t))}var Ss=null,lh=0,dh=null,uh=0,ph=null,TJ=15e3;function aI(e){return`project:${e||""}|includeJoinRequests:false`}function AJ(e){const t=aI(e);return!Ss||Ss.key!==t||Date.now()>=Ss.expiresAtMs?null:Ss.payload}function EJ(e,t){Ss={key:aI(e),expiresAtMs:Date.now()+TJ,payload:t}}function xJ(e){return!e||typeof e!="object"?e:{...e,join_requests:[]}}function DJ(){const e=document.getElementById("syncSharingReview"),t=document.getElementById("syncSharingReviewList"),n=document.getElementById("syncSharingReviewMeta"),r=document.getElementById("syncLegacyClaims"),i=document.getElementById("syncLegacyClaimsMeta");e&&(e.hidden=!0),t&&(t.textContent=""),n&&(n.textContent=""),r&&(r.hidden=!0),i&&(i.textContent="")}async function jJ(e,t){if(_.activeTab==="health"&&!t.requireFreshSyncStatus){const r=AJ(e);if(r)return{payload:r,fetchedFreshSyncStatus:!1}}const n=!ba();return{payload:await Od(n,e,{includeJoinRequests:!1,signal:t.signal}),fetchedFreshSyncStatus:!0}}function LJ(e){return e.requiredSurface!=="all"?!0:e.actorLoadError||e.coordinatorAdminLoadError||e.shareOperationsLoadError?!1:!e.requiresDeviceIdentityInventory||!e.deviceIdentityInventoryLoadError}async function OJ(e){const t=OW();let n=null,r=null,i=_.lastDeviceIdentityInventory,o=_.lastShareOperations,s=!1,c=!1,l=_.deviceIdentityInventoryLoadError,d=!1;try{n=await Mk({signal:e.signal})}catch{s=!0}try{r=await Dd({signal:e.signal})}catch{c=!0}if(_.activeTab==="advanced"){l=!1;try{i=await Ud({signal:e.signal})}catch{l=!0}}try{const u=await dv({signal:e.signal});o=Array.isArray(u.items)?u.items:[]}catch{d=!0}return{actorsPayload:n,coordinatorAdminStatus:r,deviceIdentityInventory:i,shareOperations:o,actorLoadError:s,coordinatorAdminLoadError:c,deviceIdentityInventoryLoadError:l,shareOperationsLoadError:d,duplicatePersonDecisions:t}}function ud(e={}){const t=$J(++lh,{requiredSurface:e.requiredSurface??"all",requireFreshSyncStatus:e.requireFreshSyncStatus??!1,signal:e.signal});return dh=t,t}async function $J(e,t){try{const n=_.currentProject||"",{payload:r,fetchedFreshSyncStatus:i}=await jJ(n,t);if(t.signal?.aborted)return!1;const{actorsPayload:o,coordinatorAdminStatus:s,deviceIdentityInventory:c,shareOperations:l,actorLoadError:d,coordinatorAdminLoadError:u,deviceIdentityInventoryLoadError:p,shareOperationsLoadError:f,duplicatePersonDecisions:m}=await OJ(t);if(e!==lh)return dh??!1;if(t.signal?.aborted)return!1;const v=LJ({requiredSurface:t.requiredSurface,actorLoadError:d,coordinatorAdminLoadError:u,shareOperationsLoadError:f,requiresDeviceIdentityInventory:_.activeTab==="advanced",deviceIdentityInventoryLoadError:p});i&&EJ(n,xJ(r)),NJ(r.coordinator);const b=JSON.stringify([r,o,s,c,p,l,f,m,PJ()]);if(b===dd)return v;dd=b;const g=r.status&&typeof r.status=="object"?r.status:null;g&&(_.lastSyncStatus=g),Array.isArray(o?.items)?_.lastSyncActors=o.items:_.lastSyncActors=[];const y=Array.isArray(r.peers)?r.peers:[],S=new Set(y.map(R=>String(R?.peer_device_id||"").trim()).filter(Boolean)),w=Array.isArray(_.pendingAcceptedSyncPeers)?_.pendingAcceptedSyncPeers.filter(R=>{const k=String(R?.peer_device_id||"").trim();return k&&!S.has(k)}):[];return _.pendingAcceptedSyncPeers=w,_.lastSyncPeers=[...y,...w],p||(_.lastDeviceIdentityInventory=c),_.deviceIdentityInventoryLoadError=p,_.lastShareOperations=l,_.shareOperationsLoadError=f,_.lastSyncSharingReview=r.sharing_review||[],_.lastSyncLegacySharedReview=r.legacy_shared_review&&typeof r.legacy_shared_review=="object"?r.legacy_shared_review:null,_.lastSyncCoordinator=r.coordinator||null,_.lastSyncCoordinatorAdminStatus=s&&typeof s=="object"?s:null,_.lastSyncJoinRequests=Array.isArray(r.join_requests)?r.join_requests:[],_.lastSyncAttempts=r.attempts||[],_.lastSyncLegacyDevices=r.legacy_devices||[],_.lastSyncDuplicatePersonDecisions=m,_.lastSyncViewModel=TW({actors:_.lastSyncActors,peers:_.lastSyncPeers,coordinator:_.lastSyncCoordinator,status:g,shareOperations:_.lastShareOperations,shareOperationsLoadError:f,reconciliation:r.recipient_policy_reconciliation,duplicatePersonDecisions:_.lastSyncDuplicatePersonDecisions}),HR(),ld(),N3(),T3(),oI(),rh(),QR(),GR(),FJ(),d&&P3(),u&&(_.lastSyncCoordinatorAdminStatus=null,ld()),v}catch{return t.signal?.aborted?!1:e!==lh?dh??!1:(dd="",_.deviceIdentityInventoryLoadError=!0,MJ(),!1)}}function MJ(){Er("syncTeamSkeleton"),Er("syncActorsSkeleton"),Er("syncPeersSkeleton"),Er("syncDiagSkeleton"),DJ(),ZR();const e=document.getElementById("syncSetupPanel"),t=document.getElementById("syncJoinPanel");e&&(e.hidden=!1),t&&(t.hidden=!1),A3(),VW()}function FJ(){if(_.activeTab==="health"){hm();return}VS()}function BJ(){dd="",_.lastSyncPeers?.length&&rh()}async function pd(){await ud()}function qJ(e={}){const t=UJ(++uh,e.signal);return ph=t,t}async function UJ(e,t){try{const n=await Fk(!1,{signal:t});return t?.aborted?!1:e!==uh?ph??!1:(_.pairingPayloadRaw=n||null,Qm(),!0)}catch{return t?.aborted?!1:e!==uh?ph??!1:(_.pairingPayloadRaw=null,Qm(),!1)}}function GJ(e){mz(),nl(),j3(pd),k3(pd),YW(rh),q3(e,pd),E3(pd),QW(e),ih(),D3()}function HJ(e,t){const n=nt("runtimeLabel");n&&(n.textContent=t?`v${e} (${t})`:`v${e}`,n.title=t?`codemem ${e} (${t})`:`codemem ${e}`,n.hidden=!1)}async function VJ(){try{const e=await gk();if(!e?.version)return;HJ(e.version,"80e3126")}catch{}}var fh=null,sI=1500,Cs=V0(),cI="codemem-legacy-upgrade-notice-dismissed",jr=null,cn=!1,fd=!1,mh=!1;function lI(e,t=0){const n=Number(e);return Number.isFinite(n)?Math.max(0,n):t}function dI(e){if(!e||typeof e!="object")return null;const t=e.legacy_shared_review??e;if(!t||typeof t!="object")return null;const n=t;if(n.has_data!==!0)return null;const r=Array.isArray(n.groups)?n.groups:[],i=lI(n.total_group_count,r.length),o=lI(n.memory_count);return i<=0||o<=0?null:{groupCount:i,memoryCount:o}}function uI(){try{return localStorage.getItem(cI)==="1"}catch{return!1}}function KJ(){if(document.getElementById("legacyUpgradeDontShow")?.checked)try{localStorage.setItem(cI,"1")}catch{}}function zJ(e,t){e&&t?Qx(t):Xx()}function pI(e){!e||mh||uI()||(mh=!0,Uy(()=>zJ(!0,e)))}async function WJ(){if(!(mh||uI()))try{pI(dI(await Od(!1,"",{includeJoinRequests:!1})))}catch{}}function Ri(e,t){_.viewerReconnectOpen=e;const n=nt("viewerReconnectOverlay"),r=nt("viewerReconnectDetail");!n||!r||(n.hidden=!e,r.textContent=t||"Trying again automatically while the viewer comes back.",_.activeTab==="feed"&&Cn(!0))}async function hh(){try{return await vk(),!0}catch{return!1}}function vh(){return document.visibilityState!=="hidden"&&!YC()}function fI(){return`${_.activeTab}:${_.advancedSection}:${_.syncPairingOpen}`}function JJ(e){_.refreshQueued||e.surface!==fI()||!e.refreshSucceeded||!fd||cn||(fd=!1,zu("connection_restored"))}function mI(){if(cn)return;cn=!0,fd=!0,zu("connection_lost"),gh(),Uy(),Lr("error","(reconnecting)"),Ri(!0,"The viewer server is restarting or temporarily unavailable. Trying again automatically…");const e=async()=>{if(await hh()){if(jr&&(clearTimeout(jr),jr=null),cn=!1,Ri(!0,"Viewer responded. Restoring your session…"),vh()){Lr("refreshing"),Rs();try{await gd()}catch{}}else Lr("paused",document.visibilityState==="hidden"?"(tab hidden)":"(settings open)");cn||Ri(!1);return}Ri(!0,"Still reconnecting… the viewer will recover automatically as soon as the server responds."),jr=setTimeout(e,sI)};jr=setTimeout(e,sI)}function Lr(e,t){_.refreshState=e;const n=nt("refreshStatus");if(!n)return;n.dataset.refreshState=e;const r=o=>{const s=nt("refreshAnnouncer");!s||fh===e||(s.textContent=o,fh=e)};if(e==="refreshing"){n.textContent="refreshing…";return}if(e==="paused"){n.textContent="paused",r("Auto refresh paused.");return}if(e==="error"&&t==="(reconnecting)"){n.textContent="reconnecting…",r("Viewer reconnecting.");return}if(e==="error"){n.textContent="refresh failed",r("Refresh failed.");return}const i=t?` ${t}`:"";n.textContent=`updated ${new Date().toLocaleTimeString()}${i}`,fh=null}function gh(){El(),Cs.cancel(),Oo&&(clearTimeout(Oo),Oo=null),_.refreshQueued=!1,_.refreshTimer&&(clearInterval(_.refreshTimer),_.refreshTimer=null)}function hI(){gh(),Lr("paused")}function Rs(){_.refreshTimer||(_.refreshTimer=setInterval(()=>Or(),5e3))}document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?(gh(),Lr("paused","(tab hidden)")):!YC()&&!cn&&(Rs(),Or())});var md=!1;function vI(){const e=_.advancedSection==="sync",t=nt("advancedSyncContent"),n=nt("advancedTeamsContent");t&&(t.hidden=!e),n&&(n.hidden=e);const r=nt("advancedTabsMount");r&&$D(r,_.advancedSection,YJ),queueMicrotask(()=>{const i=window.location.hash.replace(/^#/,"");if(!e&&md){md=!1;const o=document.getElementById("advancedAdministrationDisclosure");o instanceof HTMLDetailsElement&&(o.open=!0),document.getElementById("coordinatorAdminHeading")?.focus()}ih(i==="sync/diagnostics"||i==="advanced/sync/diagnostics"?"diagnostics":"main")})}function YJ(e,t={}){Rb(e,!0),vI(),e==="teams"&&t.focusContent&&queueMicrotask(()=>document.getElementById("coordinatorAdminHeading")?.focus())}var QJ=oD();function gI(e){const t=new Set(J0(_.lastCoordinatorAdminStatus));Yr.forEach(r=>{const i=nt(`tab-${r}`);i&&(i.hidden=r!==e||!t.has(r))}),Yr.forEach(r=>{const i=nt(`tabBtn-${r}`);if(!i)return;i.hidden=!t.has(r);const o=r===e&&t.has(r);i.classList.toggle("active",o),o?i.setAttribute("aria-current","page"):i.removeAttribute("aria-current")});const n=nt(`tabBtn-${e}`);n&&QJ(n),e==="advanced"&&vI()}function kn(e,t={}){El(),Cs.cancel();const n=ya(e,_.lastCoordinatorAdminStatus);n==="advanced"&&Rb(t.advancedSection??mp()??_.advancedSection),Ib(n,t.canonicalHash?{canonicalHash:!0}:{}),n==="health"&&li("settings-health"),gI(n),Or()}function XJ(){window.addEventListener("codemem:navigate-advanced-sync",tY),Yr.forEach(e=>{nt(`tabBtn-${e}`)?.addEventListener("click",()=>kn(e,e==="advanced"?{canonicalHash:!0,advancedSection:"sync"}:{canonicalHash:!0}))}),nt("syncTurnOnButton")?.addEventListener("click",()=>{JC("sync"),vR(hI)}),nt("advancedTeamSettingsLink")?.addEventListener("click",e=>{e.preventDefault(),Uu("teams"),kn("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),nt("advancedSharingLink")?.addEventListener("click",e=>{e.preventDefault(),Uu("invitations"),kn("sharing",{canonicalHash:!0}),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus())}),window.addEventListener("hashchange",()=>{const e=fp();if(e){const t=mp();md=Cb(),kn(e,t?{advancedSection:t}:{}),e==="advanced"&&t==="teams"&&queueMicrotask(()=>document.getElementById("coordinatorAdminHeading")?.focus())}}),md=Cb(),kn(_.activeTab)}async function ZJ(){try{const e=await Ts();_.knownProjects=e,BJ();const t=up("projectFilter");if(!t)return;t.textContent="";const n=document.createElement("option");n.value="",n.textContent="All Projects",t.appendChild(n),e.forEach(r=>{const i=document.createElement("option");i.value=r,i.textContent=r,t.appendChild(i)})}catch{}}function eY(e){_.pendingDeviceIdentityFocus=e?.trim()||null,kn("devices",{canonicalHash:!0})}function tY(){kn("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("advancedSyncButton")?.focus())}var hd=UE({},{onOpenTeamSetup:fC,onReviewDevices:eY}),yI={version:1,identities:[],teams:[],teamMemberships:[],identityDevices:[],projectRecipients:[]},yh=0,bh=null,Vt=null;async function nY(e={}){const t=[];let n=0;for(;;){const r=await Ho({limit:250,offset:n,signal:e.signal});if(t.push(...r.projects),!r.has_more)break;n+=r.limit}return nc(t)}function rY(){const e=new Map,t={unknown:0,offline:1,available:2},n=(r,i)=>{!r||t[i]<=t[e.get(r)??"unknown"]||e.set(r,i)};for(const r of _.lastSyncCoordinator?.discovered_devices??[])n(String(r.device_id??"").trim(),r.stale?"unknown":"available");for(const r of _.lastSyncPeers){const i=String(r.peer_device_id??"").trim(),o=_s(r);n(i,o==="connected"||o==="available"?"available":o==="offline"?"offline":"unknown")}return[...e].map(([r,i])=>({deviceId:r,state:i}))}function iY(){return _.lastSyncPeers.flatMap(e=>{const t=String(e.peer_device_id??"").trim();return t?[{deviceId:t,runtimeVersion:e.runtime_version??null,runtimeVersionObservedAt:e.runtime_version_observed_at??null}]:[]})}function bI(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:null}function oY(e){return _.lastSyncPeers.flatMap(t=>{const n=String(t.peer_device_id??"").trim();if(!n)return[];const r=t.has_error?"error":t.status?.sync_status,i=["ok","error","stale"].includes(r??"")?r:"unknown";return[{deviceId:n,paired:t.pinned===!0,status:i,lastSyncAt:t.last_sync_at??t.status?.last_sync_at??null,recentIn:bI(t.recent_ops?.in),recentOut:bI(t.recent_ops?.out),statusAvailable:e}]})}async function aY(e){try{const t=await Gd({peerDeviceId:e});if(t.items.length!==1||t.items[0]?.peer_device_id!==e)return{message:"This device is no longer paired here. Refresh Devices before retrying.",tone:"warning"};const n=Bm(t),r=await vd();return{message:r?n.message:`${n.message} Refresh Devices to see the latest sync status.`,tone:n.ok&&!n.warning&&r?"success":"warning"}}catch(t){return t instanceof Error&&/\bsync_disabled\b/.test(t.message)?{message:"Device sync is off. Turn it on in Settings → Device Sync, then try again.",tone:"warning"}:{message:ct(t,"Could not sync this device. Check its pairing and try again."),tone:"warning"}}}function sY(e){if(e==="advanced_sync"){kn("advanced",{advancedSection:"sync"}),queueMicrotask(()=>document.getElementById("tabBtn-advanced")?.focus());return}if(e==="sharing_teams"){kn("sharing",{canonicalHash:!0}),Uu("teams"),queueMicrotask(()=>document.getElementById("tabBtn-sharing")?.focus());return}kn(e,{canonicalHash:!0}),queueMicrotask(()=>document.getElementById(`tabBtn-${e}`)?.focus())}function vd(e={}){const t=document.getElementById("devicesMount");if(!t||e.deferWhileRenaming&&document.activeElement?.closest(".devices-rename-form"))return Promise.resolve(!0);const n=dY(t,++yh,e);return bh=n,n}async function cY(){const[e,t]=await Promise.all([vd(),hd()]);return e&&t}function _I(){return{localDeviceId:_.lastSyncStatus?.device_id??void 0,onCommitted:cY,onNavigate:sY,onRetry:()=>{vd()},onSyncDevice:aY}}function lY(e){if(!Vt){cl(e,yI,{version:1,items:[]},[],[],{loadError:!0});return}cl(e,Vt.intent,Vt.reconciliation,Vt.projects,Vt.availability,{..._I(),coordinatorEnrollmentIssueCount:Vt.coordinatorEnrollmentIssueCount,inventory:Vt.inventory,inventoryUnavailable:Vt.inventoryUnavailable,peerRuntimeMetadata:Vt.peerRuntimeMetadata,peerSyncMetadata:Vt.peerSyncMetadata,refreshError:!0})}async function dY(e,t,n){Vt||cl(e,yI,{version:1,items:[]},[],[],{loading:!0});try{const[r,i,o,s,c]=await Promise.all([nY(n),qd(n),sN(n),Ud(n).then(f=>({inventory:f,unavailable:!1})).catch(()=>({inventory:Vt?.inventory,unavailable:!0})),ud({requiredSurface:"devices",signal:n.signal})]);if(n.signal?.aborted)return!1;if(t!==yh)return bh??!1;const l=rY(),d=iY(),u=oY(c),p=pv(_.lastSyncStatus);return!s.unavailable&&s.inventory&&(_.lastDeviceIdentityInventory=s.inventory),_.deviceIdentityInventoryLoadError=s.unavailable,cl(e,i,o,r,l,{..._I(),inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:p,peerRuntimeMetadata:d,peerSyncMetadata:u,syncStatusUnavailable:!c}),Vt={projects:r,intent:i,reconciliation:o,availability:l,peerRuntimeMetadata:d,peerSyncMetadata:u,inventory:s.inventory,inventoryUnavailable:s.unavailable,coordinatorEnrollmentIssueCount:p},c}catch{return n.signal?.aborted?!1:t!==yh?bh??!1:(lY(e),!1)}}up("projectFilter")?.addEventListener("change",()=>{Cs.cancel(),El(),_.currentProject=up("projectFilter")?.value||"",li("scope"),Cn(!0),Or()});var Oo=null;async function uY(e){await Promise.all([j2({signal:e.signal}),rK({signal:e.signal}),Vx().catch(()=>{})])}function pY(e,t,n,r){if(t!=="health"&&VS(),t==="feed"){const s=Y$();e.push(J_(s,{signal:r.signal}),um({signal:r.signal}))}if(t==="projects"&&e.push(To({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="sharing"&&e.push(hd({awaitTeamSetupSummary:!0,signal:r.signal}).then(n)),t==="devices"&&e.push(vd({deferWhileRenaming:!0,signal:r.signal}).then(n)),t==="health"&&e.push(L2({signal:r.signal}),ud({requiredSurface:"health",requireFreshSyncStatus:fd,signal:r.signal}).then(n)),t==="advanced"&&_.advancedSection==="sync"&&e.push(ud({signal:r.signal}).then(n)),t==="advanced"&&_.advancedSection==="teams"&&e.push(ol({deferWhileRenaming:!0,signal:r.signal}).then(n)),!_.syncPairingOpen)return;const i=t==="advanced"&&_.advancedSection==="sync",o=qJ({signal:r.signal});e.push(i?o.then(n):o)}async function Or(){cn||(Oo&&clearTimeout(Oo),Oo=setTimeout(()=>gd(),80))}async function fY(e,t){if(!t.isCurrent()&&!Oh(e))return;const n=await hh();t.isOwned()&&(n?Lr("error"):mI())}function mY(e){Cs.finish(e),_.refreshInFlight=!1,!(!_.refreshQueued||cn||!vh())&&(_.refreshQueued=!1,gd())}async function gd(){if(cn||!vh())return;if(_.refreshInFlight){_.refreshQueued=!0;return}_.refreshInFlight=!0;const e=Cs.begin();try{Lr("refreshing");const t=_.activeTab,n=fI(),r=[uY(e)];let i=!0;if(pY(r,t,s=>{i=i&&s},e),await Go(Promise.all(r),e.signal),!e.isCurrent()){if(Oh(e.signal.reason))throw e.signal.reason;return}pI(dI(_.lastSyncLegacySharedReview)),t==="feed"&&Cn(!0);const o=ya(_.activeTab,_.lastCoordinatorAdminStatus);o!==_.activeTab&&(El(),Ib(o)),gI(_.activeTab),Lr(i?"idle":"error"),JJ({refreshSucceeded:i,surface:n})}catch(t){await fY(t,e)}finally{mY(e)}}rD();var wI=document.getElementById("toastRoot");wI&&G0(wI);var SI=document.getElementById("diagnosticsDrawerMount");SI&&Hx(SI);var CI=document.getElementById("legacyTeamSetupMount");CI&&OG(CI,{onCompleted:async()=>{let e,t;const n={requireTeamSetupSummary:!0};if(_.activeTab==="sharing"?(t=await To(n),e=await hd(n)):(e=await hd(n),t=await To(n)),!e||!t)throw new Error("team_setup_refresh_failed")}});var RI=document.getElementById("legacyUpgradeDialogMount");RI&&Yx(RI,{onDismiss:KJ,onReviewGroups:()=>{window.location.hash="sync",setTimeout(()=>document.getElementById("syncSharingReview")?.scrollIntoView({block:"start"}),120)},onReviewProjects:()=>{window.location.hash="projects"}}),aD(Sc("themeToggle")),Tb(gp()),XJ(),vU(),Kx(),MV(()=>Or(),{onOpenTeamSetup:fC}),GJ(()=>Or()),rM(),pz(hI,Rs,()=>Or()),ZJ(),nt("viewerReconnectRetry")?.addEventListener("click",async()=>{if(zu("reconnect_requested"),Ri(!0,"Checking whether the viewer server is back…"),!await hh()){mI();return}jr&&(clearTimeout(jr),jr=null),cn=!1,Ri(!0,"Viewer responded. Restoring your session…"),Rs();try{await gd()}catch{}cn||Ri(!1)}),VJ(),WJ(),Or(),Rs()})();