@taskforcehq/taskforce 0.3.327 → 0.3.328

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/dist/Taskforce.module.css +24 -53
  2. package/dist/components/activity/EntityActivityTimeline.js +15 -5
  3. package/dist/components/context/AttachmentPreviewHost.js +1 -1
  4. package/dist/components/context/ContextAttachmentManager.d.ts +3 -0
  5. package/dist/components/context/ContextAttachmentManager.js +116 -20
  6. package/dist/components/features/planning/PlanningEntitySummary.d.ts +3 -1
  7. package/dist/components/features/planning/PlanningEntitySummary.js +3 -2
  8. package/dist/components/features/planning/PlanningLinkPicker.d.ts +3 -1
  9. package/dist/components/features/planning/PlanningLinkPicker.js +5 -3
  10. package/dist/components/features/planning/PlanningModule.js +26 -9
  11. package/dist/components/features/planning/PlanningVisualIdentity.d.ts +14 -0
  12. package/dist/components/features/planning/PlanningVisualIdentity.js +106 -0
  13. package/dist/components/features/planning/planningWorkspaceModel.d.ts +11 -0
  14. package/dist/components/task/TaskActionHeader.d.ts +2 -1
  15. package/dist/components/task/TaskActionHeader.js +2 -2
  16. package/dist/components/task/TaskCard.js +37 -4
  17. package/dist/components/task/TaskContextUpload.d.ts +3 -0
  18. package/dist/components/task/TaskContextUpload.js +2 -2
  19. package/dist/components/task/TaskForm.d.ts +4 -0
  20. package/dist/components/task/TaskForm.js +32 -7
  21. package/dist/components/task/TaskImageReviews.js +16 -16
  22. package/dist/components/task/TaskStatusActions.js +11 -2
  23. package/dist/components/task/TaskWorkstreamPicker.js +2 -1
  24. package/dist/components/ui/DocumentTypeIcon.d.ts +7 -0
  25. package/dist/components/ui/DocumentTypeIcon.js +8 -0
  26. package/dist/components/ui/TaxonomyDropdown.d.ts +9 -1
  27. package/dist/components/ui/TaxonomyDropdown.js +30 -3
  28. package/dist/components/views/StandaloneLayout.js +62 -9
  29. package/dist/components/views/WidgetView.js +8 -5
  30. package/dist/components/views/panels/PlanningDrawer.d.ts +7 -1
  31. package/dist/components/views/panels/PlanningDrawer.js +48 -44
  32. package/dist/config/envSchema.js +1 -0
  33. package/dist/config/localServiceCloudTarget.d.ts +10 -0
  34. package/dist/config/localServiceCloudTarget.js +76 -0
  35. package/dist/core/AiProfileService.d.ts +1 -0
  36. package/dist/core/AiProfileService.js +2 -1
  37. package/dist/core/AttachmentLinkService.js +7 -4
  38. package/dist/core/DeletedTaskLifecycleService.d.ts +4 -0
  39. package/dist/core/DeletedTaskLifecycleService.js +21 -0
  40. package/dist/core/McpTokenService.d.ts +4 -0
  41. package/dist/core/McpTokenService.js +52 -0
  42. package/dist/core/TaskAttachmentLinksDurableMutationService.d.ts +5 -0
  43. package/dist/core/TaskAttachmentLinksDurableMutationService.js +20 -11
  44. package/dist/core/Taskforce.d.ts +63 -1
  45. package/dist/core/Taskforce.js +558 -73
  46. package/dist/core/types.d.ts +2 -1
  47. package/dist/documentReviews/DocumentReviewCommentStore.d.ts +11 -0
  48. package/dist/documentReviews/DocumentReviewCommentStore.js +35 -2
  49. package/dist/documentReviews/service.d.ts +4 -0
  50. package/dist/documentReviews/service.js +141 -46
  51. package/dist/hooks/tasks/useTaskFormActions.d.ts +3 -0
  52. package/dist/hooks/tasks/useTaskFormActions.js +33 -7
  53. package/dist/hooks/useTaskforce.d.ts +59 -50
  54. package/dist/hooks/useTaskforce.js +103 -1
  55. package/dist/mcp/canonicalAssetHelpers.d.ts +13 -0
  56. package/dist/mcp/canonicalAssetHelpers.js +39 -5
  57. package/dist/mcp/collaborationRegistrar.js +15 -13
  58. package/dist/mcp/documentAssetRegistrar.js +16 -9
  59. package/dist/mcp/localServiceProxy.js +4 -1
  60. package/dist/mcp/runtime.d.ts +16 -0
  61. package/dist/mcp/runtime.js +566 -171
  62. package/dist/mcp/taskAttachmentCommandAdapter.d.ts +2 -0
  63. package/dist/mcp/taskAttachmentCommandAdapter.js +14 -8
  64. package/dist/mcp/taskPlanningRegistrar.js +42 -34
  65. package/dist/mcp/toolRegistry.js +2 -2
  66. package/dist/migrations/taskSchemaMigrations.js +35 -0
  67. package/dist/runtime/appGateDefinitions.d.ts +2 -2
  68. package/dist/runtime/appGateDefinitions.js +2 -2
  69. package/dist/server/appAccess.d.ts +12 -0
  70. package/dist/server/appAccess.js +21 -0
  71. package/dist/server/authorizedWorkspaceAccess.d.ts +12 -0
  72. package/dist/server/authorizedWorkspaceAccess.js +40 -0
  73. package/dist/server/cloudCollectionRead.d.ts +25 -0
  74. package/dist/server/cloudCollectionRead.js +120 -0
  75. package/dist/server/cloudCollectionReadPool.d.ts +52 -0
  76. package/dist/server/cloudCollectionReadPool.js +140 -0
  77. package/dist/server/cloudCollectionReadWorker.d.ts +1 -0
  78. package/dist/server/cloudCollectionReadWorker.js +36 -0
  79. package/dist/server/index.d.ts +3 -11
  80. package/dist/server/index.js +53 -40
  81. package/dist/server/localServiceLease.d.ts +3 -0
  82. package/dist/server/localServiceLease.js +9 -1
  83. package/dist/server/routes/documents.d.ts +5 -2
  84. package/dist/server/routes/documents.js +160 -13
  85. package/dist/server/routes/durableTaskHttpRouters.d.ts +2 -0
  86. package/dist/server/routes/durableTaskHttpRouters.js +2 -2
  87. package/dist/server/routes/localService.js +2 -0
  88. package/dist/server/routes/primitives.d.ts +2 -0
  89. package/dist/server/routes/shared.d.ts +24 -0
  90. package/dist/server/routes/shared.js +114 -18
  91. package/dist/server/routes/sync.js +22 -0
  92. package/dist/server/routes/syncV3FeedRoutes.js +4 -2
  93. package/dist/server/routes/syncV3LocalCaptureRoutes.js +20 -2
  94. package/dist/server/routes/syncV3OperationRoutes.js +17 -2
  95. package/dist/server/routes/tasks.js +199 -89
  96. package/dist/server/routes.js +35 -7
  97. package/dist/service/localServiceCli.js +36 -25
  98. package/dist/service/localServiceClientLifecycle.js +67 -6
  99. package/dist/shared/planningIdentity.d.ts +20 -0
  100. package/dist/shared/planningIdentity.js +79 -0
  101. package/dist/storage/postgresAdapter.js +4 -0
  102. package/dist/storage/postgresRequestDiagnostics.d.ts +8 -0
  103. package/dist/storage/postgresRequestDiagnostics.js +24 -0
  104. package/dist/storage/workspaceAssetStore.d.ts +32 -0
  105. package/dist/storage/workspaceAssetStore.js +70 -0
  106. package/dist/sync/coordinator/localSyncExecutionPermitStore.d.ts +16 -0
  107. package/dist/sync/coordinator/localSyncExecutionPermitStore.js +70 -22
  108. package/dist/sync/coordinator/workspaceSyncTransportGateway.js +4 -2
  109. package/dist/sync/engine/workspaceSyncEngineRemoteServices.d.ts +5 -0
  110. package/dist/sync/engine/workspaceSyncEngineServerRemoteServices.d.ts +1 -1
  111. package/dist/sync/engine/workspaceSyncEngineServerRemoteServices.js +15 -0
  112. package/dist/sync/engine/workspaceSyncEngineServerRunnerOperations.js +26 -3
  113. package/dist/sync/engine/workspaceSyncV2ChangeDispatcher.js +2 -0
  114. package/dist/sync/syncApplyHandlers.d.ts +3 -1
  115. package/dist/sync/syncApplyHandlers.js +29 -0
  116. package/dist/sync/syncService.js +9 -0
  117. package/dist/sync/taskSyncPayload.d.ts +1 -0
  118. package/dist/sync/taskSyncPayload.js +6 -0
  119. package/dist/sync/v3/durableTaskAttachmentLinksMutationRouter.d.ts +1 -0
  120. package/dist/sync/v3/durableTaskAttachmentLinksMutationRouter.js +21 -3
  121. package/dist/sync/v3/durableTaskHttpBulkMutationRouter.js +17 -4
  122. package/dist/sync/v3/localInitiativeOutboxService.js +4 -2
  123. package/dist/sync/v3/localOutboxDispatcher.js +5 -1
  124. package/dist/sync/v3/localTaskAttachmentLinksOutboxHandler.js +12 -2
  125. package/dist/sync/v3/localTaskAttachmentLinksOutboxService.d.ts +1 -0
  126. package/dist/sync/v3/localTaskAttachmentLinksOutboxService.js +15 -3
  127. package/dist/sync/v3/localWorkstreamOutboxService.js +4 -2
  128. package/dist/sync/v3/syncDurabilityStore.d.ts +8 -0
  129. package/dist/sync/v3/syncDurabilityStore.js +171 -33
  130. package/dist/sync/v3/taskAttachmentLinksMutationService.d.ts +1 -0
  131. package/dist/sync/v3/taskAttachmentLinksMutationService.js +18 -2
  132. package/dist/sync/v3/taskMetadataCoexistence.js +4 -0
  133. package/dist/sync/v3/workspaceSyncV2ProjectionExclusions.js +1 -9
  134. package/dist/sync/v3/workspaceSyncV3CloudOperationHandler.js +1 -0
  135. package/dist/sync/v3/workspaceSyncV3CombinedFeedOrchestrator.js +7 -1
  136. package/dist/sync/v3/workspaceSyncV3CombinedLocalApply.js +15 -3
  137. package/dist/sync/v3/workspaceSyncV3CombinedRepairBaseline.d.ts +4 -0
  138. package/dist/sync/v3/workspaceSyncV3CombinedRepairBaseline.js +29 -6
  139. package/dist/sync/v3/workspaceSyncV3CombinedRepairMaterialization.d.ts +1 -0
  140. package/dist/sync/v3/workspaceSyncV3CombinedRepairMaterialization.js +29 -7
  141. package/dist/sync/v3/workspaceSyncV3CombinedRepairSnapshot.js +62 -7
  142. package/dist/sync/v3/workspaceSyncV3OperationProtocol.d.ts +1 -0
  143. package/dist/sync/v3/workspaceSyncV3RepairSqlBatching.d.ts +2 -0
  144. package/dist/sync/v3/workspaceSyncV3RepairSqlBatching.js +10 -0
  145. package/dist/sync/v3/workspaceSyncV3TaskRootProjection.d.ts +1 -1
  146. package/dist/sync/v3/workspaceSyncV3TaskRootProjection.js +1 -1
  147. package/dist/sync/workspacePullFeed.d.ts +6 -1
  148. package/dist/sync/workspacePullFeed.js +172 -161
  149. package/dist/sync/workspaceSyncModel.d.ts +11 -0
  150. package/dist/sync/workspaceSyncModel.js +27 -2
  151. package/dist/types.d.ts +8 -0
  152. package/dist/ui/assets/{AiIdentityRosterCard-DB1BLO_j.js → AiIdentityRosterCard-MZs7lVED.js} +1 -1
  153. package/dist/ui/assets/{AiProfilesModule-DPxQeF9N.js → AiProfilesModule-C3i0LOxe.js} +1 -1
  154. package/dist/ui/assets/{AnnotatedAttachmentWorkspace-DHNYaNg6.js → AnnotatedAttachmentWorkspace-DVZk5Tln.js} +1 -1
  155. package/dist/ui/assets/AssetTraySortControl-Kf1pelSy.js +1 -0
  156. package/dist/ui/assets/ContextAttachmentManager-B8boOs6Q.js +3 -0
  157. package/dist/ui/assets/{DocumentWorkspace-BC7sy5TG.js → DocumentWorkspace-DXH4XUsB.js} +4 -4
  158. package/dist/ui/assets/EntityActivityTimeline-BtSTq0ON.js +1 -0
  159. package/dist/ui/assets/PlanningModule-BPVyEa-f.js +1 -0
  160. package/dist/ui/assets/PlanningModule-CoIR9hbV.css +1 -0
  161. package/dist/ui/assets/{PlansPage-BVH_NfgT.js → PlansPage-ChqgxALc.js} +1 -1
  162. package/dist/ui/assets/TaskContextUpload-CB3ol0sN.js +1 -0
  163. package/dist/ui/assets/TaskContextUpload-qmBeUw3u.css +1 -0
  164. package/dist/ui/assets/{TaskSettings-xVsxSa0g.js → TaskSettings-g4ECKNOz.js} +1 -1
  165. package/dist/ui/assets/{TaskforceAgentsModule-CkAxW19K.js → TaskforceAgentsModule-BazdUwxZ.js} +1 -1
  166. package/dist/ui/assets/WorkflowManagerModule-DWFspC-o.js +1 -0
  167. package/dist/ui/assets/index-BUplSsv_.js +7 -0
  168. package/dist/ui/assets/index-gz2EXuoK.css +1 -0
  169. package/dist/ui/assets/{vendor-icons-B8ZNsH1g.js → vendor-icons-BkFLXavV.js} +1 -1
  170. package/dist/ui/index.html +3 -3
  171. package/dist/utils/constants.d.ts +2 -2
  172. package/dist/utils/constants.js +1 -1
  173. package/dist/utils/contextAttachmentUpload.d.ts +2 -0
  174. package/dist/utils/contextAttachmentUpload.js +7 -0
  175. package/dist/utils/contextFiles.d.ts +1 -1
  176. package/dist/utils/contextFiles.js +4 -4
  177. package/package.json +6 -1
  178. package/dist/ui/assets/AssetTraySortControl-DphbyHVc.js +0 -1
  179. package/dist/ui/assets/ContextAttachmentManager-CMxSzHqc.js +0 -3
  180. package/dist/ui/assets/EntityActivityTimeline-pJ2ZjZ-k.js +0 -1
  181. package/dist/ui/assets/PlanningModule-CeTqXMMz.css +0 -1
  182. package/dist/ui/assets/PlanningModule-t5GbvVR9.js +0 -1
  183. package/dist/ui/assets/TaskContextUpload-Ds4LnDzV.css +0 -1
  184. package/dist/ui/assets/TaskContextUpload-bl4fOOUz.js +0 -1
  185. package/dist/ui/assets/WorkflowManagerModule-BKqIGVnF.js +0 -1
  186. package/dist/ui/assets/index-BzJlVnNS.css +0 -1
  187. package/dist/ui/assets/index-Cx7vZJHL.js +0 -7
@@ -0,0 +1,7 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/EntityActivityTimeline-BtSTq0ON.js","assets/vendor-react-CKJs5o3c.js","assets/vendor-icons-BkFLXavV.js","assets/vendor-markdown-_lhNCyq-.js","assets/vendor-dnd-CJ-AjP-Y.js","assets/vendor-router-AqJMU8Lz.js","assets/EntityActivityTimeline-BfJbZRdl.css","assets/TaskContextUpload-CB3ol0sN.js","assets/ContextAttachmentManager-B8boOs6Q.js","assets/TaskContextUpload-qmBeUw3u.css","assets/TaskSettings-g4ECKNOz.js","assets/TaskSettings-CnIBL_Eb.css","assets/AnnotatedAttachmentWorkspace-DVZk5Tln.js","assets/AssetTraySortControl-Kf1pelSy.js","assets/AssetTraySortControl-B9k5caQW.css","assets/AnnotatedAttachmentWorkspace-CBRZ8rca.css","assets/DocumentWorkspace-DXH4XUsB.js","assets/DocumentWorkspace-BIBGBfd7.css","assets/TaskforceAgentsModule-BazdUwxZ.js","assets/AiIdentityRosterCard-MZs7lVED.js","assets/TaskforceAgentsModule-D6IC0S7Q.css","assets/WorkflowManagerModule-DWFspC-o.js","assets/WorkflowManagerModule-DF10XENz.css","assets/AiProfilesModule-C3i0LOxe.js","assets/PlanningModule-BPVyEa-f.js","assets/PlanningModule-CoIR9hbV.css","assets/PlansPage-ChqgxALc.js","assets/PlansPage-C2nkK2Bp.css"])))=>i.map(i=>d[i]);
2
+ import{r as o,j as a,R as Y,a as tc,b as RT}from"./vendor-react-CKJs5o3c.js";import{I as Gs,C as Td,a as Nd,S as bg,F as jT,R as bi,b as PT,c as ET,d as nA,U as Mh,G as NT,H as MT,M as DT,e as LT,P as OT,B as BT,f as WT,W as $T,L as FT,g as UT,h as zT,i as HT,j as GT,k as Vh,l as Qi,m as VT,n as KT,o as qT,p as YT,T as ZT,q as Bu,r as Vf,s as JT,t as ri,u as Si,A as gv,v as sA,w as za,x as xd,y as QT,z as XT,D as e0,E as oA,J as yd,K as Du,N as iA,O as t0,X as Mo,Q as yv,V as Sf,Y as Sd,Z as Rd,_ as r0,$ as cA,a0 as Ef,a1 as a0,a2 as tb,a3 as n0,a4 as Nf,a5 as s0,a6 as lA,a7 as dA,a8 as o0,a9 as i0,aa as c0,ab as uA,ac as l0,ad as d0,ae as u0,af as pA,ag as p0,ah as kv,ai as po,aj as fA,ak as f0,al as mA,am as m0,an as h0,ao as g0,ap as y0,aq as rb,ar as ab,as as k0,at as v0,au as w0,av as b0,aw as S0,ax as hA,ay as A0,az as nb,aA as C0,aB as I0,aC as _0}from"./vendor-icons-BkFLXavV.js";import{s as T0,M as x0,r as sb,a as R0}from"./vendor-markdown-_lhNCyq-.js";import{u as vv,a as Mf,P as wv,b as gA,D as bv,c as yA,S as Sv,v as Av,d as Cv,C as Sg,e as Iv,s as kA,K as vA,f as j0,p as P0,g as ob,h as E0,i as wA,j as N0}from"./vendor-dnd-CJ-AjP-Y.js";import{u as bA,a as SA,b as M0,M as D0,N as ib,B as L0}from"./vendor-router-AqJMU8Lz.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))n(s);new MutationObserver(s=>{for(const i of s)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function r(s){const i={};return s.integrity&&(i.integrity=s.integrity),s.referrerPolicy&&(i.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?i.credentials="include":s.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function n(s){if(s.ep)return;s.ep=!0;const i=r(s);fetch(s.href,i)}})();const Lu="default",Ag="General",fo="task",O0=2,B0=[{value:Lu,label:Ag,icon:"Inbox"}],AA=[{value:fo,label:"Task",icon:"CheckSquare",color:"blue-500"}],W0=[{value:O0,label:"Medium",color:"blue-500",icon:"Minus"}];function $0(){return B0.map(e=>({...e}))}function F0(){return AA.map(e=>({...e}))}function U0(e){const t=String(e||"").trim().toLowerCase();return AA.find(r=>r.value===t)}function CA(){return W0.map(e=>({...e}))}const z0={categories:$0(),types:F0(),priorities:CA(),taxonomies:[],apiEndpoint:"/api/taskforce/task",apiBaseUrl:void 0,cloudAuthBaseUrl:void 0,cloudMcpBaseUrl:void 0,wsBaseUrl:void 0,position:"bottom-right",offsetY:70,theme:"dawn",shortcut:"Alt+T",manualComplexityEnabled:!1,checklistDropdownEnabled:!0,showTaskCardStatusLabel:!1},H0=["light","dawn","dark","midnight"],Kh="dawn",G0=[{id:"light",label:"Light",family:"light",icon:"sun"},{id:"dawn",label:"Dawn",family:"light",icon:"wind"},{id:"dark",label:"Dark",family:"dark",icon:"moon"},{id:"midnight",label:"Midnight",family:"dark",icon:"sparkles"}],V0=new Set(H0),K0=new Set(G0.filter(e=>e.family==="light").map(e=>e.id));function q0(e){return typeof e=="string"&&V0.has(e)}function Pu(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return q0(t)?t:null}function IA(e){const t=Pu(e);return t!==null&&K0.has(t)}function qh(e){const t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t))return null;const r=Math.floor(t);return r>0?r:null}const Y0=new RegExp("(?<![\\w-])((?:IN|WS|D|I)-\\d+)(?![\\w-])","gi"),Z0={IN:"initiative",WS:"workstream",D:"document",I:"image"};function _A(e){const r=String(e||"").trim().toUpperCase().match(/^(IN|WS|D|I)-(\d+)$/);if(!r)return null;const n=qh(r[2]);return n?{kind:Z0[r[1]],token:`${r[1]}-${n}`,referenceNumber:n}:null}function Wu(e,t){const r=qh(typeof t=="object"&&t!==null?t.referenceNumber:t);return r?`${e}${r}`:""}function Cg(e,t){const r=String(e||"").trim(),n=String(t||"").trim();if(!r||!n)return null;const s=r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=n.match(new RegExp(`^${s}(\\d+)$`,"i"));return i?qh(i[1]):null}function Kf(e,t){return t?typeof t.referenceLabel=="string"&&t.referenceLabel.trim().length>0?t.referenceLabel.trim():Wu(e,t.referenceNumber):""}const _v="T-",Rk="LT-",J0=/^task-[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i,Q0=/^task-\d{10,}-[a-z0-9]+$/i,X0=new RegExp("(?<![\\w-])((?:LT|T)-\\d+|task-(?:[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}|\\d{10,}-[a-z0-9]+))(?![\\w-])","gi");function TA(e){const t=String(e||"").trim();return Ig(t)!==null||RA(t)!==null||J0.test(t)||Q0.test(t)}function ex(e,t){const r=String(t||"").trim();if(!r||!TA(r))return null;const n=r.toLowerCase(),s=Ig(r),i=RA(r),l=e.filter(c=>c.id.toLowerCase()===n||s!==null&&c.referenceNumber===s||i!==null&&c.localReferenceNumber===i?!0:hs(c).toLowerCase()===n);return l.length===1?l[0].id:null}function tx(e){const t=new Map,r=(s,i)=>{const l=String(s||"").trim().toLowerCase();if(l){if(!t.has(l)){t.set(l,i);return}t.get(l)!==i&&t.set(l,null)}};return e.forEach(s=>{r(s.id,s.id),s.referenceNumber&&r(xA(s.referenceNumber),s.id),s.localReferenceNumber&&r(Tv(s.localReferenceNumber),s.id),r(hs(s),s.id)}),{revision:JSON.stringify(Array.from(t.entries()).sort(([s],[i])=>s.localeCompare(i))),resolve:s=>{const i=String(s||"").trim();return!i||!TA(i)?null:t.get(i.toLowerCase())??null}}}function xA(e){return Wu(_v,e)}function Tv(e){return typeof e=="number"||e===null||e===void 0?Wu(Rk,e):Wu(Rk,{referenceNumber:e.localReferenceNumber??null})}function Ig(e){return Cg(_v,e)}function RA(e){return Cg(Rk,e)}function hs(e){if(!e)return"";if(typeof e.referenceLabel=="string"&&e.referenceLabel.trim().length>0)return e.referenceLabel.trim();const t=Kf(_v,e);return t||Tv(e.localReferenceNumber)}function rx(e){return!e?.referenceNumber&&!!e?.localReferenceNumber}function xv(e){return{label:hs(e),isProvisional:rx(e)}}CA();const ax={low:1,medium:2,high:3,critical:4,"on-hold":1};function nx(e){const t=String(e||"").trim().toLowerCase();return t==="blocked"||t==="on hold"||t==="on-hold"?"on-hold":t==="task"||t==="on-hold"||t==="in-progress"||t==="review"||t==="done"||t==="cancelled"?t:"task"}function Yh(e){if(typeof e=="number"&&Number.isFinite(e))return Math.max(1,Math.round(e));const t=Number(e);return Number.isFinite(t)?Math.max(1,Math.round(t)):ax[String(e||"").trim().toLowerCase()]??2}function No(e){const t=typeof e.referenceNumber=="number"?e.referenceNumber:Number.isFinite(Number(e.referenceNumber))?Number(e.referenceNumber):null,r=typeof e.localReferenceNumber=="number"?e.localReferenceNumber:Number.isFinite(Number(e.localReferenceNumber))?Number(e.localReferenceNumber):null;return{...e,referenceNumber:t&&t>0?Math.floor(t):null,localReferenceNumber:r&&r>0?Math.floor(r):null,referenceLabel:typeof e.referenceLabel=="string"&&e.referenceLabel.trim().length>0?e.referenceLabel.trim():t?xA(t):Tv(r),assignee:(()=>{const n=String(e.assignee||"").trim(),s=n.toLowerCase();return s==="agent"||s==="ai"?"agent":!n||s==="user"||s==="human"||s==="unassigned"||s==="none"||s==="null"?"unassigned":n})(),category:typeof e.category=="string"?e.category:e.category?.value||"default",type:(typeof e.type=="string"?e.type:e.type?.label||"task").toLowerCase(),priority:Yh(e.priority),complexity:typeof e.complexity=="number"?e.complexity:3,status:nx(e.status)}}function Df(e){return JSON.stringify(e)}function cb(e,t){if(e.length===0)return t.length===0?e:t;const r=new Map(e.map(i=>[i.id,i]));let n=e.length!==t.length;const s=t.map((i,l)=>{const c=r.get(i.id),d=c&&Df(c)===Df(i)?c:i;return d!==e[l]&&(n=!0),d});return n?s:e}function sx(e,t,r){if(!e||typeof e!="object")return{tasks:t,archivedTasks:r};const n=No(e),s=String(n.id||"").trim();if(!s)return{tasks:t,archivedTasks:r};const i=!!n.isArchived,l=i?{...n,isArchived:!0}:{...n,isArchived:!1},c=(i?r:t).find(h=>h.id===s),d=(i?t:r).some(h=>h.id===s);if(c&&!d&&Df(c)===Df(l))return{tasks:t,archivedTasks:r};const f=h=>[...h].sort((y,k)=>{const b=Date.parse(String(y.updatedAt||y.createdAt||"")),C=Date.parse(String(k.updatedAt||k.createdAt||""));if(Number.isFinite(b)&&Number.isFinite(C)&&b!==C)return C-b;if(Number.isFinite(b)!==Number.isFinite(C))return Number.isFinite(C)?1:-1;const S=Date.parse(String(k.createdAt||""))-Date.parse(String(y.createdAt||""));return Number.isFinite(S)&&S!==0?S:String(y.id).localeCompare(String(k.id))}),p=t.some(h=>h.id===s)?t.filter(h=>h.id!==s):t,g=r.some(h=>h.id===s)?r.filter(h=>h.id!==s):r;return i?{tasks:p,archivedTasks:f([...g,l])}:{tasks:f([...p,l]),archivedTasks:g}}function ox(e,t){if(!t.length||!e.length)return[];const r=new Set(t.map(s=>Number(s.value))),n=Array.from(new Set(e.map(s=>Number(s)).filter(s=>Number.isFinite(s)&&r.has(s))));return n.length>0?n:t.map(s=>Number(s.value))}function qy(e,t){return t.some(r=>String(r)===String(e))}function ix(e,t){if(!e.length||!t.length)return e;const r=new Set(t.map(s=>s.value)),n=Array.from(new Set(e.filter(s=>r.has(s))));return n.length>0?n:t.map(s=>s.value)}const cx={taskForm:{commentsSectionTitle:"Activity & Comments",noComments:"No comments yet. Start the conversation!",noActivity:"No activity yet.",you:"You",commentPlaceholder:"Type a comment...",newActivity:"New activity",newActivityAriaLabel:"New activity. Scroll to latest.",scheduledLabel:"Scheduled:",dueLabel:"Due:",createdLabel:"Created:",updatedLabel:"Updated:",completedLabel:"Completed:",emptyValue:"—",dueBeforeScheduled:"Due date is before scheduled date.",overdue:"This task is overdue."},schedule:{},taskList:{searchPlaceholder:"Search tasks...",clearSearchTitle:"Clear search",categoryLabel:"Category",typeLabel:"Type",priorityLabel:"Priority",statusLabel:"Status",assigneeLabel:"Assignee",sortByLabel:"Sort By:",sortCreated:"Created",sortUpdated:"Updated",sortPriority:"Priority",sortDirectionDescTitle:"Sort: Last First",sortDirectionAscTitle:"Sort: First First",resetFiltersTitle:"Reset all filters",archiveAllTitle:"Archive all completed and cancelled tasks",noTasksToArchiveTitle:"No tasks to archive",archiveFinished:"Archive Finished",linksLabel:"Links",linksAll:"All",linksParents:"Parents",linksLinked:"Linked",linksUnlinked:"Unlinked",includeArchive:"Archived",noMatchingTasks:"No matching tasks",noActiveTasks:"No active tasks",addTaskToCategoryTitle:"Add task to {category}"},actionHeader:{saveChangesTitle:"Save Changes",update:"Update",copyTaskIdTitle:"Click to copy Task ID",startWorking:"Start Working",stopWorking:"Stop Working",unlockAndContinue:"Unlock & Continue Work",readyForReview:"Ready for Review",markComplete:"Mark Complete",unmarkComplete:"Unmark Complete",cancelTask:"Cancel Task",unmarkCancelled:"Unmark Cancelled",archiveNow:"Archive Now",completeTaskToArchive:"Complete task to archive",clearFormTitle:"Clear Form",clear:"Clear",addTaskTitle:"Add Task",addTask:"Add Task"},standalone:{searchPlaceholder:"Search tasks...",clearSearchTitle:"Clear search",sortLabel:"Sort:",sortCreated:"Created",sortUpdated:"Updated",sortPriority:"Priority",sortComplexity:"Complexity",sortDirectionDescTitle:"Sort: Last First",sortDirectionAscTitle:"Sort: First First",groupLabel:"Group:",groupCategory:"Category",groupType:"Type",groupPriority:"Priority",groupComplexity:"Complexity",groupAssignee:"Assignee",groupStatus:"Status",groupHierarchy:"Hierarchy",groupSchedule:"Schedule",showEmptyColumns:"Show Empty Columns",compressEmptyColumns:"Compress Empty Columns",hideEmptyColumns:"Hide Empty Columns",expandCards:"Expand Cards",compressCards:"Compress Cards",exitZenMode:"Exit Zen Mode",enterZenMode:"Enter Zen Mode",toggleFilters:"Toggle Filters",addTask:"Add Task",helpTutorial:"Help & Support",settings:"Settings",filtersCaps:"FILTERS:",categoryLabel:"Category",typeLabel:"Type",priorityLabel:"Priority",statusLabel:"Status",assigneeLabel:"Assignee",linksLabel:"Links:",chooseLinksTitle:"Choose which linked tasks are shown",linksAll:"All",linksParents:"Parents",linksLinked:"Linked",linksUnlinked:"Unlinked",includeArchiveTitle:"Include archived tasks",includeArchive:"Archived",clearFilters:"Clear Filters",noTasksMatchFilters:"No tasks match current filters.",showingWithLinksHint:"Showing: {parentFilterLabel}. Switch Links to All or clear filters.",visibleActiveTasksTitle:"Visible active tasks / total active tasks",totalActiveTasksTitle:"Total active tasks"},setup:{headingCheckFailed:"Setup Check Failed",headingGlobalRequired:"Global Setup Required",headingWorkspaceRequired:"Configure your new workspace.",subtitleUnreadable:"Taskforce could not read setup state. Retry to continue.",subtitleGlobalRequired:"Choose your default operating mode to continue.",subtitleWorkspaceRequired:"",runtimeLabel:"Runtime",workspaceTermProject:"Project",workspaceTermMission:"Mission",coreModeOption:"Core Mode: {workspaceLabel} planning defaults",operationsModeOption:"Operations Mode: Mission-first terminology and flows",workspaceNamePlaceholder:"{workspaceLabel} name",workspaceDescriptionPlaceholder:"{workspaceLabel} description (optional)",saving:"Saving...",saveGlobalSetup:"Save Global Setup",saveWorkspaceSetup:"Save {workspaceLabel} Setup",globalSetupSaved:"Global setup saved.",workspaceSetupSaved:"{workspaceLabel} setup saved.",saveFailedWithStatus:"Failed to save setup ({status})",saveFailed:"Failed to save setup.",saveWorkspaceFailed:"Failed to save workspace profile.",retrySetupCheck:"Retry Setup Check",signOut:"Sign Out"}},lx={taskForm:{commentsSectionTitle:"Actividad y comentarios",noComments:"Aun no hay comentarios. Inicia la conversacion.",noActivity:"Aun no hay actividad.",you:"Tu",commentPlaceholder:"Escribe un comentario...",newActivity:"Nueva actividad",newActivityAriaLabel:"Nueva actividad. Ir a la mas reciente.",scheduledLabel:"Programado:",dueLabel:"Vence:",createdLabel:"Creado:",updatedLabel:"Actualizado:",completedLabel:"Completado:",emptyValue:"—",dueBeforeScheduled:"La fecha de vencimiento es anterior a la fecha programada.",overdue:"Esta tarea esta vencida."},schedule:{},taskList:{searchPlaceholder:"Buscar tareas...",clearSearchTitle:"Limpiar busqueda",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridad",statusLabel:"Estado",assigneeLabel:"Asignado a",sortByLabel:"Ordenar por:",sortCreated:"Creado",sortUpdated:"Actualizado",sortPriority:"Prioridad",sortDirectionDescTitle:"Orden: mas reciente primero",sortDirectionAscTitle:"Orden: mas antiguo primero",resetFiltersTitle:"Restablecer todos los filtros",archiveAllTitle:"Archivar todas las tareas completadas y canceladas",noTasksToArchiveTitle:"No hay tareas para archivar",archiveFinished:"Archivar finalizadas",linksLabel:"Vinculos",linksAll:"Todas",linksParents:"Padres",linksLinked:"Vinculadas",linksUnlinked:"Sin vinculo",includeArchive:"Incluir archivo",noMatchingTasks:"No hay tareas coincidentes",noActiveTasks:"No hay tareas activas",addTaskToCategoryTitle:"Agregar tarea a {category}"},actionHeader:{saveChangesTitle:"Guardar cambios",update:"Actualizar",copyTaskIdTitle:"Haz clic para copiar el ID de la tarea",startWorking:"Comenzar trabajo",stopWorking:"Detener trabajo",unlockAndContinue:"Desbloquear y continuar",readyForReview:"Lista para revision",markComplete:"Marcar como completada",unmarkComplete:"Quitar completada",cancelTask:"Cancelar tarea",unmarkCancelled:"Quitar cancelada",archiveNow:"Archivar ahora",completeTaskToArchive:"Completa la tarea para archivar",clearFormTitle:"Limpiar formulario",clear:"Limpiar",addTaskTitle:"Agregar tarea",addTask:"Agregar tarea"},standalone:{searchPlaceholder:"Buscar tareas...",clearSearchTitle:"Limpiar busqueda",sortLabel:"Orden:",sortCreated:"Creado",sortUpdated:"Actualizado",sortPriority:"Prioridad",sortComplexity:"Complejidad",sortDirectionDescTitle:"Orden: mas reciente primero",sortDirectionAscTitle:"Orden: mas antiguo primero",groupLabel:"Agrupar:",groupCategory:"Categoria",groupType:"Tipo",groupPriority:"Prioridad",groupComplexity:"Complejidad",groupAssignee:"Asignado a",groupStatus:"Estado",groupHierarchy:"Jerarquia",groupSchedule:"Calendario",showEmptyColumns:"Mostrar columnas vacias",compressEmptyColumns:"Comprimir columnas vacias",hideEmptyColumns:"Ocultar columnas vacias",expandCards:"Expandir tarjetas",compressCards:"Comprimir tarjetas",exitZenMode:"Salir del modo zen",enterZenMode:"Entrar en modo zen",toggleFilters:"Alternar filtros",addTask:"Agregar tarea",helpTutorial:"Ayuda y soporte",settings:"Configuracion",filtersCaps:"FILTROS:",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridad",statusLabel:"Estado",assigneeLabel:"Asignado a",linksLabel:"Vinculos:",chooseLinksTitle:"Elige que tareas vinculadas se muestran",linksAll:"Todas",linksParents:"Padres",linksLinked:"Vinculadas",linksUnlinked:"Sin vinculo",includeArchiveTitle:"Incluir tareas archivadas",includeArchive:"Incluir archivo",clearFilters:"Limpiar filtros",noTasksMatchFilters:"Ninguna tarea coincide con los filtros actuales.",showingWithLinksHint:"Mostrando: {parentFilterLabel}. Cambia Vinculos a Todas o limpia filtros.",visibleActiveTasksTitle:"Tareas activas visibles / total de tareas activas",totalActiveTasksTitle:"Total de tareas activas"},setup:{headingCheckFailed:"Fallo en verificacion de configuracion",headingGlobalRequired:"Configuracion global requerida",headingWorkspaceRequired:"Configuracion del espacio requerida",subtitleUnreadable:"Taskforce no pudo leer el estado de configuracion. Reintenta para continuar.",subtitleGlobalRequired:"Elige tu modo operativo predeterminado para continuar.",subtitleWorkspaceRequired:"Configura el perfil de tu espacio para continuar.",runtimeLabel:"Entorno",workspaceTermProject:"Proyecto",workspaceTermMission:"Mision",coreModeOption:"Modo Core: valores predeterminados de planificacion para {workspaceLabel}",operationsModeOption:"Modo Operaciones: terminologia y flujos orientados a Mision",workspaceNamePlaceholder:"Nombre de {workspaceLabel}",workspaceDescriptionPlaceholder:"Descripcion de {workspaceLabel} (opcional)",saving:"Guardando...",saveGlobalSetup:"Guardar configuracion global",saveWorkspaceSetup:"Guardar configuracion de {workspaceLabel}",globalSetupSaved:"Configuracion global guardada.",workspaceSetupSaved:"Configuracion de {workspaceLabel} guardada.",saveFailedWithStatus:"Error al guardar la configuracion ({status})",saveFailed:"Error al guardar la configuracion.",saveWorkspaceFailed:"Error al guardar el perfil del espacio.",retrySetupCheck:"Reintentar verificacion",signOut:"Cerrar sesion"}},dx={taskForm:{commentsSectionTitle:"Atividade e comentarios",noComments:"Ainda nao ha comentarios. Inicie a conversa.",noActivity:"Ainda nao ha atividade.",you:"Voce",commentPlaceholder:"Digite um comentario...",newActivity:"Nova atividade",newActivityAriaLabel:"Nova atividade. Ir para a mais recente.",scheduledLabel:"Agendado:",dueLabel:"Vencimento:",createdLabel:"Criado:",updatedLabel:"Atualizado:",completedLabel:"Concluido:",emptyValue:"—",dueBeforeScheduled:"A data de vencimento e anterior a data agendada.",overdue:"Esta tarefa esta atrasada."},schedule:{},taskList:{searchPlaceholder:"Buscar tarefas...",clearSearchTitle:"Limpar busca",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridade",statusLabel:"Status",assigneeLabel:"Atribuido para",sortByLabel:"Ordenar por:",sortCreated:"Criado",sortUpdated:"Atualizado",sortPriority:"Prioridade",sortDirectionDescTitle:"Ordem: mais recente primeiro",sortDirectionAscTitle:"Ordem: mais antigo primeiro",resetFiltersTitle:"Redefinir todos os filtros",archiveAllTitle:"Arquivar todas as tarefas concluidas e canceladas",noTasksToArchiveTitle:"Nao ha tarefas para arquivar",archiveFinished:"Arquivar finalizadas",linksLabel:"Vinculos",linksAll:"Todas",linksParents:"Pais",linksLinked:"Vinculadas",linksUnlinked:"Sem vinculo",includeArchive:"Incluir arquivo",noMatchingTasks:"Nenhuma tarefa correspondente",noActiveTasks:"Nenhuma tarefa ativa",addTaskToCategoryTitle:"Adicionar tarefa a {category}"},actionHeader:{saveChangesTitle:"Salvar alteracoes",update:"Atualizar",copyTaskIdTitle:"Clique para copiar o ID da tarefa",startWorking:"Iniciar trabalho",stopWorking:"Parar trabalho",unlockAndContinue:"Desbloquear e continuar",readyForReview:"Pronto para revisao",markComplete:"Marcar como concluida",unmarkComplete:"Desmarcar concluida",cancelTask:"Cancelar tarefa",unmarkCancelled:"Desmarcar cancelada",archiveNow:"Arquivar agora",completeTaskToArchive:"Conclua a tarefa para arquivar",clearFormTitle:"Limpar formulario",clear:"Limpar",addTaskTitle:"Adicionar tarefa",addTask:"Adicionar tarefa"},standalone:{searchPlaceholder:"Buscar tarefas...",clearSearchTitle:"Limpar busca",sortLabel:"Ordenar:",sortCreated:"Criado",sortUpdated:"Atualizado",sortPriority:"Prioridade",sortComplexity:"Complexidade",sortDirectionDescTitle:"Ordem: mais recente primeiro",sortDirectionAscTitle:"Ordem: mais antigo primeiro",groupLabel:"Agrupar:",groupCategory:"Categoria",groupType:"Tipo",groupPriority:"Prioridade",groupComplexity:"Complexidade",groupAssignee:"Atribuido para",groupStatus:"Status",groupHierarchy:"Hierarquia",groupSchedule:"Agenda",showEmptyColumns:"Mostrar colunas vazias",compressEmptyColumns:"Comprimir colunas vazias",hideEmptyColumns:"Ocultar colunas vazias",expandCards:"Expandir cards",compressCards:"Comprimir cards",exitZenMode:"Sair do modo zen",enterZenMode:"Entrar no modo zen",toggleFilters:"Alternar filtros",addTask:"Adicionar tarefa",helpTutorial:"Ajuda e suporte",settings:"Configuracoes",filtersCaps:"FILTROS:",categoryLabel:"Categoria",typeLabel:"Tipo",priorityLabel:"Prioridade",statusLabel:"Status",assigneeLabel:"Atribuido para",linksLabel:"Vinculos:",chooseLinksTitle:"Escolha quais tarefas vinculadas sao exibidas",linksAll:"Todas",linksParents:"Pais",linksLinked:"Vinculadas",linksUnlinked:"Sem vinculo",includeArchiveTitle:"Incluir tarefas arquivadas",includeArchive:"Incluir arquivo",clearFilters:"Limpar filtros",noTasksMatchFilters:"Nenhuma tarefa corresponde aos filtros atuais.",showingWithLinksHint:"Mostrando: {parentFilterLabel}. Mude Vinculos para Todas ou limpe os filtros.",visibleActiveTasksTitle:"Tarefas ativas visiveis / total de tarefas ativas",totalActiveTasksTitle:"Total de tarefas ativas"},setup:{headingCheckFailed:"Falha na verificacao da configuracao",headingGlobalRequired:"Configuracao global obrigatoria",headingWorkspaceRequired:"Configuracao do espaco obrigatoria",subtitleUnreadable:"Taskforce nao conseguiu ler o estado da configuracao. Tente novamente para continuar.",subtitleGlobalRequired:"Escolha seu modo operacional padrao para continuar.",subtitleWorkspaceRequired:"Configure o perfil do seu espaco para continuar.",runtimeLabel:"Ambiente",workspaceTermProject:"Projeto",workspaceTermMission:"Missao",coreModeOption:"Modo Core: padroes de planejamento para {workspaceLabel}",operationsModeOption:"Modo Operacoes: terminologia e fluxos orientados por Missao",workspaceNamePlaceholder:"Nome de {workspaceLabel}",workspaceDescriptionPlaceholder:"Descricao de {workspaceLabel} (opcional)",saving:"Salvando...",saveGlobalSetup:"Salvar configuracao global",saveWorkspaceSetup:"Salvar configuracao de {workspaceLabel}",globalSetupSaved:"Configuracao global salva.",workspaceSetupSaved:"Configuracao de {workspaceLabel} salva.",saveFailedWithStatus:"Falha ao salvar configuracao ({status})",saveFailed:"Falha ao salvar configuracao.",saveWorkspaceFailed:"Falha ao salvar perfil do espaco.",retrySetupCheck:"Tentar verificacao novamente",signOut:"Sair"}},jA=["en-US","es-419","pt-BR"],Zh="en-US",Yy={"en-US":cx,"es-419":lx,"pt-BR":dx},PA={en:"en-US",es:"es-419",pt:"pt-BR"};let Ad=Zh;function ux(e){return e.split(".").filter(Boolean)}function Zy(e,t){let r=e;for(const n of t){if(!r||typeof r!="object")return;r=r[n]}return typeof r=="string"?r:void 0}function EA(e){if(!e)return Zh;const t=jA.find(n=>n.toLowerCase()===e.toLowerCase());if(t)return t;const r=e.split("-")[0]?.toLowerCase()||"";return PA[r]||Zh}function Jy(e,t){return t?e.replace(/\{([^}]+)\}/g,(r,n)=>{const s=t[n];return s==null?"":String(s)}):e}function NA(){return Ad}function px(){return[...jA]}function MA(e){const t=EA(e);return Ad=t,t}function fx(e){const t=typeof navigator<"u"?navigator.language:null;return Ad=EA(t),Ad}function bt(e,t){const r=ux(e),n=Zy(Yy[Ad],r);if(n)return Jy(n,t);const s=Ad.split("-")[0]?.toLowerCase()||"",i=PA[s];if(i&&i!==Ad){const c=Zy(Yy[i],r);if(c)return Jy(c,t)}const l=Zy(Yy[Zh],r);return l?Jy(l,t):e}const mx="default",jd="bootstrap";function hx(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0")}function _g(e){const t=String(e||"").trim().toLowerCase();return t?`${(t.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"project").slice(0,56)}-${hx(t)}`:jd}function Rv(e){const t=String(e||"").trim().toLowerCase();if(!t)return jd;const r=t.replace(/[^a-z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"");return r?r.slice(0,96):jd}function DA(e){const t=String(e||"").trim();return t?_g(t):jd}function gx(e){return(e.runtimeMode==="cloud"?"cloud":"local")==="cloud"?jd:DA(e.projectRoot)}function yx(e){if((e.runtimeMode==="cloud"?"cloud":"local")==="cloud"){const r=String(e.workspaceId||"").trim();return r&&!jv(r)?_g(`cloud-workspace:${r}`):jd}return DA(e.projectRoot)}function jv(e){return String(e||"").trim().toLowerCase()===mx}const kx={local:{runtimeMode:"local",authSource:"cloud",workspaceMode:"single-local",workspaceSwitchingEnabled:!1},cloud:{runtimeMode:"cloud",authSource:"cloud",workspaceMode:"multi-cloud",workspaceSwitchingEnabled:!0}};function vx(e){return String(e||"").trim().toLowerCase()==="cloud"?"cloud":"local"}function wx(e){return kx[vx(e)]}const Lf={production:{appBaseUrl:"https://app.taskforcehq.ai",mcpBaseUrl:"https://mcp.taskforcehq.ai",label:"Production",themeToken:"production"},staging:{appBaseUrl:"https://staging-app.taskforcehq.ai",mcpBaseUrl:"https://staging-mcp.taskforcehq.ai",label:"Staging",themeToken:"staging"},performance:{appBaseUrl:"https://performance-app.taskforcehq.ai",mcpBaseUrl:"https://performance-mcp.taskforcehq.ai",label:"Performance",themeToken:"performance"}};function Tg(e){const t=String(e||"").trim().toLowerCase();return t==="production"||t==="staging"||t==="performance"?t:null}function bx(e){return Tg(e)||"production"}function lb(e){return Lf[bx(String(e||""))]}function Sx(e){const t=String(e||"").trim().toLowerCase();if(!t)return null;for(const[r,n]of Object.entries(Lf))if(new URL(n.appBaseUrl).hostname.toLowerCase()===t||new URL(n.mcpBaseUrl).hostname.toLowerCase()===t)return r;return null}function Pv(e){const t=String(e||"").trim();if(!t)return null;try{return Sx(new URL(t).hostname)}catch{return null}}function Ax(e){const t=Pv(e);return t?Lf[t].mcpBaseUrl:null}function od(e,t){return String(e[t]||"").trim()}function db(e,t,r){e.push(t),r?.(t)}function Cx(e,t){const r=[],n=od(e,"ENV"),s=Tg(n);if(s)return db(r,`[Taskforce compat] ENV=${n} is deprecated; set TASKFORCE_CLOUD_ENVIRONMENT=${s} instead.`,t),{cloudEnvironment:s,warnings:r};const i=[{key:"TASKFORCE_CLOUD_PROXY_BASE_URL",value:od(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL",value:od(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")},{key:"VITE_TASKFORCE_CLOUD_MCP_BASE_URL",value:od(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL")},{key:"VITE_TASKFORCE_API_BASE_URL",value:od(e,"VITE_TASKFORCE_API_BASE_URL")},{key:"VITE_TASKFORCE_BASE_URL",value:od(e,"VITE_TASKFORCE_BASE_URL")},{key:"TASKFORCE_BASE_URL",value:od(e,"TASKFORCE_BASE_URL")}];for(const l of i){if(!l.value)continue;const c=Pv(l.value);if(c)return db(r,`[Taskforce compat] ${l.key} is being used to infer TASKFORCE_CLOUD_ENVIRONMENT=${c}. Set TASKFORCE_CLOUD_ENVIRONMENT explicitly.`,t),{cloudEnvironment:c,warnings:r}}return{cloudEnvironment:null,warnings:r}}function Ki(e,t){return String(e[t]||"").trim()}function Ix(e){return e.toLowerCase()==="cloud"?"cloud":"local"}function bu(e){return String(e||"").trim().replace(/\/+$/,"")}function _x(e){return String(e||"").trim().replace(/\/+$/,"")}function _c(...e){for(const t of e)if(String(t||"").trim())return String(t||"").trim();return""}function Tx(e,t={}){const r=[],n=v=>{r.push(v),t.onWarning?.(v)},s=Ix(Ki(e,"TASKFORCE_RUNTIME_MODE")),i=Tg(Ki(e,"TASKFORCE_CLOUD_ENVIRONMENT")),l=i?{cloudEnvironment:i}:Cx(e,n),c=i||l.cloudEnvironment,d=bu(String(t.requestBaseUrl||"")),f=bu(_c(Ki(e,"VITE_TASKFORCE_BASE_URL"),Ki(e,"TASKFORCE_BASE_URL"))),p=bu(Ki(e,"VITE_TASKFORCE_API_BASE_URL")),g=bu(Ki(e,"VITE_TASKFORCE_CLOUD_AUTH_BASE_URL")),h=bu(_c(Ki(e,"VITE_TASKFORCE_CLOUD_MCP_BASE_URL"),Ki(e,"TASKFORCE_CLOUD_MCP_BASE_URL"))),y=bu(Ki(e,"TASKFORCE_CLOUD_PROXY_BASE_URL")),k=_x(Ki(e,"VITE_TASKFORCE_WS_BASE_URL")),b=c?Lf[c].appBaseUrl:"",C=c?Lf[c].mcpBaseUrl:"",S=_c(y,g,p,f,b),w=_c(h,C,S),T=_c(d,f,p,g,S),E=_c(d,p,f,S),x=_c(g,f,p,S),N=s==="local"?_c(k,d,p,f,y,g,b,S):_c(d,k,E,T,S);return{runtimeMode:s,cloudEnvironment:c,cloudBaseUrl:S,cloudMcpBaseUrl:w,baseUrl:T,apiBaseUrl:E,cloudAuthBaseUrl:x,wsBaseUrl:N,cloudAuthViaLocalProxy:s==="local"||!!y,warnings:r}}function Ev(e){return Tx({TASKFORCE_CLOUD_ENVIRONMENT:"",VITE_TASKFORCE_BASE_URL:e.VITE_TASKFORCE_BASE_URL,VITE_TASKFORCE_API_BASE_URL:e.VITE_TASKFORCE_API_BASE_URL,VITE_TASKFORCE_CLOUD_AUTH_BASE_URL:e.VITE_TASKFORCE_CLOUD_AUTH_BASE_URL,VITE_TASKFORCE_CLOUD_MCP_BASE_URL:e.VITE_TASKFORCE_CLOUD_MCP_BASE_URL,VITE_TASKFORCE_WS_BASE_URL:e.VITE_TASKFORCE_WS_BASE_URL})}function ub(e){const t=String(e.workspaceId||"default").trim().replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"default",r=Number.isFinite(Number(e.epoch))?Math.max(0,Math.floor(Number(e.epoch))):0,n=String(e.seed||"session").trim().replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"session",s=String(e.phase||"bootstrap").trim().replace(/[^A-Za-z0-9_-]+/g,"-").replace(/^-+|-+$/g,"")||"bootstrap";return`tfb-${n}-${t}-e${r}-${s}`}function Qy(e,t){const r=String(t||"").trim();if(!r)return e;const n=new Headers(e?.headers||void 0);return n.has("x-taskforce-bootstrap-trace-id")||n.set("x-taskforce-bootstrap-trace-id",r),{...e||{},headers:n}}function xx(e){const t=String(e.activeWorkspaceId||"").trim();return{email:e.email,password:e.password,...t&&t!=="default"?{workspaceId:t}:{}}}const Jh="unassigned",LA="agent",qf="UserRound",xg="color-mix(in srgb, var(--text-helper) 68%, transparent)",Rx="user",jx=/^[0-9a-f]{8,}$/i,Cd={value:Jh,label:"Unassigned",icon:qf,color:xg,kind:"unassigned"};function OA(e){const t=String(e||"").trim().toLowerCase();return t===LA||t==="ai"||t.startsWith("ai-profile-")}function Nv(e){const t=String(e||"").trim().toLowerCase();return!t||t===Jh||t==="none"||t==="null"||t===Rx}function jk(e){return OA(e)?"agent":Nv(e)?"unassigned":"member"}function Px(e){const t=String(e.displayName||"").trim(),r=String(e.email||"").trim().toLowerCase();return t||r||String(e.userId||"").trim()||"Workspace member"}function gl(){return[{...Cd}]}function Ex(e){const t=new Map;for(const r of e){const n=String(r.userId||"").trim();n&&t.set(n,{value:n,label:Px(r),icon:"User",color:"#22c55e",kind:"member",avatarUrl:typeof r.avatarUrl=="string"&&r.avatarUrl.trim().length>0?r.avatarUrl.trim():null})}return $u(Array.from(t.values()))}function $u(e){const t=new Map;for(const n of gl())t.set(n.value,n);for(const n of Array.isArray(e)?e:[]){const s=String(n?.value||"").trim(),i=typeof n?.archivedAt=="string"?n.archivedAt.trim():"";!s||i||s===Jh||s===LA||t.set(s,{value:s,label:String(n.label||s).trim()||s,icon:String(n.icon||(n.kind==="agent"?"Bot":"User")),color:String(n.color||(n.kind==="agent"?"#8b5cf6":"#22c55e")),kind:n.kind==="agent"?"agent":"member",avatarUrl:typeof n.avatarUrl=="string"&&n.avatarUrl.trim().length>0?n.avatarUrl.trim():null,avatarRevision:Number.isFinite(Number(n.avatarRevision))?Math.max(0,Math.floor(Number(n.avatarRevision))):null,avatarUpdatedAt:typeof n.avatarUpdatedAt=="string"&&n.avatarUpdatedAt.trim().length>0?n.avatarUpdatedAt.trim():null,username:typeof n.username=="string"&&n.username.trim().length>0?n.username.trim():null,surfaceType:typeof n.surfaceType=="string"&&n.surfaceType.trim().length>0?n.surfaceType.trim():null,providerMetadata:n.providerMetadata&&typeof n.providerMetadata=="object"&&!Array.isArray(n.providerMetadata)?n.providerMetadata:null,archivedAt:null,createdAt:typeof n.createdAt=="string"&&n.createdAt.trim().length>0?n.createdAt.trim():null,updatedAt:typeof n.updatedAt=="string"&&n.updatedAt.trim().length>0?n.updatedAt.trim():null})}const r=[Jh];return Array.from(t.values()).sort((n,s)=>{const i=r.indexOf(n.value),l=r.indexOf(s.value);return i>=0||l>=0?i<0?1:l<0?-1:i-l:n.label.localeCompare(s.label,void 0,{sensitivity:"base"})})}function BA(e,t){const r=String(t||"").trim();if(!r||e.some(i=>i.value===r))return e;const n=r.replace(/^ai-profile-/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim(),s=n?n.split(" ").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" "):r;if(jk(r)==="agent"){const i=String(r).toLowerCase().startsWith("ai-profile-")&&n.split(" ").every(l=>jx.test(l));return $u([...e,{value:r,label:i?"AI":s||"AI",icon:"Bot",color:"#8b5cf6",kind:"agent"}])}return jk(r)==="member"?$u([...e,{value:r,label:s||r,icon:"User",color:"#22c55e",kind:"member"}]):e}function WA(e){const t=Array.isArray(e)?e.filter(Boolean):[];return $u(t)}function Of(e,t){const r=String(e||"").trim(),s=WA(t).find(i=>i.value===r);return s?s.label:OA(r)?"AI":Nv(r)?"Unassigned":r||"Unassigned"}const Pk=1,$A="taskforce.workspaceContext.v2",Nx="taskforce.uiState.app.v1",Mx="taskforce.bootstrapDebug.v1",pb=5e3,Xm=new Map;function eh(e){return Array.from(new Set(e.map(t=>String(t??"").trim()).filter(t=>t.length>0))).sort()}function Fu(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function kd(e){if(Array.isArray(e))return Array.from(new Set(e.filter(t=>typeof t=="string").map(t=>t.trim()).filter(Boolean)))}function Ek(e){if(Array.isArray(e))return Array.from(new Set(e.filter(t=>typeof t=="string"&&t.trim().length>0||typeof t=="number")))}function Dx(e){if(!Fu(e))return;const t={};return Object.entries(e).forEach(([r,n])=>{const s=String(r||"").trim(),i=Ek(n);!s||!i||(t[s]=i)}),t}function Lx(e){if(!Fu(e))return;const t={};return Object.entries(e).forEach(([r,n])=>{const s=String(r||"").trim();!s||typeof n!="boolean"||(t[s]=n)}),t}function Ox(e){if(!Fu(e))return;const t={};return Object.entries(e).forEach(([r,n])=>{const s=String(r||"").trim();if(!s||typeof n!="string")return;const i=n.trim();i&&(t[s]=i)}),t}function Bx(e){if(!Fu(e))return;const t=kd(e.categories),r=kd(e.types),n=kd(e.priorities);if(!t||!r||!n)return;const s={};return Fu(e.taxonomies)&&Object.entries(e.taxonomies).forEach(([i,l])=>{const c=String(i||"").trim(),d=kd(l);!c||!d||(s[c]=d)}),{categories:t,types:r,priorities:n,taxonomies:s}}function FA(e){if(!Fu(e))return null;const t={version:Pk},r=["category","type","priority","assignee","status","complexity","schedule","docs"];e.groupBy==="approach"&&(t.groupBy="status"),typeof e.groupBy=="string"&&r.includes(e.groupBy)&&(t.groupBy=e.groupBy);const n=e.activeWorkspaceModule==="agents"?"aiProfiles":e.activeWorkspaceModule==="workflows"?"tasks":e.activeWorkspaceModule;typeof n=="string"&&["tasks","planning","docs","annotate","workflowManager","taskforceAgents","aiProfiles"].includes(n)&&(t.activeWorkspaceModule=n),(e.emptyColumnMode==="show"||e.emptyColumnMode==="collapse"||e.emptyColumnMode==="hide")&&(t.emptyColumnMode=e.emptyColumnMode),(e.taskScope==="open"||e.taskScope==="archived"||e.taskScope==="deleted")&&(t.taskScope=e.taskScope),typeof e.openTaskId=="string"?t.openTaskId=e.openTaskId.trim()||null:e.openTaskId===null&&(t.openTaskId=null),typeof e.compressedCards=="boolean"&&(t.compressedCards=e.compressedCards),typeof e.zenMode=="boolean"&&(t.zenMode=e.zenMode),typeof e.searchQuery=="string"&&(t.searchQuery=e.searchQuery);const i=Lx(e.collapsedCategories);i&&(t.collapsedCategories=i);const l=kd(e.filterCategories);l&&(t.filterCategories=l);const c=Ek(e.filterPriorities);c&&(t.filterPriorities=c);const d=kd(e.filterTypes);d&&(t.filterTypes=d);const f=Ek(e.filterStatus);f&&(t.filterStatus=f);const p=kd(e.filterAssignees);p&&(t.filterAssignees=p),typeof e.filterAssigneesAllSelected=="boolean"&&(t.filterAssigneesAllSelected=e.filterAssigneesAllSelected);const g=Dx(e.filterTaxonomies);g&&(t.filterTaxonomies=g);const h=Bx(e.filterTaxonomySignature);if(h&&(t.filterTaxonomySignature=h),(e.sortBy==="created"||e.sortBy==="priority"||e.sortBy==="updated"||e.sortBy==="complexity")&&(t.sortBy=e.sortBy),(e.sortOrder==="asc"||e.sortOrder==="desc")&&(t.sortOrder=e.sortOrder),typeof e.hasInitedFilters=="boolean"&&(t.hasInitedFilters=e.hasInitedFilters),typeof e.lastCategory=="string"&&(t.lastCategory=e.lastCategory),typeof e.taskforceAgentId=="string"){const k=e.taskforceAgentId.trim();k&&(t.taskforceAgentId=k)}if(typeof e.taskforceAgentConversationId=="string"){const k=e.taskforceAgentConversationId.trim();k&&(t.taskforceAgentConversationId=k)}const y=Ox(e.taskforceAgentConversationByAgentId);return y&&Object.keys(y).length>0&&(t.taskforceAgentConversationByAgentId=y),t}function Wx(e){const t=eh(e.categories.map(i=>i.value)),r=eh(e.types.map(i=>i.value)),n=eh(e.priorities.map(i=>i.value));if(t.length===0||r.length===0||n.length===0)return null;const s={};return(e.taxonomies||[]).forEach(i=>{const l=String(i.id??"").trim();l&&(s[l]=eh((i.options||[]).map(c=>c.value)))}),{categories:t,types:r,priorities:n,taxonomies:s}}function Jp(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}function $x(e,t){if(!e||!t||!Jp(e.categories||[],t.categories||[])||!Jp(e.types||[],t.types||[])||!Jp(e.priorities||[],t.priorities||[]))return!1;const r=Object.keys(e.taxonomies||{}).sort(),n=Object.keys(t.taxonomies||{}).sort();return Jp(r,n)?r.every(s=>Jp(e.taxonomies[s]||[],t.taxonomies[s]||[])):!1}function Fx(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem(Mx)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function wr(e,t){if(!Fx())return;console.info("[Taskforce Bootstrap]",e,t&&typeof t=="object"?t:{})}function Ux(e,t,r,n=!1){const s=String(e).trim()||"default",i=String(t).trim()||"default",l=String(r||"default").trim()||"default";return`${n?"cloud":"same-origin"}::${i}::${s}::${l}`}async function Af(e){const t=String(e.stateKey||"default").trim()||"default",r=String(e.workspaceId||"").trim(),n=e.patch&&typeof e.patch=="object"?e.patch:{},s=JSON.stringify(n),i=Ux(t,r||"default",e.dedupeScope,e.useCloudProxy),l=Date.now(),c=Xm.get(i);if(c&&c.serializedPatch===s){if(c.status==="success"&&e.skipIfUnchanged!==!1)return wr("ui_state_persist_skipped",{stateKey:t,workspaceId:r||"default",reason:"unchanged"}),{skipped:!0,reason:"unchanged"};if(e.respectFailureCooldown!==!1&&c.retryAfter>l)return wr("ui_state_persist_skipped",{stateKey:t,workspaceId:r||"default",reason:"cooldown",retryAfterMs:c.retryAfter-l}),{skipped:!0,reason:"cooldown"}}try{const d=await fetch(`/api/taskforce/ui-state${e.useCloudProxy?"?taskforceCloud=1":""}`,{method:"POST",headers:{"Content-Type":"application/json",...e.headers||{}},credentials:"include",...e.keepalive?{keepalive:!0}:{},body:JSON.stringify({stateKey:t,...r?{workspaceId:r}:{},patch:n})}),f=await d.json().catch(()=>({}));if(d.ok&&f?.success!==!1)return Xm.set(i,{serializedPatch:s,status:"success",retryAfter:0}),{skipped:!1,response:d,payload:f};if(Xm.set(i,{serializedPatch:s,status:"failure",retryAfter:l+(e.failureRetryMs??pb)}),wr("ui_state_persist_failed",{stateKey:t,workspaceId:r||"default",status:d.status,error:String(f?.error||"")}),e.throwOnError)throw new Error(String(f?.error||`Failed to persist UI state (${d.status})`));return{skipped:!1,response:d,payload:f}}catch(d){if(Xm.set(i,{serializedPatch:s,status:"failure",retryAfter:l+(e.failureRetryMs??pb)}),wr("ui_state_persist_failed",{stateKey:t,workspaceId:r||"default",error:d instanceof Error?d.message:String(d)}),e.throwOnError)throw d;return{skipped:!1,payload:null}}}function Mv(e){const t=_g(e);return`${$A}.${t}`}function UA(e){const t=Rv(e);return`${$A}.${t}`}function Nk(e){if(typeof window>"u")return"";try{const t=Mv(e),r=String(window.localStorage.getItem(t)||"").trim();if(r&&r.length<=120&&!/\s/.test(r))return r;const n=UA(e),s=String(window.localStorage.getItem(n)||"").trim();return s&&s.length<=120&&!/\s/.test(s)?(window.localStorage.setItem(t,s),s):""}catch{return""}}function zx(e,t){if(typeof window>"u")return;const r=String(e||"").trim();try{if(!r||jv(r))return;const n=Mv(t),s=String(window.localStorage.getItem(n)||"").trim();if(!r&&s&&s.toLowerCase()!=="default")return;window.localStorage.setItem(n,r)}catch{}}function fb(e){if(!(typeof window>"u"))try{window.localStorage.removeItem(Mv(e)),window.localStorage.removeItem(UA(e))}catch{}}function zA(e){const t=Rv(e);return`${Nx}.${t}`}function mb(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(zA(e));if(!t)return null;const r=JSON.parse(t);return FA(r)}catch{return null}}function Hx(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(zA(t),JSON.stringify(e))}catch{}}const Mk="taskforce.localMutationActorUserId.v1";function HA(e){return typeof e=="string"?e.trim().replace(/\/+$/,""):""}function Gx(e){const t=String(e||"").trim().toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="::1"||t==="[::1]"}function pf(e){if(!(typeof window>"u"))try{const t=String(e||"").trim();if(!t||t==="anonymous"){window.sessionStorage.removeItem(Mk);return}window.sessionStorage.setItem(Mk,t)}catch{}}function Dv(){if(typeof window>"u")return"";try{return String(window.sessionStorage.getItem(Mk)||"").trim()}catch{return""}}function Vx(e,t){if(typeof window>"u"||!e.startsWith("/api/taskforce/")||!Gx(window.location.hostname))return!1;try{return new URL(t,window.location.origin).origin===window.location.origin}catch{return e.startsWith("/")}}function Kx(e,t,r){if(!Vx(e,t))return r;const n=Dv();if(!n)return r;const s=new Headers(r?.headers||void 0);return s.has("x-taskforce-user-id")||s.set("x-taskforce-user-id",n),{...r,headers:s}}function qx(e,t){if(!e.startsWith("/"))return e;const r=HA(t);return r?`${r}${e}`:e}async function Yx(e,t,r){const n=qx(e,r),s=HA(r).length>0,i=Kx(e,n,t),l=typeof performance<"u"?performance.now():Date.now();try{const c=await fetch(n,i);if(!(s&&n!==e&&e.startsWith("/api/taskforce/")&&(c.status===401||c.status===403)))return c;wr("taskforce_api_auth_fallback_retry",{path:e,primaryUrl:n,fallbackUrl:e,status:c.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-l)});try{const f=await fetch(e,i);return wr("taskforce_api_auth_fallback_completed",{path:e,primaryUrl:n,fallbackUrl:e,primaryStatus:c.status,fallbackStatus:f.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-l)}),f}catch{return wr("taskforce_api_auth_fallback_failed",{path:e,primaryUrl:n,fallbackUrl:e,status:c.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-l)}),c}}catch(c){if(!s||!e.startsWith("/"))throw c;wr("taskforce_api_network_fallback_retry",{path:e,primaryUrl:n,fallbackUrl:e,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-l),error:c instanceof Error?c.message:String(c)});const d=await fetch(e,i);return wr("taskforce_api_network_fallback_completed",{path:e,primaryUrl:n,fallbackUrl:e,fallbackStatus:d.status,durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-l)}),d}}const ff=Object.freeze({coverageProfileId:"task-planning-metadata",coverageVersion:4,coverageDigest:"c622f33d62c9f9251559a5b3644ba617da31c1b53d4fd0927b529e76c89948d1"}),Lv=Object.freeze(["task/root-v1","task-relationship/full-v1","taxonomy/full-v1","initiative/full-v1","workstream/full-v1","task-comments/full-v1","task-checklist/full-v1","task-attachment-links/full-v1","entity-event/full-v1"]),mf=Object.freeze({coverageProfileId:"task-planning-metadata",coverageVersion:5,coverageDigest:"1227152d1998809427f8560f85c8ef2da8780d3ea697390fbaa48c9e85a97be2"}),Zx=Lv,hf=Object.freeze({coverageProfileId:"task-planning-metadata",coverageVersion:6,coverageDigest:"0aa90b110c71cf37a1234617b098d055f1df1e8da389184c7b147833164e338d"}),Jx=Object.freeze([...Lv,"workstream-task-order/full-v1"]),kn=Object.freeze({coverageProfileId:"task-planning-metadata",coverageVersion:3,coverageDigest:"48544ecfcb72c44866cdd39d02d0ba83222bc5e236045880f7f62b979be46117"}),Qx=1,Xx=Object.freeze(["task/root-v1","task-relationship/full-v1","taxonomy/full-v1","initiative/full-v1","workstream/full-v1"]);function yl(e){const t=String(e.coverageProfileId||"").trim(),r=Number(e.coverageVersion),n=String(e.coverageDigest||"").trim();return t===kn.coverageProfileId&&r===kn.coverageVersion&&n===kn.coverageDigest?{coverage:kn,excludedProjections:Xx,nestedWriterPrerequisitesRequired:!1,workflowWriterPrerequisitesRequired:!1,planningOrderWriterPrerequisitesRequired:!1}:t===ff.coverageProfileId&&r===ff.coverageVersion&&n===ff.coverageDigest?{coverage:ff,excludedProjections:Lv,nestedWriterPrerequisitesRequired:!0,workflowWriterPrerequisitesRequired:!1,planningOrderWriterPrerequisitesRequired:!1}:t===mf.coverageProfileId&&r===mf.coverageVersion&&n===mf.coverageDigest?{coverage:mf,excludedProjections:Zx,nestedWriterPrerequisitesRequired:!0,workflowWriterPrerequisitesRequired:!0,planningOrderWriterPrerequisitesRequired:!1}:t===hf.coverageProfileId&&r===hf.coverageVersion&&n===hf.coverageDigest?{coverage:hf,excludedProjections:Jx,nestedWriterPrerequisitesRequired:!0,workflowWriterPrerequisitesRequired:!1,planningOrderWriterPrerequisitesRequired:!0}:null}function GA(e){for(const t of[kn,ff,mf,hf]){const r=yl(t);if(e.length===r.excludedProjections.length&&r.excludedProjections.every((n,s)=>e[s]===n))return t}return null}function Ov(e,t=kn){if(!e||typeof e!="object"||Array.isArray(e))return!1;const r=e,n=r.coverage;return r.capabilityVersion===Qx&&r.runtimeMode==="cloud"&&r.routeAvailable===!0&&r.writerPrerequisitesReady===!0&&r.activationReady===!0&&Array.isArray(r.missingPrerequisites)&&r.missingPrerequisites.length===0&&!!n&&typeof n=="object"&&!Array.isArray(n)&&n.coverageProfileId===t.coverageProfileId&&n.coverageVersion===t.coverageVersion&&n.coverageDigest===t.coverageDigest}function Bv(e,t=kn){if(!e||typeof e!="object"||Array.isArray(e))return!1;const r=e,n=r.excludedProjections,s=yl(t);return s?r.cloudWritesFenced===!0&&Array.isArray(n)&&n.length===s.excludedProjections.length&&s.excludedProjections.every((i,l)=>n[l]===i):!1}function eR(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return t.cloudWritesFenced===!1&&Array.isArray(t.excludedProjections)&&t.excludedProjections.length===0}const VA=Object.freeze(["task/root-v1","task-relationship/full-v1","taxonomy/full-v1","initiative/full-v1","workstream/full-v1","task-comments/full-v1","task-checklist/full-v1","task-attachment-links/full-v1","entity-event/full-v1","workstream-task-order/full-v1"]),tR=new Set(VA);function hb(e){const t=new Set;for(const r of e||[]){const n=String(r||"").trim();if(!n||!tR.has(n)||t.has(n))throw new Error("Workspace sync v2 projection exclusions are invalid.");t.add(n)}return VA.filter(r=>t.has(r))}function rR(e,t){try{const r=hb(e),n=hb(t);return r.length===n.length&&r.every((s,i)=>s===n[i])}catch{return!1}}function aR(e,t){const r=[],n={},s=i=>{n[i]=(n[i]||0)+1};for(const i of e){if(i.op==="upsert"){const l=t.has("task-comments/full-v1"),c=t.has("task-checklist/full-v1"),d=t.has("task-attachment-links/full-v1");if(t.has("task/root-v1")&&s("task/root-v1"),l||c||d){const f={...i.task};l&&(delete f.comments,s("task-comments/full-v1")),c&&(delete f.checklistItems,s("task-checklist/full-v1")),d&&(delete f.attachments,s("task-attachment-links/full-v1")),r.push({...i,task:f});continue}}if(t.has("task/root-v1")&&i.op==="delete"){s("task/root-v1");continue}if(t.has("task-relationship/full-v1")&&(i.op==="task-relationship-upsert"||i.op==="task-relationship-delete")){s("task-relationship/full-v1");continue}if(t.has("taxonomy/full-v1")&&i.op==="taxonomy-upsert"){s("taxonomy/full-v1");continue}if(t.has("initiative/full-v1")&&i.op==="initiative-upsert"){s("initiative/full-v1");continue}if(t.has("workstream/full-v1")&&i.op==="workstream-upsert"){s("workstream/full-v1");continue}if(t.has("entity-event/full-v1")&&(i.op==="task-event-upsert"||i.op==="entity-event-upsert")){s("entity-event/full-v1");continue}r.push(i)}return{changes:r,suppressedCounts:n}}function Dk(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number"){if(!Number.isFinite(e))throw new Error("Canonical JSON cannot contain non-finite numbers.");return e}if(Array.isArray(e))return e.map(Dk);if(typeof e=="object"){const t={};for(const r of Object.keys(e).sort()){const n=e[r];n!==void 0&&(t[r]=Dk(n))}return t}throw new Error(`Canonical JSON cannot contain ${typeof e}.`)}function $a(e){return JSON.stringify(Dk(e))}const KA=1;function nR(e){if(e.version!==KA)throw new TypeError("The sync transfer completion group version is unsupported.");if(!e.workspaceId.trim())throw new TypeError("The sync transfer completion group workspace is required.");if(!Number.isSafeInteger(e.coordinatorGeneration)||e.coordinatorGeneration<0)throw new TypeError("The sync transfer completion group generation is invalid.");if(e.ownerMode!=="browser-gateway"&&e.ownerMode!=="server")throw new TypeError("The sync transfer completion group owner is invalid.");if(!e.serverInstanceId.trim())throw new TypeError("The sync transfer completion group server instance is required.");if(!Array.isArray(e.permitIds)||e.permitIds.length===0)throw new TypeError("The sync transfer completion group requires at least one permit.");const t=e.permitIds.map(r=>r.trim());if(t.some((r,n)=>!r||r!==e.permitIds[n]))throw new TypeError("The sync transfer completion group contains an invalid permit ID.");if(new Set(t).size!==t.length)throw new TypeError("The sync transfer completion group contains duplicate permit IDs.");$a(e.previousBoundary),$a(e.expectedBoundary)}const mo=45e3,Wv=18e4;function Rg(e,t){const r=t?.completionGroup;if(!r)return{};if(nR(r),r.workspaceId!==e)throw new TypeError("The local sync apply completion group workspace does not match the request.");if(r.ownerMode!=="browser-gateway")throw new TypeError("The local sync browser apply requires a browser-gateway completion group.");return{coordinatorGeneration:r.coordinatorGeneration,permitIds:[...r.permitIds]}}async function qA(e,t=100){const r=new URLSearchParams({workspaceId:e,limit:String(Math.max(1,Math.min(100,Math.floor(t))))});return an(fetch(`/api/taskforce/sync/workspace/content-obligations?${r.toString()}`,{credentials:"include",headers:{"x-taskforce-workspace-id":e}}))}async function YA(e,t,r){return an(fetch("/api/taskforce/sync/workspace/content-obligations/failures",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json","x-taskforce-workspace-id":e},body:JSON.stringify({workspaceId:e,obligationIds:t,error:r})}))}async function sR(e,t,r=[],n=[],s=lC){const i=await s(e);if(!i.ok)return i;const l=new Set(Array.from(t,v=>String(v||"").trim()).filter(Boolean)),c=new Set(Array.from(r,v=>String(v||"").trim()).filter(Boolean)),d=new Set(Array.from(n,v=>String(v||"").trim()).filter(Boolean)),f=i.data;if(f.success!==!0||f.contractVersion!==3||f.workspaceId!==e||!Array.isArray(f.tasks)||!Array.isArray(f.activeTaskRelationshipIds)||!Array.isArray(f.initiatives)||!Array.isArray(f.workstreams)||!f.initiativeProjection||typeof f.initiativeProjection!="object"||f.initiativeProjection.owner!=="v2"&&f.initiativeProjection.owner!=="v3"||typeof f.initiativeProjection.epoch!="string"||!/^\d+$/.test(f.initiativeProjection.epoch)||f.activeTaskRelationshipIds.some(v=>typeof v!="string"||!v.trim())||!f.taxonomy||typeof f.taxonomy!="object"||Array.isArray(f.taxonomy)||typeof f.taxonomy.activeOperation!="boolean"||typeof f.taxonomy.owned!="boolean"||typeof f.taxonomy.entityRevision!="string"||!/^\d+$/.test(f.taxonomy.entityRevision)||typeof f.taxonomy.lifecycleRevision!="string"||!/^\d+$/.test(f.taxonomy.lifecycleRevision)||f.taxonomy.lastSequence!==null&&(typeof f.taxonomy.lastSequence!="string"||!/^\d+$/.test(f.taxonomy.lastSequence)))return{ok:!1,status:502,data:{activeMetadataTaskIds:[],activeCreateTaskIds:[],activeDeleteTaskIds:[],activeLifecycleTaskIds:[],activeReopenTaskIds:[],activeTaskRelationshipIds:[],activeInitiativeIds:[],protectedInitiativeIds:[],protectedWorkstreamIds:[],taxonomyProtected:!0,initiativeProjectionOwner:"v3",initiativeProjectionEpoch:"0",combinedProjectionOwner:"v2",combinedProjectionEpoch:"0"}};const p=f.combinedProjection;if(p!==void 0&&(!p||typeof p!="object"||Array.isArray(p)||p.owner!=="v2"&&p.owner!=="v3"||typeof p.epoch!="string"||!/^\d+$/.test(p.epoch)))return{ok:!1,status:502,data:{activeMetadataTaskIds:[],activeCreateTaskIds:[],activeDeleteTaskIds:[],activeLifecycleTaskIds:[],activeReopenTaskIds:[],activeTaskRelationshipIds:[],activeInitiativeIds:[],protectedInitiativeIds:[],protectedWorkstreamIds:[],taxonomyProtected:!0,initiativeProjectionOwner:"v3",initiativeProjectionEpoch:"0",combinedProjectionOwner:"v2",combinedProjectionEpoch:"0"}};const g=p?yl({coverageProfileId:p.coverageProfileId,coverageVersion:p.coverageVersion,coverageDigest:p.coverageDigest}):null;if(p?.owner==="v3"&&!g)return{ok:!1,status:502,data:{activeMetadataTaskIds:[],activeCreateTaskIds:[],activeDeleteTaskIds:[],activeLifecycleTaskIds:[],activeReopenTaskIds:[],activeTaskRelationshipIds:[],activeInitiativeIds:[],protectedInitiativeIds:[],protectedWorkstreamIds:[],taxonomyProtected:!0,initiativeProjectionOwner:"v3",initiativeProjectionEpoch:"0",combinedProjectionOwner:"v2",combinedProjectionEpoch:"0",combinedExcludedProjections:[]}};const h=[];for(const v of f.tasks){const V=String(v?.taskId||"").trim();if(!v||typeof v!="object"||Array.isArray(v)||!V||typeof v.activeOperation!="boolean"||typeof v.activeCreateOperation!="boolean"||v.activeDeleteOperation!==void 0&&typeof v.activeDeleteOperation!="boolean"||v.deleteOwned!==void 0&&typeof v.deleteOwned!="boolean"||typeof v.activeLifecycleOperation!="boolean"||typeof v.activeReopenOperation!="boolean"||typeof v.reopenAssigneeOwned!="boolean")return{ok:!1,status:502,data:{activeMetadataTaskIds:[],activeCreateTaskIds:[],activeDeleteTaskIds:[],activeLifecycleTaskIds:[],activeReopenTaskIds:[],activeTaskRelationshipIds:[],activeInitiativeIds:[],protectedInitiativeIds:[],protectedWorkstreamIds:[],taxonomyProtected:!0,initiativeProjectionOwner:"v3",initiativeProjectionEpoch:"0",combinedProjectionOwner:"v2",combinedProjectionEpoch:"0"}};h.push({entry:v,taskId:V})}const y=h.filter(({taskId:v})=>v.length>0&&l.has(v)),k=Array.from(new Set(y.filter(({entry:v})=>v?.activeOperation===!0).map(({taskId:v})=>v))).sort(),b=Array.from(new Set(y.filter(({entry:v})=>v?.activeCreateOperation===!0).map(({taskId:v})=>v))).sort(),C=Array.from(new Set(y.filter(({entry:v})=>v?.activeDeleteOperation===!0||v?.deleteOwned===!0).map(({taskId:v})=>v))).sort(),S=Array.from(new Set(y.filter(({entry:v})=>v?.activeLifecycleOperation===!0).map(({taskId:v})=>v))).sort(),w=Array.from(new Set(y.filter(({entry:v})=>v?.activeReopenOperation===!0).map(({taskId:v})=>v))).sort(),T=Array.from(new Set(f.activeTaskRelationshipIds.map(v=>String(v).trim()))).sort(),E=[],x=[];for(const v of f.initiatives){const V=String(v?.entityId||"").trim();if(!(v&&typeof v=="object"&&!Array.isArray(v)&&v.domain==="initiative"&&V.length>0&&typeof v.activeOperation=="boolean"&&typeof v.owned=="boolean"&&typeof v.entityRevision=="string"&&/^\d+$/.test(v.entityRevision)&&typeof v.lifecycleRevision=="string"&&/^\d+$/.test(v.lifecycleRevision)&&(v.lastSequence===null||typeof v.lastSequence=="string"&&/^\d+$/.test(v.lastSequence))&&(v.canonicalFingerprint===null||typeof v.canonicalFingerprint=="string"&&/^[a-f0-9]{64}$/.test(v.canonicalFingerprint))))return{ok:!1,status:502,data:{activeMetadataTaskIds:[],activeCreateTaskIds:[],activeDeleteTaskIds:[],activeLifecycleTaskIds:[],activeReopenTaskIds:[],activeTaskRelationshipIds:[],activeInitiativeIds:[],protectedInitiativeIds:[],protectedWorkstreamIds:[],taxonomyProtected:!0,initiativeProjectionOwner:"v3",initiativeProjectionEpoch:"0",combinedProjectionOwner:"v2",combinedProjectionEpoch:"0"}};c.has(V)&&(v.activeOperation===!0&&E.push(V),(v.activeOperation===!0||v.owned===!0)&&x.push(V))}const N=[];for(const v of f.workstreams){const V=String(v?.entityId||"").trim();if(!(v&&typeof v=="object"&&!Array.isArray(v)&&v.domain==="workstream"&&V.length>0&&typeof v.activeOperation=="boolean"&&typeof v.owned=="boolean"&&typeof v.entityRevision=="string"&&/^\d+$/.test(v.entityRevision)&&typeof v.lifecycleRevision=="string"&&/^\d+$/.test(v.lifecycleRevision)&&(v.lastSequence===null||typeof v.lastSequence=="string"&&/^\d+$/.test(v.lastSequence))&&(v.canonicalFingerprint===null||typeof v.canonicalFingerprint=="string"&&/^[a-f0-9]{64}$/.test(v.canonicalFingerprint))))return{ok:!1,status:502,data:{activeMetadataTaskIds:[],activeCreateTaskIds:[],activeDeleteTaskIds:[],activeLifecycleTaskIds:[],activeReopenTaskIds:[],activeTaskRelationshipIds:[],activeInitiativeIds:[],protectedInitiativeIds:[],protectedWorkstreamIds:[],taxonomyProtected:!0,initiativeProjectionOwner:"v3",initiativeProjectionEpoch:"0",combinedProjectionOwner:"v2",combinedProjectionEpoch:"0"}};d.has(V)&&(v.activeOperation===!0||v.owned===!0)&&N.push(V)}return{ok:!0,status:i.status,data:{activeMetadataTaskIds:k,activeCreateTaskIds:b,activeDeleteTaskIds:C,activeLifecycleTaskIds:S,activeReopenTaskIds:w,activeTaskRelationshipIds:T,activeInitiativeIds:Array.from(new Set(E)).sort(),protectedInitiativeIds:Array.from(new Set(x)).sort(),protectedWorkstreamIds:Array.from(new Set(N)).sort(),taxonomyProtected:f.taxonomy.activeOperation===!0||f.taxonomy.owned===!0,initiativeProjectionOwner:f.initiativeProjection.owner,initiativeProjectionEpoch:f.initiativeProjection.epoch,combinedProjectionOwner:p?.owner==="v3"?"v3":"v2",combinedProjectionEpoch:p&&typeof p.epoch=="string"?p.epoch:"0",combinedCoverage:p?.owner==="v3"&&g?g.coverage:void 0,combinedExcludedProjections:p?.owner==="v3"&&g?[...g.excludedProjections]:[]}}}function oR(e){const t=Number(e?.status);return Number.isFinite(t)&&t>0?Math.floor(t):0}async function an(e){try{const t=await e,r=await t.text().catch(()=>"");let n={};if(r)try{n=JSON.parse(r)}catch{n={error:!t.ok&&t.statusText?`${t.status} ${t.statusText}`:r.slice(0,400)}}else!t.ok&&t.statusText&&(n={error:`${t.status} ${t.statusText}`});const s=t.headers.get("retry-after");let i;if(s){const l=Number.parseInt(s,10);if(Number.isFinite(l)&&l>0)i=l*1e3;else{const c=Date.parse(s);if(Number.isFinite(c)){const d=c-Date.now();d>0&&(i=d)}}}return{ok:t.ok,status:t.status,data:n,retryAfterMs:i}}catch(t){const n=String(t?.name||"").trim()==="AbortError"?{error:"Workspace sync pull request timed out."}:{};return{ok:!1,status:oR(t),data:n}}}function Ns(e,t,r){const n=typeof AbortController=="function"?new AbortController:null,s=n?globalThis.setTimeout(()=>n.abort(),Math.max(1,Math.floor(r))):null;return fetch(e,{...t,...n?{signal:n.signal}:{}}).finally(()=>{s!==null&&globalThis.clearTimeout(s)})}async function iR(e){return an(fetch(e("/api/taskforce/sync/user-settings"),{method:"GET",credentials:"include"}))}async function cR(e,t){return an(fetch(e("/api/taskforce/sync/user-settings"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(t)}))}async function lR(e,t){return an(fetch(e("/api/taskforce/sync/workspace/handshake"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:t})}))}async function dR(e,t){return an(fetch(e("/api/taskforce/sync/workspace/provision"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(t)}))}async function uR(e,t){const r=new URLSearchParams({limit:String(t.limit),workspaceId:t.workspaceId});if(t.cursor&&r.set("cursor",t.cursor),t.repairMode===!0&&r.set("repair","1"),t.contentMode==="manifest"&&r.set("content","manifest"),t.excludeInitiatives===!0&&r.set("excludeInitiatives","1"),t.excludedProjections?.length){r.set("excludeProjections",t.excludedProjections.join(","));const i=GA(t.excludedProjections);i&&(r.set("coverageProfileId",i.coverageProfileId),r.set("coverageVersion",String(i.coverageVersion)),r.set("coverageDigest",i.coverageDigest))}const n=e("/api/taskforce/sync/workspace/pull"),s=n.includes("?")?"&":"?";return an(Ns(`${n}${s}${r.toString()}`,{method:"GET",credentials:"include"},mo))}async function ZA(e,t){const r=new URLSearchParams({workspaceId:t.workspaceId,limit:String(t.limit||100)});t.cursor&&r.set("cursor",t.cursor),t.repairCursor&&r.set("repairCursor",t.repairCursor);const n=e("/api/taskforce/sync/v3/workspace/feed"),s=n.includes("?")?"&":"?";return an(Ns(`${n}${s}${r.toString()}`,{method:"GET",credentials:"include"},mo))}async function JA(e,t){const r=t.coverage||kn,n=new URLSearchParams({workspaceId:t.workspaceId,limit:String(t.limit||100),coverageProfileId:r.coverageProfileId,coverageVersion:String(r.coverageVersion),coverageDigest:r.coverageDigest});t.cursor&&n.set("cursor",t.cursor),t.repairCursor&&n.set("repairCursor",t.repairCursor),t.forceRepair===!0&&n.set("forceRepair","1");const s=e("/api/taskforce/sync/v3/workspace/feed"),i=s.includes("?")?"&":"?",l=t.forceRepair===!0||t.repairCursor?Wv:mo;return an(Ns(`${s}${i}${n.toString()}`,{method:"GET",credentials:"include"},l))}async function QA(e){const t=new URLSearchParams({workspaceId:e});return an(Ns(`/api/taskforce/sync/v3/local/feed?${t.toString()}`,{method:"GET",headers:{"x-taskforce-workspace-id":e},credentials:"include"},mo))}async function XA(e,t,r){return an(Ns("/api/taskforce/sync/v3/local/feed",{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-workspace-id":e},credentials:"include",body:JSON.stringify({workspaceId:e,...t,...Rg(e,r)})},mo))}async function eC(e,t=kn){const r=new URLSearchParams({workspaceId:e,coverageProfileId:t.coverageProfileId,coverageVersion:String(t.coverageVersion),coverageDigest:t.coverageDigest});return an(Ns(`/api/taskforce/sync/v3/local/feed?${r.toString()}`,{method:"GET",headers:{"x-taskforce-workspace-id":e},credentials:"include"},mo))}async function tC(e,t,r=kn,n){return an(Ns("/api/taskforce/sync/v3/local/feed",{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-workspace-id":e},credentials:"include",body:JSON.stringify({workspaceId:e,...t,...r,...Rg(e,n)})},mo))}async function rC(e){const t=new URLSearchParams({workspaceId:e});return an(Ns(`/api/taskforce/sync/v3/local/task-comment-audit?${t.toString()}`,{method:"GET",headers:{"x-taskforce-workspace-id":e},credentials:"include"},mo))}async function aC(e,t){const r=new URLSearchParams({workspaceId:t.workspaceId,limit:String(t.limit||50)});t.cursor&&r.set("cursor",t.cursor);const n=e("/api/taskforce/sync/v3/workspace/task-comment-audit"),s=n.includes("?")?"&":"?";return an(Ns(`${n}${s}${r.toString()}`,{method:"GET",credentials:"include"},mo))}async function nC(e,t,r){return an(Ns("/api/taskforce/sync/v3/local/task-comment-audit",{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-workspace-id":e},credentials:"include",body:JSON.stringify({workspaceId:e,page:t,...Rg(e,r)})},mo))}async function pR(e){return an(Ns("/api/taskforce/sync/v3/local/coordinator/recovery/authoritative-repair-complete",{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-workspace-id":e.workspaceId},credentials:"include",body:JSON.stringify(e)},mo))}async function sC(e,t){const r=new URLSearchParams({workspaceId:t.workspaceId,limit:String(t.limit||100)});t.cursor&&r.set("cursor",t.cursor);const n=e("/api/taskforce/sync/workspace/initiative-repair"),s=n.includes("?")?"&":"?";return an(Ns(`${n}${s}${r.toString()}`,{method:"GET",credentials:"include"},Wv))}async function oC(e,t){const r=t.coverage||kn,n=new URLSearchParams({workspaceId:t.workspaceId,limit:String(t.limit||100),coverageProfileId:r.coverageProfileId,coverageVersion:String(r.coverageVersion),coverageDigest:r.coverageDigest});t.cursor&&n.set("cursor",t.cursor);const s=e("/api/taskforce/sync/workspace/combined-repair"),i=s.includes("?")?"&":"?";return an(Ns(`${s}${i}${n.toString()}`,{method:"GET",credentials:"include"},Wv))}async function iC(e){const t=new URLSearchParams({workspaceId:e});return an(Ns(`/api/taskforce/sync/workspace/content-manifest?${t.toString()}`,{method:"GET",headers:{"x-taskforce-workspace-id":e},credentials:"include"},mo))}async function fR(e,t){return an(Ns(e("/api/taskforce/sync/workspace/content"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(t)},mo))}async function cC(e,t={}){const r=e.changes.filter(_=>_.op==="upsert").map(_=>String(_.task?.id||"").trim()).filter(Boolean),n=e.changes.filter(_=>_.op==="delete").map(_=>String(_.taskId||"").trim()).filter(Boolean),s=new Set(r),i=e.changes.filter(_=>_.op==="initiative-upsert").map(_=>String(_.initiative?.id||"").trim()).filter(Boolean),l=e.changes.filter(_=>_.op==="workstream-upsert").map(_=>String(_.workstream?.id||"").trim()).filter(Boolean);let c=[],d=[],f=[],p=new Set,g=new Set,h=new Set,y=!1,k=[],b=new Set,C=new Set,S="v2",w="v2",T="0",E=null,x=[];if(e.changes.length>0){const _=await sR(e.workspaceId,[...r,...n],i,l,t.readOwnership);if(!_.ok)return{ok:!1,status:_.status,data:_.data,retryAfterMs:_.retryAfterMs};p=new Set(_.data.activeCreateTaskIds),g=new Set(_.data.activeDeleteTaskIds),h=new Set(_.data.activeTaskRelationshipIds),y=_.data.taxonomyProtected,k=_.data.activeInitiativeIds,b=new Set(_.data.protectedInitiativeIds),C=new Set(_.data.protectedWorkstreamIds),S=_.data.initiativeProjectionOwner,w=_.data.combinedProjectionOwner,T=_.data.combinedProjectionEpoch,E=_.data.combinedCoverage||null,x=_.data.combinedExcludedProjections||[],c=_.data.activeMetadataTaskIds.filter(j=>s.has(j)&&!p.has(j)),d=_.data.activeLifecycleTaskIds.filter(j=>s.has(j)&&!p.has(j)),f=_.data.activeReopenTaskIds.filter(j=>s.has(j)&&!p.has(j))}const N=e.changes.filter(_=>_.op==="upsert"?!p.has(String(_.task?.id||"").trim()):_.op==="delete"?!g.has(String(_.taskId||"").trim()):_.op==="task-relationship-upsert"||_.op==="task-relationship-delete"?!h.has(String(_.relationship?.id||"").trim()):_.op==="taxonomy-upsert"?!y:_.op==="initiative-upsert"?S!=="v3"&&!b.has(String(_.initiative?.id||"").trim()):_.op==="workstream-upsert"?!C.has(String(_.workstream?.id||"").trim()):!0),v=aR(N,new Set(x)).changes,V=w==="v3"?e.changes.length-v.length:0;return{ok:!0,status:200,data:{changes:v,ownership:{activeV3TaskMetadataIds:c,activeV3TaskLifecycleIds:d,activeV3TaskReopenAssigneeIds:f,activeV3InitiativeIds:k,initiativeProjectionOwner:S,combinedProjectionOwner:w,combinedProjectionEpoch:T,combinedCoverage:E,combinedExcludedProjections:x,combinedV3SuppressedChangeCount:V}}}}async function mR(e,t){const r=await cC({workspaceId:t.workspaceId,changes:t.changes});if(!r.ok)return r;const{changes:n,ownership:s}=r.data;return n.length===0?{ok:!0,status:204,data:{success:!0,skipped:!0}}:an(fetch(e("/api/taskforce/sync/workspace/push"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({...t,changes:n,...s.activeV3TaskMetadataIds.length>0?{activeV3TaskMetadataIds:s.activeV3TaskMetadataIds}:{},...s.activeV3TaskLifecycleIds.length>0?{activeV3TaskLifecycleIds:s.activeV3TaskLifecycleIds}:{},...s.activeV3TaskReopenAssigneeIds.length>0?{activeV3TaskReopenAssigneeIds:s.activeV3TaskReopenAssigneeIds}:{},...s.activeV3InitiativeIds.length>0?{activeV3InitiativeIds:s.activeV3InitiativeIds}:{},...s.initiativeProjectionOwner==="v3"?{v3InitiativeProjectionOwned:!0}:{},...s.combinedCoverage?{combinedCoverage:s.combinedCoverage,excludedProjections:s.combinedExcludedProjections||[]}:{},...t.repairMode===!0?{repair:!0}:{}})}))}async function lC(e){const t=new URLSearchParams({workspaceId:e});return an(Ns(`/api/taskforce/sync/v3/local/metadata-ownership?${t.toString()}`,{method:"GET",headers:{"x-taskforce-workspace-id":e},credentials:"include"},mo))}async function dC(e,t,r){const n=JSON.stringify({workspaceId:e,changes:t,workspaceMembers:Array.isArray(r?.workspaceMembers)?r.workspaceMembers:void 0,...r?.repairMode===!0?{repair:!0}:{},excludedProjections:r?.excludedProjections,contentPullObligations:r?.contentPullObligations,contentPullResolutionClaims:r?.contentPullResolutionClaims,...Rg(e,r),bootstrapSnapshot:r?.bootstrapSnapshot?{currentAnnotatedAttachmentSessionIds:Array.isArray(r.bootstrapSnapshot.currentAnnotatedAttachmentSessionIds)?r.bootstrapSnapshot.currentAnnotatedAttachmentSessionIds:[]}:void 0}),s="/api/taskforce/sync/workspace/apply-local",i=[];try{const l=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-workspace-id":e},credentials:"include",body:n});if(l.ok){const f=await l.json().catch(()=>({}));return{ok:!0,status:l.status,data:f,failures:i}}const c=await l.text().catch(()=>"");let d={};if(c)try{d=JSON.parse(c)}catch{d={error:c.slice(0,400)}}else l.statusText&&(d={error:`${l.status} ${l.statusText}`});return i.push(`${s}:${l.status}`),{ok:!1,status:l.status,data:d,failures:i}}catch{i.push(`${s}:network`)}return{ok:!1,status:0,data:{},failures:i}}function Tc(e){return`${e.kind}:${e.path}`}const gb="WORKSPACE_SYNC_V3_APPLY_NOT_COMMITTED";function $v(e){return{handshakeWorkspace:t=>lR(e,t),provisionWorkspace:t=>dR(e,t),pushWorkspaceChanges:({ownership:t,pushBoundary:r,...n})=>mR(e,n),pullWorkspaceChanges:t=>uR(e,t),pullWorkspaceContent:({previousCursor:t,...r})=>fR(e,r),pullInitiativeFeed:t=>ZA(e,t),pullInitiativeRepair:t=>sC(e,t),pullCombinedFeed:t=>JA(e,t),pullCombinedRepair:t=>oC(e,t),pullTaskCommentAudit:t=>aC(e,t),abandonTransferReceipts:()=>{},acknowledgeNonApplyingTransferReceipts:()=>{},buildV2ApplyCompletionGroup:()=>{},buildV2PushApplyCompletionGroup:()=>{},buildV3ApplyCompletionGroup:()=>{}}}const uC=1;function pC(e){if(!Array.isArray(e)||e.length===0||e.some(t=>typeof t!="string"||t.trim().length===0||t!==t.trim())||new Set(e).size!==e.length)throw new TypeError("A V2 push boundary requires nonempty, unique, trimmed batch operation identities.");return Object.freeze({version:uC,projection:"v2-push",batchOperationIdentities:Object.freeze([...e])})}function th(e){if(!e||typeof e!="object"||Array.isArray(e)||e.version!==uC||e.projection!=="v2-push"||!Array.isArray(e.batchOperationIdentities))throw new TypeError("The V2 push boundary is invalid.");return pC(e.batchOperationIdentities)}function Dh(e){const t=e.filter(r=>r?.op==="upsert").map(r=>String(r.task?.id||"").trim()).filter(Boolean);return Array.from(new Set(t))}function fC(e,t){if(!Array.isArray(t)||t.some(i=>typeof i!="string"||i.trim().length===0||i!==i.trim())||new Set(t).size!==t.length)throw new TypeError("The expected V2 push task echo identities are invalid.");if(!e||typeof e!="object"||Array.isArray(e))throw new TypeError("The V2 push authoritative echo response is invalid.");const r=e;if(!Array.isArray(r.appliedTaskUpserts))throw new TypeError("The V2 push authoritative echo response is missing appliedTaskUpserts.");const n=r.appliedTaskUpserts.map(i=>{const l=i&&typeof i=="object"&&!Array.isArray(i)?i:null;if(!l||typeof l.archived!="boolean")return null;const c=l.task&&typeof l.task=="object"&&!Array.isArray(l.task)?l.task:null,d=String(c?.id||"").trim();return!c||!d?null:{archived:l.archived===!0,task:c,...l.durableRevision&&typeof l.durableRevision=="object"&&!Array.isArray(l.durableRevision)?{durableRevision:l.durableRevision}:{}}}).filter(i=>!!i),s=n.map(i=>String(i.task.id).trim());if(n.length!==r.appliedTaskUpserts.length||s.length!==t.length||new Set(s).size!==s.length||s.some((i,l)=>i!==t[l]))throw new TypeError("The V2 push authoritative task echo contract is incomplete or malformed.");return n}const Lk="V1:AESGCM:",Fv="AES-GCM",hR=12;async function mC(e){const t=Buffer.from(e,"base64");if(t.length!==32)throw new Error("Encryption key must be exactly 32 bytes (256-bit).");return crypto.subtle.importKey("raw",t,{name:Fv},!1,["encrypt","decrypt"])}async function yb(e,t){if(!e)return e;const r=crypto.getRandomValues(new Uint8Array(hR)),n=await mC(t),i=new TextEncoder().encode(e),l=await crypto.subtle.encrypt({name:Fv,iv:r},n,i),c=Buffer.from(l).toString("base64"),d=Buffer.from(r).toString("base64");return`${Lk}${d}:${c}`}async function kb(e,t){if(!e||!e.startsWith(Lk))return e;const r=e.slice(Lk.length),[n,s]=r.split(":");if(!n||!s)throw new Error("Malformed encrypted document payload.");const i=Buffer.from(n,"base64"),l=Buffer.from(s,"base64"),c=await mC(t);try{const d=await crypto.subtle.decrypt({name:Fv,iv:i},c,l);return new TextDecoder("utf-8").decode(d)}catch(d){throw new Error(`Failed to decrypt document: ${d.message}`)}}async function Lh(e,t){t&&(e.op==="document-upsert"&&typeof e.content=="string"&&(e.content=await kb(e.content,t)),e.op==="asset-upsert"&&typeof e.contentBase64=="string"&&(e.contentBase64=await kb(e.contentBase64,t)))}async function Qh(e,t){const r=e==="document"?new TextEncoder().encode(t):Uint8Array.from(atob(t),s=>s.charCodeAt(0)),n=await crypto.subtle.digest("SHA-256",r);return{sha256:Array.from(new Uint8Array(n),s=>s.toString(16).padStart(2,"0")).join(""),sizeBytes:r.byteLength}}function vb(e){return String(e||"").trim().toLowerCase()}function wb(e){return/^[a-f0-9]{64}$/.test(e)}function bb(e){return Number.isSafeInteger(e)&&e>=0}function gR(e,t){if(!t||!t.existsLocally||t.kind!==e.kind||t.path!==e.path||t.manifestVersion!==e.manifestVersion)return{shouldFetch:!0,reasons:["missing"]};const r=[],n=vb(e.sha256),s=vb(t.sha256);return!wb(n)||!wb(s)?r.push("unknown-hash"):n!==s&&r.push("hash-mismatch"),(!bb(e.sizeBytes)||!bb(t.sizeBytes)||e.sizeBytes!==t.sizeBytes)&&r.push("size-mismatch"),(!e.metadataFingerprint||!t.metadataFingerprint||e.metadataFingerprint!==t.metadataFingerprint)&&r.push("metadata-mismatch"),{shouldFetch:r.length>0,reasons:r}}const Sb=1;var pl={};function yn(e){return e&&typeof e=="object"?e:{}}const yR=3e4,kR=60*6e4;function vR(e,t=Date.now()){const r=Math.max(0,Math.floor(Number(e.attempts)||0));if(r===0)return!0;const n=Date.parse(String(e.updatedAt||""));if(!Number.isFinite(n))return!0;const s=Math.min(kR,yR*2**Math.min(r-1,7));return n+s<=t}function ti(e){const t=Number(e||0);return t===0||t===429||t>=500}function Ab(e,t){const r=String(e.code||"").trim().toUpperCase(),n=String(e.error||"").trim();return r==="WORKSPACE_ID_ALREADY_EXISTS"||n.toLowerCase()==="workspace id already exists"?"This workspace is already linked to another cloud account. Sign in with the original account, ask the workspace owner to grant you access, or keep this workspace local-only.":n||`Workspace provisioning failed (${t})`}function wR(e,t){if(t!==400)return!1;const r=String(e.code||"").trim().toUpperCase(),n=String(e.error||"").trim().toLowerCase();return r==="WORKSPACE_ID_REQUIRED"&&n.includes("no cloud workspace is selected")}async function bR(e){if(!e.cloudAuthConfigured)return{success:!1,error:"Cloud auth endpoint is not configured."};if(e.runtimeMode!=="local")return{success:!1,error:"Workspace sync is only available in local runtime."};if(!e.isAuthenticated)return{success:!1,error:"Authentication required."};try{const t=e.remoteServices||$v(e.resolveCloudAuthUrl);let r=await t.handshakeWorkspace(e.workspaceId);if(r.ok)return{success:!0,provisioned:!1};const n=yn(r.data);if(r.status===401)return{success:!1,statusCode:401,transient:!1,error:String(n.error||"Authentication required for workspace sync.")};if(r.status===429)return{success:!1,statusCode:429,retryAfterMs:r.retryAfterMs,transient:!0,error:String(n.error||"Workspace sync rate limited. Please retry later.")};if(wR(n,r.status)){const s=await t.provisionWorkspace({workspaceId:e.workspaceId,name:e.workspaceName||e.workspaceId});if(!s.ok){const i=yn(s.data);return{success:!1,statusCode:s.status,transient:ti(s.status),retryAfterMs:s.retryAfterMs,error:Ab(i,s.status)}}if(r=await t.handshakeWorkspace(e.workspaceId),!r.ok){const i=yn(r.data);return r.status===401?{success:!1,statusCode:401,transient:!1,error:String(i.error||"Authentication required for workspace sync.")}:r.status===429?{success:!1,statusCode:429,retryAfterMs:r.retryAfterMs,transient:!0,error:String(i.error||"Workspace sync rate limited. Please retry later.")}:{success:!1,statusCode:r.status,transient:ti(r.status),error:String(i.error||`Workspace sync handshake failed (${r.status})`)}}return{success:!0,provisioned:!0}}if(r.status===409&&n.code==="WORKSPACE_ID_MISMATCH"){if(e.allowProvisionOnMismatch===!1)return{success:!1,statusCode:409,transient:!1,error:String(n.error||"Selected cloud workspace could not be attached to this local workspace.")};const s=await t.provisionWorkspace({workspaceId:e.workspaceId,name:e.workspaceName||e.workspaceId});if(!s.ok){const i=yn(s.data);return{success:!1,statusCode:s.status,error:Ab(i,s.status)}}if(r=await t.handshakeWorkspace(e.workspaceId),!r.ok){const i=yn(r.data);return r.status===401?{success:!1,statusCode:401,transient:!1,error:String(i.error||"Authentication required for workspace sync.")}:r.status===429?{success:!1,statusCode:429,retryAfterMs:r.retryAfterMs,transient:!0,error:String(i.error||"Workspace sync rate limited. Please retry later.")}:{success:!1,statusCode:r.status,transient:ti(r.status),error:String(i.error||`Workspace sync handshake failed (${r.status})`)}}return{success:!0,provisioned:!0}}return{success:!1,statusCode:r.status,transient:ti(r.status),error:String(n.error||`Workspace sync handshake failed (${r.status})`)}}catch{return{success:!1,statusCode:0,transient:!0,error:"Failed to validate workspace sync access."}}}function SR(e,t,r){if(!e)return;const n={};for(const i of t)n[i.op]=(n[i.op]||0)+1;const s=(i,l)=>i&&{...i,changeCount:l};return{...e,totalChanges:t.length,byOp:n,domains:{...e.domains,tasks:s(e.domains.tasks,(n.upsert||0)+(n.delete||0)),taskRelationships:s(e.domains.taskRelationships,(n["task-relationship-upsert"]||0)+(n["task-relationship-delete"]||0)),initiatives:s(e.domains.initiatives,n["initiative-upsert"]||0),workstreams:s(e.domains.workstreams,n["workstream-upsert"]||0),taxonomy:s(e.domains.taxonomy,n["taxonomy-upsert"]||0)},...r?.combinedV3SuppressedChangeCount?{combinedV3SuppressedChangeCount:r.combinedV3SuppressedChangeCount}:{}}}async function AR(e,t,r){const n=$a({contractVersion:1,workspaceId:e,repairMode:r,changes:t});try{const s=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return Array.from(new Uint8Array(s)).map(i=>i.toString(16).padStart(2,"0")).join("")}catch{let s=2166136261;for(let l=0;l<n.length;l+=1)s^=n.charCodeAt(l),s=Math.imul(s,16777619);const i=(s>>>0).toString(16).padStart(8,"0");return`${e}:fallback:${i}`}}const CR=64,Cb=4*1024*1024,IR=45*1024*1024,_R=64*1024;function Ib(e){switch(e.op){case"upsert":return`${e.op}:${e.task.id}`;case"delete":return`${e.op}:${e.taskId}`;case"task-relationship-upsert":case"task-relationship-delete":return`${e.op}:${e.relationship.id}`;case"initiative-upsert":return`${e.op}:${e.initiative.id}`;case"workstream-upsert":return`${e.op}:${e.workstream.id}`;case"planning-identity-upsert":return`${e.op}:${e.identity.entityType}:${e.identity.entityId}`;case"taxonomy-upsert":return e.op;case"ai-profile-upsert":return`${e.op}:${e.profile.id}`;case"document-upsert":case"document-delete":return`${e.op}:${e.path}`;case"document-manifest":return`${e.op}:${e.manifest.path}`;case"asset-upsert":case"asset-delete":return`${e.op}:${e.path}`;case"asset-manifest":return`${e.op}:${e.manifest.path}`;case"document-review-session-upsert":return`${e.op}:${e.session.id}`;case"document-review-session-delete":return`${e.op}:${e.sessionId}`;case"document-review-comment-upsert":return`${e.op}:${e.comment.id}`;case"document-review-comment-delete":return`${e.op}:${e.commentId}`;case"annotated-attachment-session-upsert":return`${e.op}:${e.session.id}`;case"annotated-attachment-session-delete":return`${e.op}:${e.sessionId}`;case"taskforce-agent-upsert":return`${e.op}:${e.agent.id}`;case"agent-role-upsert":return`${e.op}:${e.role.id}`;case"taskforce-agent-skill-upsert":return`${e.op}:${e.skill.id}`;case"agent-conversation-upsert":return`${e.op}:${e.conversation.id}`;case"entity-event-upsert":return`${e.op}:${e.event.id}`;case"task-event-upsert":return`${e.op}:${e.event.id}`}}function TR(e,t){const r=new Map;for(const[s,i]of e.entries()){const l=Ib(i),c=r.get(l)||[];c.push(s),r.set(l,c)}const n=new Map;return t.map(s=>{const i=Ib(s),l=r.get(i)||[],c=n.get(i)||0,d=l[c];if(d===void 0)throw new Error(`Prepared V2 push change is not present in the frozen payload: ${i}.`);n.set(i,c+1);const f=e[d];return JSON.stringify(f)===JSON.stringify(s)?{sourceChangeIndex:d}:{sourceChangeIndex:d,preparedChange:s}})}function xR(e,t){const r=new Set;return t.batches.map(n=>n.map(s=>{const i=s.sourceChangeIndex;if(!Number.isSafeInteger(i)||i<0||i>=e.length||r.has(i))throw new Error("Persisted V2 push prepared plan contains an invalid source change index.");return r.add(i),s.preparedChange||e[i]}))}function hC(e){switch(e.op){case"taxonomy-upsert":case"ai-profile-upsert":case"initiative-upsert":case"taskforce-agent-upsert":case"taskforce-agent-skill-upsert":return 0;case"workstream-upsert":return 1;case"planning-identity-upsert":return 2;case"upsert":return 2;case"document-upsert":case"document-manifest":case"asset-upsert":case"asset-manifest":return 3;case"document-review-session-upsert":case"annotated-attachment-session-upsert":case"agent-conversation-upsert":case"task-relationship-upsert":return 4;case"document-review-comment-upsert":case"task-event-upsert":case"entity-event-upsert":return 5;case"document-review-comment-delete":case"annotated-attachment-session-delete":case"task-relationship-delete":return 6;case"document-review-session-delete":case"document-delete":case"asset-delete":return 7;case"delete":return 8;default:return 4}}function RR(e){return e.op==="document-upsert"||e.op==="document-manifest"||e.op==="asset-upsert"||e.op==="asset-manifest"||e.op==="document-delete"||e.op==="asset-delete"}function _b(e,t){return _R+new TextEncoder().encode(JSON.stringify({workspaceId:e.workspaceId,idempotencyKey:"0".repeat(64),changes:t,repairMode:e.repairMode===!0,repair:e.repairMode===!0})).byteLength}function jR(e,t,r){const n=t.map((l,c)=>({plain:l,safe:r[c],phase:hC(l),preparedIndex:c})).sort((l,c)=>l.phase-c.phase||l.preparedIndex-c.preparedIndex);if(n.length===0)return{batches:[[]],oversizedChangeIndex:null};const s=[];let i=[];for(const l of n){const c=_b(e,[l.safe]);if(c>IR)return{batches:[],oversizedChangeIndex:l.preparedIndex};const d=i.length>0&&i[0].phase!==l.phase,f=[...i,l],p=i.length>0&&_b(e,f.map(g=>g.safe))>Cb;(d||i.length>=CR||p)&&(s.push(i),i=[]),i.push(l),c>Cb&&(s.push(i),i=[])}return i.length>0&&s.push(i),{batches:s,oversizedChangeIndex:null}}async function PR(e){const t=e.remoteServices||$v(e.resolveCloudAuthUrl);let r={activeV3TaskMetadataIds:[],activeV3TaskLifecycleIds:[],activeV3TaskReopenAssigneeIds:[],activeV3InitiativeIds:[],initiativeProjectionOwner:"v2",combinedProjectionOwner:"v2",combinedProjectionEpoch:"0",combinedV3SuppressedChangeCount:0},n,s=e.preparedPlan||null,i=null;if(s){if(s.contractVersion!==Sb)throw new Error("Persisted V2 push prepared plan version is unsupported.");i=xR(e.payload.changes,s),n=i.flat(),r=s.ownership}else n=e.payload.changes;if(!s&&n.length>0){const _=await cC({workspaceId:e.workspaceId,changes:n},{readOwnership:e.localServices?.readPushOwnership});if(!_.ok){const j=yn(_.data);return{success:!1,status:_.status,error:typeof j.error=="string"?j.error:"Local workspace sync ownership could not be verified.",code:typeof j.code=="string"?j.code:void 0,retryAfterMs:_.retryAfterMs,transient:ti(_.status),requestMs:0,changeCount:e.payload.changes.length,deleteCount:e.payload.deleteTaskIds.size,currentTaskIds:e.payload.currentTaskIds,currentTaskWatermarks:e.payload.currentTaskWatermarks??new Map,currentTaskChangeKeys:e.payload.currentTaskChangeKeys??new Map,currentTaskRelationshipChangeKeys:e.payload.currentTaskRelationshipChangeKeys??new Map,currentTaxonomyChangeKey:e.payload.currentTaxonomyChangeKey??"",deleteTaskIds:e.payload.deleteTaskIds,currentInitiativeIds:e.payload.currentInitiativeIds,currentInitiativeWatermarks:e.payload.currentInitiativeWatermarks,currentWorkstreamIds:e.payload.currentWorkstreamIds,currentWorkstreamWatermarks:e.payload.currentWorkstreamWatermarks,currentAiProfileIds:e.payload.currentAiProfileIds,currentAiProfileWatermarks:e.payload.currentAiProfileWatermarks,currentAiProfileChangeKeys:e.payload.currentAiProfileChangeKeys??new Map,currentDocumentPaths:e.payload.currentDocumentPaths,deleteDocumentPaths:e.payload.deleteDocumentPaths,currentDocumentWatermarks:e.payload.currentDocumentWatermarks,currentAssetPaths:e.payload.currentAssetPaths,deleteAssetPaths:e.payload.deleteAssetPaths,currentAssetWatermarks:e.payload.currentAssetWatermarks,currentDocumentReviewSessionIds:e.payload.currentDocumentReviewSessionIds,deleteDocumentReviewSessionIds:e.payload.deleteDocumentReviewSessionIds,currentDocumentReviewSessionWatermarks:e.payload.currentDocumentReviewSessionWatermarks,currentDocumentReviewCommentIds:e.payload.currentDocumentReviewCommentIds,deleteDocumentReviewCommentIds:e.payload.deleteDocumentReviewCommentIds,currentDocumentReviewCommentWatermarks:e.payload.currentDocumentReviewCommentWatermarks,currentAnnotatedAttachmentSessionIds:e.payload.currentAnnotatedAttachmentSessionIds,deleteAnnotatedAttachmentSessionIds:e.payload.deleteAnnotatedAttachmentSessionIds,currentAnnotatedAttachmentSessionWatermarks:e.payload.currentAnnotatedAttachmentSessionWatermarks,currentTaskforceAgentIds:e.payload.currentTaskforceAgentIds??new Set,currentTaskforceAgentWatermarks:e.payload.currentTaskforceAgentWatermarks??new Map,currentTaskforceAgentSkillIds:e.payload.currentTaskforceAgentSkillIds??new Set,currentTaskforceAgentSkillWatermarks:e.payload.currentTaskforceAgentSkillWatermarks??new Map,currentAgentConversationIds:e.payload.currentAgentConversationIds??new Set,currentAgentConversationWatermarks:e.payload.currentAgentConversationWatermarks??new Map,currentTaskEventWatermarks:e.payload.currentTaskEventWatermarks,pushedWatermarks:new Map,pushedTaskChangeKeys:new Map,emittedEventIds:[],appliedTaskUpserts:[]}}n=_.data.changes,r=_.data.ownership}const l=n.length,c=SR(e.payload.deltaDiagnostics,n,r),d=e.payload.deleteTaskIds.size;let f=0;if(l===0&&e.repairMode!==!0&&(r?.combinedProjectionOwner==="v3"||!!e.payload.deltaDiagnostics&&e.payload.deltaDiagnostics?.baselineResetReason!=="missing-baseline"))return{success:!0,syncedAt:new Date().toISOString(),requestMs:0,changeCount:0,effectiveDeltaDiagnostics:c,deleteCount:d,currentTaskIds:e.payload.currentTaskIds,currentTaskWatermarks:e.payload.currentTaskWatermarks??new Map,currentTaskChangeKeys:e.payload.currentTaskChangeKeys??new Map,currentTaskRelationshipChangeKeys:e.payload.currentTaskRelationshipChangeKeys??new Map,currentTaxonomyChangeKey:e.payload.currentTaxonomyChangeKey??"",deleteTaskIds:e.payload.deleteTaskIds,currentInitiativeIds:e.payload.currentInitiativeIds,currentInitiativeWatermarks:e.payload.currentInitiativeWatermarks,currentWorkstreamIds:e.payload.currentWorkstreamIds,currentWorkstreamWatermarks:e.payload.currentWorkstreamWatermarks,currentAiProfileIds:e.payload.currentAiProfileIds,currentAiProfileWatermarks:e.payload.currentAiProfileWatermarks,currentAiProfileChangeKeys:e.payload.currentAiProfileChangeKeys??new Map,currentDocumentPaths:e.payload.currentDocumentPaths,deleteDocumentPaths:e.payload.deleteDocumentPaths,currentDocumentWatermarks:e.payload.currentDocumentWatermarks,currentAssetPaths:e.payload.currentAssetPaths,deleteAssetPaths:e.payload.deleteAssetPaths,currentAssetWatermarks:e.payload.currentAssetWatermarks,currentDocumentReviewSessionIds:e.payload.currentDocumentReviewSessionIds,deleteDocumentReviewSessionIds:e.payload.deleteDocumentReviewSessionIds,currentDocumentReviewSessionWatermarks:e.payload.currentDocumentReviewSessionWatermarks,currentDocumentReviewCommentIds:e.payload.currentDocumentReviewCommentIds,deleteDocumentReviewCommentIds:e.payload.deleteDocumentReviewCommentIds,currentDocumentReviewCommentWatermarks:e.payload.currentDocumentReviewCommentWatermarks,currentAnnotatedAttachmentSessionIds:e.payload.currentAnnotatedAttachmentSessionIds,deleteAnnotatedAttachmentSessionIds:e.payload.deleteAnnotatedAttachmentSessionIds,currentAnnotatedAttachmentSessionWatermarks:e.payload.currentAnnotatedAttachmentSessionWatermarks,currentTaskforceAgentIds:e.payload.currentTaskforceAgentIds??new Set,currentTaskforceAgentWatermarks:e.payload.currentTaskforceAgentWatermarks??new Map,currentTaskforceAgentSkillIds:e.payload.currentTaskforceAgentSkillIds??new Set,currentTaskforceAgentSkillWatermarks:e.payload.currentTaskforceAgentSkillWatermarks??new Map,currentAgentConversationIds:e.payload.currentAgentConversationIds??new Set,currentAgentConversationWatermarks:e.payload.currentAgentConversationWatermarks??new Map,currentTaskEventWatermarks:e.payload.currentTaskEventWatermarks,pushedWatermarks:new Map,pushedTaskChangeKeys:new Map,emittedEventIds:[],appliedTaskUpserts:[]};let g=n;if(typeof process<"u"&&pl?.TASKFORCE_SYNC_KEY){const _=pl.TASKFORCE_SYNC_KEY,j=[];for(const F of g)F.op==="document-upsert"&&typeof F.content=="string"?j.push({...F,content:await yb(F.content,_)}):F.op==="asset-upsert"&&typeof F.contentBase64=="string"&&F.contentBase64.length>0?j.push({...F,contentBase64:await yb(F.contentBase64,_)}):j.push(F);g=j}let h=jR(e,n,g);if(i){let _=0;h={oversizedChangeIndex:null,batches:i.map(j=>j.map(F=>{const z={plain:F,safe:g[_],phase:hC(F),preparedIndex:_};return _+=1,z}))}}if(h.oversizedChangeIndex!==null){const _=n[h.oversizedChangeIndex];return{success:!1,status:413,error:`Workspace sync change ${h.oversizedChangeIndex+1} (${_.op}) exceeds the single-change transfer limit.`,transient:!1,requestMs:f,changeCount:l,deleteCount:d,currentTaskIds:e.payload.currentTaskIds,currentTaskWatermarks:e.payload.currentTaskWatermarks??new Map,currentTaskChangeKeys:e.payload.currentTaskChangeKeys??new Map,currentTaskRelationshipChangeKeys:e.payload.currentTaskRelationshipChangeKeys??new Map,currentTaxonomyChangeKey:e.payload.currentTaxonomyChangeKey??"",deleteTaskIds:e.payload.deleteTaskIds,currentInitiativeIds:e.payload.currentInitiativeIds,currentInitiativeWatermarks:e.payload.currentInitiativeWatermarks,currentWorkstreamIds:e.payload.currentWorkstreamIds,currentWorkstreamWatermarks:e.payload.currentWorkstreamWatermarks,currentAiProfileIds:e.payload.currentAiProfileIds,currentAiProfileWatermarks:e.payload.currentAiProfileWatermarks,currentAiProfileChangeKeys:e.payload.currentAiProfileChangeKeys??new Map,currentDocumentPaths:e.payload.currentDocumentPaths,deleteDocumentPaths:e.payload.deleteDocumentPaths,currentDocumentWatermarks:e.payload.currentDocumentWatermarks,currentAssetPaths:e.payload.currentAssetPaths,deleteAssetPaths:e.payload.deleteAssetPaths,currentAssetWatermarks:e.payload.currentAssetWatermarks,currentDocumentReviewSessionIds:e.payload.currentDocumentReviewSessionIds,deleteDocumentReviewSessionIds:e.payload.deleteDocumentReviewSessionIds,currentDocumentReviewSessionWatermarks:e.payload.currentDocumentReviewSessionWatermarks,currentDocumentReviewCommentIds:e.payload.currentDocumentReviewCommentIds,deleteDocumentReviewCommentIds:e.payload.deleteDocumentReviewCommentIds,currentDocumentReviewCommentWatermarks:e.payload.currentDocumentReviewCommentWatermarks,currentAnnotatedAttachmentSessionIds:e.payload.currentAnnotatedAttachmentSessionIds,deleteAnnotatedAttachmentSessionIds:e.payload.deleteAnnotatedAttachmentSessionIds,currentAnnotatedAttachmentSessionWatermarks:e.payload.currentAnnotatedAttachmentSessionWatermarks,currentTaskforceAgentIds:e.payload.currentTaskforceAgentIds??new Set,currentTaskforceAgentWatermarks:e.payload.currentTaskforceAgentWatermarks??new Map,currentTaskforceAgentSkillIds:e.payload.currentTaskforceAgentSkillIds??new Set,currentTaskforceAgentSkillWatermarks:e.payload.currentTaskforceAgentSkillWatermarks??new Map,currentAgentConversationIds:e.payload.currentAgentConversationIds??new Set,currentAgentConversationWatermarks:e.payload.currentAgentConversationWatermarks??new Map,currentTaskEventWatermarks:e.payload.currentTaskEventWatermarks,pushedWatermarks:new Map,pushedTaskChangeKeys:new Map,emittedEventIds:[],appliedTaskUpserts:[]}}const y=new Set,k=[];let b;if(s){if(b=[...s.batchOperationIdentities],b.length!==h.batches.length||new Set(b).size!==b.length||b.some(_=>!/^[a-f0-9]{64}$/.test(_)))throw new Error("Persisted V2 push prepared plan fingerprint does not match its frozen batches.")}else{b=await Promise.all(h.batches.map(j=>AR(e.workspaceId,j.map(F=>F.plain),e.repairMode===!0)));const _=TR(e.payload.changes,n);s={contractVersion:Sb,ownership:r,batches:h.batches.map(j=>j.map(F=>_[F.preparedIndex])),batchOperationIdentities:[...b]}}const C=pC(b),S=e.acknowledgedNonApplyingBatchOperationIdentities||[];if(new Set(S).size!==S.length)throw new Error("Persisted V2 push batch acknowledgement state does not match the frozen push plan.");for(const _ of S){const j=b.indexOf(_);if(j>=0&&Dh(h.batches[j].map(F=>F.plain)).length>0)throw new Error("Persisted V2 push batch acknowledgement state does not match the frozen push plan.")}const w=S.filter(_=>{const j=b.indexOf(_);return j>=0&&Dh(h.batches[j].map(F=>F.plain)).length===0}),T=e.preparedPlan?[]:S.filter(_=>!w.includes(_));s&&!e.preparedPlan&&await e.onPreparedPlan?.({plan:s,acknowledgedOperationIdentities:w,replayedLegacyAcknowledgementIdentities:T});const E=new Set(w);if(e.preparedPlan&&E.size!==S.length)throw new Error("Persisted V2 push batch acknowledgement state does not match the frozen push plan.");let x=0,N=0;const v=[],V=async _=>{if(v.length===0)return;const j=v.splice(0);await t.abandonTransferReceipts({workspaceId:e.workspaceId,receipts:j,errorCode:_})};try{for(const[_,j]of h.batches.entries()){const F=j.map(Ie=>Ie.plain),z=j.map(Ie=>Ie.safe),M=Dh(F),O=b[_];if(E.has(O)){x+=1,N+=F.length;continue}v.length>0&&await t.retainTransferReceipts?.({workspaceId:e.workspaceId,receipts:v});const Z=async()=>{const Ie=Date.now(),Ye=await t.pushWorkspaceChanges({workspaceId:e.workspaceId,idempotencyKey:O,pushBoundary:C,changes:z,ownership:r,repairMode:e.repairMode===!0});return f+=Date.now()-Ie,Ye};let U=await Z(),ve=yn(U.data),te=U.status===409&&ve.code==="SYNC_PUSH_IN_PROGRESS";if(!U.ok&&!te&&(U.status===403||U.status===409)&&(await e.ensureCloudWorkspaceReadyForSync()).success&&(U=await Z(),ve=yn(U.data),te=U.status===409&&ve.code==="SYNC_PUSH_IN_PROGRESS"),U.transferReceipt&&v.push(U.transferReceipt),!U.ok){await V("WORKSPACE_SYNC_V2_PUSH_ATTEMPT_FAILED");const Ie=yn(U.data),Ye=Array.from(new Set(F.map(he=>he.op))),ge=F.filter(RR).length;return{success:!1,status:U.status,error:typeof Ie.error=="string"?Ie.error:void 0,code:typeof Ie.code=="string"?Ie.code:void 0,batchProgress:{totalBatches:h.batches.length,completedBatches:x,completedChanges:N,failedBatchIndex:_,failedChangeCount:F.length,failedOperations:Ye,failureDomain:ge===F.length?"content":ge===0?"metadata":"mixed"},retryAfterMs:U.retryAfterMs,transient:te||ti(U.status),requestMs:f,changeCount:l,deleteCount:d,currentTaskIds:e.payload.currentTaskIds,currentTaskWatermarks:e.payload.currentTaskWatermarks??new Map,currentTaskChangeKeys:e.payload.currentTaskChangeKeys??new Map,currentTaskRelationshipChangeKeys:e.payload.currentTaskRelationshipChangeKeys??new Map,currentTaxonomyChangeKey:e.payload.currentTaxonomyChangeKey??"",deleteTaskIds:e.payload.deleteTaskIds,currentInitiativeIds:e.payload.currentInitiativeIds,currentInitiativeWatermarks:e.payload.currentInitiativeWatermarks,currentWorkstreamIds:e.payload.currentWorkstreamIds,currentWorkstreamWatermarks:e.payload.currentWorkstreamWatermarks,currentAiProfileIds:e.payload.currentAiProfileIds,currentAiProfileWatermarks:e.payload.currentAiProfileWatermarks,currentAiProfileChangeKeys:e.payload.currentAiProfileChangeKeys??new Map,currentDocumentPaths:e.payload.currentDocumentPaths,deleteDocumentPaths:e.payload.deleteDocumentPaths,currentDocumentWatermarks:e.payload.currentDocumentWatermarks,currentAssetPaths:e.payload.currentAssetPaths,deleteAssetPaths:e.payload.deleteAssetPaths,currentAssetWatermarks:e.payload.currentAssetWatermarks,currentDocumentReviewSessionIds:e.payload.currentDocumentReviewSessionIds,deleteDocumentReviewSessionIds:e.payload.deleteDocumentReviewSessionIds,currentDocumentReviewSessionWatermarks:e.payload.currentDocumentReviewSessionWatermarks,currentDocumentReviewCommentIds:e.payload.currentDocumentReviewCommentIds,deleteDocumentReviewCommentIds:e.payload.deleteDocumentReviewCommentIds,currentDocumentReviewCommentWatermarks:e.payload.currentDocumentReviewCommentWatermarks,currentAnnotatedAttachmentSessionIds:e.payload.currentAnnotatedAttachmentSessionIds,deleteAnnotatedAttachmentSessionIds:e.payload.deleteAnnotatedAttachmentSessionIds,currentAnnotatedAttachmentSessionWatermarks:e.payload.currentAnnotatedAttachmentSessionWatermarks,currentTaskforceAgentIds:e.payload.currentTaskforceAgentIds??new Set,currentTaskforceAgentWatermarks:e.payload.currentTaskforceAgentWatermarks??new Map,currentTaskforceAgentSkillIds:e.payload.currentTaskforceAgentSkillIds??new Set,currentTaskforceAgentSkillWatermarks:e.payload.currentTaskforceAgentSkillWatermarks??new Map,currentAgentConversationIds:e.payload.currentAgentConversationIds??new Set,currentAgentConversationWatermarks:e.payload.currentAgentConversationWatermarks??new Map,currentTaskEventWatermarks:e.payload.currentTaskEventWatermarks,pushedWatermarks:new Map,pushedTaskChangeKeys:new Map,emittedEventIds:[],appliedTaskUpserts:[]}}const ce=yn(U.data);if(Array.isArray(ce.emittedEventIds))for(const Ie of ce.emittedEventIds.map(Ye=>String(Ye||"").trim()).filter(Boolean))y.add(Ie);const Le=fC(ce,M);if(k.push(...Le),U.transferReceipt&&Le.length===0){await t.acknowledgeNonApplyingTransferReceipts({workspaceId:e.workspaceId,receipts:[U.transferReceipt]});const Ie=v.indexOf(U.transferReceipt);Ie>=0&&v.splice(Ie,1),E.add(O),await e.onNonApplyingBatchAcknowledged?.({operationIdentity:O,acknowledgedOperationIdentities:b.filter(Ye=>E.has(Ye))})}x+=1,N+=F.length}}catch(_){throw await V("WORKSPACE_SYNC_V2_PUSH_ATTEMPT_FAILED"),_}return{success:!0,syncedAt:new Date().toISOString(),requestMs:f,changeCount:l,batchProgress:{totalBatches:h.batches.length,completedBatches:x,completedChanges:N,failedBatchIndex:null,failedChangeCount:0,failedOperations:[],failureDomain:null},effectiveDeltaDiagnostics:c,deleteCount:d,currentTaskIds:e.payload.currentTaskIds,currentTaskWatermarks:e.payload.currentTaskWatermarks??new Map,currentTaskChangeKeys:e.payload.currentTaskChangeKeys??new Map,currentTaskRelationshipChangeKeys:e.payload.currentTaskRelationshipChangeKeys??new Map,currentTaxonomyChangeKey:e.payload.currentTaxonomyChangeKey??"",deleteTaskIds:e.payload.deleteTaskIds,currentInitiativeIds:e.payload.currentInitiativeIds,currentInitiativeWatermarks:e.payload.currentInitiativeWatermarks,currentWorkstreamIds:e.payload.currentWorkstreamIds,currentWorkstreamWatermarks:e.payload.currentWorkstreamWatermarks,currentAiProfileIds:e.payload.currentAiProfileIds,currentAiProfileWatermarks:e.payload.currentAiProfileWatermarks,currentAiProfileChangeKeys:e.payload.currentAiProfileChangeKeys??new Map,currentDocumentPaths:e.payload.currentDocumentPaths,deleteDocumentPaths:e.payload.deleteDocumentPaths,currentDocumentWatermarks:e.payload.currentDocumentWatermarks,currentAssetPaths:e.payload.currentAssetPaths,deleteAssetPaths:e.payload.deleteAssetPaths,currentAssetWatermarks:e.payload.currentAssetWatermarks,currentDocumentReviewSessionIds:e.payload.currentDocumentReviewSessionIds,deleteDocumentReviewSessionIds:e.payload.deleteDocumentReviewSessionIds,currentDocumentReviewSessionWatermarks:e.payload.currentDocumentReviewSessionWatermarks,currentDocumentReviewCommentIds:e.payload.currentDocumentReviewCommentIds,deleteDocumentReviewCommentIds:e.payload.deleteDocumentReviewCommentIds,currentDocumentReviewCommentWatermarks:e.payload.currentDocumentReviewCommentWatermarks,currentAnnotatedAttachmentSessionIds:e.payload.currentAnnotatedAttachmentSessionIds,deleteAnnotatedAttachmentSessionIds:e.payload.deleteAnnotatedAttachmentSessionIds,currentAnnotatedAttachmentSessionWatermarks:e.payload.currentAnnotatedAttachmentSessionWatermarks,currentTaskforceAgentIds:e.payload.currentTaskforceAgentIds??new Set,currentTaskforceAgentWatermarks:e.payload.currentTaskforceAgentWatermarks??new Map,currentTaskforceAgentSkillIds:e.payload.currentTaskforceAgentSkillIds??new Set,currentTaskforceAgentSkillWatermarks:e.payload.currentTaskforceAgentSkillWatermarks??new Map,currentAgentConversationIds:e.payload.currentAgentConversationIds??new Set,currentAgentConversationWatermarks:e.payload.currentAgentConversationWatermarks??new Map,currentTaskEventWatermarks:e.payload.currentTaskEventWatermarks,pushedWatermarks:e.payload.pushedWatermarks,pushedTaskChangeKeys:e.payload.pushedTaskChangeKeys??new Map,emittedEventIds:Array.from(y),appliedTaskUpserts:k,pushBoundary:C,pushTransferReceipts:v}}async function ER(e){const t=e.remoteServices||$v(e.resolveCloudAuthUrl);let r=[];const n=ve=>{ve.transferReceipt&&r.push(ve.transferReceipt)},s=async ve=>{if(r.length===0)return;const te=r;await t.abandonTransferReceipts({workspaceId:e.workspaceId,receipts:te,errorCode:ve}),r=[]},i=e.localServices?.readContentManifest||iC,l=e.localServices?.applyV2Batch||dC,c=e.localServices?.listContentPullObligations||qA,d=e.localServices?.recordContentPullObligationFailures||YA,f=async(ve,te)=>{const ce=await d(e.workspaceId,ve,te);if(!ce.ok)throw new Error(String(ce.data?.error||"Failed to persist content-pull retry state."))};let p=e.cursor,g=!0,h=0,y=0,k=0,b=0;const C=new Set;let S=!1,w=!1,T=!1,E=!1,x=!1,N=!1,v=!1,V=!1;const _=new Set,j=new Set,F=new Set;let z=null;const M={manifestEntries:0,bodiesRequested:0,bodiesTransferred:0,contentBytesTransferred:0,contentBytesAvoided:0,obligationsAttempted:0,obligationsResolved:0,obligationsRemaining:0},O=Number.isFinite(Number(e.maxPages))?Math.max(1,Math.floor(Number(e.maxPages))):20;let Z=new Map;const U=new Set;try{{const ve=await c(e.workspaceId,100);if(!ve.ok)throw new Error(String(ve.data?.error||`Local content-pull obligation read failed (${ve.status}).`));const te=Array.isArray(ve.data?.obligations)?ve.data.obligations:[];te.forEach(Le=>{U.add(Tc(Le))});const ce=te.filter(Le=>vR(Le));if(M.obligationsAttempted=ce.length,ce.length>0){const Le=await t.pullWorkspaceContent({workspaceId:e.workspaceId,requests:ce.map(({kind:Ie,path:Ye})=>({kind:Ie,path:Ye})),previousCursor:p});if(n(Le),Le.ok){const Ie=Le.data||{},Ye=Array.isArray(Ie.changes)?Ie.changes:[],ge=Array.isArray(Ie.contentMetadata)?Ie.contentMetadata:[],he=new Map(ge.map(ae=>[`${ae.kind}:${ae.path}`,ae])),Ae=new Map(ce.map(ae=>[Tc(ae),ae]));if(he.size!==ge.length||ge.some(ae=>!Ae.has(`${ae.kind}:${ae.path}`)))throw await f(ce.map(Tc),"Content response contained duplicate or unexpected authoritative metadata."),new Error("Workspace content obligation response contained invalid authoritative metadata.");const ye=[],Ne=[];for(const ae of Ye){if(ae.op!=="document-upsert"&&ae.op!=="asset-upsert")throw await f(ce.map(Tc),`Content response contained invalid operation ${ae.op}.`),new Error(`Workspace content obligation returned invalid operation: ${ae.op}.`);const q=ae.op==="document-upsert"?"document":"asset",W=`${q}:${ae.path}`;if(!Ae.has(W))throw await f(ce.map(Tc),`Content response contained unexpected body ${W}.`),new Error(`Workspace content obligation returned an unexpected body: ${W}.`);const K=he.get(W);if(!K)throw await f([W],"Content response omitted authoritative metadata."),new Error(`Workspace content obligation omitted authoritative metadata: ${W}.`);if(ye.includes(W))throw await f([W],"Content response contained a duplicate body."),new Error(`Workspace content obligation returned a duplicate body: ${W}.`);if(typeof process<"u"&&pl?.TASKFORCE_SYNC_KEY)try{await Lh(ae,pl.TASKFORCE_SYNC_KEY)}catch(ie){throw await f([W],String(ie?.message||"Content decryption failed.")),ie}const Re=await Qh(q,ae.op==="document-upsert"?ae.content:ae.contentBase64);if(Re.sha256!==String(K.sha256||"").toLowerCase()||Re.sizeBytes!==Number(K.sizeBytes)||String(K.updatedAt||"")<String(Ae.get(W)?.sourceWatermark||"")||String(ae.updatedAt||"")<String(Ae.get(W)?.sourceWatermark||""))throw await f([W],"Authoritative content response was stale or failed verification."),new Error(`Workspace content obligation verification failed: ${W}.`);ye.push(W);const we=Ae.get(W);Ne.push({kind:q,path:ae.path,resolution:"exact-version",sourceWatermark:we.sourceWatermark,metadataFingerprint:we.metadataFingerprint})}if(Ye.length>0){const ae=r.length>0?t.buildV2ApplyCompletionGroup({workspaceId:e.workspaceId,previousCursor:p,nextCursor:p,receipts:r}):void 0;if(r.length>0&&!ae)throw new Error("Content-obligation receipts did not produce an apply completion group.");let q;try{q=await l(e.workspaceId,Ye,{repairMode:e.repairMode===!0,excludedProjections:e.excludedProjections,contentPullResolutionClaims:Ne,...ae?{completionGroup:ae}:{}})}catch(K){throw await f(ye,String(K?.message||"Content obligation apply failed.")),K}if(!q.ok||yn(q.data).success===!1)throw await f(ye,String(yn(q.data).error||"Workspace content obligation apply failed.")),new Error(String(yn(q.data).error||"Workspace content obligation apply failed."));r=[],M.obligationsResolved=ye.length;const W=ce.map(Tc).filter(K=>!ye.includes(K));W.length>0&&await f(W,"Authoritative content body remains unavailable.")}else{if(r.length>0){const ae=t.buildV2ApplyCompletionGroup({workspaceId:e.workspaceId,previousCursor:p,nextCursor:p,receipts:r});if(!ae)throw new Error("Unavailable content receipts did not produce an apply completion group.");const q=await l(e.workspaceId,[],{repairMode:e.repairMode===!0,excludedProjections:e.excludedProjections,completionGroup:ae});if(!q.ok||yn(q.data).success===!1)throw new Error(String(yn(q.data).error||"Unavailable content receipt settlement failed."));r=[]}await f(ce.map(Tc),"Authoritative content body remains unavailable.")}}else await s("WORKSPACE_SYNC_CONTENT_OBLIGATION_RETRY"),await f(ce.map(Tc),String(yn(Le.data).error||`Content pull failed (${Le.status}).`))}M.obligationsRemaining=Math.max(0,te.length-M.obligationsResolved)}if(e.contentMode==="manifest"){const ve=await i(e.workspaceId);if(!ve.ok)throw new Error(`Local workspace content manifest failed (${ve.status||0}).`);const te=Array.isArray(ve.data?.entries)?ve.data.entries:[];Z=new Map(te.map(ce=>[`${ce.kind}:${ce.path}`,ce]))}for(;g&&h<O;){const ve=async()=>{const W=Date.now(),K=await t.pullWorkspaceChanges({workspaceId:e.workspaceId,cursor:p,limit:e.bootstrap?500:200,repairMode:e.repairMode===!0,contentMode:e.contentMode,excludeInitiatives:e.excludeInitiatives,excludedProjections:e.excludedProjections});return k+=Date.now()-W,K};let te=await ve();if(n(te),!te.ok&&te.status===403&&e.ensureCloudWorkspaceReadyForSync&&(await e.ensureCloudWorkspaceReadyForSync()).success&&(await s("WORKSPACE_SYNC_V2_PULL_RETRY"),te=await ve(),n(te)),!te.ok){await s("WORKSPACE_SYNC_V2_PULL_REJECTED");const W=yn(te.data);return{success:!1,kind:"pull_http",status:te.status,errorCode:typeof W.code=="string"?W.code:void 0,error:typeof W.error=="string"?W.error:void 0,retryAfterMs:te.retryAfterMs,transient:ti(te.status),cursor:p,pages:h,appliedChanges:y,pullRequestMs:k,applyMs:b,pulledDeleteTaskIds:C,pulledActiveUpserts:S,pulledArchivedUpserts:w,pulledTaskEventUpserts:T,pulledPlanningUpserts:E,pulledTaskforceAgentUpserts:x,pulledTaskforceAgentSkillUpserts:v,pulledAgentConversationUpserts:V,documentDecryptFailures:Array.from(_),serverDiagnostics:null}}const ce=te.data||{};if(!rR(ce.excludedProjections,e.excludedProjections))return await s("SYNC_V2_PROJECTION_EXCLUSIONS_MISMATCH"),{success:!1,kind:"pull_http",status:502,errorCode:"SYNC_V2_PROJECTION_EXCLUSIONS_MISMATCH",error:"Cloud pull did not attest the requested v2 projection exclusions.",transient:!1,cursor:p,pages:h,appliedChanges:y,pullRequestMs:k,applyMs:b,pulledDeleteTaskIds:C,pulledActiveUpserts:S,pulledArchivedUpserts:w,pulledTaskEventUpserts:T,pulledPlanningUpserts:E,pulledTaskforceAgentUpserts:x,pulledTaskforceAgentSkillUpserts:v,pulledAgentConversationUpserts:V,documentDecryptFailures:Array.from(_),serverDiagnostics:null};let Le=Array.isArray(ce?.changes)?ce.changes:[];const Ie=new Map,Ye=[];if(e.contentMode==="manifest"){const W=[],K=[];for(const we of Le){if(we.op!=="document-manifest"&&we.op!=="asset-manifest"){K.push(we);continue}const ie=we.manifest;if(M.manifestEntries+=1,!ie.existsLocally){Ye.push({manifest:ie,sourceWatermark:ie.updatedAt}),U.add(`${ie.kind}:${ie.path}`);continue}const Q=`${ie.kind}:${ie.path}`,H=gR(ie,Z.get(Q));H.shouldFetch?H.reasons.every(se=>se==="metadata-mismatch")?(K.push(we),M.contentBytesAvoided+=Math.max(0,ie.sizeBytes)):(W.push({kind:ie.kind,path:ie.path}),Ie.set(Q,ie),M.bodiesRequested+=1):M.contentBytesAvoided+=Math.max(0,ie.sizeBytes)}const Re=[...W];for(;Re.length>0;){let we=Re.splice(0,100);for(;we.length>0;){const ie=await t.pullWorkspaceContent({workspaceId:e.workspaceId,requests:we,previousCursor:p});if(!ie.ok)throw n(ie),new Error(`Workspace content pull failed (${ie.status||0}).`);n(ie);const Q=ie.data||{},H=Array.isArray(Q.changes)?Q.changes:[],se=Array.isArray(Q.missing)?Q.missing:[];if(se.length>0){const ue="path"in se[0]?se[0].path:se[0].assetId;throw new Error(`Workspace content changed or disappeared during reconciliation: ${se[0].kind}:${ue}`)}K.push(...H);const Pe=Array.isArray(Q.remaining)?Q.remaining:[];if(H.length===0&&Pe.length>=we.length)throw new Error("Workspace content pull made no progress.");we=Pe}}Le=K}else{const W=[];for(const K of Le){if(K.op!=="document-manifest"&&K.op!=="asset-manifest"){W.push(K);continue}Ye.push({manifest:K.manifest,sourceWatermark:K.manifest.updatedAt}),U.add(`${K.manifest.kind}:${K.manifest.path}`)}Le=W}const ge=ce?.diagnostics&&typeof ce.diagnostics=="object"?ce.diagnostics:null;z=ge;const he=Array.isArray(ce?.workspaceMembers),Ae=he?ce.workspaceMembers:void 0;for(const W of Le){if(W.op==="upsert"){W?.archived===!0||W?.task?.isArchived===!0?w=!0:S=!0;continue}if(W.op==="annotated-attachment-session-upsert"){const Re=String(W?.session?.id||"").trim();Re&&F.add(Re);continue}if(W.op==="task-event-upsert"||W.op==="entity-event-upsert"){T=!0;continue}if(W.op==="initiative-upsert"||W.op==="workstream-upsert"){E=!0;continue}if(W.op==="taskforce-agent-upsert"){x=!0;continue}if(W.op==="agent-role-upsert"){N=!0;continue}if(W.op==="taskforce-agent-skill-upsert"){v=!0;continue}if(W.op==="agent-conversation-upsert"){V=!0;continue}if(W.op==="document-upsert"){if(typeof W.content=="string"&&typeof process<"u"&&pl?.TASKFORCE_SYNC_KEY)try{await Lh(W,pl.TASKFORCE_SYNC_KEY)}catch{const Re=String(W.path||"").trim();Re&&_.add(Re)}continue}if(W.op==="asset-upsert"){if(typeof W.contentBase64=="string"&&typeof process<"u"&&pl?.TASKFORCE_SYNC_KEY)try{await Lh(W,pl.TASKFORCE_SYNC_KEY)}catch{const Re=String(W.path||"").trim();Re&&_.add(Re)}continue}if(W.op!=="delete")continue;const K=String(W.taskId||"").trim();K&&C.add(K)}if(e.contentMode==="manifest"&&Ie.size>0){const W=new Set;for(const K of Le){if(K.op!=="document-upsert"&&K.op!=="asset-upsert")continue;const Re=K.op==="document-upsert"?"document":"asset",we=Ie.get(`${Re}:${K.path}`);if(!we)continue;const ie=await Qh(Re,K.op==="document-upsert"?K.content:K.contentBase64);if(we.sha256&&ie.sha256!==we.sha256.toLowerCase()||ie.sizeBytes!==we.sizeBytes)throw new Error(`Workspace content verification failed for ${Re}:${K.path}.`);W.add(`${Re}:${K.path}`),M.bodiesTransferred+=1,M.contentBytesTransferred+=ie.sizeBytes}if(W.size!==Ie.size)throw new Error("Workspace content pull did not return every requested body.")}e.onPagePulled&&e.onPagePulled();const ye=ce&&"nextCursor"in ce&&(ce.nextCursor===null||typeof ce.nextCursor=="string")?ce.nextCursor:p,Ne=Le.flatMap(W=>W.op!=="document-delete"&&W.op!=="asset-delete"?[]:W.deletedAt?[{kind:W.op==="document-delete"?"document":"asset",path:W.path,resolution:"at-or-before-watermark",sourceWatermark:W.deletedAt}]:[]),ae=e.bootstrap&&!ce?.hasMore,q=r.length>0?t.buildV2ApplyCompletionGroup({workspaceId:e.workspaceId,previousCursor:p,nextCursor:ye,receipts:r}):void 0;if(r.length>0&&!q)throw new Error("V2 sync transfer receipts did not produce an apply completion group.");if(Le.length>0||Ye.length>0||he||q||ae){const W=Date.now(),K=await l(e.workspaceId,Le,{...he?{workspaceMembers:Ae}:{},repairMode:e.repairMode===!0,excludedProjections:e.excludedProjections,...ae?{bootstrapSnapshot:{currentAnnotatedAttachmentSessionIds:Array.from(F)}}:{},...q?{completionGroup:q}:{},...Ye.length>0?{contentPullObligations:Ye}:{},...Ne.length>0?{contentPullResolutionClaims:Ne}:{}}),Re=K.failures;if(!K.ok){b+=Date.now()-W,await s("WORKSPACE_SYNC_V2_APPLY_NOT_COMMITTED");const ie=yn(K.data);if(Re.some(se=>se.endsWith(":401")))return{success:!1,kind:"apply_auth",status:401,transient:!1,failures:Re,cursor:p,pages:h,appliedChanges:y,pullRequestMs:k,applyMs:b,pulledDeleteTaskIds:C,pulledActiveUpserts:S,pulledArchivedUpserts:w,pulledTaskEventUpserts:T,pulledPlanningUpserts:E,pulledTaskforceAgentUpserts:x,pulledTaskforceAgentSkillUpserts:v,pulledAgentConversationUpserts:V,documentDecryptFailures:Array.from(_),serverDiagnostics:ge};const H=Re.some(se=>{if(se.endsWith(":network"))return!0;const Pe=se.split(":").pop()||"",ue=Number.parseInt(Pe,10);return Number.isFinite(ue)&&(ue===429||ue>=500)});return{success:!1,kind:"apply_all_candidates",status:K.status||void 0,transient:H,error:String(ie.error||"").trim()||void 0,failures:Re,hasTransientApplyFailure:H,cursor:p,pages:h,appliedChanges:y,pullRequestMs:k,applyMs:b,pulledDeleteTaskIds:C,pulledActiveUpserts:S,pulledArchivedUpserts:w,pulledTaskEventUpserts:T,pulledPlanningUpserts:E,pulledTaskforceAgentUpserts:x,pulledTaskforceAgentSkillUpserts:v,pulledAgentConversationUpserts:V,documentDecryptFailures:Array.from(_),emittedEventIds:Array.from(j),serverDiagnostics:z}}const we=yn(K.data);if(we.success===!1)return b+=Date.now()-W,await s("WORKSPACE_SYNC_V2_APPLY_NOT_COMMITTED"),{success:!1,kind:"apply_payload",transient:!1,error:String(we.error||"Workspace sync apply failed."),cursor:p,pages:h,appliedChanges:y,pullRequestMs:k,applyMs:b,pulledDeleteTaskIds:C,pulledActiveUpserts:S,pulledArchivedUpserts:w,pulledTaskEventUpserts:T,pulledPlanningUpserts:E,pulledTaskforceAgentUpserts:x,pulledTaskforceAgentSkillUpserts:v,pulledAgentConversationUpserts:V,documentDecryptFailures:Array.from(_),emittedEventIds:Array.from(j),serverDiagnostics:z};if(b+=Date.now()-W,y+=Le.length,Array.isArray(we.emittedEventIds))for(const ie of we.emittedEventIds)j.add(String(ie));Le.some(ie=>ie.op==="ai-profile-upsert")&&e.onAiProfilesApplied?.(),e.onChangesApplied&&e.onChangesApplied(Le.length),Ne.forEach(ie=>{U.delete(Tc(ie))})}r=[],ce&&"nextCursor"in ce&&(ce.nextCursor===null||typeof ce.nextCursor=="string")&&(p=ce.nextCursor),g=!!ce?.hasMore,h+=1}return{success:!0,hasMore:g,syncedAt:new Date().toISOString(),cursor:p||null,pages:h,appliedChanges:y,pullRequestMs:k,applyMs:b,pulledDeleteTaskIds:C,pulledActiveUpserts:S,pulledArchivedUpserts:w,pulledTaskEventUpserts:T,pulledPlanningUpserts:E,pulledTaskforceAgentUpserts:x,pulledAgentRoleUpserts:N,pulledTaskforceAgentSkillUpserts:v,pulledAgentConversationUpserts:V,documentDecryptFailures:Array.from(_),emittedEventIds:Array.from(j),serverDiagnostics:e.contentMode==="manifest"?{...z||{},contentReconciliation:M}:z}}catch(ve){let te=ve;try{await s("WORKSPACE_SYNC_V2_APPLY_NOT_COMMITTED")}catch(ce){te=ce}return{success:!1,kind:"exception",status:0,transient:!0,error:String(te?.message||te||"Workspace sync pull failed unexpectedly."),cursor:p||null,pages:h,appliedChanges:y,pullRequestMs:k,applyMs:b,pulledDeleteTaskIds:C,pulledActiveUpserts:S,pulledArchivedUpserts:w,pulledTaskEventUpserts:T,pulledPlanningUpserts:E,pulledTaskforceAgentUpserts:x,pulledTaskforceAgentSkillUpserts:v,pulledAgentConversationUpserts:V,documentDecryptFailures:Array.from(_),emittedEventIds:Array.from(j),serverDiagnostics:e.contentMode==="manifest"?{...z||{},contentReconciliation:M}:z}}}async function NR(e){const t=await iR(e.resolveCloudAuthUrl);if(!t.ok){const h=Number(t.status||0);return{success:!1,error:`Sync pull failed (${t.status})`,statusCode:t.status,retryAfterMs:t.retryAfterMs,transient:ti(h)}}const r=yn(t.data),n=r.settings&&typeof r.settings=="object"?r.settings:{},s=typeof r.updatedAt=="string"&&r.updatedAt.trim().length>0?r.updatedAt.trim():null,i=e.getLocalUpdatedAt(e.userId),l=i?Date.parse(i):NaN,c=s?Date.parse(s):NaN;if(!i&&e.preferCloudOnFirstSync&&Number.isFinite(c))return await e.applyRemoteSettings(n),{success:!0,mode:"pulled",updatedAt:s};if(Number.isFinite(c)&&(!Number.isFinite(l)||c>l))return await e.applyRemoteSettings(n),{success:!0,mode:"pulled",updatedAt:s};const d=i||new Date().toISOString(),f=await cR(e.resolveCloudAuthUrl,{settings:e.buildLocalSettings(),updatedAt:d});if(!f.ok){const h=Number(f.status||0);return{success:!1,error:`Sync push failed (${f.status})`,statusCode:f.status,retryAfterMs:f.retryAfterMs,transient:ti(h)}}const p=yn(f.data);return{success:!0,mode:"pushed",updatedAt:typeof p.updatedAt=="string"&&p.updatedAt.trim().length>0?p.updatedAt.trim():d}}function MR(e){const t=Math.max(1,Math.floor(Number(e)||1)),r=Math.min(12e4,1500*2**Math.max(0,t-1)),n=Math.floor(r*(.15*Math.random()));return r+n}function DR(e){const t=String(e||"").trim().replace(/\\/g,"/");if(!t||t.startsWith("/"))return null;const r=t.split("/").filter(Boolean);return r.length===0||r.some(n=>n==="."||n==="..")?null:r.join("/")}function LR(e){const t=DR(e);return!t||!["users/","workspaces/","system/","tmp/","quarantine/"].some(n=>t.startsWith(n))?null:t}function OR(e){return String(e||"").trim()}function BR(e,t){return OR(e).replace(/[^a-zA-Z0-9._-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||t}function WR(e,t){const r=BR(t,"default"),n=String(e||"").replace(/\\/g,"/");return(n.startsWith(`workspaces/${r}/assets/ai-profiles/`)||n.startsWith(`workspaces/${r}/assets/images/ai-profiles/`))&&n.includes("/avatar/")}function $R(e,t){const r=String(e||"").trim();if(!r.startsWith("/api/taskforce/context/"))return null;const n=r.slice(23).split(/[?#]/,1)[0]||"";if(!n)return null;try{return t(decodeURIComponent(n))}catch{return null}}function FR(e,t){return WR(e,t)}function UR(e){const t=e.split("/").pop()||"",r=t.lastIndexOf("."),n=r>=0?t.slice(r).toLowerCase():"";return n===".png"?"image/png":n===".jpg"||n===".jpeg"?"image/jpeg":n===".webp"?"image/webp":n===".gif"?"image/gif":"application/octet-stream"}function zR(e){return String(e||"").match(/(^|\/)(asset-[a-f0-9]{32})(?=[^/]*$)/i)?.[2]}function HR(e,t,r){const n=new Map;for(const s of Array.isArray(e)?e:[]){const i=String(s?.updatedAt||s?.createdAt||"").trim();for(const l of[s?.avatarUrl,s?.avatarSourceUrl]){const c=$R(l,r);!c||!FR(c,t)||n.has(c)||n.set(c,{updatedAt:i,assetId:zR(c),originalFilename:c.split("/").pop()||c,mimeType:UR(c)})}}return n}const GR=new Set(["assetId","path","caption","displayName","originalFilename","referenceNumber","referenceLabel","linkRole"]);[...GR];function Ok(e,t){return e<t?-1:e>t?1:0}function ei(e){return typeof e!="string"?void 0:e.trim()||void 0}function Bf(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Planning comments must be an array.");return e.map((t,r)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Planning comment ${r} must be an object.`);const n=t,s=ei(n.id),i=ei(n.author),l=Date.parse(String(n.timestamp||"").trim());if(!s||!i||!Number.isFinite(l))throw new Error(`Planning comment ${r} has invalid identity, author, or timestamp.`);const c=ei(n.submittedAuthor);return{id:s,author:i,...c?{submittedAuthor:c}:{},text:String(n.text||""),timestamp:new Date(l).toISOString()}}).sort((t,r)=>Ok(t.timestamp,r.timestamp)||Ok(t.id,r.id))}}function Wf(e){if(e!==void 0){if(!Array.isArray(e))throw new Error("Planning attachments must be an array.");return e.map((t,r)=>{if(typeof t=="string"){const h=t.trim();if(!h)throw new Error(`Planning attachment ${r} path is required.`);return h}if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Planning attachment ${r} must be a path or object.`);const n=t,s=ei(n.path);if(!s)throw new Error(`Planning attachment ${r} path is required.`);const i=ei(n.fsPath),l=ei(n.timestamp),c=n.assetId===null?null:ei(n.assetId),d=n.referenceNumber===null?null:Number.isFinite(Number(n.referenceNumber))?Math.max(1,Math.floor(Number(n.referenceNumber))):void 0,f=n.referenceLabel===null?null:ei(n.referenceLabel),p=n.taskId===null?null:ei(n.taskId),g=n.linkRole==="attachment"||n.linkRole==="image"||n.linkRole==="reference"?n.linkRole:void 0;return{path:s,...i?{fsPath:i}:{},...typeof n.caption=="string"?{caption:n.caption}:{},...typeof n.displayName=="string"?{displayName:n.displayName}:{},...typeof n.originalFilename=="string"?{originalFilename:n.originalFilename}:{},...l?{timestamp:l}:{},...c!==void 0?{assetId:c}:{},...d!==void 0?{referenceNumber:d}:{},...f!==void 0?{referenceLabel:f}:{},...p!==void 0?{taskId:p}:{},...g?{linkRole:g}:{}}})}}function VR(e){if(e===void 0)return[];if(!Array.isArray(e))throw new Error("Planning attachments must be an array.");return e.map((t,r)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Durable planning attachment ${r} must be a canonical asset link.`);const n=t,s=ei(n.assetId),i=ei(n.path);if(!s||!i)throw new Error(`Durable planning attachment ${r} requires assetId and path.`);const l=n.referenceNumber===null?null:Number.isInteger(n.referenceNumber)&&Number(n.referenceNumber)>0?Number(n.referenceNumber):void 0,c=n.referenceLabel===null?null:ei(n.referenceLabel),d=n.linkRole==="attachment"||n.linkRole==="image"||n.linkRole==="reference"?n.linkRole:void 0;return{assetId:s,path:i,...typeof n.caption=="string"?{caption:n.caption}:{},...typeof n.displayName=="string"?{displayName:n.displayName}:{},...typeof n.originalFilename=="string"?{originalFilename:n.originalFilename}:{},...l!==void 0?{referenceNumber:l}:{},...c!==void 0?{referenceLabel:c}:{},...d?{linkRole:d}:{}}}).sort((t,r)=>Ok(`${t.assetId}\0${t.linkRole||""}\0${t.path}\0${JSON.stringify(t)}`,`${r.assetId}\0${r.linkRole||""}\0${r.path}\0${JSON.stringify(r)}`))}function KR(e){return Array.isArray(e)?e.slice(0,24).flatMap(t=>{if(!t||typeof t!="object"||Array.isArray(t))return[];const r=t,n=String(r.name||"").trim();if(!n)return[];const s=String(r.resultText||"").trim().slice(0,4e3);return[{name:n.slice(0,120),...r.arguments&&typeof r.arguments=="object"&&!Array.isArray(r.arguments)?{arguments:r.arguments}:{},ok:r.ok!==!1,...s?{resultText:s}:{}}]}):[]}function qR(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object"||Array.isArray(t))return[];const r=t,n=r.role==="assistant"?"assistant":r.role==="user"?"user":null,s=String(r.content||"").trim();if(!n||!s)return[];const i={role:n,content:s};for(const c of["agentId","agentName","providerKey","providerLabel","modelKey","modelLabel","modelId"]){const d=String(r[c]||"").trim();d&&(i[c]=d)}const l=KR(r.toolActivity);return n==="assistant"&&l.length>0&&(i.toolActivity=l),[i]}):[]}const YR=["chat_app","ide","cli","coding_tool","agent"],ZR={chat_app:"Chat App",ide:"IDE",cli:"CLI",coding_tool:"Coding Tool",agent:"Agent"},JR={chat_app:"Chat Apps",ide:"IDEs",cli:"CLI",coding_tool:"Coding Tools",agent:"Agents",unclassified:"Unclassified"};function QR(e){return typeof e=="string"&&YR.includes(e)}function gC(e){if(typeof e!="string")return null;const t=e.trim();return t==="other"?"agent":QR(t)?t:null}function Mee(e){return ZR[e]}function Dee(e){return e??"unclassified"}function Lee(e){return JR[e]}const XR=["cloud_metered","local_unmetered"],ej={cloud_metered:"Cloud MCP",local_unmetered:"Local MCP"};function tj(e){return typeof e=="string"&&XR.includes(e)}function yC(e){if(typeof e!="string")return null;const t=e.trim();return tj(t)?t:null}function Oee(e){return ej[e]}function ml(e){if(e==null)return;const t=String(e).trim();return t.length>0?t:void 0}function Ha(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function $f(e){return ml(e)}function Nc(e){return Ha(e)}function ms(e){return Ha(e)}function Uu(e){const t=Ha(e);return t&&t.startsWith("/api/taskforce/context/")?t:null}function Xy(e){return ml(e)}function Qp(e){if(e!==void 0)return Ha(e)}function rj(e){return typeof e=="boolean"?e:void 0}function rh(e,t){if(e===void 0)return;if(e===null||e==="")return t?.nullable?null:void 0;const r=typeof e=="number"?e:Number(e);if(!Number.isFinite(r))return t?.nullable?null:void 0;const n=Math.floor(r);return Number.isFinite(t?.min)&&n<Number(t?.min)?t?.nullable?null:void 0:n}function aj(e){if(!e||typeof e!="object"||Array.isArray(e))return;const r=Object.entries(e).reduce((n,[s,i])=>s==="approach"?n:Array.isArray(i)?(n[s]=i.map(l=>String(l??"")),n):(i==null||(n[s]=String(i)),n),{});return Object.keys(r).length>0?r:{}}function nj(e){if(Array.isArray(e))return e.map(t=>{const r=t;return{id:r.id,author:r.author,...r.submittedAuthor===void 0?{}:{submittedAuthor:r.submittedAuthor},text:r.text,timestamp:r.timestamp}})}function sj(e){return Array.isArray(e)?e:void 0}function oj(e){return Array.isArray(e)?e:void 0}function kC(e){const t=e&&typeof e=="object"?e:{},r=Object.prototype.hasOwnProperty.call(t,"cardCoverAssetId");return{id:String(t.id||"").trim(),title:String(t.title||"").trim(),description:t.description===void 0?void 0:t.description||null,status:String(t.status||"task").trim()||"task",priority:rh(t.priority,{min:1})??void 0,complexity:rh(t.complexity,{min:1,nullable:!0}),type:String(t.type||"").trim(),category:String(t.category||"").trim(),canceledReason:t.canceledReason===void 0?void 0:t.canceledReason||null,createdAt:String(t.createdAt||"").trim(),updatedAt:Xy(t.updatedAt),completedAt:t.completedAt===void 0?void 0:t.completedAt||null,isArchived:rj(t.isArchived),taxonomies:aj(t.taxonomies),createdBy:Xy(t.createdBy),assignee:Xy(t.assignee),scheduledDate:Qp(t.scheduledDate),dueDate:Qp(t.dueDate),scheduledWeekKey:Qp(t.scheduledWeekKey),orderInDay:rh(t.orderInDay,{min:0,nullable:!0}),workstreamId:Qp(t.workstreamId),referenceNumber:rh(t.referenceNumber,{min:1,nullable:!0}),comments:nj(t.comments),attachments:sj(t.attachments),...r?{cardCoverAssetId:Qp(t.cardCoverAssetId)}:{},checklistItems:oj(t.checklistItems)}}function ij(e){if(!e||typeof e!="object"||Array.isArray(e))return{};const t=Object.entries(e).filter(([n])=>String(n||"").trim().length>0).sort(([n],[s])=>n.localeCompare(s)),r={};for(const[n,s]of t){if(Array.isArray(s)){r[n]=s.map(i=>String(i??"")).sort((i,l)=>i.localeCompare(l));continue}s!=null&&(r[n]=String(s))}return r}function cj(e){return Array.isArray(e)?e.map(t=>{const r=t&&typeof t=="object"?t:{};return{id:String(r.id||"").trim(),title:String(r.title||"").trim(),isCompleted:!!r.isCompleted,order:r.order===void 0||r.order===null?"":String(r.order)}}).sort((t,r)=>{const n=Number.parseInt(t.order,10),s=Number.parseInt(r.order,10);return Number.isFinite(n)&&Number.isFinite(s)&&n!==s?n-s:t.title!==r.title?t.title.localeCompare(r.title):t.id.localeCompare(r.id)}):[]}function lj(e){return Array.isArray(e)?e.map(t=>{const r=t&&typeof t=="object"?t:null;return{id:String(r?.id||"").trim(),author:String(r?.author||"").trim(),submittedAuthor:ml(r?.submittedAuthor)||"",text:String(r?.text||""),timestamp:ms(r?.timestamp)||"",actor:r?.actor??null}}).sort((t,r)=>t.timestamp!==r.timestamp?t.timestamp.localeCompare(r.timestamp):t.id!==r.id?t.id.localeCompare(r.id):t.author!==r.author?t.author.localeCompare(r.author):t.text.localeCompare(r.text)):[]}function dj(e){return Array.isArray(e)?e.map(t=>{if(typeof t=="string")return{path:t.trim(),fsPath:"",caption:"",displayName:"",originalFilename:"",assetId:"",referenceNumber:"",taskId:"",timestamp:""};const r=t&&typeof t=="object"?t:null;return{path:String(r?.path||"").trim(),fsPath:ml(r?.fsPath)||"",caption:ml(r?.caption)||"",displayName:ml(r?.displayName)||"",originalFilename:ml(r?.originalFilename)||"",assetId:$f(r?.assetId)||"",referenceNumber:r?.referenceNumber===void 0||r.referenceNumber===null?"":String(r.referenceNumber),taskId:Nc(r?.taskId)||"",timestamp:ms(r?.timestamp)||""}}).sort((t,r)=>t.path!==r.path?t.path.localeCompare(r.path):t.assetId!==r.assetId?t.assetId.localeCompare(r.assetId):t.timestamp!==r.timestamp?t.timestamp.localeCompare(r.timestamp):JSON.stringify(t).localeCompare(JSON.stringify(r))):[]}function uj(e,t){const r=kC(e);return JSON.stringify({id:r.id,title:r.title,description:Ha(r.description)||"",category:r.category,type:r.type,priority:r.priority===void 0||r.priority===null?"":String(r.priority),complexity:r.complexity===void 0||r.complexity===null?"":String(r.complexity),status:r.status,canceledReason:Ha(r.canceledReason)||"",createdAt:r.createdAt,completedAt:ms(r.completedAt)||"",taxonomies:ij(r.taxonomies),createdBy:$f(r.createdBy)||"",assignee:$f(r.assignee)||"",scheduledDate:Ha(r.scheduledDate)||"",dueDate:Ha(r.dueDate)||"",scheduledWeekKey:Ha(r.scheduledWeekKey)||"",orderInDay:r.orderInDay===void 0||r.orderInDay===null?"":String(r.orderInDay),workstreamId:Nc(r.workstreamId)||"",referenceNumber:r.referenceNumber===void 0||r.referenceNumber===null?"":String(r.referenceNumber),comments:lj(r.comments),attachments:dj(r.attachments),checklistItems:cj(r.checklistItems),isArchived:t?"1":"0"})}function pj(...e){return e.reduce((t,r)=>{const n=ms(r)||"";return t?n&&n>t?n:t:n},"")}function fj(e){const t=e||{};return pj(t.createdAt,t.updatedAt,t.lastActiveAt,t.colorUpdatedAt,t.archivedAt,t.rosterStateUpdatedAt)}function vC(e){const t=e||{};return JSON.stringify({id:String(t.id||"").trim(),workspaceId:String(t.workspaceId||"").trim(),profileToken:String(t.profileToken||"").trim(),name:String(t.name||"").trim(),username:String(t.username||"").trim(),icon:String(t.icon||"Bot").trim()||"Bot",color:String(t.color||"#8b5cf6").trim()||"#8b5cf6",colorSource:Ha(t.colorSource)||"",colorUpdatedAt:ms(t.colorUpdatedAt)||"",avatarUrl:Uu(t.avatarUrl)||"",avatarSourceUrl:Uu(t.avatarSourceUrl)||"",avatarRevision:Number.isFinite(Number(t.avatarRevision))?Math.max(0,Math.floor(Number(t.avatarRevision))):0,avatarUpdatedAt:ms(t.avatarUpdatedAt)||"",description:Ha(t.description)||"",role:Ha(t.role)||"",provider:Ha(t.provider)||"",model:Ha(t.model)||"",surfaceType:Ha(t.surfaceType)||"",seatScope:Ha(t.seatScope)||"",providerMetadata:t.providerMetadata&&typeof t.providerMetadata=="object"&&!Array.isArray(t.providerMetadata)?t.providerMetadata:null,archivedAt:ms(t.archivedAt)||"",archivedBy:$f(t.archivedBy)||"",archivedReason:Ha(t.archivedReason)||"",mergedIntoProfileId:$f(t.mergedIntoProfileId)||"",rosterStateUpdatedAt:ms(t.rosterStateUpdatedAt)||"",createdAt:ms(t.createdAt)||"",updatedAt:ms(t.updatedAt)||"",lastActiveAt:ms(t.lastActiveAt)||""})}function mj(e){return JSON.stringify(e.map(t=>vC(t)).sort())}function Uv(e){return $a(e||null)}function wC(e){return e.taxonomyState&&typeof e.taxonomyState=="object"?$a({taxonomyState:e.taxonomyState}):Array.isArray(e.taxonomies)?$a({taxonomies:e.taxonomies}):""}const Xo={kind:"task",getId:e=>String(e?.id||"").trim(),getWatermark:e=>String(e?.updatedAt||e?.createdAt||"").trim(),getChangeKey:e=>uj(e,!!e?.isArchived)},Cf={kind:"ai-profile",getId:e=>String(e?.id||"").trim(),getWatermark:e=>fj(e),getChangeKey:e=>vC(e)};function Tb(e,t,r){const n=e.getId(t);if(!n)return!1;const s=e.getChangeKey(t),i=r?.watermarks;if(!i||i.size===0||!i.has(n))return!0;const c=r?.changeKeys?.get(n);return typeof c=="string"?c!==s:(i.get(n)||"")!==s}function xb(e){return kC(e)}function Rb(e,t){const r=e??t;return new Set(Array.from(r).map(n=>String(n||"").trim()).filter(n=>n.length>0))}function hj(e){return[...e].sort((t,r)=>{const n=String(t?.createdAt||"").trim(),s=String(r?.createdAt||"").trim(),i=n.localeCompare(s);return i!==0?i:String(t?.id||"").trim().localeCompare(String(r?.id||"").trim())})}function jb(e){return[...e].sort((t,r)=>{const n=String(t?.id||"").trim(),s=String(r?.id||"").trim();return n.localeCompare(s)})}function gj(e){const t=new Date().toISOString(),r=new Set(Array.from(e.pendingDeletedTaskIds).map(u=>String(u||"").trim()).filter(u=>u.length>0)),n=new Map(Array.from(e.pendingDeletedTaskWatermarks||new Map).map(([u,Pt])=>[String(u||"").trim(),String(Pt||"").trim()]).filter(([u,Pt])=>u.length>0&&Number.isFinite(Date.parse(Pt)))),s=new Map((e.deletedTasks||[]).map(u=>[String(u.taskId||"").trim(),u])),i=u=>{const Pt=s.get(u);return{op:"delete",taskId:u,deletedAt:Pt?.deletedAt||n.get(u)||t,...Pt?{actor:Pt.actor,actorType:Pt.actorType,source:Pt.source,details:Pt.details}:{}}},l=e.lastPushedWatermarks,c=e.lastPushedTaskChangeKeys,d=(u,Pt)=>(u?.referenceNumber===void 0||u?.referenceNumber===null)&&Number.isFinite(Number(u?.localReferenceNumber))?!0:Tb(Xo,{...u,isArchived:Pt},{watermarks:l,changeKeys:c}),f=jb(e.tasks||[]),p=jb(e.archivedTasks||[]),g=new Map,h=new Map,y=new Map,k=new Map,b=f.filter(u=>!r.has(String(u?.id||"").trim())&&d(u,!1)).map(u=>{const Pt=String(u?.id||"").trim(),pr=Xo.getWatermark(u),Yr=Xo.getChangeKey({...u,isArchived:!1});return Pt&&(y.set(Pt,pr),k.set(Pt,Yr)),{op:"upsert",archived:!1,task:xb(u)}}),C=p.filter(u=>!r.has(String(u?.id||"").trim())&&d(u,!0)).map(u=>{const Pt=String(u?.id||"").trim(),pr=Xo.getWatermark(u),Yr=Xo.getChangeKey({...u,isArchived:!0});return Pt&&(y.set(Pt,pr),k.set(Pt,Yr)),{op:"upsert",archived:!0,task:xb(u)}}),S=new Set;for(const u of e.tasks||[]){const Pt=String(u?.id||"").trim();Pt&&(S.add(Pt),g.set(Pt,Xo.getWatermark(u)),h.set(Pt,Xo.getChangeKey({...u,isArchived:!1})))}for(const u of e.archivedTasks||[]){const Pt=String(u?.id||"").trim();Pt&&(S.add(Pt),g.set(Pt,Xo.getWatermark(u)),h.set(Pt,Xo.getChangeKey({...u,isArchived:!0})))}const w=Array.from(e.lastPushedTaskIds).filter(u=>!S.has(u)).map(u=>i(u)),T=Array.from(r).map(u=>i(u)),E=new Set([...w.map(u=>String(u.taskId)),...T.map(u=>String(u.taskId))]),x=e.lastPushedTaskRelationshipChangeKeys,N=new Map,v=(Array.isArray(e.taskRelationships)?e.taskRelationships:[]).filter(u=>u?.id&&Number.isFinite(Date.parse(String(u.updatedAt||"")))).map(u=>{const Pt=String(u.id||"").trim(),pr=Uv(u);return N.set(Pt,pr),{op:u.deletedAt?"task-relationship-delete":"task-relationship-upsert",relationship:u,relationshipId:Pt,changeKey:pr}}).filter(u=>x?.get(u.relationshipId)!==u.changeKey).map(({relationshipId:u,changeKey:Pt,...pr})=>pr),V=new Set((Array.isArray(e.initiatives)?e.initiatives:[]).map(u=>String(u?.id||"").trim()).filter(u=>u.length>0)),_=new Map((Array.isArray(e.initiatives)?e.initiatives:[]).map(u=>[String(u?.id||"").trim(),String(u?.updatedAt||u?.createdAt||"").trim()]).filter(([u])=>u.length>0)),j=e.lastPushedInitiativeWatermarks,F=!j||j.size===0,z=(Array.isArray(e.initiatives)?e.initiatives:[]).map(u=>({op:"initiative-upsert",initiative:{id:String(u?.id||"").trim(),referenceNumber:Number.isFinite(Number(u?.referenceNumber))?Math.max(1,Math.floor(Number(u.referenceNumber))):null,referenceLabel:typeof u?.referenceLabel=="string"&&u.referenceLabel.trim().length>0?u.referenceLabel.trim():void 0,title:String(u?.title||"").trim(),description:typeof u?.description=="string"?u.description:null,ownerId:typeof u?.ownerId=="string"&&u.ownerId.trim().length>0?u.ownerId.trim():null,comments:Bf(u?.comments),createdAt:String(u?.createdAt||"").trim(),updatedAt:String(u?.updatedAt||u?.createdAt||"").trim(),order:Number.isFinite(Number(u?.order))?Math.floor(Number(u.order)):null,attachments:Wf(u?.attachments),isArchived:!!u?.isArchived}})).filter(u=>u.initiative.id.length>0).filter(u=>F?!0:j.get(u.initiative.id)!==u.initiative.updatedAt),M=new Set((Array.isArray(e.workstreams)?e.workstreams:[]).map(u=>String(u?.id||"").trim()).filter(u=>u.length>0)),O=new Map((Array.isArray(e.workstreams)?e.workstreams:[]).map(u=>[String(u?.id||"").trim(),String(u?.updatedAt||u?.createdAt||"").trim()]).filter(([u])=>u.length>0)),Z=e.lastPushedWorkstreamWatermarks,U=!Z||Z.size===0,ve=(Array.isArray(e.workstreams)?e.workstreams:[]).map(u=>({op:"workstream-upsert",workstream:{id:String(u?.id||"").trim(),referenceNumber:Number.isFinite(Number(u?.referenceNumber))?Math.max(1,Math.floor(Number(u.referenceNumber))):null,referenceLabel:typeof u?.referenceLabel=="string"&&u.referenceLabel.trim().length>0?u.referenceLabel.trim():void 0,initiativeId:typeof u?.initiativeId=="string"&&u.initiativeId.trim().length>0?u.initiativeId.trim():null,title:String(u?.title||"").trim(),description:typeof u?.description=="string"?u.description:null,ownerId:typeof u?.ownerId=="string"&&u.ownerId.trim().length>0?u.ownerId.trim():null,comments:Bf(u?.comments),createdAt:String(u?.createdAt||"").trim(),updatedAt:String(u?.updatedAt||u?.createdAt||"").trim(),order:Number.isFinite(Number(u?.order))?Math.floor(Number(u.order)):null,attachments:Wf(u?.attachments),isArchived:!!u?.isArchived}})).filter(u=>u.workstream.id.length>0).filter(u=>U?!0:Z.get(u.workstream.id)!==u.workstream.updatedAt),te=[...(Array.isArray(e.initiatives)?e.initiatives:[]).map(u=>({entityType:"initiative",entityId:String(u?.id||"").trim(),icon:u?.icon??null,color:u?.color??null,updatedAt:String(u?.identityUpdatedAt||"").trim()})),...(Array.isArray(e.workstreams)?e.workstreams:[]).map(u=>({entityType:"workstream",entityId:String(u?.id||"").trim(),icon:u?.icon??null,color:u?.color??null,updatedAt:String(u?.identityUpdatedAt||"").trim()}))].filter(u=>u.entityId.length>0&&Number.isFinite(Date.parse(u.updatedAt))).map(u=>({op:"planning-identity-upsert",identity:u})),ce=new Set((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(u=>String(u?.id||"").trim()).filter(u=>u.length>0)),Le=new Map((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(u=>[String(u?.id||"").trim(),Cf.getWatermark(u)]).filter(([u])=>u.length>0)),Ie=new Map((Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(u=>[String(u?.id||"").trim(),Cf.getChangeKey(u)]).filter(([u])=>u.length>0)),Ye=e.lastPushedAiProfileWatermarks,ge=e.lastPushedAiProfileChangeKeys,he=!Ye||Ye.size===0,Ae=(Array.isArray(e.aiProfiles)?e.aiProfiles:[]).map(u=>({op:"ai-profile-upsert",profile:{id:String(u.id||"").trim(),workspaceId:String(u.workspaceId||"").trim(),profileToken:String(u.profileToken||"").trim(),name:String(u.name||"").trim(),username:String(u.username||"").trim(),icon:String(u.icon||"Bot").trim()||"Bot",color:String(u.color||"#8b5cf6").trim()||"#8b5cf6",colorSource:typeof u.colorSource=="string"?u.colorSource:null,colorUpdatedAt:typeof u.colorUpdatedAt=="string"?u.colorUpdatedAt:null,avatarUrl:Uu(u.avatarUrl),avatarSourceUrl:Uu(u.avatarSourceUrl),avatarRevision:Number.isFinite(Number(u.avatarRevision))?Math.max(0,Math.floor(Number(u.avatarRevision))):0,avatarUpdatedAt:typeof u.avatarUpdatedAt=="string"&&u.avatarUpdatedAt.trim().length>0?u.avatarUpdatedAt.trim():null,description:typeof u.description=="string"&&u.description.trim()||null,role:typeof u.role=="string"&&u.role.trim()||null,provider:typeof u.provider=="string"&&u.provider.trim()||null,model:typeof u.model=="string"&&u.model.trim()||null,surfaceType:gC(u.surfaceType),seatScope:yC(u.seatScope),providerMetadata:u.providerMetadata&&typeof u.providerMetadata=="object"&&!Array.isArray(u.providerMetadata)?u.providerMetadata:null,archivedAt:typeof u.archivedAt=="string"&&u.archivedAt.trim().length>0?u.archivedAt.trim():null,archivedBy:typeof u.archivedBy=="string"&&u.archivedBy.trim().length>0?u.archivedBy.trim():null,archivedReason:typeof u.archivedReason=="string"&&u.archivedReason.trim()||null,mergedIntoProfileId:typeof u.mergedIntoProfileId=="string"&&u.mergedIntoProfileId.trim().length>0?u.mergedIntoProfileId.trim():null,rosterStateUpdatedAt:typeof u.rosterStateUpdatedAt=="string"&&u.rosterStateUpdatedAt.trim().length>0?u.rosterStateUpdatedAt.trim():null,createdAt:String(u.createdAt||"").trim(),updatedAt:String(u.updatedAt||u.createdAt||"").trim(),lastActiveAt:typeof u.lastActiveAt=="string"&&u.lastActiveAt.trim().length>0?u.lastActiveAt.trim():null}})).filter(u=>u.profile.id.length>0&&u.profile.workspaceId.length>0).filter(u=>he?!0:Tb(Cf,u.profile,{watermarks:Ye,changeKeys:ge})),ye=Rb(e.currentDocumentPaths,(Array.isArray(e.documents)?e.documents:[]).map(u=>String(u?.path||"").trim())),Ne=new Set(Array.from(e.lastPushedDocumentPaths||new Set).map(u=>String(u||"").trim()).filter(u=>u.length>0&&!ye.has(u))),ae=new Map((Array.isArray(e.documents)?e.documents:[]).map(u=>[String(u?.path||"").trim(),String(u?.updatedAt||"").trim()]).filter(([u])=>u.length>0)),q=e.lastPushedDocumentWatermarks,W=!q||q.size===0,K=(Array.isArray(e.documents)?e.documents:[]).map(u=>({op:"document-upsert",path:String(u.path||"").trim(),updatedAt:String(u.updatedAt||"").trim(),content:typeof u.content=="string"?u.content:"",assetId:typeof u.assetId=="string"&&u.assetId.trim().length>0?u.assetId.trim():void 0,documentId:typeof u.documentId=="string"&&u.documentId.trim().length>0?u.documentId.trim():null,referenceNumber:Number.isFinite(Number(u.referenceNumber))?Math.max(1,Math.floor(Number(u.referenceNumber))):null,version:Number.isFinite(Number(u.version))?Math.max(1,Math.floor(Number(u.version))):null,taskId:typeof u.taskId=="string"&&u.taskId.trim().length>0?u.taskId.trim():null,linkTargetType:u.linkTargetType==="initiative"||u.linkTargetType==="workstream"||u.linkTargetType==="task"?u.linkTargetType:null,linkTargetId:typeof u.linkTargetId=="string"&&u.linkTargetId.trim().length>0?u.linkTargetId.trim():null,logicalName:typeof u.logicalName=="string"&&u.logicalName.trim().length>0?u.logicalName.trim():null,caption:typeof u.caption=="string"&&u.caption.trim().length>0?u.caption.trim():null,originalFilename:typeof u.originalFilename=="string"&&u.originalFilename.trim().length>0?u.originalFilename.trim():null,linkRole:u.linkRole==="reference"?"reference":"attachment",...u.links?{links:u.links}:{}})).filter(u=>u.path.length>0).filter(u=>W?!0:q.get(u.path)!==u.updatedAt),Re=Rb(e.currentAssetPaths,(Array.isArray(e.assets)?e.assets:[]).map(u=>String(u?.path||"").trim())),we=new Set(Array.from(e.lastPushedAssetPaths||new Set).map(u=>String(u||"").trim()).filter(u=>u.length>0&&!Re.has(u))),ie=new Map((Array.isArray(e.assets)?e.assets:[]).map(u=>[String(u?.path||"").trim(),String(u?.updatedAt||"").trim()]).filter(([u])=>u.length>0)),Q=e.lastPushedAssetWatermarks,H=!Q||Q.size===0,se=(Array.isArray(e.assets)?e.assets:[]).map(u=>({op:"asset-upsert",path:String(u.path||"").trim(),updatedAt:String(u.updatedAt||"").trim(),contentBase64:typeof u.contentBase64=="string"?u.contentBase64:"",assetId:typeof u.assetId=="string"&&u.assetId.trim().length>0?u.assetId.trim():void 0,kind:u.kind==="image"?"image":"file",mimeType:typeof u.mimeType=="string"&&u.mimeType.trim().length>0?u.mimeType.trim():"application/octet-stream",referenceNumber:Number.isFinite(Number(u.referenceNumber))?Math.max(1,Math.floor(Number(u.referenceNumber))):null,taskId:typeof u.taskId=="string"&&u.taskId.trim().length>0?u.taskId.trim():null,linkTargetType:u.linkTargetType==="initiative"||u.linkTargetType==="workstream"||u.linkTargetType==="task"?u.linkTargetType:null,linkTargetId:typeof u.linkTargetId=="string"&&u.linkTargetId.trim().length>0?u.linkTargetId.trim():null,logicalName:typeof u.logicalName=="string"&&u.logicalName.trim().length>0?u.logicalName.trim():null,caption:typeof u.caption=="string"&&u.caption.trim().length>0?u.caption.trim():null,originalFilename:typeof u.originalFilename=="string"&&u.originalFilename.trim().length>0?u.originalFilename.trim():null,linkRole:u.linkRole==="reference"?"reference":u.linkRole==="image"?"image":"attachment",...u.links?{links:u.links}:{}})).filter(u=>u.path.length>0&&u.contentBase64.length>0).filter(u=>H?!0:Q.get(u.path)!==u.updatedAt),Pe=Array.isArray(e.documentReviewSessions)?e.documentReviewSessions:[],ue=new Set(Pe.map(u=>String(u?.id||"").trim()).filter(u=>u.length>0)),ne=new Set(Pe.filter(u=>String(u?.deletedAt||"").trim().length===0).map(u=>String(u?.id||"").trim()).filter(u=>u.length>0)),Me=e.lastPushedDocumentReviewSessionIds||new Set,pe=new Map(Pe.map(u=>[String(u?.id||"").trim(),String(u?.deletedAt||u?.updatedAt||u?.createdAt||"").trim()]).filter(([u])=>u.length>0)),le=e.lastPushedDocumentReviewSessionWatermarks,Ce=!le||le.size===0,P=Pe.map(u=>({op:"document-review-session-upsert",session:{id:String(u.id||"").trim(),assetId:String(u.assetId||"").trim(),documentId:typeof u.documentId=="string"&&u.documentId.trim().length>0?u.documentId.trim():null,documentVersion:Number.isFinite(Number(u.documentVersion))?Math.max(1,Math.floor(Number(u.documentVersion))):null,title:typeof u.title=="string"&&u.title.trim().length>0?u.title.trim():null,status:u.status==="resolved"?"resolved":"open",comments:[],createdByActorId:typeof u.createdByActorId=="string"&&u.createdByActorId.trim().length>0?u.createdByActorId.trim():null,updatedByActorId:typeof u.updatedByActorId=="string"&&u.updatedByActorId.trim().length>0?u.updatedByActorId.trim():null,createdAt:String(u.createdAt||"").trim(),updatedAt:String(u.updatedAt||u.createdAt||"").trim(),deletedAt:typeof u.deletedAt=="string"&&u.deletedAt.trim().length>0?u.deletedAt.trim():null}})).filter(u=>u.session.id.length>0&&u.session.assetId.length>0&&!u.session.deletedAt).filter(u=>Ce?!0:le.get(u.session.id)!==u.session.updatedAt),ee=Pe.filter(u=>String(u?.deletedAt||"").trim().length>0).map(u=>({sessionId:String(u?.id||"").trim(),deletedAt:String(u?.deletedAt||u?.updatedAt||u?.createdAt||t).trim()||t})).filter(u=>u.sessionId.length>0).filter(u=>Ce?!0:le.get(u.sessionId)!==u.deletedAt),Se=Array.from(Me).map(u=>String(u||"").trim()).filter(u=>u.length>0&&!ue.has(u)),_e=[...Se.map(u=>({sessionId:u,deletedAt:t})),...ee],ke=new Set([...Se,...ee.map(u=>u.sessionId)]),Ze=Array.isArray(e.documentReviewComments)?e.documentReviewComments:[],st=new Set(Ze.map(u=>String(u?.id||"").trim()).filter(u=>u.length>0)),at=new Set(Ze.filter(u=>String(u?.deletedAt||"").trim().length===0).map(u=>String(u?.id||"").trim()).filter(u=>u.length>0)),oe=e.lastPushedDocumentReviewCommentIds||new Set,We=new Map(Ze.map(u=>[String(u?.id||"").trim(),[u?.deletedAt,u?.threadStatusUpdatedAt,u?.updatedAt,u?.createdAt].map(Pt=>String(Pt||"").trim()).filter(Pt=>Number.isFinite(Date.parse(Pt))).sort().at(-1)||""]).filter(([u])=>u.length>0)),G=e.lastPushedDocumentReviewCommentWatermarks,Be=!G||G.size===0,Xe=Ze.map(u=>({op:"document-review-comment-upsert",comment:{id:String(u.id||"").trim(),sessionId:String(u.sessionId||"").trim(),body:String(u.body||"").trim(),anchor:u.anchor??null,order:Number.isFinite(Number(u.order))?Math.max(0,Math.floor(Number(u.order))):0,authorActorId:typeof u.authorActorId=="string"&&u.authorActorId.trim().length>0?u.authorActorId.trim():null,updatedByActorId:typeof u.updatedByActorId=="string"&&u.updatedByActorId.trim().length>0?u.updatedByActorId.trim():null,deletedByActorId:typeof u.deletedByActorId=="string"&&u.deletedByActorId.trim().length>0?u.deletedByActorId.trim():null,parentCommentId:typeof u.parentCommentId=="string"&&u.parentCommentId.trim().length>0?u.parentCommentId.trim():null,threadStatus:u.parentCommentId?null:u.threadStatus==="resolved"?"resolved":"open",threadStatusUpdatedAt:typeof u.threadStatusUpdatedAt=="string"&&u.threadStatusUpdatedAt.trim().length>0?u.threadStatusUpdatedAt.trim():null,resolvedAt:typeof u.resolvedAt=="string"&&u.resolvedAt.trim().length>0?u.resolvedAt.trim():null,resolvedByActorId:typeof u.resolvedByActorId=="string"&&u.resolvedByActorId.trim().length>0?u.resolvedByActorId.trim():null,createdAt:String(u.createdAt||"").trim(),updatedAt:String(u.updatedAt||u.createdAt||"").trim(),deletedAt:typeof u.deletedAt=="string"&&u.deletedAt.trim().length>0?u.deletedAt.trim():null}})).filter(u=>u.comment.id.length>0&&u.comment.sessionId.length>0&&!u.comment.deletedAt).filter(u=>Be?!0:G.get(u.comment.id)!==([u.comment.threadStatusUpdatedAt,u.comment.updatedAt].filter(Pt=>typeof Pt=="string"&&Number.isFinite(Date.parse(Pt))).sort().at(-1)||u.comment.updatedAt)),ze=Ze.filter(u=>String(u?.deletedAt||"").trim().length>0).map(u=>({commentId:String(u?.id||"").trim(),deletedAt:String(u?.deletedAt||u?.updatedAt||u?.createdAt||t).trim()||t,deletedByActorId:typeof u?.deletedByActorId=="string"&&u.deletedByActorId.trim().length>0?u.deletedByActorId.trim():null})).filter(u=>u.commentId.length>0).filter(u=>Be?!0:G.get(u.commentId)!==u.deletedAt),qe=Array.from(oe).map(u=>String(u||"").trim()).filter(u=>u.length>0&&!st.has(u)),Te=[...qe.map(u=>({commentId:u,deletedAt:t,deletedByActorId:null})),...ze],fe=new Set([...qe,...ze.map(u=>u.commentId)]),Ee=Array.isArray(e.annotatedAttachmentSessions)?e.annotatedAttachmentSessions:[],$e=new Set(Ee.map(u=>String(u?.id||"").trim()).filter(u=>u.length>0)),rt=new Set(Ee.filter(u=>String(u?.deletedAt||"").trim().length===0).map(u=>String(u?.id||"").trim()).filter(u=>u.length>0)),kt=e.lastPushedAnnotatedAttachmentSessionIds||new Set,xe=new Map(Ee.map(u=>[String(u?.id||"").trim(),String(u?.deletedAt||u?.updatedAt||u?.createdAt||"").trim()]).filter(([u])=>u.length>0)),St=e.lastPushedAnnotatedAttachmentSessionWatermarks,jt=!St||St.size===0,$=Ee.map(u=>({op:"annotated-attachment-session-upsert",session:{id:String(u.id||"").trim(),workspaceId:String(u.workspaceId||"").trim(),taskId:String(u.taskId||"").trim(),baseImageAssetId:String(u.baseImageAssetId||"").trim(),title:typeof u.title=="string"&&u.title.trim().length>0?u.title.trim():null,globalInstruction:typeof u.globalInstruction=="string"&&u.globalInstruction.trim().length>0?u.globalInstruction.trim():null,annotations:Array.isArray(u.annotations)?u.annotations:[],createdByActorId:typeof u.createdByActorId=="string"&&u.createdByActorId.trim().length>0?u.createdByActorId.trim():null,updatedByActorId:typeof u.updatedByActorId=="string"&&u.updatedByActorId.trim().length>0?u.updatedByActorId.trim():null,createdAt:String(u.createdAt||"").trim(),updatedAt:String(u.updatedAt||u.createdAt||"").trim(),deletedAt:typeof u.deletedAt=="string"&&u.deletedAt.trim().length>0?u.deletedAt.trim():null}})).filter(u=>u.session.id.length>0&&u.session.workspaceId.length>0&&u.session.baseImageAssetId.length>0&&!u.session.deletedAt).filter(u=>jt?!0:St.get(u.session.id)!==u.session.updatedAt),Ke=Ee.filter(u=>String(u?.deletedAt||"").trim().length>0).map(u=>({sessionId:String(u?.id||"").trim(),deletedAt:String(u?.deletedAt||u?.updatedAt||u?.createdAt||t).trim()||t})).filter(u=>u.sessionId.length>0).filter(u=>jt?!0:St.get(u.sessionId)!==u.deletedAt),Qe=Array.from(kt).map(u=>String(u||"").trim()).filter(u=>u.length>0&&!$e.has(u)),Ge=[...Qe.map(u=>({sessionId:u,deletedAt:t})),...Ke],At=new Set([...Qe,...Ke.map(u=>u.sessionId)]),Nt=Array.isArray(e.taskforceAgents)?e.taskforceAgents:[],Bt=new Set(Nt.filter(u=>String(u?.deletedAt||"").trim().length===0).map(u=>String(u?.id||"").trim()).filter(u=>u.length>0)),Qt=new Map(Nt.map(u=>[String(u?.id||"").trim(),String(u?.deletedAt||u?.updatedAt||u?.createdAt||"").trim()]).filter(([u])=>u.length>0)),Xt=e.lastPushedTaskforceAgentWatermarks,nt=!Xt||Xt.size===0,Mt=Nt.map(u=>({op:"taskforce-agent-upsert",agent:{id:String(u.id||"").trim(),tenantId:String(u.tenantId||"").trim()||void 0,workspaceId:String(u.workspaceId||"").trim(),...Object.prototype.hasOwnProperty.call(u,"definition")?{definition:u.definition,definitionRevision:Number(u.definitionRevision)||0,definitionHash:String(u.definitionHash||"").trim(),lifecycleStatus:String(u.lifecycleStatus||"").trim(),managedProfileId:typeof u.managedProfileId=="string"&&u.managedProfileId.trim()||null,configurationState:u.configurationState,configurationIssues:Array.isArray(u.configurationIssues)?u.configurationIssues:[]}:{},name:String(u.name||"").trim()||"Agent",modelProvider:"taskforce_hq",providerKey:String(u.providerKey||"").trim(),modelKey:String(u.modelKey||"").trim(),modelTier:String(u.modelTier||"").trim(),systemPrompt:typeof u.systemPrompt=="string"?u.systemPrompt:"",enabled:u.enabled!==!1,createdByUserId:typeof u.createdByUserId=="string"&&u.createdByUserId.trim().length>0?u.createdByUserId.trim():null,updatedByUserId:typeof u.updatedByUserId=="string"&&u.updatedByUserId.trim().length>0?u.updatedByUserId.trim():null,createdAt:String(u.createdAt||"").trim(),updatedAt:String(u.updatedAt||u.createdAt||"").trim(),deletedAt:typeof u.deletedAt=="string"&&u.deletedAt.trim().length>0?u.deletedAt.trim():null}})).filter(u=>u.agent.id.length>0&&u.agent.workspaceId.length>0).filter(u=>nt?!0:Xt.get(u.agent.id)!==(u.agent.deletedAt||u.agent.updatedAt)),ur=Array.isArray(e.agentRoles)?e.agentRoles:[];ur.forEach(u=>{const Pt=String(u?.id||"").trim();if(!Pt)return;const pr=`agent-role:${Pt}`;String(u?.deletedAt||"").trim()||Bt.add(pr),Qt.set(pr,String(u?.deletedAt||u?.updatedAt||u?.createdAt||"").trim())});const je=ur.map(u=>({op:"agent-role-upsert",role:{id:String(u.id||"").trim(),tenantId:String(u.tenantId||"").trim()||void 0,workspaceId:String(u.workspaceId||"").trim(),lifecycleStatus:u.lifecycleStatus==="retired"?"retired":"active",currentRevision:Number(u.currentRevision)||0,currentContentHash:String(u.currentContentHash||"").trim(),definition:u.definition,revisions:Array.isArray(u.revisions)?u.revisions:[],createdByActorId:typeof u.createdByActorId=="string"&&u.createdByActorId.trim()||null,updatedByActorId:typeof u.updatedByActorId=="string"&&u.updatedByActorId.trim()||null,createdAt:String(u.createdAt||"").trim(),updatedAt:String(u.updatedAt||u.createdAt||"").trim(),retiredAt:typeof u.retiredAt=="string"&&u.retiredAt.trim()||null,deletedAt:typeof u.deletedAt=="string"&&u.deletedAt.trim()||null}})).filter(u=>u.role.id.length>0&&u.role.workspaceId.length>0&&u.role.currentRevision>0&&u.role.currentContentHash.length>0).filter(u=>{if(nt)return!0;const Pt=`agent-role:${u.role.id}`;return Xt.get(Pt)!==(u.role.deletedAt||u.role.updatedAt)}),ot=Array.isArray(e.taskforceAgentSkills)?e.taskforceAgentSkills:[],pt=new Set(ot.map(u=>String(u?.id||"").trim()).filter(u=>u.length>0)),Ve=new Map(ot.map(u=>[String(u?.id||"").trim(),String(u?.updatedAt||u?.createdAt||"").trim()]).filter(([u])=>u.length>0)),lt=e.lastPushedTaskforceAgentSkillWatermarks,It=!lt||lt.size===0,wt=ot.map(u=>({op:"taskforce-agent-skill-upsert",skill:{...u,id:String(u.id||"").trim(),tenantId:String(u.tenantId||"").trim()||void 0,workspaceId:String(u.workspaceId||"").trim(),revision:Number(u.revision),contentHash:String(u.contentHash||"").trim(),createdAt:String(u.createdAt||"").trim(),updatedAt:String(u.updatedAt||u.createdAt||"").trim()}})).filter(u=>u.skill.id.length>0&&u.skill.workspaceId.length>0&&Number.isInteger(u.skill.revision)&&u.skill.revision>0).filter(u=>It?!0:lt.get(u.skill.id)!==u.skill.updatedAt),$t=Array.isArray(e.agentConversations)?e.agentConversations:[],Yt=new Set($t.filter(u=>String(u?.deletedAt||"").trim().length===0).map(u=>String(u?.id||"").trim()).filter(u=>u.length>0)),qt=new Map($t.map(u=>[String(u?.id||"").trim(),String(u?.deletedAt||u?.updatedAt||u?.createdAt||"").trim()]).filter(([u])=>u.length>0)),er=e.lastPushedAgentConversationWatermarks,_t=!er||er.size===0,Dt=$t.map(u=>({op:"agent-conversation-upsert",conversation:{id:String(u.id||"").trim(),tenantId:String(u.tenantId||"").trim()||void 0,workspaceId:String(u.workspaceId||"").trim(),agentId:String(u.agentId||"").trim(),taskId:typeof u.taskId=="string"&&u.taskId.trim().length>0?u.taskId.trim():null,title:String(u.title||"Agent chat").trim()||"Agent chat",messages:qR(u.messages),modelProvider:typeof u.modelProvider=="string"&&u.modelProvider.trim().length>0?u.modelProvider.trim():null,modelId:typeof u.modelId=="string"&&u.modelId.trim().length>0?u.modelId.trim():null,usage:u.usage&&typeof u.usage=="object"?u.usage:null,latencyMs:Number.isFinite(Number(u.latencyMs))?Number(u.latencyMs):null,createdByUserId:typeof u.createdByUserId=="string"&&u.createdByUserId.trim().length>0?u.createdByUserId.trim():null,updatedByUserId:typeof u.updatedByUserId=="string"&&u.updatedByUserId.trim().length>0?u.updatedByUserId.trim():null,createdAt:String(u.createdAt||"").trim(),updatedAt:String(u.updatedAt||u.createdAt||"").trim(),deletedAt:typeof u.deletedAt=="string"&&u.deletedAt.trim().length>0?u.deletedAt.trim():null}})).filter(u=>u.conversation.id.length>0&&u.conversation.workspaceId.length>0&&u.conversation.agentId.length>0).filter(u=>_t?!0:er.get(u.conversation.id)!==(u.conversation.deletedAt||u.conversation.updatedAt)),Tt=hj(Array.isArray(e.taskEvents)?e.taskEvents:[]),Xr=new Map(Tt.map(u=>[String(u?.id||"").trim(),String(u?.createdAt||"").trim()]).filter(([u])=>u.length>0)),Rr=e.lastPushedTaskEventWatermarks,la=!Rr||Rr.size===0,sa=Tt.map(u=>{const Pt=u.entityType==="initiative"||u.entityType==="workstream"?u.entityType:"task",pr=String(u.entityId||u.taskId||"").trim(),Yr={id:String(u.id||"").trim(),workspaceId:String(u.workspaceId||"").trim(),entityType:Pt,entityId:pr,taskId:Pt==="task"?String(u.taskId||pr).trim():void 0,action:String(u.action||"").trim(),actor:String(u.actor||"system").trim()||"system",actorType:u.actorType==="ai"||u.actorType==="human"||u.actorType==="system"?u.actorType:"system",details:u.details&&typeof u.details=="object"&&!Array.isArray(u.details)?u.details:{},createdAt:String(u.createdAt||"").trim()};return Pt==="task"?{op:"task-event-upsert",event:{...Yr,entityType:"task",taskId:String(Yr.taskId||pr).trim()}}:{op:"entity-event-upsert",event:{...Yr,entityType:Pt,taskId:void 0}}}).filter(u=>u.event.id.length>0&&u.event.entityId.length>0&&u.event.workspaceId.length>0&&u.event.action.length>0&&Number.isFinite(Date.parse(u.event.createdAt))).filter(u=>la?!0:Rr.get(u.event.id)!==u.event.createdAt),ea=wC({taxonomyState:e.taxonomyState,taxonomies:e.taxonomies}),Ur=ea.length>0&&e.lastPushedTaxonomyChangeKey!==ea,Ft=[...z,...ve,...te,...Ur&&e.taxonomyState&&typeof e.taxonomyState=="object"?[{op:"taxonomy-upsert",taxonomyState:e.taxonomyState,updatedAt:t}]:Ur&&Array.isArray(e.taxonomies)?[{op:"taxonomy-upsert",taxonomies:e.taxonomies,updatedAt:t}]:[],...Ae,...K,...Array.from(Ne).map(u=>({op:"document-delete",path:u,deletedAt:t})),...se,...Array.from(we).map(u=>({op:"asset-delete",path:u,deletedAt:t})),...P,..._e.map(u=>({op:"document-review-session-delete",sessionId:u.sessionId,deletedAt:u.deletedAt})),...Xe,...Te.map(u=>({op:"document-review-comment-delete",commentId:u.commentId,deletedAt:u.deletedAt,deletedByActorId:u.deletedByActorId})),...$,...Ge.map(u=>({op:"annotated-attachment-session-delete",sessionId:u.sessionId,deletedAt:u.deletedAt})),...Mt,...je,...wt,...Dt,...sa,...b,...C,...v.filter(u=>!u.relationship.deletedAt),...v.filter(u=>!!u.relationship.deletedAt),...Array.from(E).map(u=>i(u))],ft=e.baselineResetReason??null,Rt=u=>{const Pt=u.upsertCount+(u.deleteCount||0);if(u.currentCount===0&&Pt===0)return{mode:"none",reason:null,currentCount:0,baselineCount:u.baselineCount,changeCount:Pt};if(u.alwaysFull)return{mode:Pt>0?"send-all":"none",reason:Pt>0?"full-state-domain":null,currentCount:u.currentCount,baselineCount:u.baselineCount,changeCount:Pt};const pr=u.baselineCount===0&&u.currentCount>0&&u.upsertCount>=u.currentCount;return{mode:pr?"send-all":"delta",reason:pr?ft||"missing-baseline":null,currentCount:u.currentCount,baselineCount:u.baselineCount,changeCount:Pt}},_r=Ft.reduce((u,Pt)=>{const pr=String(Pt.op||"").trim();return u[pr]=(u[pr]||0)+1,u},{});return{changes:Ft,currentTaskIds:new Set(Array.from(S).filter(u=>!r.has(u))),currentTaskWatermarks:new Map(Array.from(g.entries()).filter(([u])=>!r.has(u))),currentTaskChangeKeys:new Map(Array.from(h.entries()).filter(([u])=>!r.has(u))),currentTaskRelationshipChangeKeys:N,currentTaxonomyChangeKey:ea,deleteTaskIds:E,currentInitiativeIds:V,currentInitiativeWatermarks:_,currentWorkstreamIds:M,currentWorkstreamWatermarks:O,currentAiProfileIds:ce,currentAiProfileWatermarks:Le,currentAiProfileChangeKeys:Ie,currentDocumentPaths:ye,deleteDocumentPaths:Ne,currentDocumentWatermarks:ae,currentAssetPaths:Re,deleteAssetPaths:we,currentAssetWatermarks:ie,currentDocumentReviewSessionIds:ne,deleteDocumentReviewSessionIds:ke,currentDocumentReviewSessionWatermarks:pe,currentDocumentReviewCommentIds:at,deleteDocumentReviewCommentIds:fe,currentDocumentReviewCommentWatermarks:We,currentAnnotatedAttachmentSessionIds:rt,deleteAnnotatedAttachmentSessionIds:At,currentAnnotatedAttachmentSessionWatermarks:xe,currentTaskforceAgentIds:Bt,currentTaskforceAgentWatermarks:Qt,currentTaskforceAgentSkillIds:pt,currentTaskforceAgentSkillWatermarks:Ve,currentAgentConversationIds:Yt,currentAgentConversationWatermarks:qt,currentTaskEventWatermarks:Xr,pushedWatermarks:y,pushedTaskChangeKeys:k,deltaDiagnostics:{totalChanges:Ft.length,byOp:_r,baselineResetReason:ft,domains:{tasks:Rt({currentCount:S.size,baselineCount:l?.size||0,upsertCount:b.length+C.length,deleteCount:E.size}),taskRelationships:Rt({currentCount:N.size,baselineCount:x?.size||0,upsertCount:_r["task-relationship-upsert"]||0,deleteCount:_r["task-relationship-delete"]||0}),initiatives:Rt({currentCount:V.size,baselineCount:j?.size||0,upsertCount:z.length}),workstreams:Rt({currentCount:M.size,baselineCount:Z?.size||0,upsertCount:ve.length}),aiProfiles:Rt({currentCount:ce.size,baselineCount:Ye?.size||0,upsertCount:Ae.length}),documents:Rt({currentCount:ye.size,baselineCount:q?.size||0,upsertCount:K.length,deleteCount:Ne.size}),assets:Rt({currentCount:Re.size,baselineCount:Q?.size||0,upsertCount:se.length,deleteCount:we.size}),documentReviewSessions:Rt({currentCount:ne.size,baselineCount:le?.size||0,upsertCount:P.length,deleteCount:ke.size}),documentReviewComments:Rt({currentCount:at.size,baselineCount:G?.size||0,upsertCount:Xe.length,deleteCount:fe.size}),annotatedAttachmentSessions:Rt({currentCount:rt.size,baselineCount:St?.size||0,upsertCount:$.length,deleteCount:At.size}),taskforceAgents:Rt({currentCount:Bt.size,baselineCount:Xt?.size||0,upsertCount:Mt.length+je.length}),taskforceAgentSkills:Rt({currentCount:pt.size,baselineCount:lt?.size||0,upsertCount:wt.length}),agentConversations:Rt({currentCount:Yt.size,baselineCount:er?.size||0,upsertCount:Dt.length}),taskEvents:Rt({currentCount:Xr.size,baselineCount:Rr?.size||0,upsertCount:sa.length}),taxonomy:Rt({currentCount:e.taxonomyState&&typeof e.taxonomyState=="object"||Array.isArray(e.taxonomies)?1:0,baselineCount:e.lastPushedTaxonomyChangeKey?1:0,upsertCount:_r["taxonomy-upsert"]||0})}}}}function yj(e){const t=(e.tasks||[]).map(c=>`${c.id}:${c.updatedAt||c.createdAt||""}:${c.status}`).sort(),r=(e.archivedTasks||[]).map(c=>`${c.id}:${c.updatedAt||c.createdAt||""}:${c.status}`).sort(),n=e.pendingDeletedTaskIds?Array.from(e.pendingDeletedTaskIds).sort():[],s=(e.taskRelationships||[]).filter(c=>String(c?.id||"").trim().length>0&&Number.isFinite(Date.parse(String(c?.updatedAt||"")))).map(c=>({id:String(c.id||"").trim(),changeKey:Uv(c)})).sort((c,d)=>c.id.localeCompare(d.id)||c.changeKey.localeCompare(d.changeKey)),i=(e.initiatives||[]).map(c=>({id:String(c.id||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),title:String(c.title||"").trim(),ownerId:typeof c.ownerId=="string"?c.ownerId.trim():"",comments:Bf(c.comments)||[],attachments:Wf(c.attachments)||[],isArchived:!!c.isArchived,icon:c.icon??null,color:c.color??null,identityUpdatedAt:String(c.identityUpdatedAt||"").trim()})).filter(c=>c.id.length>0).sort((c,d)=>c.id.localeCompare(d.id)),l=(e.workstreams||[]).map(c=>({id:String(c.id||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),initiativeId:typeof c.initiativeId=="string"?c.initiativeId.trim():"",title:String(c.title||"").trim(),ownerId:typeof c.ownerId=="string"?c.ownerId.trim():"",comments:Bf(c.comments)||[],attachments:Wf(c.attachments)||[],isArchived:!!c.isArchived,icon:c.icon??null,color:c.color??null,identityUpdatedAt:String(c.identityUpdatedAt||"").trim()})).filter(c=>c.id.length>0).sort((c,d)=>c.id.localeCompare(d.id));return JSON.stringify({workspaceId:e.workspaceId,initiatives:i,workstreams:l,taskRelationships:s,taxonomyState:e.taxonomyState&&typeof e.taxonomyState=="object"?e.taxonomyState:null,taxonomies:Array.isArray(e.taxonomies)?e.taxonomies:[],aiProfiles:Array.isArray(e.aiProfiles)?e.aiProfiles.map(c=>({id:String(c.id||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),name:String(c.name||"").trim(),username:String(c.username||"").trim(),archivedAt:String(c.archivedAt||"").trim(),archivedReason:String(c.archivedReason||"").trim(),mergedIntoProfileId:String(c.mergedIntoProfileId||"").trim(),rosterStateUpdatedAt:String(c.rosterStateUpdatedAt||"").trim()})).filter(c=>c.id.length>0).sort((c,d)=>c.id.localeCompare(d.id)):[],taskEvents:Array.isArray(e.taskEvents)?e.taskEvents.map(c=>({id:String(c.id||"").trim(),taskId:String(c.taskId||"").trim(),action:String(c.action||"").trim(),actor:String(c.actor||"").trim(),actorType:c.actorType==="ai"||c.actorType==="human"||c.actorType==="system"?c.actorType:"system",createdAt:String(c.createdAt||"").trim()})).filter(c=>c.id.length>0&&c.taskId.length>0).sort((c,d)=>c.id.localeCompare(d.id)):[],documents:Array.isArray(e.documents)?e.documents.map(c=>({path:String(c.path||"").trim(),updatedAt:String(c.updatedAt||"").trim(),length:typeof c.content=="string"?c.content.length:0})).filter(c=>c.path.length>0).sort((c,d)=>c.path.localeCompare(d.path)):[],assets:Array.isArray(e.assets)?e.assets.map(c=>({path:String(c.path||"").trim(),updatedAt:String(c.updatedAt||"").trim(),length:typeof c.contentBase64=="string"?c.contentBase64.length:0,kind:c.kind==="image"?"image":"file"})).filter(c=>c.path.length>0).sort((c,d)=>c.path.localeCompare(d.path)):[],documentReviewSessions:Array.isArray(e.documentReviewSessions)?e.documentReviewSessions.map(c=>({id:String(c.id||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),assetId:String(c.assetId||"").trim(),status:c.status==="resolved"?"resolved":"open",deletedAt:String(c.deletedAt||"").trim(),commentCount:Array.isArray(c.comments)?c.comments.length:0})).filter(c=>c.id.length>0).sort((c,d)=>c.id.localeCompare(d.id)):[],documentReviewComments:Array.isArray(e.documentReviewComments)?e.documentReviewComments.map(c=>({id:String(c.id||"").trim(),sessionId:String(c.sessionId||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),deletedAt:String(c.deletedAt||"").trim(),bodyLength:String(c.body||"").length})).filter(c=>c.id.length>0).sort((c,d)=>c.id.localeCompare(d.id)):[],annotatedAttachmentSessions:Array.isArray(e.annotatedAttachmentSessions)?e.annotatedAttachmentSessions.map(c=>({id:String(c.id||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),taskId:String(c.taskId||"").trim(),baseImageAssetId:String(c.baseImageAssetId||"").trim(),deletedAt:String(c.deletedAt||"").trim(),annotationCount:Array.isArray(c.annotations)?c.annotations.length:0})).filter(c=>c.id.length>0).sort((c,d)=>c.id.localeCompare(d.id)):[],taskforceAgents:Array.isArray(e.taskforceAgents)?e.taskforceAgents.map(c=>({id:String(c.id||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),deletedAt:String(c.deletedAt||"").trim(),definitionRevision:Number(c.definitionRevision)||0,definitionHash:String(c.definitionHash||"").trim(),lifecycleStatus:String(c.lifecycleStatus||"").trim(),managedProfileId:String(c.managedProfileId||"").trim(),name:String(c.name||"").trim(),modelTier:String(c.modelTier||"").trim(),providerKey:String(c.providerKey||"").trim(),modelKey:String(c.modelKey||"").trim(),enabled:c.enabled!==!1})).filter(c=>c.id.length>0).sort((c,d)=>c.id.localeCompare(d.id)):[],agentRoles:Array.isArray(e.agentRoles)?e.agentRoles.map(c=>({id:String(c.id||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),deletedAt:String(c.deletedAt||"").trim(),lifecycleStatus:c.lifecycleStatus,currentRevision:Number(c.currentRevision)||0,currentContentHash:String(c.currentContentHash||"").trim(),revisionCount:Array.isArray(c.revisions)?c.revisions.length:0})).filter(c=>c.id.length>0).sort((c,d)=>c.id.localeCompare(d.id)):[],taskforceAgentSkills:Array.isArray(e.taskforceAgentSkills)?e.taskforceAgentSkills.map(c=>({id:String(c.id||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),revision:Number(c.revision)||0,contentHash:String(c.contentHash||"").trim(),lifecycleStatus:String(c.lifecycleStatus||"").trim(),revisionCount:Array.isArray(c.revisions)?c.revisions.length:0})).filter(c=>c.id.length>0).sort((c,d)=>c.id.localeCompare(d.id)):[],agentConversations:Array.isArray(e.agentConversations)?e.agentConversations.map(c=>({id:String(c.id||"").trim(),agentId:String(c.agentId||"").trim(),taskId:String(c.taskId||"").trim(),updatedAt:String(c.updatedAt||c.createdAt||"").trim(),deletedAt:String(c.deletedAt||"").trim(),messageCount:Array.isArray(c.messages)?c.messages.length:0,modelId:String(c.modelId||"").trim()})).filter(c=>c.id.length>0).sort((c,d)=>c.id.localeCompare(d.id)):[],active:t,archived:r,pendingDeletes:n})}function Bk(e,t,r=[],n=[]){const s=new Map;for(const i of[...e||[],...t||[]]){const l=Array.isArray(i?.taskEvents)?i.taskEvents:[];for(const c of l){const d=String(c?.id||"").trim(),f=String(c?.taskId||i?.id||"").trim(),p=String(c?.workspaceId||"").trim(),g=String(c?.createdAt||"").trim();if(!d||!f||!p||!g)continue;const h={id:d,workspaceId:p,entityType:"task",entityId:f,taskId:f,action:String(c?.action||"").trim(),actor:String(c?.actor||"system").trim()||"system",actorType:c?.actorType==="ai"||c?.actorType==="human"||c?.actorType==="system"?c.actorType:"system",details:c?.details,createdAt:g},y=s.get(d);(!y||h.createdAt>y.createdAt)&&s.set(d,h)}}for(const i of r||[]){const l=Array.isArray(i?.entityEvents)?i.entityEvents:[];for(const c of l){const d=String(c?.id||"").trim(),f=String(c?.entityId||i?.id||"").trim(),p=String(c?.workspaceId||"").trim(),g=String(c?.createdAt||"").trim();if(!d||!f||!p||!g)continue;const h={id:d,workspaceId:p,entityType:"initiative",entityId:f,action:String(c?.action||"").trim(),actor:String(c?.actor||"system").trim()||"system",actorType:c?.actorType==="ai"||c?.actorType==="human"||c?.actorType==="system"?c.actorType:"system",details:c?.details,createdAt:g},y=s.get(d);(!y||h.createdAt>y.createdAt)&&s.set(d,h)}}for(const i of n||[]){const l=Array.isArray(i?.entityEvents)?i.entityEvents:[];for(const c of l){const d=String(c?.id||"").trim(),f=String(c?.entityId||i?.id||"").trim(),p=String(c?.workspaceId||"").trim(),g=String(c?.createdAt||"").trim();if(!d||!f||!p||!g)continue;const h={id:d,workspaceId:p,entityType:"workstream",entityId:f,action:String(c?.action||"").trim(),actor:String(c?.actor||"system").trim()||"system",actorType:c?.actorType==="ai"||c?.actorType==="human"||c?.actorType==="system"?c.actorType:"system",details:c?.details,createdAt:g},y=s.get(d);(!y||h.createdAt>y.createdAt)&&s.set(d,h)}}return Array.from(s.values()).sort((i,l)=>i.createdAt!==l.createdAt?i.createdAt.localeCompare(l.createdAt):i.id.localeCompare(l.id))}function Gn(e){return Object.freeze(structuredClone(Array.from(e||[])))}function Pb(e,t){return new Set(e?Array.from(e):t)}function kj(e){const t=Gn(e.tasks),r=Gn(e.archivedTasks),n=Gn(e.deletedTasks),s=Gn(e.initiatives),i=Gn(e.workstreams),l=Gn(e.documents),c=Gn(e.assets),d=e.pendingDeletedTaskIds?new Set(e.pendingDeletedTaskIds):new Set,f=e.pendingDeletedTaskWatermarks?new Map(e.pendingDeletedTaskWatermarks):new Map;if(!e.pendingDeletedTaskIds&&!e.pendingDeletedTaskWatermarks)for(const g of n){const h=String(g?.taskId||"").trim(),y=String(g?.deletedAt||"").trim();h&&(d.add(h),Number.isFinite(Date.parse(y))&&f.set(h,y))}const p=e.taskEvents?Gn(e.taskEvents):Object.freeze(Bk(t,r,s,i));return Object.freeze({workspaceId:String(e.workspaceId||"").trim(),tasks:t,archivedTasks:r,deletedTasks:n,pendingDeletedTaskIds:d,pendingDeletedTaskWatermarks:f,taskRelationships:Gn(e.taskRelationships),initiatives:s,workstreams:i,taxonomies:Gn(e.taxonomies),taxonomyState:e.taxonomyState?structuredClone(e.taxonomyState):void 0,aiProfiles:Gn(e.aiProfiles),documents:l,assets:c,currentDocumentPaths:Pb(e.currentDocumentPaths,l.map(g=>g.path)),currentAssetPaths:Pb(e.currentAssetPaths,c.map(g=>g.path)),documentReviewSessions:Gn(e.documentReviewSessions),documentReviewComments:Gn(e.documentReviewComments),annotatedAttachmentSessions:Gn(e.annotatedAttachmentSessions),taskforceAgents:Gn(e.taskforceAgents),agentRoles:Gn(e.agentRoles),taskforceAgentSkills:Gn(e.taskforceAgentSkills),agentConversations:Gn(e.agentConversations),taskEvents:p})}function lo(e){return new Set(e)}function ds(e){return new Map(e)}function vj(e,t){return new Set(HR(Array.from(e),t,r=>LR(String(r||"").trim())).keys())}function wj(e){const{snapshot:t,baseline:r}=e,n=e.forceAllAiProfiles===!0,s=n?vj(t.aiProfiles,t.workspaceId):new Set,i=lo(r.lastPushedAssetPaths),l=ds(r.lastPushedAssetWatermarks),c=lo(r.lastPushedDocumentPaths),d=ds(r.lastPushedDocumentWatermarks);for(const g of[...s,...e.forceAssetPaths||[]])i.delete(g),l.delete(g);for(const g of e.forceDocumentPaths||[])c.delete(g),d.delete(g);const f=structuredClone(gj({tasks:Array.from(t.tasks),archivedTasks:Array.from(t.archivedTasks),taskRelationships:Array.from(t.taskRelationships),taskEvents:Array.from(t.taskEvents),lastPushedTaskIds:lo(r.lastPushedTaskIds),pendingDeletedTaskIds:lo(t.pendingDeletedTaskIds),pendingDeletedTaskWatermarks:ds(t.pendingDeletedTaskWatermarks),deletedTasks:Array.from(t.deletedTasks),initiatives:Array.from(t.initiatives),workstreams:Array.from(t.workstreams),taxonomies:Array.from(t.taxonomies),taxonomyState:t.taxonomyState,lastPushedInitiativeIds:lo(r.lastPushedInitiativeIds),lastPushedInitiativeWatermarks:ds(r.lastPushedInitiativeWatermarks),lastPushedWorkstreamIds:lo(r.lastPushedWorkstreamIds),lastPushedWorkstreamWatermarks:ds(r.lastPushedWorkstreamWatermarks),aiProfiles:Array.from(t.aiProfiles),lastPushedAiProfileIds:n?new Set:lo(r.lastPushedAiProfileIds),lastPushedAiProfileWatermarks:n?new Map:ds(r.lastPushedAiProfileWatermarks),lastPushedAiProfileChangeKeys:n?new Map:ds(r.lastPushedAiProfileChangeKeys),documents:Array.from(t.documents),assets:Array.from(t.assets),currentDocumentPaths:t.currentDocumentPaths,currentAssetPaths:t.currentAssetPaths,documentReviewSessions:Array.from(t.documentReviewSessions),documentReviewComments:Array.from(t.documentReviewComments),annotatedAttachmentSessions:Array.from(t.annotatedAttachmentSessions),taskforceAgents:Array.from(t.taskforceAgents),agentRoles:Array.from(t.agentRoles),taskforceAgentSkills:Array.from(t.taskforceAgentSkills),agentConversations:Array.from(t.agentConversations),lastPushedDocumentPaths:c,lastPushedDocumentWatermarks:d,lastPushedAssetPaths:i,lastPushedAssetWatermarks:l,lastPushedDocumentReviewSessionIds:lo(r.lastPushedDocumentReviewSessionIds),lastPushedDocumentReviewSessionWatermarks:ds(r.lastPushedDocumentReviewSessionWatermarks),lastPushedDocumentReviewCommentIds:lo(r.lastPushedDocumentReviewCommentIds),lastPushedDocumentReviewCommentWatermarks:ds(r.lastPushedDocumentReviewCommentWatermarks),lastPushedAnnotatedAttachmentSessionIds:lo(r.lastPushedAnnotatedAttachmentSessionIds),lastPushedAnnotatedAttachmentSessionWatermarks:ds(r.lastPushedAnnotatedAttachmentSessionWatermarks),lastPushedTaskforceAgentIds:n?new Set:lo(r.lastPushedTaskforceAgentIds),lastPushedTaskforceAgentWatermarks:n?new Map:ds(r.lastPushedTaskforceAgentWatermarks),lastPushedTaskforceAgentSkillIds:n?new Set:lo(r.lastPushedTaskforceAgentSkillIds),lastPushedTaskforceAgentSkillWatermarks:n?new Map:ds(r.lastPushedTaskforceAgentSkillWatermarks),lastPushedAgentConversationIds:lo(r.lastPushedAgentConversationIds),lastPushedAgentConversationWatermarks:ds(r.lastPushedAgentConversationWatermarks),lastPushedTaskEventWatermarks:ds(r.lastPushedTaskEventWatermarks),baselineResetReason:r.baselineResetReason,lastPushedWatermarks:ds(r.lastPushedWatermarks),lastPushedTaskChangeKeys:ds(r.lastPushedTaskChangeKeys),lastPushedTaskRelationshipChangeKeys:ds(r.lastPushedTaskRelationshipChangeKeys),lastPushedTaxonomyChangeKey:r.lastPushedTaxonomyChangeKey})),p=bC(t);return Object.freeze({snapshot:t,signature:p,payload:f})}function bC(e){return yj({workspaceId:e.workspaceId,tasks:Array.from(e.tasks),archivedTasks:Array.from(e.archivedTasks),taskRelationships:Array.from(e.taskRelationships),taskEvents:Array.from(e.taskEvents),pendingDeletedTaskIds:lo(e.pendingDeletedTaskIds),initiatives:Array.from(e.initiatives),workstreams:Array.from(e.workstreams),taxonomies:Array.from(e.taxonomies),taxonomyState:e.taxonomyState,aiProfiles:Array.from(e.aiProfiles),documents:Array.from(e.documents),assets:Array.from(e.assets),documentReviewSessions:Array.from(e.documentReviewSessions),documentReviewComments:Array.from(e.documentReviewComments),annotatedAttachmentSessions:Array.from(e.annotatedAttachmentSessions),taskforceAgents:Array.from(e.taskforceAgents),agentRoles:Array.from(e.agentRoles),taskforceAgentSkills:Array.from(e.taskforceAgentSkills),agentConversations:Array.from(e.agentConversations)})}function SC(e){return ml(e)}function Xi(e){return Ha(e)}function bj(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e,s=String(n.id||"").trim(),i=String(n.workspaceId||t||"").trim(),l=Number(n.currentRevision),c=Number.isInteger(l)&&l>0?l:0,d=String(n.currentContentHash||"").trim(),f=n.lifecycleStatus;return!s||!i||!c||!d||f!=="active"&&f!=="retired"||t&&i!==t?null:{id:s,tenantId:SC(n.tenantId),workspaceId:i,lifecycleStatus:f,currentRevision:c,currentContentHash:d,definition:n.definition,revisions:Array.isArray(n.revisions)?n.revisions.map(p=>({roleId:String(p?.roleId||s).trim()||s,revision:Number.isInteger(Number(p?.revision))&&Number(p?.revision)>0?Number(p.revision):0,definition:p?.definition,contentHash:String(p?.contentHash||"").trim(),createdByActorId:Xi(p?.createdByActorId),createdAt:String(p?.createdAt||r||"").trim()})):[],createdByActorId:Xi(n.createdByActorId),updatedByActorId:Xi(n.updatedByActorId),createdAt:String(n.createdAt||r||"").trim(),updatedAt:String(n.updatedAt||r||n.createdAt||"").trim(),retiredAt:Xi(n.retiredAt),deletedAt:Xi(n.deletedAt)}}function Sj(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e,s=String(n.id||"").trim(),i=String(n.workspaceId||t||"").trim(),l=String(n.lifecycleStatus||"").trim(),c=Number(n.revision);return!s||!i||!Number.isInteger(c)||c<1||t&&i!==t||l!=="active"&&l!=="retired"||!Array.isArray(n.revisions)?null:{id:s,tenantId:SC(n.tenantId),workspaceId:i,lifecycleStatus:l,definition:n.definition,revision:c,contentHash:String(n.contentHash||"").trim(),revisions:n.revisions.map(d=>{if(!d||typeof d!="object"||Array.isArray(d))return null;const f=d,p=Number(f.revision);return!Number.isInteger(p)||p<1?null:{revision:p,contentHash:String(f.contentHash||"").trim(),definition:f.definition,createdByActorId:Xi(f.createdByActorId),createdAt:String(f.createdAt||r||"").trim()}}).filter(d=>d!==null),createdByActorId:Xi(n.createdByActorId),updatedByActorId:Xi(n.updatedByActorId),createdAt:String(n.createdAt||r||"").trim(),updatedAt:String(n.updatedAt||r||n.createdAt||"").trim(),retiredAt:Xi(n.retiredAt),retiredByActorId:Xi(n.retiredByActorId)}}function Eb(e){if(!Array.isArray(e))return;const t=e.filter(r=>typeof r=="string"&&r.trim().length>0).map(r=>r.trim());return t.length>0?t:void 0}function AC(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return Array.isArray(t.categories)||Array.isArray(t.types)||Array.isArray(t.priorities)||Array.isArray(t.taxonomies)||!!t.displayLabels&&typeof t.displayLabels=="object"&&!Array.isArray(t.displayLabels)}function Aj(e){const t=e||{};return{categories:Array.isArray(t.categories)?t.categories.map(n=>typeof n=="string"?{value:n.toLowerCase().replace(/\s+/g,"-"),label:n}:n):[],types:Array.isArray(t.types)?t.types.map(n=>({...U0(n.value),...n,aliases:Array.isArray(n.aliases)?n.aliases.filter(i=>typeof i=="string"&&i.trim().length>0).map(i=>i.trim()):void 0,status:n.status==="retired"?"retired":"active"})):[],priorities:Array.isArray(t.priorities)?t.priorities:[],taxonomies:Array.isArray(t.taxonomies)?t.taxonomies.map(n=>({...n,aliases:Eb(n.aliases),options:Array.isArray(n.options)?n.options.map(s=>({...s,aliases:Eb(s.aliases),status:s.status==="retired"?"retired":"active"})):[],status:n.status==="retired"?"retired":"active",formEnabled:n.formEnabled!==!1,filterEnabled:n.filterEnabled!==!1,sortEnabled:n.sortEnabled===!0})):[],displayLabels:{category:typeof t.displayLabels?.category=="string"&&t.displayLabels.category.trim().length>0?t.displayLabels.category.trim():void 0,type:typeof t.displayLabels?.type=="string"&&t.displayLabels.type.trim().length>0?t.displayLabels.type.trim():void 0,priority:typeof t.displayLabels?.priority=="string"&&t.displayLabels.priority.trim().length>0?t.displayLabels.priority.trim():void 0}}}function Oh(){return{version:2,revision:null,enabled:!1,phase:"idle",setupIntent:null,startupFullReconcileCompletedAt:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null,lastErrorMessage:null,pushBaseline:null}}function Nb(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,r=t.counter,n=typeof t.writerId=="string"?t.writerId.trim():"";return!Number.isSafeInteger(r)||Number(r)<1||!n||n.length>200?null:{counter:Number(r),writerId:n}}function Cj(e,t){return e?t?e.counter!==t.counter?e.counter<t.counter?-1:1:e.writerId===t.writerId?0:e.writerId<t.writerId?-1:1:1:t?-1:0}function Ij(e,t){const r=String(t||"").trim();if(!r)throw new Error("Workspace sync state revision writer is required");if(r.length>200)throw new Error("Workspace sync state revision writer is too long");if(e?.counter===Number.MAX_SAFE_INTEGER)throw new Error("Workspace sync state revision counter is exhausted");return{counter:(e?.counter||0)+1,writerId:r}}function qi(e){const t=String(e||"").trim();return t.length>0?t:null}function Mb(e){return String(e||"").trim().toLowerCase()==="attach-cloud-import"?"attach-cloud-import":null}function _j(e){if(!Array.isArray(e)||e.length<2)return null;const t=String(e[0]||"").trim(),r=String(e[1]||"").trim();return!t||!r?null:[t,r]}function Tj(e){return Array.isArray(e)?e.map(t=>String(t||"").trim()).filter(t=>t.length>0):[]}function Db(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,r=n=>Array.isArray(t[n])?t[n].map(s=>_j(s)).filter(s=>Array.isArray(s)):[];return{taskIds:Tj(t.taskIds),taskWatermarks:r("taskWatermarks"),taskChangeKeys:r("taskChangeKeys"),taskRelationshipChangeKeys:r("taskRelationshipChangeKeys"),initiativeWatermarks:r("initiativeWatermarks"),workstreamWatermarks:r("workstreamWatermarks"),aiProfileWatermarks:r("aiProfileWatermarks"),aiProfileChangeKeys:r("aiProfileChangeKeys"),documentWatermarks:r("documentWatermarks"),assetWatermarks:r("assetWatermarks"),documentReviewSessionWatermarks:r("documentReviewSessionWatermarks"),documentReviewCommentWatermarks:r("documentReviewCommentWatermarks"),annotatedAttachmentSessionWatermarks:r("annotatedAttachmentSessionWatermarks"),taskEventWatermarks:r("taskEventWatermarks"),taxonomyStateFingerprint:String(t.taxonomyStateFingerprint||"").trim(),taxonomyChangeKey:String(t.taxonomyChangeKey||"")}}function xj(e,t){if(!!!(e.enabled??e.cloudSyncEnabled))return"idle";const n=String(e.phase||"").trim().toLowerCase();if(n==="idle"||n==="provision-local"||n==="attach-cloud"||n==="active"||n==="error")return n;const s=String(e.bootstrapMode||"").trim().toLowerCase();if(s==="provision-local"||s==="attach-cloud")return s;const i=String(e.sourceOfTruth||"").trim().toLowerCase();return e.onboardingCompleted?"active":i==="cloud"?t.lastPullAt?"active":"attach-cloud":i==="local"?t.lastPullAt||t.lastPushAt?"active":"provision-local":(t.lastPullAt||t.lastPushAt,"active")}function ek(e){const t=Oh();if(!e||typeof e!="object")return{state:t,changed:!1};const r=e,n=r.lastErrorMessage,s=typeof n=="string"&&n.trim().length>0?n:null,i={version:2,revision:Nb(r.revision),enabled:!!(r.enabled??r.cloudSyncEnabled),phase:"idle",setupIntent:Mb(r.setupIntent),startupFullReconcileCompletedAt:qi(r.startupFullReconcileCompletedAt),pullCursor:qi(r.pullCursor),lastPullAt:qi(r.lastPullAt),lastPushAt:qi(r.lastPushAt),lastSyncedAt:qi(r.lastSyncedAt),lastErrorMessage:s,pushBaseline:Db(r.pushBaseline)};i.phase=xj(r,i),i.enabled||(i.phase="idle",i.pullCursor=null);const c=Number(r.version||0)!==2||JSON.stringify(Nb(r.revision))!==JSON.stringify(i.revision)||!!(r.enabled??r.cloudSyncEnabled)!==i.enabled||String(r.phase||"").trim()!==i.phase||Mb(r.setupIntent)!==i.setupIntent||qi(r.startupFullReconcileCompletedAt)!==i.startupFullReconcileCompletedAt||qi(r.pullCursor)!==i.pullCursor||qi(r.lastPullAt)!==i.lastPullAt||qi(r.lastPushAt)!==i.lastPushAt||qi(r.lastSyncedAt)!==i.lastSyncedAt||s!==i.lastErrorMessage||JSON.stringify(Db(r.pushBaseline))!==JSON.stringify(i.pushBaseline);return{state:i,changed:c}}const Rj="taskforce.sync.lease.v1",jj="taskforce.sync.completed.v1",Pj="taskforce.sync.lease.v1",Ej=2500,Nj=9e3,Mj=()=>!0;function dl(e){const t=String(e||"").trim();return t.length>0&&t.toLowerCase()!=="default"}function Xp(e){const t=String(e||"").trim();return t.length>0?t:null}function tk(e){return`${Rj}.${e}`}function Lb(e,t){return`${jj}.${e}.${t}`}function Dj(e){if(!e)return null;try{const t=JSON.parse(e),r=String(t?.workspaceId||"").trim(),n=String(t?.operation||"").trim(),s=String(t?.completedAt||"").trim();return!r||!Number.isFinite(Date.parse(s))||n!=="pull"&&n!=="push"&&n!=="repair"?null:{workspaceId:r,operation:n,completedAt:s}}catch{return null}}function Lj(e){if(!e)return null;try{const t=JSON.parse(e),r=String(t?.ownerId||"").trim(),n=String(t?.workspaceId||"").trim(),s=String(t?.operation||"").trim(),i=String(t?.heartbeatAt||"").trim(),l=String(t?.expiresAt||"").trim();return!r||!n||!i||!l||s!=="pull"&&s!=="push"&&s!=="repair"?null:{ownerId:r,workspaceId:n,operation:s,heartbeatAt:i,expiresAt:l}}catch{return null}}function Oj(e,t,r,n){return{ownerId:e,workspaceId:t,operation:r,heartbeatAt:new Date(n).toISOString(),expiresAt:new Date(n+Nj).toISOString()}}function Bj(e,t=Date.now()){if(!e)return!0;const r=Date.parse(e.expiresAt);return!Number.isFinite(r)||r<=t}function rk(e,t){const r={...e,...t,version:2,phase:t.phase||e.phase,setupIntent:t.setupIntent===void 0?e.setupIntent??null:t.setupIntent??null,startupFullReconcileCompletedAt:t.startupFullReconcileCompletedAt===void 0?e.startupFullReconcileCompletedAt??null:Xp(t.startupFullReconcileCompletedAt),pullCursor:t.pullCursor===void 0?e.pullCursor:Xp(t.pullCursor),lastPullAt:t.lastPullAt===void 0?e.lastPullAt:Xp(t.lastPullAt),lastPushAt:t.lastPushAt===void 0?e.lastPushAt:Xp(t.lastPushAt),lastSyncedAt:t.lastSyncedAt===void 0?e.lastSyncedAt:Xp(t.lastSyncedAt),lastErrorMessage:t.lastErrorMessage===void 0?e.lastErrorMessage:t.lastErrorMessage??null,pushBaseline:t.pushBaseline===void 0?e.pushBaseline??null:t.pushBaseline??null};return r.enabled||(r.phase="idle",r.setupIntent=null,r.pullCursor=null),r}function Ob(e){return{...e,pushBaseline:null}}function Wj(e){const{currentWorkspaceId:t,setWorkspaceCloudSyncEnabled:r,setWorkspaceSyncPhase:n,setWorkspaceSyncSetupIntent:s,setWorkspaceLastPullAt:i,setWorkspaceLastPushAt:l,setWorkspaceLastErrorMessage:c,isWorkspaceOperationAuthorized:d=Mj}=e,[f,p]=o.useState(null),g=o.useRef(null),h=o.useRef(null),y=o.useRef(0),k=o.useRef(!1),b=o.useRef(!1),C=o.useRef(""),S=o.useRef(""),w=o.useRef(new Set),T=o.useRef(new Set),E=o.useRef(new Map),x=o.useRef(null),N=o.useRef(Oh()),v=o.useRef(""),V=o.useRef(null),_=o.useRef(null),j=o.useRef(null),F=o.useRef(null);if(!v.current){const ie=Date.now().toString(36),Q=Math.random().toString(36).slice(2,10);v.current=`sync-lease-${ie}-${Q}`}const z=o.useCallback(()=>{y.current=0,h.current=null,g.current!==null&&typeof window<"u"&&(window.clearTimeout(g.current),g.current=null),p(null)},[]),M=o.useCallback((ie,Q)=>{if(typeof window>"u"||!d())return;const H=Math.max(1,y.current+1);y.current=H;const se=MR(H),Pe=Number(Q?.minDelayMs),ue=Number.isFinite(Pe)&&Pe>0?Math.max(se,Math.floor(Pe)):se,ne=Date.now()+ue;h.current=ne,p(new Date(ne).toISOString()),g.current!==null&&window.clearTimeout(g.current),g.current=window.setTimeout(()=>{g.current=null,h.current=null,p(null),d()&&ie()},ue)},[d]),O=o.useCallback(()=>{const ie=h.current;return typeof ie=="number"&&Number.isFinite(ie)&&ie>Date.now()},[]),Z=o.useCallback(ie=>{if(typeof window>"u")return null;const Q=String(ie||"").trim();return dl(Q)?Lj(window.localStorage.getItem(tk(Q))):null},[]),U=o.useCallback((ie,Q)=>{if(typeof window>"u")return null;const H=String(ie||"").trim();if(!dl(H))return null;try{const se=Dj(window.localStorage.getItem(Lb(H,Q)));return se?.workspaceId===H&&se.operation===Q?se:null}catch{return null}},[]),ve=o.useCallback(ie=>{const Q=String(ie||"").trim();if(Q)try{F.current?.postMessage({workspaceId:Q})}catch{}},[]),te=o.useCallback((ie,Q)=>{const H=String(ie||"").trim();if(dl(H))try{F.current?.postMessage({kind:"state",workspaceId:H,state:Ob(Q)})}catch{}},[]),ce=o.useCallback((ie,Q,H=new Date().toISOString())=>{if(typeof window>"u")return;const se=String(ie||"").trim();if(!(!dl(se)||!Number.isFinite(Date.parse(H))))try{window.localStorage.setItem(Lb(se,Q),JSON.stringify({workspaceId:se,operation:Q,completedAt:new Date(H).toISOString()}))}catch{return}},[]),Le=o.useCallback((ie,Q,H,se=Date.now())=>{const Pe=U(ie,Q),ue=Pe?Date.parse(Pe.completedAt):NaN,ne=Number(H);return Number.isFinite(ue)&&Number.isFinite(ne)&&ne>0&&ue<=se&&se-ue<ne},[U]),Ie=o.useCallback((ie,Q)=>{if(typeof window>"u")return null;const H=String(ie||"").trim();if(!dl(H))return null;const se=Oj(v.current,H,Q,Date.now());try{window.localStorage.setItem(tk(H),JSON.stringify(se))}catch{return null}return ve(H),se},[ve]),Ye=o.useCallback(()=>{j.current!==null&&typeof window<"u"&&(window.clearInterval(j.current),j.current=null)},[]),ge=o.useCallback((ie,Q)=>{if(typeof window>"u")return;const H=String(ie||V.current||"").trim();if(!H)return;const se=Z(H),Pe=se?.ownerId===v.current;if(!(!Q?.force&&se&&!Pe)){Ye();try{window.localStorage.removeItem(tk(H))}catch{}V.current=null,_.current=null,ve(H)}},[ve,Z,Ye]),he=o.useCallback((ie,Q)=>{typeof window>"u"||(Ye(),j.current=window.setInterval(()=>{if(!d()){Ye();return}const H=String(V.current||"").trim(),se=_.current;if(!H||!se){Ye();return}if(Z(H)?.ownerId!==v.current){Ye(),V.current=null,_.current=null;return}Ie(H,se)},Ej),V.current=ie,_.current=Q)},[d,Z,Ye,Ie]),Ae=o.useCallback(async(ie,Q)=>{if(!d())return!1;if(typeof window>"u")return!0;const H=String(ie||"").trim();if(!dl(H))return!1;const se=Z(H);if(se?.ownerId===v.current)return Ie(H,Q)?(he(H,Q),!0):!1;if(se&&!Bj(se)||!Ie(H,Q))return!1;const ne=Z(H);return!ne||ne.ownerId!==v.current?!1:(he(H,Q),!0)},[d,Z,he,Ie]),ye=o.useCallback(ie=>{ge(ie,{force:!0})},[ge]),Ne=o.useCallback(ie=>{const Q=N.current,H=rk(Q,{enabled:!!ie.enabled,phase:ie.phase||Q.phase,setupIntent:ie.setupIntent,pullCursor:ie.pullCursor,lastPullAt:ie.lastPullAt,lastPushAt:ie.lastPushAt,lastSyncedAt:ie.lastSyncedAt,lastErrorMessage:ie.lastErrorMessage});N.current=H,x.current=H.pullCursor,r(H.enabled),n(H.phase),s(H.setupIntent??null),i(H.lastPullAt),l(H.lastPushAt),c(H.lastErrorMessage??null)},[r,n,s,i,l,c]),ae=o.useCallback((ie,Q)=>{const H=N.current.revision,se=ie.revision;if(se){const Pe=Cj(se,H);if(Pe<0||Pe===0&&!Q?.allowEqualRevision)return!1}else if(H||!Q?.allowUnversioned)return!1;return N.current=ie,Ne(ie),!0},[Ne]),q=o.useCallback(ie=>{const Q=rk(N.current,ie);return Ne(Q),Q},[Ne]),W=o.useCallback(()=>N.current,[]),K=o.useCallback(async ie=>{const Q=rk(N.current,{...ie,revision:Ij(N.current.revision,v.current)});N.current=Q,x.current=Q.pullCursor;const H=await Af({workspaceId:t,stateKey:"workspace-sync",patch:Ob(Q),throwOnError:!0,respectFailureCooldown:!1}),se=H.response,Pe=H.payload;if(H.skipped)return ae(Q,{allowEqualRevision:!0})&&te(t,Q),N.current;if(!se)throw new Error("Failed to persist workspace sync state (missing response)");if(!se.ok||Pe?.success===!1)throw new Error(Pe?.error||`Failed to persist workspace sync state (${se.status})`);const ue=Pe?.state&&typeof Pe.state=="object"&&!Array.isArray(Pe.state)?ek(Pe.state).state:Q;return ae(ue,{allowEqualRevision:!0})&&te(t,ue),N.current},[ae,te,t]),Re=o.useCallback(async()=>{if(!dl(t)){const ie=Oh();N.current=ie,Ne(ie);return}try{const ie=await fetch(`/api/taskforce/ui-state?key=workspace-sync&workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!ie.ok)return;const Q=await ie.json().catch(()=>({})),H=ek(Q?.state&&typeof Q.state=="object"?Q.state:null);ae(H.state,{allowEqualRevision:!0,allowUnversioned:!0})&&(H.changed||!H.state.revision)&&K(H.state)}catch{}},[ae,t,K]),we=o.useCallback(async(ie,Q)=>{if(!dl(t))return{success:!1,error:"Workspace setup is required before enabling sync."};try{if(!ie.enabled)return await K({enabled:!1,phase:"idle",setupIntent:null,pullCursor:null}),{success:!0};if(!Q.isAuthenticated)return{success:!1,error:"Sign in is required before enabling workspace sync."};if(!Q.cloudAuthConfigured)return{success:!1,error:"Cloud authentication endpoint is not configured."};const H=await Q.ensureCloudWorkspaceReadyForSync();return H.success?(await K({enabled:!0,phase:H.provisioned?"provision-local":"attach-cloud",setupIntent:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}),{success:!0}):{success:!1,error:H.error||"Workspace sync handshake failed."}}catch{return{success:!1,error:"Failed to save workspace sync settings."}}},[t,K]);return o.useEffect(()=>{C.current="",S.current="",w.current=new Set,T.current=new Set,E.current=new Map,x.current=null,N.current=Oh(),k.current=!1,b.current=!1,ge(),z()},[z,t,ge]),o.useEffect(()=>{if(typeof window>"u"||typeof BroadcastChannel>"u")return;const ie=new BroadcastChannel(Pj);return F.current=ie,ie.onmessage=Q=>{const H=Q.data;if(H?.kind!=="state"||String(H.workspaceId||"").trim()!==t||!H.state||typeof H.state!="object"||Array.isArray(H.state))return;const se=ek(H.state);ae(se.state)},()=>{ie.onmessage=null,ie.close(),F.current===ie&&(F.current=null)}},[ae,t]),o.useEffect(()=>()=>{g.current!==null&&typeof window<"u"&&(window.clearTimeout(g.current),g.current=null),ge()},[ge]),{workspaceRetryAt:f,isWorkspaceRetryPending:O,workspacePushInFlightRef:k,workspacePullInFlightRef:b,workspaceLastPushedSignatureRef:C,workspacePendingSignatureRef:S,workspaceLastPushedTaskIdsRef:w,workspaceDeletedTaskIdsRef:T,workspaceDeletedTaskWatermarksRef:E,workspacePullCursorRef:x,clearWorkspaceRetry:z,scheduleWorkspaceRetry:M,persistWorkspaceSyncPatch:K,applyWorkspaceSyncPatchLocally:q,readWorkspaceSyncStateSnapshot:W,loadWorkspaceSyncState:Re,applyWorkspaceSyncStateSnapshot:Ne,saveWorkspaceCloudSyncSettings:we,acquireWorkspaceSyncLease:Ae,releaseWorkspaceSyncLease:ge,forceClearWorkspaceSyncLease:ye,readWorkspaceSyncLease:Z,readWorkspaceSyncCompletion:U,recordWorkspaceSyncCompletion:ce,wasWorkspaceSyncOperationCompletedRecently:Le}}class $j{constructor(t=2048){this.maxSeenEventIds=t}seenEventIds=new Set;seenEventIdQueue=[];activeEpoch="";lastSeq=null;telemetry={accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0};process(t){const r=typeof t.eventId=="string"?t.eventId.trim():"";if(r&&this.seenEventIds.has(r))return this.telemetry.duplicateDiscarded+=1,{accepted:!1,reason:"duplicate",shouldRecover:!1};const n=typeof t.serverEpoch=="string"?t.serverEpoch.trim():"",s=Number(t.seq);if(!(n.length>0&&Number.isFinite(s)&&s>=0))return r?(this.rememberEventId(r),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1}):(this.telemetry.invalidDiscarded+=1,{accepted:!1,reason:"invalid",shouldRecover:!1});const l=Math.floor(s);if(this.activeEpoch&&this.activeEpoch!==n)return this.activeEpoch=n,this.lastSeq=l,r&&this.rememberEventId(r),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};if(!this.activeEpoch)return this.activeEpoch=n,this.lastSeq=l,r&&this.rememberEventId(r),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1};const c=this.lastSeq;if(typeof c=="number"){if(l<=c){this.telemetry.outOfOrderDiscarded+=l===c?0:1,this.telemetry.duplicateDiscarded+=l===c?1:0;const d=l<c;return d&&(this.telemetry.recoveryTriggered+=1),{accepted:!1,reason:l===c?"duplicate":"out-of-order",shouldRecover:d}}if(l>c+1)return this.telemetry.outOfOrderDiscarded+=1,this.telemetry.recoveryTriggered+=1,{accepted:!1,reason:"out-of-order",shouldRecover:!0}}return this.lastSeq=l,r&&this.rememberEventId(r),this.telemetry.accepted+=1,{accepted:!0,shouldRecover:!1}}getTelemetry(){return{...this.telemetry}}rememberEventId(t){for(this.seenEventIds.add(t),this.seenEventIdQueue.push(t);this.seenEventIdQueue.length>this.maxSeenEventIds;){const r=this.seenEventIdQueue.shift();r&&this.seenEventIds.delete(r)}}}function CC(e){const{enabled:t,workspaceId:r,websocketUrl:n,reconnectBaseMs:s=400,reconnectMaxMs:i=1e4,degradeAfterAttempts:l=5,replayLimit:c=200,onSignal:d,onTelemetry:f,userId:p}=e,[g,h]=o.useState("degraded-fallback"),y=o.useRef(null),k=o.useRef(null),b=o.useRef(0),C=o.useRef(""),S=o.useRef(!1),w=o.useRef(null),T=o.useRef(null),E=o.useRef(new $j),x=o.useRef(d),N=o.useRef(f);o.useEffect(()=>{x.current=d},[d]),o.useEffect(()=>{N.current=f},[f]);const[v,V]=o.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),_=o.useMemo(()=>String(r||"").trim(),[r]),j=o.useMemo(()=>String(n||"").trim(),[n]);return o.useEffect(()=>{let F=!1;const z=()=>{k.current!==null&&(window.clearTimeout(k.current),k.current=null)},M=()=>{const ge=y.current;if(y.current=null,ge)try{ge.close()}catch{}},O=ge=>ge==="taskforce:replay-gap"||ge==="taskforce:replay-reset"?4:ge==="taskforce:mutation"||ge==="taskforce:replay"?3:1,Z=ge=>{const he=T.current;if(he){const Ae=O(he.type),ye=O(ge.type);if(ye<Ae)return;ye===Ae&&(ge={...ge,eventIds:Array.from(new Set([...he.eventIds||[],...he.eventId?[he.eventId]:[],...ge.eventIds||[],...ge.eventId?[ge.eventId]:[]])),invalidations:[...he.invalidations||[],...ge.invalidations||[]]})}T.current=ge,w.current!==null&&window.clearTimeout(w.current),w.current=window.setTimeout(()=>{w.current=null;const Ae=x.current;if(!T.current||typeof Ae!="function")return;const ye=T.current;T.current=null,Ae(ye)},80)},U=ge=>{try{const he=JSON.parse(String(ge.data||""));return!he||typeof he!="object"?null:he}catch{return null}},ve=ge=>{const he=typeof ge.serverEpoch=="string"?ge.serverEpoch.trim():"",Ae=Number(ge.seq);!he||!Number.isFinite(Ae)||Ae<0||(C.current=`${he}:${Math.floor(Ae)}`,S.current=!1)},te=ge=>{const he=typeof ge.entityType=="string"?ge.entityType.trim():"";if(!he)return null;const Ae=Array.isArray(ge.affectedCollections)?ge.affectedCollections.map(Ne=>typeof Ne=="string"?Ne.trim():"").filter(Boolean):void 0,ye=Number(ge.dataVersion);return{entityType:he,changeType:typeof ge.changeType=="string"?ge.changeType.trim():void 0,entityIds:Array.isArray(ge.entityIds)?ge.entityIds.map(Ne=>typeof Ne=="string"?Ne.trim():"").filter(Boolean):[],affectedCollections:Ae,lifecycleTransition:typeof ge.lifecycleTransition=="string"?ge.lifecycleTransition.trim():void 0,dataVersion:Number.isFinite(ye)?ye:void 0}},ce=()=>{const ge=E.current.getTelemetry();V(ge);const he=N.current;typeof he=="function"&&he(ge)},Le=ge=>{const he={type:"taskforce:replay",workspaceId:_,limit:c},Ae=C.current;Ae&&(he.cursor=Ae),ge.send(JSON.stringify(he))},Ie=()=>{if(!t||F)return;z(),b.current+=1;const ge=b.current,he=Math.max(50,Math.floor(s)),Ae=Math.max(he,Math.floor(i)),ye=Math.min(Ae,he*Math.pow(2,Math.max(0,ge-1)));h(ge>=l?"degraded-fallback":"reconnecting"),k.current=window.setTimeout(()=>{F||(k.current=null,Ye())},ye)},Ye=()=>{if(!t||F||!_||!j)return;M();let ge;try{ge=new WebSocket(j)}catch{Ie();return}y.current=ge,ge.addEventListener("open",()=>{b.current=0,h("connected"),ge.send(JSON.stringify({type:"taskforce:subscribe",workspaceId:_,userId:p||void 0})),Le(ge)}),ge.addEventListener("message",he=>{const Ae=U(he);if(!Ae||typeof Ae.type!="string")return;const ye=typeof Ae.workspaceId=="string"?Ae.workspaceId.trim():_;if(!(!ye||ye!==_)){if(Ae.type==="taskforce:update"){Z({type:"taskforce:update",workspaceId:_,eventId:typeof Ae.eventId=="string"?Ae.eventId.trim():void 0});return}if(Ae.type==="taskforce:mutation"){const Ne=E.current.process({eventId:Ae.eventId,serverEpoch:Ae.serverEpoch,seq:Ae.seq});if(!Ne.accepted){ce(),Ne.shouldRecover&&(C.current="",S.current||(S.current=!0,Z({type:"taskforce:replay-gap",workspaceId:_})));return}ve(Ae),ce();const ae=te(Ae);Z({type:Ae.type,workspaceId:_,eventId:typeof Ae.eventId=="string"?Ae.eventId.trim():void 0,invalidations:ae?[ae]:void 0});return}if(Ae.type==="taskforce:replay"){const Ne=Array.isArray(Ae.events)?Ae.events:[];let ae=0;const q=[],W=[];for(const K of Ne){if(!E.current.process({eventId:K.eventId,serverEpoch:K.serverEpoch,seq:K.seq}).accepted)continue;ae+=1,ve(K);const we=te(K);we&&q.push(we),typeof K.eventId=="string"&&K.eventId.trim()&&W.push(K.eventId.trim())}S.current=!1,ce(),(ae>0||Ae.truncated===!0)&&Z({type:"taskforce:replay",workspaceId:_,eventIds:W,invalidations:q}),Ae.truncated===!0&&Le(ge);return}if(Ae.type==="taskforce:replay-gap"||Ae.type==="taskforce:replay-reset"){if(C.current="",S.current)return;S.current=!0,Z({type:Ae.type,workspaceId:_})}}}),ge.addEventListener("close",he=>{if(y.current===ge&&(y.current=null),!F&&t){const Ae=Number(he?.code||0),ye=String(he?.reason||"").trim();console.warn(`[Taskforce] Realtime socket closed workspace=${_} user=${String(p||"anonymous").trim()||"anonymous"} code=${Ae}${ye?` reason=${ye}`:""}`)}Ie()}),ge.addEventListener("error",()=>{try{ge.close()}catch{}})};return!t||!_||!j?(h("degraded-fallback"),z(),M(),()=>{z(),M()}):(h("reconnecting"),Ye(),()=>{F=!0,z(),w.current!==null&&(window.clearTimeout(w.current),w.current=null),T.current=null,M()})},[t,_,j,s,i,l,c,p]),{connectionState:g,telemetry:v}}const Wk="taskforce:context-assets-mutated";function Fj(e){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new CustomEvent(Wk,{detail:e}))}const $k="taskforce:ai-profiles-mutated";function IC(e){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new CustomEvent($k,{detail:e}))}const Fk="taskforce:agents-mutated";function _C(e){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new CustomEvent(Fk,{detail:e}))}const Uk="taskforce:agent-skills-mutated";function TC(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Uk,{detail:e}))}const Uj=4,ah=100;function gf(e,t,r){if(e===null)return null;if(typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:String(e);if(typeof e=="bigint")return e.toString();if(e instanceof Date)return e.toISOString();if(t>=Uj)return"[MaxDepth]";if(typeof e=="function"||typeof e=="symbol"||typeof e>"u")return String(e);if(Array.isArray(e))return e.slice(0,ah).map(n=>gf(n,t+1,r));if(e instanceof Set)return Array.from(e.values()).slice(0,ah).map(n=>gf(n,t+1,r));if(e instanceof Map){const n={};for(const[s,i]of Array.from(e.entries()).slice(0,ah))n[String(s)]=gf(i,t+1,r);return n}if(typeof e=="object"){if(r.has(e))return"[Circular]";r.add(e);const n={};for(const[s,i]of Object.entries(e).slice(0,ah))n[s]=gf(i,t+1,r);return r.delete(e),n}return String(e)}function jg(e){if(!(!e||typeof e!="object"||Array.isArray(e)))return gf(e,0,new WeakSet)}function xC(e){const t=jg(e);if(!t)return"null";try{return JSON.stringify(t)}catch{return"[UnserializableSyncEventDetails]"}}const RC="anthropic",zj="anthropic.claude-sonnet-4-6",jC=[{key:"anthropic",label:"Anthropic"},{key:"openai",label:"OpenAI"},{key:"google",label:"Google"},{key:"xai",label:"xAI"},{key:"deepseek",label:"DeepSeek"},{key:"meta",label:"Meta"},{key:"mistral",label:"Mistral AI"},{key:"amazon",label:"Amazon"}],zv=[{key:zj,providerKey:"anthropic",label:"Claude Sonnet 4.6",source:"bedrock",runtime:"bedrock-runtime",defaultTier:"balanced",runtimeModelId:"us.anthropic.claude-sonnet-4-6",availability:"verified",visible:!0,supportsTemperature:!0,defaultMaxTokens:512},{key:"anthropic.claude-haiku-4-5",providerKey:"anthropic",label:"Claude Haiku 4.5",source:"bedrock",runtime:"bedrock-runtime",defaultTier:"fast",runtimeModelId:"us.anthropic.claude-haiku-4-5-20251001-v1:0",availability:"configured",visible:!0,supportsTemperature:!0,defaultMaxTokens:512},{key:"anthropic.claude-sonnet-5",providerKey:"anthropic",label:"Claude Sonnet 5",source:"bedrock",runtime:"bedrock-anthropic-messages",defaultTier:"balanced",runtimeModelId:"anthropic.claude-sonnet-5",availability:"account_unavailable",visible:!1,supportsTemperature:!1,defaultMaxTokens:1024},{key:"anthropic.claude-fable-5",providerKey:"anthropic",label:"Claude Fable 5",source:"bedrock",runtime:"bedrock-anthropic-messages",defaultTier:"advanced",runtimeModelId:"anthropic.claude-fable-5",availability:"account_unavailable",visible:!1,supportsTemperature:!1,defaultMaxTokens:1024},{key:"anthropic.claude-opus-4-8",providerKey:"anthropic",label:"Claude Opus 4.8",source:"bedrock",runtime:"bedrock-anthropic-messages",defaultTier:"advanced",runtimeModelId:"anthropic.claude-opus-4-8",availability:"account_unavailable",visible:!1,supportsTemperature:!1,defaultMaxTokens:1024},{key:"amazon.nova-lite",providerKey:"amazon",label:"Nova Lite",source:"bedrock",runtime:"bedrock-runtime",defaultTier:"fast",runtimeModelId:"us.amazon.nova-lite-v1:0",availability:"configured",visible:!0,supportsTemperature:!0,defaultMaxTokens:512},{key:"amazon.nova-2-lite",providerKey:"amazon",label:"Nova 2 Lite",source:"bedrock",runtime:"bedrock-runtime",defaultTier:"fast",runtimeModelId:"us.amazon.nova-2-lite-v1:0",availability:"verified",visible:!0,supportsTemperature:!0,defaultMaxTokens:512},{key:"amazon.nova-pro",providerKey:"amazon",label:"Nova Pro",source:"bedrock",runtime:"bedrock-runtime",defaultTier:"balanced",runtimeModelId:"us.amazon.nova-pro-v1:0",availability:"configured",visible:!0,supportsTemperature:!0,defaultMaxTokens:512},{key:"deepseek.v3-2",providerKey:"deepseek",label:"DeepSeek V3.2",source:"bedrock",runtime:"bedrock-runtime",defaultTier:"balanced",runtimeModelId:"deepseek.v3.2",availability:"configured",visible:!0,supportsTemperature:!0,defaultMaxTokens:512},{key:"google.gemma-3-12b-it",providerKey:"google",label:"Gemma 3 12B IT",source:"bedrock",runtime:"bedrock-runtime",defaultTier:"fast",runtimeModelId:"google.gemma-3-12b-it",availability:"configured",visible:!0,supportsTemperature:!0,defaultMaxTokens:512},{key:"meta.llama-3-3-70b-instruct",providerKey:"meta",label:"Llama 3.3 70B Instruct",source:"bedrock",runtime:"bedrock-runtime",defaultTier:"balanced",runtimeModelId:"us.meta.llama3-3-70b-instruct-v1:0",availability:"configured",visible:!0,supportsTemperature:!0,defaultMaxTokens:512},{key:"meta.llama-4-scout-17b-instruct",providerKey:"meta",label:"Llama 4 Scout 17B Instruct",source:"bedrock",runtime:"bedrock-runtime",defaultTier:"balanced",runtimeModelId:"us.meta.llama4-scout-17b-instruct-v1:0",availability:"verified",visible:!0,supportsTemperature:!0,defaultMaxTokens:512},{key:"mistral.large-3",providerKey:"mistral",label:"Mistral Large 3",source:"bedrock",runtime:"bedrock-runtime",defaultTier:"balanced",runtimeModelId:"mistral.mistral-large-3-675b-instruct",availability:"configured",visible:!0,supportsTemperature:!0,defaultMaxTokens:512},{key:"xai.grok-4-3",providerKey:"xai",label:"Grok 4.3",source:"bedrock",runtime:"bedrock-mantle",defaultTier:"advanced",runtimeModelId:"xai.grok-4.3",availability:"verified",visible:!0,supportsTemperature:!1,defaultMaxTokens:1024},{key:"openai.gpt-oss-120b",providerKey:"openai",label:"gpt-oss-120b",source:"bedrock",runtime:"bedrock-runtime",defaultTier:"balanced",runtimeModelId:"openai.gpt-oss-120b-1:0",availability:"verified",visible:!0,supportsTemperature:!0,defaultMaxTokens:512},{key:"openai.gpt-5-4",providerKey:"openai",label:"GPT-5.4",source:"bedrock",runtime:"bedrock-mantle",defaultTier:"advanced",runtimeModelId:"openai.gpt-5.4",availability:"account_unavailable",visible:!1,supportsTemperature:!1,defaultMaxTokens:1024}];function Hj(e){return e.visible&&e.availability!=="account_unavailable"}function Bee(e){const t=String(e||"").trim();return zv.find(r=>r.key===t)||null}function Hv(e){const t=String(e||"").trim().toLowerCase();return jC.some(r=>r.key===t)?t:RC}function Gj(e){const t=Hv(e);return zv.filter(r=>r.providerKey===t&&Kj(r))}function Vj(e,t){const r=String(e||"").trim(),n=Gj(t??RC);return n.some(s=>s.key===r)?r:n[0]?.key||""}function Kj(e){return Hj(e)}function Wee(e){const t=Hv(e);return jC.find(r=>r.key===t)?.label||"Anthropic"}function $ee(e){const t=String(e||"").trim();return zv.find(r=>r.key===t)?.label||t||"No configured model"}const PC="taskforce.userGlobalSyncMeta.v1",qj="taskforce.syncDebug.v1",Yj=12e4,EC="taskforce.syncWatermarks.v3",Zj=300*1e3,Bb="Another local window is already syncing this workspace. Wait a few seconds, or press Repair in that window.";function Rc(e){const t=String(e||"").trim();return t.length>0&&t.toLowerCase()!=="default"}function Jj(){if(typeof window>"u")return!1;try{const e=String(window.localStorage.getItem(qj)||"").trim().toLowerCase();return e==="1"||e==="true"||e==="on"||e==="yes"}catch{return!1}}function js(e,t){if(!Jj())return;console.info("[Taskforce Sync]",e,t&&typeof t=="object"?t:{})}function Qj(e){const t=e?.providerMetadata??e?.provider_metadata??null;return{id:String(e?.id||"").trim(),workspaceId:String(e?.workspaceId||e?.workspace_id||"").trim(),profileToken:String(e?.profileToken||e?.profile_token||"").trim(),name:String(e?.name||"").trim(),username:String(e?.username||"").trim(),icon:String(e?.icon||"Bot").trim()||"Bot",color:String(e?.color||"#8b5cf6").trim()||"#8b5cf6",avatarUrl:Uu(e?.avatarUrl??e?.avatar_url),avatarSourceUrl:Uu(e?.avatarSourceUrl??e?.avatar_source_url),avatarRevision:Number.isFinite(Number(e?.avatarRevision??e?.avatar_revision))?Math.max(0,Math.floor(Number(e?.avatarRevision??e?.avatar_revision))):0,avatarUpdatedAt:ms(e?.avatarUpdatedAt??e?.avatar_updated_at),description:Ha(e?.description),role:Ha(e?.role),provider:Ha(e?.provider),model:Ha(e?.model),surfaceType:gC(e?.surfaceType??e?.surface_type),seatScope:yC(e?.seatScope??e?.seat_scope),providerMetadata:t&&typeof t=="object"&&!Array.isArray(t)?t:null,archivedAt:ms(e?.archivedAt??e?.archived_at),archivedBy:Nc(e?.archivedBy??e?.archived_by),archivedReason:Ha(e?.archivedReason??e?.archived_reason),mergedIntoProfileId:Nc(e?.mergedIntoProfileId??e?.merged_into_profile_id),rosterStateUpdatedAt:ms(e?.rosterStateUpdatedAt??e?.roster_state_updated_at),createdAt:String(e?.createdAt||e?.created_at||"").trim(),updatedAt:String(e?.updatedAt||e?.updated_at||e?.createdAt||e?.created_at||"").trim(),lastActiveAt:ms(e?.lastActiveAt??e?.last_active_at)}}function Xj(e){const t=String(e?.modelTier||e?.model_tier||"").trim().toLowerCase();return{id:String(e?.id||"").trim(),tenantId:String(e?.tenantId||e?.tenant_id||"").trim()||void 0,workspaceId:String(e?.workspaceId||e?.workspace_id||"").trim(),name:String(e?.name||"Agent").trim()||"Agent",modelProvider:"taskforce_hq",providerKey:Hv(e?.providerKey??e?.provider_key),modelKey:Vj(e?.modelKey??e?.model_key,e?.providerKey??e?.provider_key),modelTier:t==="fast"||t==="advanced"?t:"balanced",systemPrompt:typeof(e?.systemPrompt??e?.system_prompt)=="string"?String(e?.systemPrompt??e?.system_prompt):"",enabled:(e?.enabled??!0)!==!1&&Number(e?.enabled??1)!==0,createdByUserId:Nc(e?.createdByUserId??e?.created_by_user_id),updatedByUserId:Nc(e?.updatedByUserId??e?.updated_by_user_id),createdAt:String(e?.createdAt||e?.created_at||"").trim(),updatedAt:String(e?.updatedAt||e?.updated_at||e?.createdAt||e?.created_at||"").trim(),deletedAt:ms(e?.deletedAt??e?.deleted_at)}}function eP(e){const t=Array.isArray(e?.messages)?e.messages.map(n=>({role:n?.role==="assistant"?"assistant":"user",content:String(n?.content||"").trim()})).filter(n=>n.content.length>0):[],r=(e?.usage??e?.usage_json)&&typeof(e?.usage??e?.usage_json)=="object"?e?.usage??e?.usage_json:null;return{id:String(e?.id||"").trim(),tenantId:String(e?.tenantId||e?.tenant_id||"").trim()||void 0,workspaceId:String(e?.workspaceId||e?.workspace_id||"").trim(),agentId:String(e?.agentId||e?.agent_id||"").trim(),taskId:Nc(e?.taskId??e?.task_id),title:String(e?.title||"Agent chat").trim()||"Agent chat",messages:t,modelProvider:Ha(e?.modelProvider??e?.model_provider),modelId:Ha(e?.modelId??e?.model_id),usage:r,latencyMs:Number.isFinite(Number(e?.latencyMs??e?.latency_ms))?Number(e?.latencyMs??e?.latency_ms):null,createdByUserId:Nc(e?.createdByUserId??e?.created_by_user_id),updatedByUserId:Nc(e?.updatedByUserId??e?.updated_by_user_id),createdAt:String(e?.createdAt||e?.created_at||"").trim(),updatedAt:String(e?.updatedAt||e?.updated_at||e?.createdAt||e?.created_at||"").trim(),deletedAt:ms(e?.deletedAt??e?.deleted_at)}}function Wb(){if(typeof window>"u")return{};try{const e=window.localStorage.getItem(PC);if(!e)return{};const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}function tP(e){if(!(typeof window>"u"))try{window.localStorage.setItem(PC,JSON.stringify(e))}catch{}}function rP(e){try{return JSON.stringify(e&&typeof e=="object"?e:null)}catch{return"null"}}function aP(e){return e.flatMap(t=>{const r=String(t?.id||"").trim();return!r||!Array.isArray(t?.comments)?[]:t.comments.map(n=>({id:String(n?.id||"").trim(),sessionId:r,body:String(n?.body||""),anchor:n?.anchor??null,order:Number.isFinite(Number(n?.order))?Math.max(0,Math.floor(Number(n.order))):0,authorActorId:typeof n?.authorActorId=="string"&&n.authorActorId.trim().length>0?n.authorActorId.trim():null,updatedByActorId:typeof n?.updatedByActorId=="string"&&n.updatedByActorId.trim().length>0?n.updatedByActorId.trim():null,deletedByActorId:typeof n?.deletedByActorId=="string"&&n.deletedByActorId.trim().length>0?n.deletedByActorId.trim():null,createdAt:String(n?.createdAt||"").trim(),updatedAt:String(n?.updatedAt||n?.createdAt||"").trim(),deletedAt:typeof n?.deletedAt=="string"&&n.deletedAt.trim().length>0?n.deletedAt.trim():null})).filter(n=>n.id.length>0&&n.sessionId.length>0)})}function NC(e){return{taskIds:Array.from(e.taskIds.values()),taskWatermarks:Array.from(e.taskWatermarks.entries()),taskChangeKeys:Array.from((e.taskChangeKeys||new Map).entries()),taskRelationshipChangeKeys:Array.from((e.taskRelationshipChangeKeys||new Map).entries()),initiativeWatermarks:Array.from(e.initiativeWatermarks.entries()),workstreamWatermarks:Array.from(e.workstreamWatermarks.entries()),aiProfileWatermarks:Array.from(e.aiProfileWatermarks.entries()),aiProfileChangeKeys:Array.from((e.aiProfileChangeKeys||new Map).entries()),taskforceAgentWatermarks:Array.from((e.taskforceAgentWatermarks||new Map).entries()),taskforceAgentSkillWatermarks:Array.from((e.taskforceAgentSkillWatermarks||new Map).entries()),agentConversationWatermarks:Array.from((e.agentConversationWatermarks||new Map).entries()),documentWatermarks:Array.from(e.documentWatermarks.entries()),assetWatermarks:Array.from(e.assetWatermarks.entries()),documentReviewSessionWatermarks:Array.from(e.documentReviewSessionWatermarks.entries()),documentReviewCommentWatermarks:Array.from(e.documentReviewCommentWatermarks.entries()),annotatedAttachmentSessionWatermarks:Array.from(e.annotatedAttachmentSessionWatermarks.entries()),taskEventWatermarks:Array.from(e.taskEventWatermarks.entries()),taxonomyStateFingerprint:typeof e.taxonomyStateFingerprint=="string"?e.taxonomyStateFingerprint:"",taxonomyChangeKey:typeof e.taxonomyChangeKey=="string"?e.taxonomyChangeKey:""}}function MC(e,t){if(!e||typeof e!="object")return null;const r=typeof e.taxonomyStateFingerprint=="string"?e.taxonomyStateFingerprint:"",n=!t||!r||r===t?new Map(Array.isArray(e.taskWatermarks)?e.taskWatermarks:[]):new Map;return{taskIds:new Set(Array.isArray(e.taskIds)?e.taskIds.map(i=>String(i||"").trim()).filter(i=>i.length>0):Array.from(n.keys())),taskWatermarks:n,taskChangeKeys:new Map(Array.isArray(e.taskChangeKeys)?e.taskChangeKeys:[]),taskRelationshipChangeKeys:new Map(Array.isArray(e.taskRelationshipChangeKeys)?e.taskRelationshipChangeKeys:[]),initiativeWatermarks:new Map(Array.isArray(e.initiativeWatermarks)?e.initiativeWatermarks:[]),workstreamWatermarks:new Map(Array.isArray(e.workstreamWatermarks)?e.workstreamWatermarks:[]),aiProfileWatermarks:new Map(Array.isArray(e.aiProfileWatermarks)?e.aiProfileWatermarks:[]),aiProfileChangeKeys:new Map(Array.isArray(e.aiProfileChangeKeys)?e.aiProfileChangeKeys:[]),taskforceAgentWatermarks:new Map(Array.isArray(e.taskforceAgentWatermarks)?e.taskforceAgentWatermarks:[]),taskforceAgentSkillWatermarks:new Map(Array.isArray(e.taskforceAgentSkillWatermarks)?e.taskforceAgentSkillWatermarks:[]),agentConversationWatermarks:new Map(Array.isArray(e.agentConversationWatermarks)?e.agentConversationWatermarks:[]),documentWatermarks:new Map(Array.isArray(e.documentWatermarks)?e.documentWatermarks:[]),assetWatermarks:new Map(Array.isArray(e.assetWatermarks)?e.assetWatermarks:[]),documentReviewSessionWatermarks:new Map(Array.isArray(e.documentReviewSessionWatermarks)?e.documentReviewSessionWatermarks:[]),documentReviewCommentWatermarks:new Map(Array.isArray(e.documentReviewCommentWatermarks)?e.documentReviewCommentWatermarks:[]),annotatedAttachmentSessionWatermarks:new Map(Array.isArray(e.annotatedAttachmentSessionWatermarks)?e.annotatedAttachmentSessionWatermarks:[]),taskEventWatermarks:new Map(Array.isArray(e.taskEventWatermarks)?e.taskEventWatermarks:[]),taxonomyChangeKey:typeof e.taxonomyChangeKey=="string"?e.taxonomyChangeKey:""}}function ak(e,t){if(typeof window>"u")return null;try{const r=`${EC}.${e}`,n=window.localStorage.getItem(r);if(!n)return null;const s=JSON.parse(n);return!s||s.v!==2&&s.v!==3&&s.v!==4&&s.v!==5&&s.v!==6&&s.v!==7&&s.v!==8&&s.v!==9&&s.v!==10&&s.v!==11&&s.v!==12?null:MC(s,t)}catch{return null}}function $b(e,t){if(typeof window>"u")return!1;try{const r=`${EC}.${e}`;return window.localStorage.setItem(r,JSON.stringify({v:12,savedAt:new Date().toISOString(),...NC(t)})),!0}catch{return!1}}function nP({currentWorkspaceId:e,workspaceSyncPhase:t,clearWorkspaceRetry:r,setWorkspaceSyncBusy:n,setUserGlobalSyncStatus:s,setUserGlobalSyncError:i,setWorkspaceLastErrorMessage:l,setWorkspaceLastErrorAt:c,reportSyncEvent:d,setAuthBlocked:f,setIsAuthenticated:p,checkAuthSession:g,ensureCloudWorkspaceReadyForSync:h,scheduleWorkspaceSyncRetry:y,persistWorkspaceSyncPatchSafely:k}){const b=async(S,w)=>{r(),n(!1),s("error");const T="Session expired. Sign in again to resume cloud sync.";i(T),l(T),c(new Date().toISOString()),d(e,{eventType:S==="handshake"?"handshake":S,status:"error",statusCode:w,errorMessage:T}),f(!0),p(!1),await g()};return{handleSyncAuthFailure:b,ensureWorkspaceSyncReady:async()=>{if(!Rc(e)){const T="Workspace sync blocked: local workspace ID is unresolved.";return l(T),c(new Date().toISOString()),i(T),s("error"),!1}const S=await h();if(S.success)return!0;if(S.statusCode===401)return await b("handshake",401),!1;const w=S.error||"Workspace sync handshake failed.";return l(w),c(new Date().toISOString()),i(w),s("error"),d(e,{eventType:"handshake",status:"error",statusCode:S.statusCode,errorMessage:w}),S.transient||ti(S.statusCode)?y(S.retryAfterMs):(t==="active"||t==="attach-cloud"||t==="provision-local")&&k({phase:"error",lastErrorMessage:w}),!1}}}const DC=5*6e4;function nk(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function Yf(e){return e.cloudAuthConfigured&&e.runtimeMode==="local"&&e.workspaceCloudSyncEnabled&&e.authSessionResolved}function sP({enabled:e,phase:t,busy:r,retryAt:n,lastErrorMessage:s,lastErrorAt:i,lastPullAt:l,lastPushAt:c,nowMs:d,pullLagToleranceMs:f=DC,pendingChanges:p=0,durableOutbox:g}){if(!e)return{status:"off",summary:"Sync is turned off for this workspace.",recommendedAction:"Turn on sync when you are ready to back up this workspace."};if(t==="provision-local")return{status:"syncing",summary:r?"Uploading this workspace to cloud for the first time.":"Preparing the first upload to cloud.",recommendedAction:"Keep this window open while the first upload finishes. If it seems stalled, press Sync."};if(t==="attach-cloud")return{status:"syncing",summary:r?"Pulling the cloud workspace into this device.":"Waiting for the first cloud pull into this device.",recommendedAction:"Keep this window open for the first cloud pull. If it does not move, press Repair."};if((g?.blocked||0)>0){const C=g?.blocked||0,S=g?.pending||0;return{status:"attention",summary:`${C} durable local change${C===1?"":"s"} could not sync${S>0?`; ${S} later change${S===1?" is":"s are"} waiting`:""}.`,recommendedAction:"Press Repair to reconcile and replay supported task changes. If Repair is blocked, copy the report for diagnosis."}}if(g?.recovery&&g.recovery.state!=="completed")return g.recovery.state==="awaiting_baseline"?{status:"attention",summary:"Durable local recovery is waiting for an authoritative cloud repair.",recommendedAction:"Press Repair to resume the verified cloud baseline and replay."}:g.recovery.replayBlocked>0?{status:"attention",summary:"A recovered local change is still blocked during replay.",recommendedAction:"Copy the Sync Manager report so the replay conflict can be diagnosed safely."}:{status:"syncing",summary:"Recovered local changes are replaying against the repaired cloud baseline.",recommendedAction:"No action needed unless the recovery state remains unchanged."};if(n)return{status:"attention",summary:"Sync hit a temporary problem and will retry automatically.",recommendedAction:"Wait for the automatic retry, or press Sync to retry now."};if(s||t==="error")return{status:"attention",summary:"Sync needs attention before it can continue.",recommendedAction:"Press Sync to retry. If the same error keeps returning, press Repair."};if(p>0||(g?.pending||0)>0||(g?.inFlight||0)>0)return{status:"syncing",summary:"Local changes are waiting to sync.",recommendedAction:"No action needed unless the queue remains unchanged."};if(r)return{status:"syncing",summary:"Sync is currently running.",recommendedAction:"No action needed."};const h=nk(l),y=nk(c),k=nk(i);return h===null?{status:"attention",summary:y===null?"This device has not completed its first cloud pull.":"Cloud uploads are working, but this device has not completed a cloud pull.",recommendedAction:"Press Retry now. If the cloud check still does not complete, press Repair and copy the report."}:k!==null&&k>h?{status:"attention",summary:"A sync issue occurred after the last successful cloud pull.",recommendedAction:"Press Retry now to verify cloud changes can still be received. If the issue returns, copy the report."}:Number.isFinite(d)&&d-h>Math.max(0,f)?{status:"attention",summary:y!==null&&y>h?"Cloud uploads are succeeding, but this device has not received cloud changes recently.":"This device has not checked for cloud changes recently.",recommendedAction:"Press Retry now to check cloud changes. If Last cloud check does not advance, press Repair and copy the report."}:{status:"healthy",summary:"A recent cloud check succeeded and no local changes are waiting.",recommendedAction:"No action needed."}}function oP(e){return Yf(e)&&e.workspaceSyncPhase!=="attach-cloud"&&e.workspaceSyncReferenceSnapshotsReady}function iP(e){return Yf(e)&&e.workspaceSyncPhase==="active"&&e.workspaceSyncReferenceSnapshotsReady}function cP(e){return Yf(e)?e.workspaceSyncPhase==="provision-local"||e.workspaceSyncPhase==="error"||e.retryPending?{shouldStart:!1,shouldKickOffImmediately:!1}:{shouldStart:!0,shouldKickOffImmediately:e.workspaceSyncPhase==="attach-cloud"||!e.lastPullAt}:{shouldStart:!1,shouldKickOffImmediately:!1}}function lP(e){return Yf(e)&&e.isAuthenticated&&e.workspaceSyncPhase==="active"}function dP(e){return Yf(e)&&e.isAuthenticated&&e.workspaceSyncPhase!=="provision-local"&&e.workspaceSyncPhase!=="attach-cloud"&&!e.alreadyRan}function uP(e){const{workspaceSyncPhase:t,lastBootstrapPhase:r,workspaceLastPullAt:n}=e;return t==="provision-local"?"provision-local":t==="attach-cloud"?"attach-cloud":t==="active"||r==="active"?"active":r==="provision-local"||r==="attach-cloud"?r:n?"attach-cloud":"provision-local"}function pP({workspaceSyncPhase:e,lastBootstrapPhaseRef:t,bootstrapPhaseStartedAtRef:r,bootstrapLastProgressAtRef:n}){if(e==="attach-cloud"||e==="provision-local"){t.current=e,r.current===null&&(r.current=Date.now()),n.current=null;return}r.current=null,n.current=null}function fP({currentWorkspaceId:e,workspaceCloudSyncEnabled:t,workspaceSyncPhase:r,workspacePullInFlightRef:n,workspacePushInFlightRef:s,bootstrapPhaseStartedAtRef:i,bootstrapLastProgressAtRef:l,isExecutionAuthorized:c=()=>!0,setWorkspaceLastErrorMessage:d,setWorkspaceLastErrorAt:f,setUserGlobalSyncStatus:p,setUserGlobalSyncError:g,setWorkspaceSyncBusy:h,persistWorkspaceSyncPatchSafely:y}){if(!c()||!t||r!=="attach-cloud"&&r!=="provision-local")return;const k=window.setInterval(()=>{if(!c()||r!=="attach-cloud"&&r!=="provision-local"||n.current||s.current)return;const b=Math.max(i.current??0,l.current??0);if(b>0&&Date.now()-b<Yj)return;const S=`Workspace sync ${r==="attach-cloud"?"initial cloud pull":"initial cloud upload"} stalled. Press Repair to restart sync for this workspace.`;d(S),f(new Date().toISOString()),p("error"),g(S),h(!1),y({phase:"error",lastErrorMessage:S}),js("workspace_sync_bootstrap_timeout",{workspaceId:e,phase:r})},1e4);return()=>window.clearInterval(k)}function mP(e){const t=String(e||"").trim();return t.length>0&&t.toLowerCase()!=="default"}const Gv={allowed:!0};function gs(e,t){return{allowed:!1,reason:e,retainPendingSignature:t?.retainPendingSignature===!0}}function Vv(e,t){return e.cloudAuthConfigured?e.runtimeMode!=="local"?gs("runtime-not-local"):e.workspaceCloudSyncEnabled?(t?.requireValidWorkspace??!0)&&!mP(e.currentWorkspaceId)?gs("invalid-workspace"):null:gs("sync-disabled"):gs("cloud-auth-unconfigured")}function zk(e){const t=Vv(e);return t||(e.repairModeActive&&!e.repairModeBypass?gs("repair-active",{retainPendingSignature:!0}):e.workspaceSyncPhase==="attach-cloud"&&!e.repairModeBypass?gs("attach-cloud",{retainPendingSignature:!0}):e.isAuthenticated?e.pushInFlight?gs("push-in-flight",{retainPendingSignature:!0}):e.pullInFlight?gs("pull-in-flight",{retainPendingSignature:!0}):Gv:gs("auth-required"))}function Hk(e){const t=Vv(e);return t||(e.repairModeActive&&!e.repairModeBypass?gs("repair-active"):e.workspaceSyncPhase==="provision-local"?gs("provision-local"):e.retryPending?gs("retry-pending"):e.isAuthenticated?e.pullInFlight?gs("pull-in-flight"):e.pushInFlight?gs("push-in-flight"):Gv:gs("auth-required"))}function Gk(e){const t=Vv(e,{requireValidWorkspace:!1});return t||(e.isAuthenticated?Gv:gs("auth-required"))}function hP(e){return gs("lease-held",{retainPendingSignature:e==="push"})}const gP=512;function yP({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:r,workspaceSyncPhase:n,workspacePullInFlightRef:s,realtimePullDebounceRef:i,realtimeSuppressedEventIdsRef:l,clearWorkspaceRetry:c,isWorkspaceRetryPending:d,isExecutionAuthorized:f=()=>!0,isServerOwned:p=()=>!1,signalServerWake:g,pullWorkspaceChangesFromCloud:h}){const y=new Set;let k=!1,b=!1,C=null,S=!1;const w=()=>{if(b||!p())return;const _=S?[]:C;_&&(S=!1,C=null,b=!0,g?.(_).catch(()=>{}).finally(()=>{b=!1,w()}))},T=_=>{if(!S){if(!b&&C===null){C=_,w();return}if(C===null){C=_;return}C=null,S=!0}},E=()=>{C=null,S=!0,w()},x=()=>{if(!k&&y.size===0)return;const _=k?[]:Array.from(y);y.clear(),k=!1,_.length===0?E():T(_)};return{handleRealtimeSignal:_=>{if(!e||t!=="local"||!r||n==="provision-local")return;const j=Array.from(new Set([..._?.eventIds||[],..._?.eventId?[_.eventId]:[]].map(z=>String(z||"").trim()).filter(Boolean)));let F=j.length===0;for(const z of j)l.current.delete(z)||(F=!0);if(F){if(p()){if(j.length===0)k=!0;else if(!k)for(const z of j)y.add(z),y.size>=gP&&(T(Array.from(y)),y.clear());i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{i.current=null,x()},180);return}f()&&(s.current||(d()&&c(),i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>{i.current=null,f()&&h()},180)))}},recordSuppressedEventIds:(_,j)=>{const F=j?.queueRef,z=Number.isFinite(j?.maxQueueSize)?Math.max(1,Number(j?.maxQueueSize)):2048,M=Number.isFinite(j?.ttlMs)?Math.max(0,Number(j?.ttlMs)):null;for(const O of _){const Z=String(O||"").trim();!Z||l.current.has(Z)||(l.current.add(Z),F&&F.current.push(Z),M!==null&&window.setTimeout(()=>{l.current.delete(Z)},M))}if(F)for(;F.current.length>z;){const O=F.current.shift();O&&l.current.delete(O)}},clearRealtimePullDebounce:()=>{i.current!==null&&(window.clearTimeout(i.current),i.current=null),y.clear(),k=!1,C=null,S=!1}}}function LC(e){e.lastPushedTaskIds.current=new Set,e.lastPushedWatermarks.current=new Map,e.lastPushedTaskChangeKeys.current=new Map,e.lastPushedTaskRelationshipChangeKeys.current=new Map,e.lastPushedTaxonomyChangeKey.current="",e.lastPushedInitiativeIds.current=new Set,e.lastPushedInitiativeWatermarks.current=new Map,e.lastPushedWorkstreamIds.current=new Set,e.lastPushedWorkstreamWatermarks.current=new Map,e.lastPushedAiProfileIds.current=new Set,e.lastPushedAiProfileWatermarks.current=new Map,e.lastPushedAiProfileChangeKeys.current=new Map,e.lastPushedDocumentPaths.current=new Set,e.lastPushedDocumentWatermarks.current=new Map,e.lastPushedAssetPaths.current=new Set,e.lastPushedAssetWatermarks.current=new Map,e.baselineResetReason.current="repair-reset"}function kP(e){LC(e),e.lastPushedDocumentReviewSessionIds.current=new Set,e.lastPushedDocumentReviewSessionWatermarks.current=new Map,e.lastPushedDocumentReviewCommentIds.current=new Set,e.lastPushedDocumentReviewCommentWatermarks.current=new Map,e.lastPushedAnnotatedAttachmentSessionIds.current=new Set,e.lastPushedAnnotatedAttachmentSessionWatermarks.current=new Map,e.lastPushedTaskEventWatermarks.current=new Map}async function vP(e){const t=await globalThis.crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}function wP({currentWorkspaceId:e,workspaceCloudSyncEnabled:t,workspaceSyncPhase:r,workspaceLastPullAt:n,runtime:s,localServices:i,acquireWorkspaceSyncLease:l,releaseWorkspaceSyncLease:c,forceClearWorkspaceSyncLease:d,clearWorkspaceRetry:f,clearWorkspaceIssue:p,reportWorkspaceWindowContention:g,reportSyncEvent:h,persistWorkspaceSyncPatch:y,persistWorkspaceSyncWatermarksSnapshotBestEffort:k,buildWorkspaceSyncSignature:b,pullWorkspaceChangesFromCloud:C,pushWorkspaceChangesToCloud:S,cloudAuthConfigured:w,runtimeMode:T,isAuthenticated:E,checkAuthSession:x,isExecutionAuthorized:N=()=>!0,coordinatorGeneration:v=null}){const V=s.lastBootstrapPhase,_=s.repairMode,j=s.forceFullAiProfilePush,F=s.startupRepairRan,z=s.startupFullReconcileRan,M=s.fullReconcileInFlight,O=s.pullCursor,Z=s.attachBootstrapBaselineSignature,U=s.captureAttachBootstrapBaseline,ve=s.pendingSignature,te=s.pendingPushReplay,ce=s.lastPushedSignature;s.baselineResetReason;const Le=s.bootstrapPhaseStartedAtMs,Ie=s.bootstrapLastProgressAtMs,Ye=r==="provision-local"?"push":r==="attach-cloud"?"bootstrap":"pull";return{retryWorkspaceCloudSync:async()=>{if(!N())return!1;f();let Ae=Gk({cloudAuthConfigured:w,runtimeMode:T,workspaceCloudSyncEnabled:t,currentWorkspaceId:e,isAuthenticated:E});if(!Ae.allowed&&Ae.reason==="auth-required"){if(!await x())return h(e,{eventType:Ye,status:"error",errorMessage:"Manual sync retry blocked: sign in is required.",details:{source:"retry.blocked",reason:"auth-required",phase:r}}),!1;Ae=Gk({cloudAuthConfigured:w,runtimeMode:T,workspaceCloudSyncEnabled:t,currentWorkspaceId:e,isAuthenticated:!0})}if(!Ae.allowed)return h(e,{eventType:Ye,status:"error",errorMessage:`Manual sync retry blocked: ${Ae.reason}.`,details:{source:"retry.blocked",reason:Ae.reason,phase:r}}),!1;if(j.current=!0,r==="provision-local"){const q=b();return q?S(q,{forceAllAiProfiles:!0}):!1}const ye=te.current;if(r==="active"&&ye)return ve.current=ye.signature,S(ye.signature,{forceAllAiProfiles:ye.forceAllAiProfiles,repairMode:ye.repairMode});const Ne=await C();if(r==="attach-cloud")return Ne;const ae=b();if(ae){ve.current=ae;const q=await S(ae,{forceAllAiProfiles:j.current===!0});return Ne||q}return Ne},resetWorkspaceSyncCursorAndPull:async()=>{if(!N())return;if(!await l(e,"repair")&&(d(e),!await l(e,"repair"))){g("repair"),h(e,{eventType:"bootstrap",status:"error",errorMessage:"Manual sync repair blocked because another window is already syncing this workspace.",details:{source:"repair.blocked",reason:"lease-held",phase:r}});return}const ye=uP({workspaceSyncPhase:r,lastBootstrapPhase:V.current,workspaceLastPullAt:n}),Ne=ye==="provision-local",ae=ye==="active"||ye==="attach-cloud";f(),p();try{if(!t){h(e,{eventType:"bootstrap",status:"error",errorMessage:"Manual sync repair blocked because workspace sync is turned off.",details:{source:"repair.blocked",reason:"sync-disabled",phase:r}});return}let q=null;if(ye!=="provision-local")try{q=await i.prepareOutboxRecovery(e)}catch(we){h(e,{eventType:"bootstrap",status:"error",errorMessage:String(we?.message||"Blocked local changes could not enter recovery."),details:{source:"repair.local-recovery-blocked",phase:r}});return}if(Le.current=null,Ie.current=null,O.current=null,Z.current="",U.current=!1,ve.current="",ce.current="",j.current=!1,F.current=!1,z.current=!1,M.current=!1,Ne&&(kP(s),k()),_.current=!0,h(e,{eventType:"bootstrap",status:"success",errorMessage:"Manual sync repair started.",details:{source:"repair.started",phase:r,repairPhase:ye,lastBootstrapPhase:V.current}}),await y({phase:ye,pullCursor:null,startupFullReconcileCompletedAt:null,lastErrorMessage:null}),ye==="provision-local"){const we=b();if(!we)return;await S(we,{forceAllAiProfiles:!0,repairMode:!0});return}const W=await C({repairMode:!0,...q?.kind==="recovery"&&q.needsAuthoritativeRepair?{forceV3AuthoritativeRepair:!0,recoveryBatchId:q.recoveryBatchId}:{}});if(ye!=="active"&&ye!=="attach-cloud"||!W)return;ae&&(LC(s),k());const K=b();if(!K)return;if(ve.current=K,await S(K,{forceAllAiProfiles:!0,repairMode:!0})&&v!==null&&i.completeAuthoritativeRepair){const we=await i.completeAuthoritativeRepair({workspaceId:e,coordinatorGeneration:v,repairId:`repair-${globalThis.crypto.randomUUID()}`,stateSignatureSha256:await vP(K)});(!we.ok||we.data?.success!==!0)&&h(e,{eventType:"bootstrap",status:"error",statusCode:we.status,errorMessage:String(we.data?.error||"Authoritative repair could not settle coordinator recovery."),details:{source:"repair.coordinator-recovery-settlement-failed",phase:r,code:we.data?.code||null}})}}finally{_.current=!1,c(e)}}}}function bP({workspaceSyncPhase:e,forceCursorNull:t,currentCursor:r}){const n=e==="attach-cloud";return{bootstrap:n,cursor:n||t===!0?null:r,successEventType:n?"bootstrap":"pull"}}function SP({workspaceSyncPhase:e,forceCursorNull:t,repairMode:r,startupFullReconcileRan:n,pendingSignature:s,fallbackSignature:i,lastPushedSignature:l}){const c=e==="attach-cloud",d=c&&r===!0,f=s||i,p=!c&&f&&f!==l?f:null;return{successEventType:c?"bootstrap":"pull",shouldCaptureAttachBootstrapBaseline:c&&!d,shouldClearPendingSignature:c||p!==null,shouldRefreshReferenceSnapshots:c,shouldSeedWorkspaceSnapshotPushBaseline:c&&!d,shouldScheduleStartupFullReconcile:!t&&!c&&!n,deferredPushSignature:p}}function OC(e){if(typeof e!="string")return;const t=e.trim();return t.length>0?t:void 0}function AP(e){return OC(e)??null}function CP(e){if(e==null||e==="")return null;const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(1,Math.floor(t)):null}function IP(e){if(e==null||e==="")return null;const t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.floor(t):null}function _P(e,t,r){if(e===void 0||!e||typeof e!="object"||Array.isArray(e))return;const n=e,s=["canonicalFingerprint","contractVersion","domain","entityId","entityRevision","lifecycleRevision","mutationKind","sequence"],i=Object.keys(n).sort(),l=new Set(["create","metadata-update","append-comment","archive","unarchive"]);if(!(i.length!==s.length||i.some((c,d)=>c!==s[d])||n.contractVersion!==3||n.domain!==t||n.entityId!==r||typeof n.mutationKind!="string"||!l.has(n.mutationKind)||typeof n.sequence!="string"||!/^[1-9]\d*$/.test(n.sequence)||typeof n.entityRevision!="string"||!/^\d+$/.test(n.entityRevision)||typeof n.lifecycleRevision!="string"||!/^\d+$/.test(n.lifecycleRevision)||n.entityRevision==="0"||n.mutationKind==="create"&&(n.entityRevision!=="1"||n.lifecycleRevision!=="0")||(n.mutationKind==="archive"||n.mutationKind==="unarchive")&&n.lifecycleRevision==="0"||typeof n.canonicalFingerprint!="string"||!/^[a-f0-9]{64}$/.test(n.canonicalFingerprint)))return n}function TP(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;const r=e,n=String(r.id||"").trim();if(!n)return null;const s=_P(r.durableRevision,"initiative",n);if(Object.prototype.hasOwnProperty.call(r,"durableRevision")&&!s)throw new Error("Initiative durable revision is invalid.");const i=Bf(r.comments);return{id:n,referenceNumber:CP(r.referenceNumber),referenceLabel:OC(r.referenceLabel),title:String(r.title||"").trim(),description:typeof r.description=="string"?r.description:null,ownerId:AP(r.ownerId),...i?{comments:i}:{},createdAt:String(r.createdAt||t||"").trim(),updatedAt:String(r.updatedAt||t||r.createdAt||"").trim(),order:IP(r.order),attachments:Wf(r.attachments),isArchived:!!r.isArchived,...s?{durableRevision:s}:{}}}function xP(e){const t=TP(e);if(!t||!t.createdAt||!t.updatedAt)throw new Error("Initiative is missing canonical sync identity or watermarks.");return{...t,attachments:VR(e.attachments)}}const BC=["create","metadata-update","append-comment","archive","unarchive"],RP={coverageProfileId:"covered-metadata",coverageVersion:1,projections:[{projectionId:"initiative/full-v1",domain:"initiative",schemaVersion:1,mutationKinds:BC,fields:["id","referenceNumber","referenceLabel","title","description","ownerId","comments","attachments","order","createdAt","updatedAt","isArchived"],dependencies:[],operationAtomic:!0}]};function Vk(e){return Array.isArray(e)?e.every(Vk):!e||typeof e!="object"?!0:Object.entries(e).every(([t,r])=>t!=="content"&&t!=="contentBase64"&&Vk(r))}function WC(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return typeof t.coverageDigest=="string"&&/^[a-f0-9]{64}$/.test(t.coverageDigest)&&$a({coverageProfileId:t.coverageProfileId,coverageVersion:t.coverageVersion,projections:t.projections})===$a(RP)}function $C(e){const t=n=>/^\d+$/.test(String(n??""));if(e.projection!=="initiative/full-v1"||e.domain!=="initiative"||!e.entityId||!BC.includes(e.mutationKind)||!t(e.sequence)||!t(e.entityRevision)||!t(e.lifecycleRevision)||!/^[a-f0-9]{64}$/.test(e.payloadFingerprint)||!Vk(e.payload)||e.contentSha256!==void 0||e.sizeBytes!==void 0)throw new Error("Workspace sync v3 initiative entry is invalid.");const r=xP(e.payload);if(r.id!==e.entityId||$a(r)!==$a(e.payload))throw new Error("Workspace sync v3 initiative payload is not canonical.")}const jP={getLocalProjection:QA,applyLocalProjection:XA,pullFeed:ZA,pullInitiativeRepair:sC};function PP(e,t){const r=e.data?.projection;return!e.ok||e.data?.success!==!0||e.data?.contractVersion!==3||e.data?.workspaceId!==t||!r||r.owner!=="v2"&&r.owner!=="v3"||!/^\d+$/.test(r.epoch)?null:r}function If(e){return e.data?.result?.projection||e.data?.projection||null}function fl(e,t,r){return{kind:"transient-failure",status:e.status,retryAfterMs:e.retryAfterMs,error:String(e.data?.error||r),excludeInitiativesFromV2:t==="v3"}}function nh(e){return e===0||e===429||e>=500}function Fb(e,t){const r=e.data,n=r.coverage,s=r?.repair;if(e.status!==409||r?.workspaceId!==t||r?.protocolVersion!==3||r.legacyInitiativePushDisabled!==!0||r.code!=="CURSOR_EXPIRED"&&r.code!=="COVERAGE_CHANGED"||!s||!WC(n)||s.mode!=="authoritative-covered-projection-snapshot"||!/^\d+$/.test(String(s.snapshotSequence||""))||!Array.isArray(s.entries)||typeof s.hasMore!="boolean"||s.hasMore!==!!s.nextRepairCursor||typeof s.resumeCursor!="string"||!s.resumeCursor)return null;try{s.entries.forEach($C)}catch{return null}return s}function EP(e,t){const r=e.data;if(!e.ok||r?.protocolVersion!==3||r?.workspaceId!==t||r.legacyInitiativePushDisabled!==!0||!Array.isArray(r.entries)||typeof r.nextCursor!="string"||!r.nextCursor||typeof r.hasMore!="boolean"||!WC(r.coverage)||!/^\d+$/.test(String(r.cycleHighWatermark||""))||!/^\d+$/.test(String(r.lastScannedSequence||""))||!r.diagnostics||r.diagnostics.coveredCount!==r.entries.length||r.diagnostics.scannedCount<r.entries.length)return null;try{r.entries.forEach($C)}catch{return null}return r}async function NP(e){let t=e.projection,r=t.repair?.cursor||null;const n=new Set;for(;;){const s=await e.dependencies.pullInitiativeRepair(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,cursor:r,limit:100});if(!s.ok)return s.status===401?{kind:"auth-failure",status:401,excludeInitiativesFromV2:!1}:fl(s,"v2","Initiative fallback repair failed.");const i=s.data;if(i?.success!==!0||i.workspaceId!==e.workspaceId||!/^\d+$/.test(String(i.snapshotSequence||""))||!Array.isArray(i.entries)||typeof i.hasMore!="boolean"||i.hasMore!==!!i.nextRepairCursor)return{kind:"transient-failure",status:502,error:"Initiative fallback repair returned an invalid page.",excludeInitiativesFromV2:!1};const l=await e.dependencies.applyLocalProjection(e.workspaceId,{kind:"fallback-repair",epoch:t.epoch,previousCursor:r,page:{snapshotSequence:String(i.snapshotSequence),entries:i.entries,hasMore:i.hasMore,nextRepairCursor:i.nextRepairCursor||null}}),c=If(l);if(!l.ok||!c)return fl(l,"v3","Initiative fallback repair could not be staged locally.");if(t=c,!i.hasMore)return t.owner==="v2"?{kind:"v2-fallback",excludeInitiativesFromV2:!1}:{kind:"transient-failure",status:502,error:"Initiative fallback repair did not switch ownership.",excludeInitiativesFromV2:!0};const d=String(i.nextRepairCursor||"");if(!d||d===r||n.has(d))return{kind:"transient-failure",status:502,error:"Initiative fallback repair made no progress.",excludeInitiativesFromV2:!1};n.add(d),r=d}}async function id(e){return NP(e)}async function sh(e){const t=await e.dependencies.applyLocalProjection(e.workspaceId,{kind:"rollback",epoch:e.projection.epoch}),r=If(t);return!t.ok||!r||r.owner!=="v2"?fl(t,e.projection.owner,"Initiative activation rollback is not ready."):{kind:"transient-failure",status:409,error:"Local initiative changes must complete v2 synchronization before v3 activation can retry.",excludeInitiativesFromV2:!1}}async function Kk(e){const t={...jP,...e.dependencies},r={...t,applyLocalProjection:async(...l)=>{const c=await t.applyLocalProjection(...l);return c.ok&&c.data?.success!==!1&&"page"in l[1]&&e.onChangesApplied?.(l[1].page.entries.length),c}},n=await r.getLocalProjection(e.workspaceId),s=PP(n,e.workspaceId);if(!s)return fl(n,"v2","Local initiative projection state is unavailable.");if(s.owner==="v3"&&s.repair?.resumeCursor.startsWith("v2-fallback:"))return id({...e,projection:s,dependencies:r});if(!e.activationEnabled)return s.owner==="v3"?id({...e,projection:s,dependencies:r}):s.repair?sh({workspaceId:e.workspaceId,projection:s,dependencies:r}):{kind:"v2-fallback",excludeInitiativesFromV2:!1};let i=s;for(;i.owner==="v2"||i.repair;){const l=await r.pullFeed(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,repairCursor:i.repair?.cursor||null,limit:100});if(l.status===401)return{kind:"auth-failure",status:401,excludeInitiativesFromV2:!1};if(l.status===404||l.status!==409&&!nh(l.status))return i.owner==="v3"?id({...e,projection:i,dependencies:r}):sh({workspaceId:e.workspaceId,projection:i,dependencies:r});if(nh(l.status))return fl(l,"v2","Workspace sync v3 feed is temporarily unavailable.");const c=Fb(l,e.workspaceId);if(!c)return i.owner==="v3"?id({...e,projection:i,dependencies:r}):sh({workspaceId:e.workspaceId,projection:i,dependencies:r});const d=await r.applyLocalProjection(e.workspaceId,{kind:"repair",epoch:i.epoch,previousCursor:i.repair?.cursor||null,page:c}),f=If(d);if(!d.ok||!f)return sh({workspaceId:e.workspaceId,projection:i,dependencies:r});const p=i.repair?.cursor||null;if(i=f,i.owner==="v2"&&i.repair?.cursor===p)return{kind:"transient-failure",status:502,error:"Initiative repair made no local progress.",excludeInitiativesFromV2:!1}}for(;i.owner==="v3";){const l=await r.pullFeed(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,cursor:i.opaqueCursor,limit:100});if(l.status===401)return{kind:"auth-failure",status:401,excludeInitiativesFromV2:!0};if(l.status===404||l.status!==409&&!l.ok&&!nh(l.status))return id({...e,projection:i,dependencies:r});if(nh(l.status))return fl(l,"v3","Workspace sync v3 feed is temporarily unavailable.");if(l.status===409){const p=Fb(l,e.workspaceId);if(!p)return id({...e,projection:i,dependencies:r});const g=await r.applyLocalProjection(e.workspaceId,{kind:"repair",epoch:i.epoch,previousCursor:null,page:p}),h=If(g);if(!g.ok||!h)return fl(g,"v3","Initiative repair could not be applied locally.");if(i=h,i.repair)return Kk({...e,dependencies:t});continue}const c=EP(l,e.workspaceId);if(!c||!i.opaqueCursor)return id({...e,projection:i,dependencies:r});const d=await r.applyLocalProjection(e.workspaceId,{kind:"delta",epoch:i.epoch,previousCursor:i.opaqueCursor,page:c}),f=If(d);if(!d.ok||!f)return fl(d,"v3","Workspace sync v3 feed could not be applied locally.");if(f.owner!=="v3"||f.repair||f.opaqueCursor!==c.nextCursor)return{kind:"transient-failure",status:502,error:"Workspace sync v3 feed did not commit its exact cursor.",excludeInitiativesFromV2:!0};if(!c.hasMore)return{kind:"v3-active",excludeInitiativesFromV2:!0};if(f.opaqueCursor===i.opaqueCursor)return{kind:"transient-failure",status:502,error:"Workspace sync v3 feed made no local progress.",excludeInitiativesFromV2:!0};i=f}return{kind:"v2-fallback",excludeInitiativesFromV2:!1}}const vd=Object.freeze([]),MP=960*1e3,DP="coverage/task-planning-metadata-v1",LP={getLocalProjection:eC,applyLocalProjection:tC,pullFeed:JA,pullFallbackRepair:oC,getLocalTaskCommentAudit:rC,pullTaskCommentAudit:aC,applyLocalTaskCommentAudit:nC};function Bh(e){return yl(e)?.coverage||null}function hl(e){return e.owner!=="v3"?vd:yl(e)?.excludedProjections||vd}function Yi(e,t){return e.coverageProfileId===t.coverageProfileId&&e.coverageVersion===t.coverageVersion&&e.coverageDigest===t.coverageDigest}function OP(e,t){return Yi(t,kn)?e:{...e,coverage:t}}function Tu(e,t,r,n){return Yi(n,kn)?e.applyLocalProjection(t,r):e.applyLocalProjection(t,r,n)}function FC(e){return!!(e&&e.coverageId===DP&&(e.owner==="v2"||e.owner==="v3")&&yl(e)&&typeof e.coverageRepairRequired=="boolean"&&/^\d+$/.test(e.epoch)&&(e.repair===null||typeof e.repair=="object"&&/^\d+$/.test(String(e.repair.epoch||""))&&e.repair.snapshotId&&/^\d+$/.test(String(e.repair.snapshotSequence||""))&&typeof e.repair.resumeCursor=="string"&&(e.repair.cursor===null||typeof e.repair.cursor=="string")))}function BP(e,t){const r=e.data?.projection;return!e.ok||e.data?.success!==!0||e.data?.contractVersion!==3||e.data?.workspaceId!==t||!FC(r)?null:r}function xu(e,t){const r=e.data?.result?.projection||e.data?.projection;return e.ok&&e.data?.success===!0&&e.data?.contractVersion===3&&e.data?.workspaceId===t&&FC(r)?r:null}function ef(e){return e.ok&&e.data?.success===!0&&e.data?.result?.state==="invalidated"}function uo(e,t,r){return{kind:"transient-failure",status:e.status,retryAfterMs:e.retryAfterMs,error:String(e.data?.error||r),...e.data?.causeCode?{causeCode:String(e.data.causeCode)}:{},...e.data?.causeAssetId?{causeAssetId:String(e.data.causeAssetId)}:{},excludedProjections:hl(t)}}function us(e,t){return{kind:"transient-failure",status:502,error:t,excludedProjections:hl(e)}}function WP(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return!1;const n=e;return n.success===!0&&n.contractVersion===3&&n.workspaceId===t&&n.previousCursor===r&&Array.isArray(n.entries)&&typeof n.hasMore=="boolean"&&n.hasMore===!!n.nextCursor}async function $P(e){const t=await e.dependencies.getLocalTaskCommentAudit(e.workspaceId),r=t.ok&&t.data?.success===!0&&t.data.contractVersion===3&&t.data.workspaceId===e.workspaceId&&(t.data.cursor===null||t.data.cursor===void 0||typeof t.data.cursor=="string")?t.data.cursor||null:void 0,n=t.data?.nextSweepAt==null?null:String(t.data.nextSweepAt);if(r===void 0)return uo(t,e.projection,"Local task comment audit state is unavailable.");const s=Date.now(),i=Date.parse(n||""),l=Number.isFinite(i)&&i>s&&i<=s+MP;if(r===null&&l)return null;const c=await e.dependencies.pullTaskCommentAudit(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,cursor:r,limit:50});if(c.status===401)return{kind:"auth-failure",status:401,excludedProjections:hl(e.projection)};if(!c.ok||!WP(c.data,e.workspaceId,r))return uo(c,e.projection,"Cloud task comment audit is temporarily unavailable.");const d=await e.dependencies.applyLocalTaskCommentAudit(e.workspaceId,c.data),f=d.data?.result,p=f?.stale===!0&&f.previousCursor===c.data.nextCursor&&f.nextCursor===c.data.nextCursor;return!d.ok||d.data?.success!==!0||d.data.contractVersion!==3||d.data.workspaceId!==e.workspaceId||!p&&(f?.previousCursor!==r||f?.nextCursor!==c.data.nextCursor)?uo(d,e.projection,"Task comment audit could not be applied locally."):(p||e.onChangesApplied?.(Math.max(0,Number(f?.reconciliationsQueued)||0)+Math.max(0,Number(f?.activityEventsApplied)||0)),null)}function tf(e){return e===0||e===429||e>=500}function Pg(e,t){if(!e||typeof e!="object"||Array.isArray(e))return!1;const r=e;return r.coverageProfileId===t.coverageProfileId&&r.coverageVersion===t.coverageVersion&&r.coverageDigest===t.coverageDigest}function Kv(e,t,r){if(!e||typeof e!="object"||Array.isArray(e))return!1;const n=e;return n.success===!0&&n.protocolVersion===3&&n.workspaceId===t&&Pg(n.coverage,r)&&!!n.snapshotId&&/^\d+$/.test(String(n.snapshotSequence||""))&&Number.isFinite(Date.parse(String(n.expiresAt||"")))&&Array.isArray(n.entries)&&typeof n.hasMore=="boolean"&&n.hasMore===!!n.nextRepairCursor&&!!n.resumeCursor&&!!n.diagnostics&&n.diagnostics.returnedEntries===n.entries.length}function UC(e,t,r){const n=e.data,s=String(n?.code||"unknown");let i="repair envelope is incompatible";n?.protocolVersion!==3||n?.workspaceId!==t?i="protocol or workspace scope is incompatible":["CURSOR_EXPIRED","COVERAGE_CHANGED","EXPLICIT_REPAIR"].includes(s)?Pg(n.coverage,r)?n.repairMode!=="authoritative-covered-projection-snapshot"?i="repair mode is incompatible":Ov(n.peerCapability,r)?Bv(n.legacyV2Boundary,r)?Kv(n.repair,t,r)||(i="repair page is incompatible"):i="legacy v2 boundary attestation is incompatible":i="peer capability attestation is incompatible":i="coverage attestation is incompatible":i="repair code is unsupported";const l=String(n?.error||"").trim();return`Cloud combined workspace sync returned an invalid repair response (${s}; ${i}).`+(l?` Cloud error: ${l}`:"")}function oh(e,t,r){const n=e.data;return e.status===409&&n?.protocolVersion===3&&n.workspaceId===t&&(n.code==="CURSOR_EXPIRED"||n.code==="COVERAGE_CHANGED"||n.code==="EXPLICIT_REPAIR")&&Pg(n.coverage,r)&&n.repairMode==="authoritative-covered-projection-snapshot"&&Ov(n.peerCapability,r)&&Bv(n.legacyV2Boundary,r)&&Kv(n.repair,t,r)?n.repair:null}function FP(e,t,r){const n=e.data;return e.ok&&n?.success===!0&&n.protocolVersion===3&&n.workspaceId===t&&Pg(n.coverage,r)&&Ov(n.peerCapability,r)&&Bv(n.legacyV2Boundary,r)&&Array.isArray(n.entries)&&typeof n.nextCursor=="string"&&n.nextCursor&&typeof n.hasMore=="boolean"&&/^\d+$/.test(String(n.cycleHighWatermark||""))&&/^\d+$/.test(String(n.lastScannedSequence||""))&&n.diagnostics&&n.diagnostics.coveredCount===n.entries.length&&n.diagnostics.scannedCount>=n.entries.length?n:null}function UP(e){const t=e.data&&typeof e.data=="object"?e.data.peerCapability:void 0,r=Array.isArray(t?.missingPrerequisites)?String(t.missingPrerequisites[0]||"").trim():"";return r?`Cloud combined workspace sync prerequisite is not ready (${r}).`:"Cloud combined workspace sync capability attestation is missing or incompatible."}function zP(e,t,r){const n=String(e.data?.code||"").trim();return n&&!["CURSOR_EXPIRED","COVERAGE_CHANGED","EXPLICIT_REPAIR"].includes(n)?UC(e,t,r):UP(e)}function HP(e){return e.data?.success!==!1?!1:e.status===410&&e.data.code==="WORKSPACE_SYNC_V3_COMBINED_REPAIR_SNAPSHOT_UNAVAILABLE"||e.status===400&&e.data.code==="INVALID_SYNC_V3_REPAIR_CURSOR"}async function ih(e){let t=e.projection;const r=Bh(t);if(!r)return us(t,"Persisted combined workspace sync coverage is unsupported.");let n=t.repair?.resumeCursor.startsWith("v2-fallback:")?t.repair.cursor:null;const s=new Set;let i=!1;for(;;){const l=await e.dependencies.pullFallbackRepair(e.resolveCloudAuthUrl,OP({workspaceId:e.workspaceId,cursor:n,limit:100},r));if(l.status===401)return{kind:"auth-failure",status:401,excludedProjections:hl(t)};if(l.status===410&&n&&!i&&l.data?.success===!1&&l.data.code==="WORKSPACE_SYNC_V3_COMBINED_REPAIR_SNAPSHOT_UNAVAILABLE"){i=!0,n=null,s.clear();continue}if(!l.ok)return uo(l,t,"Combined v2 fallback repair failed.");const c=Kv(l.data,e.workspaceId,r)&&eR(l.data.legacyV2Boundary)?l.data:null;if(!c)return us(t,"Combined v2 fallback repair returned an invalid page.");const d=await Tu(e.dependencies,e.workspaceId,{kind:"fallback-repair",epoch:t.epoch,previousCursor:n,page:c},r),f=xu(d,e.workspaceId);if(!d.ok||!f)return uo(d,t,"Combined v2 fallback repair could not be applied locally.");if(t=f,!c.hasMore)return t.owner==="v2"&&!t.repair?{kind:"v2-fallback",excludedProjections:vd}:us(t,"Combined v2 fallback repair did not release v3 ownership.");const p=String(c.nextRepairCursor||"");if(!p||p===n||s.has(p)||t.owner!=="v3"||t.repair?.cursor!==p||!t.repair.resumeCursor.startsWith("v2-fallback:"))return us(t,"Combined v2 fallback repair made no progress.");s.add(p),n=p}}function Ub(e){return qk(e,!1)}async function qk(e,t){const r={...LP,...e.dependencies},n={...r,applyLocalProjection:async(...C)=>{const S=await r.applyLocalProjection(...C);return S.ok&&S.data?.success!==!1&&!ef(S)&&e.onChangesApplied?.(C[1].page.entries.length),S}},s=e.coverage||kn,i=yl(s);if(!i)return{kind:"transient-failure",status:502,error:"Requested combined workspace sync coverage is unsupported.",excludedProjections:vd};const l=await n.getLocalProjection(e.workspaceId,s),c=BP(l,e.workspaceId);if(!c)return{kind:"transient-failure",status:l.status,retryAfterMs:l.retryAfterMs,error:String(l.data?.error||"Local combined projection state is unavailable."),excludedProjections:vd};if(c.owner==="v3"&&c.repair?.resumeCursor.startsWith("v2-fallback:"))return ih({...e,projection:c,dependencies:n});if(!e.activationEnabled)return c.owner==="v3"?ih({...e,projection:c,dependencies:n}):{kind:"v2-fallback",excludedProjections:vd};let d=c,f=!1,p=!1,g=t;const h=Bh(d);if(!h)return us(d,"Persisted combined workspace sync coverage is unsupported.");if(d.coverageRepairRequired||d.owner==="v3"&&!d.repair&&!Yi(h,s)){const C=await n.pullFeed(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,...d.owner==="v3"&&d.opaqueCursor?{cursor:d.opaqueCursor}:{},limit:100,...Yi(s,kn)?{}:{coverage:s}});if(C.status===401)return{kind:"auth-failure",status:401,excludedProjections:hl(d)};if(tf(C.status))return uo(C,d,"Combined workspace sync coverage upgrade is temporarily unavailable.");const S=oh(C,e.workspaceId,s);if(!S)return us(d,"Cloud combined workspace sync did not provide the required coverage upgrade repair.");const w=await Tu(n,e.workspaceId,{kind:"repair",epoch:d.epoch,previousCursor:null,page:S,...e.recoveryBatchId?{recoveryBatchId:e.recoveryBatchId}:{}},s),T=xu(w,e.workspaceId),E=T?Bh(T):null;if(T&&ef(w)){if(g)return us(T,"A refreshed combined repair snapshot still predates authoritative local state.");d=T,p=!0,g=!0}else if(!w.ok||!T||!E||(S.hasMore?!T.repair||T.repair.cursor!==S.nextRepairCursor||!Yi(E,h):T.coverageRepairRequired||T.repair!==null||!Yi(E,s)))return uo(w,d,"Combined workspace sync coverage upgrade could not be applied locally.");d=T,f=!!(e.recoveryBatchId&&!d.repair)}if(e.forceAuthoritativeRepair&&!f&&d.owner==="v3"&&!d.repair){const C=await n.pullFeed(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,limit:100,forceRepair:!0,...Yi(s,kn)?{}:{coverage:s}});if(C.status===401)return{kind:"auth-failure",status:401,excludedProjections:hl(d)};if(tf(C.status))return uo(C,d,"Combined workspace sync authoritative recovery is temporarily unavailable.");const S=oh(C,e.workspaceId,s);if(!S)return us(d,"Cloud combined workspace sync did not provide the requested authoritative repair.");const w=await Tu(n,e.workspaceId,{kind:"repair",epoch:d.epoch,previousCursor:null,page:S,...e.recoveryBatchId?{recoveryBatchId:e.recoveryBatchId}:{}},s),T=xu(w,e.workspaceId);if(!w.ok||!T)return uo(w,d,"Combined workspace sync authoritative recovery could not be applied locally.");if(d=T,ef(w)){if(g)return us(d,"A refreshed combined repair snapshot still predates authoritative local state.");p=!0,g=!0}}let y=!1,k=!1;for(;d.owner==="v2"||d.repair||p;){const C=y||p?null:d.repair?.cursor||null,S=await n.pullFeed(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,...y||p?{forceRepair:!0}:{repairCursor:C},limit:100,...Yi(s,kn)?{}:{coverage:s}});if(S.status===401)return{kind:"auth-failure",status:401,excludedProjections:hl(d)};if(C&&!k&&HP(S)){k=!0,y=!0;continue}if(tf(S.status))return uo(S,d,"Combined workspace sync feed is temporarily unavailable.");const w=oh(S,e.workspaceId,s);if(!w)return us(d,zP(S,e.workspaceId,s));const T=await Tu(n,e.workspaceId,{kind:"repair",epoch:d.epoch,previousCursor:C,page:w,...e.recoveryBatchId?{recoveryBatchId:e.recoveryBatchId}:{}},s),E=xu(T,e.workspaceId);if(!T.ok||!E)return uo(T,d,"Combined workspace sync repair could not be applied locally.");if(d=E,y=!1,p=!1,ef(T)){if(g)return us(d,"A refreshed combined repair snapshot still predates authoritative local state.");g=!0,p=!0;continue}if(d.repair?.cursor===C)return us(d,"Combined workspace sync repair made no local progress.")}const b=Bh(d);if(d.owner!=="v3"||!b||!Yi(b,s))return us(d,"Combined workspace sync repair did not activate the requested coverage.");if(e.recoveryBatchId)return{kind:"v3-active",excludedProjections:i.excludedProjections};for(;d.owner==="v3";){const C=await n.pullFeed(e.resolveCloudAuthUrl,{workspaceId:e.workspaceId,cursor:d.opaqueCursor,limit:100,...Yi(s,kn)?{}:{coverage:s}});if(C.status===401)return{kind:"auth-failure",status:401,excludedProjections:hl(d)};if(C.status===404||C.status!==409&&!C.ok&&!tf(C.status))return ih({...e,projection:d,dependencies:n});if(tf(C.status))return uo(C,d,"Combined workspace sync feed is temporarily unavailable.");if(C.status===409){const E=oh(C,e.workspaceId,s);if(!E)return us(d,UC(C,e.workspaceId,s));const x=await Tu(n,e.workspaceId,{kind:"repair",epoch:d.epoch,previousCursor:null,page:E,...e.recoveryBatchId?{recoveryBatchId:e.recoveryBatchId}:{}},s),N=xu(x,e.workspaceId);if(!x.ok||!N)return uo(x,d,"Combined workspace sync repair could not be applied locally.");if(d=N,ef(x))return g?us(d,"A refreshed combined repair snapshot still predates authoritative local state."):qk({...e,forceAuthoritativeRepair:!0},!0);if(d.repair)return qk({...e,dependencies:r},g);continue}const S=FP(C,e.workspaceId,s);if(!S||!d.opaqueCursor)return ih({...e,projection:d,dependencies:n});const w=await Tu(n,e.workspaceId,{kind:"delta",epoch:d.epoch,previousCursor:d.opaqueCursor,page:S},s),T=xu(w,e.workspaceId);if(!w.ok||!T)return uo(w,d,"Combined workspace sync page could not be applied locally.");if(T.owner!=="v3"||T.repair||T.opaqueCursor!==S.nextCursor)return us(d,"Combined workspace sync feed did not commit its exact v3 cursor.");if(!S.hasMore)return await $P({resolveCloudAuthUrl:e.resolveCloudAuthUrl,workspaceId:e.workspaceId,projection:T,dependencies:n,onChangesApplied:e.onChangesApplied})||{kind:"v3-active",excludedProjections:i.excludedProjections};if(T.opaqueCursor===d.opaqueCursor)return us(d,"Combined workspace sync feed made no local progress.");d=T}return{kind:"v2-fallback",excludedProjections:vd}}var GP={};async function zC(e){const t=e.remoteServices,r=e.localServices.applyV2Batch,n=await t.pullWorkspaceContent({workspaceId:e.workspaceId,requests:[{kind:"asset",assetId:e.assetId}],previousCursor:null}),s=n.transferReceipt;let i=!1;try{if(!n.ok)return{success:!1,error:`Workspace attachment asset hydration failed (${n.status||0}).`};const l=n.data||{};if((l.missing?.length||0)>0||(l.remaining?.length||0)>0)return{success:!1,error:`Workspace attachment asset is unavailable in cloud content: ${e.assetId}`};const c=Array.isArray(l.changes)?l.changes:[],d=c.filter(w=>(w.op==="document-upsert"||w.op==="asset-upsert")&&String(w.assetId||"").trim()===e.assetId);if(c.length!==1||d.length!==1)return{success:!1,error:`Workspace attachment asset hydration returned an unexpected payload: ${e.assetId}`};try{await Lh(d[0],typeof process<"u"?GP?.TASKFORCE_SYNC_KEY:void 0)}catch{return{success:!1,error:`Workspace attachment asset hydration decryption failed: ${e.assetId}`}}const f=Array.isArray(l.contentMetadata)?l.contentMetadata:[],p=d[0].op==="document-upsert"?"document":"asset",g=f.filter(w=>w.kind===p&&w.assetId===e.assetId&&w.path===d[0].path);if(f.length!==1||g.length!==1)return{success:!1,error:`Workspace attachment asset hydration metadata is unavailable: ${e.assetId}`};const h=g[0],y=d[0].op==="document-upsert"?await Qh("document",d[0].content):await Qh("asset",d[0].contentBase64);if(y.sha256!==h.sha256.toLowerCase()||y.sizeBytes!==h.sizeBytes)return{success:!1,error:`Workspace attachment asset hydration verification failed: ${e.assetId}`};const k=s?t.buildV2ApplyCompletionGroup({workspaceId:e.workspaceId,previousCursor:null,nextCursor:null,receipts:[s]}):void 0;if(s&&!k)return{success:!1,error:"Workspace attachment asset hydration could not bind its transfer to local apply."};const b=k?await r(e.workspaceId,d,{completionGroup:k}):await r(e.workspaceId,d);if(!b.ok)return{success:!1,error:`Workspace attachment asset hydration apply failed (${b.status||0}).`};i=!0;const C=b.data&&typeof b.data=="object"?b.data:{},S=Array.isArray(C.emittedEventIds)?C.emittedEventIds.map(w=>String(w||"").trim()).filter(Boolean):[];return{success:!0,appliedChanges:d.length,emittedEventIds:S}}finally{s&&!i&&await t.abandonTransferReceipts({workspaceId:e.workspaceId,receipts:[s],errorCode:"WORKSPACE_SYNC_V3_ATTACHMENT_HYDRATION_NOT_COMMITTED"})}}function VP(e){return e.causeCode==="TASK_ATTACHMENT_ASSET_NOT_READY"&&e.causeAssetId?e.causeAssetId:e.status!==409?null:/^Task attachment asset is unavailable because it has not reached this runtime: ([A-Za-z0-9._:-]+)$/.exec(String(e.error||""))?.[1]||null}function KP(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e.repair;return t&&typeof t=="object"&&!Array.isArray(t)?t:e}function zb(e){return e.kind==="delta"?String(e.page.nextCursor||"")||null:e.page.hasMore===!0?String(e.page.nextRepairCursor||"")||null:e.kind==="repair"&&String(e.page.resumeCursor||"")||null}function qP(e){const t=new WeakMap,r=new Set,n=f=>{const p=KP(f.data);return f.transferReceipt&&(r.add(f.transferReceipt),p&&t.set(p,f.transferReceipt)),f},s=(f,p)=>{const g=t.get(f);if(!g)return;const h=e.remoteServices.buildV3ApplyCompletionGroup({workspaceId:e.workspaceId,apply:p,receipts:[g]});if(!h)throw new Error("A v3 sync transfer receipt did not produce an apply completion group.");return h},i=async f=>{try{await e.remoteServices.abandonTransferReceipts({workspaceId:e.workspaceId,receipts:f,errorCode:gb})}catch{await e.remoteServices.abandonTransferReceipts({workspaceId:e.workspaceId,receipts:f,errorCode:gb})}},l=async f=>{const p=t.get(f);p&&(await i([p]),t.delete(f),r.delete(p))},c=async(f,p,g)=>{let h=!1;try{const y=s(f,p),k=await g(y);if(y&&(!k||typeof k!="object"||!("ok"in k)||k.ok!==!0))h=!0,await l(f);else if(y){const b=t.get(f);t.delete(f),b&&r.delete(b)}return k}catch(y){throw h||await l(f),y}};return{abandonPendingReceipts:async()=>{if(r.size===0)return;const f=Array.from(r);await i(f);for(const p of f)r.delete(p)},initiative:{getLocalProjection:e.localServices.readInitiativeProjection,applyLocalProjection:(f,p)=>{if(p.kind==="rollback")return e.localServices.applyInitiativeProjection(f,p);const g={projection:"initiative",kind:p.kind,epoch:p.epoch,previousCursor:p.previousCursor,nextCursor:zb({kind:p.kind,page:p.page})};return c(p.page,g,h=>e.localServices.applyInitiativeProjection(f,p,h?{completionGroup:h}:void 0))},pullFeed:async(f,p)=>n(await e.remoteServices.pullInitiativeFeed(p)),pullInitiativeRepair:async(f,p)=>n(await e.remoteServices.pullInitiativeRepair(p))},combined:{getLocalProjection:e.localServices.readCombinedProjection,applyLocalProjection:(f,p,g)=>{const h={projection:"combined",kind:p.kind,epoch:p.epoch,previousCursor:p.previousCursor,nextCursor:zb({kind:p.kind,page:p.page})};return c(p.page,h,y=>e.localServices.applyCombinedProjection(f,p,g,y?{completionGroup:y}:void 0))},getLocalTaskCommentAudit:e.localServices.readTaskCommentAuditCursor,applyLocalTaskCommentAudit:(f,p)=>{const g={projection:"task-comment-audit",kind:"audit",previousCursor:p.previousCursor,nextCursor:p.nextCursor};return c(p,g,h=>e.localServices.applyTaskCommentAuditPage(f,p,h?{completionGroup:h}:void 0))},pullFeed:async(f,p)=>n(await e.remoteServices.pullCombinedFeed(p)),pullFallbackRepair:async(f,p)=>n(await e.remoteServices.pullCombinedRepair(p)),pullTaskCommentAudit:async(f,p)=>n(await e.remoteServices.pullTaskCommentAudit(p))}}}function YP({cloudAuthConfigured:e,runtimeMode:t,initiativeFeedActivationEnabled:r,combinedFeedActivationEnabled:n,combinedFeedCoverage:s,workspaceCloudSyncEnabled:i,currentWorkspaceId:l,workspaceSyncPhase:c,isAuthenticated:d,checkAuthSession:f,resolveCloudAuthUrl:p,ensureCloudWorkspaceReadyForSync:g,ensureWorkspaceSyncReady:h,handleSyncAuthFailure:y,clearWorkspaceRetry:k,clearWorkspaceIssue:b,isWorkspaceRetryPending:C,isDurableRecoveryBlockingOrdinaryPush:S,isExecutionAuthorized:w=()=>!0,scheduleWorkspaceSyncRetry:T,persistWorkspaceSyncPatchSafely:E,persistWorkspaceSyncPatchBestEffort:x,persistWorkspaceSyncWatermarksSnapshotBestEffort:N,refreshWorkspaceAiProfilePushBaselineFromPersistence:v,reportSyncEvent:V,acquireWorkspaceSyncLease:_,releaseWorkspaceSyncLease:j,recordWorkspaceSyncCompletion:F,reportWorkspaceWindowContention:z,refreshWorkspaceSyncMarkdownDocumentsSnapshot:M,refreshWorkspaceSyncAiProfilesSnapshot:O,refreshWorkspaceSyncAssetsSnapshot:Z,refreshWorkspaceSyncTaxonomySnapshot:U,refreshWorkspaceSyncPlanningEntitiesSnapshot:ve,refreshWorkspaceSyncDocumentReviewSessionsSnapshot:te,refreshWorkspaceSyncAnnotatedAttachmentSessionsSnapshot:ce,refreshWorkspaceSyncTaskforceAgentsSnapshot:Le,refreshLocalWorkspaceTaskCollections:Ie,buildWorkspaceSyncPayload:Ye,buildWorkspaceSyncSignature:ge,seedWorkspaceSnapshotPushBaseline:he,shouldSuppressAttachBootstrapPush:Ae,recordSuppressedEventIds:ye,runtime:Ne,localServices:ae,remoteServices:q,setWorkspaceSyncBusy:W,setUserGlobalSyncStatus:K,setUserGlobalSyncError:Re,setWorkspaceLastErrorMessage:we,setWorkspaceLastErrorAt:ie,setWorkspaceLastPullAt:Q,setWorkspaceLastPushAt:H,setWorkspaceSyncPendingChanges:se,setTasks:Pe,setArchivedTasks:ue,now:ne,scheduleTask:Me,logDebug:pe=()=>{},notifyAiProfilesMutated:le=()=>{},notifyAgentsMutated:Ce=()=>{},notifyAgentSkillsMutated:P=()=>{}}){const{repairMode:ee,forceFullAiProfilePush:Se,pushInFlight:_e,pullInFlight:ke,pullAfterPushRequested:Ze,pendingPushReplay:st,blockedPushSignature:at,lastPushedSignature:oe,pendingSignature:We,lastPushedTaskIds:G,deletedTaskIds:Be,deletedTaskWatermarks:Xe,pullCursor:ze,lastPushedWatermarks:qe,lastPushedTaskChangeKeys:Te,lastPushedTaskRelationshipChangeKeys:fe,lastPushedTaxonomyChangeKey:Ee,lastPushedInitiativeIds:$e,lastPushedInitiativeWatermarks:rt,lastPushedWorkstreamIds:kt,lastPushedWorkstreamWatermarks:xe,lastPushedAiProfileIds:St,lastPushedAiProfileWatermarks:jt,lastPushedAiProfileChangeKeys:$,lastPushedDocumentPaths:Ke,lastPushedDocumentWatermarks:Qe,lastPushedAssetPaths:Ge,lastPushedAssetWatermarks:At,lastPushedDocumentReviewSessionIds:Nt,lastPushedDocumentReviewSessionWatermarks:Bt,lastPushedDocumentReviewCommentIds:Qt,lastPushedDocumentReviewCommentWatermarks:Xt,lastPushedAnnotatedAttachmentSessionIds:nt,lastPushedAnnotatedAttachmentSessionWatermarks:Mt,lastPushedTaskforceAgentIds:ur,lastPushedTaskforceAgentWatermarks:je,lastPushedTaskforceAgentSkillIds:ot,lastPushedTaskforceAgentSkillWatermarks:pt,lastPushedAgentConversationIds:Ve,lastPushedAgentConversationWatermarks:lt,lastPushedTaskEventWatermarks:It,baselineResetReason:wt,captureAttachBootstrapBaseline:$t,startupFullReconcileRan:Yt,startupFullReconcileRequested:qt,fullReconcileInFlight:er,bootstrapLastProgressAtMs:_t,realtimeSuppressedEventQueue:Dt}=Ne,Tt=new Map;let Xr=!1;const Rr=(Ft,ft,Rt)=>{if(Xr||!w()||Tt.has(Ft))return;let _r=null;_r=Me(()=>{Tt.delete(Ft),!Xr&&w()&&ft()},Rt),Tt.set(Ft,_r)},la=()=>{if(!Xr){Xr=!0;for(const Ft of Tt.values())Ft.cancel();Tt.clear()}},sa=async(Ft,ft)=>{if(!w())return!1;if(ft?.repairMode!==!0&&S())return We.current=Ft,!1;let Rt=zk({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:i,currentWorkspaceId:l,workspaceSyncPhase:c,isAuthenticated:d,repairModeActive:ee.current===!0,repairModeBypass:ft?.repairMode===!0,pushInFlight:_e.current,pullInFlight:ke.current});if(!Rt.allowed&&Rt.reason==="auth-required"){if(!await f())return!1;Rt=zk({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:i,currentWorkspaceId:l,workspaceSyncPhase:c,isAuthenticated:!0,repairModeActive:ee.current===!0,repairModeBypass:ft?.repairMode===!0,pushInFlight:_e.current,pullInFlight:ke.current})}if(!Rt.allowed)return Rt.retainPendingSignature&&(We.current=Ft),!1;if(Ae(Ft))return!1;if(!await _(l,"push")){const zr=hP("push");return!zr.allowed&&zr.retainPendingSignature&&(We.current=Ft),z("push"),!1}_e.current=!0,W(!0),K("syncing"),Re(null);const u=ne().getTime(),Pt=ft?.forceAllAiProfiles===!0||Se.current===!0,pr=ft?.repairMode===!0||ee.current===!0;let Yr=null,tr=!1,$r=Ft,Lt=!1;try{v?.();const zr=[await M(),await O(),await Z(),await U(),await ve(),await te(),await ce(),await Le?.()];if(pr&&zr.some(ut=>ut===!1)){const ut="Workspace sync repair could not refresh the complete local snapshot. Press Repair to retry.";return k(),K("error"),Re(ut),we(ut),ie(ne().toISOString()),await x({phase:"error",lastErrorMessage:ut}),V(l,{eventType:"push",status:"error",errorMessage:ut,details:{recovery:"repair-snapshot-refresh-failed"}}),!1}if(!await h()||!w())return!1;const Kt=ge();if(Kt&&($r=Kt),Ae($r))return!1;const Jr=st.current,nr=Jr&&Jr.signature===$r&&(!Pt||Jr.forceAllAiProfiles===!0)&&(!pr||Jr.repairMode===!0)?Jr:null,Zr=nr?.payload||Ye({forceAllAiProfiles:Pt});Yr=Zr,tr=nr!==null,se(Zr.changes.length);const He=await PR({resolveCloudAuthUrl:p,workspaceId:l,payload:Zr,ensureCloudWorkspaceReadyForSync:g,repairMode:nr?.repairMode??pr,remoteServices:q,localServices:ae});if(!He.success){if(He.status===401)return Lt=!0,st.current=null,await y("push",401),!1;let ut=He.error?`Workspace sync push failed (${He.status||0}): ${He.error}`:`Workspace sync push failed (${He.status||0})`;return He.status===413&&(ut="Workspace sync failed because the payload is too large. This usually happens when one or more attachments exceed the project limit."),K("error"),Re(ut),we(ut),ie(ne().toISOString()),V(l,{eventType:"push",status:"error",statusCode:He.status,errorMessage:ut,requestMs:He.requestMs,details:{payloadDiagnostics:Zr.deltaDiagnostics||null,replayedPayload:tr,...He.batchProgress?{pushBatchProgress:He.batchProgress}:{}}}),We.current=$r,He.transient||ti(He.status)?(st.current={signature:$r,payload:Zr,forceAllAiProfiles:nr?.forceAllAiProfiles??Pt,repairMode:nr?.repairMode??pr},T(He.retryAfterMs)):(Lt=!0,at.current=$r,st.current=null,c==="active"&&E({phase:"error",lastErrorMessage:ut})),!1}const Ca=He.appliedTaskUpserts||[];if(Ca.length>0){const ut=He.pushTransferReceipts||[],ka=He.pushBoundary?q.buildV2PushApplyCompletionGroup({workspaceId:l,pushBoundary:He.pushBoundary,receipts:ut}):void 0;if(ut.length>0&&!ka)throw await q.abandonTransferReceipts({workspaceId:l,receipts:ut,errorCode:"WORKSPACE_SYNC_V2_PUSH_APPLY_COMPLETION_INVALID"}),new Error("Accepted V2 push echoes are missing an atomic local apply completion group.");let Wt;try{const rr=Ca.map(oa=>({op:"upsert",archived:oa.archived===!0,task:oa.task,...oa.durableRevision?{durableRevision:oa.durableRevision}:{}}));Wt=ka?await ae.applyV2Batch(l,rr,{completionGroup:ka}):await ae.applyV2Batch(l,rr)}catch(rr){throw ut.length>0&&await q.abandonTransferReceipts({workspaceId:l,receipts:ut,errorCode:"WORKSPACE_SYNC_V2_PUSH_AUTHORITATIVE_APPLY_FAILED"}),rr}if(!Wt.ok)throw ut.length>0&&await q.abandonTransferReceipts({workspaceId:l,receipts:ut,errorCode:"WORKSPACE_SYNC_V2_PUSH_AUTHORITATIVE_APPLY_FAILED"}),new Error(`Authoritative V2 push echo apply failed (${Wt.status||0}).`);for(const rr of Ca){const oa=String(rr.task.id||"").trim(),Mr=String(rr.task.updatedAt||rr.task.createdAt||"").trim();!oa||!Mr||(He.currentTaskWatermarks?.set(oa,Mr),He.pushedWatermarks.set(oa,Mr))}try{await Ie()}catch{pe("push_local_task_refresh_failed",{workspaceId:l,taskCount:Ca.length})}}st.current=null,at.current="",oe.current=$r,G.current=He.currentTaskIds,qe.current=He.currentTaskWatermarks?new Map(He.currentTaskWatermarks):new Map(qe.current),Te.current=He.currentTaskChangeKeys?new Map(He.currentTaskChangeKeys):new Map(Te.current),fe&&(fe.current=He.currentTaskRelationshipChangeKeys?new Map(He.currentTaskRelationshipChangeKeys):new Map(fe.current)),Ee&&(Ee.current=He.currentTaxonomyChangeKey??Ee.current),$e.current=new Set(He.currentInitiativeIds),rt.current=new Map(He.currentInitiativeWatermarks),kt.current=new Set(He.currentWorkstreamIds),xe.current=new Map(He.currentWorkstreamWatermarks),St.current=new Set(He.currentAiProfileIds),jt.current=new Map(He.currentAiProfileWatermarks),$.current=He.currentAiProfileChangeKeys?new Map(He.currentAiProfileChangeKeys):new Map($.current),Ke.current=new Set(He.currentDocumentPaths),Qe.current=new Map(He.currentDocumentWatermarks),Ge.current=new Set(He.currentAssetPaths),At.current=new Map(He.currentAssetWatermarks),Nt.current=new Set(He.currentDocumentReviewSessionIds),Bt.current=new Map(He.currentDocumentReviewSessionWatermarks),Qt.current=new Set(He.currentDocumentReviewCommentIds),Xt.current=new Map(He.currentDocumentReviewCommentWatermarks),nt.current=new Set(He.currentAnnotatedAttachmentSessionIds),Mt.current=new Map(He.currentAnnotatedAttachmentSessionWatermarks),ur&&(ur.current=new Set(He.currentTaskforceAgentIds)),je&&(je.current=new Map(He.currentTaskforceAgentWatermarks)),ot&&(ot.current=new Set(He.currentTaskforceAgentSkillIds)),pt&&(pt.current=new Map(He.currentTaskforceAgentSkillWatermarks)),Ve&&(Ve.current=new Set(He.currentAgentConversationIds)),lt&&(lt.current=new Map(He.currentAgentConversationWatermarks)),It.current=new Map(He.currentTaskEventWatermarks),Pt&&(Se.current=!1);for(const[ut,ka]of He.pushedWatermarks)qe.current.set(ut,ka);for(const[ut,ka]of He.pushedTaskChangeKeys||new Map)Te.current.set(ut,ka);if(He.deleteTaskIds.size>0)for(const ut of He.deleteTaskIds)Be.current.delete(ut),Xe.current.delete(ut),qe.current.delete(ut),Te.current.delete(ut);const da=await N();wt.current=da?null:"storage-write-failed",Array.isArray(He.emittedEventIds)&&He.emittedEventIds.length>0&&ye(He.emittedEventIds,{queueRef:Dt,maxQueueSize:2048}),k();const ir=He.syncedAt||ne().toISOString();return oe.current=ge(),H(ir),se(0),K("idle"),E({phase:"active",lastPushAt:ir,lastSyncedAt:ir}),V(l,{eventType:c==="provision-local"?"bootstrap":"push",status:"success",changeCount:He.changeCount,requestMs:He.requestMs,details:{payloadDiagnostics:He.effectiveDeltaDiagnostics||Zr.deltaDiagnostics||null,...He.batchProgress?{pushBatchProgress:He.batchProgress}:{},...He.effectiveDeltaDiagnostics&&Zr.deltaDiagnostics&&He.effectiveDeltaDiagnostics.totalChanges!==Zr.deltaDiagnostics.totalChanges?{candidatePayloadDiagnostics:Zr.deltaDiagnostics}:{},replayedPayload:tr}}),!0}catch(zr){const Ir="Workspace sync push failed.";return K("error"),Re(Ir),we(Ir),ie(ne().toISOString()),We.current=$r,Yr&&(st.current={signature:$r,payload:Yr,forceAllAiProfiles:Pt,repairMode:pr}),T(),V(l,{eventType:"push",status:"error",errorMessage:`${Ir} ${String(zr?.message||"").trim()}`.trim(),details:{replayedPayload:tr}}),pe("push_failed_exception",{workspaceId:l,elapsedMs:ne().getTime()-u}),!1}finally{_e.current=!1,W(ke.current),j(l),Ze.current&&!ke.current&&!C()&&Rr("pull-after-push",()=>{ea()},0);const zr=We.current,Ir=ge();zr&&Ir&&Ir!==oe.current&&!ke.current&&!C()&&!Lt&&Rr("pending-push",()=>{const Kt=We.current||Ir;We.current="",sa(Kt)},120)}},ea=async Ft=>{if(!w())return!1;const ft=Ft?.repairMode===!0,Rt=async Yr=>{ft&&(k(),await x({phase:"error",lastErrorMessage:Yr}))};let _r=Hk({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:i,currentWorkspaceId:l,workspaceSyncPhase:c,isAuthenticated:d,repairModeActive:ee.current===!0,repairModeBypass:ft,retryPending:C(),pullInFlight:ke.current,pushInFlight:_e.current});if(!_r.allowed&&_r.reason==="auth-required"){if(!await f())return await Rt("Session expired. Sign in again, then press Repair to resume cloud sync."),!1;_r=Hk({cloudAuthConfigured:e,runtimeMode:t,workspaceCloudSyncEnabled:i,currentWorkspaceId:l,workspaceSyncPhase:c,isAuthenticated:!0,repairModeActive:ee.current===!0,repairModeBypass:ft,retryPending:C(),pullInFlight:ke.current,pushInFlight:_e.current})}if(!_r.allowed)return _r.reason==="push-in-flight"&&!ft&&(Ze.current=!0),!1;if(Ze.current=!1,!await _(l,"pull"))return z("pull"),!1;ke.current=!0,W(!0),K("syncing"),Re(null);const Pt=ne().getTime();let pr=!1;try{if(!await h())return await Rt("Workspace sync repair could not validate cloud access. Resolve the reported error, then press Repair to retry."),!1;if(!w())return!1;const tr={authFailure:!1,failure:null};let $r=!1,Lt=[],zr=0;const Ir=Wt=>{zr+=Math.max(0,Number(Wt)||0)},Kt=qP({workspaceId:l,remoteServices:q,localServices:ae});let Jr="",Br="";const nr=(Wt,rr)=>Wt.kind==="auth-failure"?(tr.authFailure=!0,!1):Wt.kind==="transient-failure"?(tr.failure={status:Wt.status,retryAfterMs:Wt.retryAfterMs,error:String(Wt.error||"Workspace projection synchronization failed."),projectionCycle:rr},!1):!0;try{if(n===!0){const Wt=await Kk({activationEnabled:!1,resolveCloudAuthUrl:p,workspaceId:l,onChangesApplied:Ir,dependencies:Kt.initiative});if(nr(Wt,"initiative")){const rr=await Ub({activationEnabled:!0,coverage:s,resolveCloudAuthUrl:p,workspaceId:l,forceAuthoritativeRepair:Ft?.forceV3AuthoritativeRepair===!0,...Ft?.recoveryBatchId?{recoveryBatchId:Ft.recoveryBatchId}:{},onChangesApplied:Ir,dependencies:Kt.combined});Lt=rr.excludedProjections;const oa=rr.kind==="transient-failure"?VP(rr):null;oa?(Jr=oa,Br=rr.kind==="transient-failure"?rr.error:""):nr(rr,"combined")}}else{if(n!==void 0){const Wt=await Ub({activationEnabled:!1,coverage:s,resolveCloudAuthUrl:p,workspaceId:l,onChangesApplied:Ir,dependencies:Kt.combined});nr(Wt,"combined")}if(!tr.authFailure&&!tr.failure&&r!==void 0){const Wt=await Kk({activationEnabled:r,resolveCloudAuthUrl:p,workspaceId:l,onChangesApplied:Ir,dependencies:Kt.initiative});nr(Wt,"initiative")&&($r=Wt.excludeInitiativesFromV2)}}}finally{await Kt.abandonPendingReceipts()}if(tr.authFailure)return await y("pull",401),await Rt("Session expired. Sign in again, then press Repair to resume cloud sync."),!1;if(tr.failure)return we(tr.failure.error),ie(ne().toISOString()),V(l,{eventType:"apply",status:"error",statusCode:tr.failure.status,errorMessage:tr.failure.error,details:{recovery:"projection-cycle-retry",projectionCycle:tr.failure.projectionCycle,...tr.failure.retryAfterMs!==void 0?{retryAfterMs:tr.failure.retryAfterMs}:{}}}),ft?await x({phase:"error",lastErrorMessage:tr.failure.error}):T(tr.failure.retryAfterMs),!1;if(Jr){const Wt=await zC({workspaceId:l,assetId:Jr,remoteServices:q,localServices:ae}).catch(rr=>({success:!1,error:rr instanceof Error?rr.message:String(rr||"Unknown hydration failure.")}));return Wt.success&&Wt.emittedEventIds.length>0&&ye(Wt.emittedEventIds,{ttlMs:6e4}),K("error"),Re(Br),we(Br),ie(ne().toISOString()),V(l,{eventType:"apply",status:"error",errorMessage:Br,changeCount:Wt.success?Wt.appliedChanges:0,details:{recovery:Wt.success?"combined-attachment-asset-hydrated-retry-pending":"combined-attachment-asset-hydration-failed",assetId:Jr,...Wt.success?{}:{hydrationError:Wt.error}}}),T(),!1}const Zr=bP({workspaceSyncPhase:c,forceCursorNull:Ft?.forceCursorNull===!0,currentCursor:ze.current}),He=await ER({resolveCloudAuthUrl:p,workspaceId:l,cursor:ft?null:Zr.cursor,bootstrap:Zr.bootstrap,ensureCloudWorkspaceReadyForSync:g,maxPages:ft?200:20,repairMode:ft||ee.current===!0,contentMode:Ft?.forceCursorNull===!0?"manifest":"full",excludeInitiatives:$r,excludedProjections:Lt,onPagePulled:()=>{_t.current=ne().getTime()},onAiProfilesApplied:()=>{le({workspaceId:l,reason:"sync-apply",origin:"sync-orchestrator"})},onChangesApplied:()=>{_t.current=ne().getTime()},remoteServices:q,localServices:ae});if(!He.success){if(He.kind==="pull_http"&&He.status===401)return await y("pull",401),await Rt("Session expired. Sign in again, then press Repair to resume cloud sync."),!1;if(He.kind==="apply_auth")return await y("apply",401),await Rt("Session expired. Sign in again, then press Repair to resume cloud sync."),!1;if(He.kind==="pull_http"&&He.errorCode==="INVALID_SYNC_CURSOR"){const rr="Saved sync cursor was invalid. Clearing it and retrying from the beginning.";return ze.current=null,E({pullCursor:null}),K("error"),Re(rr),we(rr),ie(ne().toISOString()),V(l,{eventType:"pull",status:"error",statusCode:He.status,errorMessage:rr,requestMs:He.pullRequestMs,details:{recovery:"cursor-reset",...He.serverDiagnostics?{serverPullDiagnostics:He.serverDiagnostics}:{}}}),ft?await x({phase:"error",lastErrorMessage:rr}):T(150),!1}let Wt=He.kind==="apply_payload"||He.kind==="apply_all_candidates"||He.kind==="exception"?String(He.error||"Workspace sync apply failed."):`Workspace sync pull failed (${He.status||0})`;return He.status===413&&(Wt="Local sync failed because the downloaded payload is too large. This usually happens when the workspace contains massive attachments."),K("error"),Re(Wt),we(Wt),ie(ne().toISOString()),V(l,{eventType:He.kind?.startsWith("apply")?"apply":"pull",status:"error",statusCode:He.status,errorMessage:Wt,requestMs:He.pullRequestMs,details:{pages:He.pages,applyMs:He.applyMs,...He.serverDiagnostics?{serverPullDiagnostics:He.serverDiagnostics}:{}}}),ft?await x({phase:"error",lastErrorMessage:Wt}):He.transient||He.hasTransientApplyFailure||ti(He.status)?T(He.retryAfterMs):E({phase:"error",lastErrorMessage:Wt}),!1}if(ft&&He.hasMore===!0){const Wt="Workspace sync repair stopped before the full cloud snapshot was downloaded. Press Repair to retry.";return K("error"),Re(Wt),we(Wt),ie(ne().toISOString()),await x({phase:"error",lastErrorMessage:Wt}),V(l,{eventType:"pull",status:"error",errorMessage:Wt,requestMs:He.pullRequestMs,details:{pages:He.pages,applyMs:He.applyMs,recovery:"repair-pull-incomplete"}}),!1}Array.isArray(He.emittedEventIds)&&ye(He.emittedEventIds,{ttlMs:6e4}),(He.pulledTaskforceAgentUpserts||He.pulledAgentRoleUpserts||He.pulledTaskforceAgentSkillUpserts||He.pulledAgentConversationUpserts)&&await Le?.(),(He.pulledTaskforceAgentUpserts||He.pulledAgentRoleUpserts||He.pulledAgentConversationUpserts)&&Ce({workspaceId:l,reason:"sync-apply"}),He.pulledTaskforceAgentSkillUpserts&&P({workspaceId:l,reason:"sync-apply"}),He.pulledDeleteTaskIds.size>0&&(Pe(Wt=>Wt.filter(rr=>!He.pulledDeleteTaskIds.has(String(rr.id||"")))),ue(Wt=>Wt.filter(rr=>!He.pulledDeleteTaskIds.has(String(rr.id||"")))));const da=Array.isArray(He.documentDecryptFailures)?He.documentDecryptFailures.filter(Wt=>String(Wt||"").trim().length>0):[];if(da.length>0&&pe("pull_document_decrypt_failures",{workspaceId:l,failureCount:da.length}),ze.current=He.cursor||null,zr>0||He.appliedChanges>0&&(ft||He.pulledActiveUpserts||He.pulledArchivedUpserts||He.pulledTaskEventUpserts||He.pulledPlanningUpserts||He.pulledDeleteTaskIds.size>0))try{await Ie()}catch{if(pe("pull_local_refresh_failed",{workspaceId:l,appliedChanges:He.appliedChanges+zr}),ft){const Wt="Workspace sync repair could not refresh tasks and relationships after the cloud pull. Press Repair to retry.";return k(),K("error"),Re(Wt),we(Wt),ie(ne().toISOString()),await x({phase:"error",lastErrorMessage:Wt}),!1}}k(),b();const ir=He.syncedAt||ne().toISOString();Q(ir),se(0),K("idle");const ut=SP({workspaceSyncPhase:c,forceCursorNull:Ft?.forceCursorNull===!0,repairMode:ft,startupFullReconcileRan:Yt.current,pendingSignature:We.current,fallbackSignature:ge(),lastPushedSignature:oe.current});if(ut.shouldCaptureAttachBootstrapBaseline&&($t.current=!0),ut.shouldClearPendingSignature&&(We.current=ut.deferredPushSignature||"",st.current=null),await x({phase:"active",pullCursor:ze.current,lastPullAt:ir,lastSyncedAt:ir,...Ft?.forceCursorNull===!0?{startupFullReconcileCompletedAt:ir}:{},lastErrorMessage:null}),V(l,{eventType:ut.successEventType,status:"success",changeCount:He.appliedChanges+zr,requestMs:He.pullRequestMs,details:{pages:He.pages,applyMs:He.applyMs,...He.serverDiagnostics?{serverPullDiagnostics:He.serverDiagnostics}:{}}}),ut.shouldRefreshReferenceSnapshots&&(await M(),await Z(),await te(),await ce()),ut.shouldSeedWorkspaceSnapshotPushBaseline&&he(),ut.shouldRefreshReferenceSnapshots||ut.shouldSeedWorkspaceSnapshotPushBaseline)return pr=!0,!0;if(ut.shouldScheduleStartupFullReconcile&&(qt.current=!0,Rr("startup-full-reconcile",()=>{!qt.current||er.current||(qt.current=!1,Yt.current=!0,er.current=!0,ea({forceCursorNull:!0}).finally(()=>{er.current=!1}))},250)),Ft?.forceCursorNull===!0&&!ft&&c==="active"){const Wt=ge();Wt&&(Se.current=!0,We.current=Wt,Rr("pending-push",()=>{const rr=We.current||Wt;We.current="",sa(rr,{forceAllAiProfiles:!0})},120))}else if(ut.deferredPushSignature){const Wt=ut.deferredPushSignature;Rr("pending-push",()=>{const rr=We.current||Wt;We.current="",sa(rr)},120)}return pr=!0,!0}catch(Yr){const tr=String(Yr?.message||"").trim(),$r=tr?`Workspace sync pull failed. ${tr}`:"Workspace sync pull failed.";return K("error"),Re($r),we($r),ie(ne().toISOString()),ft?await x({phase:"error",lastErrorMessage:$r}):T(),V(l,{eventType:"pull",status:"error",errorMessage:$r,requestMs:ne().getTime()-Pt}),pe("pull_failed_exception",{workspaceId:l,elapsedMs:ne().getTime()-Pt,error:tr||null}),!1}finally{ke.current=!1,W(_e.current),pr&&F(l,"pull"),j(l)}};return{pushWorkspaceChangesToCloud:sa,pullWorkspaceChangesFromCloud:ea,resumeDeferredWork:()=>{w()&&(Ze.current&&Rr("pull-after-push",()=>{ea()},0),We.current&&Rr("pending-push",()=>{const Ft=We.current;Ft&&(We.current="",sa(Ft,{forceAllAiProfiles:Se.current}))},120),qt.current&&Rr("startup-full-reconcile",()=>{!qt.current||er.current||(qt.current=!1,Yt.current=!0,er.current=!0,ea({forceCursorNull:!0}).finally(()=>{er.current=!1}))},250))},dispose:la}}function ZP(e){return YP({now:()=>new Date,scheduleTask:(t,r)=>{const n=window.setTimeout(t,r);return{cancel:()=>window.clearTimeout(n)}},logDebug:js,notifyAiProfilesMutated:IC,notifyAgentsMutated:_C,notifyAgentSkillsMutated:TC,...e})}const JP="/api/taskforce/sync/v3/local/dispatch",QP=20,XP=1e5;function e2(e){if(e===void 0)return;if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Local outbox dispatch returned an invalid outbox status.");const t=e,r=b=>{const C=Number(t[b]);return Number.isInteger(C)&&C>=0?C:null},n=r("activeDepth"),s=r("pending"),i=r("inFlight"),l=r("blocked");let c;if(t.operationStates!==void 0){if(!t.operationStates||typeof t.operationStates!="object"||Array.isArray(t.operationStates))throw new Error("Local outbox dispatch returned invalid operation states.");const b=t.operationStates,C=w=>{const T=Number(b[w]);return Number.isInteger(T)&&T>=0?T:null},S={pending:C("pending"),retryScheduled:C("retryScheduled"),inFlight:C("inFlight"),stale:C("stale"),blocked:C("blocked")};if(Object.values(S).some(w=>w===null)||s===null||i===null||l===null||S.pending+S.retryScheduled!==s||S.inFlight+S.stale!==i||S.blocked!==l)throw new Error("Local outbox dispatch returned inconsistent operation states.");c={pending:S.pending,retryScheduled:S.retryScheduled,inFlight:S.inFlight,stale:S.stale,blocked:S.blocked}}const d=b=>t[b]===null||typeof t[b]=="string"?t[b]:void 0,f=d("oldestActiveCreatedAt"),p=d("oldestActionableAt"),g=d("blockedErrorCode"),h=t.recovery;let y=null;if(h!==null){if(!h||typeof h!="object"||Array.isArray(h))throw new Error("Local outbox dispatch returned an invalid recovery status.");const b=h,C=v=>{const V=Number(b[v]);return Number.isInteger(V)&&V>=0?V:null},S=String(b.state||""),w=C("replayTotal"),T=C("replayPending"),E=C("replayInFlight"),x=C("replayBlocked"),N=C("replayAccepted");if(typeof b.recoveryBatchId!="string"||!["awaiting_baseline","baseline_ready","replay_queued","completed"].includes(S)||w===null||T===null||E===null||x===null||N===null||w<T+E+x+N||typeof b.createdAt!="string"||typeof b.updatedAt!="string"||b.completedAt!==null&&typeof b.completedAt!="string")throw new Error("Local outbox dispatch returned an invalid recovery status.");y={recoveryBatchId:b.recoveryBatchId,state:S,replayTotal:w,replayPending:T,replayInFlight:E,replayBlocked:x,replayAccepted:N,createdAt:b.createdAt,updatedAt:b.updatedAt,completedAt:b.completedAt}}let k;if(t.attachmentApplyObligations!==void 0){if(!t.attachmentApplyObligations||typeof t.attachmentApplyObligations!="object"||Array.isArray(t.attachmentApplyObligations))throw new Error("Local outbox dispatch returned invalid attachment apply obligations.");const b=t.attachmentApplyObligations,C=Number(b.open),S=Number(b.due),w=Number(b.totalAttempts);if(![C,S,w].every(T=>Number.isInteger(T)&&T>=0)||S>C||b.oldestOpenCreatedAt!==null&&typeof b.oldestOpenCreatedAt!="string"||b.nextAttemptAt!==null&&typeof b.nextAttemptAt!="string"||b.lastError!==null&&typeof b.lastError!="string")throw new Error("Local outbox dispatch returned invalid attachment apply obligations.");k={open:C,due:S,totalAttempts:w,oldestOpenCreatedAt:b.oldestOpenCreatedAt,nextAttemptAt:b.nextAttemptAt,lastError:b.lastError}}if(n===null||s===null||i===null||l===null||n!==s+i+l||f===void 0||g===void 0||!Object.prototype.hasOwnProperty.call(t,"recovery"))throw new Error("Local outbox dispatch returned an invalid outbox status.");return{activeDepth:n,pending:s,inFlight:i,blocked:l,...c?{operationStates:c}:{},oldestActiveCreatedAt:f,...p!==void 0?{oldestActionableAt:p}:{},blockedErrorCode:g,recovery:y,...k?{attachmentApplyObligations:k}:{}}}function t2(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Local outbox dispatch returned an invalid response.");const t=e,r=Number(t.claimed),n=Array.isArray(t.outcomes)?t.outcomes:[],s=i=>{if(i.retryDependency===void 0)return!0;if(i.disposition!=="retry"||!i.retryDependency||typeof i.retryDependency!="object"||Array.isArray(i.retryDependency))return!1;const l=i.retryDependency;return Object.keys(l).sort().join(",")==="assetId,kind"&&l.kind==="asset"&&typeof l.assetId=="string"&&/^[A-Za-z0-9._:-]+$/.test(l.assetId)};if(t.success!==!0||!Number.isInteger(r)||r<0||r>1||n.length!==r||n.some(i=>!i||typeof i!="object"||!["accepted","retry","blocked","lease-lost"].includes(String(i.disposition||""))))throw new Error("Local outbox dispatch returned an invalid response.");if(n.some(i=>!s(i)))throw new Error("Local outbox dispatch returned an invalid retry dependency.");return{success:!0,claimed:r,outcomes:n,outbox:e2(t.outbox)}}async function r2(e){const t=String(e.workspaceId||"").trim();if(!t)throw new Error("Workspace id is required to drain the local outbox.");const r=e.fetchImpl||fetch,n=Math.max(1,Math.min(100,Math.floor(e.operationBudget??QP))),s=Math.max(1,Math.floor(e.requestTimeoutMs??XP));let i=0;const l=new Set;let c;for(;i<n;){const d=new AbortController;let f,p;const g=new Promise((y,k)=>{p=k,f=setTimeout(()=>{d.abort(),k(new Error("Local outbox dispatch timed out."))},s)}),h=()=>{d.abort(e.signal?.reason),p?.(new DOMException("Local outbox dispatch aborted.","AbortError"))};e.signal?.aborted?h():e.signal?.addEventListener("abort",h,{once:!0});try{const y=(async()=>{const S=await r(JP,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:t,limit:1}),signal:d.signal});if(!S.ok)throw new Error(`Local outbox dispatch failed (${S.status}).`);return t2(await S.json())})(),k=await Promise.race([y,g]);if(c=k.outbox,k.claimed===0)return{processed:i,retryRecommended:!1,budgetExhausted:!1,...c?{outbox:c}:{}};i+=k.claimed;const b=k.outcomes[0],C=b?.disposition;if(C==="retry"&&b.retryDependency?.kind==="asset"){const S=`${b.retryDependency.kind}:${b.retryDependency.assetId}`;if(l.has(S))return{processed:i,retryRecommended:!0,budgetExhausted:!1,...c?{outbox:c}:{}};if(!e.hydrateAsset||!await e.hydrateAsset(b.retryDependency.assetId))return{processed:i,retryRecommended:!0,budgetExhausted:!1,...c?{outbox:c}:{}};l.add(S);continue}if(C==="retry"||C==="lease-lost")return{processed:i,retryRecommended:!0,budgetExhausted:!1,...c?{outbox:c}:{}}}finally{f!==void 0&&clearTimeout(f),e.signal?.removeEventListener("abort",h)}}return{processed:i,retryRecommended:!0,budgetExhausted:!0,...c?{outbox:c}:{}}}const a2=3e4,n2=1e3,s2=3e4;function o2(e){const t=o.useRef(null),r=o.useRef(""),n=o.useRef(null),s=o.useRef(null),i=o.useRef({enabled:e.enabled,workspaceId:e.workspaceId,authorityScope:e.authorityScope,remoteServices:e.remoteServices,localServices:e.localServices,isAuthorityCurrent:e.isAuthorityCurrent,onHydratedEventIds:e.onHydratedEventIds,onOutboxStatus:e.onOutboxStatus});i.current={enabled:e.enabled,workspaceId:e.workspaceId,authorityScope:e.authorityScope,remoteServices:e.remoteServices,localServices:e.localServices,isAuthorityCurrent:e.isAuthorityCurrent,onHydratedEventIds:e.onHydratedEventIds,onOutboxStatus:e.onOutboxStatus};const l=o.useCallback(()=>{n.current!==null&&(window.clearTimeout(n.current),n.current=null)},[]),c=o.useCallback(async()=>{const d=i.current;if(!d.enabled||!d.workspaceId||!d.remoteServices)return;const f=d.workspaceId,p=d.remoteServices,g=s.current;if(g?.key===f&&g.authorityScope===d.authorityScope&&g.at>Date.now()){n.current===null&&(n.current=window.setTimeout(()=>{n.current=null,c()},g.at-Date.now()));return}(g?.key!==f||g.authorityScope!==d.authorityScope||g.at<=Date.now())&&(s.current=null);const h=t.current;if(h?.key===f&&h.authorityScope===d.authorityScope){r.current=f;return}h&&h.controller.abort(),l();const y={key:f,authorityScope:d.authorityScope,controller:new AbortController};t.current=y;let k=0;try{const b=await r2({workspaceId:f,signal:y.controller.signal,hydrateAsset:async S=>{const w=i.current;if(y.controller.signal.aborted||!w.enabled||w.workspaceId!==f||w.authorityScope!==y.authorityScope||w.remoteServices!==p||w.isAuthorityCurrent?.(y.authorityScope)===!1)return!1;const T=await zC({workspaceId:f,assetId:S,remoteServices:p,localServices:d.localServices}).catch(()=>({success:!1,error:"Attachment hydration failed."})),E=i.current;return y.controller.signal.aborted||!E.enabled||E.workspaceId!==f||E.authorityScope!==y.authorityScope||E.remoteServices!==p||E.isAuthorityCurrent?.(y.authorityScope)===!1||!T.success?!1:(T.emittedEventIds.length>0&&d.onHydratedEventIds?.(T.emittedEventIds),!0)}}),C=i.current;if(!C.enabled||C.workspaceId!==f||C.authorityScope!==y.authorityScope)return;b.retryRecommended&&(k=b.budgetExhausted?n2:s2,s.current={key:f,authorityScope:y.authorityScope,at:Date.now()+k}),b.outbox&&d.onOutboxStatus?.(b.outbox)}catch{}finally{t.current===y&&(t.current=null)}if(!(!i.current.enabled||i.current.workspaceId!==f)){if(r.current===f){r.current="",c();return}k>0&&(n.current=window.setTimeout(()=>{n.current=null,c()},k))}},[l]);o.useEffect(()=>{e.onOutboxStatus?.(null)},[e.onOutboxStatus,e.workspaceId]),o.useEffect(()=>{if(!e.enabled){t.current?.controller.abort(),t.current=null,r.current="",s.current=null,i.current.onOutboxStatus?.(null),l();return}c()},[l,e.enabled,e.mutationFingerprint,e.authorityScope,e.remoteServices,e.workspaceId,c]),o.useEffect(()=>{if(!e.enabled)return;const d=()=>{c()},f=()=>{document.visibilityState==="visible"&&c()},p=window.setInterval(()=>{c()},a2);return window.addEventListener("online",d),document.addEventListener("visibilitychange",f),()=>{window.removeEventListener("online",d),document.removeEventListener("visibilitychange",f),window.clearInterval(p);const g=t.current;g?.key===e.workspaceId&&(g.controller.abort(),t.current=null),r.current===e.workspaceId&&(r.current=""),l()}},[l,e.authorityScope,e.enabled,e.remoteServices,e.workspaceId,c])}const i2="/api/taskforce/sync/v3/local/recovery";async function c2(e){const t=String(e.workspaceId||"").trim();if(!t)throw new Error("Workspace id is required to prepare local recovery.");const r=await(e.fetchImpl||fetch)(i2,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:t})}),n=await r.json().catch(()=>null);if(!r.ok||n?.success!==!0){const c=String(n?.error||`Local workspace sync recovery failed (${r.status}).`),d=typeof n?.code=="string"?n.code.trim():"";let f="unknown-origin";try{f=new URL(r.url).origin}catch{}throw new Error(`${c} [${d||"UNKNOWN_RECOVERY_ERROR"}; HTTP ${r.status}; ${f}]`)}if(n.kind==="none"&&n.needsAuthoritativeRepair===!1&&n.recovery===null)return{kind:"none",needsAuthoritativeRepair:!1,recoveryBatchId:null};if(n.kind!=="recovery"||typeof n.needsAuthoritativeRepair!="boolean"||!n.recovery||typeof n.recovery!="object"||Array.isArray(n.recovery))throw new Error("Local workspace sync recovery returned an invalid response.");const s=n.recovery,i=String(s.recoveryBatchId||"").trim(),l=String(s.state||"");if(!/^recovery-[A-Za-z0-9-]{1,200}$/.test(i)||!["awaiting_baseline","baseline_ready","replay_queued","completed"].includes(l)||n.needsAuthoritativeRepair===!0&&l!=="awaiting_baseline")throw new Error("Local workspace sync recovery returned an invalid state.");return{kind:"recovery",needsAuthoritativeRepair:n.needsAuthoritativeRepair,recoveryBatchId:i,state:l}}function l2(e={}){return{readPushOwnership:lC,readContentManifest:iC,applyV2Batch:dC,listContentPullObligations:qA,recordContentPullObligationFailures:YA,readInitiativeProjection:QA,applyInitiativeProjection:XA,readCombinedProjection:eC,applyCombinedProjection:tC,readTaskCommentAuditCursor:rC,applyTaskCommentAuditPage:nC,prepareOutboxRecovery:t=>c2({workspaceId:t,...e.recoveryFetchImpl?{fetchImpl:e.recoveryFetchImpl}:{}}),completeAuthoritativeRepair:pR}}const co="/api/taskforce/sync/v3/local/coordinator";class Yn extends Error{constructor(t,r,n){super(t),this.code=r,this.status=n,this.name="LocalSyncCoordinatorBrowserClientError"}}class HC{fetchImpl;constructor(t){this.fetchImpl=t||globalThis.fetch.bind(globalThis)}attachWorkspace(t){return this.requestJson(`${co}/attach`,vi("POST",t))}readStatus(t){const r=ch(t);return this.requestJson(`${co}/status?${r.toString()}`,{method:"GET",credentials:"include"})}attachCredential(t){return this.requestJson(`${co}/credential`,vi("POST",t))}switchWorkspace(t){return this.requestJson(`${co}/workspace-switch`,vi("POST",t))}clearCredential(t){const r=ch(t);return this.requestJson(`${co}/credential?${r.toString()}`,{method:"DELETE",credentials:"include"})}issuePermit(t){return this.requestJson(`${co}/permits`,vi("POST",t))}issueCommand(t){return this.requestJson(`${co}/commands`,vi("POST",t))}signalWake(t){return this.requestJson(`${co}/wake`,vi("POST",t))}transferOwnership(t){return this.requestJson(`${co}/ownership-transfer`,vi("POST",t))}readCommand(t){const r=ch(t);return t.rootCommandId&&r.set("rootCommandId",t.rootCommandId),this.requestJson(`${co}/commands/${encodeURIComponent(t.commandId)}?${r.toString()}`,{method:"GET",credentials:"include"})}readPermit(t){const r=ch(t);return this.requestJson(`${co}/permits/${encodeURIComponent(t.permitId)}?${r.toString()}`,{method:"GET",credentials:"include"})}async executeGateway(t){return await this.fetchImpl(`${co}/gateway`,vi("POST",t))}applyCombinedFeed(t){const r=t.command.kind==="delta"?t.command:{...t.command,epoch:t.command.expectedEpoch,previousCursor:t.command.previousRepairCursor,expectedEpoch:void 0,previousRepairCursor:void 0};return this.requestJson("/api/taskforce/sync/v3/local/feed",vi("POST",{workspaceId:t.workspaceId,executionPermitId:t.executionPermitId,coordinatorGeneration:t.coordinatorGeneration,...r,...t.coverage}))}releasePermit(t){return this.requestJson(`${co}/permits/${encodeURIComponent(t.permitId)}/release`,vi("POST",{workspaceId:t.workspaceId,coordinatorGeneration:t.coordinatorGeneration,...t.pushBoundary?{pushBoundary:t.pushBoundary}:{}}))}abandonPermit(t){return this.permitAction(t,"abandon")}permitAction(t,r){return this.requestJson(`${co}/permits/${encodeURIComponent(t.permitId)}/${r}`,vi("POST",{workspaceId:t.workspaceId,coordinatorGeneration:t.coordinatorGeneration,...t.errorCode?{errorCode:t.errorCode}:{}}))}async requestJson(t,r){const n=await this.fetchImpl(t,r);return n.ok||await d2(n),n.json()}}function ch(e){return new URLSearchParams({workspaceId:e.workspaceId,coordinatorGeneration:String(e.coordinatorGeneration)})}function vi(e,t){return{method:e,headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(t)}}async function d2(e){let t={};try{t=await e.json()}catch{}throw new Yn(String(t.error||`Local sync coordinator request failed (${e.status}).`),String(t.code||"SYNC_COORDINATOR_REQUEST_FAILED"),e.status)}const Hb="taskforce.local-sync-coordinator.command.v1",u2=500,p2=240,f2=8,m2=600*1e3;function qv(e,t="default"){return t==="priority"?`${Hb}.priority:${e}`:`${Hb}:${e}`}function h2(e,t,r=()=>new Date,n="default"){e.setItem(qv(t.workspaceId,n),JSON.stringify({storedAt:r().toISOString(),envelope:t}))}function Gb(e,t,r=()=>new Date,n="default"){const s=qv(t,n);try{const i=e.getItem(s);if(!i)return null;const l=JSON.parse(i),c=Date.parse(String(l.storedAt||"")),d=l.envelope;return!d||d.workspaceId!==t||!d.commandId||!Number.isInteger(d.coordinatorGeneration)||!Number.isFinite(c)||r().getTime()-c>m2?(Eu(e,t,n),null):d}catch{return Eu(e,t,n),null}}function g2(e,t,r="default"){e.removeItem(qv(t,r))}async function sk(e){const{client:t,envelope:r,storage:n=null,pollIntervalMs:s=u2,maxPollAttempts:i=p2,delay:l=b2,recoverExisting:c=!1,storageLane:d="default"}=e;if(n&&!c)try{h2(n,r,void 0,d)}catch{}try{let f=c?await y2(t,r,{delay:l,pollIntervalMs:s,maxPollAttempts:i}):await k2(t,r,{delay:l,pollIntervalMs:s,maxPollAttempts:i});const p=new Set;for(let g=0;g<i;g+=1){if(p.has(f.commandId))throw new Yn("The local sync coordinator command references contain a cycle.","SYNC_COORDINATOR_COMMAND_REFERENCE_CYCLE",409);if(p.add(f.commandId),f.status==="succeeded")return Eu(n,r.workspaceId,d),f;if(f.status==="failed")throw Eu(n,r.workspaceId,d),new Yn(f.errorMessage||"The local sync coordinator command failed.",f.errorCode||"SYNC_COORDINATOR_COMMAND_FAILED",409);if(f.status==="superseded"){const h=v2(f);if(!h)return Eu(n,r.workspaceId,d),f;if(p.size>=f2)throw new Yn("The local sync coordinator command reference chain is too long.","SYNC_COORDINATOR_COMMAND_REFERENCE_LIMIT",409);f=await Xh(t,r,h);continue}await l(Math.max(1,s)),f=await Xh(t,r,f.commandId),p.delete(f.commandId)}throw new Yn("The local sync coordinator command did not finish before the browser wait limit.","SYNC_COORDINATOR_COMMAND_WAIT_TIMEOUT",408)}catch(f){const p=tg(f);throw n&&w2(p)&&Eu(n,r.workspaceId,d),p}}function Eu(e,t,r){if(e)try{g2(e,t,r)}catch{}}async function y2(e,t,r){for(let n=0;n<r.maxPollAttempts;n+=1)try{return await Xh(e,t,t.commandId)}catch(s){const i=tg(s);if(i.code==="SYNC_COORDINATOR_COMMAND_NOT_FOUND")return(await e.issueCommand(t)).command;if(!eg(i))throw i;await r.delay(Math.max(1,r.pollIntervalMs))}throw GC()}async function k2(e,t,r){try{return(await e.issueCommand(t)).command}catch(n){const s=tg(n);if(!eg(s))throw s;for(let i=0;i<r.maxPollAttempts;i+=1)try{return await Xh(e,t,t.commandId)}catch(l){const c=tg(l);if(c.code==="SYNC_COORDINATOR_COMMAND_NOT_FOUND")return(await e.issueCommand(t)).command;if(!eg(c))throw c;await r.delay(Math.max(1,r.pollIntervalMs))}throw GC()}}async function Xh(e,t,r){return(await e.readCommand({commandId:r,workspaceId:t.workspaceId,coordinatorGeneration:t.coordinatorGeneration,rootCommandId:t.commandId})).command}function v2(e){if(!e.result||typeof e.result!="object")return null;const t=e.result,r=t.leaderCommandId||t.supersedingCommandId;return typeof r=="string"&&r.trim()?r.trim():null}function eg(e){return e.status===0||e.status===408||e.status===429||e.status>=500}function w2(e){return!eg(e)&&e.code!=="SYNC_COORDINATOR_COMMAND_WAIT_TIMEOUT"}function GC(){return new Yn("The local sync coordinator command did not finish before the browser wait limit.","SYNC_COORDINATOR_COMMAND_WAIT_TIMEOUT",408)}function tg(e){return e instanceof Yn?e:new Yn(e instanceof Error&&e.message.trim()?e.message:"The local sync coordinator request failed.","SYNC_COORDINATOR_REQUEST_FAILED",0)}function b2(e){return new Promise(t=>{setTimeout(t,e)})}const Yk="taskforce:auth-session-changed";function Vb(){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new Event(Yk))}const S2=new HC;function A2(e){const t=e.client||S2,r=Math.max(1e3,e.pollIntervalMs??3e3),[n,s]=o.useState({phase:"idle",snapshot:null,error:null}),i=o.useRef(0),l=o.useRef(0),c=o.useRef(null),d=o.useRef(null),f=o.useRef(null);f.current=n.snapshot;const p=o.useCallback(w=>{const T=c.current;if(T?.workspaceId===e.workspaceId)return T.promise;const E=ok(),x=E?Gb(E,e.workspaceId):null;if(!x)return null;const N=sk({client:t,envelope:x,storage:E,recoverExisting:!0}),v={workspaceId:e.workspaceId,scope:w,promise:N};return c.current=v,N.catch(()=>{}).finally(()=>{c.current===v&&(c.current=null)}),N},[t,e.workspaceId]),g=o.useCallback(w=>{const T=d.current;if(T?.workspaceId===e.workspaceId)return T.promise;const E=ok(),x=E?Gb(E,e.workspaceId,void 0,"priority"):null;if(!x)return null;const N=sk({client:t,envelope:x,storage:E,recoverExisting:!0,storageLane:"priority"}),v={workspaceId:e.workspaceId,scope:w,promise:N};return d.current=v,N.catch(()=>{}).finally(()=>{d.current===v&&(d.current=null)}),N},[t,e.workspaceId]),h=o.useCallback(async(w,T)=>{const E=await t.attachWorkspace({workspaceId:e.workspaceId});if(i.current!==w||l.current!==T)return null;if(E.runtimeResumePending===!0)throw new Yn("The local sync runtime has not resumed yet.",E.runtimeResumeErrorCode||"SYNC_COORDINATOR_RUNTIME_RESUME_PENDING",503);const x=await t.readStatus({workspaceId:e.workspaceId,coordinatorGeneration:E.state.coordinatorGeneration});if(i.current!==w||l.current!==T)return null;if(x.credential.status!=="ready")throw new Yn("The local sync coordinator credential is not ready after attach.","SYNC_COORDINATOR_CREDENTIAL_BLOCKED",409);return f.current=x,s({phase:"ready",snapshot:x,error:null}),p(w),g(w),x},[t,e.workspaceId,p,g]),y=o.useCallback(async()=>{if(!e.enabled||!e.workspaceId)return null;const w=i.current,T=l.current+1;l.current=T;try{const E=f.current;if(!E)return await h(w,T);const x=await t.readStatus({workspaceId:e.workspaceId,coordinatorGeneration:E.state.coordinatorGeneration});return i.current!==w||l.current!==T?null:x.credential.status!=="ready"||x.serverInstanceId!==E.serverInstanceId?await h(w,T):(f.current=x,s({phase:"ready",snapshot:x,error:null}),p(w),g(w),x)}catch(E){if(i.current!==w||l.current!==T)return null;const x=ik(E);if(x.code==="SYNC_COORDINATOR_STALE_GENERATION"||x.code==="SYNC_COORDINATOR_INACTIVE_WORKSPACE")try{return await h(w,T)}catch(N){if(i.current!==w||l.current!==T)return null;const v=ik(N);return s(V=>({phase:"error",snapshot:V.snapshot,error:v})),null}return s(N=>({phase:"error",snapshot:N.snapshot,error:x})),null}},[h,t,e.enabled,e.workspaceId,p,g]);o.useEffect(()=>{const w=i.current+1;if(i.current=w,f.current=null,!e.enabled||!e.workspaceId||typeof window>"u"){s({phase:"idle",snapshot:null,error:null});return}let T=!1,E=null;s({phase:"attaching",snapshot:null,error:null});const x=()=>{T||(E=window.setTimeout(()=>{E=null,y().finally(x)},r))},N=()=>{document.visibilityState==="visible"&&y()},v=()=>{y()},V=()=>{f.current=null,y()},_=()=>{y().then(F=>{if(F?.state.ownershipMode==="server")return t.signalWake({workspaceId:e.workspaceId,coordinatorGeneration:F.state.coordinatorGeneration,source:"connectivity"}).catch(()=>{})})};document.addEventListener("visibilitychange",N),window.addEventListener("focus",v),window.addEventListener("online",_),window.addEventListener(Yk,V);const j=l.current+1;return l.current=j,h(w,j).catch(F=>{i.current!==w||l.current!==j||s({phase:"error",snapshot:null,error:ik(F)})}).finally(x),()=>{T=!0,i.current+=1,E!==null&&window.clearTimeout(E),document.removeEventListener("visibilitychange",N),window.removeEventListener("focus",v),window.removeEventListener("online",_),window.removeEventListener(Yk,V)}},[h,t,e.enabled,e.workspaceId,r,y]);const k=o.useCallback(async(w,T=null)=>{const E=f.current;if(!E)throw new Yn("The local sync coordinator is not attached.","SYNC_COORDINATOR_UNAVAILABLE",409);const x=w==="DisableSync";if(x){const z=d.current;if(z?.workspaceId===e.workspaceId)return z.promise;const M=g(i.current);if(M)return M}const N=c.current;if(!x&&N?.workspaceId===e.workspaceId&&await N.promise,!x){const z=p(i.current);z&&await z}const v={commandId:crypto.randomUUID(),workspaceId:e.workspaceId,coordinatorGeneration:E.state.coordinatorGeneration,type:w,version:1,args:T},V=sk({client:t,envelope:v,storage:ok(),storageLane:x?"priority":"default"}),_={workspaceId:e.workspaceId,scope:i.current,promise:V},j=x?d:c;j.current=_;const F=()=>{j.current===_&&(j.current=null),i.current===_.scope&&e.workspaceId===_.workspaceId&&y()};return V.then(F,F),V},[t,e.workspaceId,y,p,g]),b=o.useCallback(async(w,T=[])=>{const E=f.current;return!E||E.state.ownershipMode!=="server"?!1:(await t.signalWake({workspaceId:e.workspaceId,coordinatorGeneration:E.state.coordinatorGeneration,source:w,eventIds:T}),!0)},[t,e.workspaceId]),C=o.useCallback(async w=>{const T=f.current,E=String(T?.state.activeWorkspaceId||"").trim(),x=String(w||"").trim();if(!T||!E)throw new Yn("The local sync coordinator is not attached to an active workspace.","SYNC_COORDINATOR_UNAVAILABLE",409);if(!x)throw new Yn("The target workspace is required.","SYNC_COORDINATOR_COMMAND_INVALID",400);if(x===E)return T.state;const N=i.current,v=await t.switchWorkspace({commandId:crypto.randomUUID(),expectedActiveWorkspaceId:E,targetWorkspaceId:x,coordinatorGeneration:T.state.coordinatorGeneration,version:1});return i.current===N&&(l.current+=1,f.current=null,s({phase:"attaching",snapshot:null,error:null})),v.state},[t]),S=o.useCallback(async w=>{const T=f.current;if(!T)throw new Yn("The local sync coordinator is not attached.","SYNC_COORDINATOR_UNAVAILABLE",409);if(T.state.ownershipMode===w)return T.state;const E=i.current,x=await t.transferOwnership({commandId:crypto.randomUUID(),workspaceId:e.workspaceId,coordinatorGeneration:T.state.coordinatorGeneration,targetMode:w,version:1});if(i.current===E){const N={...T,state:x.state};f.current=N,s({phase:"ready",snapshot:N,error:null}),y()}return x.state},[t,e.workspaceId,y]);return o.useMemo(()=>({...n,refresh:y,issueCommand:k,signalWake:b,switchWorkspace:C,transferOwnership:S}),[k,y,b,n,C,S])}function ok(){if(typeof window>"u")return null;try{return window.sessionStorage}catch{return null}}function ik(e){return e instanceof Yn?e:new Yn(e instanceof Error&&e.message.trim()?e.message:"The local sync coordinator request failed.","SYNC_COORDINATOR_REQUEST_FAILED",0)}function C2(e){return e.serverCommandMode}function I2(e){return e.runtimeMode==="local"}function Kb(e){const t=String(e.workspaceId||"").trim(),r=e.snapshot,n=r?.state,s=r?.credential,i=r?[r.serverInstanceId,n?.activeWorkspaceId||"",n?.coordinatorGeneration??"",n?.ownershipMode||"",n?.transitionState||"",s?.status||"",s?.coordinatorGeneration??""].join(":"):`${e.phase}:unavailable`;let l,c=!1,d=!1,f=!0;return e.phase!=="ready"||!r||!n||!s?l="coordinator-unavailable":!t||n.activeWorkspaceId!==t?l="workspace-mismatch":s.status!=="ready"||s.workspaceId!==t?l="credential-blocked":s.coordinatorGeneration!==n.coordinatorGeneration?l="generation-mismatch":n.transitionState!=="idle"?l="transition-active":n.ownershipMode==="browser-gateway"?(l="browser-owner",c=!0,f=!1):n.ownershipMode==="server"?(l="server-owner",c=!0,d=!0,f=!1):n.ownershipMode==="stopped"?l="coordinator-stopped":l="transition-active",{browserSchedulingAllowed:l==="browser-owner",coordinatorAuthorityReady:c,serverCommandMode:d,transitionFenced:f,reason:l,authorityEpoch:i}}class _2 extends Error{constructor(t,r){super(t),this.code=r,this.name="WorkspaceSyncTransportGatewayError"}}function T2(e){if(e.type==="handshake")return"handshake";if(e.type==="provision"||e.type==="bootstrap-push")return"bootstrap";if(e.type==="push")return"push";if(e.type==="v3-dispatch")return"v3-dispatch";if(e.type==="initiative-repair"||e.type==="combined-repair"||e.type==="v3-feed-repair"||e.type==="pull"&&e.repairMode===!0||e.type==="v3-feed"&&(e.forceRepair===!0||e.repairCursor))return"repair";if(e.type==="pull"||e.type==="v3-feed"||e.type==="task-comment-audit"||e.type==="content-pull")return"pull";throw x2("The requested sync gateway operation is not supported.")}function x2(e){return new _2(e,"SYNC_COORDINATOR_GATEWAY_OPERATION_INVALID")}function R2(e){return e.type==="v3-dispatch"?9e4:e.type==="initiative-repair"||e.type==="combined-repair"||e.type==="v3-feed-repair"||e.type==="v3-feed"&&(e.forceRepair===!0||e.repairCursor)?75e3:e.type==="push"&&e.repairMode===!0||e.type==="pull"&&e.repairMode===!0?18e4:e.type==="push"||e.type==="bootstrap-push"||e.type==="pull"||e.type==="v3-feed"||e.type==="content-pull"?9e4:e.type==="task-comment-audit"?45e3:2e4}const j2=5e3;function qb(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function P2(e,t){return!qb(e)||e.success!==!0||e.workspaceId!==t||!Array.isArray(e.changes)||typeof e.hasMore!="boolean"||!Object.hasOwn(e,"nextCursor")||!(e.nextCursor===null||typeof e.nextCursor=="string")||e.workspaceMembers!==void 0&&!Array.isArray(e.workspaceMembers)||e.excludedProjections!==void 0&&(!Array.isArray(e.excludedProjections)||e.excludedProjections.some(r=>typeof r!="string"))?!1:e.diagnostics===void 0||qb(e.diagnostics)}function lh(e){return{cursor:e??null}}function rf(e){return{version:1,projection:e.projection,cursor:e.cursor??null,...e.coverage?{coverage:{...e.coverage}}:{}}}async function E2(e,t){const r=await e.text();let n={},s=!1;if(r)try{n=JSON.parse(r),s=!!(n&&typeof n=="object"&&!Array.isArray(n))}catch{n={error:r.slice(0,400)}}const i=e.headers.get("retry-after");let l;if(i){const c=Number.parseInt(i,10);if(Number.isFinite(c)&&c>0)l=c*1e3;else{const d=Date.parse(i),f=d-t;Number.isFinite(d)&&f>0&&(l=f)}}return{result:{ok:e.status>=200&&e.status<300,status:e.status,data:n,...l===void 0?{}:{retryAfterMs:l}},validJsonObject:s}}function N2(e){const t=e.now,r=e.createPermitId||(()=>crypto.randomUUID()),n=new WeakMap,s=p=>{if(p!==e.workspaceId)throw new TypeError("The browser-gateway sync operation workspace does not match its coordinator.")},i=async(p,g="SYNC_COORDINATOR_BROWSER_ABANDONED",h)=>{const k=(await e.client.abandonPermit({permitId:p,workspaceId:e.workspaceId,coordinatorGeneration:e.coordinatorGeneration,errorCode:g}))?.permit;if(!k||k.permitId!==p||k.workspaceId!==e.workspaceId||k.coordinatorGeneration!==e.coordinatorGeneration||k.serverInstanceId!==e.serverInstanceId||k.ownerMode!=="browser-gateway"||h&&(k.operationClass!==h.operationClass||k.operationIdentity!==h.operationIdentity)||!["released","abandoned-clean","abandoned-reconcile-required"].includes(k.state)||h?.acceptedReceipt===!0&&(k.upstreamDisposition!=="accepted"||!["released","abandoned-reconcile-required"].includes(k.state)))throw new Error("The browser-gateway execution permit was not abandoned safely.");return k},l=async(p,g,h)=>{try{await i(p,void 0,h)}catch{}throw g},c=async p=>{if(e.isExecutionAuthorized?.()===!1)throw new Error("The browser-gateway sync authority selection was revoked.");s(p.operation.workspaceId);const g=t(),h=Math.max(1,Math.floor(e.permitDeadlineMs??R2(p.operation)+j2)),y=T2(p.operation),k={operationClass:y,operationIdentity:p.operationIdentity||null},b=r();let C;try{C=await e.client.issuePermit({permitId:b,workspaceId:e.workspaceId,coordinatorGeneration:e.coordinatorGeneration,operationClass:y,operationIdentity:p.operationIdentity||null,lastCommittedCursor:p.previousBoundary,deadlineAt:new Date(g.getTime()+h).toISOString()})}catch(V){return l(b,V,k)}const S=C?.permit;if(!S||S.permitId!==b||S.workspaceId!==e.workspaceId||S.coordinatorGeneration!==e.coordinatorGeneration||S.serverInstanceId!==e.serverInstanceId||S.ownerMode!=="browser-gateway"||S.operationClass!==y||S.operationIdentity!==k.operationIdentity||S.state!=="issued-idle")return l(b,new Error("The browser-gateway execution permit is invalid."),k);let w;try{w=await e.client.executeGateway({permitId:S.permitId,workspaceId:e.workspaceId,coordinatorGeneration:e.coordinatorGeneration,operationIdentity:p.operationIdentity||null,operation:p.operation})}catch(V){return l(b,V,k)}let T;try{T=await E2(w,g.getTime())}catch(V){return l(b,V,k)}const E=T.result;let x;try{x=await e.client.readPermit({permitId:b,workspaceId:e.workspaceId,coordinatorGeneration:e.coordinatorGeneration})}catch(V){return l(b,V,k)}const N=x?.permit;if(!N||N.permitId!==b||N.workspaceId!==e.workspaceId||N.coordinatorGeneration!==e.coordinatorGeneration||N.serverInstanceId!==e.serverInstanceId||N.ownerMode!=="browser-gateway"||N.operationClass!==y||N.operationIdentity!==k.operationIdentity||N.state!=="gateway-complete-awaiting-apply"||!["accepted","rejected","unknown"].includes(N.upstreamDisposition||""))return l(b,new Error("The browser-gateway did not settle its execution permit."),k);if(N.upstreamDisposition==="accepted"&&(p.requireAcceptedJsonObject&&!T.validJsonObject||p.validateAcceptedData&&!p.validateAcceptedData(E.data)))return l(b,new Error("The accepted browser-gateway sync response is invalid."),k);if(!p.applying){if(N.upstreamDisposition==="accepted"){let V;try{V=await e.client.releasePermit({permitId:b,workspaceId:e.workspaceId,coordinatorGeneration:e.coordinatorGeneration})}catch(j){return l(b,j,k)}const _=V?.permit;if(!_||_.permitId!==b||_.workspaceId!==e.workspaceId||_.coordinatorGeneration!==e.coordinatorGeneration||_.serverInstanceId!==e.serverInstanceId||_.ownerMode!=="browser-gateway"||_.operationClass!==y||_.operationIdentity!==k.operationIdentity||_.state!=="released")return l(b,new Error("The browser-gateway execution permit was not released."),k)}else await i(b,void 0,k);return E}if(N.upstreamDisposition!=="accepted")return await i(b,void 0,k),E;if(!p.previousBoundary)return l(b,new Error("A browser-gateway applying request did not declare its prior boundary."),k);const v=Object.freeze({});return n.set(v,{permitId:b,workspaceId:e.workspaceId,previousBoundary:p.previousBoundary,operationClass:y,operationIdentity:k.operationIdentity}),{...E,transferReceipt:{token:v}}},d=(p,g,h)=>{if(s(p),!Array.isArray(g)||g.length===0)throw new TypeError("A browser-gateway apply completion group requires transfer receipts.");const y=g.map(k=>{if(!k||typeof k!="object")throw new TypeError("The browser-gateway transfer receipt is invalid.");const b=k.token;if(!b||typeof b!="object")throw new TypeError("The browser-gateway transfer receipt token is invalid.");const C=n.get(b);if(!C||C.workspaceId!==p)throw new TypeError("The browser-gateway transfer receipt does not belong to this adapter.");if(h&&$a(C.previousBoundary)!==$a(h))throw new TypeError("The browser-gateway transfer receipt starts at a different boundary.");return C});if(new Set(y.map(k=>k.permitId)).size!==y.length)throw new TypeError("The browser-gateway apply completion group contains duplicate receipts.");return y},f=(p,g,h,y)=>{const k=d(p,g,h);return{version:KA,workspaceId:p,coordinatorGeneration:e.coordinatorGeneration,ownerMode:"browser-gateway",serverInstanceId:e.serverInstanceId,permitIds:k.map(b=>b.permitId),previousBoundary:h,expectedBoundary:y}};return{handshakeWorkspace:p=>c({operation:{type:"handshake",workspaceId:p},applying:!1}),provisionWorkspace:p=>c({operation:{type:"provision",...p},applying:!1}),pushWorkspaceChanges:p=>{const{ownership:g}=p,h=th(p.pushBoundary),y=Dh(p.changes);return c({operation:{type:"push",workspaceId:p.workspaceId,idempotencyKey:p.idempotencyKey,changes:p.changes,...p.repairMode===!0?{repairMode:!0}:{},...g.activeV3TaskMetadataIds.length>0?{activeV3TaskMetadataIds:g.activeV3TaskMetadataIds}:{},...g.activeV3TaskLifecycleIds.length>0?{activeV3TaskLifecycleIds:g.activeV3TaskLifecycleIds}:{},...g.activeV3TaskReopenAssigneeIds.length>0?{activeV3TaskReopenAssigneeIds:g.activeV3TaskReopenAssigneeIds}:{},...g.activeV3InitiativeIds.length>0?{activeV3InitiativeIds:g.activeV3InitiativeIds}:{},...g.initiativeProjectionOwner==="v3"?{v3InitiativeProjectionOwned:!0}:{},...g.combinedCoverage?{combinedCoverage:g.combinedCoverage,excludedProjections:g.combinedExcludedProjections||[]}:{}},operationIdentity:p.idempotencyKey,previousBoundary:h,applying:!0,requireAcceptedJsonObject:!0,validateAcceptedData:k=>{try{return fC(k,y),!0}catch{return!1}}})},pullWorkspaceChanges:p=>{const g=p.excludedProjections?.length?GA(p.excludedProjections):null;return c({operation:{type:"pull",...p,...g?{coverage:g}:{},excludedProjections:p.excludedProjections?[...p.excludedProjections]:void 0},previousBoundary:lh(p.cursor),applying:!0,requireAcceptedJsonObject:!0,validateAcceptedData:h=>P2(h,p.workspaceId)})},pullWorkspaceContent:p=>{const{previousCursor:g,...h}=p;return c({operation:{type:"content-pull",...h},previousBoundary:lh(g),applying:!0})},pullInitiativeFeed:p=>c({operation:{type:"v3-feed",...p,limit:p.limit||100},previousBoundary:rf({projection:"initiative",cursor:p.repairCursor||p.cursor}),applying:!0}),pullInitiativeRepair:p=>c({operation:{type:"initiative-repair",...p,limit:p.limit||100},previousBoundary:rf({projection:"initiative",cursor:p.cursor}),applying:!0}),pullCombinedFeed:p=>c({operation:{type:"v3-feed",...p,limit:p.limit||100},previousBoundary:rf({projection:"combined",cursor:p.repairCursor||p.cursor,coverage:p.coverage||kn}),applying:!0}),pullCombinedRepair:p=>c({operation:{type:"combined-repair",...p,limit:p.limit||100,coverage:p.coverage||kn},previousBoundary:rf({projection:"combined",cursor:p.cursor,coverage:p.coverage||kn}),applying:!0}),pullTaskCommentAudit:p=>c({operation:{type:"task-comment-audit",...p,limit:p.limit||50},previousBoundary:rf({projection:"task-comment-audit",cursor:p.cursor}),applying:!0}),abandonTransferReceipts:async({workspaceId:p,receipts:g,errorCode:h})=>{const y=d(p,g);await Promise.all(y.map(k=>i(k.permitId,h,{operationClass:k.operationClass,operationIdentity:k.operationIdentity,acceptedReceipt:!0})))},acknowledgeNonApplyingTransferReceipts:async({workspaceId:p,receipts:g})=>{const h=d(p,g);await Promise.all(h.map(async y=>{const k=await e.client.releasePermit({permitId:y.permitId,workspaceId:p,coordinatorGeneration:e.coordinatorGeneration,...y.operationClass==="push"?{pushBoundary:th(y.previousBoundary)}:{}});if(!k?.permit||k.permit.state!=="released"||k.permit.permitId!==y.permitId||k.permit.workspaceId!==p||k.permit.coordinatorGeneration!==e.coordinatorGeneration||k.permit.serverInstanceId!==e.serverInstanceId||k.permit.ownerMode!=="browser-gateway"||k.permit.operationClass!==y.operationClass)throw new Error("The browser-gateway non-applying transfer receipt was not released.")}))},buildV2ApplyCompletionGroup:({workspaceId:p,previousCursor:g,nextCursor:h,receipts:y})=>f(p,y,lh(g),lh(h)),buildV2PushApplyCompletionGroup:({workspaceId:p,pushBoundary:g,receipts:h})=>f(p,h,th(g),th(g)),buildV3ApplyCompletionGroup:({workspaceId:p,apply:g,receipts:h})=>{const y=d(p,h),k=y[0].previousBoundary;if(!("projection"in k)||k.projection!==g.projection||y.some(S=>$a(S.previousBoundary)!==$a(k)))throw new TypeError("The v3 transfer receipts do not match the applied projection.");const b=g.kind==="repair"&&g.previousCursor===null&&y.every(S=>S.operationClass==="pull");if(k.cursor!==g.previousCursor&&!b)throw new TypeError("The v3 apply does not start at the receipt boundary.");const C=g.kind==="delta"||g.kind==="audit"?"pull":"repair";if(!b&&y.some(S=>S.operationClass!==C))throw new TypeError("The v3 transfer receipt operation does not match the apply.");return f(p,h,k,{...k,cursor:g.nextCursor})}}}function Yb(e){const t=e.current===e.captured&&e.current.mode!=="blocked"&&e.browserSchedulingAllowed;return t||e.onDenied?.(),t}function M2(e){if(!e.authority.browserSchedulingAllowed)return{mode:"blocked",remoteServices:null};const t=String(e.workspaceId||"").trim(),r=e.snapshot,n=r?.state,s=r?.credential;if(e.phase!=="ready"||e.authority.reason!=="browser-owner"||!t||!r||!n||!s||n.activeWorkspaceId!==t||n.ownershipMode!=="browser-gateway"||n.transitionState!=="idle"||s.status!=="ready"||s.workspaceId!==t||s.coordinatorGeneration!==n.coordinatorGeneration||!Number.isSafeInteger(n.coordinatorGeneration)||n.coordinatorGeneration<1||!String(r.serverInstanceId||"").trim())return{mode:"blocked",remoteServices:null};const i=e.createGatewayRemoteServices||N2;let l;return l={mode:"browser-gateway",remoteServices:i({workspaceId:t,coordinatorGeneration:n.coordinatorGeneration,serverInstanceId:r.serverInstanceId,client:e.client,now:()=>new Date,isExecutionAuthorized:()=>e.isSelectionAuthorized?.(l)!==!1}),coordinatorGeneration:n.coordinatorGeneration,serverInstanceId:r.serverInstanceId},l}const Zb={documents:!1,aiProfiles:!1,assets:!1,documentReviewSessions:!1,annotatedAttachmentSessions:!1,taskforceAgents:!1};function D2(e){const{currentWorkspaceId:t,cloudAuthConfigured:r,runtimeMode:n,authSessionResolved:s,isAuthenticated:i,authUserId:l,projectName:c,resolveCloudAuthUrl:d,resolveWebSocketUrl:f,realtimeSyncEnabled:p,localOutboxDispatchEnabled:g,localCoordinatorBrowserAuthorityGateEnabled:h=!1,localCoordinatorClient:y,initiativeFeedActivationEnabled:k,combinedFeedActivationEnabled:b,combinedFeedCoverage:C,tasks:S,archivedTasks:w,deletedTasks:T=[],initiatives:E,workstreams:x,taxonomies:N,taxonomyState:v,setupState:V,globalTheme:_,locale:j,globalWeekStartsOn:F,themeUseGlobalDefault:z,setTasks:M,setArchivedTasks:O,setAuthBlocked:Z,setIsAuthenticated:U,checkAuthSession:ve,setGlobalTheme:te,setCurrentTheme:ce,setSetupState:Le,setLocale:Ie,setGlobalWeekStartsOn:Ye,fetchPlanningEntities:ge}=e,he=o.useMemo(()=>rP(v),[v]),[Ae,ye]=o.useState("disconnected"),[Ne,ae]=o.useState(null),[q,W]=o.useState(null),[K,Re]=o.useState(null),[we,ie]=o.useState(null),[Q,H]=o.useState(null),[se,Pe]=o.useState(!1),[ue,ne]=o.useState("idle"),[Me,pe]=o.useState(null),[le,Ce]=o.useState(!1),[P,ee]=o.useState(0),[Se,_e]=o.useState(null),ke=o.useRef(null),Ze=o.useCallback(D=>{ke.current=D,_e(D)},[]),[st,at]=o.useState([]),[oe,We]=o.useState(""),G=o.useRef(S||[]),Be=o.useRef(w||[]),Xe=o.useRef(T||[]),ze=o.useRef([]),[qe,Te]=o.useState([]),fe=o.useCallback(D=>{ze.current=D,Te(D)},[]),Ee=o.useRef(E||[]),$e=o.useRef(x||[]),rt=o.useRef(v),kt=o.useRef(N||[]),xe=o.useRef([]),St=o.useRef(new Set),[jt,$]=o.useState([]),[Ke,Qe]=o.useState(""),[Ge,At]=o.useState(null),[Nt,Bt]=o.useState(null),[Qt,Xt]=o.useState(0),[nt,Mt]=o.useState(null),ur=o.useRef([]),[je,ot]=o.useState([]),[pt,Ve]=o.useState(""),lt=o.useRef([]),It=o.useRef(new Set),[wt,$t]=o.useState([]),[Yt,qt]=o.useState(""),er=o.useRef([]),_t=o.useRef([]),[Dt,Tt]=o.useState([]),[Xr,Rr]=o.useState(""),la=o.useRef([]),[sa,ea]=o.useState([]),[Ur,Ft]=o.useState(""),ft=o.useRef([]),Rt=o.useRef([]),_r=o.useRef([]),u=o.useRef([]),[Pt,pr]=o.useState(Zb),[Yr,tr]=o.useState("degraded-fallback"),[$r,Lt]=o.useState({accepted:0,duplicateDiscarded:0,outOfOrderDiscarded:0,invalidDiscarded:0,recoveryTriggered:0}),zr=o.useRef(!1),Ir=o.useRef(null),Kt=o.useRef("missing-baseline"),Jr=o.useRef(0),Br=o.useRef(!1),nr=o.useRef(new Set),Zr=o.useRef(""),He=o.useRef(""),Ca=o.useRef(""),da=o.useRef(""),ir=o.useRef(""),ut=o.useRef(""),ka=o.useRef(""),Wt=o.useRef(!1),rr=o.useRef(null),oa=o.useRef(new Set),Mr=o.useRef([]),vn=o.useRef(null),En=o.useRef(""),Ga=o.useRef(()=>Promise.resolve(!1)),Hr=o.useRef(""),Na=o.useRef(async()=>{}),ta=o.useRef(null),ua=o.useRef(null),Qr=o.useRef("idle"),br=o.useCallback(()=>{Ir.current!==null&&(window.clearTimeout(Ir.current),Ir.current=null)},[]),yr=o.useCallback(D=>{if(typeof window>"u")return;br();const L=Math.max(1,Math.floor(Jr.current)+1);Jr.current=L;const Ct=1500*2**Math.max(0,L-1),zt=Number.isFinite(Number(D))?Math.max(0,Math.floor(Number(D))):0,xt=Math.max(Math.min(12e4,Ct),zt);Ir.current=window.setTimeout(()=>{Ir.current=null,Na.current({preferCloudOnFirstSync:!1})},xt)},[br]),Gr=o.useCallback(D=>{pr(L=>L[D]?L:{...L,[D]:!0})},[]),Kr=Object.values(Pt).every(Boolean),dt=o.useMemo(()=>y||new HC,[y]),Ma=I2({runtimeMode:n}),Zt=A2({enabled:Ma,workspaceId:t,client:dt}),Sr=o.useMemo(()=>Kb({workspaceId:t,phase:Zt.phase,snapshot:Zt.snapshot}),[t,Zt.phase,Zt.snapshot,h]),va=o.useMemo(()=>Kb({workspaceId:t,phase:Zt.phase,snapshot:Zt.snapshot}),[t,Zt.phase,Zt.snapshot]),Ya=o.useRef(Sr);o.useLayoutEffect(()=>{Ya.current=Sr},[Sr]);const Ar=o.useCallback(()=>Ya.current.browserSchedulingAllowed,[]),{workspaceRetryAt:ma,isWorkspaceRetryPending:me,workspacePushInFlightRef:it,workspacePullInFlightRef:mt,workspaceLastPushedSignatureRef:ht,workspacePendingSignatureRef:Ht,workspaceLastPushedTaskIdsRef:sr,workspaceDeletedTaskIdsRef:wa,workspaceDeletedTaskWatermarksRef:fr,workspacePullCursorRef:or,clearWorkspaceRetry:Tr,scheduleWorkspaceRetry:ha,persistWorkspaceSyncPatch:ba,applyWorkspaceSyncPatchLocally:nn,readWorkspaceSyncStateSnapshot:kr,loadWorkspaceSyncState:ho,applyWorkspaceSyncStateSnapshot:wn,saveWorkspaceCloudSyncSettings:Bn,acquireWorkspaceSyncLease:Wn,releaseWorkspaceSyncLease:Ta,forceClearWorkspaceSyncLease:Ms,recordWorkspaceSyncCompletion:Vs,wasWorkspaceSyncOperationCompletedRecently:Ks}=Wj({currentWorkspaceId:t,setWorkspaceCloudSyncEnabled:Pe,setWorkspaceSyncPhase:ne,setWorkspaceSyncSetupIntent:pe,setWorkspaceLastPullAt:W,setWorkspaceLastPushAt:Re,setWorkspaceLastErrorMessage:H,isWorkspaceOperationAuthorized:Ar}),ys=o.useCallback(D=>{(D.phase==="attach-cloud"||D.phase==="provision-local")&&(Qr.current=D.phase,ta.current===null&&(ta.current=Date.now()),ua.current=null),wn(D)},[wn]),$n=o.useRef(new Map),Ia=o.useRef(new Map),fn=o.useRef(new Map),xa=o.useRef(""),ks=o.useRef(new Set),sn=o.useRef(new Map),mn=o.useRef(new Set),on=o.useRef(new Map),Zn=o.useRef(new Set),Da=o.useRef(new Map),qs=o.useRef(new Map),vt=o.useRef(new Set),hr=o.useRef(new Map),ga=o.useRef(new Set),ia=o.useRef(new Map),Za=o.useRef(new Set),Ys=o.useRef(new Map),ca=o.useRef(new Set),vs=o.useRef(new Map),Fa=o.useRef(new Set),Jn=o.useRef(new Map),La=o.useRef(new Set),vr=o.useRef(new Map),Ja=o.useRef(new Set),Qn=o.useRef(new Map),cn=o.useRef(new Set),bn=o.useRef(new Map),Ra=o.useRef(new Map),Zs=o.useCallback(D=>D?(sr.current=new Set(D.taskIds),$n.current=D.taskWatermarks,Ia.current=D.taskChangeKeys||new Map,fn.current=D.taskRelationshipChangeKeys||new Map,xa.current=D.taxonomyChangeKey||"",ks.current=new Set(Array.from(D.initiativeWatermarks.keys())),sn.current=D.initiativeWatermarks,mn.current=new Set(Array.from(D.workstreamWatermarks.keys())),on.current=D.workstreamWatermarks,Zn.current=new Set(Array.from(D.aiProfileWatermarks.keys())),Da.current=D.aiProfileWatermarks,qs.current=D.aiProfileChangeKeys||new Map,La.current=new Set(Array.from((D.taskforceAgentWatermarks||new Map).keys())),vr.current=D.taskforceAgentWatermarks||new Map,Ja.current=new Set(Array.from((D.taskforceAgentSkillWatermarks||new Map).keys())),Qn.current=D.taskforceAgentSkillWatermarks||new Map,cn.current=new Set(Array.from((D.agentConversationWatermarks||new Map).keys())),bn.current=D.agentConversationWatermarks||new Map,vt.current=new Set(Array.from(D.documentWatermarks.keys())),hr.current=D.documentWatermarks,ga.current=new Set(Array.from(D.assetWatermarks.keys())),ia.current=D.assetWatermarks,Za.current=new Set(Array.from(D.documentReviewSessionWatermarks.keys())),Ys.current=D.documentReviewSessionWatermarks,ca.current=new Set(Array.from(D.documentReviewCommentWatermarks.keys())),vs.current=D.documentReviewCommentWatermarks,Fa.current=new Set(Array.from(D.annotatedAttachmentSessionWatermarks.keys())),Jn.current=D.annotatedAttachmentSessionWatermarks,Ra.current=D.taskEventWatermarks,Kt.current=null,!0):!1,[sr]),Xn=o.useCallback(()=>({taskIds:sr.current,taskWatermarks:$n.current,taskChangeKeys:Ia.current,taskRelationshipChangeKeys:fn.current,taxonomyChangeKey:xa.current,initiativeWatermarks:sn.current,workstreamWatermarks:on.current,aiProfileWatermarks:Da.current,aiProfileChangeKeys:qs.current,taskforceAgentWatermarks:vr.current,taskforceAgentSkillWatermarks:Qn.current,agentConversationWatermarks:bn.current,documentWatermarks:hr.current,assetWatermarks:ia.current,documentReviewSessionWatermarks:Ys.current,documentReviewCommentWatermarks:vs.current,annotatedAttachmentSessionWatermarks:Jn.current,taskEventWatermarks:Ra.current}),[]),es=o.useCallback(()=>{if(Kt.current==="repair-reset"||Kt.current==="storage-write-failed")return!1;const D=ak(t,he);return!D||D.aiProfileWatermarks.size===0?!1:(Zn.current=new Set(D.aiProfileWatermarks.keys()),Da.current=new Map(D.aiProfileWatermarks),qs.current=new Map(D.aiProfileChangeKeys||[]),!0)},[t,he]),pa=o.useRef(!1),Sn=o.useRef(!1),ln=o.useRef(!1),An=o.useRef(!1),ws=o.useRef(!1),Oa=o.useRef(""),Va=o.useRef(!1),de=3e4,yt=p?3e4:15e3,ar=Math.max(3e4,yt),[gr,Pr]=o.useState(null);o.useEffect(()=>{const D=Date.now();if(n!=="local"||!se||ue!=="active")return;const L=q?Date.parse(q):NaN;if(!Number.isFinite(L))return;const Ct=L+DC-D;if(Ct<=0)return;const zt=window.setTimeout(()=>{Pr(Date.now())},Ct+50);return()=>window.clearTimeout(zt)},[n,se,ue,q]);const ra=o.useMemo(()=>{const D=q?Date.parse(q):NaN,L=K?Date.parse(K):NaN;return Number.isFinite(D)&&Number.isFinite(L)?D>=L?q:K:Number.isFinite(D)?q:Number.isFinite(L)?K:null},[q,K]),Fn=sP({enabled:se,phase:ue,busy:le,retryAt:ma,lastErrorMessage:Q,lastErrorAt:we,lastPullAt:q,lastPushAt:K,nowMs:gr??Date.now(),pendingChanges:P,durableOutbox:Se}),Qa=Fn.status,Ai=Fn.summary,Cn=Fn.recommendedAction,si=o.useCallback(D=>{const L=String(D||"").trim();if(!L)return null;const zt=Wb()[L]?.updatedAt;return typeof zt=="string"&&zt.trim().length>0?zt.trim():null},[]),Nn=o.useCallback((D,L)=>{const Ct=String(D||"").trim(),zt=String(L||"").trim();if(!Ct||!zt)return;const xt=Wb();xt[Ct]={updatedAt:zt},tP(xt)},[]),bs=o.useCallback(()=>{const D=V?.mode==="operations"?"operations":"core";return{theme:_,operatingMode:D,localization:{locale:j,weekStartsOn:F}}},[_,V?.mode,j,F]),Oo=o.useCallback(async D=>{if(!(!D||typeof D!="object")){Br.current=!0;try{const L={},Ct=Pu(D.theme);if(Ct&&(te(Ct),z&&ce(Ct),L.theme=Ct),(D.operatingMode==="core"||D.operatingMode==="operations")&&(Le(zt=>zt&&{...zt,mode:D.operatingMode}),L.setup={mode:D.operatingMode}),D.localization&&typeof D.localization=="object"){const zt={};if(typeof D.localization.locale=="string"&&D.localization.locale.trim().length>0){const Oe=MA(D.localization.locale.trim());Ie(Oe)}const xt=String(D.localization.weekStartsOn||"").trim().toLowerCase();(xt==="sunday"||xt==="monday")&&(Ye(xt),zt.weekStartsOn=xt),Object.keys(zt).length>0&&(L.schedulePreferences=zt)}Object.keys(L).length>0&&await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(L)})}finally{Br.current=!1}}},[z,te,ce,Le,Ie,Ye]),Vt=o.useCallback(async D=>{const L=D?.preferCloudOnFirstSync!==!1;if(!r)return;if(n!=="local"||!i){br(),Jr.current=0,ye("disconnected");return}const Ct=String(l||"").trim();if(!Ct||Ct==="anonymous"){br(),Jr.current=0,ye("disconnected");return}if(!zr.current){ye("syncing"),ae(null),zr.current=!0;try{const zt=await NR({resolveCloudAuthUrl:d,userId:Ct,preferCloudOnFirstSync:L,getLocalUpdatedAt:si,buildLocalSettings:bs,applyRemoteSettings:Oo});if(!zt.success){ye("error"),zt.transient?(ae(zt.error||"Sync failed temporarily. Retrying automatically."),yr(zt.retryAfterMs)):(br(),Jr.current=0,ae(zt.error||"Sync failed."));return}br(),Jr.current=0;const xt=String(zt.updatedAt||"").trim()||new Date().toISOString();Nn(Ct,xt),ye("idle"),ae(null),nr.current.add(Ct),zt.mode==="pulled"&&(Zr.current="")}catch{ye("error"),ae("Sync failed temporarily. Retrying automatically."),yr()}finally{zr.current=!1}}},[r,n,i,l,d,si,bs,Oo,Nn,br,yr]);o.useEffect(()=>{Na.current=Vt},[Vt]),o.useEffect(()=>()=>{br()},[br]);const Sa=o.useCallback(()=>{H(null),ie(null)},[]),hn=o.useCallback(D=>{H(Bb),ie(new Date().toISOString()),ye("error"),ae(Bb),js("workspace_sync_window_contention",{workspaceId:t,operation:D})},[t]),aa=o.useCallback(async D=>{try{return await ba(D)}catch{return nn(D)}},[nn,ba]),Ds=o.useCallback(D=>{aa(D).catch(()=>{})},[aa]),Mn=o.useCallback(()=>{const D={...Xn(),taxonomyStateFingerprint:he},L=$b(t,D);return aa({pushBaseline:NC(D)}).catch(()=>{}),L},[Xn,t,aa,he]);o.useEffect(()=>{He.current="",Ca.current="",da.current="",ir.current="",ut.current="",ka.current="",Oa.current="",Va.current=!1,at([]),We(""),ur.current=[],$([]),Qe(""),ot([]),Ve(""),er.current=[],_t.current=[],$t([]),qt(""),la.current=[],Tt([]),Rr(""),ft.current=[],Rt.current=[],u.current=[],ea([]),Ft(""),pr(Zb),H(null),ie(null),ee(0),oa.current=new Set,Mr.current=[],$n.current=new Map,Ia.current=new Map,fn.current=new Map,xa.current="",ks.current=new Set,sn.current=new Map,mn.current=new Set,on.current=new Map,Zn.current=new Set,Da.current=new Map,qs.current=new Map,vt.current=new Set,hr.current=new Map,ga.current=new Set,ia.current=new Map,Za.current=new Set,Ys.current=new Map,ca.current=new Set,vs.current=new Map,Fa.current=new Set,Jn.current=new Map,La.current=new Set,vr.current=new Map,Ja.current=new Set,Qn.current=new Map,cn.current=new Set,bn.current=new Map,Ra.current=new Map,Sn.current=!!kr().startupFullReconcileCompletedAt,go.current=!1;const D=ak(t,he);Zs(D)||(Kt.current="missing-baseline")},[t,Zs,he]),o.useEffect(()=>{if(Kt.current!=="missing-baseline")return;const D=ak(t,he);if(Zs(D))return;const L=MC(kr().pushBaseline,he);Zs(L)&&$b(t,{...Xn(),taxonomyStateFingerprint:he})},[Xn,t,Zs,kr,he,se,ue]),o.useEffect(()=>{Sn.current=!!kr().startupFullReconcileCompletedAt},[t,kr,q,ue]);const Ls=o.useCallback(D=>{ha(()=>Ga.current(),{minDelayMs:D})},[ha]);o.useEffect(()=>{pP({workspaceSyncPhase:ue,lastBootstrapPhaseRef:Qr,bootstrapPhaseStartedAtRef:ta,bootstrapLastProgressAtRef:ua})},[ue]),o.useEffect(()=>fP({currentWorkspaceId:t,workspaceCloudSyncEnabled:se,workspaceSyncPhase:ue,workspacePullInFlightRef:mt,workspacePushInFlightRef:it,bootstrapPhaseStartedAtRef:ta,bootstrapLastProgressAtRef:ua,isExecutionAuthorized:Ar,setWorkspaceLastErrorMessage:D=>H(D),setWorkspaceLastErrorAt:D=>ie(D),setUserGlobalSyncStatus:ye,setUserGlobalSyncError:D=>ae(D),setWorkspaceSyncBusy:Ce,persistWorkspaceSyncPatchSafely:Ds}),[t,se,ue,Ds,mt,it,Sr.authorityEpoch,Ar]),o.useEffect(()=>{G.current=S||[]},[S]),o.useEffect(()=>{Be.current=w||[]},[w]),o.useEffect(()=>{let D=!1;return fetch("/api/taskforce/task-relationships",{method:"GET",credentials:"include"}).then(L=>L.ok?L.json():null).then(L=>{!D&&Array.isArray(L?.relationships)&&fe(L.relationships)}).catch(()=>{}),()=>{D=!0}},[w,t,S,fe]),o.useEffect(()=>{Xe.current=T||[],wa.current=new Set((T||[]).map(D=>String(D?.taskId||"").trim()).filter(D=>D.length>0)),fr.current=new Map((T||[]).map(D=>[String(D?.taskId||"").trim(),String(D?.deletedAt||"").trim()]).filter(([D,L])=>D.length>0&&Number.isFinite(Date.parse(L))))},[T,wa,fr]),o.useEffect(()=>{Ee.current=E||[]},[E]),o.useEffect(()=>{$e.current=x||[]},[x]),o.useEffect(()=>{rt.current=v,kt.current=N||[]},[N,v]);const Ss=o.useRef(!1),go=o.useRef(!1),ts=o.useMemo(()=>({repairMode:An,forceFullAiProfilePush:Ss,pushInFlight:it,pullInFlight:mt,pullAfterPushRequested:ws,pendingPushReplay:vn,blockedPushSignature:En,lastPushedSignature:ht,pendingSignature:Ht,lastPushedTaskIds:sr,deletedTaskIds:wa,deletedTaskWatermarks:fr,pullCursor:or,lastPushedWatermarks:$n,lastPushedTaskChangeKeys:Ia,lastPushedTaskRelationshipChangeKeys:fn,lastPushedTaxonomyChangeKey:xa,lastPushedInitiativeIds:ks,lastPushedInitiativeWatermarks:sn,lastPushedWorkstreamIds:mn,lastPushedWorkstreamWatermarks:on,lastPushedAiProfileIds:Zn,lastPushedAiProfileWatermarks:Da,lastPushedAiProfileChangeKeys:qs,lastPushedDocumentPaths:vt,lastPushedDocumentWatermarks:hr,lastPushedAssetPaths:ga,lastPushedAssetWatermarks:ia,lastPushedDocumentReviewSessionIds:Za,lastPushedDocumentReviewSessionWatermarks:Ys,lastPushedDocumentReviewCommentIds:ca,lastPushedDocumentReviewCommentWatermarks:vs,lastPushedAnnotatedAttachmentSessionIds:Fa,lastPushedAnnotatedAttachmentSessionWatermarks:Jn,lastPushedTaskforceAgentIds:La,lastPushedTaskforceAgentWatermarks:vr,lastPushedTaskforceAgentSkillIds:Ja,lastPushedTaskforceAgentSkillWatermarks:Qn,lastPushedAgentConversationIds:cn,lastPushedAgentConversationWatermarks:bn,lastPushedTaskEventWatermarks:Ra,baselineResetReason:Kt,captureAttachBootstrapBaseline:Va,attachBootstrapBaselineSignature:Oa,startupRepairRan:pa,startupFullReconcileRan:Sn,startupFullReconcileRequested:ln,fullReconcileInFlight:go,lastBootstrapPhase:Qr,bootstrapPhaseStartedAtMs:ta,bootstrapLastProgressAtMs:ua,realtimeSuppressedEventQueue:Mr}),[]),rs=o.useMemo(()=>l2(),[]),Un=o.useRef(null),na=o.useMemo(()=>M2({workspaceId:t,phase:Zt.phase,snapshot:Zt.snapshot,authority:Sr,client:dt,isSelectionAuthorized:D=>Un.current===D&&Ar()}),[Sr.authorityEpoch,Sr.browserSchedulingAllowed,Sr.reason,t,dt,Zt.phase,Zt.snapshot?.credential.coordinatorGeneration,Zt.snapshot?.credential.status,Zt.snapshot?.credential.workspaceId,Zt.snapshot?.serverInstanceId,Zt.snapshot?.state.activeWorkspaceId,Zt.snapshot?.state.coordinatorGeneration,Zt.snapshot?.state.ownershipMode,Zt.snapshot?.state.transitionState,h]),Js=na.remoteServices;o.useLayoutEffect(()=>(Un.current=na,()=>{Un.current===na&&(Un.current=null)}),[na]);const yo=o.useCallback(async()=>{const D=na,L=Un.current??{mode:"blocked",remoteServices:null};return!Js||!Yb({current:L,captured:D,browserSchedulingAllowed:Ar()})?{success:!1,statusCode:409,transient:!0,error:"Browser workspace sync authority changed before cloud readiness validation."}:bR({cloudAuthConfigured:r,runtimeMode:n,isAuthenticated:i,resolveCloudAuthUrl:d,workspaceId:t,workspaceName:c||t,allowProvisionOnMismatch:ue!=="attach-cloud",remoteServices:Js})},[r,t,i,Ar,c,d,n,Js,ue,na]),Bo=o.useRef(t);Bo.current=t;const oi=o.useCallback(()=>kj({workspaceId:Bo.current,tasks:G.current,archivedTasks:Be.current,taskRelationships:ze.current,deletedTasks:Xe.current,pendingDeletedTaskIds:wa.current,pendingDeletedTaskWatermarks:fr.current,initiatives:Ee.current,workstreams:$e.current,taxonomies:kt.current,taxonomyState:rt.current,aiProfiles:ur.current,documents:xe.current,assets:lt.current,currentDocumentPaths:St.current,currentAssetPaths:It.current,documentReviewSessions:er.current,documentReviewComments:_t.current,annotatedAttachmentSessions:la.current,taskforceAgents:ft.current,agentRoles:Rt.current,taskforceAgentSkills:_r.current,agentConversations:u.current}),[]),ii=o.useCallback(D=>{const L=oi();return wj({snapshot:L,forceAllAiProfiles:D?.forceAllAiProfiles===!0,baseline:{lastPushedTaskIds:sr.current,lastPushedWatermarks:$n.current,lastPushedTaskChangeKeys:Ia.current,lastPushedTaskRelationshipChangeKeys:fn.current,lastPushedTaxonomyChangeKey:xa.current,lastPushedInitiativeIds:ks.current,lastPushedInitiativeWatermarks:sn.current,lastPushedWorkstreamIds:mn.current,lastPushedWorkstreamWatermarks:on.current,lastPushedAiProfileIds:Zn.current,lastPushedAiProfileWatermarks:Da.current,lastPushedAiProfileChangeKeys:qs.current,lastPushedDocumentPaths:vt.current,lastPushedDocumentWatermarks:hr.current,lastPushedAssetPaths:ga.current,lastPushedAssetWatermarks:ia.current,lastPushedDocumentReviewSessionIds:Za.current,lastPushedDocumentReviewSessionWatermarks:Ys.current,lastPushedDocumentReviewCommentIds:ca.current,lastPushedDocumentReviewCommentWatermarks:vs.current,lastPushedAnnotatedAttachmentSessionIds:Fa.current,lastPushedAnnotatedAttachmentSessionWatermarks:Jn.current,lastPushedTaskforceAgentIds:La.current,lastPushedTaskforceAgentWatermarks:vr.current,lastPushedTaskforceAgentSkillIds:Ja.current,lastPushedTaskforceAgentSkillWatermarks:Qn.current,lastPushedAgentConversationIds:cn.current,lastPushedAgentConversationWatermarks:bn.current,lastPushedTaskEventWatermarks:Ra.current,baselineResetReason:Kt.current}})},[oi]),as=o.useCallback(D=>ii(D).payload,[ii]),Ka=o.useCallback((D,L)=>{if(n==="local")try{const Ct={...L,workspaceId:D,details:jg(L.details)};fetch("/api/taskforce/sync/events",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ct)}).catch(zt=>{js("sync_event_post_failed",{workspaceId:D,eventType:L.eventType,status:L.status,error:String(zt?.message||zt||"")})})}catch(Ct){js("sync_event_post_failed",{workspaceId:D,eventType:L.eventType,status:L.status,error:String(Ct?.message||Ct||"")})}},[n]),In=o.useCallback(()=>bC(oi()),[oi]),Ci=o.useMemo(()=>JSON.stringify({tasks:(S||[]).map(D=>({id:String(D.id||"").trim(),updatedAt:String(D.updatedAt||D.createdAt||"").trim(),status:String(D.status||"").trim(),referenceNumber:D.referenceNumber??null,localReferenceNumber:D.localReferenceNumber??null})).sort((D,L)=>D.id.localeCompare(L.id)),archivedTasks:(w||[]).map(D=>({id:String(D.id||"").trim(),updatedAt:String(D.updatedAt||D.createdAt||"").trim(),status:String(D.status||"").trim(),referenceNumber:D.referenceNumber??null,localReferenceNumber:D.localReferenceNumber??null})).sort((D,L)=>D.id.localeCompare(L.id)),initiatives:(E||[]).map(D=>({id:String(D.id||"").trim(),updatedAt:String(D.updatedAt||D.createdAt||"").trim(),isArchived:!!D.isArchived})).sort((D,L)=>D.id.localeCompare(L.id)),workstreams:(x||[]).map(D=>({id:String(D.id||"").trim(),updatedAt:String(D.updatedAt||D.createdAt||"").trim(),initiativeId:typeof D.initiativeId=="string"?D.initiativeId.trim():"",isArchived:!!D.isArchived})).sort((D,L)=>D.id.localeCompare(L.id)),taskEvents:Bk(S||[],w||[],E||[],x||[]).map(D=>({id:String(D.id||"").trim(),entityType:String(D.entityType||"task").trim(),entityId:String(D.entityId||D.taskId||"").trim(),createdAt:String(D.createdAt||"").trim(),action:String(D.action||"").trim()})).sort((D,L)=>D.id.localeCompare(L.id)),deletedTasks:(T||[]).map(D=>({taskId:String(D?.taskId||"").trim(),deletedAt:String(D?.deletedAt||"").trim()})).filter(D=>D.taskId.length>0&&Number.isFinite(Date.parse(D.deletedAt))).sort((D,L)=>D.taskId.localeCompare(L.taskId)),taxonomies:Array.isArray(N)?N:[],taxonomyState:v&&typeof v=="object"?v:null}),[S,w,T,E,x,N,v]);o2({enabled:g===!0&&n==="local"&&va.browserSchedulingAllowed&&se,workspaceId:t,mutationFingerprint:Ci,authorityScope:na,remoteServices:Js,localServices:rs,isAuthorityCurrent:D=>Un.current===D&&Ar(),onHydratedEventIds:D=>{$o.current.recordSuppressedEventIds(D,{ttlMs:6e4})},onOutboxStatus:Ze});const As=o.useCallback(()=>{if(g!==!0)return!1;const D=ke.current;return D===null||D.recovery!==null&&D.recovery.state!=="completed"},[g]),Ii=o.useMemo(()=>{const D=[];for(const L of S||[]){const Ct=Array.isArray(L.attachments)?L.attachments.length:0;Ct>0&&D.push(`${L.id}:${Ct}`)}return D.join("|")},[S]),_n=o.useCallback(D=>{if(!D)return!1;if(Va.current)return Va.current=!1,Oa.current=D,ht.current=D,ee(0),!0;const L=Oa.current;return L?D===L?(ht.current=D,ee(0),!0):(Oa.current="",!1):!1},[]),Wo=o.useCallback(async()=>{if(n!=="local"||!Rc(t)||r&&(!s||!i))return!1;try{const D=await fetch(`/api/taskforce/taxonomy-state?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!D.ok)return!1;const L=await D.json();return AC(L)?(rt.current=L,kt.current=Array.isArray(L.taxonomies)?L.taxonomies:[],!0):!1}catch(D){return js("taxonomy_snapshot_refresh_failed",{workspaceId:t,error:String(D?.message||D||"")}),!1}},[n,t,r,s,i]),_a=o.useCallback(async()=>{if(n!=="local"||!Rc(t)||r&&(!s||!i))return!1;try{const D=await fetch(`/api/taskforce/sync/workspace/documents?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!D.ok)return!1;const L=await D.json();if(!Array.isArray(L?.documents))return!1;const Ct=Array.isArray(L?.documents)?L.documents.map(Oe=>({path:String(Oe?.path||"").trim(),updatedAt:String(Oe?.updatedAt||"").trim(),content:typeof Oe?.content=="string"?Oe.content:"",assetId:typeof Oe?.assetId=="string"&&Oe.assetId.trim().length>0?Oe.assetId.trim():void 0,documentId:typeof Oe?.documentId=="string"&&Oe.documentId.trim().length>0?Oe.documentId.trim():null,referenceNumber:Number.isFinite(Number(Oe?.referenceNumber))?Math.max(1,Math.floor(Number(Oe.referenceNumber))):null,version:Number.isFinite(Number(Oe?.version))?Math.max(1,Math.floor(Number(Oe.version))):null,taskId:typeof Oe?.taskId=="string"&&Oe.taskId.trim().length>0?Oe.taskId.trim():null,logicalName:typeof Oe?.logicalName=="string"&&Oe.logicalName.trim().length>0?Oe.logicalName.trim():null,caption:typeof Oe?.caption=="string"&&Oe.caption.trim().length>0?Oe.caption.trim():null,originalFilename:typeof Oe?.originalFilename=="string"&&Oe.originalFilename.trim().length>0?Oe.originalFilename.trim():null,linkRole:Oe?.linkRole==="reference"?"reference":"attachment"})).filter(Oe=>Oe.path.length>0):[],zt=new Set(Array.isArray(L?.knownPaths)?L.knownPaths.map(Oe=>String(Oe||"").trim()).filter(Oe=>Oe.length>0):Ct.map(Oe=>Oe.path)),xt=typeof L?.fingerprint=="string"?L.fingerprint:JSON.stringify(Ct.map(Oe=>`${Oe.path}:${Oe.updatedAt}:${Oe.content.length}`).sort());return xt===He.current||(He.current=xt,xe.current=Ct,St.current=zt,at(Ct),We(xt)),!0}catch(D){return js("documents_snapshot_refresh_failed",{workspaceId:t,error:String(D?.message||D||"")}),!1}finally{Gr("documents")}},[n,t,r,s,i,Gr]),Cs=o.useCallback(async()=>{if(n!=="local")return Mt("runtime-not-local"),!1;if(!Rc(t))return Mt("workspace-id-invalid"),!1;if(r&&(!s||!i))return Mt(s?"auth-required":"auth-unresolved"),!1;Mt(null);try{const D=await fetch(`/api/taskforce/sync/workspace/ai-profiles?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!D.ok)return Bt(`HTTP ${D.status}`),At(new Date().toISOString()),!1;const L=await D.json();if(!Array.isArray(L?.aiProfiles))return!1;const Ct=Array.isArray(L?.aiProfiles)?L.aiProfiles:[];Xt(Ct.length);const zt=Array.isArray(L?.aiProfiles)?L.aiProfiles.map(Oe=>Qj(Oe)).filter(Oe=>Oe.id.length>0&&Oe.workspaceId.length>0):[];Bt(null),At(new Date().toISOString());const xt=typeof L?.fingerprint=="string"?L.fingerprint:mj(zt);return xt===Ca.current||(Ca.current=xt,ur.current=zt,$(zt),Qe(xt)),!0}catch(D){return Bt(String(D?.message||D||"unknown-error")),At(new Date().toISOString()),js("ai_profiles_snapshot_refresh_failed",{workspaceId:t,error:String(D?.message||D||"")}),!1}finally{Gr("aiProfiles")}},[n,t,r,s,i,Gr]),jr=o.useCallback(async()=>{if(n!=="local"||!Rc(t)||r&&(!s||!i))return!1;try{const D=await fetch(`/api/taskforce/sync/workspace/assets?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!D.ok)return!1;const L=await D.json();if(!Array.isArray(L?.assets))return!1;const Ct=Array.isArray(L?.assets)?L.assets.map(Oe=>({path:String(Oe?.path||"").trim(),updatedAt:String(Oe?.updatedAt||"").trim(),contentBase64:typeof Oe?.contentBase64=="string"?Oe.contentBase64:"",assetId:typeof Oe?.assetId=="string"&&Oe.assetId.trim().length>0?Oe.assetId.trim():void 0,kind:Oe?.kind==="image"?"image":"file",mimeType:typeof Oe?.mimeType=="string"&&Oe.mimeType.trim().length>0?Oe.mimeType.trim():"application/octet-stream",referenceNumber:Number.isFinite(Number(Oe?.referenceNumber))?Math.max(1,Math.floor(Number(Oe.referenceNumber))):null,taskId:typeof Oe?.taskId=="string"&&Oe.taskId.trim().length>0?Oe.taskId.trim():null,logicalName:typeof Oe?.logicalName=="string"&&Oe.logicalName.trim().length>0?Oe.logicalName.trim():null,caption:typeof Oe?.caption=="string"&&Oe.caption.trim().length>0?Oe.caption.trim():null,originalFilename:typeof Oe?.originalFilename=="string"&&Oe.originalFilename.trim().length>0?Oe.originalFilename.trim():null,linkRole:Oe?.linkRole==="reference"?"reference":Oe?.linkRole==="image"?"image":"attachment"})).filter(Oe=>Oe.path.length>0&&Oe.contentBase64.length>0):[],zt=new Set(Array.isArray(L?.knownPaths)?L.knownPaths.map(Oe=>String(Oe||"").trim()).filter(Oe=>Oe.length>0):Ct.map(Oe=>Oe.path)),xt=typeof L?.fingerprint=="string"?L.fingerprint:JSON.stringify(Ct.map(Oe=>`${Oe.path}:${Oe.updatedAt}:${Oe.contentBase64.length}`).sort());return xt===da.current||(da.current=xt,lt.current=Ct,It.current=zt,ot(Ct),Ve(xt)),!0}catch(D){return js("assets_snapshot_refresh_failed",{workspaceId:t,error:String(D?.message||D||"")}),!1}finally{Gr("assets")}},[n,t,r,s,i,Gr]),nc=o.useCallback(async()=>{if(n!=="local"||!Rc(t)||r&&(!s||!i))return!1;try{const D=await fetch(`/api/taskforce/planning/bootstrap?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!D.ok)return!1;const L=await D.json();if(!Array.isArray(L?.initiatives)||!Array.isArray(L?.workstreams))return!1;const Ct=Array.isArray(L?.initiatives)?L.initiatives.filter(xt=>!!(xt&&typeof xt=="object"&&typeof xt.id=="string")):[],zt=Array.isArray(L?.workstreams)?L.workstreams.filter(xt=>!!(xt&&typeof xt=="object"&&typeof xt.id=="string")):[];return Ee.current=Ct,$e.current=zt,!0}catch(D){return js("planning_snapshot_refresh_failed",{workspaceId:t,error:String(D?.message||D||"")}),!1}},[n,t,r,s,i]),Xa=o.useCallback(async()=>{if(n!=="local"||!Rc(t)||r&&(!s||!i))return!1;try{const D=await fetch(`/api/taskforce/sync/workspace/document-reviews?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!D.ok)return!1;const L=await D.json();if(!Array.isArray(L?.sessions))return!1;const Ct=Array.isArray(L?.sessions)?L.sessions.map(Oe=>({id:String(Oe?.id||"").trim(),assetId:String(Oe?.assetId||"").trim(),documentId:typeof Oe?.documentId=="string"&&Oe.documentId.trim().length>0?Oe.documentId.trim():null,documentVersion:Number.isFinite(Number(Oe?.documentVersion))?Math.max(1,Math.floor(Number(Oe.documentVersion))):null,title:typeof Oe?.title=="string"&&Oe.title.trim().length>0?Oe.title.trim():null,status:Oe?.status==="resolved"?"resolved":"open",comments:Array.isArray(Oe?.comments)?Oe.comments:[],createdByActorId:typeof Oe?.createdByActorId=="string"&&Oe.createdByActorId.trim().length>0?Oe.createdByActorId.trim():null,updatedByActorId:typeof Oe?.updatedByActorId=="string"&&Oe.updatedByActorId.trim().length>0?Oe.updatedByActorId.trim():null,createdAt:String(Oe?.createdAt||"").trim(),updatedAt:String(Oe?.updatedAt||Oe?.createdAt||"").trim(),deletedAt:typeof Oe?.deletedAt=="string"&&Oe.deletedAt.trim().length>0?Oe.deletedAt.trim():null})).filter(Oe=>Oe.id.length>0&&Oe.assetId.length>0):[],zt=Array.isArray(L?.comments)?L.comments.map(Oe=>({id:String(Oe?.id||"").trim(),sessionId:String(Oe?.sessionId||"").trim(),body:typeof Oe?.body=="string"?Oe.body:"",anchor:Oe?.anchor??null,order:Number.isFinite(Number(Oe?.order))?Math.max(0,Math.floor(Number(Oe.order))):0,authorActorId:typeof Oe?.authorActorId=="string"&&Oe.authorActorId.trim().length>0?Oe.authorActorId.trim():null,updatedByActorId:typeof Oe?.updatedByActorId=="string"&&Oe.updatedByActorId.trim().length>0?Oe.updatedByActorId.trim():null,deletedByActorId:typeof Oe?.deletedByActorId=="string"&&Oe.deletedByActorId.trim().length>0?Oe.deletedByActorId.trim():null,createdAt:String(Oe?.createdAt||"").trim(),updatedAt:String(Oe?.updatedAt||Oe?.createdAt||"").trim(),deletedAt:typeof Oe?.deletedAt=="string"&&Oe.deletedAt.trim().length>0?Oe.deletedAt.trim():null})).filter(Oe=>Oe.id.length>0&&Oe.sessionId.length>0):aP(Ct),xt=typeof L?.fingerprint=="string"?L.fingerprint:JSON.stringify([...Ct.map(Oe=>`${Oe.id}:${Oe.updatedAt}:${Oe.status}:${Oe.deletedAt||""}:${Oe.comments.length}`).sort(),...zt.map(Oe=>`${Oe.id}:${Oe.sessionId}:${Oe.updatedAt}:${Oe.deletedAt||""}`).sort()]);return xt===ir.current||(ir.current=xt,er.current=Ct,_t.current=zt,$t(Ct),qt(xt)),!0}catch(D){return js("document_review_sessions_snapshot_refresh_failed",{workspaceId:t,error:String(D?.message||D||"")}),!1}finally{Gr("documentReviewSessions")}},[n,t,r,s,i,Gr]),dn=o.useCallback(async()=>{if(n!=="local"||!Rc(t)||r&&(!s||!i))return!1;try{const D=await fetch(`/api/taskforce/sync/workspace/annotated-attachments?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!D.ok)return!1;const L=await D.json();if(!Array.isArray(L?.sessions))return!1;const Ct=Array.isArray(L?.sessions)?L.sessions.map(xt=>({id:String(xt?.id||"").trim(),workspaceId:String(xt?.workspaceId||"").trim(),taskId:String(xt?.taskId||"").trim(),baseImageAssetId:String(xt?.baseImageAssetId||"").trim(),title:typeof xt?.title=="string"&&xt.title.trim().length>0?xt.title.trim():null,globalInstruction:typeof xt?.globalInstruction=="string"&&xt.globalInstruction.trim().length>0?xt.globalInstruction.trim():null,annotations:Array.isArray(xt?.annotations)?xt.annotations:[],createdByActorId:typeof xt?.createdByActorId=="string"&&xt.createdByActorId.trim().length>0?xt.createdByActorId.trim():null,updatedByActorId:typeof xt?.updatedByActorId=="string"&&xt.updatedByActorId.trim().length>0?xt.updatedByActorId.trim():null,createdAt:String(xt?.createdAt||"").trim(),updatedAt:String(xt?.updatedAt||xt?.createdAt||"").trim(),deletedAt:typeof xt?.deletedAt=="string"&&xt.deletedAt.trim().length>0?xt.deletedAt.trim():null})).filter(xt=>xt.id.length>0&&xt.workspaceId.length>0&&xt.taskId.length>0&&xt.baseImageAssetId.length>0):[],zt=typeof L?.fingerprint=="string"?L.fingerprint:JSON.stringify(Ct.map(xt=>`${xt.id}:${xt.updatedAt}:${xt.taskId}:${xt.baseImageAssetId}:${xt.annotations.length}:${xt.deletedAt||""}`).sort());return zt===ut.current||(ut.current=zt,la.current=Ct,Tt(Ct),Rr(zt)),!0}catch(D){return js("annotated_attachment_sessions_snapshot_refresh_failed",{workspaceId:t,error:String(D?.message||D||"")}),!1}finally{Gr("annotatedAttachmentSessions")}},[n,t,r,s,i,Gr]),Is=o.useCallback(async()=>{if(n!=="local"||!Rc(t)||r&&(!s||!i))return!1;try{const D=await fetch(`/api/taskforce/sync/workspace/taskforce-agents?workspaceId=${encodeURIComponent(t)}`,{method:"GET",credentials:"include"});if(!D.ok)return!1;const L=await D.json();if(!Array.isArray(L?.agents)||!Array.isArray(L?.roles)||!Array.isArray(L?.skills)||!Array.isArray(L?.conversations))return!1;const Ct=Array.isArray(L?.agents)?L.agents.map(Jt=>Xj(Jt)).filter(Jt=>Jt.id.length>0&&Jt.workspaceId.length>0):[],zt=Array.isArray(L?.conversations)?L.conversations.map(Jt=>eP(Jt)).filter(Jt=>Jt.id.length>0&&Jt.workspaceId.length>0&&Jt.agentId.length>0):[],xt=Array.isArray(L?.roles)?L.roles.map(Jt=>bj(Jt,t)).filter(Jt=>!!Jt):[],Oe=L.skills.map(Jt=>Sj(Jt,t)).filter(Jt=>!!(Jt&&Jt.id.length>0&&Jt.workspaceId.length>0)),ya=typeof L?.fingerprint=="string"?L.fingerprint:JSON.stringify([...Ct.map(Jt=>`${Jt.id}:${Jt.updatedAt}:${Jt.deletedAt||""}:${Jt.name}:${Jt.modelTier}`).sort(),...xt.map(Jt=>`${Jt.id}:${Jt.updatedAt}:${Jt.deletedAt||""}:${Jt.currentRevision}:${Jt.currentContentHash}`).sort(),...Oe.map(Jt=>`${Jt.id}:${Jt.updatedAt}:${Jt.revision}:${Jt.contentHash}:${Jt.lifecycleStatus}`).sort(),...zt.map(Jt=>`${Jt.id}:${Jt.agentId}:${Jt.updatedAt}:${Jt.deletedAt||""}:${Jt.messages.length}`).sort()]);return ya===ka.current||(ka.current=ya,ft.current=Ct,Rt.current=xt,_r.current=Oe,u.current=zt,ea(Ct),Ft(ya)),!0}catch(D){return js("taskforce_agents_snapshot_refresh_failed",{workspaceId:t,error:String(D?.message||D||"")}),!1}finally{Gr("taskforceAgents")}},[n,t,r,s,i,Gr]),Md=o.useCallback(()=>{sr.current=new Set([...G.current,...Be.current].map(L=>String(L?.id||"").trim()).filter(L=>L.length>0)),$n.current=new Map([...G.current,...Be.current].map(L=>[String(L?.id||"").trim(),Xo.getWatermark(L)]).filter(([L])=>L.length>0)),Ia.current=new Map([...G.current.map(L=>[String(L?.id||"").trim(),Xo.getChangeKey({...L,isArchived:!1})]),...Be.current.map(L=>[String(L?.id||"").trim(),Xo.getChangeKey({...L,isArchived:!0})])].filter(([L])=>L.length>0)),fn.current=new Map(ze.current.map(L=>[String(L?.id||"").trim(),Uv(L)]).filter(([L])=>L.length>0)),xa.current=wC({taxonomyState:rt.current,taxonomies:kt.current}),ks.current=new Set(Ee.current.map(L=>String(L?.id||"").trim()).filter(L=>L.length>0)),sn.current=new Map(Ee.current.map(L=>[String(L?.id||"").trim(),String(L?.updatedAt||L?.createdAt||"").trim()]).filter(([L])=>L.length>0)),mn.current=new Set($e.current.map(L=>String(L?.id||"").trim()).filter(L=>L.length>0)),on.current=new Map($e.current.map(L=>[String(L?.id||"").trim(),String(L?.updatedAt||L?.createdAt||"").trim()]).filter(([L])=>L.length>0)),Zn.current=new Set(ur.current.map(L=>String(L?.id||"").trim()).filter(L=>L.length>0)),Da.current=new Map(ur.current.map(L=>[String(L?.id||"").trim(),Cf.getWatermark(L)]).filter(([L])=>L.length>0)),qs.current=new Map(ur.current.map(L=>[String(L?.id||"").trim(),Cf.getChangeKey(L)]).filter(([L])=>L.length>0)),vt.current=new Set(xe.current.map(L=>String(L?.path||"").trim()).filter(L=>L.length>0)),hr.current=new Map(xe.current.map(L=>[String(L?.path||"").trim(),String(L?.updatedAt||"").trim()]).filter(([L])=>L.length>0)),ga.current=new Set(lt.current.map(L=>String(L?.path||"").trim()).filter(L=>L.length>0)),ia.current=new Map(lt.current.map(L=>[String(L?.path||"").trim(),String(L?.updatedAt||"").trim()]).filter(([L])=>L.length>0)),Za.current=new Set(er.current.map(L=>String(L?.id||"").trim()).filter(L=>L.length>0)),Ys.current=new Map(er.current.map(L=>[String(L?.id||"").trim(),String(L?.updatedAt||L?.createdAt||"").trim()]).filter(([L])=>L.length>0)),ca.current=new Set(_t.current.map(L=>String(L?.id||"").trim()).filter(L=>L.length>0)),vs.current=new Map(_t.current.map(L=>[String(L?.id||"").trim(),String(L?.updatedAt||L?.createdAt||"").trim()]).filter(([L])=>L.length>0)),Fa.current=new Set(la.current.map(L=>String(L?.id||"").trim()).filter(L=>L.length>0)),Jn.current=new Map(la.current.map(L=>[String(L?.id||"").trim(),String(L?.updatedAt||L?.createdAt||"").trim()]).filter(([L])=>L.length>0)),La.current=new Set([...ft.current.map(L=>String(L?.id||"").trim()),...Rt.current.map(L=>`agent-role:${String(L?.id||"").trim()}`)].filter(L=>L.length>0)),vr.current=new Map([...ft.current.map(L=>[String(L?.id||"").trim(),String(L?.deletedAt||L?.updatedAt||L?.createdAt||"").trim()]),...Rt.current.map(L=>[`agent-role:${String(L?.id||"").trim()}`,String(L?.deletedAt||L?.updatedAt||L?.createdAt||"").trim()])].filter(([L])=>L.length>0)),Ja.current=new Set(_r.current.map(L=>String(L?.id||"").trim()).filter(L=>L.length>0)),Qn.current=new Map(_r.current.map(L=>[String(L?.id||"").trim(),String(L?.updatedAt||L?.createdAt||"").trim()]).filter(([L])=>L.length>0)),cn.current=new Set(u.current.map(L=>String(L?.id||"").trim()).filter(L=>L.length>0)),bn.current=new Map(u.current.map(L=>[String(L?.id||"").trim(),String(L?.deletedAt||L?.updatedAt||L?.createdAt||"").trim()]).filter(([L])=>L.length>0)),Ra.current=new Map(Bk(G.current,Be.current,Ee.current,$e.current).map(L=>[String(L?.id||"").trim(),String(L?.createdAt||"").trim()]).filter(([L])=>L.length>0));const D=Mn();Kt.current=D?null:"storage-write-failed"},[Mn]),kl=o.useCallback(async()=>{const[D,L,Ct]=await Promise.all([fetch("/api/taskforce/tasks",{method:"GET",credentials:"include"}),fetch("/api/taskforce/archive",{method:"GET",credentials:"include"}),fetch("/api/taskforce/task-relationships",{method:"GET",credentials:"include"})]);if(!D.ok||!L.ok||!Ct.ok)throw new Error("Required task collection refresh failed.");const[zt,xt,Oe]=await Promise.all([D.json(),L.json(),Ct.json()]);if(!Array.isArray(zt?.tasks)||!Array.isArray(xt?.archived)||!Array.isArray(Oe?.relationships))throw new Error("Required task collection refresh returned an invalid response.");const ya=zt.tasks.map(Aa=>No(Aa)),Jt=xt.archived.map(Aa=>({...No(Aa),isArchived:!0}));G.current=ya,Be.current=Jt,fe(Oe.relationships),M(ya),O(Jt),await ge().catch(()=>{js("refresh_planning_entities_failed",{workspaceId:t})})},[t,ge,O,M,fe]),{handleSyncAuthFailure:Tn,ensureWorkspaceSyncReady:_i}=o.useMemo(()=>nP({currentWorkspaceId:t,workspaceSyncPhase:ue,clearWorkspaceRetry:Tr,setWorkspaceSyncBusy:Ce,setUserGlobalSyncStatus:ye,setUserGlobalSyncError:D=>ae(D),setWorkspaceLastErrorMessage:D=>H(D),setWorkspaceLastErrorAt:D=>ie(D),reportSyncEvent:Ka,setAuthBlocked:Z,setIsAuthenticated:U,checkAuthSession:ve,ensureCloudWorkspaceReadyForSync:yo,scheduleWorkspaceSyncRetry:Ls,persistWorkspaceSyncPatchSafely:Ds}),[t,ue,Tr,Ka,Z,U,ve,yo,Ls,Ds]),zn=o.useMemo(()=>{const D=na;return Js?ZP({cloudAuthConfigured:r,runtimeMode:n,initiativeFeedActivationEnabled:k,combinedFeedActivationEnabled:b,combinedFeedCoverage:C,workspaceCloudSyncEnabled:se,currentWorkspaceId:t,workspaceSyncPhase:ue,isAuthenticated:i,checkAuthSession:ve,resolveCloudAuthUrl:d,ensureCloudWorkspaceReadyForSync:yo,ensureWorkspaceSyncReady:_i,handleSyncAuthFailure:Tn,clearWorkspaceRetry:Tr,clearWorkspaceIssue:Sa,isWorkspaceRetryPending:me,isDurableRecoveryBlockingOrdinaryPush:As,isExecutionAuthorized:()=>Yb({current:Un.current??{mode:"blocked",remoteServices:null},captured:D,browserSchedulingAllowed:Ar(),onDenied:()=>{const L=Ya.current;!L.serverCommandMode||Hr.current===L.authorityEpoch||(Hr.current=L.authorityEpoch,Ka(t,{eventType:"handshake",status:"error",statusCode:409,errorMessage:"Browser cloud execution was blocked by persisted server ownership.",details:{errorCode:"SYNC_BROWSER_EXECUTION_FENCED_BY_SERVER_OWNER",authorityEpoch:L.authorityEpoch,capturedTransportMode:D.mode}}))}}),scheduleWorkspaceSyncRetry:Ls,persistWorkspaceSyncPatchSafely:Ds,persistWorkspaceSyncPatchBestEffort:aa,persistWorkspaceSyncWatermarksSnapshotBestEffort:Mn,refreshWorkspaceAiProfilePushBaselineFromPersistence:es,reportSyncEvent:Ka,acquireWorkspaceSyncLease:Wn,releaseWorkspaceSyncLease:Ta,recordWorkspaceSyncCompletion:Vs,reportWorkspaceWindowContention:hn,refreshWorkspaceSyncMarkdownDocumentsSnapshot:_a,refreshWorkspaceSyncAiProfilesSnapshot:Cs,refreshWorkspaceSyncAssetsSnapshot:jr,refreshWorkspaceSyncTaxonomySnapshot:Wo,refreshWorkspaceSyncPlanningEntitiesSnapshot:nc,refreshWorkspaceSyncDocumentReviewSessionsSnapshot:Xa,refreshWorkspaceSyncAnnotatedAttachmentSessionsSnapshot:dn,refreshWorkspaceSyncTaskforceAgentsSnapshot:Is,refreshLocalWorkspaceTaskCollections:kl,buildWorkspaceSyncPayload:as,buildWorkspaceSyncSignature:In,seedWorkspaceSnapshotPushBaseline:Md,shouldSuppressAttachBootstrapPush:_n,recordSuppressedEventIds:(...L)=>$o.current.recordSuppressedEventIds(...L),runtime:ts,localServices:rs,remoteServices:Js,setWorkspaceSyncBusy:Ce,setUserGlobalSyncStatus:ye,setUserGlobalSyncError:ae,setWorkspaceLastErrorMessage:H,setWorkspaceLastErrorAt:ie,setWorkspaceLastPullAt:W,setWorkspaceLastPushAt:Re,setWorkspaceSyncPendingChanges:ee,setTasks:M,setArchivedTasks:O,scheduleTask:(L,Ct)=>{const zt=window.setTimeout(L,Ct);return{cancel:()=>window.clearTimeout(zt)}},logDebug:js,notifyAiProfilesMutated:IC,notifyAgentsMutated:_C,notifyAgentSkillsMutated:TC}):null},[r,n,k,b,C,se,t,ue,he,i,ve,d,yo,_i,Tn,Tr,Sa,As,Ls,Ds,aa,Mn,es,Ka,Wn,Ta,Vs,hn,_a,Cs,jr,Wo,nc,Xa,dn,Is,kl,as,In,Md,_n,na,Js,M,O]);o.useEffect(()=>{zn?.resumeDeferredWork()},[Sr.authorityEpoch,zn]),o.useEffect(()=>()=>zn?.dispose(),[zn]);const _s=o.useCallback((D,L)=>zn?zn.pushWorkspaceChangesToCloud(D,L):Promise.resolve(!1),[zn]),Qs=o.useCallback(D=>zn?zn.pullWorkspaceChangesFromCloud(D):Promise.resolve(!1),[zn]),ko=o.useRef(Qs);ko.current=Qs;const $o=o.useRef({handleRealtimeSignal:()=>{},recordSuppressedEventIds:()=>{},clearRealtimePullDebounce:()=>{}}),ns=o.useMemo(()=>yP({cloudAuthConfigured:r,runtimeMode:n,workspaceCloudSyncEnabled:se,workspaceSyncPhase:ue,workspacePullInFlightRef:mt,realtimePullDebounceRef:rr,realtimeSuppressedEventIdsRef:oa,clearWorkspaceRetry:Tr,isWorkspaceRetryPending:me,isExecutionAuthorized:Ar,isServerOwned:()=>C2(Ya.current),signalServerWake:D=>Zt.signalWake("realtime",D),pullWorkspaceChangesFromCloud:Qs}),[r,n,se,ue,Tr,me,Ar,Zt.signalWake,Qs]);$o.current=ns;const ci=f("/taskforce-ws"),li=String(l||"").trim(),vo=!!(p&&(Ar()||Sr.serverCommandMode)&&r&&n==="local"&&se&&s&&i&&li&&li!=="anonymous"&&ci),sc=CC({enabled:vo,workspaceId:t,websocketUrl:ci,onSignal:ns.handleRealtimeSignal,onTelemetry:Lt,userId:li||void 0});o.useEffect(()=>{tr(sc.connectionState)},[sc.connectionState]),o.useEffect(()=>()=>ns.clearRealtimePullDebounce(),[ns]),o.useEffect(()=>{Sr.browserSchedulingAllowed||(Tr(),$o.current.clearRealtimePullDebounce())},[Sr.authorityEpoch,Sr.browserSchedulingAllowed,Tr]);const vl=o.useCallback(async D=>Sr.serverCommandMode?(await Zt.issueCommand(D.enabled?"EnableSync":"DisableSync"),{success:!0}):Ar()?Bn(D,{cloudAuthConfigured:r,isAuthenticated:i,ensureCloudWorkspaceReadyForSync:yo}):{success:!1,error:"Workspace sync ownership is changing. Wait for the coordinator to become ready."},[Bn,r,i,yo,Sr.serverCommandMode,Ar,Zt]),Dc=o.useCallback(async()=>{await Vt({preferCloudOnFirstSync:!1})},[Vt]),ss=o.useMemo(()=>wP({currentWorkspaceId:t,workspaceCloudSyncEnabled:se,workspaceSyncPhase:ue,workspaceLastPullAt:q,runtime:ts,localServices:rs,acquireWorkspaceSyncLease:Wn,releaseWorkspaceSyncLease:Ta,forceClearWorkspaceSyncLease:Ms,clearWorkspaceRetry:Tr,clearWorkspaceIssue:Sa,reportWorkspaceWindowContention:hn,reportSyncEvent:Ka,persistWorkspaceSyncPatch:ba,persistWorkspaceSyncWatermarksSnapshotBestEffort:Mn,buildWorkspaceSyncSignature:In,pullWorkspaceChangesFromCloud:Qs,pushWorkspaceChangesToCloud:_s,cloudAuthConfigured:r,runtimeMode:n,isAuthenticated:i,checkAuthSession:ve,isExecutionAuthorized:Ar,coordinatorGeneration:Zt.snapshot?.state?.coordinatorGeneration??null}),[t,he,se,ue,q,ts,rs,Wn,Ta,Ms,Tr,Sa,hn,Ka,ba,Mn,In,Qs,_s,r,n,i,ve,Ar,Zt.snapshot?.state?.coordinatorGeneration]),Vr=o.useCallback(async()=>{if(Sr.serverCommandMode){const D=Zt.snapshot||await Zt.refresh();return!D||D.credential.status!=="ready"?!1:(await Zt.issueCommand("Retry"),!0)}return Ar()?ss.retryWorkspaceCloudSync():!1},[Sr.serverCommandMode,Ar,Zt,ss]),Dd=o.useCallback(async()=>{if(Sr.serverCommandMode){Zt.issueCommand("Repair").catch(()=>{});return}Ar()&&await ss.resetWorkspaceSyncCursorAndPull()},[Sr.serverCommandMode,Ar,Zt,ss]),Dn=o.useCallback(()=>{const D=zk({cloudAuthConfigured:r,runtimeMode:n,workspaceCloudSyncEnabled:se,currentWorkspaceId:t,workspaceSyncPhase:ue,isAuthenticated:i,repairModeActive:An.current===!0,repairModeBypass:!1,pushInFlight:it.current,pullInFlight:mt.current}),L=me(),Ct=Hk({cloudAuthConfigured:r,runtimeMode:n,workspaceCloudSyncEnabled:se,currentWorkspaceId:t,workspaceSyncPhase:ue,isAuthenticated:i,repairModeActive:An.current===!0,repairModeBypass:!1,retryPending:L,pushInFlight:it.current,pullInFlight:mt.current}),zt=Gk({cloudAuthConfigured:r,runtimeMode:n,workspaceCloudSyncEnabled:se,currentWorkspaceId:t,isAuthenticated:i});return{workspaceId:t,enabled:se,phase:ue,status:Qa,summary:Ai,lastSuccessfulSyncAt:ra,lastPullAt:q,lastPushAt:K,lastErrorAt:we,pendingChanges:P+(Se?.activeDepth||0),lastErrorMessage:Q,recommendedAction:Cn,pushBlockedReason:D.allowed?null:D.reason,pullBlockedReason:Ct.allowed?null:Ct.reason,retryBlockedReason:zt.allowed?null:zt.reason,repairActive:An.current===!0,pushInFlight:it.current===!0,pullInFlight:mt.current===!0,retryPending:L,documentSnapshotCount:st.length,aiProfileSnapshotCount:jt.length,aiProfileSnapshotRawCount:Qt,aiProfileSnapshotLastFetchAt:Ge,aiProfileSnapshotLastFetchError:Nt,aiProfileSnapshotLastSkipReason:nt,assetSnapshotCount:je.length,documentReviewSessionSnapshotCount:wt.length,documentReviewSessionSnapshotFingerprint:Yt,annotatedAttachmentSessionSnapshotCount:Dt.length,annotatedAttachmentSessionSnapshotFingerprint:Xr,taskforceAgentSnapshotCount:sa.length,taskforceAgentSnapshotFingerprint:Ur,lastPushedAiProfileCount:Zn.current.size,lastPushedAiProfileWatermarkCount:Da.current.size,lastPushedTaskforceAgentCount:La.current.size,lastPushedTaskforceAgentWatermarkCount:vr.current.size,lastPushedAgentConversationCount:cn.current.size,lastPushedAgentConversationWatermarkCount:bn.current.size,forceFullAiProfilePushQueued:Ss.current===!0,durableOutbox:Se}},[r,t,n,se,ue,i,Qa,Ai,ra,q,K,we,P,Se,Q,Cn,st.length,jt.length,Qt,Ge,Nt,nt,je.length,wt.length,Yt,Dt.length,Xr,sa.length,Ur,me]);o.useEffect(()=>{Ga.current=Vr},[Vr]);const Os=o.useCallback(()=>{_a(),jr()},[_a,jr]);o.useEffect(()=>{if(!r||n!=="local"||!se||!s||!i)return;_a(),Cs(),jr(),Xa(),dn(),Is();const D=Bs=>{const xs=Bs.detail;(String(xs?.workspaceId||"").trim()||"default")===t&&Os()},L=Bs=>{const xs=Bs.detail;(String(xs?.workspaceId||"").trim()||"default")===t&&(Cs(),jr())},Ct=Bs=>{const xs=Bs.detail;(String(xs?.workspaceId||"").trim()||"default")===t&&String(xs?.reason||"").trim()!=="sync-apply"&&Is()},zt=Bs=>{const xs=Bs.detail;(String(xs?.workspaceId||"").trim()||"default")===t&&String(xs?.reason||"").trim()!=="sync-apply"&&Is()};window.addEventListener(Wk,D),window.addEventListener($k,L),window.addEventListener(Fk,Ct),window.addEventListener(Uk,zt);const xt=window.setInterval(()=>{_a()},de),Oe=window.setInterval(()=>{Cs()},de),ya=window.setInterval(()=>{jr()},de),Jt=window.setInterval(()=>{Xa()},de),Aa=window.setInterval(()=>{dn()},de),xn=window.setInterval(()=>{Is()},de);return()=>{window.removeEventListener(Wk,D),window.removeEventListener($k,L),window.removeEventListener(Fk,Ct),window.removeEventListener(Uk,zt),window.clearInterval(xt),window.clearInterval(Oe),window.clearInterval(ya),window.clearInterval(Jt),window.clearInterval(Aa),window.clearInterval(xn)}},[r,n,se,s,i,t,Os,_a,Cs,jr,Xa,dn,Is,de]),o.useEffect(()=>{!r||n!=="local"||!se||!s||!i||Ii&&Os()},[r,n,se,s,i,Ii,Os]),o.useEffect(()=>{if(!Ar()||!oP({cloudAuthConfigured:r,runtimeMode:n,workspaceCloudSyncEnabled:se,authSessionResolved:s,workspaceSyncPhase:ue,workspaceSyncReferenceSnapshotsReady:Kr}))return;const D=In();if(_n(D)||!D||D===ht.current||En.current===D)return;En.current="";const L=as();if(ee(L.changes.length),it.current||mt.current){Ht.current=D;return}const Ct=window.setTimeout(()=>{if(Ar()){if(it.current||mt.current){Ht.current=In();return}_s(D)}},1500);return()=>window.clearTimeout(Ct)},[r,n,se,s,ue,Kr,In,_n,as,Ci,Ke,oe,pt,Yt,Xr,Ur,_s,it,mt,Sr.authorityEpoch,Ar]),o.useEffect(()=>{if(!Ar()||!iP({cloudAuthConfigured:r,runtimeMode:n,workspaceCloudSyncEnabled:se,authSessionResolved:s,workspaceSyncPhase:ue,workspaceSyncReferenceSnapshotsReady:Kr}))return;const D=window.setInterval(()=>{if(!Ar()||it.current||mt.current||me())return;const L=In();if(!L||L===ht.current||En.current===L)return;En.current="";const Ct=as();ee(Ct.changes.length),Ct.changes.length!==0&&_s(L)},ar);return()=>window.clearInterval(D)},[r,n,se,s,ue,Kr,In,as,_s,me,ar,Sr.authorityEpoch,Ar]),o.useEffect(()=>{r&&n==="local"&&se||(Tr(),Ce(!1))},[r,n,se,Tr]),o.useEffect(()=>{if(!Ar())return;const D=cP({cloudAuthConfigured:r,runtimeMode:n,workspaceCloudSyncEnabled:se,authSessionResolved:s,workspaceSyncPhase:ue,lastPullAt:q,retryPending:me()});if(!D.shouldStart)return;D.shouldKickOffImmediately&&ko.current();const L=window.setInterval(()=>{Ar()&&(Ks(t,"pull",yt)||ko.current())},yt);return()=>{window.clearInterval(L)}},[r,n,se,s,ue,q,t,me,Ks,yt,Sr.authorityEpoch,Ar]),o.useEffect(()=>{if(!Ar()||!lP({cloudAuthConfigured:r,runtimeMode:n,workspaceCloudSyncEnabled:se,authSessionResolved:s,isAuthenticated:i,workspaceSyncPhase:ue}))return;const D=window.setInterval(()=>{Ar()&&(go.current||(go.current=!0,ko.current({forceCursorNull:!0}).finally(()=>{go.current=!1})))},Zj);return()=>window.clearInterval(D)},[r,n,se,s,i,ue,Sr.authorityEpoch,Ar]),o.useEffect(()=>{n!=="local"||!i||!l||l==="anonymous"||Vt({preferCloudOnFirstSync:!0})},[n,i,l,Vt]),o.useEffect(()=>{if(n!=="local"||!i||!l||l==="anonymous"||!nr.current.has(l)||Br.current)return;const D=bs(),L=JSON.stringify(D);if(!Zr.current){Zr.current=L;return}if(L===Zr.current)return;Zr.current=L,Nn(l,new Date().toISOString());const Ct=window.setTimeout(()=>{Vt({preferCloudOnFirstSync:!1})},350);return()=>window.clearTimeout(Ct)},[n,i,l,bs,Nn,Vt]),o.useEffect(()=>{Ar()&&dP({cloudAuthConfigured:r,runtimeMode:n,workspaceCloudSyncEnabled:se,authSessionResolved:s,isAuthenticated:i,workspaceSyncPhase:ue,alreadyRan:pa.current})&&(pa.current=!0,fetch("/api/taskforce/sync/workspace/repair-startup",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:t})}).then(async D=>{if(!D.ok)return;const L=await D.json().catch(()=>({}));L?.applied>0&&(js("startup_repair_applied",{workspaceId:t,applied:L.applied,skipped:L.skipped,failed:L.failed}),_a(),Cs(),jr(),Xa())}).catch(()=>{}))},[r,n,se,s,i,ue,t,_a,Cs,jr,Xa,Sr.authorityEpoch,Ar]);const Ts=Ma&&Zt.phase==="ready"&&Zt.snapshot?.state.activeWorkspaceId===t?{coordinatorGeneration:Zt.snapshot.state.coordinatorGeneration,localDataVersion:Zt.snapshot.state.localDataVersion}:null,wo=Ma?{phase:Zt.phase,snapshot:Zt.snapshot,errorMessage:Zt.error?.message||null}:null,wl=o.useCallback(async D=>{if(n!=="local"||!Ma)return!1;if(Zt.phase!=="ready"||!Zt.snapshot)throw new Yn("The local sync coordinator is not ready to switch workspaces.","SYNC_COORDINATOR_UNAVAILABLE",409);return await Zt.switchWorkspace(D),!0},[Zt,Ma,n]),bl=o.useCallback(async D=>{if(n!=="local"||!Ma)return!1;if(Zt.phase!=="ready"||!Zt.snapshot)throw new Yn("The local sync coordinator is not ready to transfer ownership.","SYNC_COORDINATOR_UNAVAILABLE",409);return await Zt.transferOwnership(D),D==="server"&&(await Zt.issueCommand(se?"EnableSync":"DisableSync"),se&&Zt.issueCommand("Sync").catch(()=>{})),!0},[Zt,Ma,n,se]);return{userGlobalSyncStatus:Ae,setUserGlobalSyncStatus:ye,userGlobalSyncError:Ne,setUserGlobalSyncError:ae,workspaceLastPullAt:q,workspaceLastPushAt:K,workspaceLastErrorAt:we,workspaceLastErrorMessage:Q,workspaceLastSuccessfulSyncAt:ra,workspaceCloudSyncEnabled:se,workspaceSyncPhase:ue,workspaceSyncSetupIntent:Me,workspaceSyncStatus:Qa,workspaceSyncSummary:Ai,workspaceSyncRecommendedAction:Cn,workspaceSyncBusy:le,workspaceSyncPendingChanges:P+(Se?.activeDepth||0),workspaceTaskRelationships:qe,localCoordinatorDataVersion:Ts,localCoordinatorStatus:wo,switchLocalCoordinatorWorkspace:wl,transferLocalCoordinatorOwnership:bl,syncInFlightRef:Wt,workspaceRetryAt:ma,isWorkspaceRetryPending:me,workspacePushInFlightRef:it,workspacePullInFlightRef:mt,workspaceLastPushedSignatureRef:ht,workspacePendingSignatureRef:Ht,workspaceLastPushedTaskIdsRef:sr,workspaceDeletedTaskIdsRef:wa,workspaceDeletedTaskWatermarksRef:fr,workspacePullCursorRef:or,clearWorkspaceRetry:Tr,persistWorkspaceSyncPatch:ba,loadWorkspaceSyncState:ho,applyWorkspaceSyncStateSnapshot:ys,syncUserGlobalSettings:Vt,buildWorkspaceSyncSignature:In,pushWorkspaceChangesToCloud:_s,pullWorkspaceChangesFromCloud:Qs,saveWorkspaceCloudSyncSettings:vl,retryUserGlobalSettingsSync:Dc,retryWorkspaceCloudSync:Vr,resetWorkspaceSyncCursorAndPull:Dd,getWorkspaceSyncDiagnostics:Dn}}function L2(e,t){return typeof t=="number"&&Number.isFinite(t)&&t>0?t:e==="error"?12e3:2600}function O2(){const[e,t]=o.useState(null),r=o.useRef(null),n=o.useCallback(()=>{r.current!==null&&(window.clearTimeout(r.current),r.current=null),t(null)},[]),s=o.useCallback((i,l="info",c,d)=>{if(!i||(r.current!==null&&(window.clearTimeout(r.current),r.current=null),t({message:i,tone:l,ttlMs:c,actionLabel:d?.label,onAction:d?.onAction,ownerKey:d?.ownerKey}),d))return;const f=L2(l,c);r.current=window.setTimeout(()=>{r.current=null,t(null)},f)},[]);return o.useEffect(()=>()=>{r.current!==null&&(window.clearTimeout(r.current),r.current=null)},[]),{uiNotice:e,pushNotice:s,clearNotice:n}}function B2(e){const{resolveCloudAuthUrl:t,currentWorkspaceId:r,normalizedCloudAuthBaseUrl:n,normalizedCloudMcpBaseUrl:s,mergedConfig:i,availableWorkspaces:l,currentTheme:c,configLoaded:d,globalTheme:f,themeUseGlobalDefault:p,keyShortcut:g,jsonBackupEnabled:h,globalJsonBackupEnabled:y,globalWeekStartsOn:k,locale:b,supportedLocales:C,jsonBackupUseGlobalDefault:S,manualComplexityEnabled:w,checklistDropdownEnabled:T,showTaskCardStatusLabel:E,pathSaved:x,settingsSection:N,setupState:v,buildInfo:V,saveSetupMode:_,saveWorkspaceProfile:j,setCurrentTheme:F,handleSaveTheme:z,handleSaveGlobalTheme:M,setKeyShortcut:O,handleJsonBackupEnabledChange:Z,handleSaveGlobalJsonBackupEnabled:U,handleSaveGlobalWeekStartsOn:ve,handleSaveLocale:te,handleManualComplexityEnabledChange:ce,handleChecklistDropdownEnabledChange:Le,handleShowTaskCardStatusLabelChange:Ie,handleResetProjectToGlobal:Ye,handleSaveSettings:ge,initiativeTemplates:he,fetchInitiativeTemplates:Ae,createInitiativeFromTemplate:ye,setShowFolderBrowser:Ne,setBrowserTarget:ae,fetchFolders:q,activeCategories:W,pathValidation:K,taxonomyDisplayLabels:Re,handleUpdateCategory:we,handleRemoveCategory:ie,handleSaveCategory:Q,handleAddPath:H,handleRemovePath:se,handleUpdateCategoryIcon:Pe,handleUpdateCategoryColor:ue,activeTypes:ne,handleSaveType:Me,handleRemoveType:pe,handleUpdateType:le,taxonomies:Ce,handleUpdateTaxonomies:P,priorities:ee,handleUpdatePriorities:Se,analyzeSystemTaxonomyPack:_e,handleApplySystemTaxonomyPack:ke,handleUpdateTaxonomyDisplayLabels:Ze,projectRoot:st,projectName:at,mcpHostRoot:oe,serverHostRoot:We,mcpScriptPath:G,tenantId:Be,runtimeMode:Xe,workspaceSwitchingEnabled:ze,deleteWorkspace:qe,setMcpHostRoot:Te,isAuthenticated:fe}=e,Ee=o.useCallback(async(xe,St)=>{const jt=t(xe),$=new Headers(St?.headers||void 0);if(xe.startsWith("/api/taskforce/settings/mcp/")){const Qe=String(r||"").trim();Qe&&Qe!=="default"&&!$.has("x-taskforce-workspace-id")&&$.set("x-taskforce-workspace-id",Qe)}const Ke={...St,headers:$,credentials:St?.credentials??"include"};if(typeof window<"u"&&/^https?:\/\//i.test(jt))try{new URL(jt,window.location.origin).origin!==window.location.origin&&Ke.mode===void 0&&(Ke.mode="cors")}catch{}return fetch(jt,Ke)},[r,t]),$e=o.useCallback(async()=>{const xe=new Headers,St=String(r||"").trim();St&&St!=="default"&&xe.set("x-taskforce-workspace-id",St);const jt=await fetch("/api/taskforce/mcp/global-cli-health",{method:"POST",headers:xe,credentials:"include"}),$=await jt.json().catch(()=>({}));if(!jt.ok||!$?.result)throw new Error(String($?.error||"Unable to validate the global Taskforce CLI."));return $.result},[r]),rt=o.useCallback(async()=>{const xe=await fetch("/api/taskforce/update/status",{method:"GET",credentials:"include"}),St=await xe.json().catch(()=>({}));if(!xe.ok||!St?.result)throw new Error(String(St?.error||"Unable to determine Taskforce update availability."));return St.result},[]),kt=l.find(xe=>xe.id===r);return{fetchCloudAuthApi:Ee,checkLocalMcpCliHealth:$e,getLocalUpdateStatus:rt,currentTheme:c,configLoaded:d,globalTheme:f,themeUseGlobalDefault:p,keyShortcut:g,jsonBackupEnabled:h,globalJsonBackupEnabled:y,globalWeekStartsOn:k,locale:b,supportedLocales:C,jsonBackupUseGlobalDefault:S,manualComplexityEnabled:w,checklistDropdownEnabled:T,showTaskCardStatusLabel:E,pathSaved:x,initialSection:N,setupState:v,buildInfo:V,onSaveSetupMode:_,onSaveWorkspaceProfile:j,onThemeChange:F,onSaveTheme:z,onSaveGlobalTheme:M,onKeyShortcutChange:O,onJsonBackupEnabledChange:Z,onSaveGlobalJsonBackupEnabled:U,onSaveGlobalWeekStartsOn:ve,onSaveLocale:te,onManualComplexityEnabledChange:ce,onChecklistDropdownEnabledChange:Le,onShowTaskCardStatusLabelChange:Ie,onResetProjectToGlobal:Ye,onSaveSettings:ge,initiativeTemplates:he,onRefreshInitiativeTemplates:Ae,onCreateInitiativeFromTemplate:ye,onShowFolderBrowserChange:Ne,onBrowserTargetChange:ae,onFetchFolders:q,categories:W,pathValidation:K,taxonomyDisplayLabels:Re,onUpdateCategory:we,onRemoveCategory:ie,onSaveCategory:Q,onAddPath:H,onRemovePath:se,onUpdateCategoryIcon:Pe,onUpdateCategoryColor:ue,types:ne,onSaveType:Me,onRemoveType:pe,onUpdateType:le,taxonomies:Ce,onUpdateTaxonomies:P,priorities:ee,onUpdatePriorities:Se,onAnalyzeSystemTaxonomyPack:_e,onApplySystemTaxonomyPack:ke,onUpdateTaxonomyDisplayLabels:Ze,projectRoot:st,projectName:at,mcpHostRoot:oe,serverHostRoot:We,mcpScriptPath:G,tenantId:Be,workspaceId:r,runtimeMode:Xe,cloudAuthBaseUrl:n||i.cloudAuthBaseUrl,cloudMcpBaseUrl:s||void 0,workspaceSwitchingEnabled:ze,currentWorkspaceRole:kt?.role||"member",currentWorkspaceName:String(kt?.name||""),onDeleteWorkspace:qe,onMcpHostRootChange:Te,isAuthenticated:fe}}function W2(e){const{keyShortcut:t,themeUseGlobalDefault:r,runtimeMode:n,jsonBackupUseGlobalDefault:s,globalTheme:i,globalJsonBackupEnabled:l,setCurrentTheme:c,setThemeUseGlobalDefault:d,setGlobalTheme:f,setJsonBackupEnabled:p,setJsonBackupUseGlobalDefault:g,setGlobalJsonBackupEnabled:h,setGlobalWeekStartsOn:y,setLocale:k,setManualComplexityEnabled:b,setChecklistDropdownEnabled:C,setShowTaskCardStatusLabel:S}=e,w=o.useCallback(async()=>{try{const M=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({shortcut:t})});if(!M.ok)throw new Error(`Failed to save global settings (${M.status})`);return!0}catch{return console.error("[Taskforce] Failed to save shortcut"),!1}},[t]),T=o.useCallback(async M=>{c(M),d(!1);try{const O=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:M})});if(!O.ok)throw new Error(`Failed to save config (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save project theme"),!1}},[c,d]),E=o.useCallback(async M=>{f(M),r&&c(M);try{const O=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:M})});if(!O.ok)throw new Error(`Failed to save global settings (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save global theme"),!1}},[f,r,c]),x=o.useCallback(async M=>{if(n==="cloud")return p(!1),g(!1),!1;p(M),g(!1);try{const O=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:M})});if(!O.ok)throw new Error(`Failed to save config (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save project backup setting"),!1}},[n,p,g]),N=o.useCallback(async M=>{if(n==="cloud")return h(!1),s&&p(!1),!1;h(M),s&&p(M);try{const O=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({jsonBackupEnabled:M})});if(!O.ok)throw new Error(`Failed to save global settings (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save global backup setting"),!1}},[n,h,s,p]),v=o.useCallback(async M=>{y(M);try{const O=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schedulePreferences:{weekStartsOn:M}})});if(!O.ok)throw new Error(`Failed to save global settings (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save regional week start setting"),!1}},[y]),V=o.useCallback(async M=>{const O=MA(M);return k(O),!0},[k]),_=o.useCallback(async M=>{b(M);try{const O=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({manualComplexityEnabled:M})});if(!O.ok)throw new Error(`Failed to save config (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save manual complexity setting"),!1}},[b]),j=o.useCallback(async M=>{C(M);try{const O=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({checklistDropdownEnabled:M})});if(!O.ok)throw new Error(`Failed to save config (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save checklist dropdown setting"),!1}},[C]),F=o.useCallback(async M=>{S(M);try{const O=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({showTaskCardStatusLabel:M})});if(!O.ok)throw new Error(`Failed to save config (${O.status})`);return!0}catch{return console.error("[Taskforce] Failed to save task card status label setting"),!1}},[S]),z=o.useCallback(async()=>{d(!0),g(!0),c(i),p(l),b(!1),C(!0),S(!1);try{const M=await fetch("/api/taskforce/config",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({theme:null,jsonBackupEnabled:null,manualComplexityEnabled:null,checklistDropdownEnabled:null,showTaskCardStatusLabel:null})});if(!M.ok)throw new Error(`Failed to save config (${M.status})`);return!0}catch{return console.error("[Taskforce] Failed to reset project settings"),!1}},[d,g,c,i,p,l,b,C,S]);return{handleSaveSettings:w,handleSaveTheme:T,handleSaveGlobalTheme:E,handleJsonBackupEnabledChange:x,handleSaveGlobalJsonBackupEnabled:N,handleSaveGlobalWeekStartsOn:v,handleSaveLocale:V,handleManualComplexityEnabledChange:_,handleChecklistDropdownEnabledChange:j,handleShowTaskCardStatusLabelChange:F,handleResetProjectToGlobal:z}}function $2(e){const{activeCategories:t,activeTab:r,activeTypes:n,archivedTasks:s,browserTarget:i,category:l,configLoaded:c,customCategories:d,refreshTaskCollections:f,fetchTasks:p,filterCategories:g,getCategoryPaths:h,normalizePath:y,pathValidation:k,setBrowserTarget:b,setCategory:C,setCustomCategories:S,setCustomTypes:w,setFilterCategories:T,setPathValidation:E,setPriorities:x,setShowFolderBrowser:N,setTaxonomies:v,tasks:V}=e,_=o.useCallback(async(ae,q)=>{const W=await ae.json().catch(()=>({}));return String(W?.error||q)},[]),j=o.useCallback(()=>[...V,...s],[s,V]),F=o.useCallback(ae=>ae.priorities.find(q=>q.value===2)?.value||ae.priorities[0]?.value||2,[]),z=o.useCallback(async ae=>{if(ae.length!==0)try{const q=await fetch("/api/taskforce/validate-paths",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paths:ae})});if(q.ok){const W=await q.json();E(K=>({...K,...W.results}))}}catch(q){console.error("[Taskforce] Failed to validate paths:",q)}},[E]);o.useEffect(()=>{if(r!=="settings"||!c)return;const ae=[];t.forEach(W=>{h(W).forEach(Re=>{ae.includes(Re)||ae.push(Re)})});const q=ae.filter(W=>!k[W]);q.length>0&&z(q)},[t,r,c,h,k,z]);const M=o.useCallback(async(ae,q)=>{if(c){S(W=>(W.length>0?W:t).map(Re=>Re.value===ae.value?ae:Re)),q&&q!==ae.label&&(l===q&&C(ae.label),g.includes(q)&&T(W=>W.map(K=>K===q?ae.label:K)));try{const Re={categories:(d.length>0?d:t).map(we=>we.value===ae.value?ae:we)};q&&q!==ae.label&&(Re.reassignFrom=q,Re.reassignTo=ae.label),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Re)}),q&&await p()}catch(W){console.error("[Taskforce] Failed to update category",W)}}},[t,l,c,d,p,g,C,S,T]),O=o.useCallback(async ae=>{if(!c)return;const q=ae.trim().toLowerCase().replace(/\s+/g,"-");if(t.some(K=>K.value===q))return;const W={value:q,label:ae.trim(),color:"blue-200",icon:"Folder"};S(K=>[...K.length>0?K:t,W]);try{const Re=[...d.length>0?d:t,W];await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:Re})})}catch(K){console.error("[Taskforce] Failed to create category",K)}},[t,c,d,S]),Z=o.useCallback((ae,q)=>{if(!q.trim())return;const W=t.find(ie=>ie.value===ae);if(!W)return;const K=h(W),Re=q.trim();if(K.includes(Re))return;const we=[...K,Re];M({...W,path:void 0,paths:we}),z(we)},[t,h,M,z]),U=o.useCallback((ae,q)=>{const W=t.find(K=>K.value===ae);W&&M({...W,icon:q})},[t,M]),ve=o.useCallback((ae,q)=>{const W=t.find(K=>K.value===ae);W&&M({...W,color:q})},[t,M]),te=o.useCallback((ae,q)=>{const W=t.find(we=>we.value===ae);if(!W)return;const Re=h(W).filter(we=>we!==q);M({...W,path:void 0,paths:Re})},[t,h,M]),ce=o.useCallback(ae=>{const q=y(ae);if(i&&typeof i=="object"&&i.type==="category"){const W=t.find(K=>K.value===i.value);if(W){const K=h(W);if(!K.includes(q)){const Re=[...K,q];M({...W,path:void 0,paths:Re})}}}N(!1),b(null)},[t,i,h,M,y,b,N]),Le=o.useCallback(async ae=>{if(!c)return;const q=Lu,W=t.find(ie=>ie.value===q),K=W?{...W}:{value:q,label:Ag,icon:"Inbox"},Re=K.label,we=t.find(ie=>ie.value===ae);S(ie=>{let H=(ie.length>0?ie:t).filter(se=>se.value!==ae);return H.some(se=>se.value===q)||(H=[K,...H]),H}),we&&((l===we.label||l===we.value)&&C(q),(g.includes(we.label)||g.includes(we.value))&&T(ie=>{const Q=ie.filter(H=>H!==we.label&&H!==we.value);return Q.includes(q)?Q:[...Q,q]}));try{let ie=(d.length>0?d:t).filter(Q=>Q.value!==ae);ie.some(Q=>Q.value===q)||(ie=[K,...ie]),await fetch("/api/taskforce/categories",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({categories:ie,reassignFrom:we?.label||ae,reassignTo:Re})}),await p()}catch(ie){console.error("[Taskforce] Failed to remove category",ie)}},[t,l,c,d,p,g,C,S,T]),Ie=o.useCallback(async ae=>{if(!ae.trim())return;const q=ae.trim().toLowerCase().replace(/\s+/g,"-");if(n.some(K=>K.value===q))return;const W=[...n,{value:q,label:ae.trim(),status:"active"}];w(W);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:W})})}catch(K){console.error("Failed to save type",K)}},[n,w]),Ye=o.useCallback(async ae=>{const q=n.map(W=>W.value===ae?{...W,status:"retired"}:W);w(q);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:q})}),await p()}catch(W){console.error("Failed to save type",W)}},[n,p,w]),ge=o.useCallback(async(ae,q)=>{const W=n.find(ie=>ie.value===ae);if(!W)return;const K=typeof q.label=="string"?q.label.trim():W.label;if(!K)return;const Re=n.map(ie=>ie.value===ae?{...ie,...q,label:K}:ie);if(JSON.stringify(Re)!==JSON.stringify(n)){w(Re);try{await fetch("/api/taskforce/types",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({types:Re})})}catch(ie){console.error("Failed to update type",ie)}}},[n,w]),he=o.useCallback(async ae=>{if(c){v(ae);try{await fetch("/api/taskforce/taxonomies",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({taxonomies:ae})})}catch(q){console.error("[Taskforce] Failed to save taxonomies",q)}}},[c,v]),Ae=o.useCallback(async ae=>{if(c){x(ae);try{await fetch("/api/taskforce/priorities",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priorities:ae})})}catch(q){console.error("[Taskforce] Failed to save priorities",q)}}},[c,x]),ye=o.useCallback(ae=>{const q=j(),W=new Set(ae.categories.map(H=>H.value)),K=new Set(ae.types.map(H=>H.value)),Re=new Set(ae.priorities.map(H=>Number(H.value))),we=Array.from(new Set(q.map(H=>String(H.category||"").trim()).filter(H=>H.length>0&&!W.has(H)))).sort(),ie=Array.from(new Set(q.map(H=>String(H.type||"").trim()).filter(H=>H.length>0&&!K.has(H)))).sort(),Q=Array.from(new Set(q.map(H=>Number(H.priority)).filter(H=>Number.isFinite(H)&&H>0&&!Re.has(H)))).sort((H,se)=>H-se);return{unmatchedCategoryValues:we,unmatchedTypeValues:ie,incompatiblePriorityValues:Q}},[j]),Ne=o.useCallback(async ae=>{if(!c)return{success:!1,error:"Settings are still loading."};const{pack:q,sections:W,remapExistingValuesToDefault:K,workspaceIdOverride:Re}=ae,we=String(Re||"").trim(),ie=we.length>0,Q=ie?[]:j(),H=Pe=>{if(!we)return Pe;const ue=Pe.includes("?")?"&":"?";return`${Pe}${ue}workspaceId=${encodeURIComponent(we)}`},se=()=>{const Pe={"Content-Type":"application/json"};return we&&(Pe["x-taskforce-workspace-id"]=we),Pe};try{const Pe=await fetch(H("/api/taskforce/taxonomy-library/apply"),{method:"POST",headers:se(),body:JSON.stringify({packId:q.id,sections:W,remapExistingValuesToDefault:K})}),ue=await Pe.json().catch(()=>({}));if(Pe.ok&&ue.taxonomyState)return ie||(W.categories&&ue.taxonomyState.categories&&S(ue.taxonomyState.categories),W.types&&ue.taxonomyState.types&&w(ue.taxonomyState.types),W.priorities&&ue.taxonomyState.priorities&&x(ue.taxonomyState.priorities),await f({isSilent:!0})),{success:!0};if(ue.code!=="WORKSPACE_SYNC_V3_TAXONOMY_ACTIVATION_DISABLED")return{success:!1,error:ue.error||"Failed to apply taxonomy library pack atomically."};if(W.categories){const ne=new Set(q.categories.map(le=>le.value)),Me=K?[...q.categories]:[...q.categories,...t.filter(le=>!ne.has(le.value)).map(le=>({...le,disabled:!0}))];ie||S(Me);const pe=await fetch(H("/api/taskforce/categories"),{method:"POST",headers:se(),body:JSON.stringify({categories:Me})});if(!pe.ok)return{success:!1,error:await _(pe,"Failed to apply category library pack.")}}if(W.types){const ne=new Set(q.types.map(Ce=>Ce.value)),Me=q.types.find(Ce=>Ce.value===fo)?.value||q.types[0]?.value||fo;if(K){const Ce=Q.filter(P=>P.type&&!ne.has(String(P.type))).map(P=>({id:P.id,type:Me}));if(Ce.length>0){const P=await fetch(H("/api/taskforce/bulk-update-fields"),{method:"POST",headers:se(),body:JSON.stringify({updates:Ce})});if(!P.ok)return{success:!1,error:await _(P,"Failed to remap task types to the pack default.")}}}const pe=K?[...q.types]:[...q.types,...n.filter(Ce=>!ne.has(Ce.value)).map(Ce=>({...Ce,status:"retired"}))];ie||w(pe);const le=await fetch(H("/api/taskforce/types"),{method:"POST",headers:se(),body:JSON.stringify({types:pe})});if(!le.ok)return{success:!1,error:await _(le,"Failed to apply task type library pack.")}}if(W.priorities){const ne=new Set(q.priorities.map(Ce=>Ce.value)),Me=Array.from(new Set(Q.map(Ce=>Number(Ce.priority)).filter(Ce=>Number.isFinite(Ce)&&Ce>0&&!ne.has(Ce)))).sort((Ce,P)=>Ce-P);if(Me.length>0&&!K)return{success:!1,error:`This workspace still uses priority levels ${Me.join(", ")}. Enable "Remap unmatched existing values to default" to replace them before applying this pack.`};if(Me.length>0){const Ce=F(q),P=Q.filter(ee=>Me.includes(Number(ee.priority))).map(ee=>({id:ee.id,priority:Ce}));if(P.length>0){const ee=await fetch(H("/api/taskforce/bulk-update-fields"),{method:"POST",headers:se(),body:JSON.stringify({updates:P})});if(!ee.ok)return{success:!1,error:await _(ee,"Failed to remap task priorities to the pack default.")}}}const pe=q.priorities.map(Ce=>({...Ce,value:Number(Ce.value)}));ie||x(pe);const le=await fetch(H("/api/taskforce/priorities"),{method:"POST",headers:se(),body:JSON.stringify({priorities:pe})});if(!le.ok)return{success:!1,error:await _(le,"Failed to apply priority library pack.")}}return ie||await f({isSilent:!0}),{success:!0}}catch(Pe){return console.error("[Taskforce] Failed to apply system taxonomy pack",Pe),{success:!1,error:Pe instanceof Error?Pe.message:"Failed to apply system taxonomy pack."}}},[t,n,c,j,F,_,f,S,w,x]);return{getCategoryPaths:h,validatePaths:z,handleUpdateCategory:M,handleSaveCategory:O,handleAddPath:Z,handleUpdateCategoryIcon:U,handleUpdateCategoryColor:ve,handleRemovePath:te,handleSelectPath:ce,handleRemoveCategory:Le,handleSaveType:Ie,handleRemoveType:Ye,handleUpdateType:ge,handleUpdateTaxonomies:he,handleUpdatePriorities:Ae,analyzeSystemTaxonomyPack:ye,handleApplySystemTaxonomyPack:Ne}}function F2({shouldDeferProtectedApiCalls:e,shouldBlockProtectedApiCalls:t}){const[r,n]=o.useState([]),s=e||t,i=o.useCallback(async()=>{if(s)return[];try{const l=await fetch("/api/taskforce/initiative-templates");if(!l.ok)return[];const c=await l.json(),d=Array.isArray(c?.templates)?c.templates:[];return n(d),d}catch{return[]}},[s]);return{initiativeTemplates:r,fetchInitiativeTemplates:i}}function U2(){const[e,t]=o.useState(!1),r=o.useCallback(async()=>{if(!document.fullscreenElement){try{await document.documentElement.requestFullscreen(),t(!0)}catch(n){console.error(`Error attempting to enable full-screen mode: ${n}`)}return}document.exitFullscreen&&(await document.exitFullscreen(),t(!1))},[]);return o.useEffect(()=>{const n=()=>{t(!!document.fullscreenElement)};return document.addEventListener("fullscreenchange",n),()=>document.removeEventListener("fullscreenchange",n)},[]),{zenMode:e,setZenModeState:t,toggleZenMode:r}}function z2({tasks:e,archivedTasks:t,setTasks:r,setArchivedTasks:n,setLoadingTasks:s,getCurrentWorkspaceId:i,workspaceResetKey:l,shouldDeferProtectedApiCalls:c,shouldBlockProtectedApiCalls:d,handleUnauthorized:f,authRequiredForApi:p}){const g=o.useRef(new Map),h=o.useRef(!1),y=o.useRef(e),k=o.useRef(t),b=o.useRef(null),C=o.useRef(null);o.useEffect(()=>{y.current=e},[e]),o.useEffect(()=>{k.current=t},[t]);const S=o.useCallback(z=>Df(z),[]),w=o.useCallback((z,M)=>M.aborted?z===M.reason?!0:z instanceof DOMException?z.name==="AbortError":String(z?.name||"").toLowerCase()==="aborterror":!1,[]),[T,E]=o.useState([]),x=o.useRef(new Map),N=o.useCallback(z=>{!z.length||typeof window>"u"||(E(M=>Array.from(new Set([...M,...z]))),z.forEach(M=>{const O=x.current.get(M);O&&window.clearTimeout(O);const Z=window.setTimeout(()=>{x.current.delete(M),E(U=>U.filter(ve=>ve!==M))},2e3);x.current.set(M,Z)}))},[]);o.useEffect(()=>()=>{typeof window>"u"||(x.current.forEach(z=>window.clearTimeout(z)),x.current.clear())},[]),o.useEffect(()=>{g.current=new Map,h.current=!1,b.current?.abort("workspace-reset"),b.current=null,C.current?.abort("workspace-reset"),C.current=null,typeof window<"u"&&(x.current.forEach(z=>window.clearTimeout(z)),x.current.clear()),E([])},[l]);const v=o.useCallback(async(z=!1,M)=>{if(!(M?.ignoreAuthGuard===!0)&&(c||d))return;s(!z);const Z=String(i()||"").trim();b.current?.abort("superseded");const U=new AbortController;b.current=U;try{const ve=await fetch("/api/taskforce/tasks",{signal:U.signal});if(ve.status===401){f(),r([]),z||s(!1);return}if(ve.ok){const ce=((await ve.json()).tasks||[]).map(ye=>No(ye));if(String(i()||"").trim()!==Z)return;const Ie=new Map,Ye=[],ge=M?.highlightChangedTaskIds===void 0?null:new Set(M.highlightChangedTaskIds.map(ye=>ex(ce,ye)||ye));for(const ye of ce){const Ne=S(ye);if(Ie.set(ye.id,Ne),!h.current)continue;const ae=g.current.get(ye.id);(!ae||ae!==Ne)&&(ge===null||ge.has(ye.id))&&Ye.push(ye.id)}g.current=Ie,h.current?N(Ye):h.current=!0;const he=y.current,Ae=cb(he,ce);y.current=Ae,Ae!==he&&r(Ae)}}catch(ve){if(w(ve,U.signal))return;console.error("[Taskforce] Failed to fetch tasks:",ve)}finally{b.current===U&&(b.current=null,s(!1))}},[S,i,N,f,r,s,p,c,d]),V=o.useCallback(async(z=!1,M)=>{if(!(M?.ignoreAuthGuard===!0)&&(c||d))return!1;z||s(!0);const Z=String(i()||"").trim();C.current?.abort("superseded");const U=new AbortController;C.current=U;try{const ve=await fetch("/api/taskforce/archive",{signal:U.signal});if(ve.ok){const te=await ve.json();if(String(i()||"").trim()!==Z)return!1;const Le=(te.archived||[]).map(ge=>({...No(ge),isArchived:!0})),Ie=k.current,Ye=cb(Ie,Le);return k.current=Ye,Ye!==Ie&&n(Ye),!0}return!1}catch(ve){return w(ve,U.signal)||console.error("[Taskforce] Failed to fetch archive:",ve),!1}finally{C.current===U&&(C.current=null,z||s(!1))}},[i,w,n,s,c,d]),_=o.useCallback(async z=>{const M=z?.isSilent!==!1,O=z?.ignoreAuthGuard===!0,Z=z?.includeActive!==!1,U=z?.includeArchive!==!1;await Promise.all([Z?v(M,{ignoreAuthGuard:O,highlightChangedTaskIds:z?.highlightChangedTaskIds}):Promise.resolve(!1),U?V(M,{ignoreAuthGuard:O}):Promise.resolve(!1)])},[V,v]),j=o.useCallback(async z=>{await _({isSilent:!0,includeActive:z?.includeActive!==!1,includeArchive:z?.includeArchive!==!1,highlightChangedTaskIds:z?.highlightChangedTaskIds})},[_]),F=o.useCallback(z=>{const M=sx(z,y.current,k.current),O=M.tasks!==y.current,Z=M.archivedTasks!==k.current;y.current=M.tasks,k.current=M.archivedTasks,O&&r(M.tasks),Z&&n(M.archivedTasks)},[r,n]);return{tasksRef:y,archivedTasksRef:k,recentlyChangedTaskIds:T,markRecentlyChangedTasks:N,fetchTasks:v,fetchArchive:V,refreshTaskCollections:_,refreshTaskCollectionsFromInvalidation:j,mergeTaskFromServer:F,getTaskRevisionKey:S}}function H2(e){const{editingTaskId:t,relationshipTasks:r,initiatives:n=[],workstreams:s=[],workstreamInput:i="",resolveWorkstreamIdInput:l,supplementalTasks:c=[],assignee:d,setAssignee:f,setChecklistItems:p,setComments:g}=e,h=o.useRef(null),y=o.useMemo(()=>{if(c.length===0)return r;const S=new Map;return r.forEach(w=>S.set(w.id,w)),c.forEach(w=>S.set(w.id,w)),Array.from(S.values())},[r,c]),k=o.useMemo(()=>{if(t)return y.find(S=>S.id===t)},[y,t]);o.useEffect(()=>{t&&(p(k?.checklistItems||[]),g(k?.comments||[]))},[t,k?.id,k?.updatedAt,k?.checklistItems,k?.comments,p,g]),o.useEffect(()=>{if(!t||!k){h.current=null;return}const S=k.assignee||"unassigned",w=h.current;if(!w||w.taskId!==t){h.current={taskId:t,assignee:S},d!==S&&f(S);return}w.assignee!==S&&(d===w.assignee&&f(S),h.current={taskId:t,assignee:S})},[d,k?.assignee,k?.id,t,f]);const b=o.useMemo(()=>{if(k?.workstreamId)return s.find(S=>S.id===k.workstreamId);if(!(t||!i.trim()))return l?.(i)||void 0},[k,t,l,i,s]),C=o.useMemo(()=>{if(b?.initiativeId)return n.find(S=>S.id===b.initiativeId)},[b,n]);return{currentTask:k,currentTaskWorkstream:b,currentTaskInitiative:C}}const Yv="WS-",Zv="IN-";function Eo(e){return Wu(Yv,e)}function VC(e){return Cg(Yv,e)}function zu(e){return Kf(Yv,e)}function fs(e){return Wu(Zv,e)}function G2(e){return Cg(Zv,e)}function KC(e){return Kf(Zv,e)}function Zk(e,t){const r=String(t||"").trim();if(!r)return null;const n=G2(r);return e.find(s=>s.id===r||fs(s)===r||n!==null&&s.referenceNumber===n)||null}function V2(e){const t={};return e.forEach(r=>{const n=r.defaultValue;if(n!=null){if(Array.isArray(n)){n.length>0&&(t[r.id]=n.map(s=>typeof s=="number"?s:String(s)));return}t[r.id]=typeof n=="number"?n:String(n)}}),t}function K2(e,t){return e.filter(r=>{const n=t[r.id],s=Array.isArray(n)?n.length>0:n!=null&&n!=="";return r.status==="retired"&&!s?!1:r.formEnabled!==!1||r.isRequired===!0||s})}function q2(e){const{activeCategories:t,activeTypes:r,activeTab:n,attachments:s,checklistItems:i,comments:l,description:c,editingTaskId:d,flushPendingAutoSave:f,getDescriptionDraft:p,getPreferredCategoryValue:g,getTitleDraft:h,lastUsedCategory:y,newCommentText:k,relationshipTasks:b,workstreams:C,showArchive:S,taxonomies:w,setActiveTab:T,setAssignee:E,setAttachments:x,setAttachmentsDirty:N,setCategory:v,setChecklistItems:V,setComments:_,setComplexity:j,setDescription:F,setDueDate:z,setEditingTaskId:M,setError:O,setFormTaxonomies:Z,setIsOpen:U,setNewCommentText:ve,setPendingNavigation:te,setWorkstreamInput:ce,setPriority:Le,setScheduledDate:Ie,setShowArchive:Ye,setStatus:ge,setTaskReturnTrail:he,setTitle:Ae,setType:ye,setUnsavedModalOpen:Ne,taskReturnTrail:ae,title:q}=e,W=o.useCallback(()=>r.find(ne=>String(ne.value||"").trim().length>0)?.value||fo,[r]),K=o.useCallback(async ne=>{if(d){await f()&&ne();return}if(!((h?.()??q).trim()!==""||(p?.()??c).trim()!==""||i.length>0||k.trim()!==""||l.length>0||s.length>0)){ne();return}te(()=>ne),Ne(!0)},[s,l.length,c,d,f,p,h,i,k,te,Ne,q]),Re=o.useCallback(()=>{U(!1)},[U]),we=o.useCallback(()=>{M(null),Ae(""),F("");const ne=y,Me=t.some(pe=>pe.label===ne||pe.value===ne);if(ne&&Me){const pe=t.find(le=>le.label===ne||le.value===ne);v(pe?.value||ne)}else v(g(t));ye(W()),Le(2),j(3),ge("task"),E("unassigned"),Ie(""),z(""),ce(""),V([]),Z(V2(w)),_([]),ve(""),x([]),N(!1),O("")},[t,g,W,y,E,x,N,v,V,_,j,F,z,M,O,Z,ve,Le,Ie,ge,Ae,ye,w]),ie=o.useCallback(ne=>{const Me=ne.trim();if(!Me)return null;const pe=Ig(Me);if(pe){const P=b.find(ee=>ee.referenceNumber===pe);if(P)return P}const le=b.find(P=>P.id===Me);if(le)return le;const Ce=b.find(P=>hs(P)===Me);return Ce||null},[b]),Q=o.useCallback(ne=>{const Me=ne.trim();if(!Me)return null;const pe=Me.toLowerCase(),le=VC(Me);if(le){const ee=C.find(Se=>Se.referenceNumber===le);if(ee)return ee}const Ce=C.find(ee=>ee.id===Me);if(Ce)return Ce;const P=C.find(ee=>ee.title.trim().toLowerCase()===pe);return P||null},[C]),H=o.useCallback((ne,Me)=>{Me?.preserveReturnTrail||he([]),M(ne.id),Ae(ne.title),F(ne.description||""),v(ne.category||g(t)),ye(ne.type||W()),Le(typeof ne.priority=="number"?ne.priority:2),j(typeof ne.complexity=="number"?ne.complexity:3),ge(ne.status||"task"),E(ne.assignee||"unassigned"),Ie(ne.scheduledDate||""),z(ne.dueDate||"");const pe=ne.workstreamId&&C.find(le=>le.id===ne.workstreamId)||null;ce(pe?Eo(pe)||pe.id:""),V(ne.checklistItems||[]),_(ne.comments||[]),Z(ne.taxonomies||{}),x(ne.attachments||[]),N(!1),T("add")},[t,g,W,T,E,x,N,v,V,_,j,F,z,M,Z,Le,Ie,ge,he,Ae,ye,C]),se=o.useCallback(ne=>{const Me=b.find(pe=>pe.id===ne);Me&&(n==="add"&&d&&d!==Me.id&&he(pe=>pe[pe.length-1]===d?pe:[...pe,d]),Me.isArchived&&!S&&Ye(!0),H(Me,{preserveReturnTrail:!0}))},[n,d,H,b,Ye,he,S]),Pe=o.useCallback(()=>{if(n!=="add"||!d||ae.length===0)return!1;const ne=[...ae];for(;ne.length>0;){const Me=ne.pop();if(!Me)continue;const pe=b.find(le=>le.id===Me);if(pe)return pe.isArchived&&!S&&Ye(!0),he(ne),H(pe,{preserveReturnTrail:!0}),!0}return he([]),!1},[n,d,H,b,Ye,he,S,ae]),ue=o.useCallback(()=>{he([])},[he]);return{handleNavigation:K,handleClose:Re,resetForm:we,resolveTaskIdInput:ie,resolveWorkstreamIdInput:Q,handleEdit:H,handleOpenTaskById:se,returnToPreviousTask:Pe,clearReturnToParentTask:ue}}function Y2(e){return e.map(t=>({...t}))}function Z2(e){return e.map(t=>({...t}))}function J2(e){return e.map(t=>({...t}))}const Q2={id:"software-development",label:"Software Development",description:"A software-oriented starter pack with developer-focused work types and a 4-level priority scale.",isDefaultStarter:!0,categories:[{value:"default",label:"General",icon:"Inbox"},{value:"product",label:"Product",icon:"Layers",color:"blue-500"},{value:"ui-ux",label:"UI/UX",icon:"Palette",color:"violet-500"},{value:"backend",label:"Backend",icon:"Server",color:"emerald-500"}],types:[{value:"feature",label:"Feature",icon:"Star",color:"teal-500",status:"active"},{value:"bug",label:"Bug",icon:"Bug",color:"red-500",status:"active"},{value:"chore",label:"Chore",icon:"Zap",color:"amber-500",status:"active"},{value:"refactor",label:"Refactor",icon:"Code",color:"blue-500",status:"active"},{value:"documentation",label:"Docs",icon:"Book",color:"sky-500",status:"active"}],priorities:[{value:1,label:"Low",color:"amber-200",icon:"ArrowDown"},{value:2,label:"Medium",color:"yellow-500",icon:"Minus"},{value:3,label:"High",color:"orange-500",icon:"ArrowUp"},{value:4,label:"Critical",color:"red-500",icon:"AlertTriangle"}]},X2=[{id:"general",label:"General",description:"A neutral starter pack for broad project and AI collaboration workflows.",categories:[{value:Lu,label:Ag,icon:"Inbox"}],types:[{value:"task",label:"Task",icon:"CheckSquare",color:"blue-500",status:"active"},{value:"deliverable",label:"Deliverable",icon:"Package",color:"teal-500",status:"active"},{value:"issue",label:"Issue",icon:"AlertCircle",color:"red-500",status:"active"},{value:"idea",label:"Idea",icon:"Lightbulb",color:"amber-500",status:"active"},{value:"review",label:"Review",icon:"Search",color:"violet-500",status:"active"}],priorities:[{value:1,label:"Low",color:"teal-500",icon:"ArrowDown"},{value:2,label:"Medium",color:"blue-500",icon:"Minus"},{value:3,label:"High",color:"amber-500",icon:"ArrowUp"}]},Q2];function qC(){return X2.map(e=>({...e,categories:Y2(e.categories),types:Z2(e.types),priorities:J2(e.priorities)}))}const eE={"red-200":"#eb7a7a","orange-200":"#eba87a","amber-200":"#ebc17a","yellow-200":"#ebd07a","green-200":"#7aeba4","teal-200":"#7aebdf","sky-200":"#7ac8eb","blue-200":"#7aa5eb","indigo-200":"#7a7ceb","violet-200":"#9c7aeb","red-500":"#e42525","orange-500":"#e47325","amber-500":"#e49d25","yellow-500":"#e4b625","green-500":"#25e46b","teal-500":"#25e4cf","sky-500":"#25a9e4","blue-500":"#256ee4","indigo-500":"#2529e4","violet-500":"#5f25e4","red-700":"#951818","orange-700":"#954b18","amber-700":"#956718","yellow-700":"#957718","green-700":"#189546","teal-700":"#189587","sky-700":"#186e95","blue-700":"#184895","indigo-700":"#181b95","violet-700":"#3e1895"},Fee=["red-200","orange-200","amber-200","yellow-200","green-200","teal-200","sky-200","blue-200","indigo-200","violet-200","red-500","orange-500","amber-500","yellow-500","green-500","teal-500","sky-500","blue-500","indigo-500","violet-500","red-700","orange-700","amber-700","yellow-700","green-700","teal-700","sky-700","blue-700","indigo-700","violet-700"];function rn(e){if(e)return eE[e]||e}const wd=[{value:"task",label:"To Do",shortLabel:"To Do",icon:"Square",color:"blue-200"},{value:"on-hold",label:"Blocked",shortLabel:"Blocked",icon:"Pause",color:"amber-500"},{value:"in-progress",label:"Working",shortLabel:"Working",icon:"Play",color:"blue-500"},{value:"review",label:"Review",shortLabel:"Review",icon:"ClipboardCheck",color:"violet-500"},{value:"done",label:"Done",shortLabel:"Done",icon:"SquareCheck",color:"green-500"},{value:"cancelled",label:"Cancelled",shortLabel:"Cancelled",icon:"Ban",color:"var(--status-cancelled)"}],rc=wd.map(({value:e,label:t,icon:r,color:n})=>({value:e,label:t,icon:r,color:n}));function Po(e){const t=String(e||"task").trim().toLowerCase();return t==="completed"?wd.find(r=>r.value==="done")||wd[0]:wd.find(r=>r.value===t)||wd[0]}const YC=["Folder","Code","FileText","Terminal","Database","Cpu","Globe","Layout","Server","Search","Settings","Zap","Shield","Star","Layers","Bug","Box","Book","MessageSquare","Image","Music","Video","Map","Mail","Camera","Heart","Anchor","Rocket","Target","Flag","Bookmark","Briefcase","Puzzle","SquareUserRound","Users","User","Unplug","Clock","Lock","Pencil","TrafficCone","CircleDollarSign","Activity","Wrench","Microscope","Palette","Webhook","FlaskConical","Route","Compass","Landmark","BookOpen","Bot","Cloud","Kanban","Infinity","Monitor","Smartphone","History","Brain","Calendar","Play","Pause","Sparkles","Check","Ban","Circle","CheckCircle","Wind","Github","Square","SquareCheck","CheckSquare","Package","AlertCircle","Lightbulb","ClipboardCheck","ScanSearch","Inbox","HelpCircle","Gauge","FileCode","ArrowDown","Minus","ArrowUp","AlertTriangle","CircleQuestionMark","TriangleAlert"],Hu=YC.reduce((e,t)=>(e[t]=Gs[t]||Td,e),{}),Uee=YC,rg=Object.fromEntries(qC().flatMap(e=>e.types).filter(e=>e.icon&&e.color).reduce((e,t)=>(e.some(([r])=>r===t.value)||e.push([t.value,{icon:t.icon,color:t.color}]),e),[])),tE={PDF:"red-500",DOC:"blue-500",DOCX:"blue-500",CSV:"teal-500",JSON:"amber-500",TXT:"violet-200",MD:"violet-200"};function rE(e){const t=String(e||"").trim().toLowerCase();return rn(rg[t]?.color)||rn("violet-200")||"#9c7aeb"}function zee(e){switch(Number(e)){case 1:return"var(--text-muted)";case 2:return"var(--text-secondary)";case 3:return"var(--priority-high)";case 4:return"var(--priority-critical)";default:return"var(--text-secondary)"}}function aE(e){const t=String(e||"").trim().toUpperCase();return rn(tE[t])||"var(--text-muted)"}const nE=/[\u2010-\u2015\u2212]/g;function Jv(e){return String(e??"").trim().replace(nE,"-").replace(/\s+/g," ").toLowerCase()}function Eg(e){const t=Jv(e);if(!t)return null;const r=t.match(/^(l\s*t|t)\s*(?:-\s*)?(\d+)$/i);return r?`${r[1].replace(/\s+/g,"").toLowerCase()}-${r[2]}`:null}function Ng(e){const t=Jv(e);return{raw:t,tokens:t?t.split(" ").filter(Boolean):[],referenceToken:Eg(e)}}function jo(e,t){const r=String(t??"").trim();r&&e.push(r)}function Su(e,t,r){const n=String(r??"").trim();if(!n)return;const s=t?.find(i=>String(i.value)===n);jo(e,s?.label)}function sE(e,t={}){const r=[];return jo(r,e.title),jo(r,e.description),jo(r,e.id),jo(r,hs(e)),jo(r,e.category),jo(r,e.type),jo(r,e.priority),jo(r,e.status),jo(r,e.assignee||"unassigned"),jo(r,e.canceledReason),Su(r,t.categories,e.category),Su(r,t.types,e.type),Su(r,t.priorities,e.priority),Su(r,rc,e.status),Su(r,t.assigneeOptions,e.assignee||"unassigned"),Object.entries(e.taxonomies||{}).forEach(([n,s])=>{const i=t.taxonomies?.find(c=>c.id===n);jo(r,i?.label),(Array.isArray(s)?s:[s]).forEach(c=>{jo(r,c),Su(r,i?.options,c)})}),r}function ag(e,t,r={}){const n=typeof t=="string"?Ng(t):t;if(!n.raw)return!0;const s=sE(e,r),l=s.map(Jv).filter(Boolean).join(" ");return l.includes(n.raw)||n.referenceToken&&s.map(Eg).some(d=>d?.includes(n.referenceToken))?!0:n.tokens.length>0&&n.tokens.every(c=>l.includes(c))}function oE(e,t){const r=e.taxonomies?.[t];return r==null||r===""?!1:Array.isArray(r)?r.some(n=>String(n).trim().length>0):String(r).trim().length>0}function Zf(e,t){const r=e.filter(s=>s.status!=="retired"),n=e.filter(s=>s.status==="retired"&&t.some(i=>oE(i,s.id)));return[...r,...n.filter(s=>!r.some(i=>i.id===s.id))]}function ZC(e,t=[]){return Zf(e,t).filter(r=>r.sortEnabled===!0).map(r=>({value:`taxonomy:${r.id}`,label:r.status==="retired"?`${r.label} (Retired)`:r.label}))}function Jb(e,t){const r=e.taxonomies?.[t.id];if(r==null||r==="")return null;const n=Array.isArray(r)?r.map(s=>String(s)):[String(r)];for(let s=0;s<t.options.length;s+=1)if(n.includes(String(t.options[s]?.value)))return s;return null}function cd(e,t){return new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()}function ng(e,t,r,n,s=[]){let i=0;if(r==="created")return i=cd(e,t),n==="desc"?i:-i;if(r==="updated"){const l=e.updatedAt||e.createdAt,c=t.updatedAt||t.createdAt;return i=new Date(c).getTime()-new Date(l).getTime(),n==="desc"?i:-i}if(r==="priority"){const l=Yh(e.priority),c=Yh(t.priority);return i=l!==c?c-l:cd(e,t),n==="desc"?i:-i}if(r==="complexity"){const l=typeof e.complexity=="number"?e.complexity:3,c=typeof t.complexity=="number"?t.complexity:3;return i=l!==c?c-l:cd(e,t),n==="desc"?i:-i}if(r.startsWith("taxonomy:")){const l=r.slice(9),c=s.find(p=>p.id===l);if(!c)return i=cd(e,t),n==="desc"?i:-i;const d=Jb(e,c),f=Jb(t,c);return d===null&&f===null?cd(e,t):d===null?1:f===null?-1:d!==f?n==="desc"?f-d:d-f:cd(e,t)}return i=cd(e,t),n==="desc"?i:-i}function iE(e,t,r){const n=e.taxonomies?.[t];return n==null||n===""?!1:Array.isArray(n)?n.some(s=>String(s)===String(r)):String(n)===String(r)}function Qv(e,t){const r=e.options.filter(s=>s.status!=="retired"),n=e.options.filter(s=>s.status==="retired"&&t.some(i=>iE(i,e.id,s.value)));return[...r,...n.filter(s=>!r.some(i=>String(i.value)===String(s.value)))]}function cE({tasks:e,archivedTasks:t,activeCategories:r,activeTypes:n,priorities:s,taxonomies:i,configLoaded:l,referenceDataLoaded:c,assigneeOptionsLoaded:d,assigneeOptions:f}){const p=o.useMemo(()=>[...e,...t],[t,e]),g=o.useMemo(()=>WA(f),[f]),h=o.useMemo(()=>Zf(i,p).filter(ue=>ue.filterEnabled!==!1).map(ue=>({...ue,options:Qv(ue,p)})),[p,i]),y=o.useMemo(()=>new Map(h.map(ue=>[ue.id,ue])),[h]),k=o.useMemo(()=>g.map(ue=>ue.value),[g]),[b,C]=o.useState(""),[S,w]=o.useState([]),[T,E]=o.useState([]),[x,N]=o.useState([]),[v,V]=o.useState(!1),[_,j]=o.useState(rc.map(ue=>ue.value)),[F,z]=o.useState(k),[M,O]=o.useState(!0),[Z,U]=o.useState({}),ve=o.useRef(d),[te,ce]=o.useState("created"),[Le,Ie]=o.useState("desc"),Ye=o.useCallback(()=>{Ie(ue=>ue==="asc"?"desc":"asc")},[]),[ge,he]=o.useState("status"),[Ae,ye]=o.useState("show"),[Ne,ae]=o.useState({}),q=o.useCallback((ue,ne)=>ne.length===0?!0:ne.every(Me=>ue.includes(Me)),[]),W=o.useCallback((ue,ne)=>ue.length===ne.length&&ue.every((Me,pe)=>Me===ne[pe]),[]);o.useEffect(()=>{if(!(!l||!c)&&d&&!v&&r.length>0&&n.length>0&&s.length>0){w(r.map(ne=>ne.value)),E(s.map(ne=>ne.value)),N(n.map(ne=>ne.value)),z(k),O(!0);const ue={};h.forEach(ne=>{ue[ne.id]=ne.options.map(Me=>Me.value)}),U(ue),V(!0)}},[l,c,d,r,n,s,h,v,k]),o.useEffect(()=>{if(!v||!d)return;const ue=new Set(k),ne=F.filter(le=>ue.has(le)),Me=M?k:ne.length>0||F.length===0?ne:k;(Me.length!==F.length||Me.some((le,Ce)=>le!==F[Ce]))&&z(Me)},[k,F,M,v,d]),o.useEffect(()=>{if(!v||!d)return;const ue=F.filter(Me=>k.includes(Me)),ne=k.length>0&&k.every(Me=>ue.includes(Me));M&&!ne&&d&&!ve.current||ne!==M&&O(ne)},[k,F,M,v,d]),o.useEffect(()=>{ve.current=d},[d]),o.useEffect(()=>{if(!l||!c||!v||r.length===0)return;const ue=ix(S,r);(ue.length!==S.length||ue.some((Me,pe)=>Me!==S[pe]))&&w(ue)},[l,c,r,v,S]),o.useEffect(()=>{if(!l||!c||!v||s.length===0||T.length===0)return;const ue=ox(T,s),ne=Array.from(new Set(T.map(pe=>Number(pe)).filter(pe=>Number.isFinite(pe))));(ue.length!==ne.length||ue.some((pe,le)=>pe!==ne[le]))&&E(ue)},[l,c,v,s,T]),o.useEffect(()=>{if(!l||!c||!v||n.length===0)return;const ue=new Set(n.map(pe=>pe.value)),ne=x.filter(pe=>ue.has(pe)),Me=ne.length>0||x.length===0?ne:n.map(pe=>pe.value);W(Me,x)||N(Me)},[n,l,x,v,W,c]),o.useEffect(()=>{if(!l||!c||!v)return;const ue={};h.forEach(Ce=>{const P=Ce.options.map(_e=>_e.value);if(P.length===0)return;const ee=Array.isArray(Z[Ce.id])?Z[Ce.id]:[],Se=ee.filter(_e=>P.includes(_e));ue[Ce.id]=Se.length>0||ee.length===0?Se:P});const ne=Object.keys(Z).sort(),Me=Object.keys(ue).sort(),pe=ne.length!==Me.length||ne.some((Ce,P)=>Ce!==Me[P]),le=Me.some(Ce=>!W(Z[Ce]||[],ue[Ce]||[]));(pe||le)&&U(ue)},[l,Z,h,v,W,c]);const K=o.useCallback(()=>{C(""),w(r.map(ne=>ne.value)),E(s.map(ne=>ne.value)),N(n.map(ne=>ne.value)),j(rc.map(ne=>ne.value)),z(k),O(!0);const ue={};h.forEach(ne=>{ue[ne.id]=ne.options.map(Me=>Me.value)}),U(ue),ce("created"),Ie("desc")},[r,s,n,h,k]),Re=o.useCallback(ue=>{z(ne=>{const Me=typeof ue=="function"?ue(ne):ue,pe=Array.from(new Set(Me.filter(Ce=>typeof Ce=="string"&&Ce.trim().length>0))),le=k.length>0&&k.every(Ce=>pe.includes(Ce));return O(le),pe})},[k]),we=o.useMemo(()=>Ng(b),[b]),ie=o.useMemo(()=>({categories:r,types:n,priorities:s,assigneeOptions:g,taxonomies:i}),[r,n,s,g,i]),Q=o.useMemo(()=>{const ue=q(S,r.map(le=>le.value)),ne=q(x,n.map(le=>le.value)),Me=q(Array.from(new Set(T.map(le=>Number(le)).filter(le=>Number.isFinite(le)))),s.map(le=>Number(le.value)).filter(le=>Number.isFinite(le))),pe=q(_,rc.map(le=>le.value));return e.filter(le=>{const Ce=ag(le,we,ie),P=!v||ue||S.includes(le.category),ee=!v||Me||qy(le.priority,T),Se=!v||ne||x.includes(le.type||fo),_e=!v||pe||_.includes(le.status),ke=!v||M||F.includes(le.assignee||"unassigned"),Ze=Object.entries(Z).every(([st,at])=>{const oe=y.get(st);if(!oe)return!0;const We=oe?.options.every(Be=>at.includes(Be.value))??!0;if(We)return!0;const G=le.taxonomies?.[st];return G?Array.isArray(G)?G.some(Be=>at.includes(Be)):at.includes(G):We||at.includes("")});return Ce&&P&&ee&&Se&&_e&&ke&&Ze}).sort((le,Ce)=>ng(le,Ce,te,Le,i))},[e,we,ie,S,T,x,_,F,M,Z,te,Le,v,h,y,r,n,s,q,i]),H=o.useMemo(()=>{const ue=q(S,r.map(le=>le.value)),ne=q(x,n.map(le=>le.value)),Me=q(Array.from(new Set(T.map(le=>Number(le)).filter(le=>Number.isFinite(le)))),s.map(le=>Number(le.value)).filter(le=>Number.isFinite(le))),pe=q(_,rc.map(le=>le.value));return e.filter(le=>{const Ce=!v||ue||S.includes(le.category),P=!v||Me||qy(le.priority,T),ee=!v||ne||x.includes(le.type||fo),Se=!v||pe||_.includes(le.status),_e=!v||M||F.includes(le.assignee||"unassigned"),ke=Object.entries(Z).every(([Ze,st])=>{const at=y.get(Ze);if(!at)return!0;const oe=at?.options.every(G=>st.includes(G.value))??!0;if(oe)return!0;const We=le.taxonomies?.[Ze];return We?Array.isArray(We)?We.some(G=>st.includes(G)):st.includes(We):oe||st.includes("")});return Ce&&P&&ee&&Se&&_e&&ke})},[e,S,T,x,_,F,M,Z,v,h,y,r,n,s,q]),se=o.useMemo(()=>{const ue=r.every(pe=>S.includes(pe.value)),ne=q(x,n.map(pe=>pe.value)),Me=q(Array.from(new Set(T.map(pe=>Number(pe)).filter(pe=>Number.isFinite(pe)))),s.map(pe=>Number(pe.value)).filter(pe=>Number.isFinite(pe)));return t.filter(pe=>{const le=ag(pe,we,ie),Ce=!v||ue||S.includes(pe.category),P=!v||Me||qy(pe.priority,T),ee=!v||ne||x.includes(pe.type||fo),Se=!v||M||F.includes(pe.assignee||"unassigned"),_e=Object.entries(Z).every(([ke,Ze])=>{const st=y.get(ke);if(!st)return!0;const at=st?.options.every(We=>Ze.includes(We.value))??!0;if(at)return!0;const oe=pe.taxonomies?.[ke];return oe?Array.isArray(oe)?oe.some(We=>Ze.includes(We)):Ze.includes(oe):at||Ze.includes("")});return le&&Ce&&P&&ee&&Se&&_e}).sort((pe,le)=>ng(pe,le,te,Le,i))},[t,we,ie,S,T,x,F,M,Z,te,Le,v,r,n,s,h,y,q,i]),Pe=o.useMemo(()=>{const ue={};return Q.forEach(ne=>{const Me=r.find(le=>le.value===ne.category),pe=Me?Me.label:ne.category||"General";ue[pe]||(ue[pe]=[]),ue[pe].push(ne)}),ue},[Q,r]);return{searchQuery:b,setSearchQuery:C,filterCategories:S,setFilterCategories:w,filterPriorities:T,setFilterPriorities:E,filterTypes:x,setFilterTypes:N,filterStatus:_,setFilterStatus:j,filterAssignees:F,setFilterAssignees:Re,filterAssigneesAllSelected:M,setFilterAssigneesAllSelected:O,filterTaxonomies:Z,setFilterTaxonomies:U,hasInitedFilters:v,setHasInitedFilters:V,sortBy:te,setSortBy:ce,sortOrder:Le,setSortOrder:Ie,toggleSortOrder:Ye,groupBy:ge,setGroupBy:he,emptyColumnMode:Ae,setEmptyColumnMode:ye,collapsedCategories:Ne,setCollapsedCategories:ae,clearFilters:K,filteredTasks:Q,searchAgnosticTasks:H,filteredArchive:se,groupedTasks:Pe}}const lE=cE,Xv="taskforce-workspace-sync-v3",dE=3,Nu="operation-identities",Zi="task-create-attempts",Mu="workstream-create-attempts";function dh(e){if(!e)return[];const t=Array.isArray(e.attempts)?[...e.attempts]:[];return e.active&&!t.some(r=>r.operationId===e.active?.operationId)&&t.push(e.active),t}function Qb(e,t){delete e.active,e.attempts=t}function qn(e,t){const r=String(e||"").trim();if(!r)throw new Error(`${t} is required.`);return r}function Pc(e,t){return e.error||new Error(t)}function uE(e){e.objectStoreNames.contains(Nu)||e.createObjectStore(Nu,{keyPath:"fingerprint"}),e.objectStoreNames.contains(Zi)||e.createObjectStore(Zi,{keyPath:"workspaceId"}),e.objectStoreNames.contains(Mu)||e.createObjectStore(Mu,{keyPath:"fingerprint"})}function ew(e,t){return e?new Promise((r,n)=>{const s=e.open(t,dE);let i=!1;s.onupgradeneeded=()=>uE(s.result),s.onsuccess=()=>{const l=s.result;if(i){l.close();return}i=!0,l.onversionchange=()=>l.close(),r(l)},s.onerror=()=>{i||(i=!0,n(Pc(s,"Failed to open the local operation identity database.")))},s.onblocked=()=>{}}):Promise.reject(new Error("IndexedDB is unavailable."))}class tw{constructor(t=globalThis.indexedDB,r=Xv){this.indexedDb=t,this.databaseName=r}async getOrCreate(t,r){const n=qn(t,"fingerprint"),s=await this.open();try{return await new Promise((i,l)=>{const c=s.transaction(Nu,"readwrite"),d=c.objectStore(Nu),f=d.get(n);let p="",g=!1;f.onsuccess=()=>{try{const h=f.result;if(h){p=qn(h.operationId,"stored operationId");return}p=qn(r(),"operationId"),g=!0,d.add({fingerprint:n,operationId:p})}catch(h){c.abort(),l(h)}},f.onerror=()=>l(Pc(f,"Failed to read the local operation identity.")),c.oncomplete=()=>i({operationId:p,created:g}),c.onerror=()=>l(c.error||new Error("Failed to persist the local operation identity.")),c.onabort=()=>l(c.error||new Error("Persisting the local operation identity was aborted."))})}finally{s.close()}}async deleteIfMatches(t,r){const n=qn(t,"fingerprint"),s=qn(r,"operationId"),i=await this.open();try{await new Promise((l,c)=>{const d=i.transaction(Nu,"readwrite"),f=d.objectStore(Nu),p=f.get(n);p.onsuccess=()=>{p.result?.operationId===s&&f.delete(n)},p.onerror=()=>c(Pc(p,"Failed to read the local operation identity.")),d.oncomplete=()=>l(),d.onerror=()=>c(d.error||new Error("Failed to delete the local operation identity.")),d.onabort=()=>c(d.error||new Error("Deleting the local operation identity was aborted."))})}finally{i.close()}}open(){return ew(this.indexedDb,this.databaseName)}}class JC{constructor(t=globalThis.indexedDB,r=Xv){this.indexedDb=t,this.databaseName=r}async getForParticipant(t,r){const n=qn(t,"workspaceId"),s=qn(r,"participantId"),i=await this.open();try{return await new Promise((l,c)=>{const d=i.transaction(Zi,"readonly"),p=d.objectStore(Zi).get(n);let g=null;p.onsuccess=()=>{const h=p.result,y=dh(h).find(k=>k.participantId===s);y&&(g={...y,created:!1,resolved:!1})},p.onerror=()=>c(Pc(p,"Failed to read the local task-create attempt.")),d.oncomplete=()=>l(g),d.onerror=()=>c(d.error||new Error("Failed to claim the local task-create attempt.")),d.onabort=()=>c(d.error||new Error("Claiming the local task-create attempt was aborted."))})}finally{i.close()}}async listPending(t){const r=qn(t,"workspaceId"),n=await this.open();try{return await new Promise((s,i)=>{const l=n.transaction(Zi,"readonly"),d=l.objectStore(Zi).get(r);let f=[];d.onsuccess=()=>{f=dh(d.result).map(p=>({...p,created:!1,resolved:!1}))},d.onerror=()=>i(Pc(d,"Failed to list local task-create attempts.")),l.oncomplete=()=>s(f),l.onerror=()=>i(l.error||new Error("Failed to list local task-create attempts.")),l.onabort=()=>i(l.error||new Error("Listing local task-create attempts was aborted."))})}finally{n.close()}}async claim(t,r,n,s){const i=qn(t,"workspaceId"),l=qn(r,"participantId"),c=await this.open();try{return await new Promise((d,f)=>{const p=c.transaction(Zi,"readwrite"),g=p.objectStore(Zi),h=g.get(i);let y=null,k=!1;h.onsuccess=()=>{try{const b=h.result||{workspaceId:i},C=dh(b),S=C.find(T=>T.participantId===l);if(S){y={...S,created:!1,resolved:!1};return}const w={workspaceId:i,operationId:qn(s(),"operationId"),task:n,participantId:l};k=!0,C.push(w),Qb(b,C),g.put(b),y={...w,created:!0,resolved:!1}}catch(b){p.abort(),f(b)}},h.onerror=()=>f(Pc(h,"Failed to read the local task-create attempt.")),p.oncomplete=()=>{if(!y)return f(new Error("Local task-create attempt was not prepared."));d({...y,created:k})},p.onerror=()=>f(p.error||new Error("Failed to persist the local task-create attempt.")),p.onabort=()=>f(p.error||new Error("Persisting the local task-create attempt was aborted."))})}finally{c.close()}}async markResolved(t,r){const n=qn(r,"operationId");await this.mutateState(t,s=>s.filter(i=>i.operationId!==n))}async abandonIfMatches(t,r){await this.mutateState(t,n=>{const s=qn(r,"operationId");return n.filter(i=>i.operationId!==s)})}async mutateState(t,r){const n=qn(t,"workspaceId"),s=await this.open();try{await new Promise((i,l)=>{const c=s.transaction(Zi,"readwrite"),d=c.objectStore(Zi),f=d.get(n);f.onsuccess=()=>{const p=f.result||{workspaceId:n},g=r(dh(p));g.length===0?d.delete(n):(Qb(p,g),d.put(p))},f.onerror=()=>l(Pc(f,"Failed to read the local task-create state.")),c.oncomplete=()=>i(),c.onerror=()=>l(c.error||new Error("Failed to update the local task-create state.")),c.onabort=()=>l(c.error||new Error("Updating the local task-create state was aborted."))})}finally{s.close()}}open(){return ew(this.indexedDb,this.databaseName)}}class pE{constructor(t=globalThis.indexedDB,r=Xv){this.indexedDb=t,this.databaseName=r}async claim(t,r,n){const s=qn(t,"fingerprint"),i=await this.open();try{return await new Promise((l,c)=>{const d=i.transaction(Mu,"readwrite"),f=d.objectStore(Mu),p=f.get(s);let g=null,h=!1;p.onsuccess=()=>{try{const y=p.result;if(y){g=y;return}g={fingerprint:s,operationId:qn(n(),"operationId"),workstream:r},h=!0,f.add(g)}catch(y){d.abort(),c(y)}},p.onerror=()=>c(Pc(p,"Failed to read the workstream-create attempt.")),d.oncomplete=()=>{if(!g)return c(new Error("Workstream-create attempt was not prepared."));l({...g,created:h})},d.onerror=()=>c(d.error||new Error("Failed to persist the workstream-create attempt.")),d.onabort=()=>c(d.error||new Error("Persisting the workstream-create attempt was aborted."))})}finally{i.close()}}async deleteIfMatches(t,r){const n=qn(t,"fingerprint"),s=qn(r,"operationId"),i=await this.open();try{await new Promise((l,c)=>{const d=i.transaction(Mu,"readwrite"),f=d.objectStore(Mu),p=f.get(n);p.onsuccess=()=>{p.result?.operationId===s&&f.delete(n)},p.onerror=()=>c(Pc(p,"Failed to read the workstream-create attempt.")),d.oncomplete=()=>l(),d.onerror=()=>c(d.error||new Error("Failed to delete the workstream-create attempt.")),d.onabort=()=>c(d.error||new Error("Deleting the workstream-create attempt was aborted."))})}finally{i.close()}}open(){return ew(this.indexedDb,this.databaseName)}}function Ec(e){return $a(e)}async function rw(e,t=globalThis.crypto){if(!t?.subtle)throw new Error("Web Crypto is unavailable.");const r=new TextEncoder().encode(Ec(e)),n=await t.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n),s=>s.toString(16).padStart(2,"0")).join("")}function yf(){if(!globalThis.crypto?.randomUUID)throw new Error("Secure task operation identity generation is unavailable.");return`operation-${globalThis.crypto.randomUUID()}`}function fE(){return{operationId:yf(),taskId:`task-${globalThis.crypto.randomUUID()}`}}async function Jk(e,t,r){const n={...t,headers:{...t.headers||{},"x-taskforce-operation-id":r}};try{return await fetch(e,n)}catch{return fetch(e,n)}}async function sg(e){if(e.ok||![400,404,409,422].includes(e.status))return!1;const t=await e.clone().json().catch(()=>null),r=String(t?.code||"").trim();return new Set(["TASK_CREATE_UNSUPPORTED_INPUT","DURABLE_TASK_HTTP_PATCH_UNSUPPORTED","DURABLE_TASK_PATCH_INVALID","WORKSPACE_SYNC_OPERATION_ID_REQUIRED","TASK_NOT_FOUND","TASK_ARCHIVED_READ_ONLY","TASK_CHECKLIST_INVALID","TASK_ATTACHMENT_LINKS_INVALID","TASK_COMMENT_INVALID","TASK_COMMENT_IDENTITY_CONFLICT"]).has(r)}function ck(e){const{id:t,createdAt:r,updatedAt:n,...s}=e;return s}function Xb(e){return`taskforce.sync.v3.cloud-task-create-participant-v1:${e}`}function Qk(e){const t=new JC,r=new tw,n=new Map,s=c=>{const d=globalThis.sessionStorage?.getItem(Xb(c));if(d)try{const p=JSON.parse(d);if(typeof p.participantId=="string"&&p.participantId.trim())return{participantId:p.participantId.trim(),draftFingerprint:typeof p.draftFingerprint=="string"?p.draftFingerprint:null}}catch{}const f=n.get(c);return f||{participantId:yf(),draftFingerprint:null}},i=(c,d)=>{n.set(c,d),globalThis.sessionStorage?.setItem(Xb(c),JSON.stringify(d))},l=c=>{i(c,{participantId:yf(),draftFingerprint:null})};return{async prepareCreate(c,d){const f=fE(),p={...d,id:f.taskId},g=await rw({workspaceId:c,task:ck(d)});let h=s(c);h.draftFingerprint&&h.draftFingerprint!==g?h={participantId:yf(),draftFingerprint:g}:h={...h,draftFingerprint:g},i(c,h);const y=await t.claim(c,h.participantId,p,()=>f.operationId),k=ck(y.task);return{operationId:y.operationId,body:y.task,recoveredChangedInput:$a(k)!==$a(ck(d))}},async confirmCreate(c,d){await t.markResolved(c,d),l(c)},resetCreateDraft(c){l(c)},async prepareUpdate(c,d,f,p){const g=$a({workspaceId:c,url:d,body:f,observedPrecondition:p}),h=await r.getOrCreate(g,yf);return{fingerprint:g,operationId:h.operationId}},confirmUpdate(c,d){return r.deleteIfMatches(c,d)}}}function mE(e){const{activeCategories:t,activeTab:r,apiEndpoint:n,assignee:s,attachments:i,attachmentsDirty:l,category:c,checklistItems:d,comments:f,complexity:p,description:g,dueDate:h,createTaskDurably:y,durableTaskHttpRootActivationEnabled:k=!1,workspaceId:b,taskHttpMutationClient:C,updateTask:S,editingTaskId:w,fetchTasks:T,formTaxonomies:E,getAttachmentsDraft:x,getDescriptionDraft:N,getPreferredCategoryValue:v,getTitleDraft:V,awaitPendingDescriptionImageUpload:_,mergeTaskFromServer:j,onTaskCreated:F,onTaskCreateAccepted:z,workstreamInput:M,priority:O,pushNotice:Z,queueWorkspaceSyncFromAuthoritativeTaskState:U,relationshipTasks:ve,supplementalTasks:te=[],resetForm:ce,resolveWorkstreamIdInput:Le,scheduledDate:Ie,setActiveTab:Ye,setAttachmentsDirty:ge,setComments:he,setError:Ae,setLastUsedCategory:ye,setLoading:Ne,setNewCommentText:ae,status:q,title:W,taxonomies:K,textDraftOccupied:Re,type:we}=e,ie=V||(()=>W),Q=N||(()=>g),H=x||(()=>i),se=o.useRef(ie),Pe=o.useRef(Q),ue=o.useRef(H),ne=o.useRef(_);se.current=ie,Pe.current=Q,ue.current=H,ne.current=_;const Me=o.useCallback(()=>({title:se.current(),description:Pe.current()}),[]),[pe,le]=o.useState(null),[Ce,P]=o.useState("idle"),[ee,Se]=o.useState(null),_e=o.useRef(null),ke=o.useRef(null),Ze=o.useRef(null),st=o.useRef(null),at=o.useRef(!1),oe=o.useRef(null),We=o.useRef(null),G=o.useRef(!1),Be=o.useRef(null),Xe=w&&(ve.find(Ke=>Ke.id===w)||te.find(Ke=>Ke.id===w))||null,ze=Xe?.isDeleted?"deleted":Xe?.isArchived?"archived":null,qe=r==="add"&&!w&&((Re??(W.trim()!==""||g.trim()!==""))||d.length>0||(f?.length||0)>0||i.length>0);o.useEffect(()=>{G.current&&!qe&&(We.current?.resetCreateDraft(b),y?.resetDraft?.()),G.current=qe},[qe,y,b]);const Te=o.useCallback((Ke=Me(),Qe=ue.current())=>JSON.stringify({title:Ke.title.trim(),description:Ke.description,category:typeof c=="string"?c:c.label||v(t),type:typeof we=="string"?we:we.label||fo,priority:Number(O),complexity:Number(p)||3,assignee:s||"agent",scheduledDate:Ie||"",dueDate:h||"",workstreamInput:M.trim(),checklistItems:d,comments:f,taxonomies:E,attachments:Qe}),[t,s,c,d,f,p,g,h,E,v,O,Me,Ie,W,we,M]),fe=o.useCallback(()=>{_e.current!==null&&(window.clearTimeout(_e.current),_e.current=null)},[]),Ee=o.useCallback(Ke=>{if(Ze.current===Ke.signature&&ke.current===null&&st.current||(ke.current=Ke,st.current))return st.current;const Ge=(async()=>{let At=!0;for(;ke.current;){const Nt=ke.current;ke.current=null,Ze.current=Nt.signature,At=await Nt.save(),At&&Se(Nt.signature)}return Ze.current=null,At})().finally(()=>{Ze.current=null,st.current=null});return st.current=Ge,Ge},[]),$e=o.useCallback(async Ke=>{const Qe=Ke?.quiet??!1,Ge=Ke?.source??"manual";if(!w&&Ge==="manual")try{await ne.current?.()}catch(nt){console.error("Description image upload did not settle before task creation.",nt);const Mt="Wait for the Description image upload to finish, then try again.";return Ae(Mt),Qe||Z(Mt,"error"),!1}const At=Ke?.textDraft??Me(),Nt=At.title,Bt=At.description,Qt=ue.current();if(w||(oe.current=null),ze)return Ae(ze==="deleted"?"Deleted tasks are read-only. Restore first to make changes.":"Archived tasks are read-only. Unarchive first to make changes."),P(Ge==="autosave"?"error":"idle"),!1;if(!Nt.trim())return Ae("Title is required"),w&&P(Ge==="autosave"?"error":"idle"),!1;const Xt=K.filter(nt=>nt.isRequired).filter(nt=>{const Mt=E[nt.id];return Array.isArray(Mt)?Mt.filter(ur=>String(ur).trim().length>0).length===0:typeof Mt!="string"&&typeof Mt!="number"||String(Mt).trim().length===0}).map(nt=>nt.label);if(Xt.length>0)return Ae(`Required taxonomy values are missing: ${Xt.join(", ")}`),w&&P(Ge==="autosave"?"error":"idle"),!1;Ne(!0),Ae(""),w&&P("saving");try{const nt=w?`/api/taskforce/task/${w}`:n.replace("/api/dev/task","/api/taskforce/task").replace("/api/taskforce/task","/api/taskforce/task"),Mt=w?"PATCH":"POST",ur=typeof c=="string"?c:c.label||v(t),je=typeof we=="string"?we:we.label||fo,ot=M.trim()?Le(M):null,pt=w?ve.find(_t=>_t.id===w):null,Ve=!w||!pt||$a(pt.checklistItems||[])!==$a(d),lt={title:Nt,description:Bt||null,category:ur||v(t),type:je,priority:O,complexity:Number(p)||3,status:w?void 0:q,completedAt:w?void 0:q==="done"?new Date().toISOString():null,assignee:s||"agent",scheduledDate:Ie||null,dueDate:h||null,workstreamId:M.trim()?ot?.id||M.trim():null,taxonomies:E,...w?{}:{createdAt:new Date().toISOString(),createdBy:"user"}};if(w&&pt)for(const[_t,Dt]of Object.entries(lt))(Dt===void 0||$a(Dt??null)===$a(pt[_t]??null))&&delete lt[_t];if(Ve&&(lt.checklistItems=d),w||(lt.comments=f),(!w||l)&&(lt.attachments=Qt),w&&Object.keys(lt).length>0&&(lt.saveSource=Ge),w&&S){const _t=await S(w,lt);return Ne(!1),P(_t===!1?"error":"saved"),_t===!1?!1:(ye(ur),ge(!1),!0)}if(!w&&y){let _t;try{_t=await y(lt)}catch(Dt){console.error("Durable task create failed before a conclusive result.",Dt);const Tt="Task creation confirmation was interrupted. Retry the same task to confirm it safely.";return Ae(Tt),Qe||Z(Tt,"error"),Ne(!1),!1}if(_t){if(_t.state==="failed"||_t.state==="rejected"||_t.state==="ambiguous"||_t.state==="disabled"){const Dt=_t.state==="disabled"?"Task was not created because durable capture became unavailable. Reload before retrying.":_t.state==="failed"?"Task was not created because durable local preparation failed. Retry the task.":_t.state==="rejected"?`Task was not created because durable capture rejected it${_t.errorCode?` (${_t.errorCode})`:""}.`:"Task creation confirmation was interrupted. Retry the same task to confirm it safely.";return Ae(Dt),Qe||Z(Dt,"error"),Ne(!1),!1}if(_t.task){const Dt=No(_t.task);oe.current=Dt,j(Dt)}if(_t.recoveredChangedInput&&(at.current=!0,Z("Recovered the previously interrupted task. Changes made after the interrupted submission were not applied.","info")),_t.state==="pending")_t.pendingReason!=="queued"&&(at.current=!0,Z(_t.pendingReason==="auth"?"Task created locally. Sign in to finish cloud sync.":_t.pendingReason==="sync-disabled"?"Task created locally. Turn on sync to send it to cloud.":"Task created locally. Cloud sync will retry automatically.","info")),Ae("");else if(_t.state==="blocked"){at.current=!0;const Dt=`Task created locally, but cloud sync is blocked${_t.errorCode?` (${_t.errorCode})`:""}.`;Ae(Dt),Z(Dt,"error")}else Ae("");return ye(ur),ge(!1),Ne(!1),!0}}let It=!1,wt=null,$t=lt;if(k&&!w){We.current||(We.current=C||Qk());const _t=await We.current.prepareCreate(b,lt);wt=_t.operationId,$t=_t.body,It=_t.recoveredChangedInput}const Yt={method:Mt,headers:{"Content-Type":"application/json"},body:JSON.stringify($t)},qt=wt?await Jk(nt,Yt,wt):await fetch(nt,Yt);if(!qt.ok){!w&&wt&&await sg(qt)&&await We.current?.confirmCreate(b,wt);const _t=await qt.json(),Dt=_t.error||_t.message||`Failed to ${w?"update":"save"} task`;return Ae(Dt),Qe||Z(Dt,"error"),Ne(!1),w&&P("error"),!1}const er=await qt.json().catch(()=>null);if(!w&&wt&&(!er||typeof er!="object"||String(er.id||"")!==String($t.id||"")))throw new Error("Durable cloud task create returned an invalid authoritative task identity.");if(!w&&wt&&await We.current?.confirmCreate(b,wt),It&&(at.current=!0,Z("Recovered the previously interrupted task. Changes made after the interrupted submission were not applied.","info")),er&&typeof er=="object"){const _t=No(er);j(_t),w?U():oe.current=_t}return ye(ur),ge(!1),Ne(!1),w&&P("saved"),!0}catch(nt){return console.error("Failed to save task.",nt),Ae("Failed to connect to server"),Qe||Z("Failed to connect to server","error"),Ne(!1),w&&P("error"),!1}},[t,n,s,l,c,d,f,p,h,y,k,b,C,S,w,ze,E,v,j,M,O,Z,U,Me,Le,ge,Ae,ye,Ne,Ie,q,K,we]),rt=o.useCallback(async()=>{if(await $e({source:"manual"})&&(!w&&!at.current&&Z("Task added successfully","success"),at.current=!1,r==="add"&&!w)){const Qe=oe.current;if(Qe&&z)try{await z(Qe)}catch(Ge){console.warn("Task create draft upload promotion failed.",Ge),Z("Task created successfully. Temporary image cleanup will retry automatically.","info")}if(Qe&&F){F(Qe);return}ce(),Ye("tasks"),await T()}},[r,w,T,z,F,Z,ce,$e,Ye]);o.useEffect(()=>{if(fe(),ke.current=null,!w){Se(null),P("idle");return}Se(Te()),P("idle")},[fe,w]);const kt=o.useCallback(async()=>{if(fe(),ze||!w||ee===null)return!0;const Ke=Me(),Qe=Te(Ke);return Qe===ee?!0:!Ke.title.trim()||h&&Ie&&h<Ie?!1:await Ee({signature:Qe,save:()=>$e({quiet:!0,source:"autosave",textDraft:Ke})})&&Te()===Qe},[Te,fe,h,w,ze,Ee,ee,Me,$e,Ie]);o.useEffect(()=>{if(!w||ze||ee===null)return;const Ke=Me(),Qe=Te(Ke);if(Qe===ee)return;if(!Ke.title.trim()){P("idle");return}if(h&&Ie&&h<Ie){P("error");return}P(Nt=>Nt==="error"?"error":"idle"),fe();const At=(()=>{try{return String(JSON.parse(ee).assignee||"")}catch{return""}})()!==String(s||"agent")?0:1400;return _e.current=window.setTimeout(async()=>{await Ee({signature:Qe,save:()=>$e({quiet:!0,source:"autosave",textDraft:Ke})})},At),()=>{fe()}},[Te,s,fe,h,w,ze,Ee,ee,Me,$e,Ie]);const xe=o.useCallback(async Ke=>{if(Ke.preventDefault(),h&&Ie&&h<Ie){le({dueDate:h,scheduledDate:Ie});return}await rt()},[h,rt,Ie]),St=o.useCallback(async()=>{le(null),await rt()},[rt]),jt=o.useCallback(()=>{le(null)},[]),$=o.useCallback(async Ke=>{if(!w||!Ke.trim())return;const Qe=Ke.trim(),Ge=Be.current,At=Ge?.taskId===w&&Ge.text===Qe?Ge:{taskId:w,text:Qe,operationId:globalThis.crypto?.randomUUID?.()||`comment-operation-${Date.now()}`,commentId:`comment-${globalThis.crypto?.randomUUID?.()||Date.now()}`,timestamp:new Date().toISOString()};Be.current=At;try{const Nt=await fetch(`/api/taskforce/task/${w}/comment`,{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-operation-id":At.operationId},body:JSON.stringify({text:Qe,commentId:At.commentId,timestamp:At.timestamp})});if(!Nt.ok){const Qt=await sg(Nt),nt=(await Nt.json().catch(()=>({}))).error||"Failed to add comment.";Qt&&(Be.current=null),Ae(nt),Z(nt,"error");return}const Bt=await Nt.json().catch(()=>null);if(Be.current=null,ae(""),Bt&&typeof Bt=="object"){const Qt=No(Bt);he(Qt.comments||[]),j(Bt),Se(Te()),P("saved")}else await T(!0);U()}catch(Nt){console.error("Failed to add comment",Nt),Ae("Failed to add comment."),Z("Failed to add comment.","error")}},[w,T,Te,j,Z,U,he,Ae,ae]);return{autoSaveState:Ce,flushAutoSave:kt,scheduleWarningPrompt:pe,saveTask:$e,handleSubmit:xe,confirmScheduleWarning:St,cancelScheduleWarning:jt,handleAddComment:$}}function hE(e){const{editingTaskId:t,workstreamInput:r,pushNotice:n,relationshipTasks:s,resolveWorkstreamIdInput:i,setError:l,updateTask:c}=e;return{handleSetWorkstreamForCurrentTask:o.useCallback(async f=>{if(!t)return;const p=s.find(k=>k.id===t);if(!p)return;const g=typeof f=="string"?f.trim():f===null?"":r.trim(),h=g?i(g):null,y=g.length>0?h?.id||g:null;if((p.workstreamId||null)===y){n(y?"Task already belongs to that workstream.":"Task is already standalone.","info");return}try{if(await c(t,{workstreamId:y})===!1)return;l(""),n(y?"Workstream set":"Workstream removed","info")}catch{l("Failed to set workstream."),n("Failed to set workstream.","error")}},[t,r,n,s,i,l,c])}}const aw=new Set(["title","description","priority","complexity","type","category","createdBy","assignee","scheduledDate","dueDate","scheduledWeekKey","orderInDay","workstreamId","taxonomies"]);function gE(e){const t={};for(const r of aw)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t}class Wh extends Error{constructor(t,r,n){super(t),this.code=r,this.statusCode=n,this.name="DurableTaskMetadataMutationError"}}function QC(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:null;if(!t)throw new Wh("Task metadata patch must be an object.","DURABLE_TASK_PATCH_INVALID",400);const r=Object.keys(t);if(r.length===0)throw new Wh("Task metadata patch cannot be empty.","DURABLE_TASK_PATCH_INVALID",400);const n=r.filter(s=>!aw.has(s));if(n.length>0)throw new Wh(`Task metadata patch contains unsupported fields: ${n.sort().join(", ")}.`,"DURABLE_TASK_PATCH_INVALID",400);return{...t}}const Pd="taskforce:tasks-mutated";function yE(e){typeof window>"u"||typeof window.dispatchEvent!="function"||window.dispatchEvent(new CustomEvent(Pd,{detail:e}))}const uh=aw,kE=new Set(["status","assignee","canceledReason","completedAt","completed","inProgress","readyForReview","cancelled"]);function vE(e,t){return e===void 0||t===void 0?e===t:$a(e)===$a(t)}function pn(e,t,r,n){return t?e.map(s=>{if(s.id!==r)return s;const i={...s};for(const l of Object.keys(n))Object.prototype.hasOwnProperty.call(t,l)?i[l]=t[l]:delete i[l];return i}):e}function af(e,t){return{taskId:t,updatedAt:e?.updatedAt??null,status:e?.status??null,isArchived:e?.isArchived===!0}}function wE({tasks:e,archivedTasks:t,editingTaskId:r,setTasks:n,setArchivedTasks:s,setDeletedTasks:i,setError:l,resetForm:c,setActiveTab:d,fetchTasks:f,fetchArchive:p,fetchDeletedTasks:g,mergeTaskFromServer:h,pushNotice:y,cloudAuthConfigured:k,runtimeMode:b,isAuthenticated:C,workspaceCloudSyncEnabled:S,buildWorkspaceSyncSignature:w,pushWorkspaceChangesToCloud:T,workspacePendingSignatureRef:E,workspaceDeletedTaskIdsRef:x,workspaceDeletedTaskWatermarksRef:N,mutateTaskMetadata:v,mutateTaskStatus:V,mutateTaskLifecycle:_,mutateTaskDelete:j,mutateTaskRestore:F,durableTaskMetadataActivationEnabled:z=!1,durableTaskStatusActivationEnabled:M=!1,durableTaskDeleteActivationEnabled:O=!1,durableTaskHttpRootActivationEnabled:Z=!1,workspaceId:U="default",taskHttpMutationClient:ve}){const te=o.useRef(new Map);o.useEffect(()=>{if(typeof window>"u")return;const P=ee=>{const Se=ee.detail,_e=Se?.authoritativeTask,ke=String(Se?.workspaceId||"").trim()||"default";!_e||ke!==U||(te.current.set(_e.id,_e),h(_e))};return window.addEventListener(Pd,P),()=>window.removeEventListener(Pd,P)},[h,U]);const[ce,Le]=o.useState(null),Ie=o.useRef(null),Ye=o.useRef(null),ge=o.useRef(null),he=o.useRef(null),Ae=o.useCallback(async(P,ee,Se,_e,ke)=>{const Ze=["checklistItems","attachments","comments"].some(oe=>Object.prototype.hasOwnProperty.call(Se,oe));if(!Z&&!Ze)return fetch(P,ee);he.current||(he.current=ve||Qk());const st=await he.current.prepareUpdate(U,P,Se,_e),at=await Jk(P,ee,st.operationId);if(at.ok){const oe=await at.clone().json().catch(()=>null);if(!ke(oe))throw new Error("Durable cloud task mutation returned an invalid authoritative response.");await he.current.confirmUpdate(st.fingerprint,st.operationId)}else await sg(at)&&await he.current.confirmUpdate(st.fingerprint,st.operationId);return at},[Z,ve,U]),ye=o.useCallback((P,ee,Se,_e,ke)=>Ae(P,ee,Se,ke,Ze=>!!Ze&&typeof Ze=="object"&&String(Ze.id||"")===_e),[Ae]);o.useEffect(()=>()=>{typeof window>"u"||(Ye.current!==null&&(window.clearTimeout(Ye.current),Ye.current=null),ge.current=null)},[]);const Ne=o.useCallback((P=0)=>{if(!(k&&b==="local"&&C&&S)||typeof window>"u")return;const ee=Math.max(0,P),Se=Date.now()+ee,_e=ge.current;if(Ye.current!==null){if(ee<=0||_e!==null&&_e>=Se)return;window.clearTimeout(Ye.current),Ye.current=null}ge.current=Se,Ye.current=window.setTimeout(()=>{Ye.current=null,ge.current=null;const ke=w();ke&&(E.current=ke,T(ke))},ee)},[k,b,C,S,w,E,T]),ae=o.useCallback(async(P,ee)=>{let Se=await fetch(`/api/taskforce/deleted${P}`,ee);return Se.status===404&&(Se=await fetch(`/api/taskforce/trash${P}`,ee)),Se},[]),q=async(P,ee=!1,Se={})=>{if(!Se.skipConfirm&&!confirm("Move this task to Trash? You can restore it later."))return!1;const _e=ee||t.some(ke=>ke.id===P);try{let ke=null;if(O){const at=await j?.(P);if(!at){const oe="Task was not deleted because durable capture was unavailable.";return l(oe),y(oe,"error"),!1}if(at.state!=="disabled"){if(at.state==="rejected"||at.state==="failed"||at.state==="ambiguous"){const oe=at.state==="ambiguous"?"Task delete confirmation was interrupted. Retry the same delete to confirm it safely.":`Task was not deleted because durable capture rejected it${at.errorCode?` (${at.errorCode})`:""}.`;return l(oe),y(oe,"error"),!1}if(ke=at.deleted||null,!ke){const oe="Task delete was captured, but its Trash record was unavailable.";return l(oe),y(oe,"error"),!1}}}let Ze=ke?{deleted:ke}:{};if(!ke){const at=`/api/taskforce/task/${P}`,oe=e.find(G=>G.id===P)||t.find(G=>G.id===P),We=await Ae(at,{method:"DELETE"},{},af(oe,P),G=>!!G&&typeof G=="object"&&G.success===!0&&!!G.deleted&&typeof G.deleted=="object"&&String(G.deleted.taskId||"")===P);if(!We.ok){const Be=(await We.json().catch(()=>({}))).error||"Failed to delete task.";return l(Be),y(Be,"error"),!1}Ze=await We.json().catch(()=>({}))}const st=Ze?.deleted&&typeof Ze.deleted=="object"&&Ze.deleted.taskSnapshot?{...Ze.deleted,taskSnapshot:No(Ze.deleted.taskSnapshot)}:null;if(window.location.search.includes(P)){const at=new URL(window.location.href);at.searchParams.delete("task"),window.history.pushState({},"",at.toString())}if(_e?s(at=>at.filter(oe=>oe.id!==P)):n(at=>at.filter(oe=>oe.id!==P)),st){i(oe=>[st,...oe.filter(We=>We.taskId!==P)]);const at=String(st.deletedAt||"").trim();Number.isFinite(Date.parse(at))&&N.current.set(P,at)}else await g(!0),N.current.set(P,new Date().toISOString());if(x.current.add(P),!ke&&k&&b==="local"&&C&&S){const at=w();E.current=at,T(at)}return r===P&&(c(),d("tasks")),l(""),y("Task moved to Trash.","info"),!0}catch(ke){return console.error("Failed to delete task:",ke),l("Failed to delete task."),y("Failed to delete task.","error"),!1}},W=o.useCallback(async(P,ee,Se={})=>{try{const _e=`/api/taskforce/deleted/${P}/restore`,ke=String(ee||"").trim();if(O){if(!ke||!F)throw new Error("Durable local task restore requires the expected task identity and capture client.");const We=await F(P,ke,Se.restoreDestination||"previous");if(!We||We.state==="failed"||We.state==="ambiguous"||We.state==="rejected"||We.state==="disabled"){const Be="Failed to capture task restore durably.";return l(Be),Se.silent||y(Be,"error"),null}const G=We.task;if(!G||G.id!==ke)throw new Error("Durable local task restore did not return the restored task.");return h(G),i(Be=>Be.filter(Xe=>Xe.id!==P&&Xe.taskId!==ke)),x.current.delete(P),x.current.delete(ke),N.current.delete(P),N.current.delete(ke),l(""),Se.silent||y(We.state==="accepted"?"Task restored from Trash.":"Task restored locally; cloud sync is pending.","info"),No(G)}if(Z&&!ke)throw new Error("Durable cloud task restore requires the expected task identity.");const Ze=N.current.get(ke)||N.current.get(P)||null,st=Z?await Ae(_e,{method:"POST"},{},{taskId:ke,updatedAt:Ze,status:"deleted",isArchived:!1},We=>!We||typeof We!="object"?!1:String(We.id||"").trim()===ke):await ae(`/${P}/restore`,{method:"POST"});if(!st.ok){const G=(await st.json().catch(()=>({}))).error||"Failed to restore deleted task.";return l(G),Se.silent||y(G,"error"),null}const at=await st.json().catch(()=>null);at?h(at):await f(!0);const oe=String(at?.id||"").trim();return i(We=>We.filter(G=>G.id!==P&&G.taskId!==ke&&G.taskId!==oe)),x.current.delete(P),N.current.delete(P),oe&&(x.current.delete(oe),N.current.delete(oe)),Ne(),l(""),Se.silent||y(at?.isArchived===!0?"Task restored to Archived.":"Task restored to Active.","info"),at?No(at):null}catch(_e){return console.error("Failed to restore deleted task:",_e),l("Failed to restore deleted task."),Se.silent||y("Failed to restore deleted task.","error"),null}},[Z,O,Ae,f,h,F,y,Ne,ae,i,l]),K=o.useCallback(async P=>{try{const ee=await ae(`/${P}`,{method:"DELETE"});if(!ee.ok){const _e=(await ee.json().catch(()=>({}))).error||"Failed to permanently delete deleted task.";return l(_e),y(_e,"error"),!1}return i(Se=>Se.filter(_e=>_e.id!==P&&_e.taskId!==P)),Ne(),l(""),y("Deleted task permanently removed.","info"),!0}catch(ee){return console.error("Failed to permanently delete deleted task:",ee),l("Failed to permanently delete deleted task."),y("Failed to permanently delete deleted task.","error"),!1}},[y,Ne,ae,i,l]),Re=o.useCallback(async()=>{try{const P=await ae("/empty",{method:"POST"});if(!P.ok){const ke=(await P.json().catch(()=>({}))).error||"Failed to permanently delete deleted tasks.";return l(ke),y(ke,"error"),null}const ee=await P.json().catch(()=>({})),Se=Number(ee?.deleted||0);return i([]),Ne(),l(""),y(Se===1?"Deleted task permanently removed.":`${Se} deleted tasks permanently removed.`,"info"),Se}catch(P){return console.error("Failed to empty deleted tasks:",P),l("Failed to permanently delete deleted tasks."),y("Failed to permanently delete deleted tasks.","error"),null}},[y,Ne,ae,i,l]),we=o.useCallback((P,ee,Se,_e,ke)=>{if(P.state==="disabled")return!1;if(P.state==="rejected"||P.state==="failed"){const Ze=_e.find(at=>at.id===ee)||ke.find(at=>at.id===ee);n(at=>pn(at,Ze,ee,Se)),s(at=>pn(at,Ze,ee,Se));const st=P.state==="failed"?"Task was not saved because durable local preparation failed. Retry the edit.":P.retryable?"Task was not saved because durable capture is busy. Retry the edit shortly.":`Task was not saved because durable capture rejected it${P.errorCode?` (${P.errorCode})`:""}.`;return l(st),y(st,"error"),!0}if("task"in P&&P.task&&h(P.task),P.state==="accepted")l("");else if(P.state==="pending")l(""),P.pendingReason!=="queued"&&y(P.pendingReason==="auth"?"Task saved locally. Sign in to finish cloud sync.":P.pendingReason==="sync-disabled"?"Task saved locally. Turn on sync to send it to cloud.":"Task saved locally. Cloud sync will retry automatically.","info");else{const Ze=P.state==="blocked"?`Task saved locally, but cloud sync is blocked${P.errorCode?` (${P.errorCode})`:""}.`:"Task save confirmation was interrupted. Retry the same edit to confirm it safely.";l(Ze),y(Ze,"error")}return!0},[h,y,s,l,n]),ie=o.useCallback(async(P,ee,Se={})=>{const _e=Object.keys(Se).some(We=>uh.has(We)),ke=Object.keys(Se).filter(We=>!kE.has(We)&&!uh.has(We));if(M&&ke.length>0){const We=`Task status was not saved because the combined update contains unsupported fields: ${ke.sort().join(", ")}.`;l(We),y(We,"error");return}const Ze=new Date().toISOString(),st={...Se,status:ee,completedAt:ee==="done"||ee==="cancelled"?Se.completedAt||Ze:null,completed:ee==="done",inProgress:ee==="in-progress",readyForReview:ee==="review",cancelled:ee==="cancelled"},at=e,oe=t;if(n(We=>We.map(G=>G.id===P.id?{...G,...st}:G)),s(We=>We.map(G=>G.id===P.id?{...G,...st}:G)),V)try{const We=Object.prototype.hasOwnProperty.call(Se,"assignee")?{kind:"set",value:Se.assignee??null}:{kind:"preserve"},G=gE(Se);delete G.assignee;const Be=await V(P.id,{status:ee,assigneeIntent:We,canceledReason:ee==="cancelled"?Se.canceledReason??null:null,metadataPatch:G});if(Be&&we(Be,P.id,st,at,oe))return;if(!Be&&M){const Xe=at.find(qe=>qe.id===P.id)||oe.find(qe=>qe.id===P.id);n(qe=>pn(qe,Xe,P.id,st)),s(qe=>pn(qe,Xe,P.id,st));const ze="Task status was not saved because durable capture was unavailable.";l(ze),y(ze,"error");return}}catch(We){console.error("Durable task status update failed before a conclusive result.",We);const G=at.find(Xe=>Xe.id===P.id)||oe.find(Xe=>Xe.id===P.id);n(Xe=>pn(Xe,G,P.id,st)),s(Xe=>pn(Xe,G,P.id,st));const Be="Task save confirmation was interrupted. Retry the same edit to confirm it safely.";l(Be),y(Be,"error");return}if(z&&_e){const We=at.find(Be=>Be.id===P.id)||oe.find(Be=>Be.id===P.id);n(Be=>pn(Be,We,P.id,st)),s(Be=>pn(Be,We,P.id,st));const G="Task was not saved because durable status capture is required for this combined metadata update.";l(G),y(G,"error");return}try{const We={...Se,status:ee,completedAt:st.completedAt},G={method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(We)},Be=await ye(`/api/taskforce/task/${P.id}`,G,We,P.id,af(P,P.id));if(!Be.ok){const qe=(await Be.json().catch(()=>({}))).error||"Failed to update task status.";l(qe),y(qe,"error"),n(at),s(oe);return}const Xe=await Be.json().catch(()=>null);Xe?h(Xe):await f(!0),Ne(),l("")}catch(We){console.error("Failed to update task status.",We),l("Failed to update task status."),y("Failed to update task status.","error"),n(at),s(oe)}},[t,z,Z,M,f,ye,we,h,V,y,Ne,s,l,n,e]),Q=o.useCallback(async(P,ee)=>{const Se=ee.saveSource;if(ee=Object.fromEntries(Object.entries(ee).filter(([Te])=>Te!=="saveSource")),Object.keys(ee).length===0)return!0;const _e=te.current.get(P),ke=e.find(Te=>Te.id===P)||t.find(Te=>Te.id===P),Ze=Date.parse(String(_e?.updatedAt||"")),st=Date.parse(String(ke?.updatedAt||"")),at=_e&&(!ke||Number.isFinite(Ze)&&(!Number.isFinite(st)||Ze>=st))?_e:ke;if(ke&&at===ke&&_e&&te.current.delete(P),at&&(ee=Object.fromEntries(Object.entries(ee).filter(([Te,fe])=>!vE(at[Te],fe))),Object.keys(ee).length===0))return!0;if(ee.status){const Te=e.find(fe=>fe.id===P)||t.find(fe=>fe.id===P);if(Te){await ie(Te,ee.status,ee);return}if(M){const fe="Task status was not saved because the current task could not be resolved safely.";l(fe),y(fe,"error");return}}const oe=e,We=t;n(Te=>Te.map(fe=>fe.id===P?{...fe,...ee}:fe)),s(Te=>Te.map(fe=>fe.id===P?{...fe,...ee}:fe));const G=Object.fromEntries(Object.entries(ee).filter(([Te])=>uh.has(Te)));let Be=Object.fromEntries(Object.entries(ee).filter(([Te])=>!uh.has(Te)));const Xe=Object.keys(G).length>0;let ze=Object.keys(Be).length>0,qe=!1;if(Xe&&v)try{const Te=Se?await v(P,G,{saveSource:Se}):await v(P,G);if(Te&&Te.state!=="disabled"){if(Te.state==="rejected"||Te.state==="failed"){const fe=oe.find($e=>$e.id===P)||We.find($e=>$e.id===P);n($e=>pn($e,fe,P,ee)),s($e=>pn($e,fe,P,ee));const Ee=Te.state==="failed"?"Task was not saved because durable local preparation failed. Retry the edit.":Te.retryable?"Task was not saved because durable capture is busy. Retry the edit shortly.":`Task was not saved because durable capture rejected it${Te.errorCode?` (${Te.errorCode})`:""}.`;return l(Ee),y(Ee,"error"),!1}if(qe=!0,"task"in Te&&Te.task&&h(Te.task),Te.state==="accepted")l("");else if(Te.state==="pending")l(""),Te.pendingReason!=="queued"&&y(Te.pendingReason==="auth"?"Task saved locally. Sign in to finish cloud sync.":Te.pendingReason==="sync-disabled"?"Task saved locally. Turn on sync to send it to cloud.":"Task saved locally. Cloud sync will retry automatically.","info");else{const fe=Te.state==="blocked"?`Task saved locally, but cloud sync is blocked${Te.errorCode?` (${Te.errorCode})`:""}.`:"Task save confirmation was interrupted. Retry the same edit to confirm it safely.";l(fe),y(fe,"error")}if(Te.state==="ambiguous"){if(ze){const fe=oe.find(Ee=>Ee.id===P)||We.find(Ee=>Ee.id===P);n(Ee=>pn(Ee,fe,P,Be)),s(Ee=>pn(Ee,fe,P,Be))}return!1}if(!ze)return!0}else if(z){const fe=oe.find($e=>$e.id===P)||We.find($e=>$e.id===P);n($e=>pn($e,fe,P,ee)),s($e=>pn($e,fe,P,ee));const Ee="Task was not saved because durable metadata capture was unavailable.";return l(Ee),y(Ee,"error"),!1}}catch(Te){if(console.error("Durable task metadata update failed before a conclusive result.",Te),ze){const Ee=oe.find($e=>$e.id===P)||We.find($e=>$e.id===P);n($e=>pn($e,Ee,P,Be)),s($e=>pn($e,Ee,P,Be))}const fe="Task save confirmation was interrupted. Retry the same edit to confirm it safely.";return l(fe),y(fe,"error"),!1}else if(Xe&&z){const Te=oe.find(Ee=>Ee.id===P)||We.find(Ee=>Ee.id===P);n(Ee=>pn(Ee,Te,P,ee)),s(Ee=>pn(Ee,Te,P,ee));const fe="Task was not saved because durable metadata capture was unavailable.";return l(fe),y(fe,"error"),!1}if(Xe&&!qe&&(Be={...G,...Be},ze=!0),!ze)return!0;try{const Te={...Be,...Se?{saveSource:Se}:{}},fe={method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(Te)},Ee=await ye(`/api/taskforce/task/${P}`,fe,Te,P,af(oe.find(rt=>rt.id===P)||We.find(rt=>rt.id===P),P));if(!Ee.ok){const kt=(await Ee.json().catch(()=>({}))).error||`Failed to update task ${P}.`;l(kt),y(kt,"error");const xe=oe.find(St=>St.id===P)||We.find(St=>St.id===P);return n(St=>pn(St,xe,P,Be)),s(St=>pn(St,xe,P,Be)),!1}const $e=await Ee.json().catch(()=>null);return h($e),Ne(ee.attachments!==void 0?150:0),l(""),!0}catch(Te){console.error("Failed to update task",Te);const fe=`Failed to update task ${P}.`;l(fe),y(fe,"error");const Ee=oe.find($e=>$e.id===P)||We.find($e=>$e.id===P);return n($e=>pn($e,Ee,P,Be)),s($e=>pn($e,Ee,P,Be)),!1}},[e,t,y,h,v,Ne,ie,z,M,ye]),H=async P=>{const ee=P.status==="done"?"task":"done";await ie(P,ee)},se=async P=>{const ee=P.status==="cancelled"?"task":"cancelled";await ie(P,ee)},Pe=async P=>{const ee=P.status==="in-progress"?"task":"in-progress";await ie(P,ee)},ue=async P=>{const ee=P.status==="review"?"task":"review";await ie(P,ee)},ne=async P=>{if(_)try{const ee=await _(P.id,{mutationKind:"archive",cancellation:P.status==="cancelled",reason:P.status==="cancelled"?P.canceledReason??null:null});if(ee&&we(ee,P.id,{},e,t)){const Se=ee.state!=="rejected"&&ee.state!=="failed"&&ee.state!=="ambiguous";return r===P.id&&Se&&(c(),d("tasks")),Se}if(!ee&&M)throw new Error("Durable task archive activation returned no result.")}catch(ee){console.error("Durable task archive failed before a conclusive result.",ee);const Se="Task archive confirmation was interrupted. Retry the same action to confirm it safely.";return l(Se),y(Se,"error"),!1}try{const Se=P.status==="cancelled"?"cancel":"complete",_e=`/api/taskforce/task/${P.id}/${Se}`,ke=await Ae(_e,{method:"POST"},{},af(P,P.id),Ze=>!!Ze&&typeof Ze=="object"&&String(Ze.id||"")===P.id);if(ke.ok){const Ze=await ke.json().catch(()=>null),st=[];if(Ze&&typeof Ze=="object"&&st.push(Ze),st.length>0){for(const oe of st)h(oe);Ne()}else p();const at=new Set(st.map(oe=>String(oe?.id||"").trim()).filter(oe=>oe.length>0));return r&&at.has(r)&&(c(),d("tasks")),!0}else{const st=(await ke.json().catch(()=>({}))).error||"Failed to archive task.";return l(st),y(st,"error"),!1}}catch(ee){return console.error("Failed to archive",ee),l("Failed to archive task."),y("Failed to archive task.","error"),!1}},Me=async()=>{const P=e.filter(ee=>ee.status==="done"||ee.status==="cancelled");if(P.length!==0&&confirm(`Archive ${P.length} completed/cancelled tasks?`)){if(_){let ee=!1,Se=0;for(const _e of P)try{const ke=await _(_e.id,{mutationKind:"archive",cancellation:_e.status==="cancelled",reason:_e.status==="cancelled"?_e.canceledReason??null:null});if(!ke||ke.state==="disabled"){if(!ee&&(!M||ke?.state==="disabled"))break;const Ze="Bulk archive stopped safely because durable capture became unavailable.";l(Ze),y(Ze,"error");return}if(ee=!0,we(ke,_e.id,{},e,t)){if(ke.state==="rejected"||ke.state==="failed")return;Se+=1}}catch(ke){console.error("Durable bulk archive confirmation was interrupted.",ke);const Ze="Bulk archive stopped safely. Retry to confirm the remaining tasks.";l(Ze),y(Ze,"error");return}if(ee){y(`${Se} tasks archived`,"info"),l("");return}}try{const ee=await fetch("/api/taskforce/bulk-archive",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({ids:P.map(Se=>Se.id)})});if(ee.ok){const Se=await ee.json(),_e=Array.isArray(Se?.results?.archived)?Se.results.archived:[];if(_e.length>0){for(const ke of _e)h(ke);Ne()}else n(ke=>ke.filter(Ze=>!["done","cancelled"].includes(Ze.status))),p();y(`${Se.archived||P.length} tasks archived`,"info"),l("")}else{const _e=(await ee.json().catch(()=>({}))).error||"Failed to bulk archive tasks.";l(_e),y(_e,"error")}}catch(ee){console.error("Failed to bulk archive",ee),l("Failed to bulk archive tasks."),y("Failed to bulk archive tasks.","error")}}},pe=async P=>{if(_)try{const ee=await _(P,{mutationKind:"unarchive"});if(ee&&we(ee,P,{},e,t)){ee.state!=="rejected"&&ee.state!=="failed"&&y("Task restored from archive.","info");return}if(!ee&&M)throw new Error("Durable task unarchive activation returned no result.")}catch(ee){console.error("Durable task unarchive failed before a conclusive result.",ee);const Se="Task restore confirmation was interrupted. Retry the same action to confirm it safely.";l(Se),y(Se,"error");return}try{const ee=`/api/taskforce/task/${P}/unarchive`,Se=t.find(ke=>ke.id===P)||e.find(ke=>ke.id===P),_e=await Ae(ee,{method:"POST"},{},af(Se,P),ke=>!!ke&&typeof ke=="object"&&String(ke.id||"")===P);if(_e.ok){const ke=await _e.json().catch(()=>null);ke?(h(ke),Ne()):(s(Ze=>Ze.filter(st=>st.id!==P)),await f(!0),Ne()),l(""),y("Task restored from archive.","info")}}catch(ee){console.error("Failed to unarchive",ee),l("Failed to unarchive task."),y("Failed to unarchive task.","error")}},le=o.useCallback(async(P,ee="previous",Se)=>{const _e=Array.from(new Map(P.map(oe=>[oe.id,oe])).values()),ke={requested:_e.length,completed:0,succeeded:[],failed:[]},Ze=()=>Se?.({...ke,succeeded:[...ke.succeeded],failed:[...ke.failed]}),st=(oe,We,G)=>{ke.failed.push({deletedRecordId:oe.id,taskId:oe.taskId,title:oe.taskSnapshot.title,message:We,...G?{code:G}:{}}),ke.completed+=1,Ze()},at=(oe,We)=>{h(We),i(G=>G.filter(Be=>Be.id!==oe.id&&Be.taskId!==We.id)),x.current.delete(oe.id),x.current.delete(oe.taskId),N.current.delete(oe.id),N.current.delete(oe.taskId),ke.succeeded.push(oe),ke.completed+=1,Ze()};if(O)for(const oe of _e){const We=await W(oe.id,oe.taskId,{silent:!0,restoreDestination:ee});We?at(oe,We):st(oe,"Failed to capture or confirm the durable restore.")}else{for(let oe=0;oe<_e.length;oe+=50){const We=_e.slice(oe,oe+50),G=We.map(Xe=>Xe.id),Be=ee==="archive"?{ids:G,restoreDestination:ee}:{ids:G};try{let Xe,ze=null;Z?(he.current||(he.current=ve||Qk()),ze=await he.current.prepareUpdate(U,"/api/taskforce/deleted/restore-batch",Be,ee==="archive"?{deletedRecordIds:G,restoreDestination:ee}:{deletedRecordIds:G}),Xe=await Jk("/api/taskforce/deleted/restore-batch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Be)},ze.operationId)):Xe=await ae("/restore-batch",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Be)});const qe=await Xe.json().catch(()=>({}));if(ze&&(Xe.ok||await sg(Xe))&&await he.current?.confirmUpdate(ze.fingerprint,ze.operationId),!Xe.ok){const Ee=String(qe.error||"Failed to restore the selected Trash records.");We.forEach($e=>st($e,Ee));continue}const Te=new Map(We.map(Ee=>[Ee.id,Ee])),fe=new Set;for(const Ee of qe.results||[]){const $e=String(Ee.deletedRecordId||"").trim(),rt=Te.get($e);if(!rt||!Ee.task)continue;const kt=No(Ee.task);kt.id===rt.taskId&&(fe.add($e),at(rt,kt))}for(const Ee of qe.errors||[]){const $e=String(Ee.id||"").trim(),rt=Te.get($e);!rt||fe.has($e)||(fe.add($e),st(rt,String(Ee.message||"Failed to restore the deleted task."),Ee.code?String(Ee.code):void 0))}for(const Ee of We)fe.has(Ee.id)||st(Ee,"The restore response did not include this deleted record.")}catch(Xe){const ze=Xe instanceof Error?Xe.message:"The restore request was interrupted.";We.forEach(qe=>st(qe,ze))}}Ne()}if(ke.failed.length>0){const oe=`${ke.succeeded.length} restored; ${ke.failed.length} failed and remain selected.`;l(oe),y(oe,"error")}else ke.succeeded.length>0&&(l(""),y(ee==="archive"?`${ke.succeeded.length} task${ke.succeeded.length===1?"":"s"} restored to Archive.`:`${ke.succeeded.length} task${ke.succeeded.length===1?"":"s"} restored from Trash.`,"info"));return ke},[O,Z,W,h,y,Ne,ae,i,l,ve,x,N,U]);return{copiedId:ce,handleDelete:q,handleUpdateTask:Q,handleSetStatus:ie,handleToggleComplete:H,handleToggleCancel:se,handleToggleInProgress:Pe,handleToggleReview:ue,handleArchiveTask:ne,handleBulkArchive:Me,handleUnarchive:pe,handleRestoreDeletedTask:W,handleRestoreSelectedDeletedTasks:le,handlePermanentlyDeleteDeletedTask:K,handleEmptyDeletedTasks:Re,handleCopyId:(P,ee)=>{P.stopPropagation(),navigator.clipboard.writeText(ee),Le(ee),Ie.current!==null&&window.clearTimeout(Ie.current),Ie.current=window.setTimeout(()=>{Ie.current=null,Le(null)},2e3)},queueWorkspaceSyncFromAuthoritativeTaskState:Ne}}const bE=wE;function ph(e){return e==="/api/taskforce/auth/runtime-config"||e==="/api/taskforce/sync/workspace/apply-local"||e==="/api/taskforce/sync/workspace/repair-startup"}function SE(e){try{return typeof window>"u"?null:typeof e=="string"?new URL(e,window.location.origin):e instanceof URL?e:typeof Request<"u"&&e instanceof Request?new URL(e.url,window.location.origin):null}catch{return null}}function AE({currentWorkspaceIdRef:e,resolveApiUrl:t,runtimeMode:r}){o.useEffect(()=>{if(typeof window>"u"||typeof window.fetch!="function")return;const n=window.fetch.bind(window),s=i=>{if(typeof i=="string")return r!=="cloud"?i:i.startsWith("/api/taskforce")&&!ph(i)?t(i):i;if(i instanceof URL)return r!=="cloud"?i:i.origin===window.location.origin&&i.pathname.startsWith("/api/taskforce")?ph(i.pathname)?i:new URL(t(`${i.pathname}${i.search}${i.hash}`)):i;if(typeof Request<"u"&&i instanceof Request){if(r!=="cloud")return i;const l=new URL(i.url,window.location.origin);if(l.origin===window.location.origin&&l.pathname.startsWith("/api/taskforce"))return ph(l.pathname)?i:t(`${l.pathname}${l.search}${l.hash}`)}return i};return window.fetch=((i,l)=>{const c=s(i),d=SE(c);if(!!!(d&&d.pathname.startsWith("/api/taskforce")&&!ph(d.pathname)))return n(c,l);const p=String(e.current||"").trim();if(typeof Request<"u"&&c instanceof Request){const h=new Headers(c.headers);l?.headers&&new Headers(l.headers).forEach((b,C)=>h.set(C,b)),p&&p!=="default"&&!h.has("x-taskforce-workspace-id")&&(h.set("x-taskforce-workspace-id",p),h.set("x-taskforce-workspace-authoritative","1"));const y=new Request(c,{...l,headers:h});return n(y)}const g=new Headers(l?.headers);return p&&p!=="default"&&!g.has("x-taskforce-workspace-id")&&(g.set("x-taskforce-workspace-id",p),g.set("x-taskforce-workspace-authoritative","1")),n(c,{...l,headers:g})}),()=>{window.fetch=n}},[e,t,r])}const kf=12e3,CE=3e4,IE=2e4;function fh(e){return e==="cloud"?CE:kf}function eS(){return typeof performance<"u"?performance.now():Date.now()}function _E({runtimeConfigReady:e,shouldProbeCloudAuth:t,authSessionResolved:r,resolveCloudAuthUrl:n,authOnlyCloudMode:s,authRequiredError:i,runtimeMode:l,workspaceSelectionScope:c,markBootstrapPhase:d,markBootstrapStalled:f,setRuntimeMode:p,setAuthRequiredForApi:g,setIsAuthenticated:h,setAuthUserId:y,setAuthWorkspaceId:k,setAuthUserEmail:b,setAuthUserDisplayName:C,setAuthUserAvatarUrl:S,setUserGlobalSyncStatus:w,setUserGlobalSyncError:T,setHasBetaAccess:E,setAvailableWorkspaces:x,setHydratedWorkspaceRole:N,setAssigneeOptions:v,setAuthBlocked:V,setAuthSessionResolved:_,setError:j,applyResolvedWorkspaceId:F,readPersistedWorkspaceId:z,authSessionRequestRef:M,authSessionEpochRef:O,authSessionLastCheckedAtRef:Z,authSessionLastResultRef:U,isLoopbackHost:ve,setAuthStateReadyRefs:te}){const ce=o.useCallback(async Ie=>{const Ye=Ie?.force===!0;if(d("auth"),!e)return U.current;if(!t)return p("local"),g(!1),h(!1),y("anonymous"),k(""),pf(null),b(""),C(""),S(""),w("disconnected"),T(null),E(!0),x([]),N(null),v(gl()),V(!1),_(!0),te(!1,!0,!1),U.current=!1,Z.current=Date.now(),!1;const ge=n("/api/taskforce/auth/session"),he=Date.now();if(!Ye&&M.current)return M.current;if(!Ye&&r&&he-Z.current<1500)return U.current;const Ae=++O.current;let ye=null;return ye=(async()=>{const Ne=eS(),ae=new AbortController,q=typeof window<"u"?window.setTimeout(()=>ae.abort(),IE):null,W=()=>O.current!==Ae,K=(Re,we)=>{wr(Re,{durationMs:Math.max(0,Math.round(eS()-Ne)),force:Ye,sessionUrl:ge,...we})};try{const Re=await fetch(ge,{method:"GET",credentials:"include",mode:"cors",signal:ae.signal});if(W())return U.current;if(Re.status===429)return _(!0),te(U.current,!0,!1),K("auth_session_rate_limited",{status:Re.status}),U.current;if(!Re.ok)return W()?U.current:(ve&&pf(null),_(!0),te(!1,!0,!1),U.current=!1,K("auth_session_request_failed",{status:Re.status}),!1);const we=await Re.json();if(W())return U.current;const ie=!!we.authRequiredForApi,Q=!!we.authenticated,H=Q?we.betaAccess!==!1:!0,se=typeof we.workspaceId=="string"&&we.workspaceId.trim().length>0?we.workspaceId.trim():"",Pe=typeof we.userId=="string"&&we.userId.trim().length>0?we.userId.trim():"anonymous",ue=typeof we.email=="string"&&we.email.trim().length>0?we.email.trim().toLowerCase():"",ne=typeof we.displayName=="string"?we.displayName.trim():"",Me=typeof we.avatarUrl=="string"?we.avatarUrl.trim():"",pe=l==="local",le=l==="local"||s,Ce=s||pe?!1:ie;return g(Ce),h(Q),y(Q?Pe:"anonymous"),k(Q?se:""),ve&&pf(Q?Pe:null),b(Q?ue:""),C(Q?ne:""),S(Q?Me:""),Q&&j(P=>P===i?"":P),w(Q?"idle":"disconnected"),T(null),E(H),le||F(se||z(c)||"default",{preserveNonDefaultDefault:!0}),V(s||pe?!1:ie&&!Q),_(!0),te(Q,!0,Ce),U.current=Q,Q&&d("ready"),K("auth_session_resolved",{status:Re.status,authenticated:Q,workspaceId:Q?se:"",userId:Q?Pe:"anonymous",authRequiredForApi:Ce}),Q}catch(Re){return W()||(ve&&pf(null),_(!0),te(!1,!0,!1),U.current=!1,f("Unable to verify your session."),K("auth_session_exception",{error:Re instanceof Error?Re.message:String(Re)})),U.current}finally{q!==null&&typeof window<"u"&&window.clearTimeout(q),W()||(Z.current=Date.now()),ye&&M.current===ye&&(M.current=null)}})(),M.current=ye,ye},[e,t,r,n,s,i,l,c,d,f,p,g,h,y,k,b,C,S,w,T,E,x,N,v,V,_,j,F,z,M,O,Z,U,ve,te]),Le=l==="local"&&ve&&t?Dv():"";return o.useEffect(()=>{Le&&(h(!0),_(!0),y(Le),te(!0,!0,!1),U.current=!0)},[Le,_,te,y,h,U]),o.useEffect(()=>{if(l!=="local"||!t||typeof window>"u")return;const Ie=()=>{ce()},Ye=()=>{document.visibilityState==="visible"&&Ie()};window.addEventListener("focus",Ie),window.addEventListener("online",Ie),document.addEventListener("visibilitychange",Ye);const ge=window.setInterval(Ie,3e4);return()=>{window.removeEventListener("focus",Ie),window.removeEventListener("online",Ie),document.removeEventListener("visibilitychange",Ye),window.clearInterval(ge)}},[l,t,ce]),{checkAuthSession:ce}}function TE(e){const t=e.runtimeMode==="cloud",r=!!(e.shouldGateProtectedApiCalls&&t&&!e.authSessionResolved),n=!!(e.shouldGateProtectedApiCalls&&t&&e.authSessionResolved&&e.authRequiredForApi&&!e.isAuthenticated);return{shouldDeferProtectedApiCalls:r,shouldBlockProtectedApiCalls:n,canCallProtectedApi:!(r||n)}}function xE(e){return!!(!e.isOpen||!e.canCallProtectedApi||e.authBlocked||e.authRequiredForApi&&!e.isAuthenticated)}function RE(e){return!!(e.shouldGateProtectedApiCalls&&!e.authSessionResolved||e.authRequiredForApi&&!e.isAuthenticated)}function Pa(){return typeof performance<"u"?performance.now():Date.now()}function jE(e){const{shouldDeferProtectedApiCalls:t,shouldBlockProtectedApiCalls:r,getWorkspaceRequestState:n,isWorkspaceRequestStale:s,isWorkspaceEpochStale:i,isAbortError:l,isBootstrapTimeoutError:c,fetchWithTimeout:d,handleUnauthorized:f,applyBootstrapConfig:p,loadPersistedUiState:g,fetchBuildInfo:h,markBootstrapPhase:y,markBootstrapStalled:k,fetchInitiativeTemplates:b,setReferenceDataLoaded:C,setCustomCategories:S,setCustomTypes:w,setPriorities:T,setTaxonomies:E,setTaxonomyDisplayLabels:x,setConfigLoaded:N,hasLoadedUiStateRef:v,currentWorkspaceIdRef:V,referenceDataRequestRef:_,referenceDataAbortRef:j,bootstrapConfigAbortRef:F,workspaceListAbortRef:z,assigneeOptionsAbortRef:M,workspaceListHydratedRef:O,setAvailableWorkspaces:Z,runtimeMode:U,applyResolvedWorkspaceId:ve,workspaceSwitchingEnabled:te,authSessionResolved:ce,isAuthenticated:Le,authUserId:Ie,authUserAvatarUrl:Ye,setHydratedWorkspaceRole:ge,setAssigneeOptions:he,setAssigneeOptionsLoaded:Ae,commitCurrentWorkspaceId:ye,currentWorkspaceId:Ne,workspaceSelectionScope:ae,abortWorkspaceScopedRequests:q,setWorkspaceBootstrapPending:W,checkAuthSession:K,lastConfigRefreshKeyRef:Re,lastAssigneeOptionsLoadKeyRef:we,lastWorkspaceSyncStateLoadKeyRef:ie,lastTaskSurfaceLoadKeyRef:Q,lastSettingsSurfaceLoadKeyRef:H,isOpen:se,activeTab:Pe,showArchive:ue,taskScope:ne,settingsSection:Me,workspaceBootstrapPending:pe,fetchTasks:le,fetchPlanningEntities:Ce,refreshTaskCollections:P,loadWorkspaceSyncState:ee,switchLocalCoordinatorWorkspace:Se,hasBootstrappedDataRef:_e}=e,ke=o.useCallback(async ze=>{const qe=ze?.ignoreAuthGuard===!0,Te=ze?.force===!0;if(!qe&&(t||r)){wr("bootstrap_reference_data_skipped",{reason:r?"auth_blocked":"auth_deferred",runtimeMode:U,workspaceId:String(n().workspaceId||"").trim()||"default",force:Te});return}const fe=n(),Ee=String(fe.workspaceId||"").trim()||"default";if(!(U!=="cloud"||!ce||!Le||Ee!==""&&Ee!=="default")){wr("bootstrap_reference_data_skipped",{reason:"workspace_unresolved",runtimeMode:U,workspaceId:Ee,force:Te});return}if(!Te&&_.current?.workspaceId===fe.workspaceId){wr("bootstrap_reference_data_reused",{workspaceId:Ee,force:Te}),await _.current.promise;return}C(!1);const rt=Pa(),kt=new AbortController;j.current=kt;const xe=(async()=>{await Promise.allSettled([(async()=>{let St="empty-taxonomy-state";const jt=await fetch("/api/taskforce/taxonomy-state",{signal:kt.signal});if(!jt.ok)return;const $=await jt.json().catch(()=>({}));if(AC($))St="taxonomy-state";else{St="fallback-endpoints";const[Qe,Ge,At,Nt]=await Promise.all([fetch("/api/taskforce/categories",{signal:kt.signal}),fetch("/api/taskforce/types",{signal:kt.signal}),fetch("/api/taskforce/priorities",{signal:kt.signal}),fetch("/api/taskforce/taxonomies",{signal:kt.signal})]),[Bt,Qt,Xt,nt]=await Promise.all([Qe.ok?Qe.json().catch(()=>({})):Promise.resolve({}),Ge.ok?Ge.json().catch(()=>({})):Promise.resolve({}),At.ok?At.json().catch(()=>({})):Promise.resolve({}),Nt.ok?Nt.json().catch(()=>({})):Promise.resolve({})]);$.categories=Bt.categories,$.types=Qt.types,$.priorities=Xt.priorities,$.taxonomies=nt.taxonomies}const Ke=Aj($);if(s(fe)){wr("bootstrap_reference_data_stale_drop",{workspaceId:Ee,source:St});return}Ke.categories.length>0&&S(Ke.categories),Ke.types.length>0&&w(Ke.types),Ke.priorities.length>0&&T(Ke.priorities),E(Ke.taxonomies),x(Ke.displayLabels||{}),wr("bootstrap_reference_data_source",{workspaceId:Ee,source:St,categories:Ke.categories.length,types:Ke.types.length,priorities:Ke.priorities.length,taxonomies:Ke.taxonomies.length})})(),b()]),!s(fe)&&(C(!0),wr("bootstrap_reference_data_loaded",{durationMs:Math.max(0,Math.round(Pa()-rt)),workspaceId:Ee,force:Te}))})();_.current={workspaceId:fe.workspaceId,promise:xe};try{await xe}finally{_.current?.promise===xe&&(_.current=null),j.current===kt&&(j.current=null)}},[ce,b,n,Le,s,j,_,U,S,w,T,C,E,x,r,t]),Ze=o.useCallback(async ze=>{if(!(ze?.ignoreAuthGuard===!0)&&(t||r))return;y("config");const Te=n(),fe=Pa(),Ee=new AbortController;F.current=Ee;try{const $e=await d("/api/taskforce/config",void 0,fh(U),{signal:Ee.signal});if(i(Te))return;if($e.status===401){f(),N(!0);return}let rt="";if($e.ok){const kt=await $e.json();if(i(Te))return;rt=typeof kt?.workspaceId=="string"&&kt.workspaceId.trim().length>0?kt.workspaceId.trim():"",p(kt)}if(i(Te)){const kt=String(V.current||"default").trim()||"default";if(!rt||kt!==rt)return}if(v.current||(v.current=!0,await g(rt||Te.workspaceId)),i(Te)){const kt=String(V.current||"default").trim()||"default";if(!rt||kt!==rt)return}N(!0),y("ready"),wr("bootstrap_config_loaded",{durationMs:Math.max(0,Math.round(Pa()-fe)),status:$e.status,workspaceId:rt||Te.workspaceId}),h()}catch($e){if(l($e)||i(Te))return;v.current||(v.current=!0,await g(Te.workspaceId)),k(c($e)?"Startup checks timed out.":"Unable to finish startup checks."),N(!0),wr("bootstrap_config_failed",{durationMs:Math.max(0,Math.round(Pa()-fe)),workspaceId:Te.workspaceId,error:$e instanceof Error?$e.message:String($e)})}finally{F.current===Ee&&(F.current=null)}},[p,F,V,h,d,n,f,v,l,c,i,g,y,k,U,N,r,t]),st=o.useCallback(async ze=>{await Ze(ze),await ke(ze)},[Ze,ke]),at=o.useCallback(async()=>{if(!te)return Z([]),O.current=!1,{success:!0,workspaces:[]};const ze=n(),qe=Pa(),Te=new AbortController;z.current=Te;try{const fe=await d("/api/taskforce/workspaces",{method:"GET",credentials:"include"},fh(U),{signal:Te.signal});if(i(ze))return{success:!1,error:"Workspace changed while loading workspaces."};if(fe.status===401)return Z([]),O.current=!1,{success:!1,error:"Authentication required."};const Ee=await fe.json().catch(()=>({}));if(i(ze))return{success:!1,error:"Workspace changed while loading workspaces."};if(!fe.ok||Ee?.success===!1)return Z([]),O.current=!1,{success:!1,error:Ee?.error||`Failed to load workspaces (${fe.status})`};const $e=Array.isArray(Ee?.workspaces)?Ee.workspaces.map(rt=>({id:String(rt?.id||"").trim(),name:String(rt?.name||"").trim(),role:String(rt?.role||"member").trim().toLowerCase(),slug:typeof rt?.slug=="string"?rt.slug:null,description:typeof rt?.description=="string"?rt.description:null,status:typeof rt?.status=="string"?rt.status:"",betaAccess:rt?.betaAccess===!0})).filter(rt=>rt.id&&rt.name):[];return Z($e),O.current=!0,U!=="local"&&typeof Ee?.currentWorkspaceId=="string"&&Ee.currentWorkspaceId.trim().length>0&&ve(Ee.currentWorkspaceId.trim(),{preserveNonDefaultDefault:!0}),wr("bootstrap_workspaces_loaded",{durationMs:Math.max(0,Math.round(Pa()-qe)),workspaceId:ze.workspaceId,count:$e.length,status:fe.status}),{success:!0,workspaces:$e}}catch(fe){return c(fe)&&k("Startup checks timed out."),Z([]),O.current=!1,wr("bootstrap_workspaces_failed",{durationMs:Math.max(0,Math.round(Pa()-qe)),workspaceId:ze.workspaceId,error:fe instanceof Error?fe.message:String(fe)}),{success:!1,error:l(fe)?"Workspace list request aborted.":"Failed to load workspaces."}}finally{z.current===Te&&(z.current=null)}},[ve,d,n,l,c,i,k,U,Z,z,O,te]),oe=o.useCallback(async()=>{const ze=n(),qe=Pa(),Te=new AbortController;M.current=Te,Ae(!1);try{const[fe,Ee]=await Promise.all([d("/api/taskforce/workspace/assignee-options",{method:"GET",credentials:"include"},fh(U),{signal:Te.signal}),ce&&Le?d("/api/taskforce/auth/workspace-members",{method:"GET",credentials:"include"},fh(U),{signal:Te.signal}).catch(()=>null):Promise.resolve(null)]);if(s(ze))return{success:!1,error:"Workspace changed while loading assignee options."};if(fe.status===401)return he(gl()),Ae(!0),{success:!1,error:"Authentication required."};const $e=await fe.json().catch(()=>({}));if(s(ze))return{success:!1,error:"Workspace changed while loading assignee options."};if(!fe.ok)return he(gl()),Ae(!0),{success:!1,error:$e?.error||`Failed to load assignee options (${fe.status})`};const rt=String(Ie||"").trim(),kt=String(Ye||"").trim(),xe=(Ge,At)=>{const Nt=typeof Ge?.avatarUrl=="string"&&Ge.avatarUrl.trim().length>0?Ge.avatarUrl.trim():"";if(Nt)return Nt;const Bt=String(Ge?.userId||At||"").trim();return rt&&Bt===rt&&kt?kt:null},St=Array.isArray($e?.assignees)?$e.assignees:[],jt=St.map(Ge=>{const At=String(Ge?.value||"").trim(),Nt=String(Ge?.kind||"").trim().toLowerCase();return At?Nt==="agent"||Nt==="ai"?{value:At,label:String(Ge?.label||At).trim()||At,icon:String(Ge?.icon||"Bot"),color:String(Ge?.color||"#8b5cf6"),kind:"agent",avatarUrl:typeof Ge?.avatarUrl=="string"&&Ge.avatarUrl.trim().length>0?Ge.avatarUrl.trim():null,avatarRevision:Number.isFinite(Number(Ge?.avatarRevision))?Math.max(0,Math.floor(Number(Ge.avatarRevision))):null,avatarUpdatedAt:typeof Ge?.avatarUpdatedAt=="string"&&Ge.avatarUpdatedAt.trim().length>0?Ge.avatarUpdatedAt.trim():null,username:typeof Ge?.username=="string"&&Ge.username.trim().length>0?Ge.username.trim():null,surfaceType:typeof Ge?.surfaceType=="string"&&Ge.surfaceType.trim().length>0?Ge.surfaceType.trim():null,providerMetadata:Ge?.providerMetadata&&typeof Ge.providerMetadata=="object"&&!Array.isArray(Ge.providerMetadata)?Ge.providerMetadata:null,archivedAt:typeof Ge?.archivedAt=="string"&&Ge.archivedAt.trim().length>0?Ge.archivedAt.trim():null,createdAt:typeof Ge?.createdAt=="string"&&Ge.createdAt.trim().length>0?Ge.createdAt.trim():null,updatedAt:typeof Ge?.updatedAt=="string"&&Ge.updatedAt.trim().length>0?Ge.updatedAt.trim():null}:Nt==="member"||Nt==="human"?{value:At,label:String(Ge?.label||At).trim()||At,icon:String(Ge?.icon||"User"),color:String(Ge?.color||"#22c55e"),kind:"member",avatarUrl:xe(Ge,At)}:null:null}).filter(Boolean),$=St.map(Ge=>({userId:String(Ge?.userId||"").trim(),email:String(Ge?.email||"").trim().toLowerCase(),displayName:typeof Ge?.displayName=="string"?Ge.displayName:null,avatarUrl:xe(Ge)})).filter(Ge=>Ge.userId);let Ke=$;if(Ee?.ok){const Ge=await Ee.json().catch(()=>({})),At=Array.isArray(Ge?.users)?Ge.users:[],Nt=At.find(Xt=>String(Xt?.userId||"").trim()===rt),Bt=String(Nt?.role||"").trim().toLowerCase();Bt==="owner"||Bt==="admin"||Bt==="member"||Bt==="read-only"?ge(Bt):!te&&At.length===0&&ge(null);const Qt=At.map(Xt=>({userId:String(Xt?.userId||"").trim(),email:String(Xt?.email||"").trim().toLowerCase(),displayName:typeof Xt?.displayName=="string"?Xt.displayName:null,avatarUrl:xe(Xt)})).filter(Xt=>Xt.userId);Ke=Array.from(new Map([...$,...Qt].map(Xt=>[Xt.userId,Xt])).values())}else!te&&!$.length&&ge(null);const Qe=$u([...jt,...Ex(Ke).filter(Ge=>Ge.kind==="member")]);return s(ze)?{success:!1,error:"Workspace changed while loading assignee options."}:(he(Qe),Ae(!0),wr("bootstrap_assignee_options_loaded",{durationMs:Math.max(0,Math.round(Pa()-qe)),workspaceId:ze.workspaceId,count:Qe.length}),{success:!0})}catch(fe){return s(ze)||(he(gl()),Ae(!0)),wr("bootstrap_assignee_options_failed",{durationMs:Math.max(0,Math.round(Pa()-qe)),workspaceId:ze.workspaceId,error:fe instanceof Error?fe.message:String(fe)}),{success:!1,error:l(fe)?"Assignee options request aborted.":"Failed to load assignee options."}}finally{M.current===Te&&(M.current=null)}},[M,ce,Ye,Ie,d,n,l,Le,s,U,he,Ae,ge,te]),We=o.useCallback(async(ze,qe)=>{if(!te)return{success:!1,error:"Workspace switching is unavailable in local mode.",code:"WORKSPACE_SWITCHING_DISABLED"};const Te=String(ze||"").trim();if(!Te)return{success:!1,error:"workspaceId is required."};const fe=String(V.current||"").trim()||"default",Ee=Pa();try{wr("bootstrap_workspace_switch_started",{fromWorkspaceId:fe,toWorkspaceId:Te,hydrate:qe?.hydrate!==!1});const $e=U==="local"?"/api/taskforce/session/workspace?taskforceCloud=1":"/api/taskforce/session/workspace",rt=await fetch($e,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:Te})}),kt=await rt.json().catch(()=>({}));if(!rt.ok||kt?.success===!1)return{success:!1,error:kt?.error||`Failed to switch workspace (${rt.status})`,code:kt?.code};try{fe!=="default"&&await Se(Te)}catch(St){return fe&&fe!=="default"&&(await fetch($e,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:fe})}).catch(()=>null),await K({force:!0}).catch(()=>!1)),{success:!1,error:St instanceof Error?St.message:"The local sync coordinator rejected the workspace switch.",code:String(St?.code||"SYNC_COORDINATOR_WORKSPACE_SWITCH_FAILED")}}ye(Te,{clearExplicitSelection:!1}),q(),W(!0),y("workspace");const xe=await K({force:!0});return qe?.hydrate===!1?await at():(Re.current=`${U}:${Te}:${ae}`,we.current=`${U}:${xe?"auth":"guest"}:${Te}`,ie.current=Te,se&&Pe==="tasks"&&!(ue||ne==="archived"||ne==="deleted")&&(Q.current=`${Te}:${Pe}:active:${ne}`),se&&Pe==="settings"&&(H.current=`${Te}:${Pe}:${Me}`),await Promise.all([st(),at(),P({isSilent:!1}),ee()]),Ce({ignoreAuthGuard:!0})),wr("bootstrap_workspace_switch_completed",{fromWorkspaceId:fe,toWorkspaceId:Te,hydrate:qe?.hydrate!==!1,durationMs:Math.max(0,Math.round(Pa()-Ee))}),{success:!0}}catch($e){return wr("bootstrap_workspace_switch_failed",{fromWorkspaceId:fe,toWorkspaceId:Te,hydrate:qe?.hydrate!==!1,durationMs:Math.max(0,Math.round(Pa()-Ee)),error:$e instanceof Error?$e.message:String($e)}),{success:!1,error:"Failed to switch workspace."}}finally{W(!1)}},[q,Pe,K,ye,V,st,Ce,at,se,we,Re,H,Q,ie,ee,y,P,U,Me,W,ue,Se,ne,ae,te]),G=o.useCallback(async ze=>{y("workspace"),W(!0);try{if(!te){const xe=String(Ne||"").trim()||"default";return ye(xe),{success:!0,workspaceSetupRequired:!1,workspaceId:xe}}const qe=String(ze?.preferredWorkspaceId||"").trim(),Te=Nk(ae),fe=await at();if(!fe.success)return{success:!1,workspaceSetupRequired:!1,error:fe.error||"Failed to load workspaces after authentication."};const Ee=Array.isArray(fe.workspaces)?fe.workspaces:[];if(Ee.length===0)return ye("default"),{success:!0,workspaceSetupRequired:!0};const $e=new Set(Ee.map(xe=>String(xe.id||"").trim()).filter(Boolean)),rt=String(V.current||"").trim(),kt=(qe&&$e.has(qe)?qe:"")||(rt&&$e.has(rt)?rt:"")||(Te&&$e.has(Te)?Te:"")||String(Ee[0]?.id||"").trim();if(!kt)return ye("default"),{success:!0,workspaceSetupRequired:!0};if(rt!==kt){const xe=await We(kt,{hydrate:!1});if(!xe.success)return{success:!1,workspaceSetupRequired:!1,error:xe.error||"Failed to set workspace after authentication.",code:xe.code}}else ye(kt);return{success:!0,workspaceSetupRequired:!1,workspaceId:kt}}catch{return k("Unable to resolve workspace access."),{success:!1,workspaceSetupRequired:!1,error:"Failed to resolve workspace access."}}finally{W(!1)}},[ye,Ne,V,at,y,k,W,We,ae,te]),Be=o.useCallback(async()=>{y("auth");const ze=Pa();wr("bootstrap_retry_started",{workspaceId:String(V.current||"default").trim()||"default"});const qe=await K({force:!0});let Te=!1;if(te&&qe){const fe=await G();if(!fe.success||fe.workspaceSetupRequired){await st({ignoreAuthGuard:!0}),wr("bootstrap_retry_completed",{workspaceId:String(V.current||"default").trim()||"default",authenticated:qe,workspaceSetupRequired:fe.workspaceSetupRequired===!0,success:fe.success,durationMs:Math.max(0,Math.round(Pa()-ze))});return}}W(!0);try{await st({ignoreAuthGuard:!0}),qe&&!Te&&(await Promise.all([le(!0,{ignoreAuthGuard:!0}),ke({ignoreAuthGuard:!0,force:!0})]),Ce({ignoreAuthGuard:!0})),wr("bootstrap_retry_completed",{workspaceId:String(V.current||"default").trim()||"default",authenticated:qe,workspaceSetupRequired:Te,success:!0,durationMs:Math.max(0,Math.round(Pa()-ze))})}finally{W(!1)}},[K,V,st,Ce,ke,le,y,G,W,te]),Xe=o.useCallback(async ze=>{const qe=ze?.reason||"initial-load",Te=ze?.ignoreAuthGuard===!0,fe=ze?.tasksSilent!==!1,Ee=Pa();if(y("auth"),!await K({force:!0}))return await st({ignoreAuthGuard:!0}),wr("cloud_bootstrap_completed",{reason:qe,durationMs:Math.max(0,Math.round(Pa()-Ee)),authenticated:!1,workspaceSetupRequired:!1,success:!1}),{success:!1,authenticated:!1,workspaceSetupRequired:!1,error:"Sign in required.",code:"AUTH_REQUIRED"};if(te){const rt=await G();if(!rt.success)return await st({ignoreAuthGuard:!0}),wr("cloud_bootstrap_completed",{reason:qe,durationMs:Math.max(0,Math.round(Pa()-Ee)),authenticated:!0,workspaceSetupRequired:!1,success:!1,error:rt.error||"Workspace resolution failed."}),{success:!1,authenticated:!0,workspaceSetupRequired:!1,error:rt.error||"Unable to resolve workspace access.",code:rt.code};if(rt.workspaceSetupRequired)return await st({ignoreAuthGuard:!0}),wr("cloud_bootstrap_completed",{reason:qe,durationMs:Math.max(0,Math.round(Pa()-Ee)),authenticated:!0,workspaceSetupRequired:!0,success:!0}),{success:!0,authenticated:!0,workspaceSetupRequired:!0}}W(!0);try{await Ze({ignoreAuthGuard:Te});const rt=String(V.current||"default").trim()||"default",kt=Pa();return le(fe,{ignoreAuthGuard:Te}).then(()=>{wr("cloud_bootstrap_tasks_loaded_deferred",{reason:qe,workspaceId:rt,durationMs:Math.max(0,Math.round(Pa()-kt))})}).catch(xe=>{wr("cloud_bootstrap_tasks_deferred_failed",{reason:qe,workspaceId:rt,error:xe instanceof Error?xe.message:String(xe)})}),ke({ignoreAuthGuard:Te}).then(()=>{wr("cloud_bootstrap_reference_data_loaded_deferred",{reason:qe,workspaceId:rt,durationMs:Math.max(0,Math.round(Pa()-kt))})}).catch(xe=>{wr("cloud_bootstrap_reference_data_deferred_failed",{reason:qe,workspaceId:rt,error:xe instanceof Error?xe.message:String(xe)})}),Ce({ignoreAuthGuard:Te}),wr("cloud_bootstrap_completed",{reason:qe,durationMs:Math.max(0,Math.round(Pa()-Ee)),authenticated:!0,workspaceSetupRequired:!1,success:!0,workspaceId:rt}),{success:!0,authenticated:!0,workspaceSetupRequired:!1}}finally{W(!1)}},[K,V,Ze,Ce,ke,le,y,G,W,te]);return o.useEffect(()=>{!t&&!r&&!_e.current&&(_e.current=!0,(async()=>{const ze=Pa();if(U==="cloud"&&ce&&Le){const qe=await Xe({reason:"initial-load",tasksSilent:!1});if(!qe.success||qe.workspaceSetupRequired)return}else await Ze(),await Promise.all([le(!1),ke()]),Ce();wr("bootstrap_initial_load_completed",{durationMs:Math.max(0,Math.round(Pa()-ze)),runtimeMode:U,workspaceId:String(V.current||"default").trim()||"default"})})())},[ce,V,Ze,Ce,ke,le,_e,Le,Xe,U,r,t]),o.useEffect(()=>{if(t||r||pe||ae==="bootstrap"||!_e.current)return;const ze=`${U}:${Ne}:${ae}`;Re.current!==ze&&(Re.current=ze,st())},[Ne,st,_e,Re,U,r,t,pe,ae]),o.useEffect(()=>{if(t||r||pe)return;const ze=Ne;ie.current!==ze&&(ie.current=ze,ee())},[Ne,ie,ee,r,t,pe]),o.useEffect(()=>{if(U!=="cloud"||!ce||!Le){U!=="cloud"&&Z([]),O.current=!1;return}pe||!_e.current||O.current||at()},[ce,at,_e,Le,U,Z,pe,O]),{fetchReferenceData:ke,fetchBootstrapConfig:Ze,fetchConfig:st,fetchWorkspaces:at,fetchAssigneeOptions:oe,switchWorkspace:We,resolveWorkspaceAfterAuth:G,retryBootstrapChecks:Be,runCloudBootstrap:Xe}}function PE(e){const{runtimeMode:t,workspaceUiStateScope:r,currentWorkspaceId:n,currentWorkspaceIdRef:s,referenceDataLoaded:i,activeCategories:l,activeTypes:c,priorities:d,taxonomies:f,activeWorkspaceModule:p,setActiveWorkspaceModuleState:g,groupBy:h,setGroupBy:y,emptyColumnMode:k,setEmptyColumnMode:b,taskScope:C,setTaskScope:S,openTaskId:w,setPendingOpenTaskId:T,compressedCards:E,setCompressedCards:x,zenMode:N,setZenModeState:v,searchQuery:V,setSearchQuery:_,collapsedCategories:j,setCollapsedCategories:F,filterCategories:z,setFilterCategories:M,filterPriorities:O,setFilterPriorities:Z,filterTypes:U,setFilterTypes:ve,filterStatus:te,setFilterStatus:ce,filterAssignees:Le,setFilterAssignees:Ie,filterAssigneesAllSelected:Ye,setFilterAssigneesAllSelected:ge,filterTaxonomies:he,setFilterTaxonomies:Ae,sortBy:ye,setSortBy:Ne,sortOrder:ae,setSortOrder:q,hasInitedFilters:W,setHasInitedFilters:K,lastUsedCategory:Re,setLastUsedCategory:we,taskforceAgentId:ie,setTaskforceAgentId:Q,taskforceAgentConversationId:H,setTaskforceAgentConversationId:se,taskforceAgentConversationByAgentId:Pe,setTaskforceAgentConversationByAgentId:ue}=e,ne=o.useRef(!1),Me=o.useRef(""),pe=o.useRef(!1),le=o.useRef(!1),Ce=o.useRef(null),[P,ee]=o.useState(!1),Se=o.useMemo(()=>i?Wx({categories:l,types:c,priorities:d,taxonomies:f}):null,[l,c,d,i,f]),_e=o.useCallback(oe=>{P||(le.current=!0),g(oe)},[g,P]),ke=o.useCallback((oe,We)=>{if(!oe){Ce.current=null,Q(""),se(""),ue({}),T(null);return}const G=Array.isArray(oe.filterCategories)||Array.isArray(oe.filterPriorities)||Array.isArray(oe.filterTypes)||oe.filterTaxonomies&&typeof oe.filterTaxonomies=="object";G||(Ce.current=null);const Be=Array.isArray(oe.filterCategories)||Array.isArray(oe.filterPriorities)||Array.isArray(oe.filterTypes)||Array.isArray(oe.filterStatus)||Array.isArray(oe.filterAssignees)||typeof oe.filterAssigneesAllSelected=="boolean"||oe.filterTaxonomies&&typeof oe.filterTaxonomies=="object",Xe=i,ze=!!(oe.filterTaxonomySignature&&Se);G&&!Xe&&(Ce.current={state:oe,skipActiveWorkspaceModule:We?.skipActiveWorkspaceModule});const qe=G&&Xe&&(!ze||$x(oe.filterTaxonomySignature,Se)),Te=G&&ze&&!qe,fe=!G||qe||Te;if(We?.skipActiveWorkspaceModule||(oe.activeWorkspaceModule?g(oe.activeWorkspaceModule):oe.groupBy==="docs"&&g("docs")),oe.groupBy&&oe.groupBy!=="docs"&&y(oe.groupBy),oe.emptyColumnMode&&b(oe.emptyColumnMode),oe.taskScope&&S(oe.taskScope),(typeof oe.openTaskId=="string"||oe.openTaskId===null)&&T(oe.openTaskId),typeof oe.compressedCards=="boolean"&&x(oe.compressedCards),typeof oe.zenMode=="boolean"&&v(oe.zenMode),typeof oe.searchQuery=="string"&&_(oe.searchQuery),oe.collapsedCategories&&typeof oe.collapsedCategories=="object"&&F(oe.collapsedCategories),qe?(M(Array.isArray(oe.filterCategories)?oe.filterCategories:l.map(Ee=>Ee.value)),Z(Array.isArray(oe.filterPriorities)?oe.filterPriorities:d.map(Ee=>Ee.value)),ve(Array.isArray(oe.filterTypes)?oe.filterTypes:c.map(Ee=>Ee.value)),oe.filterTaxonomies&&typeof oe.filterTaxonomies=="object"&&Ae(oe.filterTaxonomies)):Te&&(M(l.map(Ee=>Ee.value)),Z(d.map(Ee=>Ee.value)),ve(c.map(Ee=>Ee.value)),Ae({})),Array.isArray(oe.filterStatus)&&ce(oe.filterStatus),Array.isArray(oe.filterAssignees)){const Ee=oe.filterAssigneesAllSelected===!0&&!oe.filterAssignees.includes("unassigned")?["unassigned",...oe.filterAssignees]:oe.filterAssignees;Ie(Ee)}typeof oe.filterAssigneesAllSelected=="boolean"&&ge(oe.filterAssigneesAllSelected),(oe.sortBy==="created"||oe.sortBy==="priority"||oe.sortBy==="updated"||oe.sortBy==="complexity")&&Ne(oe.sortBy),(oe.sortOrder==="asc"||oe.sortOrder==="desc")&&q(oe.sortOrder),Te?K(!0):typeof oe.hasInitedFilters=="boolean"&&fe?K(oe.hasInitedFilters):Be&&fe&&K(!0),typeof oe.lastCategory=="string"&&we(oe.lastCategory),Q(typeof oe.taskforceAgentId=="string"?oe.taskforceAgentId.trim():""),se(typeof oe.taskforceAgentConversationId=="string"?oe.taskforceAgentConversationId.trim():""),ue(oe.taskforceAgentConversationByAgentId||{})},[l,c,Se,d,i,g,F,x,b,Ie,ge,M,Z,ce,Ae,ve,y,K,we,_,Ne,q,S,T,ue,se,Q,v]);o.useEffect(()=>{if(!i||!Ce.current)return;const oe=Ce.current;Ce.current=null,ke(oe.state,{skipActiveWorkspaceModule:oe.skipActiveWorkspaceModule})},[ke,i]);const Ze=o.useRef(ke);o.useEffect(()=>{Ze.current=ke},[ke]);const st=o.useCallback(async oe=>{const We=String(oe||s.current||n||"default").trim()||"default",G=`${t}:${r}:${We}`;try{const Be=await fetch(`/api/taskforce/ui-state?key=app&workspaceId=${encodeURIComponent(We)}`,{method:"GET",credentials:"include"}),Xe=Be.ok?await Be.json().catch(()=>({})):{},ze=FA(Xe?.state),qe=mb(r),Te=ze||qe?{...qe||{},...ze||{},version:Pk}:null;if(s.current!==We)return;Ze.current(Te,{skipActiveWorkspaceModule:le.current}),Me.current=G}catch{const Be=mb(r);s.current===We&&(Ze.current(Be,{skipActiveWorkspaceModule:le.current}),Me.current=G)}finally{if(s.current!==We)return;le.current=!1,pe.current=!0,ee(!0)}},[n,s,t,r]);o.useEffect(()=>{const oe=`${t}:${r}:${n}`;ne.current&&Me.current!==oe&&(ee(!1),st(n))},[n,st,t,r]),o.useEffect(()=>{if(!P)return;if(pe.current){pe.current=!1;return}const oe={version:Pk,groupBy:h,activeWorkspaceModule:p,emptyColumnMode:k,taskScope:C,openTaskId:w||null,compressedCards:E,zenMode:N,searchQuery:V,collapsedCategories:j,filterCategories:z,filterPriorities:O,filterTypes:U,filterStatus:te,filterAssignees:Le,filterAssigneesAllSelected:Ye,filterTaxonomies:he,...Se?{filterTaxonomySignature:Se}:{},sortBy:ye,sortOrder:ae,hasInitedFilters:W,lastCategory:Re||"",taskforceAgentId:ie,taskforceAgentConversationId:H,taskforceAgentConversationByAgentId:Pe};Hx(oe,r);const We=window.setTimeout(async()=>{try{await Af({stateKey:"app",workspaceId:s.current,patch:oe})}catch{}},250);return()=>window.clearTimeout(We)},[p,j,E,Se,s,k,Le,Ye,z,O,te,he,U,h,W,Re,w,V,ye,ae,C,Pe,H,ie,P,r,N]);const at=o.useCallback(oe=>{Me.current="",Ce.current=null,le.current=!1,pe.current=!1,oe?.clearLoaded&&(ne.current=!1),ee(!1)},[]);return{hasLoadedUiStateRef:ne,loadPersistedUiState:st,resetPersistedUiStateLoad:at,setActiveWorkspaceModule:_e,uiStateReady:P}}const EE="taskforce:workspace-resources-invalidated";function XC(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(EE,{detail:e}))}function NE({workspaceId:e,isOpen:t,authBlocked:r,authRequiredForApi:n,isAuthenticated:s,canCallProtectedApi:i,shouldGateProtectedApiCalls:l,authSessionResolvedRef:c,authRequiredForApiRef:d,isAuthenticatedRef:f,dataVersionRef:p,refreshTaskCollectionsForDataVersion:g,coordinatorDataVersion:h=null}){const y=o.useRef(g);y.current=g;const k=o.useRef({scopeKey:null,workspaceId:"",scopeEpoch:0,renderedVersion:null,pendingVersion:null,sourceVersions:new Map,inFlight:null}),b=o.useRef(!0);o.useEffect(()=>(b.current=!0,()=>{b.current=!1}),[]);const C=!!(h&&Number.isSafeInteger(h.coordinatorGeneration)&&h.coordinatorGeneration>0&&Number.isSafeInteger(h.localDataVersion)&&h.localDataVersion>=0),S=()=>{const T=k.current;if(!b.current||T.inFlight||T.pendingVersion===null||typeof document>"u"||document.visibilityState!=="visible")return;const E=T.pendingVersion;if(T.renderedVersion!==null&&E<=T.renderedVersion)return;const x=T.scopeKey,N=T.scopeEpoch;let v=!1,V=!1;const _=y.current().then(()=>{if(!b.current||k.current.scopeKey!==x||k.current.scopeEpoch!==N){V=!0;return}v=!0,k.current.renderedVersion=E,p.current=E,XC({workspaceId:k.current.workspaceId,source:"data-version",dataVersion:E})}).catch(()=>{}).finally(()=>{k.current.inFlight===_&&(k.current.inFlight=null),(v||V)&&S()});T.inFlight=_},w=(T,E,x)=>{if(!Number.isSafeInteger(E)||E<0)return;const N=k.current,v=e;N.scopeKey!==v&&(N.scopeKey=v,N.workspaceId=e,N.scopeEpoch+=1,N.renderedVersion=null,N.pendingVersion=null,N.sourceVersions=new Map,p.current=null);const V=N.sourceVersions.get(T);if(V!==void 0&&(x.monotonic?E<=V:E===V)){S();return}if(N.sourceVersions.set(T,E),x.establishBaseline&&V===void 0){N.renderedVersion===null&&N.pendingVersion===null&&!N.inFlight&&(N.renderedVersion=E,N.pendingVersion=E,p.current=E);return}const _=Math.max(N.renderedVersion??0,N.pendingVersion??0);N.pendingVersion=_===0?E:Math.max(_+1,E),S()};o.useEffect(()=>{!C||!h||w(`${e}:coordinator:${h.coordinatorGeneration}`,h.localDataVersion,{monotonic:!0,establishBaseline:!1})},[h,C,e]),o.useEffect(()=>{if(typeof window>"u"||typeof document>"u"||xE({isOpen:t,authBlocked:r,authRequiredForApi:n,isAuthenticated:s,canCallProtectedApi:i}))return;let T=!1;const E=async()=>{if(!(T||document.visibilityState!=="visible")&&!RE({shouldGateProtectedApiCalls:l,authSessionResolved:c.current,authRequiredForApi:d.current,isAuthenticated:f.current}))try{const _=await fetch("/api/taskforce/data-version");if(!_.ok)return;const j=await _.json(),F=Number(j?.dataVersion);if(T)return;w(`${e}:legacy`,F,{monotonic:!1,establishBaseline:!0})}catch{}},x=()=>{document.visibilityState==="visible"&&E()},N=()=>{E()},v=()=>{E()},V=window.setInterval(()=>{E()},3e3);return document.addEventListener("visibilitychange",x),window.addEventListener("focus",N),window.addEventListener("online",v),E(),()=>{T=!0,window.clearInterval(V),document.removeEventListener("visibilitychange",x),window.removeEventListener("focus",N),window.removeEventListener("online",v)}},[t,e,r,n,s,i,l,c,d,f,p])}const ME="/api/taskforce/sync/v3/local/operations",DE="/api/taskforce/sync/v3/local/dispatch";function $h(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}async function tS(e,t,r){const n=await e(t,{method:"POST",credentials:"include",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(r)});let s;try{s=JSON.parse(await n.text())}catch{s=null}return{response:n,body:$h(s)}}function On(e,t){const r=String(e||"").trim();if(!r||r.length>200)throw new Error(`${t} is invalid.`);return r}function LE(){if(!globalThis.crypto?.randomUUID)throw new Error("Secure operation ID generation is unavailable.");return globalThis.crypto.randomUUID()}function OE(e){return e===400||e===401||e===403||e===404||e===405||e===409||e===413||e===422||e===429}function Ku(e={}){const t=e.identityStore||new tw,r=e.fetchImpl||fetch,n=e.createOperationId||LE,s=e.fingerprint||rw;return{async execute(i){const l=On(i.workspaceId,"workspaceId");let c,d,f,p;try{i.preparedIdentity?(c=i.preparedIdentity.key,d={operationId:i.preparedIdentity.operationId,created:i.preparedIdentity.created},f=i.preparedIdentity.abandonIfMatches,p=i.preparedIdentity.markCaptureConfirmed):(c=await s(i.fingerprintValue),d=await t.getOrCreate(c,n),f=(v,V)=>t.deleteIfMatches(v,V),p=f)}catch{return{state:"failed",phase:"prepare",fallbackEligible:!1,errorCode:"LOCAL_OPERATION_PREPARATION_FAILED"}}const g=On(d.operationId,"operationId"),h=i.buildOperation(g),y=On(h.entityId,"entityId");let k;try{k=await tS(r,ME,{contractVersion:3,workspaceId:l,operationId:g,operation:h})}catch{return{state:"ambiguous",phase:"capture",fallbackEligible:!1,operationId:g}}if(k.response.status===404&&k.body?.success===!1&&typeof k.body.code=="string"&&i.disabledCodes.has(k.body.code))return d.created?(await f(c,g),{state:"disabled",fallbackEligible:!0,operationId:g}):{state:"ambiguous",phase:"capture",fallbackEligible:!1,operationId:g,errorCode:k.body.code};const b=$h(k.body?.task),C=$h(k.body?.deleted),S=typeof k.body?.clientId=="string"?k.body.clientId.trim():"";if(!k.response.ok||k.body?.success!==!0||k.body.contractVersion!==3||k.body.state!=="pending"||k.body.workspaceId!==l||k.body.operationId!==g||!S||(h.mutationKind==="delete"?!C||C.taskId!==y:!b||b.id!==y)){if(!k.response.ok&&OE(k.response.status)){try{await f(c,g)}catch{}return{state:"rejected",phase:"capture",fallbackEligible:!1,operationId:g,retryable:k.response.status===429,errorCode:typeof k.body?.code=="string"?k.body.code:void 0}}return{state:"ambiguous",phase:"capture",fallbackEligible:!1,operationId:g,errorCode:typeof k.body?.code=="string"?k.body.code:void 0}}try{await p(c,g)}catch{return{state:"ambiguous",phase:"capture",fallbackEligible:!1,operationId:g,errorCode:"LOCAL_OPERATION_IDENTITY_CLEANUP_FAILED"}}const w=h.mutationKind==="delete"?{deleted:C}:{task:b};if(!i.isAuthenticated)return{state:"pending",fallbackEligible:!1,operationId:g,...w,pendingReason:"auth"};if(i.dispatchEnabled===!1)return{state:"pending",fallbackEligible:!1,operationId:g,...w,pendingReason:"sync-disabled"};let T;try{T=await tS(r,DE,{workspaceId:l,limit:1})}catch{return{state:"pending",fallbackEligible:!1,operationId:g,...w,pendingReason:"retry"}}if(!T.response.ok)return{state:"pending",fallbackEligible:!1,operationId:g,...w,pendingReason:T.response.status===401?"auth":"retry",errorCode:typeof T.body?.code=="string"?T.body.code:void 0};if(T.body?.success!==!0||!Array.isArray(T.body.outcomes))return{state:"pending",fallbackEligible:!1,operationId:g,...w,pendingReason:"retry"};const E=T.body.outcomes.map($h).find(v=>v?.clientId===S&&v?.operationId===g);if(!E)return{state:"pending",fallbackEligible:!1,operationId:g,...w,pendingReason:"queued"};const x=E.disposition;if(x!=="accepted"&&x!=="retry"&&x!=="blocked"&&x!=="lease-lost")return{state:"pending",fallbackEligible:!1,operationId:g,...w,pendingReason:"retry"};const N=typeof E.errorCode=="string"?E.errorCode:void 0;return x==="accepted"?{state:"accepted",fallbackEligible:!1,operationId:g,...w,dispatchDisposition:x}:{state:x==="blocked"?"blocked":"pending",fallbackEligible:!1,operationId:g,...w,dispatchDisposition:x,pendingReason:x==="retry"||x==="lease-lost"?N==="WORKSPACE_SYNC_TRANSPORT_401"?"auth":"retry":void 0,errorCode:N}}}}const BE=new Set(["WORKSPACE_SYNC_LOCAL_CAPTURE_DISABLED"]);function WE(e={}){const t=Ku(e);return{async update(r){const n=On(r.workspaceId,"workspaceId"),s=On(r.entityId,"entityId"),i=QC(r.patch),l={domain:"task",entityId:s,mutationKind:"metadata-update",payload:{patch:i,...r.saveSource?{saveSource:r.saveSource}:{}}};return t.execute({workspaceId:n,fingerprintValue:{contractVersion:3,workspaceId:n,operation:l},buildOperation:()=>l,disabledCodes:BE,isAuthenticated:r.isAuthenticated,dispatchEnabled:r.dispatchEnabled})}}}const $E=new Set(["title","description","priority","complexity","type","category","assignee","scheduledDate","dueDate","scheduledWeekKey","orderInDay","workstreamId","taxonomies"]);function FE(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=Object.keys(e);return t.length>0&&t.every(r=>$E.has(r))}function UE(e){const t=o.useRef(null);return o.useCallback(async(r,n,s)=>{if(!e.enabled||!FE(n))return null;const i=String(e.workspaceId||"").trim(),l=String(r||"").trim();return!i||i.toLowerCase()==="default"||!l?null:(t.current||(t.current=e.client||WE()),t.current.update({workspaceId:i,entityId:l,patch:n,...s?.saveSource?{saveSource:s.saveSource}:{},isAuthenticated:e.isAuthenticated,dispatchEnabled:e.dispatchEnabled}))},[e.client,e.dispatchEnabled,e.enabled,e.isAuthenticated,e.workspaceId])}const zE=new Set(["title","description","priority","complexity","type","category","assignee","status","scheduledDate","dueDate","orderInDay","workstreamId","taxonomies"]),HE=new Set(["task","on-hold","in-progress","review","done","cancelled"]);class mh extends Error{constructor(t,r,n){super(t),this.code=r,this.statusCode=n,this.name="DurableTaskCreateMutationError"}}function GE(e){if(!e||typeof e!="object"||Array.isArray(e))throw new mh("Task create input must be an object.","TASK_CREATE_INVALID",400);const t=e;for(const n of Object.keys(t))if(!zE.has(n))throw new mh(`Task create field is not supported by this contract: ${n}`,"TASK_CREATE_INVALID",400);const r=typeof t.title=="string"?t.title.trim():"";if(!r)throw new mh("Task title is required.","TASK_CREATE_INVALID",400);if(t.status!==void 0&&!HE.has(t.status))throw new mh(`Task create status is not supported by this contract: ${String(t.status)}`,"TASK_CREATE_INVALID",400);return{...t,title:r}}const VE=new Set(["WORKSPACE_SYNC_LOCAL_CAPTURE_DISABLED","WORKSPACE_SYNC_LOCAL_CREATE_CAPTURE_DISABLED"]),KE="/api/taskforce/sync/v3/local/operations";function Ru(e){return JSON.parse(Ec(GE(e)))}function hh(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Local task create input must be an object.");const r=e,{attachments:n=[],checklistItems:s=[],comments:i=[],...l}=r;if(!Array.isArray(n)||!Array.isArray(s)||!Array.isArray(i))throw new Error("Local task create carriers must be arrays.");const c=Ru(l);if(Ec(c)!==Ec(t))throw new Error("Local task create root does not match its durable task.");return JSON.parse(Ec({...c,attachments:n,checklistItems:s,comments:i}))}function rS(e={}){const t=Ku(e),r=e.attemptStore||new JC,n=e.fetchImpl||globalThis.fetch,s=async(l,c)=>{let d,f;try{d=await n(`${KE}?workspaceId=${encodeURIComponent(l)}&operationId=${encodeURIComponent(c)}`,{method:"GET",headers:{Accept:"application/json"}}),f=await d.json()}catch{return{state:"ambiguous",phase:"capture",fallbackEligible:!1,operationId:c}}if(d.status===404&&f?.success===!1&&f?.code==="WORKSPACE_SYNC_LOCAL_OPERATION_NOT_FOUND")return null;const p=f?.operation,g=p?.payload?.task,h=p?.payload?.localCarriers;if(!d.ok||f?.success!==!0||f?.contractVersion!==3||f?.workspaceId!==l||f?.operationId!==c||p?.domain!=="task"||p?.entityId!==`task-${c}`||p?.mutationKind!=="create")return{state:"ambiguous",phase:"capture",fallbackEligible:!1,operationId:c,errorCode:typeof f?.code=="string"?f.code:void 0};try{const y=Ru(g);return{workspaceId:l,operationId:c,task:hh({...y,...h&&typeof h=="object"?h:{}},y)}}catch{return{state:"ambiguous",phase:"capture",fallbackEligible:!1,operationId:c,errorCode:"WORKSPACE_SYNC_LOCAL_REPLAY_INVALID"}}},i=async(l,c,d,f)=>{const p=await t.execute({workspaceId:l.workspaceId,preparedIdentity:{key:l.workspaceId,operationId:l.operationId,created:!1,abandonIfMatches:(g,h)=>r.abandonIfMatches(g,h),markCaptureConfirmed:(g,h)=>r.markResolved(g,h)},buildOperation:()=>{const{attachments:g,checklistItems:h,comments:y,...k}=l.task;return{domain:"task",entityId:`task-${l.operationId}`,mutationKind:"create",payload:{task:Ru(k),localCarriers:{attachments:g,checklistItems:h,comments:y}}}},disabledCodes:VE,isAuthenticated:c,dispatchEnabled:d});return f&&(p.state==="accepted"||p.state==="pending"||p.state==="blocked")?{...p,recoveredChangedInput:!0}:p};return{async recoverPending(l){const c=On(l.workspaceId,"workspaceId");let d;try{d=await r.listPending(c)}catch{return[]}const f=[];for(const p of d)f.push(await i(p,l.isAuthenticated,l.dispatchEnabled,!1));return f},async create(l){const c=On(l.workspaceId,"workspaceId"),d=Ru(l.task),f=hh(l.localTask||{...d,attachments:[],checklistItems:[],comments:[]},d),p=On(l.participantId,"participantId"),g=await s(c,p);if(g&&"state"in g)return g;if(g){const k=Ec(g.task)!==Ec(f);return i({...g},l.isAuthenticated,l.dispatchEnabled,k)}let h;try{h=await r.claim(c,p,f,()=>p)}catch{return{state:"failed",phase:"prepare",fallbackEligible:!1,errorCode:"LOCAL_OPERATION_PREPARATION_FAILED"}}try{const{attachments:k,checklistItems:b,comments:C,...S}=h.task;h={...h,task:hh({...S,attachments:k,checklistItems:b,comments:C},Ru(S))}}catch{return{state:"failed",phase:"prepare",fallbackEligible:!1,errorCode:"LOCAL_OPERATION_PREPARATION_FAILED"}}const y=!h.created&&Ec(h.task)!==Ec(f);return i(h,l.isAuthenticated,l.dispatchEnabled,y)},async resumePending(l){const c=On(l.workspaceId,"workspaceId"),d=On(l.participantId,"participantId"),f=await s(c,d);if(f&&"state"in f)return f;if(f)return i({...f},l.isAuthenticated,l.dispatchEnabled,!0);let p;try{p=await r.getForParticipant(c,d)}catch{return{state:"failed",phase:"prepare",fallbackEligible:!1,errorCode:"LOCAL_OPERATION_PREPARATION_FAILED"}}if(!p)return null;try{const{attachments:g,checklistItems:h,comments:y,...k}=p.task;p={...p,task:hh({...k,attachments:g,checklistItems:h,comments:y},Ru(k))}}catch{return{state:"failed",phase:"prepare",fallbackEligible:!1,errorCode:"LOCAL_OPERATION_PREPARATION_FAILED"}}return i(p,l.isAuthenticated,l.dispatchEnabled,!0)}}}const eI=["title","description","priority","complexity","type","category","assignee","scheduledDate","dueDate","orderInDay","workstreamId","taxonomies"],qE=new Set([...eI,"status","completedAt","workstreamId","checklistItems","comments","attachments","createdAt","createdBy"]);function YE(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;if(Object.keys(t).some(s=>!qE.has(s))||t.status!=="task"||t.completedAt!==null||!Array.isArray(t.checklistItems)||!Array.isArray(t.comments)||!Array.isArray(t.attachments)||t.createdBy!=="user")return null;const r=String(t.createdAt||"").trim();if(!Number.isFinite(Date.parse(r))||new Date(r).toISOString()!==r)return null;const n={};for(const s of eI)Object.prototype.hasOwnProperty.call(t,s)&&(n[s]=t[s]);return{task:n,localTask:{...n,checklistItems:t.checklistItems,comments:t.comments,attachments:t.attachments}}}function Xk(){if(!globalThis.crypto?.randomUUID)throw new Error("Secure task-create participant ID generation is unavailable.");return globalThis.crypto.randomUUID()}function tI(e){return`taskforce.sync.v3.task-create-participant-v2:${e}`}function ev(e,t){globalThis.sessionStorage?.setItem(tI(e),JSON.stringify(t))}function ZE(e){const t=tI(e),r=globalThis.sessionStorage?.getItem(t)?.trim();if(r)try{const s=JSON.parse(r);if(typeof s.participantId=="string"&&s.participantId.trim())return{participantId:s.participantId.trim(),draftFingerprint:typeof s.draftFingerprint=="string"?s.draftFingerprint:null}}catch{}const n={participantId:Xk(),draftFingerprint:null};return ev(e,n),n}async function JE(e){let t=ZE(e);return{get participantId(){return t.participantId},prepareForDraft(r){return t.draftFingerprint&&t.draftFingerprint!==r?t={participantId:Xk(),draftFingerprint:r}:t={...t,draftFingerprint:r},ev(e,t),t.participantId},rotate(){return t={participantId:Xk(),draftFingerprint:null},ev(e,t),t.participantId},close(){}}}async function QE(e){const{createdAt:t,updatedAt:r,...n}=e;return rw(n)}function XE(e){const t=o.useRef(null),r=o.useRef(null),n=o.useCallback(i=>(r.current?.workspaceId!==i&&(r.current?.promise.then(l=>l.close()),r.current={workspaceId:i,promise:JE(i)}),r.current.promise),[]);o.useEffect(()=>{if(!e.localRuntime)return;const i=String(e.workspaceId||"").trim();return i&&i.toLowerCase()!=="default"&&(n(i),e.enabled&&(t.current||(t.current=e.client||rS()),typeof t.current.recoverPending=="function"&&t.current.recoverPending({workspaceId:i,isAuthenticated:e.isAuthenticated,dispatchEnabled:e.dispatchEnabled}))),()=>{const l=r.current;r.current=null,l?.promise.then(c=>c.close())}},[n,e.client,e.dispatchEnabled,e.enabled,e.isAuthenticated,e.localRuntime,e.workspaceId]);const s=o.useCallback(async i=>{if(!e.localRuntime)return null;const l=String(e.workspaceId||"").trim();if(!l||l.toLowerCase()==="default")return null;t.current||(t.current=e.client||rS());const c=await n(l),d=YE(i),f=d?c.prepareForDraft(await QE(d.localTask)):c.participantId;let p;if(!e.enabled||!d){if(p=await t.current.resumePending({workspaceId:l,participantId:f,isAuthenticated:e.isAuthenticated,dispatchEnabled:e.dispatchEnabled}),!p&&!e.enabled)return null;if(!p&&e.enabled&&!d)return{state:"rejected",phase:"capture",fallbackEligible:!1,operationId:f,retryable:!1,errorCode:"TASK_CREATE_UNSUPPORTED_INPUT"}}else p=await t.current.create({workspaceId:l,participantId:f,task:d.task,localTask:d.localTask,isAuthenticated:e.isAuthenticated,dispatchEnabled:e.dispatchEnabled});return p?((p.state==="accepted"||p.state==="pending"||p.state==="blocked")&&c.rotate(),p):null},[n,e.client,e.dispatchEnabled,e.enabled,e.isAuthenticated,e.localRuntime,e.workspaceId]);return s.resetDraft=()=>{const i=String(e.workspaceId||"").trim();!i||i.toLowerCase()==="default"||n(i).then(l=>l.rotate())},s}const aS=["task","on-hold","in-progress","review","done","cancelled"];class eN extends Error{constructor(t,r,n){super(t),this.code=r,this.statusCode=n,this.name="DurableTaskStatusMutationError"}}const nS=2e3;function Ps(e){throw new eN(e,"TASK_STATUS_INVALID_PAYLOAD",400)}function tN(e){return typeof e!="string"||!aS.includes(e)?Ps(`Task status must be one of: ${aS.join(", ")}.`):e}function rN(e,t){if(e!==null&&typeof e!="string")return Ps("Task cancellation reason must be a string or null.");const r=typeof e=="string"?e.trim():null;return r!==null&&(r.length===0||r.length>nS)?Ps(`Task cancellation reason must contain 1-${nS} characters.`):t!=="cancelled"&&r!==null?Ps("Task cancellation reason must be null unless status is cancelled."):r}function aN(e){if(e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0)return{};let t;try{t=QC(e)}catch(r){if(r instanceof Wh)return Ps(r.message);throw r}return Object.prototype.hasOwnProperty.call(t,"assignee")?Ps("Task status metadataPatch cannot contain assignee; use assigneeIntent."):t}function nN(e,t){if(!e||typeof e!="object"||Array.isArray(e))return Ps("Task status assigneeIntent must be an object.");const r=e;return r.kind==="preserve"?Object.keys(r).length!==1?Ps("Preserve assignee intent must contain exactly kind."):{kind:"preserve"}:r.kind==="set"?Object.keys(r).sort().join(",")!=="kind,value"?Ps("Set assignee intent must contain exactly kind and value."):r.value!==null&&typeof r.value!="string"?Ps("Set assignee intent value must be a string or null."):{kind:"set",value:(typeof r.value=="string"?r.value.trim():"")||null}:r.kind==="claim-if-unassigned"?Object.keys(r).sort().join(",")!=="kind,value"?Ps("Claim-if-unassigned intent must contain exactly kind and value."):t!=="in-progress"?Ps("Claim-if-unassigned is valid only when status is in-progress."):typeof r.value!="string"||!r.value.trim()?Ps("Claim-if-unassigned value must be a nonblank string."):{kind:"claim-if-unassigned",value:r.value.trim()}:Ps("Task status assigneeIntent kind is invalid.")}function sN(e){if(!e||typeof e!="object"||Array.isArray(e))return Ps("Task status payload must be an object.");const t=e;if(Object.keys(t).sort().join(",")!=="assigneeIntent,canceledReason,metadataPatch,status")return Ps("Task status payload must contain exactly status, assigneeIntent, canceledReason, and metadataPatch.");const r=tN(t.status);return{status:r,assigneeIntent:nN(t.assigneeIntent,r),canceledReason:rN(t.canceledReason,r),metadataPatch:aN(t.metadataPatch)}}const oN=new Set(["WORKSPACE_SYNC_LOCAL_CAPTURE_DISABLED","WORKSPACE_SYNC_LOCAL_STATUS_CAPTURE_DISABLED"]);function iN(e={}){const t=Ku(e);return{async setStatus(r){const n=On(r.workspaceId,"workspaceId"),s=On(r.entityId,"entityId"),i=sN({status:r.status,assigneeIntent:r.assigneeIntent,canceledReason:r.canceledReason,metadataPatch:r.metadataPatch??{}}),l={domain:"task",entityId:s,mutationKind:"set-status",payload:i};return t.execute({workspaceId:n,fingerprintValue:{contractVersion:3,workspaceId:n,operation:l},buildOperation:()=>l,disabledCodes:oN,isAuthenticated:r.isAuthenticated,dispatchEnabled:r.dispatchEnabled})}}}function cN(e){const t=o.useRef(null);return o.useCallback(async(r,n)=>{if(!e.enabled)return null;const s=String(e.workspaceId||"").trim(),i=String(r||"").trim();return!s||s.toLowerCase()==="default"||!i?null:(t.current||(t.current=e.client||iN()),t.current.setStatus({workspaceId:s,entityId:i,...n,metadataPatch:n.metadataPatch,isAuthenticated:e.isAuthenticated,dispatchEnabled:e.dispatchEnabled}))},[e.client,e.dispatchEnabled,e.enabled,e.isAuthenticated,e.workspaceId])}class Au extends Error{constructor(t,r,n){super(t),this.code=r,this.statusCode=n,this.name="DurableTaskLifecycleMutationError"}}const sS=2e3;function oS(e,t){if(!t||typeof t!="object"||Array.isArray(t))throw new Au("Task lifecycle payload must be an object.","TASK_LIFECYCLE_INVALID_PAYLOAD",400);const r=t,n=Object.keys(r).sort();if(e==="unarchive"){if(n.length!==0)throw new Au("Unarchive payload must be empty.","TASK_LIFECYCLE_INVALID_PAYLOAD",400);return{cancellation:!1,reason:null}}if(n.length!==2||n[0]!=="cancellation"||n[1]!=="reason"||typeof r.cancellation!="boolean")throw new Au("Archive payload must contain exactly cancellation and reason.","TASK_LIFECYCLE_INVALID_PAYLOAD",400);if(r.reason!==null&&typeof r.reason!="string")throw new Au("Archive reason must be a string or null.","TASK_LIFECYCLE_INVALID_PAYLOAD",400);const s=typeof r.reason=="string"?r.reason.trim():null;if(s!==null&&(s.length===0||s.length>sS))throw new Au(`Archive reason must contain 1-${sS} characters.`,"TASK_LIFECYCLE_INVALID_PAYLOAD",400);if(!r.cancellation&&s!==null)throw new Au("Archive reason must be null when cancellation is false.","TASK_LIFECYCLE_INVALID_PAYLOAD",400);return{cancellation:r.cancellation,reason:s}}class gh extends Error{constructor(t,r,n){super(t),this.code=r,this.statusCode=n,this.name="DurableTaskWorkflowMutationError"}}function iS(e,t){if(!t||typeof t!="object"||Array.isArray(t))throw new gh("Task workflow payload must be an object.","TASK_WORKFLOW_INVALID_PAYLOAD",400);const r=t,n=Object.keys(r).sort();if(e==="complete"){if(n.length!==0)throw new gh("Complete payload must be empty.","TASK_WORKFLOW_INVALID_PAYLOAD",400);return{assignee:null}}if(n.length!==1||n[0]!=="assignee"||r.assignee!==null&&typeof r.assignee!="string")throw new gh("Reopen payload must contain exactly assignee as a string or null.","TASK_WORKFLOW_INVALID_PAYLOAD",400);const s=typeof r.assignee=="string"?r.assignee.trim():null;if(typeof r.assignee=="string"&&!s)throw new gh("Reopen assignee cannot be blank.","TASK_WORKFLOW_INVALID_PAYLOAD",400);return{assignee:s}}const lN=new Set(["WORKSPACE_SYNC_LOCAL_CAPTURE_DISABLED","WORKSPACE_SYNC_LOCAL_LIFECYCLE_CAPTURE_DISABLED"]);function dN(e){return e.mutationKind==="archive"?oS("archive",{cancellation:e.cancellation,reason:e.reason}):e.mutationKind==="unarchive"?(oS("unarchive",{}),{}):e.mutationKind==="complete"?(iS("complete",{}),{}):iS("reopen",{assignee:e.assignee})}function uN(e={}){const t=Ku(e),r=async n=>{const s=On(n.workspaceId,"workspaceId"),i=On(n.entityId,"entityId"),l=dN(n),c=n.mutationKind,d={domain:"task",entityId:i,mutationKind:c,payload:l};return t.execute({workspaceId:s,fingerprintValue:{contractVersion:3,workspaceId:s,operation:d},buildOperation:()=>d,disabledCodes:lN,isAuthenticated:n.isAuthenticated,dispatchEnabled:n.dispatchEnabled})};return{mutate:r,archive(n){return r({...n,mutationKind:"archive"})},unarchive(n){return r({...n,mutationKind:"unarchive"})},complete(n){return r({...n,mutationKind:"complete"})},reopen(n){return r({...n,mutationKind:"reopen"})}}}function pN(e){const t=o.useRef(null);return o.useCallback(async(r,n)=>{if(!e.enabled)return null;const s=String(e.workspaceId||"").trim(),i=String(r||"").trim();return!s||s.toLowerCase()==="default"||!i?null:(t.current||(t.current=e.client||uN()),t.current.mutate({workspaceId:s,entityId:i,isAuthenticated:e.isAuthenticated,dispatchEnabled:e.dispatchEnabled,...n}))},[e.client,e.dispatchEnabled,e.enabled,e.isAuthenticated,e.workspaceId])}const fN=new Set(["WORKSPACE_SYNC_LOCAL_CAPTURE_DISABLED","WORKSPACE_SYNC_LOCAL_DELETE_CAPTURE_DISABLED"]);function mN(e={}){const t=Ku(e);return{delete(r){const n=On(r.workspaceId,"workspaceId"),i={domain:"task",entityId:On(r.entityId,"entityId"),mutationKind:"delete",payload:{}};return t.execute({workspaceId:n,fingerprintValue:{contractVersion:3,workspaceId:n,operation:i},buildOperation:()=>i,disabledCodes:fN,isAuthenticated:r.isAuthenticated,dispatchEnabled:r.dispatchEnabled})}}}function hN(e){const t=o.useRef(null);return o.useCallback(async r=>{if(!e.enabled)return null;const n=String(e.workspaceId||"").trim(),s=String(r||"").trim();return!n||n.toLowerCase()==="default"||!s?null:(t.current||(t.current=e.client||mN()),t.current.delete({workspaceId:n,entityId:s,isAuthenticated:e.isAuthenticated,dispatchEnabled:e.dispatchEnabled}))},[e.client,e.dispatchEnabled,e.enabled,e.isAuthenticated,e.workspaceId])}const gN=new Set(["WORKSPACE_SYNC_LOCAL_CAPTURE_DISABLED","WORKSPACE_SYNC_LOCAL_DELETE_CAPTURE_DISABLED"]);function yN(e={}){const t=Ku(e);return{restore(r){const n=On(r.workspaceId,"workspaceId"),s=On(r.entityId,"entityId"),i=On(r.deletedRecordId,"deletedRecordId"),l=r.restoreDestination||"previous",c={domain:"task",entityId:s,mutationKind:"restore",payload:l==="archive"?{deletedRecordId:i,restoreDestination:l}:{deletedRecordId:i}};return t.execute({workspaceId:n,fingerprintValue:{contractVersion:3,workspaceId:n,operation:c},buildOperation:()=>c,disabledCodes:gN,isAuthenticated:r.isAuthenticated,dispatchEnabled:r.dispatchEnabled})}}}function kN(e){const t=o.useRef(null);return o.useCallback(async(r,n,s="previous")=>{if(!e.enabled)return null;const i=String(e.workspaceId||"").trim(),l=String(n||"").trim(),c=String(r||"").trim();return!i||i.toLowerCase()==="default"||!l||!c?null:(t.current||(t.current=e.client||yN()),t.current.restore({workspaceId:i,entityId:l,deletedRecordId:c,restoreDestination:s,isAuthenticated:e.isAuthenticated,dispatchEnabled:e.dispatchEnabled}))},[e.client,e.dispatchEnabled,e.enabled,e.isAuthenticated,e.workspaceId])}const rI=["active","archive","deleted","planning"];function aI(e){const t=new Set(e||[]);return rI.filter(r=>t.has(r))}function vN(e){return Array.from(new Set((e||[]).map(t=>String(t||"").trim()).filter(Boolean)))}function Id(e,t){return{collections:aI(e),taskIds:vN(t?.taskIds),ambiguous:t?.ambiguous===!0}}function nI(e,t){return e?Id([...e.collections,...t.collections],{taskIds:[...e.taskIds||[],...t.taskIds||[]],ambiguous:e.ambiguous||t.ambiguous}):Id(t.collections,{taskIds:t.taskIds,ambiguous:t.ambiguous})}function wN(e){return e.ambiguous?[]:[...e.taskIds||[]]}function bN(e,t){if(e==="taskforce:update"||e==="taskforce:replay-gap"||e==="taskforce:replay-reset"||!t?.length)return Id(rI,{ambiguous:!0});let r=null;for(const n of t){const s=String(n.entityType||"").trim(),i=aI(n.affectedCollections);let l;i.length>0?l=i:s==="task"?l=String(n.changeType||"").trim()==="delete"?["active","archive","deleted"]:["active","archive","deleted","planning"]:s==="taxonomy"?l=["active","archive","planning"]:s==="initiative"||s==="workstream"?l=["planning"]:l=[],r=nI(r,Id(l,{taskIds:n.entityIds}))}return r||Id([])}class SN{values=new Map;async getOrCreate(t,r){const n=this.values.get(t);if(n)return{operationId:n,created:!1};const s=r();return this.values.set(t,s),{operationId:s,created:!0}}async deleteIfMatches(t,r){this.values.get(t)===r&&this.values.delete(t)}}class AN{values=new Map;async claim(t,r,n){const s=this.values.get(t);if(s)return{...s,created:!1};const i={fingerprint:t,operationId:n(),workstream:r};return this.values.set(t,i),{...i,created:!0}}async deleteIfMatches(t,r){this.values.get(t)?.operationId===r&&this.values.delete(t)}}const CN=new Set(["WORKSTREAM_MUTATION_INVALID","WORKSTREAM_MUTATION_IDENTITY_REQUIRED","WORKSTREAM_NOT_FOUND","WORKSTREAM_ID_CONFLICT","WORKSTREAM_STATE_CONFLICT","WORKSTREAM_INITIATIVE_INVALID","WORKSTREAM_OWNER_INVALID","WORKSTREAM_COMMENT_AUTHOR_INVALID","WORKSTREAM_ATTACHMENT_INVALID","WORKSTREAM_HAS_ACTIVE_TASKS","WORKSTREAM_TASK_ORDER_INVALID","WORKSTREAM_TASK_ORDER_MEMBERSHIP_MISMATCH","WORKSTREAM_TASK_ORDER_IDENTITY_CONFLICT","ENTITY_EVENT_IDENTITY_COLLISION","WORKSPACE_SYNC_REVISION_CONFLICT","WORKSPACE_SYNC_IDEMPOTENCY_CONFLICT"]);function IN(e,t){return e.find(n=>n.id===t.id)?null:t}function cS(){if(!globalThis.crypto?.randomUUID)throw new Error("Secure workstream operation identity generation is unavailable.");return`operation-${globalThis.crypto.randomUUID()}`}async function nf(e){if(e.ok||e.status<400||e.status>=500)return!1;const t=await e.clone().json().catch(()=>null);return CN.has(String(t?.code||"").trim())}function _N(e){const t=globalThis.indexedDB?new tw:new SN,r=globalThis.indexedDB?new pE:new AN;return{async prepareCreate(n,s){if(!globalThis.crypto?.randomUUID)throw new Error("Secure workstream identity generation is unavailable.");const i=$a({workspaceId:n,candidate:s}),l=await r.claim(i,{...s,id:s.id||`workstream-${globalThis.crypto.randomUUID()}`,createdAt:s.createdAt||new Date().toISOString()},cS);return{fingerprint:i,operationId:l.operationId,body:l.workstream}},confirmCreate(n,s){return r.deleteIfMatches(n,s)},abandonCreate(n,s){return r.deleteIfMatches(n,s)},async prepareMutation(n,s,i,l=null){const c=$a({workspaceId:n,url:s,body:i,observedState:l}),d=await t.getOrCreate(c,cS);return{fingerprint:c,operationId:d.operationId}},confirmMutation(n,s){return t.deleteIfMatches(n,s)},abandonMutation(n,s){return t.deleteIfMatches(n,s)}}}async function sf(e,t,r){const n={...t,headers:{...t.headers||{},"x-taskforce-operation-id":r}},s=()=>fetch(e,n);let i;try{i=await s()}catch{i=await s()}if(i.status!==409)return i;const l=await i.clone().json().catch(()=>({}));if(l?.code!=="WORKSPACE_SYNC_OPERATION_IN_PROGRESS")return i;const c=Date.parse(String(l?.retryAt||"")),d=Number.isFinite(c)?Math.max(0,c-Date.now()):Number.NaN;return!Number.isFinite(d)||d>2e3?i:(await new Promise(f=>setTimeout(f,d)),s())}const TN={};function Jo(e,t){const r=e.findIndex(n=>n.id===t.id);return r===-1?[...e,t]:e.map((n,s)=>s===r?t:n)}function lk(){return{status:"loading",error:null,isRefreshing:!1,collections:{initiatives:"loading",workstreams:"loading"}}}const jc=Ev(TN),dk=(()=>{const e=jc.baseUrl,t=jc.cloudAuthBaseUrl;if(t)return t;const r=jc.apiBaseUrl;return r||e||"https://app.taskforcehq.ai"})(),yh=2e4,xN=new Set(["external-abort","superseded","workspace-reset","workspace-transition"]);function Fh(e){return typeof DOMException<"u"&&e instanceof DOMException?e.name==="AbortError":String(e?.name||"").toLowerCase()==="aborterror"}function tv(e){return typeof e=="string"&&xN.has(e)}function uk(e,t){return t.aborted?e===t.reason||tv(e)||tv(t.reason)?!0:Fh(e):!1}function lS(e){const t=new Error(`Startup checks timed out after ${e}ms.`);return t.name="BootstrapTimeoutError",t}function dS(e){const t=e&&typeof e=="object"?e:{},r=Array.isArray(t.initiatives)?t.initiatives.filter(i=>!!(i&&typeof i=="object"&&typeof i.id=="string")):[],n=Array.isArray(t.workstreams)?t.workstreams.filter(i=>!!(i&&typeof i=="object"&&typeof i.id=="string")):[],s=Array.isArray(t.workstreamTaskSummaries)?t.workstreamTaskSummaries.flatMap(i=>{if(!i||typeof i!="object")return[];const l=String(i.workstreamId||"").trim();if(!l)return[];const c=Array.isArray(i.tasks)?i.tasks:[],d=Math.max(0,Number(i.taskCount)||0),f=Math.max(0,Number(i.completedTaskCount)||0);return[{workstreamId:l,taskCount:d,completedTaskCount:f,tasks:c.filter(p=>!!(p&&typeof p=="object"&&typeof p.id=="string")).map(p=>({id:String(p.id||"").trim(),referenceNumber:typeof p.referenceNumber=="number"?p.referenceNumber:null,localReferenceNumber:typeof p.localReferenceNumber=="number"?p.localReferenceNumber:null,referenceLabel:typeof p.referenceLabel=="string"&&p.referenceLabel.trim()||void 0,title:String(p.title||"").trim()||"Untitled Task",status:typeof p.status=="string"?p.status:null,assignee:typeof p.assignee=="string"?p.assignee:null,attachmentCount:Math.max(0,Number(p.attachmentCount)||0),isArchived:!!p.isArchived}))}]}):[];return{initiatives:r,workstreams:n,workstreamTaskSummaries:s}}function RN({config:e={},initialTaskId:t,initialActivityEntryId:r,requestedWorkspaceId:n,onTaskCountChange:s,onClose:i}){const l={...z0,...e},{categories:c,types:d,apiEndpoint:f,apiBaseUrl:p,cloudAuthBaseUrl:g,cloudMcpBaseUrl:h,wsBaseUrl:y,shortcut:k}=l,b=typeof window<"u"?String(window.location.hostname||"").trim().toLowerCase():"",C=b==="localhost"||b==="127.0.0.1"||b==="::1",S=typeof window<"u"&&!C,[w,T]=o.useState({cloudEnvironment:"",cloudBaseUrl:"",cloudMcpBaseUrl:"",baseUrl:"",apiBaseUrl:"",cloudAuthBaseUrl:"",wsBaseUrl:"",cloudAuthViaLocalProxy:!1,authSource:"",workspaceMode:"",workspaceSwitchingEnabled:null,syncV3TaskMetadataActivation:!1,syncV3TaskCreateActivation:!1,syncV3TaskStatusActivation:!1,syncV3TaskDeleteActivation:!1,syncV3TaskCloudHttpRootActivation:!1,syncV3LocalOutboxDispatch:!1,localCoordinatorBrowserAuthorityGate:!1,syncV3InitiativeFeedActivation:void 0,syncV3CombinedFeedRouteAvailable:void 0,syncV3CombinedFeedActivation:void 0,syncV3CombinedFeedCoverage:void 0}),[E,x]=o.useState(!1),N=o.useCallback(I=>typeof I=="string"?I.trim().replace(/\/+$/,""):"",[]);o.useEffect(()=>{if(typeof window>"u"){x(!0);return}let I=!1;return(async()=>{try{const X=await fetch("/api/taskforce/auth/runtime-config",{method:"GET",credentials:"include",cache:"no-store"});if(!X.ok)return;const re=await X.json().catch(()=>({})),J=re?.config&&typeof re.config=="object"?re.config:{};if(I)return;const et=String(J.runtimeMode||"").trim().toLowerCase()==="cloud"?"cloud":"local",tt=String(J.workspaceMode||"").trim(),Gt=tt==="single-local"||tt==="multi-cloud"?tt:et==="cloud"?"multi-cloud":"single-local";Re(et);const cr=yl(J.syncV3?.combinedFeed?.coverage||{});T({cloudEnvironment:typeof J.cloudEnvironment=="string"?String(J.cloudEnvironment).trim().toLowerCase():"",cloudBaseUrl:N(J.cloudBaseUrl),cloudMcpBaseUrl:N(J.cloudMcpBaseUrl),baseUrl:N(J.baseUrl),apiBaseUrl:N(J.apiBaseUrl),cloudAuthBaseUrl:N(J.cloudAuthBaseUrl),wsBaseUrl:N(J.wsBaseUrl),cloudAuthViaLocalProxy:!!J.cloudAuthViaLocalProxy,authSource:"cloud",workspaceMode:Gt,workspaceSwitchingEnabled:typeof J.workspaceSwitchingEnabled=="boolean"?!!J.workspaceSwitchingEnabled:Gt==="multi-cloud",syncV3TaskMetadataActivation:J.syncV3?.taskMetadataActivation===!0,syncV3TaskCreateActivation:J.syncV3?.taskCreateActivation===!0,syncV3TaskStatusActivation:J.syncV3?.taskStatusActivation===!0,syncV3TaskDeleteActivation:J.syncV3?.taskDeleteActivation===!0,syncV3TaskCloudHttpRootActivation:J.syncV3?.taskCloudHttpRootActivation===!0,syncV3LocalOutboxDispatch:J.syncV3?.localOutboxDispatch===!0,localCoordinatorBrowserAuthorityGate:J.syncV3?.localCoordinatorBrowserAuthorityGate===!0,syncV3InitiativeFeedActivation:typeof J.syncV3?.initiativeFeedActivation=="boolean"?J.syncV3.initiativeFeedActivation:void 0,syncV3CombinedFeedRouteAvailable:typeof J.syncV3?.combinedFeed?.routeAvailable=="boolean"?J.syncV3.combinedFeed.routeAvailable:void 0,syncV3CombinedFeedActivation:typeof J.syncV3?.combinedFeed?.activationReady=="boolean"?J.syncV3.combinedFeed.activationReady:void 0,syncV3CombinedFeedCoverage:cr?.coverage})}catch{}finally{I||x(!0)}})(),()=>{I=!0}},[N]);const v=typeof window>"u"?"":C?dk:"",V=N(jc.baseUrl),_=N(jc.apiBaseUrl),j=N(jc.cloudBaseUrl),F=N(jc.cloudMcpBaseUrl),z=N(jc.cloudAuthBaseUrl),M=N(jc.wsBaseUrl),O=N(p),Z=N(g),U=N(h),ve=w.apiBaseUrl||w.baseUrl,ce=O||ve||(C?"":_||V)||"",Le=Z||z||V,Ie=w.cloudAuthBaseUrl||w.baseUrl,ge=((C?Ie||Le:Le||Ie)||ce||v).trim().replace(/\/+$/,""),he=N(Ax(w.cloudMcpBaseUrl||w.cloudAuthBaseUrl||w.cloudBaseUrl||U||Z||F||z||j||ge)),Ae=(w.cloudMcpBaseUrl||U||he||w.cloudBaseUrl||F||j||ge||v).trim().replace(/\/+$/,""),ye=!S&&!!ge&&!ce,Ne=S||E&&!!(ge||ce),ae=Ne&&!ye,q=!!(ge||ce||S),W=S?"cloud":"local",[K,Re]=o.useState(()=>W),we=W==="local"&&C&&q?Dv():"",ie=we.length>0,Q=o.useCallback(I=>!I||/^https?:\/\//i.test(I)||!ce||!I.startsWith("/")?I:`${ce}${I}`,[ce]),H=o.useCallback(I=>{if(!I||/^https?:\/\//i.test(I)||!I.startsWith("/"))return I;const X=I.startsWith("/api/taskforce/auth/")||I.startsWith("/api/taskforce/account/")||I.startsWith("/api/taskforce/billing/")||I.startsWith("/api/taskforce/sync/")||I.startsWith("/api/taskforce/settings/mcp/");if(!S&&X&&(K==="cloud"||!E||w.cloudAuthViaLocalProxy||w.workspaceMode==="multi-cloud"))return I;const re=ge||ce;if(re){const J=`${re}${I}`;if(typeof window<"u"&&!S&&X)try{if(new URL(J,window.location.origin).origin===window.location.origin)return`${dk}${I}`}catch{return`${dk}${I}`}return J}return I},[E,w.cloudAuthViaLocalProxy,w.workspaceMode,ge,ce,S,K]),se=o.useCallback(I=>{const X=String(I||"").trim()||"/taskforce-ws",re=X.startsWith("/")?X:`/${X}`,J=String(y||w.wsBaseUrl||M||ce||"").trim().replace(/\/+$/,""),Fe=typeof window<"u"?window.location.origin:"",et=J||Fe;if(!et)return"";try{const tt=new URL(re,et);return tt.protocol==="https:"&&(tt.protocol="wss:"),tt.protocol==="http:"&&(tt.protocol="ws:"),tt.toString()}catch{return""}},[y,w.wsBaseUrl,M,ce]),[Pe,ue]=o.useState("tasks"),[ne,Me]=o.useState(!1),[pe,le]=o.useState(!1),[Ce,P]=o.useState("open"),[ee,Se]=o.useState(!1),[_e,ke]=o.useState(Pu(l.theme)||Kh),[Ze,st]=o.useState(Pu(l.theme)||Kh),[at,oe]=o.useState(!0),[We]=o.useState(".taskforce"),G=!1,[Be,Xe]=o.useState(!1),[ze,qe]=o.useState([]),[Te,fe]=o.useState([]),[Ee,$e]=o.useState(""),[rt,kt]=o.useState(null),[xe,St]=o.useState(null),[jt,$]=o.useState(""),[Ke,Qe]=o.useState(""),Ge=o.useMemo(()=>gx({projectRoot:jt,runtimeMode:W}),[jt,W]),[At,Nt]=o.useState(""),[Bt,Qt]=o.useState(""),Xt=wx(K),nt=w.workspaceMode==="single-local"||w.workspaceMode==="multi-cloud"?w.workspaceMode:Xt.workspaceMode,Mt=typeof w.workspaceSwitchingEnabled=="boolean"?w.workspaceSwitchingEnabled:Xt.workspaceSwitchingEnabled,[ur,je]=o.useState(!1),[ot,pt]=o.useState(!1),[Ve,lt]=o.useState(ie),[It,wt]=o.useState(ie?we:"anonymous"),[$t,Yt]=o.useState(""),[qt,er]=o.useState(""),[_t,Dt]=o.useState(""),[Tt,Xr]=o.useState([]),[Rr,la]=o.useState(""),[sa,ea]=o.useState(!0),[Ur,Ft]=o.useState(null),[ft,Rt]=o.useState(()=>{if(W==="local")return"default";const I=Nk(Ge);return I&&I.toLowerCase()!=="default"?I:"default"}),_r=o.useMemo(()=>yx({projectRoot:jt,runtimeMode:K,workspaceId:ft}),[jt,K,ft]),[u,Pt]=o.useState([]),[pr,Yr]=o.useState(()=>gl()),[tr,$r]=o.useState(!1),[Lt,zr]=o.useState(ie),[Ir,Kt]=o.useState("idle"),[Jr,Br]=o.useState(null),[nr,Zr]=o.useState(null),He=o.useRef(null),Ca=o.useRef(0),da=o.useRef(0),ir=o.useRef(ie),ut=o.useRef(ft),ka=o.useRef(null),Wt=o.useRef(0),rr=o.useRef((typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`).replace(/[^A-Za-z0-9_-]+/g,"").slice(0,12)||"session"),[oa,Mr]=o.useState(0),vn=o.useRef(null),En=o.useRef(null),Ga=o.useRef(null),Hr=o.useRef(null),Na=o.useRef(null),ta=o.useRef(null),ua=o.useRef(null),Qr=o.useCallback((I,X)=>{const re=String(I||"").trim();if(!re)return;const J=String(ut.current||"").trim();!X?.skipTransitionReset&&J&&J!==re&&(Wt.current+=1,Mr(Wt.current)),ut.current=re,X?.clearExplicitSelection!==!1&&(ka.current=null),Rt(re)},[]);o.useEffect(()=>{ut.current=ft},[ft]);const br=o.useCallback(I=>{const X=String(I||"").trim();X&&Rt(()=>{const re=String(ka.current||"").trim();let J=X;return re&&re!==X&&(J=re),ut.current=J,J})},[]),yr=o.useCallback(()=>({workspaceId:String(ut.current||"default").trim()||"default",epoch:Wt.current}),[]),Gr=o.useCallback(()=>ut.current,[]),Kr=o.useCallback(I=>(String(ut.current||"default").trim()||"default")!==I.workspaceId||Wt.current!==I.epoch,[]),dt=o.useCallback(I=>Wt.current!==I.epoch,[]),Ma=o.useCallback(I=>Fh(I)||tv(I),[]),Zt=o.useCallback(()=>{[vn,En,Ga,Hr,Na,ta].forEach(I=>{I.current?.abort("workspace-transition"),I.current=null}),ua.current!==null&&typeof window<"u"&&(window.clearTimeout(ua.current),ua.current=null),Di.current=null},[]),Sr=o.useMemo(()=>TE({shouldGateProtectedApiCalls:ae,runtimeMode:K,authSessionResolved:Lt,authRequiredForApi:ur,isAuthenticated:Ve}),[ae,K,Lt,ur,Ve]),va=Sr.shouldDeferProtectedApiCalls,Ya=Sr.shouldBlockProtectedApiCalls,[Ar,ma]=o.useState(null),[me,it]=o.useState(null),[mt,ht]=o.useState(!1),[Ht,sr]=o.useState("unknown"),[wa,fr]=o.useState(null),[or,Tr]=o.useState(l.shortcut||"Alt+T"),[ha,ba]=o.useState(l.priorities||[]),[nn,kr]=o.useState(""),[ho,wn]=o.useState(!1),[Bn,Wn]=o.useState(!1),[Ta,Ms]=o.useState(!0),[Vs,Ks]=o.useState(()=>fx()),ys=o.useMemo(()=>px(),[]),[$n,Ia]=o.useState(()=>{try{return(Intl.DateTimeFormat().resolvedOptions().locale||"").toLowerCase().startsWith("en-us")?"sunday":"monday"}catch{return"monday"}}),[fn,xa]=o.useState(!1),[ks,sn]=o.useState(!0),[mn,on]=o.useState(!1),[Zn,Da]=o.useState(""),[qs,vt]=o.useState(null);AE({currentWorkspaceIdRef:ut,resolveApiUrl:Q,runtimeMode:K});const{initiativeTemplates:hr,fetchInitiativeTemplates:ga}=F2({shouldDeferProtectedApiCalls:va,shouldBlockProtectedApiCalls:Ya}),{zenMode:ia,setZenModeState:Za,toggleZenMode:Ys}=U2(),[ca,vs]=o.useState(!1),[Fa,Jn]=o.useState(null),{uiNotice:La,pushNotice:vr,clearNotice:Ja}=O2(),Qn=o.useRef(La);Qn.current=La;const[cn,bn]=o.useState([]),Ra=o.useRef(null),[Zs,Xn]=o.useState(0),es=o.useCallback(I=>!I||!jt?I:I.startsWith(jt)?I.slice(jt.length).replace(/^[/\\]+/,""):I,[jt]),[pa,Sn]=o.useState([]),[ln,An]=o.useState([]),[ws,Oa]=o.useState([]),[Va,de]=o.useState([]),[yt,ar]=o.useState([]),[gr,Pr]=o.useState(lk),[ra,Fn]=o.useState([]),[Qa,Ai]=o.useState(null),[Cn,si]=o.useState(null),[Nn,bs]=o.useState(()=>new Set),Oo=o.useRef(null),Vt=o.useRef(null),[Sa,hn]=o.useState(!1),[aa,Ds]=o.useState(null),[Mn,Ls]=o.useState(null),Ss=o.useCallback(I=>{String(t||"").trim()||Ls(I)},[t]),[go,ts]=o.useState(!1),[rs,Un]=o.useState([]),[na,Js]=o.useState(!1),[yo,Bo]=o.useState({}),oi=o.useRef({authSessionResolved:!1,configLoaded:!1,workspaceBootstrapPending:!1});o.useEffect(()=>{oi.current={authSessionResolved:Lt,configLoaded:na,workspaceBootstrapPending:tr}},[Lt,na,tr]);const ii=o.useCallback(I=>{Kt(I),I!=="ready"&&(Br(null),Zr(Date.now()))},[]),as=o.useCallback(I=>{const X=oi.current;X.authSessionResolved&&X.configLoaded&&!X.workspaceBootstrapPending||(Kt("stalled"),Br(I),Zr(re=>re??Date.now()))},[]),Ka=o.useCallback(async(I,X,re=kf,J)=>{const Fe=new AbortController,et=J?.signal,tt=Number(re)>0?Number(re):kf,Gt=yr(),cr=I.startsWith("/api/taskforce/")?Qy(X,ub({workspaceId:Gt.workspaceId,epoch:Gt.epoch,seed:rr.current})):X,Dr=typeof window<"u"?window.setTimeout(()=>Fe.abort("bootstrap-timeout"),tt):null,Wr=()=>{Fe.abort(et?.reason||"external-abort")};et&&(et.aborted?Wr():et.addEventListener("abort",Wr,{once:!0}));try{return await fetch(I,{...cr||{},signal:Fe.signal})}catch(Er){throw et?.aborted&&uk(Er,et)?et.reason||Er:Fh(Er)||Er==="bootstrap-timeout"?lS(tt):Er}finally{et&&et.removeEventListener("abort",Wr),Dr!==null&&typeof window<"u"&&window.clearTimeout(Dr)}},[yr]),In=o.useMemo(()=>{const I=!Lt,X=Ir==="stalled",re=Lt&&(!na||tr||X);let J="Checking account, workspace access, and setup status...";return Ir==="auth"?J="Verifying session...":Ir==="workspace"?J="Resolving workspace access...":Ir==="config"&&(J="Loading configuration..."),{phase:Ir,auth:{resolved:Lt,pending:I},config:{loaded:na},workspace:{pending:tr},pending:I||re,authPending:I,appPending:re,ready:Lt&&na&&!tr&&Ir==="ready",stalled:X,subtitle:J,error:Jr,startedAt:nr}},[Lt,Jr,Ir,nr,na,tr]),Ci=o.useCallback(I=>String(I?.name||"")==="BootstrapTimeoutError",[]),[As,Ii]=o.useState([]),[_n,Wo]=o.useState({}),[_a,Cs]=o.useState(l.taxonomies||[]),jr=o.useMemo(()=>(rs.length>0?rs:c||[]).map(X=>typeof X=="string"?{value:X.toLowerCase().replace(/\s+/g,"-"),label:X}:X).sort((X,re)=>X.label.localeCompare(re.label)),[rs,c]),nc=o.useMemo(()=>({categories:jr,types:As,priorities:ha,taxonomies:_a,displayLabels:_n}),[jr,As,ha,_a,_n]);o.useMemo(()=>jr.filter(I=>!I.disabled),[jr]);const Xa=o.useCallback(I=>I.find(re=>re.value==="default"||re.value==="general"||re.label==="General"||re.value==="Taskforce"||re.label==="Taskforce")?.value||I[0]?.value||"default",[]),dn=As.length>0?As:d,[Is,Md]=o.useState(!1),[kl,Tn]=o.useState(""),_i=o.useCallback(()=>Tn(""),[]),zn="Authentication required. Sign in to continue.",[_s,Qs]=o.useState(!1),[ko,$o]=o.useState(!1),ns=o.useCallback(()=>{pt(K==="cloud"),lt(!1),er(""),Dt(""),la(""),Tn(zn)},[zn,K]),{recentlyChangedTaskIds:ci,fetchTasks:li,fetchArchive:vo,refreshTaskCollections:sc,refreshTaskCollectionsFromInvalidation:vl,mergeTaskFromServer:Dc}=z2({tasks:pa,archivedTasks:ln,setTasks:Sn,setArchivedTasks:An,setLoadingTasks:hn,getCurrentWorkspaceId:Gr,workspaceResetKey:`${ft}:${oa}`,shouldDeferProtectedApiCalls:va,shouldBlockProtectedApiCalls:Ya,handleUnauthorized:ns,authRequiredForApi:ur});o.useEffect(()=>{oa!==0&&(Di.current=null,Hl.current="",Gl.current="",Kc.current="",yc.current="",Mi.current="",Qs(!1),Yr(gl()),$o(!1),Fn([]),Ai(null),si(null),bs(new Set),Oo.current=null,Vt.current=null,Sn([]),An([]),Oa([]),de([]),ar([]),Pr(lk()),Ls(null),hn(!1))},[An,hn,Sn,oa]);const ss=o.useCallback(async(I=!1,X)=>{if(!(X?.ignoreAuthGuard===!0)&&(va||Ya))return!1;I||hn(!0);const J=yr();Na.current?.abort("superseded");const Fe=new AbortController;Na.current=Fe;try{let et=await fetch("/api/taskforce/deleted",{signal:Fe.signal});if(et.status===404&&(et=await fetch("/api/taskforce/trash",{signal:Fe.signal})),et.status===401)return ns(),Fn([]),!1;if(et.status===404)return Kr(J)?!1:(Fn([]),si(J.workspaceId),!0);if(et.ok){const tt=await et.json();if(Kr(J))return!1;const Gt=Array.isArray(tt?.deleted)?tt.deleted.map(cr=>{const Dr=cr?.taskSnapshot&&typeof cr.taskSnapshot=="object"?No(cr.taskSnapshot):null;return Dr?{...cr,taskSnapshot:Dr}:null}).filter(cr=>!!cr):[];return Fn(Gt),si(J.workspaceId),!0}return!1}catch(et){return uk(et,Fe.signal)||Ma(et)||console.error("[Taskforce] Failed to fetch deleted tasks:",et),!1}finally{Na.current===Fe&&(Na.current=null),I||hn(!1)}},[yr,ns,Ma,Kr,va,Ya]),Vr=o.useCallback(async I=>{if(!(I?.ignoreAuthGuard===!0)&&(va||Ya))return;const re=yr();ta.current?.abort("superseded"),ua.current!==null&&typeof window<"u"&&(window.clearTimeout(ua.current),ua.current=null);const J=new AbortController;ta.current=J,Pr(Fe=>({...Fe,isRefreshing:!0}));try{const Fe=ub({workspaceId:re.workspaceId,epoch:re.epoch,seed:rr.current}),et=async Er=>{if(typeof window>"u")return fetch(Er,Qy({signal:J.signal},Fe));const Ua=new AbortController,Rs=window.setTimeout(()=>Ua.abort("planning-timeout"),yh),gn=()=>Ua.abort(J.signal.reason||"external-abort");J.signal.aborted?gn():J.signal.addEventListener("abort",gn,{once:!0});try{return await fetch(Er,Qy({signal:Ua.signal},Fe))}catch(zs){if(J.signal.aborted)throw J.signal.reason||zs;if(Fh(zs)||zs==="planning-timeout")return null;throw zs}finally{window.clearTimeout(Rs),J.signal.removeEventListener("abort",gn)}};let tt=null,Gt={initiatives:"ready",workstreams:"ready"};const cr=await et("/api/taskforce/planning/bootstrap");if(cr?.status===401){ns(),Oa([]),de([]),ar([]),Pr({status:"error",error:"Sign in again to load Planning.",isRefreshing:!1,collections:{initiatives:"error",workstreams:"error"}});return}if(cr===null)throw lS(yh);if(cr.ok){const Er=await cr.json().catch(()=>null);if(!Er||!Array.isArray(Er.initiatives)||!Array.isArray(Er.workstreams))throw new Error("Planning returned an incomplete response.");tt=dS(Er)}else{const[Er,Ua]=await Promise.all([et("/api/taskforce/initiatives"),et("/api/taskforce/workstreams")]);if(!Er||!Ua)throw new Error("Planning endpoints timed out during startup.");if(Er.status===401||Ua.status===401){ns(),Oa([]),de([]),ar([]),Pr({status:"error",error:"Sign in again to load Planning.",isRefreshing:!1,collections:{initiatives:"error",workstreams:"error"}});return}const Rs=async(zp,Yo)=>{if(!zp.ok)return{items:[],status:"error"};const Zo=await zp.json().catch(()=>null),Km=Array.isArray(Zo)?Zo:Zo&&typeof Zo=="object"&&Array.isArray(Zo[Yo])?Zo[Yo]:null;return Km?{items:Km,status:"ready"}:{items:[],status:"error"}},[gn,zs]=await Promise.all([Rs(Er,"initiatives"),Rs(Ua,"workstreams")]);if(Gt={initiatives:gn.status,workstreams:zs.status},Gt.initiatives==="error"&&Gt.workstreams==="error")throw new Error("Planning could not be loaded.");tt=dS({initiatives:gn.items,workstreams:zs.items,workstreamTaskSummaries:[]})}if(Kr(re))return;Oa(tt.initiatives),de(tt.workstreams),ar(tt.workstreamTaskSummaries);const Dr=Gt.initiatives==="error"||Gt.workstreams==="error",Wr=tt.initiatives.length===0&&tt.workstreams.length===0;Pr({status:Dr?"partial":Wr?"empty":"ready",error:Dr?"Some planning data could not be loaded.":null,isRefreshing:!1,collections:Gt})}catch(Fe){if(uk(Fe,J.signal)||Ma(Fe))return;if(Ci(Fe)?(wr("planning_bootstrap_timeout",{workspaceId:re.workspaceId,epoch:re.epoch,timeoutMs:yh}),console.warn("[Taskforce] Planning bootstrap timed out during startup; retrying in background.")):console.error("[Taskforce] Failed to fetch planning entities:",Fe),!Kr(re)){const tt=ws.length>0||Va.length>0;Pr(Gt=>({status:tt?"partial":"error",error:Fe instanceof Error&&Fe.message?Fe.message:"Planning could not be loaded.",isRefreshing:!1,collections:tt?Gt.collections:{initiatives:"error",workstreams:"error"}}))}typeof window<"u"&&!Kr(re)&&ws.length===0&&Va.length===0&&(ua.current=window.setTimeout(()=>{ua.current=null,Vr(I)},3e3))}finally{ta.current===J&&(ta.current=null)}},[kf,yh,ws.length,yr,ns,Ma,Kr,va,Ya,Va.length]),Dd=o.useCallback(async(I,X)=>{const re=String(X||"").trim();if(!re)throw new Error(`Cannot load ${I} details without an id.`);const J=yr(),Fe=await fetch(`/api/taskforce/${I}/${encodeURIComponent(re)}`),et=await Fe.json().catch(()=>({}));if(!Fe.ok)throw new Error(et?.error||`Failed to load ${I} details (${Fe.status})`);const tt=et;return Kr(J)||(I==="initiative"?Oa(Gt=>Jo(Gt,tt)):de(Gt=>Jo(Gt,tt))),tt},[yr,Kr]),Dn=o.useCallback(async(I=!1,X)=>{await li(I,X)},[li]),Os=o.useCallback(async(I=!1,X)=>{const re=String(ut.current||"default").trim()||"default",J=await vo(I,X),Fe=String(ut.current||"default").trim()||"default";return J&&Fe===re&&Ai(re),J},[vo]),Ts=o.useCallback((I=!0,X)=>{const re=String(ut.current||"default").trim()||"default";if(Qa===re)return Promise.resolve(!0);const J=Oo.current;if(J?.workspaceId===re)return J.promise;const Fe=Os(I,X).finally(()=>{Oo.current?.promise===Fe&&(Oo.current=null)});return Oo.current={workspaceId:re,promise:Fe},Fe},[Qa,Os]),wo=o.useCallback((I=!0,X)=>{const re=String(ut.current||"default").trim()||"default";if(Cn===re)return Promise.resolve(!0);const J=Vt.current;if(J?.workspaceId===re)return J.promise;const Fe=ss(I,X).finally(()=>{Vt.current?.promise===Fe&&(Vt.current=null)});return Vt.current={workspaceId:re,promise:Fe},Fe},[Cn,ss]),wl=o.useCallback(()=>{const I=String(ut.current||"default").trim()||"default";return Qa!==I?Promise.resolve(!1):Os(!0)},[Qa,Os]),bl=o.useCallback((I=!0)=>{const X=String(ut.current||"default").trim()||"default";return Cn!==X?Promise.resolve(!1):ss(I)},[Cn,ss]),D=o.useCallback(async I=>{const X=I?.isSilent!==!1,re=I?.ignoreAuthGuard===!0,J=String(ut.current||"default").trim()||"default",Fe=Qa===J,et=Cn===J;await Promise.all([sc({isSilent:X,ignoreAuthGuard:re,includeArchive:Fe,highlightChangedTaskIds:I?.highlightChangedTaskIds}),et?ss(X,{ignoreAuthGuard:re}):Promise.resolve(!1),Vr({ignoreAuthGuard:re})])},[Qa,Cn,ss,Vr,sc]),L=o.useRef(!1),Ct=o.useRef(null),zt=o.useRef(Qa),xt=o.useRef(Cn),Oe=o.useRef(vl),ya=o.useRef(ss),Jt=o.useRef(Vr);zt.current=Qa,xt.current=Cn,Oe.current=vl,ya.current=ss,Jt.current=Vr;const Aa=o.useCallback(async I=>{const X=String(ut.current||"default").trim()||"default",re=Ct.current;if(Ct.current={workspaceId:X,scope:re?.workspaceId===X?nI(re.scope,I):I},!L.current){L.current=!0;try{for(;Ct.current;){const J=Ct.current;Ct.current=null;const Fe=String(ut.current||"default").trim()||"default";if(J.workspaceId!==Fe)continue;const et=new Set(J.scope.collections),tt=et.has("active"),Gt=et.has("archive")&&zt.current===Fe,cr=et.has("deleted")&&xt.current===Fe,Dr=wN(J.scope);await Promise.all([tt||Gt?Oe.current({includeActive:tt,includeArchive:Gt,highlightChangedTaskIds:Dr}):Promise.resolve(),cr?ya.current(!0):Promise.resolve(!1),et.has("planning")?Jt.current():Promise.resolve()])}}finally{L.current=!1}}},[]),xn=o.useRef(()=>{}),Bs=o.useRef(()=>{}),xs=o.useRef(async()=>!1),ja=o.useCallback(I=>xs.current(I),[]),{userGlobalSyncStatus:di,setUserGlobalSyncStatus:Ti,userGlobalSyncError:Fo,setUserGlobalSyncError:Ld,workspaceLastPullAt:oc,workspaceLastPushAt:Sl,workspaceLastErrorAt:ic,workspaceLastErrorMessage:Yu,workspaceLastSuccessfulSyncAt:cc,workspaceCloudSyncEnabled:Rn,workspaceSyncPhase:ui,workspaceSyncSetupIntent:Lc,workspaceSyncStatus:Al,workspaceSyncSummary:Oc,workspaceSyncRecommendedAction:Cl,workspaceSyncBusy:Bg,workspaceSyncPendingChanges:xi,workspaceTaskRelationships:Od,localCoordinatorDataVersion:en,localCoordinatorStatus:Ba,switchLocalCoordinatorWorkspace:os,transferLocalCoordinatorOwnership:Qf,workspacePendingSignatureRef:Xf,workspaceDeletedTaskIdsRef:em,workspaceDeletedTaskWatermarksRef:Bd,loadWorkspaceSyncState:Zu,applyWorkspaceSyncStateSnapshot:tm,syncUserGlobalSettings:Wd,buildWorkspaceSyncSignature:rm,pushWorkspaceChangesToCloud:Ju,saveWorkspaceCloudSyncSettings:am,retryUserGlobalSettingsSync:Qu,retryWorkspaceCloudSync:$d,resetWorkspaceSyncCursorAndPull:Il,getWorkspaceSyncDiagnostics:Fd}=D2({currentWorkspaceId:ft,cloudAuthConfigured:q,runtimeMode:K,authSessionResolved:Lt,isAuthenticated:Ve,authUserId:It,projectName:Ke,resolveCloudAuthUrl:H,resolveWebSocketUrl:se,realtimeSyncEnabled:mt,localOutboxDispatchEnabled:w.syncV3LocalOutboxDispatch,localCoordinatorBrowserAuthorityGateEnabled:w.localCoordinatorBrowserAuthorityGate,initiativeFeedActivationEnabled:w.syncV3InitiativeFeedActivation,combinedFeedActivationEnabled:w.syncV3CombinedFeedActivation,combinedFeedCoverage:w.syncV3CombinedFeedCoverage,tasks:pa,archivedTasks:ln,deletedTasks:ra,initiatives:ws,workstreams:Va,taxonomies:_a,taxonomyState:_s?nc:void 0,setupState:Ar,globalTheme:Ze,locale:Vs,globalWeekStartsOn:$n,themeUseGlobalDefault:at,setTasks:Sn,setArchivedTasks:An,setAuthBlocked:pt,setIsAuthenticated:lt,checkAuthSession:ja,setGlobalTheme:st,setCurrentTheme:ke,setSetupState:ma,setLocale:Ks,setGlobalWeekStartsOn:Ia,fetchPlanningEntities:Vr}),_l=o.useCallback((I=dn)=>I.find(X=>String(X.value||"").trim().length>0)?.value||fo,[dn]),[Bc,Ri]=o.useState(()=>Xa(jr)),[Tl,xl]=o.useState(()=>_l(dn)),[Xu,Ud]=o.useState(2),[ep,nm]=o.useState(3),[Rl,sm]=o.useState("task"),[Wc,jl]=o.useState("unassigned"),[pi,zd]=o.useState(""),[lc,Hd]=o.useState(""),[Pl,om]=o.useState(""),[ji,El]=o.useState(""),[bo,im]=o.useState(""),Xs=o.useRef(ji),eo=o.useRef(bo),fi=o.useRef(!1),[tp,rp]=o.useState(!1),Uo=o.useCallback(()=>{const I=Xs.current.trim()!==""||eo.current.trim()!=="";I!==fi.current&&(fi.current=I,rp(I))},[]),dc=o.useCallback(I=>{Xs.current=I,Uo()},[Uo]),mi=o.useCallback(I=>{eo.current=I,Uo()},[Uo]),Gd=o.useCallback(()=>Xs.current,[]),ap=o.useCallback(()=>eo.current,[]);o.useEffect(()=>{Xs.current=ji,Uo()},[Uo,ji]),o.useEffect(()=>{eo.current=bo,Uo()},[bo,Uo]);const[Ws,Nl]=o.useState([]),[zo,Ml]=o.useState([]),[Dl,Ll]=o.useState(""),[Ol,hi]=o.useState({}),gi=o.useRef(null),[Ho,Cr]=o.useState(""),[np,to]=o.useState(""),[uc,Pi]=o.useState(""),[pc,cm]=o.useState({});o.useEffect(()=>{if(aa)return;const I=String(Tl||"").trim();dn.some(re=>String(re.value||"").trim()===I)||xl(_l(dn))},[dn,aa,_l,Tl]);const{searchQuery:Bl,setSearchQuery:lm,filterCategories:Vd,setFilterCategories:sp,filterPriorities:Wl,setFilterPriorities:Ei,filterTypes:$c,setFilterTypes:$l,filterStatus:op,setFilterStatus:ip,filterAssignees:So,setFilterAssignees:dm,filterAssigneesAllSelected:Wg,setFilterAssigneesAllSelected:cp,filterTaxonomies:fc,setFilterTaxonomies:Fl,hasInitedFilters:$g,setHasInitedFilters:um,sortBy:Ul,setSortBy:is,sortOrder:yi,setSortOrder:pm,toggleSortOrder:Fg,groupBy:Go,setGroupBy:Ni,emptyColumnMode:Kd,setEmptyColumnMode:zl,collapsedCategories:lp,setCollapsedCategories:dp,clearFilters:fm,filteredTasks:Fc,searchAgnosticTasks:Uc,filteredArchive:up,groupedTasks:mm}=lE({tasks:pa,archivedTasks:ln,activeCategories:jr,activeTypes:dn,priorities:ha,taxonomies:_a,configLoaded:na,referenceDataLoaded:_s,assigneeOptionsLoaded:ko,assigneeOptions:pr});xn.current=Ti,Bs.current=Ld;const{checkAuthSession:hm}=_E({runtimeConfigReady:E,shouldProbeCloudAuth:Ne,authSessionResolved:Lt,resolveCloudAuthUrl:H,authOnlyCloudMode:ye,authRequiredError:zn,runtimeMode:K,workspaceSelectionScope:Ge,markBootstrapPhase:ii,markBootstrapStalled:as,setRuntimeMode:Re,setAuthRequiredForApi:je,setIsAuthenticated:lt,setAuthUserId:wt,setAuthWorkspaceId:Yt,setAuthUserEmail:er,setAuthUserDisplayName:Dt,setAuthUserAvatarUrl:la,setUserGlobalSyncStatus:I=>xn.current(I),setUserGlobalSyncError:I=>Bs.current(I),setHasBetaAccess:ea,setAvailableWorkspaces:Pt,setHydratedWorkspaceRole:Ft,setAssigneeOptions:Yr,setAuthBlocked:pt,setAuthSessionResolved:zr,setError:Tn,applyResolvedWorkspaceId:br,readPersistedWorkspaceId:Nk,authSessionRequestRef:He,authSessionEpochRef:Ca,authSessionLastCheckedAtRef:da,authSessionLastResultRef:ir,isLoopbackHost:C,setAuthStateReadyRefs:(I,X,re)=>{Jd.current=X,gc.current=re,Qd.current=I}});xs.current=hm;const[mc,zc]=o.useState("tasks"),[pp,Ut]=o.useState(!1),[gm,fp]=o.useState(!1),qd=o.useRef([]),[Hc,ym]=o.useState([]),Yd=o.useCallback(I=>{const X=typeof I=="function"?I(qd.current):I;qd.current=X,ym(X)},[]),km=o.useCallback(()=>[...qd.current],[]),Gc=o.useRef(null),[Ug,mp]=o.useState(!1),hp=o.useCallback(()=>`task-description-${globalThis.crypto?.randomUUID?.()||`${Date.now()}-${Math.random().toString(16).slice(2)}`}`,[]),Zd=o.useRef(hp()),[zg,Ao]=o.useState(Zd.current),Vc=o.useCallback(()=>{const I=hp();Zd.current=I,Ao(I)},[hp]),vm=o.useCallback(I=>{Gc.current=I,mp(!0),I.then(()=>{Gc.current===I&&(Gc.current=null,mp(!1))},()=>{Gc.current===I&&(Gc.current=null,mp(!1))})},[]),Vo=o.useCallback(async()=>{const I=Gc.current;I&&await I},[]),[wm,gp]=o.useState(!1),Hg=o.useRef(null),hc=o.useRef(null),bm=o.useRef(!1),Jd=o.useRef(Lt),gc=o.useRef(ur),Qd=o.useRef(Ve),Hl=o.useRef(""),Gl=o.useRef(""),Kc=o.useRef(""),yc=o.useRef(""),Mi=o.useRef(""),Di=o.useRef(null),Vl=o.useRef(!1),yp=o.useRef(!1),{handleSaveSettings:qc,handleSaveTheme:kp,handleSaveGlobalTheme:vp,handleJsonBackupEnabledChange:Yc,handleSaveGlobalJsonBackupEnabled:Gg,handleSaveGlobalWeekStartsOn:wp,handleSaveLocale:Xd,handleManualComplexityEnabledChange:Sm,handleChecklistDropdownEnabledChange:Am,handleShowTaskCardStatusLabelChange:Vg,handleResetProjectToGlobal:Kg}=W2({keyShortcut:or,themeUseGlobalDefault:at,runtimeMode:K,jsonBackupUseGlobalDefault:Ta,globalTheme:Ze,globalJsonBackupEnabled:Bn,setCurrentTheme:ke,setThemeUseGlobalDefault:oe,setGlobalTheme:st,setJsonBackupEnabled:wn,setJsonBackupUseGlobalDefault:Ms,setGlobalJsonBackupEnabled:Wn,setGlobalWeekStartsOn:Ia,setLocale:Ks,setManualComplexityEnabled:xa,setChecklistDropdownEnabled:sn,setShowTaskCardStatusLabel:on});o.useEffect(()=>{K==="cloud"&&Ge!==jd&&zx(ft,Ge)},[K,ft,Ge]),o.useEffect(()=>{Jd.current=Lt,gc.current=ur,Qd.current=Ve},[Lt,ur,Ve]);const{hasLoadedUiStateRef:bp,loadPersistedUiState:Li,resetPersistedUiStateLoad:$s,setActiveWorkspaceModule:Oi,uiStateReady:Bi}=PE({runtimeMode:K,workspaceUiStateScope:_r,currentWorkspaceId:ft,currentWorkspaceIdRef:ut,referenceDataLoaded:_s,activeCategories:jr,activeTypes:dn,priorities:ha,taxonomies:_a,activeWorkspaceModule:mc,setActiveWorkspaceModuleState:zc,groupBy:Go,setGroupBy:Ni,emptyColumnMode:Kd,setEmptyColumnMode:zl,taskScope:Ce,setTaskScope:P,openTaskId:aa,setPendingOpenTaskId:Ss,compressedCards:ee,setCompressedCards:Se,zenMode:ia,setZenModeState:Za,searchQuery:Bl,setSearchQuery:lm,collapsedCategories:lp,setCollapsedCategories:dp,filterCategories:Vd,setFilterCategories:sp,filterPriorities:Wl,setFilterPriorities:Ei,filterTypes:$c,setFilterTypes:$l,filterStatus:op,setFilterStatus:ip,filterAssignees:So,setFilterAssignees:dm,filterAssigneesAllSelected:Wg,setFilterAssigneesAllSelected:cp,filterTaxonomies:fc,setFilterTaxonomies:Fl,sortBy:Ul,setSortBy:is,sortOrder:yi,setSortOrder:pm,hasInitedFilters:$g,setHasInitedFilters:um,lastUsedCategory:Ho,setLastUsedCategory:Cr,taskforceAgentId:np,setTaskforceAgentId:to,taskforceAgentConversationId:uc,setTaskforceAgentConversationId:Pi,taskforceAgentConversationByAgentId:pc,setTaskforceAgentConversationByAgentId:cm}),Cm=o.useCallback(I=>{const X=I.runtimeMode==="cloud"?"cloud":"local",re=!!I.authRequiredForApi,J=typeof I.userId=="string"&&I.userId.trim().length>0?I.userId.trim():"anonymous",Fe=X==="cloud"&&J!=="anonymous",et=Fe||Qd.current,tt=Jd.current;if(Re(X),je(re),Fe&&(lt(!0),wt(J),pt(!1),tt||zr(!0)),typeof I.workspaceId=="string"&&I.workspaceId.trim().length>0){const Rs=I.workspaceId.trim();if(X==="local"){const gn=String(ut.current||"").trim()||"default";Qr(Rs,{skipTransitionReset:!na&&gn==="default"})}else br(Rs)}pt(X==="cloud"&&re?!et:!1),I.setupState&&typeof I.setupState=="object"?ma(I.setupState):ma(null),I.runtimeCapabilities&&typeof I.runtimeCapabilities=="object"?it(I.runtimeCapabilities):it(null),ht(!!I.realtimeSyncEnabled);const Gt=String(I.realtimeSyncFlagSource||"").trim().toLowerCase();sr(Gt==="env"||Gt==="settings"||Gt==="default"?Gt:"unknown"),typeof I.shortcut=="string"&&I.shortcut.trim().length>0&&Tr(I.shortcut);const cr=Pu(I.theme);cr&&ke(cr);const Dr=Pu(I.globalTheme);Dr&&st(Dr),typeof I.themeUseGlobalDefault=="boolean"&&oe(I.themeUseGlobalDefault);const Wr=I.runtimeMode==="cloud"?"cloud":"local";typeof I.projectRoot=="string"?$(I.projectRoot):Wr==="cloud"&&$(""),typeof I.tenantId=="string"?Qt(I.tenantId.trim()):Wr==="cloud"&&Qt("");const Er=Wr==="cloud"?String(I.projectName||"").trim():I.projectName||I.paths?.projectName||"";(String(Er||"").trim().length>0||Wr==="cloud")&&Qe(Er),typeof I.mcpScript=="string"?Nt(I.mcpScript):Wr==="cloud"&&Nt(""),typeof I.hostRoot=="string"?Da(I.hostRoot):Wr==="cloud"&&Da(""),typeof I.jsonBackupEnabled=="boolean"&&wn(I.jsonBackupEnabled),typeof I.globalJsonBackupEnabled=="boolean"&&Wn(I.globalJsonBackupEnabled),typeof I.jsonBackupUseGlobalDefault=="boolean"&&Ms(I.jsonBackupUseGlobalDefault);const Ua=I?.schedulePreferences?.weekStartsOn;(Ua==="sunday"||Ua==="monday")&&Ia(Ua),typeof I.manualComplexityEnabled=="boolean"&&xa(I.manualComplexityEnabled),typeof I.checklistDropdownEnabled=="boolean"?sn(I.checklistDropdownEnabled):sn(!0),typeof I.showTaskCardStatusLabel=="boolean"?on(I.showTaskCardStatusLabel):on(!1)},[br,Qr,na,ut]),qg=o.useCallback(async()=>{const I=typeof performance<"u"?performance.now():Date.now();try{const X=await Ka("/api/taskforce/version",void 0,kf);if(!X.ok)return;const re=await X.json().catch(()=>({}));re?.build&&typeof re.build=="object"&&fr({version:String(re.build.version||""),gitSha:re.build.gitSha?String(re.build.gitSha):null,buildTime:re.build.buildTime?String(re.build.buildTime):null,deployId:re.build.deployId?String(re.build.deployId):null}),wr("build_info_loaded",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-I)})}catch(X){Ci(X)&&wr("build_info_timeout",{durationMs:Math.round((typeof performance<"u"?performance.now():Date.now())-I)})}},[Ka,Ci]),{fetchReferenceData:Kl,fetchConfig:cs,fetchWorkspaces:Zc,fetchAssigneeOptions:eu,switchWorkspace:Fs,resolveWorkspaceAfterAuth:Im,retryBootstrapChecks:Sp,runCloudBootstrap:tu}=jE({shouldDeferProtectedApiCalls:va,shouldBlockProtectedApiCalls:Ya,getWorkspaceRequestState:yr,isWorkspaceRequestStale:Kr,isWorkspaceEpochStale:dt,isAbortError:Ma,isBootstrapTimeoutError:Ci,fetchWithTimeout:Ka,handleUnauthorized:ns,applyBootstrapConfig:Cm,loadPersistedUiState:Li,fetchBuildInfo:qg,markBootstrapPhase:ii,markBootstrapStalled:as,fetchInitiativeTemplates:ga,setReferenceDataLoaded:Qs,setCustomCategories:Un,setCustomTypes:Ii,setPriorities:ba,setTaxonomies:Cs,setTaxonomyDisplayLabels:Wo,setConfigLoaded:Js,hasLoadedUiStateRef:bp,currentWorkspaceIdRef:ut,referenceDataRequestRef:Di,referenceDataAbortRef:En,bootstrapConfigAbortRef:vn,workspaceListAbortRef:Ga,assigneeOptionsAbortRef:Hr,workspaceListHydratedRef:Vl,setAvailableWorkspaces:Pt,runtimeMode:K,applyResolvedWorkspaceId:br,workspaceSwitchingEnabled:Mt,authSessionResolved:Lt,isAuthenticated:Ve,authUserId:It,authUserAvatarUrl:Rr,setHydratedWorkspaceRole:Ft,setAssigneeOptions:Yr,setAssigneeOptionsLoaded:$o,commitCurrentWorkspaceId:(I,X)=>{ka.current=I,Qr(I,X),X?.clearExplicitSelection!==!1&&(ka.current=null)},currentWorkspaceId:ft,workspaceSelectionScope:Ge,abortWorkspaceScopedRequests:Zt,setWorkspaceBootstrapPending:$r,checkAuthSession:ja,lastConfigRefreshKeyRef:Gl,lastAssigneeOptionsLoadKeyRef:Hl,lastWorkspaceSyncStateLoadKeyRef:Kc,lastTaskSurfaceLoadKeyRef:yc,lastSettingsSurfaceLoadKeyRef:Mi,isOpen:ne,activeTab:Pe,showArchive:pe,taskScope:Ce,settingsSection:xe,workspaceBootstrapPending:tr,fetchTasks:Dn,fetchPlanningEntities:Vr,refreshTaskCollections:D,loadWorkspaceSyncState:Zu,switchLocalCoordinatorWorkspace:os,hasBootstrappedDataRef:yp}),Jc=o.useCallback(async()=>{await ja(),await cs()},[ja,cs]);o.useEffect(()=>{if(!na||tr)return;const I=`${K}:${Ve?"auth":"guest"}:${ft}:${Rr||"no-avatar"}`;ko&&Hl.current===I||(Hl.current=I,eu())},[ko,Rr,na,ft,eu,Ve,K,tr]),o.useEffect(()=>{if(!Lt||!Ve)return;const I=String(It||"").trim();if(!I||I==="anonymous")return;const X=String(Rr||"").trim()||null;Yr(re=>{let J=!1;const Fe=re.map(et=>et.kind!=="member"||String(et.value||"").trim()!==I||(typeof et.avatarUrl=="string"&&et.avatarUrl.trim().length>0?et.avatarUrl.trim():null)===X?et:(J=!0,{...et,avatarUrl:X}));return J?Fe:re})},[Lt,Rr,It,Ve]);const Yg=o.useMemo(()=>Mt?u.find(X=>X.id===ft)?.role??null:Ur,[u,ft,Ur,Mt]);o.useEffect(()=>{Ve||Ft(null)},[Ve]);const ru=o.useCallback(async()=>{Br(null);const I=await tu({reason:"post-plans",ignoreAuthGuard:!0,tasksSilent:!0});return I.authenticated?I.success?I.workspaceSetupRequired?{success:!0,destination:"setup"}:{success:!0,destination:"app"}:{success:!1,destination:"app",error:I.error||"Unable to resolve workspace after plan selection.",code:I.code}:{success:!1,destination:"login",error:I.error||"Sign in required.",code:I.code||"AUTH_REQUIRED"}},[tu]),Co=o.useCallback(async I=>{const X=I?.reason||"retry",re=typeof I?.preferredWorkspaceId=="string"?I.preferredWorkspaceId.trim():"",J=I?.allowCommercialGate===!0;if(re&&Mt){if(!await ja({force:!0}))return await cs({ignoreAuthGuard:!0}),{success:!1,error:"Sign in required.",code:"AUTH_REQUIRED"};const tt=await Im({preferredWorkspaceId:re});if(!tt.success)return await cs({ignoreAuthGuard:!0}),{success:!1,error:tt.error||"Unable to resolve workspace access.",code:tt.code};if(tt.workspaceSetupRequired)return await cs({ignoreAuthGuard:!0}),{success:!0,workspaceSetupRequired:!0}}const Fe=await tu({reason:X,ignoreAuthGuard:!0,tasksSilent:!0});return Fe.authenticated?Fe.success?Fe.workspaceSetupRequired?J?{success:!0,workspaceSetupRequired:!1}:{success:!0,workspaceSetupRequired:!0}:(J||Wd({preferCloudOnFirstSync:!0}),{success:!0,workspaceSetupRequired:!1}):{success:!1,error:Fe.error||"Unable to resolve workspace access.",code:Fe.code}:{success:!1,error:Fe.error||"Sign in required.",code:Fe.code||"AUTH_REQUIRED"}},[ja,cs,Im,tu,Wd,Mt]),au=o.useCallback(async(I,X)=>{if(!Mt)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const re=String(I||"").trim();if(!re)return{success:!1,error:"Workspace name is required."};try{const J=await fetch("/api/taskforce/workspaces",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({name:re,description:typeof X=="string"?X:void 0})}),Fe=await J.json().catch(()=>({}));if(!J.ok||Fe?.success===!1)return{success:!1,error:Fe?.error||`Failed to create workspace (${J.status})`,code:Fe?.code};const et=Fe?.workspace;if(await Zc(),et?.id){const tt=await Fs(et.id);if(!tt.success)return{success:!1,error:tt.error||"Workspace created but failed to activate.",code:tt.code}}return{success:!0,workspace:et}}catch{return{success:!1,error:"Failed to create workspace."}}},[Zc,Fs,Mt]),Ap=o.useCallback(async I=>{if(!Mt)return{success:!1,error:"Workspace management is unavailable in local mode.",code:"WORKSPACE_MANAGEMENT_DISABLED"};const X=String(I||"").trim();if(!X)return{success:!1,error:"workspaceId is required.",code:"WORKSPACE_ID_REQUIRED"};try{const re=await fetch(`/api/taskforce/workspaces/${encodeURIComponent(X)}`,{method:"DELETE",credentials:"include"}),J=await re.json().catch(()=>({}));if(!re.ok||J?.success===!1)return{success:!1,error:J?.error||`Failed to delete workspace (${re.status})`,code:J?.code};await ja({force:!0}),await Promise.all([cs(),Zc()]);const Fe=typeof J?.nextWorkspaceId=="string"?J.nextWorkspaceId.trim():"";return Fe&&Qr(Fe),{success:!0,nextWorkspaceId:Fe||void 0,workspaceSetupRequired:J?.workspaceSetupRequired===!0,cleanupWarnings:Array.isArray(J?.cleanupWarnings)?J.cleanupWarnings.map(et=>String(et||"")):[]}}catch{return{success:!1,error:"Failed to delete workspace."}}},[ja,Qr,cs,Zc,Mt]),nu=o.useCallback(async I=>{const X=I==="operations"?"operations":"core";try{const re=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:X}})}),J=await re.json().catch(()=>({}));return!re.ok||J?.success===!1?!1:(await Jc(),!0)}catch{return!1}},[Jc]),_m=o.useCallback(async I=>{const X=String(I?.name||"").trim(),re=typeof I?.workspaceId=="string"?I.workspaceId.trim():"";if(!X)return{success:!1,error:"Workspace name is required.",code:"WORKSPACE_NAME_REQUIRED"};try{const J=await fetch("/api/taskforce/workspace-profile",{method:"POST",headers:{"Content-Type":"application/json","x-taskforce-runtime-mode":K},credentials:"include",body:JSON.stringify({workspaceId:re&&re!=="default"?re:void 0,name:X,description:typeof I.description=="string"?I.description:void 0,allowCreate:!0})}),Fe=await J.json().catch(()=>({}));if(!J.ok||Fe?.success===!1)return{success:!1,error:Fe?.error||`Failed to save workspace (${J.status})`,code:Fe?.code};const et=String(Fe?.workspace?.id||"").trim();if(et&&(Qr(et),await new Promise(tt=>window.setTimeout(tt,0)),K==="cloud"&&Ve&&et!==ft)){const tt=await Fs(et);if(!tt.success)return{success:!1,error:tt.error||"Workspace saved but failed to activate session workspace.",code:"WORKSPACE_SWITCH_FAILED"}}return await Jc(),{success:!0,workspaceId:et||void 0}}catch{return{success:!1,error:"Failed to save workspace profile."}}},[Qr,Jc,K,Ve,ft,Fs]),Cp=o.useCallback(async(I,X)=>{if(!q)return{success:!1,error:"Cloud auth endpoint is not configured."};const re=I.trim().toLowerCase(),J=X;if(!re||!J)return{success:!1,error:"Email and password are required."};try{const Fe=await fetch(H("/api/taskforce/auth/login"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(xx({email:re,password:J,activeWorkspaceId:ut.current}))}),et=await Fe.json().catch(()=>({}));if(!Fe.ok||!et?.success)return{success:!1,error:et?.error||"Sign in failed.",code:et?.code};Tn("");const tt=await Co();return tt.success?(Vb(),{success:!0,workspaceSetupRequired:tt.workspaceSetupRequired===!0}):{success:!1,error:tt.error||"Unable to resolve workspace after sign in.",code:tt.code}}catch{return{success:!1,error:"Sign in failed."}}},[H,q,ut,Co]),Zg=o.useCallback((I,X,re)=>{let J="/";try{const et=new URL(String(X||"/"),"https://taskforce.local");et.origin==="https://taskforce.local"&&String(X||"/").startsWith("/")&&!String(X||"/").startsWith("//")&&(J=`${et.pathname}${et.search}${et.hash}`)}catch{J="/"}let Fe=`/api/taskforce/auth/oauth/${encodeURIComponent(I)}/start?return_to=${encodeURIComponent(J)}`;re&&(Fe+=`&invite_token=${encodeURIComponent(re)}`),window.location.href=H(Fe)},[H]),ql=o.useCallback(async(I,X,re)=>{if(!q)return{success:!1,error:"Cloud auth endpoint is not configured."};const J=I.trim().toLowerCase(),Fe=X;if(!J||!Fe)return{success:!1,error:"Email and password are required."};try{const et=await fetch(H("/api/taskforce/auth/register"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:J,password:Fe,...typeof re?.displayName=="string"&&re.displayName.trim()?{displayName:re.displayName.trim()}:{},...typeof re?.planId=="string"&&re.planId.trim()?{planId:re.planId.trim()}:{},...typeof re?.planVersionId=="string"&&re.planVersionId.trim()?{planVersionId:re.planVersionId.trim()}:{},...typeof re?.interval=="string"&&re.interval.trim()?{interval:re.interval.trim()}:{}})}),tt=await et.json().catch(()=>({}));if(!et.ok||!tt?.success)return{success:!1,error:tt?.error||"Create account failed.",code:tt?.code,verificationRequired:!!tt?.verificationRequired,verificationToken:typeof tt?.verificationToken=="string"?tt.verificationToken:void 0,emailSent:tt?.emailSent!==!1,emailError:typeof tt?.emailError=="string"?tt.emailError:void 0};const Gt=tt?.planSelectionRequired===!0,cr=tt?.checkoutPending===!0,Dr=typeof tt?.commercialState=="string"?tt.commercialState:null,Wr=!!tt?.verificationRequired;if(!Wr){if(Tn(""),!!(Gt||cr||Dr==="pending_plan_selection"||Dr==="checkout_pending"))return await ja({force:!0})?{success:!0,workspaceSetupRequired:!1,planSelectionRequired:Gt,checkoutPending:cr,commercialState:Dr,verificationRequired:Wr,verificationToken:typeof tt?.verificationToken=="string"?tt.verificationToken:void 0,emailSent:tt?.emailSent!==!1,emailError:typeof tt?.emailError=="string"?tt.emailError:void 0}:{success:!1,error:"Unable to resolve workspace after registration.",code:"AUTH_REQUIRED"};const Ua=await Co({allowCommercialGate:!1});return Ua.success?{success:!0,workspaceSetupRequired:Ua.workspaceSetupRequired===!0,planSelectionRequired:Gt,checkoutPending:cr,commercialState:Dr,verificationRequired:Wr,verificationToken:typeof tt?.verificationToken=="string"?tt.verificationToken:void 0,emailSent:tt?.emailSent!==!1,emailError:typeof tt?.emailError=="string"?tt.emailError:void 0}:{success:!1,error:Ua.error||"Unable to resolve workspace after registration.",code:Ua.code}}return{success:!0,workspaceSetupRequired:!!tt?.workspaceSetupRequired,planSelectionRequired:Gt,checkoutPending:cr,commercialState:Dr,verificationRequired:Wr,verificationToken:typeof tt?.verificationToken=="string"?tt.verificationToken:void 0,emailSent:tt?.emailSent!==!1,emailError:typeof tt?.emailError=="string"?tt.emailError:void 0}}catch{return{success:!1,error:"Create account failed."}}},[ja,H,q,Co]),Jg=o.useCallback(async I=>{if(!q)return{success:!1,error:"Cloud auth endpoint is not configured."};const X=String(I.displayName||"").trim(),re=typeof I.avatarDraftId=="string"?I.avatarDraftId.trim():"",J=I.clearAvatar===!0;if(!X)return{success:!1,error:"Display name is required."};try{const Fe=await fetch(H("/api/taskforce/auth/profile"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({displayName:X,...re?{avatarDraftId:re}:{},...J?{clearAvatar:!0}:{}})}),et=await Fe.json().catch(()=>({}));if(!Fe.ok||!et?.success)return{success:!1,error:et?.error||"Failed to update profile.",code:et?.code};const tt={userId:typeof et?.profile?.userId=="string"?et.profile.userId:It,email:typeof et?.profile?.email=="string"?et.profile.email:qt,displayName:typeof et?.profile?.displayName=="string"?et.profile.displayName:null,avatarUrl:typeof et?.profile?.avatarUrl=="string"?et.profile.avatarUrl:null};return Dt(tt.displayName||""),la(tt.avatarUrl||""),{success:!0,profile:tt}}catch{return{success:!1,error:"Failed to update profile."}}},[H,q,qt,It]),ro=o.useCallback(async I=>{if(!q)return{success:!1,error:"Cloud auth endpoint is not configured."};const X=I.trim().toLowerCase();if(!X)return{success:!1,error:"Email is required."};try{const re=await fetch(H("/api/taskforce/auth/verify-email/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:X})}),J=await re.json().catch(()=>({}));return!re.ok||!J?.success?{success:!1,error:J?.error||"Failed to request verification email.",code:J?.code}:{success:!0,verificationToken:J?.verificationToken??null,emailSent:J?.emailSent!==!1,deliveryAttempted:J?.deliveryAttempted===!0||typeof J?.verificationToken=="string"&&J.verificationToken.trim().length>0,emailError:typeof J?.emailError=="string"?J.emailError:void 0}}catch{return{success:!1,error:"Failed to request verification email."}}},[H,q]),Qg=o.useCallback(async I=>{if(!q)return{success:!1,error:"Cloud auth endpoint is not configured."};const X=I.trim();if(!X)return{success:!1,error:"Token is required."};try{const re=await fetch(H("/api/taskforce/auth/verify-email/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:X})}),J=await re.json().catch(()=>({}));return!re.ok||!J?.success?{success:!1,error:J?.error||"Verification failed.",code:J?.code}:{success:!0}}catch{return{success:!1,error:"Verification failed."}}},[H,q]),Tm=o.useCallback(async I=>{if(!q)return{success:!1,error:"Cloud auth endpoint is not configured."};const X=I.trim().toLowerCase();if(!X)return{success:!1,error:"Email is required."};try{const re=await fetch(H("/api/taskforce/auth/password-reset/request"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({email:X})}),J=await re.json().catch(()=>({}));return!re.ok||!J?.success?{success:!1,error:J?.error||"Failed to request password reset.",code:J?.code}:{success:!0,resetToken:J?.resetToken??null,emailSent:J?.emailSent!==!1,deliveryAttempted:J?.deliveryAttempted===!0||typeof J?.resetToken=="string"&&J.resetToken.trim().length>0,emailError:typeof J?.emailError=="string"?J.emailError:void 0}}catch{return{success:!1,error:"Failed to request password reset."}}},[H,q]),Ip=o.useCallback(async(I,X)=>{if(!q)return{success:!1,error:"Cloud auth endpoint is not configured."};const re=I.trim(),J=X;if(!re||!J)return{success:!1,error:"Token and password are required."};try{const Fe=await fetch(H("/api/taskforce/auth/password-reset/confirm"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:re,password:J})}),et=await Fe.json().catch(()=>({}));return!Fe.ok||!et?.success?{success:!1,error:et?.error||"Failed to reset password.",code:et?.code}:{success:!0}}catch{return{success:!1,error:"Failed to reset password."}}},[H,q]),Xg=o.useCallback(async I=>{if(!q)return{success:!1,error:"Cloud auth endpoint is not configured."};const X=I.trim();if(!X)return{success:!1,error:"Token is required."};try{const re=await fetch(H("/api/taskforce/auth/invite/inspect"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:X})}),J=await re.json().catch(()=>({}));return!re.ok||!J?.success?{success:!1,error:J?.error||"Invite inspection failed.",code:J?.code,state:J?.state}:{success:!0,state:J?.state,email:typeof J?.email=="string"?J.email:void 0,workspaceId:typeof J?.workspaceId=="string"?J.workspaceId:void 0,inviteeKind:J?.inviteeKind==="existing_user"?"existing_user":"new_user",passwordRequired:J?.passwordRequired===!0,inviteeState:J?.inviteeState==="existing_account"?"existing_account":"pending_setup",availableMethods:Array.isArray(J?.availableMethods)?J.availableMethods:[]}}catch{return{success:!1,error:"Invite inspection failed."}}},[H,q]),ey=o.useCallback(async(I,X)=>{if(!q)return{success:!1,error:"Cloud auth endpoint is not configured."};const re=I.trim(),J=X;if(!re||!J)return{success:!1,error:"Token and password are required."};try{const Fe=await fetch(H("/api/taskforce/auth/invite/accept"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:re,password:J})}),et=await Fe.json().catch(()=>({}));if(!Fe.ok||!et?.success)return{success:!1,error:et?.error||"Invite acceptance failed.",code:et?.code};Tn("");const tt=typeof et?.workspaceId=="string"?et.workspaceId:null;if(tt&&Mt){const cr=await Fs(tt,{hydrate:!1});if(!cr.success)return{success:!1,error:cr.error||"Unable to resolve workspace after invite acceptance.",code:cr.code}}const Gt=await Co({preferredWorkspaceId:tt});return Gt.success?(tt&&ut.current!==tt&&Qr(tt,{clearExplicitSelection:!1}),{success:!0,workspaceSetupRequired:Gt.workspaceSetupRequired===!0}):{success:!1,error:Gt.error||"Unable to resolve workspace after invite acceptance.",code:Gt.code}}catch{return{success:!1,error:"Invite acceptance failed."}}},[Qr,H,q,ut,Co,Fs,Mt]),xm=o.useCallback(async I=>{if(!q)return{success:!1,error:"Cloud auth endpoint is not configured."};const X=I.trim();if(!X)return{success:!1,error:"Token is required."};try{const re=await fetch(H("/api/taskforce/auth/invite/join"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({token:X})}),J=await re.json().catch(()=>({}));if(!re.ok||!J?.success)return{success:!1,error:J?.error||"Invite join failed.",code:J?.code};Tn("");const Fe=typeof J?.workspaceId=="string"?J.workspaceId:null;if(Fe&&Mt){const tt=await Fs(Fe,{hydrate:!1});if(!tt.success)return{success:!1,error:tt.error||"Unable to resolve workspace after invite join.",code:tt.code}}const et=await Co({preferredWorkspaceId:Fe});return et.success?(Fe&&ut.current!==Fe&&Qr(Fe,{clearExplicitSelection:!1}),{success:!0,workspaceSetupRequired:et.workspaceSetupRequired===!0}):{success:!1,error:et.error||"Unable to resolve workspace after invite join.",code:et.code}}catch{return{success:!1,error:"Invite join failed."}}},[Qr,H,q,ut,Co,Fs,Mt]),_p=o.useCallback(async()=>{if(!q)return{success:!1,error:"Cloud auth not configured."};try{const I=await fetch(H("/api/taskforce/auth/login-methods"),{credentials:"include"}),X=await I.json().catch(()=>({}));return!I.ok||!X?.success?{success:!1,error:X?.error||"Failed to fetch login methods."}:{success:!0,methods:Array.isArray(X?.methods)?X.methods:[]}}catch{return{success:!1,error:"Failed to fetch login methods."}}},[H,q]),Rm=o.useCallback(async I=>{if(!q)return{success:!1,error:"Cloud auth not configured."};try{const X=await fetch(H(`/api/taskforce/auth/login-methods/${encodeURIComponent(I)}`),{method:"DELETE",credentials:"include"}),re=await X.json().catch(()=>({}));return!X.ok||!re?.success?{success:!1,error:re?.error||"Unlink failed.",code:re?.code}:{success:!0}}catch{return{success:!1,error:"Unlink failed."}}},[H,q]),su=o.useCallback(async I=>{if(!q)return{success:!1,error:"Cloud auth not configured."};try{const X=await fetch(H("/api/taskforce/auth/login-methods/password"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({password:I})}),re=await X.json().catch(()=>({}));return!X.ok||!re?.success?{success:!1,error:re?.error||"Failed to add password.",code:re?.code}:{success:!0}}catch{return{success:!1,error:"Failed to add password."}}},[H,q]),ty=o.useCallback(async(I,X)=>{if(!q)return{success:!1,error:"Cloud auth not configured."};try{const re=await fetch(H("/api/taskforce/auth/password/change"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({currentPassword:I,newPassword:X})}),J=await re.json().catch(()=>({}));return!re.ok||!J?.success?{success:!1,error:J?.error||"Failed to change password.",code:J?.code}:(await ja({force:!0}),Vb(),{success:!0})}catch{return{success:!1,error:"Failed to change password."}}},[H,q,ja]),Tp=o.useCallback((I,X)=>{const re=X&&/^\/[A-Za-z0-9_\-./?=&%]*$/.test(X)?X:"/",J=`/api/taskforce/auth/oauth/${encodeURIComponent(I)}/start?flow=link&return_to=${encodeURIComponent(re)}`;window.location.href=H(J)},[H]),jm=o.useCallback(()=>{Zt(),Di.current=null,Hl.current="",Gl.current="",Kc.current="",yc.current="",Mi.current="",$s({clearLoaded:!0}),Qs(!1),Yr(gl()),$o(!1),Fn([]),Sn([]),An([]),Oa([]),de([]),ar([]),Pr(lk()),hn(!1)},[Zt,$s,An,Sn]),ry=o.useCallback(async()=>{try{q&&await fetch(H("/api/taskforce/auth/logout"),{method:"POST",credentials:"include"})}catch{}finally{if(Zt(),Ca.current+=1,He.current=null,ir.current=!1,da.current=Date.now(),lt(!1),zr(!0),wt("anonymous"),Yt(""),pf(null),er(""),Dt(""),la(""),Ti("disconnected"),Ld(null),ea(!0),Qe(""),Js(!1),Qs(!1),ma(null),Kt("idle"),Br(null),$s({clearLoaded:!0}),K!=="local"&&fb(Ge),pt(K==="cloud"&&ur),Qr("default"),Pt([]),Vl.current=!1,Ft(null),K==="local"){await Promise.allSettled([cs({ignoreAuthGuard:!0}),Dn(!0,{ignoreAuthGuard:!0}),Vr({ignoreAuthGuard:!0}),Kl({ignoreAuthGuard:!0,force:!0})]);return}yp.current=!1,jm()}},[Zt,ur,fb,Qr,H,q,Ge,K,cs,Vr,Kl,Dn,jm]),Yl=o.useRef(null),ao=o.useCallback(async(I,X,re)=>{if(!globalThis.crypto?.randomUUID)throw new Error("Secure initiative operation identity generation is unavailable.");const J=re||`operation-${globalThis.crypto.randomUUID()}`,Fe={...X,headers:{...X.headers||{},"x-taskforce-operation-id":J}};try{return await fetch(I,Fe)}catch{return fetch(I,Fe)}},[]),qa=o.useMemo(()=>_N(),[]),kc=o.useCallback(async I=>{try{const X=JSON.stringify(I);if(Yl.current?.requestBody!==X){if(!globalThis.crypto?.randomUUID)throw new Error("Secure initiative operation identity generation is unavailable.");Yl.current={requestBody:X,operationId:`operation-${globalThis.crypto.randomUUID()}`}}const re=await ao("/api/taskforce/initiative-templates/create",{method:"POST",headers:{"Content-Type":"application/json"},body:X},Yl.current.operationId),J=await re.json().catch(()=>({}));return!re.ok||!J?.success?{success:!1,error:J?.error||`Create failed (${re.status})`}:(Yl.current=null,await Dn(!0),{success:!0,result:J?.results})}catch(X){return{success:!1,error:X.message}}},[Dn,ao]),ay=o.useCallback(async I=>{if(!globalThis.crypto?.randomUUID)throw new Error("Secure initiative identity generation is unavailable.");const X={...I||{},id:I?.id||`initiative-${globalThis.crypto.randomUUID()}`,createdAt:I?.createdAt||new Date().toISOString()},re=await ao("/api/taskforce/initiative",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X)}),J=await re.json().catch(()=>({}));if(!re.ok)throw new Error(J?.error||`Failed to create initiative (${re.status})`);return await Vr(),Oa(Fe=>Jo(Fe,J)),J},[Vr,ao]),ny=o.useCallback(async(I,X)=>{const re=await ao(`/api/taskforce/initiative/${encodeURIComponent(I)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(X||{})}),J=await re.json().catch(()=>({}));if(!re.ok)throw new Error(J?.error||`Failed to update initiative (${re.status})`);return await Vr(),Oa(Fe=>Jo(Fe,J)),J},[Vr,ao]),Pm=o.useCallback(async(I,X,re)=>{const J=await ao(`/api/taskforce/${I}/${encodeURIComponent(X)}/identity`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(re)}),Fe=await J.json().catch(()=>({}));if(!J.ok)throw new Error(Fe?.error||`Failed to update ${I} identity (${J.status})`);return I==="initiative"?Oa(et=>Jo(et,Fe)):de(et=>Jo(et,Fe)),Vr(),Fe},[Vr,ao]),ou=o.useCallback(()=>{Vr()},[Vr]),sy=o.useCallback(async I=>{const X=await ao(`/api/taskforce/initiative/${encodeURIComponent(I)}/archive`,{method:"POST"}),re=await X.json().catch(()=>({}));if(!X.ok)throw new Error(re?.error||`Failed to archive initiative (${X.status})`);return Oa(J=>Jo(J,re)),ou(),re},[ou,ao]),oy=o.useCallback(async I=>{const X=await ao(`/api/taskforce/initiative/${encodeURIComponent(I)}/unarchive`,{method:"POST"}),re=await X.json().catch(()=>({}));if(!X.ok)throw new Error(re?.error||`Failed to unarchive initiative (${X.status})`);return Oa(J=>Jo(J,re)),ou(),re},[ou,ao]),iy=o.useCallback(async I=>{const X=await qa.prepareCreate(ut.current||"default",I||{}),re=await sf("/api/taskforce/workstream",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(X.body)},X.operationId),J=!re.ok&&await nf(re),Fe=await re.json().catch(()=>({}));if(!re.ok){J&&await qa.abandonCreate(X.fingerprint,X.operationId);const et=Fe?.retryAt?` Retry after ${Fe.retryAt}.`:"";throw new Error(`${Fe?.error||`Failed to create workstream (${re.status})`}${et}`)}if(Fe?.id!==X.body.id)throw new Error("Created workstream identity did not match the retained request identity.");return await qa.confirmCreate(X.fingerprint,X.operationId),await Vr(),de(et=>{const tt=IN(et,Fe);return tt?Jo(et,tt):et}),Fe},[ut,Vr,qa]),cy=o.useCallback(async(I,X)=>{const re=`/api/taskforce/workstream/${encodeURIComponent(I)}`,J=X||{},Fe=Va.find(Wr=>Wr.id===I),et=Fe?{updatedAt:Fe.updatedAt||null,initiativeId:Fe.initiativeId||null,ownerId:Fe.ownerId||null,isArchived:!!Fe.isArchived}:null,tt=await qa.prepareMutation(ut.current||"default",re,J,et),Gt=await sf(re,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(J)},tt.operationId),cr=!Gt.ok&&await nf(Gt),Dr=await Gt.json().catch(()=>({}));if(!Gt.ok){cr&&await qa.abandonMutation(tt.fingerprint,tt.operationId);const Wr=Dr?.retryAt?` Retry after ${Dr.retryAt}.`:"";throw new Error(`${Dr?.error||`Failed to update workstream (${Gt.status})`}${Wr}`)}if(Dr?.id!==I)throw new Error("Updated workstream identity did not match the requested workstream.");return await qa.confirmMutation(tt.fingerprint,tt.operationId),await Vr(),de(Wr=>Jo(Wr,Dr)),Dr},[ut,Vr,qa,Va]),ly=o.useCallback(async(I,X)=>{const re=`/api/taskforce/workstream/${encodeURIComponent(I)}/task-order`,J={taskIds:X},Fe=Va.find(Wr=>Wr.id===I),et=await qa.prepareMutation(ut.current||"default",re,J,{updatedAt:Fe?.updatedAt||null,workstreamId:I}),tt=await sf(re,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(J)},et.operationId),Gt=!tt.ok&&await nf(tt),cr=await tt.json().catch(()=>({}));if(!tt.ok){Gt&&await qa.abandonMutation(et.fingerprint,et.operationId);const Wr=cr?.retryAt?` Retry after ${cr.retryAt}.`:"";throw new Error(`${cr?.error||`Failed to reorder workstream tasks (${tt.status})`}${Wr}`)}if(cr?.workstreamId!==I||!Array.isArray(cr?.taskIds))throw new Error("Reordered workstream task response did not match the request.");await qa.confirmMutation(et.fingerprint,et.operationId);const Dr=new Map(cr.taskIds.map((Wr,Er)=>[Wr,(Er+1)*1024]));Sn(Wr=>Wr.map(Er=>Dr.has(Er.id)?{...Er,workstreamOrder:Dr.get(Er.id)}:Er)),await Vr()},[ut,Vr,qa,Va]),jn=o.useCallback(async I=>{const X=`/api/taskforce/workstream/${encodeURIComponent(I)}/archive`,re=Va.find(Gt=>Gt.id===I),J=await qa.prepareMutation(ut.current||"default",X,{},re?{updatedAt:re.updatedAt||null,isArchived:!!re.isArchived}:null),Fe=await sf(X,{method:"POST"},J.operationId),et=!Fe.ok&&await nf(Fe),tt=await Fe.json().catch(()=>({}));if(!Fe.ok){et&&await qa.abandonMutation(J.fingerprint,J.operationId);const Gt=tt?.retryAt?` Retry after ${tt.retryAt}.`:"";throw new Error(`${tt?.error||`Failed to archive workstream (${Fe.status})`}${Gt}`)}if(tt?.id!==I)throw new Error("Archived workstream identity did not match the requested workstream.");return await qa.confirmMutation(J.fingerprint,J.operationId),await Vr(),de(Gt=>Jo(Gt,tt)),tt},[ut,Vr,qa,Va]),xp=o.useCallback(async I=>{const X=`/api/taskforce/workstream/${encodeURIComponent(I)}/unarchive`,re=Va.find(Gt=>Gt.id===I),J=await qa.prepareMutation(ut.current||"default",X,{},re?{updatedAt:re.updatedAt||null,isArchived:!!re.isArchived}:null),Fe=await sf(X,{method:"POST"},J.operationId),et=!Fe.ok&&await nf(Fe),tt=await Fe.json().catch(()=>({}));if(!Fe.ok){et&&await qa.abandonMutation(J.fingerprint,J.operationId);const Gt=tt?.retryAt?` Retry after ${tt.retryAt}.`:"";throw new Error(`${tt?.error||`Failed to unarchive workstream (${Fe.status})`}${Gt}`)}if(tt?.id!==I)throw new Error("Unarchived workstream identity did not match the requested workstream.");return await qa.confirmMutation(J.fingerprint,J.operationId),await Vr(),de(Gt=>Jo(Gt,tt)),tt},[ut,Vr,qa,Va]),Rp=o.useRef(!1);o.useEffect(()=>{Me(!0),!Rp.current&&(Rp.current=!0,ja())},[ja]),o.useEffect(()=>{E&&ja()},[E,ja]),o.useEffect(()=>{if(!q)return;let I=!1;const X=new AbortController,re=typeof window<"u"?window.setTimeout(()=>X.abort(),5e3):null;return fetch(H("/api/taskforce/auth/providers"),{credentials:"include",signal:X.signal}).then(J=>J.ok?J.json():null).then(J=>{!I&&Array.isArray(J?.providers)&&Xr(J.providers)}).catch(()=>{}).finally(()=>{re!==null&&typeof window<"u"&&window.clearTimeout(re)}),()=>{I=!0,X.abort()}},[q,H]),o.useEffect(()=>{if(K!=="local"||!Ne||typeof window>"u")return;const I=()=>{ja()},X=()=>{document.visibilityState==="visible"&&I()};window.addEventListener("focus",I),window.addEventListener("online",I),document.addEventListener("visibilitychange",X);const re=window.setInterval(I,3e4);return()=>{window.removeEventListener("focus",I),window.removeEventListener("online",I),document.removeEventListener("visibilitychange",X),window.clearInterval(re)}},[K,Ne,ja]),o.useEffect(()=>{s&&s(pa.length)},[pa.length,s]);const un=o.useMemo(()=>{const I=String(t||"").trim();return I?[String(n||"").trim(),I,String(r||"").trim()].join(":"):""},[r,t,n]),vc=o.useRef(un);vc.current=un;const Qc=o.useRef(null),Io=o.useRef(null),Wi=o.useRef(null),Xc=o.useRef(null),no=o.useRef(null),el=o.useRef(new Set),tl=o.useRef(new Set),rl=o.useRef(new Map),_o=o.useRef(null),Us=o.useRef(null),[dy,$i]=o.useState(0);o.useEffect(()=>{const I=Xc.current;I&&Qn.current?.ownerKey===I&&Ja(),Xc.current=null,Qc.current=null,Io.current=null,Wi.current=null,no.current=null,el.current.clear(),tl.current.clear(),rl.current.clear(),_o.current!==null&&typeof window<"u"&&(window.clearTimeout(_o.current),_o.current=null),Us.current!==null&&typeof window<"u"&&(window.clearTimeout(Us.current),Us.current=null),$i(X=>X+1)},[Ja,un]),o.useEffect(()=>()=>{_o.current!==null&&typeof window<"u"&&(window.clearTimeout(_o.current),_o.current=null),Us.current!==null&&typeof window<"u"&&(window.clearTimeout(Us.current),Us.current=null)},[]);const jp=o.useRef(!1);o.useEffect(()=>{if(!na)return;if(!jp.current&&jr.length>0){jp.current=!0;const X=Ho,re=jr.some(J=>J.label===X||J.value===X);if(X&&re){const J=jr.find(Fe=>Fe.label===X||Fe.value===X);Ri(J?.value||X)}else Ri(Xa(jr));return}const I=jr.some(X=>X.value===Bc);jr.length>0&&!I&&Ri(Xa(jr))},[na,jr,Bc,Xa,Ho]),o.useEffect(()=>{if(!na||!_s||jr.length===0)return;const I=J=>!jr.some(Fe=>Fe.value===J.category),X=pa.some(I),re=ln.some(I);if(X||re){const J=Xa(jr);X&&Sn(Fe=>Fe.map(et=>I(et)?{...et,category:J}:et)),re&&An(Fe=>Fe.map(et=>I(et)?{...et,category:J}:et))}},[na,_s,jr,pa,ln,Xa]),o.useEffect(()=>{},[D]);const Pp=o.useCallback(async()=>{await Aa(Id(["active","archive","deleted","planning"],{ambiguous:!0}))},[Aa]);o.useEffect(()=>{if(typeof window>"u")return;const I=X=>{const re=X.detail;(String(re?.workspaceId||"").trim()||"default")===ft&&(re?.authoritativeTask||Aa(Id(re?.affectedCollections?.length?re.affectedCollections:["active","archive"],{taskIds:re?.taskId?[re.taskId]:[]})))};return window.addEventListener(Pd,I),()=>{window.removeEventListener(Pd,I)}},[ft,Aa]);const Ko=String(ft||"").trim(),ls=String(It||"").trim(),wc=se("/taskforce-ws"),Em=!!(q&&K==="cloud"&&Lt&&Ve&&ls&&ls!=="anonymous"&&Ko&&!jv(Ko)&&wc);o.useEffect(()=>()=>{hc.current!==null&&typeof window<"u"&&(window.clearTimeout(hc.current),hc.current=null)},[ft]);const Nm=o.useCallback(I=>{if(K!=="cloud")return;XC({workspaceId:Ko,source:"realtime"});const X=bN(I.type,I.invalidations);X.collections.length!==0&&(Aa(X),!(!X.ambiguous||typeof window>"u")&&(hc.current!==null&&window.clearTimeout(hc.current),hc.current=window.setTimeout(()=>{hc.current=null,Aa(X)},250)))},[Ko,K,Aa]);CC({enabled:Em,workspaceId:Ko,websocketUrl:wc,onSignal:Nm,userId:ls||void 0}),NE({workspaceId:ft,isOpen:ne,authBlocked:ot,authRequiredForApi:ur,isAuthenticated:Ve,canCallProtectedApi:Sr.canCallProtectedApi,shouldGateProtectedApiCalls:ae,authSessionResolvedRef:Jd,authRequiredForApiRef:gc,isAuthenticatedRef:Qd,dataVersionRef:Hg,refreshTaskCollectionsForDataVersion:Pp,coordinatorDataVersion:en});const Fi=o.useMemo(()=>{const I=new Map;for(const X of ln)I.set(X.id,X);for(const X of pa)I.set(X.id,X);return Array.from(I.values())},[pa,ln]),Ui=o.useMemo(()=>ra.map(I=>({...I.taskSnapshot,isDeleted:!0,deletedRecordId:I.id})),[ra]);o.useEffect(()=>{if(!(va||Ya)&&ne&&!tr){if(Pe==="tasks"){const I=`${ft}:${Pe}:${pe?"archive":"active"}:${Ce}`,X=pe||Ce==="archived",re=Ce==="deleted";if(!bm.current){bm.current=!0,yc.current=I,X&&Ts(!1),re&&wo(!1);return}if(yc.current===I)return;yc.current=I,!X&&!re&&Dn(),Vr(),X&&Ts(!1),re&&wo(!1);return}if(Pe==="settings"){const I=`${ft}:${Pe}:${xe}`;if(Mi.current===I)return;Mi.current=I,cs()}}},[ft,ne,Pe,xe,pe,Ce,Dn,Vr,Ts,wo,cs,va,Ya,tr]);const Ep=o.useCallback(async(I="")=>{try{const X=await fetch(`/api/taskforce/folders?path=${encodeURIComponent(I)}`);if(X.ok){const re=await X.json();qe(re.folders||[]),fe(re.files||[]),$e(I)}}catch(X){console.error("[Taskforce] Failed to fetch folders:",X)}},[]),so=o.useCallback(I=>{const X=[];if(I.path&&X.push(I.path),I.paths&&I.paths.length>0)for(const re of I.paths)X.includes(re)||X.push(re);return X},[]),{validatePaths:Mm,handleUpdateCategory:oo,handleSaveCategory:Np,handleAddPath:Mp,handleUpdateCategoryIcon:al,handleUpdateCategoryColor:iu,handleRemovePath:nl,handleSelectPath:uy,handleRemoveCategory:bc,handleSaveType:Dp,handleRemoveType:Lp,handleUpdateType:Zl,handleUpdateTaxonomies:Op,handleUpdatePriorities:Dm,analyzeSystemTaxonomyPack:py,handleApplySystemTaxonomyPack:fy}=$2({activeCategories:jr,activeTab:Pe,activeTypes:dn,archivedTasks:ln,browserTarget:rt,category:Bc,configLoaded:na,customCategories:rs,refreshTaskCollections:D,fetchTasks:Dn,filterCategories:Vd,getCategoryPaths:so,normalizePath:es,pathValidation:yo,setBrowserTarget:kt,setCategory:Ri,setCustomCategories:Un,setCustomTypes:Ii,setFilterCategories:sp,setPathValidation:Bo,setPriorities:ba,setShowFolderBrowser:Xe,setTaxonomies:Cs,tasks:pa}),Lm=o.useCallback(async I=>{const X=_n,re={...X,...I};Wo(re);try{const J=await fetch("/api/taskforce/taxonomy-display-labels",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({displayLabels:I})});if(!J.ok)throw new Error(`Failed to save taxonomy display labels (${J.status})`);const Fe=await J.json().catch(()=>({}));Fe?.displayLabels&&typeof Fe.displayLabels=="object"&&Wo({...re,...Fe.displayLabels})}catch(J){console.error("[Taskforce] Failed to update taxonomy display labels",J),Wo(X)}},[_n]),sl=o.useCallback(I=>{Pe==="tasks"&&Ra.current&&Xn(Ra.current.scrollTop),ue(I)},[Pe]),Om=o.useRef(async()=>!0),{handleNavigation:my,handleClose:hy,resetForm:Jl,resolveWorkstreamIdInput:ol,handleEdit:To,handleOpenTaskById:il,returnToPreviousTask:io,clearReturnToParentTask:Sc}=q2({activeCategories:jr,activeTypes:dn,activeTab:Pe,attachments:Hc,checklistItems:Ws,comments:zo,description:bo,editingTaskId:aa,flushPendingAutoSave:()=>Om.current(),getDescriptionDraft:ap,getPreferredCategoryValue:Xa,getTitleDraft:Gd,lastUsedCategory:Ho,newCommentText:Dl,relationshipTasks:Fi,workstreams:Va,showArchive:pe,taxonomies:_a,setActiveTab:sl,setAssignee:jl,setAttachments:Yd,setAttachmentsDirty:gp,setCategory:Ri,setChecklistItems:Nl,setComments:Ml,setComplexity:nm,setDescription:im,setDueDate:Hd,setEditingTaskId:Ds,setError:Tn,setFormTaxonomies:hi,setIsOpen:Me,setNewCommentText:Ll,setPendingNavigation:Jn,setWorkstreamInput:om,setPriority:Ud,setScheduledDate:zd,setShowArchive:le,setStatus:sm,setTaskReturnTrail:bn,setTitle:El,setType:xl,setUnsavedModalOpen:vs,taskReturnTrail:cn,title:ji});o.useEffect(()=>{const I=String(Mn||"").trim();if(!Bi||!I)return;if(aa===I){Ls(null);return}if(Sa||tr)return;const X=tt=>tt.id===I||tt.id.endsWith(I);if(Fi.find(X)){il(I),Ls(null);return}const J=String(ut.current||"default").trim()||"default",Fe=`${J}:${I}`;if(Qa!==J&&!Nn.has(Fe)){Ts(!0).finally(()=>{(String(ut.current||"default").trim()||"default")===J&&bs(Gt=>Gt.has(Fe)?Gt:new Set(Gt).add(Fe))});return}const et=Ui.find(X);if(et){To(et),Ls(null);return}if(Cn!==J){wo(!0);return}Ls(null)},[Qa,Nn,Cn,Ui,aa,Ts,wo,To,il,Sa,Mn,Fi,Bi,tr]),o.useEffect(()=>{const I=String(t||"").trim();if(!I||!un||Qc.current===un||!E||!na||!Bi||Sa||tr)return;const X=String(n||"").trim(),re=String(ut.current||"default").trim()||"default",J=()=>{const cr=Xc.current;cr&&Qn.current?.ownerKey===cr&&Ja(),Xc.current=null};if(X&&X!==re){if(Io.current===un)return;if(K!=="cloud"||!Mt){Io.current!==un&&(Io.current=un,vr("This task is unavailable or you do not have access to it.","info",12e3));return}if(!Lt||!Ve||ot||Wi.current===un||Us.current!==null)return;const cr=un,Dr=`${cr}:workspace`;Wi.current=cr,Fs(X).then(Wr=>{if(vc.current===cr&&!Wr.success){const Er=(rl.current.get(Dr)||0)+1;if(rl.current.set(Dr,Er),Er<2&&typeof window<"u"){Us.current=window.setTimeout(()=>{Us.current=null,vc.current===cr&&$i(Rs=>Rs+1)},500);return}Io.current=cr;const Ua=`deep-link-workspace:${cr}`;Xc.current=Ua,vr("This task is unavailable or you do not have access to it.","info",12e3,{label:"Retry",onAction:()=>{vc.current===cr&&(Xc.current=null,Io.current=null,rl.current.delete(Dr),Ja(),$i(Rs=>Rs+1))},ownerKey:Ua})}}).finally(()=>{Wi.current===cr&&(Wi.current=null)});return}const Fe=cr=>{const Dr=cr.find(Er=>Er.id===I);if(Dr||X)return Dr;const Wr=cr.filter(Er=>Er.id.endsWith(I));return Wr.length===1?Wr[0]:void 0},et=Fe(Fi);if(et){J(),Qc.current=un,Io.current=null,aa!==et.id&&(et.isArchived&&le(!0),To(et));return}const tt=(cr,Dr,Wr)=>{const Er=`${un}:${cr}`;if(no.current===Er||_o.current!==null)return;no.current=Er;const Ua=un;Dr().then(Rs=>{if(vc.current!==Ua)return;if(Rs){$i(zs=>zs+1);return}const gn=(rl.current.get(Er)||0)+1;if(rl.current.set(Er,gn),gn>=2){Wr.add(Ua),$i(zs=>zs+1);return}typeof window<"u"&&(_o.current=window.setTimeout(()=>{_o.current=null,vc.current===Ua&&$i(zs=>zs+1)},500))}).finally(()=>{no.current===Er&&(no.current=null)})};if(Qa!==re&&!el.current.has(un)){tt("archive",()=>Ts(!0),el.current);return}const Gt=Fe(Ui);if(Gt){J(),Qc.current=un,Io.current=null,To(Gt);return}if(Cn!==re&&!tl.current.has(un)){tt("deleted",()=>wo(!0),tl.current);return}Io.current!==un&&(Io.current=un,vr("This task is unavailable or you do not have access to it.","info",12e3))},[Qa,ot,Lt,Ja,na,ut,dy,un,Cn,Ui,aa,Ts,wo,To,t,Ve,Sa,vr,Fi,n,E,K,le,Fs,Bi,tr,Mt]);const Ql=UE({enabled:w.syncV3TaskMetadataActivation&&K==="local",workspaceId:ft,isAuthenticated:Ve,dispatchEnabled:Rn}),gy=XE({localRuntime:K==="local",enabled:w.syncV3TaskCreateActivation&&K==="local",workspaceId:ft,isAuthenticated:Ve,dispatchEnabled:Rn}),Bm=w.syncV3TaskStatusActivation&&K==="local",yy=cN({enabled:Bm,workspaceId:ft,isAuthenticated:Ve,dispatchEnabled:Rn}),Wm=pN({enabled:K==="local",workspaceId:ft,isAuthenticated:Ve,dispatchEnabled:Rn}),$m=w.syncV3TaskDeleteActivation&&K==="local",cu=hN({enabled:$m,workspaceId:ft,isAuthenticated:Ve,dispatchEnabled:Rn}),Fm=kN({enabled:$m,workspaceId:ft,isAuthenticated:Ve,dispatchEnabled:Rn}),{copiedId:ky,handleDelete:Xl,handleUpdateTask:Ac,handleSetStatus:vy,handleToggleComplete:qo,handleToggleCancel:Bp,handleToggleInProgress:lu,handleToggleReview:Wp,handleArchiveTask:du,handleBulkArchive:zi,handleUnarchive:wy,handleRestoreDeletedTask:by,handleRestoreSelectedDeletedTasks:Sy,handlePermanentlyDeleteDeletedTask:Ay,handleEmptyDeletedTasks:Cy,handleCopyId:xo,queueWorkspaceSyncFromAuthoritativeTaskState:Um}=bE({tasks:pa,archivedTasks:ln,editingTaskId:aa,setTasks:Sn,setArchivedTasks:An,setDeletedTasks:Fn,setError:Tn,resetForm:Jl,setActiveTab:sl,fetchTasks:Dn,fetchArchive:wl,fetchDeletedTasks:bl,mergeTaskFromServer:Dc,pushNotice:vr,cloudAuthConfigured:q,runtimeMode:K,isAuthenticated:Ve,workspaceCloudSyncEnabled:Rn,buildWorkspaceSyncSignature:rm,pushWorkspaceChangesToCloud:Ju,workspacePendingSignatureRef:Xf,workspaceDeletedTaskIdsRef:em,workspaceDeletedTaskWatermarksRef:Bd,mutateTaskMetadata:Ql,mutateTaskStatus:yy,mutateTaskLifecycle:Wm,mutateTaskDelete:cu,mutateTaskRestore:Fm,durableTaskMetadataActivationEnabled:w.syncV3TaskMetadataActivation&&K==="local",durableTaskStatusActivationEnabled:Bm,durableTaskDeleteActivationEnabled:$m,durableTaskHttpRootActivationEnabled:w.syncV3TaskCloudHttpRootActivation,workspaceId:ft}),ed=o.useCallback(async()=>{const I=Zd.current;if(!(await fetch("/api/taskforce/context-upload/draft/promote",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:ft,draftUploadId:I,uploadPurpose:"task-description-draft"})})).ok)throw new Error("Task was created, but its draft upload records could not be finalized.");Vc()},[ft,Vc]),{autoSaveState:ki,flushAutoSave:zm,scheduleWarningPrompt:$p,handleSubmit:Fp,confirmScheduleWarning:Hm,cancelScheduleWarning:Iy,handleAddComment:td}=mE({activeCategories:jr,activeTab:Pe,apiEndpoint:f,assignee:Wc,attachments:Hc,attachmentsDirty:wm,category:Bc,checklistItems:Ws,comments:zo,complexity:ep,description:bo,dueDate:lc,createTaskDurably:gy,durableTaskHttpRootActivationEnabled:w.syncV3TaskCloudHttpRootActivation,workspaceId:ft,updateTask:Ac,editingTaskId:aa,fetchTasks:Dn,formTaxonomies:Ol,getAttachmentsDraft:km,getDescriptionDraft:ap,getPreferredCategoryValue:Xa,getTitleDraft:Gd,awaitPendingDescriptionImageUpload:Vo,onTaskCreateAccepted:ed,mergeTaskFromServer:Dc,onTaskCreated:To,workstreamInput:Pl,priority:Xu,pushNotice:vr,queueWorkspaceSyncFromAuthoritativeTaskState:Um,relationshipTasks:Fi,supplementalTasks:Ui,resetForm:Jl,resolveWorkstreamIdInput:ol,scheduledDate:pi,setActiveTab:sl,setAttachmentsDirty:gp,setComments:Ml,setError:Tn,setLastUsedCategory:Cr,setLoading:Md,setNewCommentText:Ll,status:Rl,title:ji,taxonomies:_a,textDraftOccupied:tp,type:Tl}),Cc=o.useCallback(async()=>{const I=Zd.current;Vc();try{if(await Vo(),!(await fetch("/api/taskforce/context-upload/draft/discard",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:ft,draftUploadId:I,uploadPurpose:"task-description-draft"})})).ok)throw new Error("Draft upload cleanup was rejected.")}catch(X){console.warn("[Taskforce] Failed to clean discarded Description image uploads.",X)}},[Vo,ft,Vc]);o.useEffect(()=>{Om.current=zm},[zm]);const{handleSetWorkstreamForCurrentTask:uu}=hE({editingTaskId:aa,workstreamInput:Pl,pushNotice:vr,relationshipTasks:Fi,resolveWorkstreamIdInput:ol,setError:Tn,updateTask:Ac}),{currentTask:Up,currentTaskWorkstream:rd,currentTaskInitiative:pu}=H2({editingTaskId:aa,relationshipTasks:Fi,initiatives:ws,workstreams:Va,workstreamInput:Pl,resolveWorkstreamIdInput:ol,supplementalTasks:Ui,assignee:Wc,setAssignee:jl,setChecklistItems:Nl,setComments:Ml}),_y=B2({resolveCloudAuthUrl:H,currentWorkspaceId:ft,normalizedCloudAuthBaseUrl:ge,normalizedCloudMcpBaseUrl:Ae,mergedConfig:l,availableWorkspaces:u,currentTheme:_e,configLoaded:na,globalTheme:Ze,themeUseGlobalDefault:at,keyShortcut:or,jsonBackupEnabled:ho,globalJsonBackupEnabled:Bn,globalWeekStartsOn:$n,locale:Vs,supportedLocales:ys,jsonBackupUseGlobalDefault:Ta,manualComplexityEnabled:fn,checklistDropdownEnabled:ks,showTaskCardStatusLabel:mn,pathSaved:G,settingsSection:xe,setupState:Ar,buildInfo:wa,saveSetupMode:nu,saveWorkspaceProfile:_m,setCurrentTheme:ke,handleSaveTheme:kp,handleSaveGlobalTheme:vp,setKeyShortcut:Tr,handleJsonBackupEnabledChange:Yc,handleSaveGlobalJsonBackupEnabled:Gg,handleSaveGlobalWeekStartsOn:wp,handleSaveLocale:Xd,handleManualComplexityEnabledChange:Sm,handleChecklistDropdownEnabledChange:Am,handleShowTaskCardStatusLabelChange:Vg,handleResetProjectToGlobal:Kg,handleSaveSettings:qc,initiativeTemplates:hr,fetchInitiativeTemplates:ga,createInitiativeFromTemplate:kc,setShowFolderBrowser:Xe,setBrowserTarget:kt,fetchFolders:Ep,activeCategories:jr,pathValidation:yo,taxonomyDisplayLabels:_n,handleUpdateCategory:oo,handleRemoveCategory:bc,handleSaveCategory:Np,handleAddPath:Mp,handleRemovePath:nl,handleUpdateCategoryIcon:al,handleUpdateCategoryColor:iu,activeTypes:dn,handleSaveType:Dp,handleRemoveType:Lp,handleUpdateType:Zl,taxonomies:_a,handleUpdateTaxonomies:Op,priorities:ha,handleUpdatePriorities:Dm,analyzeSystemTaxonomyPack:py,handleApplySystemTaxonomyPack:fy,handleUpdateTaxonomyDisplayLabels:Lm,projectRoot:jt,projectName:Ke,mcpHostRoot:nn,serverHostRoot:Zn,mcpScriptPath:At,tenantId:Bt,runtimeMode:K,workspaceSwitchingEnabled:Mt,deleteWorkspace:Ap,setMcpHostRoot:kr,isAuthenticated:Ve});o.useEffect(()=>{typeof window<"u"&&(window.__TASKFORCE_DEBUG__={tasks:pa,archivedTasks:ln,runtimeMode:K,currentWorkspaceId:ft,isAuthenticated:Ve,workspaceCloudSyncEnabled:Rn,realtimeSyncEnabled:mt,fetchTasks:Dn,fetchArchive:Os,retryWorkspaceCloudSync:$d,resetWorkspaceSyncCursorAndPull:Il,getSyncDiagnostics:Fd,__dispatch:{handleUpdateTask:Ac,handleToggleComplete:qo,handleArchiveTask:du,handleToggleCancel:Bp,handleToggleInProgress:lu,handleToggleReview:Wp,handleSubmit:Fp,handleDelete:Xl}})},[pa,ln,K,ft,Ve,Rn,mt,Dn,Os,$d,Il,Fd,Ac,qo,du,Bp,lu,Wp,Fp,Xl]);const Gm=La&&La.tone!=="error"?{message:La.message,type:"info"}:null,Vm=String(y||w.wsBaseUrl||ce||"").trim().replace(/\/+$/,"");return{config:{...l,cloudEnvironment:w.cloudEnvironment||l.cloudEnvironment||"",apiBaseUrl:ce||l.apiBaseUrl,cloudAuthBaseUrl:ge||l.cloudAuthBaseUrl,wsBaseUrl:Vm||l.wsBaseUrl},isOpen:ne,setIsOpen:Me,activeTab:Pe,setActiveTab:sl,currentTheme:_e,setCurrentTheme:ke,configLoaded:na,storagePath:We,saveSettings:qc,pathSaved:G,keyShortcut:or,setKeyShortcut:Tr,globalWeekStartsOn:$n,locale:Vs,supportedLocales:ys,saveLocale:Xd,jsonBackupEnabled:ho,setJsonBackupEnabled:wn,manualComplexityEnabled:fn,checklistDropdownEnabled:ks,showTaskCardStatusLabel:mn,setManualComplexityEnabled:xa,mcpHostRoot:nn,setMcpHostRoot:kr,settingsSection:xe,setSettingsSection:St,runtimeMode:K,workspaceMode:nt,workspaceSwitchingEnabled:Mt,cloudAuthConfigured:q,authRequiredForApi:ur,authBlocked:ot,isAuthenticated:Ve,authUserId:It,authUserEmail:qt,authUserDisplayName:_t,authUserAvatarUrl:Rr,authWorkspaceId:$t,userGlobalSyncStatus:di,workspaceLastPullAt:oc,workspaceLastPushAt:Sl,workspaceLastErrorAt:ic,userGlobalSyncError:Fo,workspaceLastErrorMessage:Yu,workspaceLastSuccessfulSyncAt:cc,workspaceSyncPhase:ui,workspaceSyncSetupIntent:Lc,workspaceSyncStatus:Al,workspaceSyncSummary:Oc,workspaceSyncRecommendedAction:Cl,workspaceSyncBusy:Bg,workspaceSyncPendingChanges:xi,localCoordinatorStatus:Ba,transferLocalCoordinatorOwnership:Qf,retryUserGlobalSettingsSync:Qu,retryWorkspaceCloudSync:$d,resetWorkspaceSyncCursorAndPull:Il,getWorkspaceSyncDiagnostics:Fd,hasBetaAccess:sa,realtimeSyncEnabled:mt,realtimeSyncFlagSource:Ht,currentWorkspaceId:ft,currentWorkspaceRole:Yg,availableWorkspaces:u,assigneeOptions:pr,workspaceCloudSyncEnabled:Rn,saveWorkspaceCloudSyncSettings:am,applyWorkspaceSyncStateSnapshot:tm,bootstrapState:In,authSessionResolved:Lt,workspaceBootstrapPending:tr,bootstrapPhase:Ir,bootstrapError:Jr,bootstrapStartedAt:nr,setupState:Ar,runtimeCapabilities:me,refreshSetupContext:Jc,retryBootstrapChecks:Sp,continueAfterCommercialOnboarding:ru,saveWorkspaceProfile:_m,fetchWorkspaces:Zc,createWorkspace:au,deleteWorkspace:Ap,switchWorkspace:Fs,loginWithCredentials:Cp,beginOAuthLogin:Zg,availableAuthProviders:Tt,fetchLoginMethods:_p,unlinkLoginMethod:Rm,addPasswordToAccount:su,changePassword:ty,beginOAuthLink:Tp,registerWithCredentials:ql,updateCurrentUserProfile:Jg,requestEmailVerification:ro,confirmEmailVerification:Qg,requestPasswordReset:Tm,confirmPasswordReset:Ip,inspectInviteAcceptance:Xg,acceptInviteWithToken:ey,joinInviteWithToken:xm,logout:ry,showFolderBrowser:Be,setShowFolderBrowser:Xe,folders:ze,files:Te,currentBrowsePath:Ee,fetchFolders:Ep,browserTarget:rt,setBrowserTarget:kt,groupBy:Go,setGroupBy:Ni,activeWorkspaceModule:mc,setActiveWorkspaceModule:Oi,emptyColumnMode:Kd,setEmptyColumnMode:zl,zenMode:ia,setZenMode:Ys,handleSelectPath:uy,handleAddPath:Mp,handleRemovePath:nl,tasks:pa,loadingTasks:Sa,archivedTasks:ln,archiveHydratedWorkspaceId:Qa,initiatives:ws,workstreams:Va,planningBootstrapTaskSummaries:yt,planningLoadState:gr,workspaceTaskRelationships:Od,deletedTasks:ra,activeCategories:jr,activeTypes:dn,priorities:ha,taxonomyDisplayLabels:_n,taxonomies:_a,searchQuery:Bl,setSearchQuery:lm,filterCategories:Vd,setFilterCategories:sp,filterTypes:$c,setFilterTypes:$l,filterPriorities:Wl,setFilterPriorities:Ei,filterStatus:op,setFilterStatus:ip,filterAssignees:So,setFilterAssignees:dm,filterTaxonomies:fc,setFilterTaxonomies:Fl,hasInitedFilters:$g,sortBy:Ul,setSortBy:is,sortOrder:yi,setSortOrder:pm,toggleSortOrder:Fg,showArchive:pe,setShowArchive:le,taskScope:Ce,setTaskScope:P,compressedCards:ee,setCompressedCards:Se,clearFilters:fm,filteredTasks:Fc,searchAgnosticTasks:Uc,filteredArchive:up,groupedTasks:mm,collapsedCategories:lp,setCollapsedCategories:dp,fetchTasks:Dn,fetchArchive:Os,ensureArchiveHydrated:Ts,fetchDeletedTasks:ss,fetchPlanningEntities:Vr,fetchPlanningEntityDetail:Dd,fetchAssigneeOptions:eu,createInitiative:ay,updateInitiative:ny,updatePlanningIdentity:Pm,archiveInitiative:sy,unarchiveInitiative:oy,createWorkstream:iy,updateWorkstream:cy,archiveWorkstream:jn,unarchiveWorkstream:xp,reorderWorkstreamTasks:ly,handleEdit:To,handleDelete:Xl,handleCopyId:xo,handleToggleComplete:qo,handleToggleCancel:Bp,handleToggleInProgress:lu,handleToggleReview:Wp,handleArchiveTask:du,handleBulkArchive:zi,handleUnarchive:wy,handleRestoreDeletedTask:by,handleRestoreSelectedDeletedTasks:Sy,handlePermanentlyDeleteDeletedTask:Ay,handleEmptyDeletedTasks:Cy,handleUpdateTask:Ac,handleSetStatus:vy,editingTaskId:aa,loading:Is,error:kl,clearTaskError:_i,title:ji,setTitle:El,setTitleDraft:dc,description:bo,setDescription:im,setDescriptionDraft:mi,checklistItems:Ws,setChecklistItems:Nl,category:Bc,setCategory:Ri,type:Tl,setType:xl,priority:Xu,setPriority:Ud,complexity:ep,setComplexity:nm,status:Rl,setStatus:sm,assignee:Wc,setAssignee:jl,scheduledDate:pi,setScheduledDate:zd,dueDate:lc,setDueDate:Hd,workstreamInput:Pl,setWorkstreamInput:om,formTaxonomies:Ol,setFormTaxonomies:hi,comments:zo,newCommentText:Dl,setNewCommentText:Ll,attachments:Hc,setAttachments:Yd,attachmentsDirty:wm,setAttachmentsDirty:gp,descriptionImageUploadPending:Ug,descriptionImageDraftId:zg,registerDescriptionImageUpload:vm,descriptionFocused:pp,setDescriptionFocused:Ut,showMarkdownHelp:go,setShowMarkdownHelp:ts,isCapturingScreenshot:gm,setIsCapturingScreenshot:fp,handleSubmit:Fp,resetForm:Jl,discardDescriptionImageDraft:Cc,handleAddComment:td,handleSetWorkstreamForCurrentTask:uu,handleOpenTaskById:il,returnToPreviousTask:io,autoSaveState:ki,unsavedModalOpen:ca,setUnsavedModalOpen:vs,pendingNavigation:Fa,handleNavigation:my,handleClose:hy,uiNotice:La,pushNotice:vr,clearNotice:Ja,successBanner:Gm,taskReturnTrail:cn,clearReturnToParentTask:Sc,copiedId:ky,recentlyChangedTaskIds:ci,scheduleWarningPrompt:$p,confirmScheduleWarning:Hm,cancelScheduleWarning:Iy,tasksScrollRef:Ra,setTasksScrollPos:Xn,taskforceAgentId:np,setTaskforceAgentId:to,taskforceAgentConversationId:uc,setTaskforceAgentConversationId:Pi,taskforceAgentConversationByAgentId:pc,setTaskforceAgentConversationByAgentId:cm,uiStateReady:Bi,handleUpdateCategory:oo,handleRemoveCategory:bc,handleSaveCategory:Np,handleUpdateCategoryIcon:al,handleUpdateCategoryColor:iu,handleSaveType:Dp,handleRemoveType:Lp,handleUpdateType:Zl,handleUpdateTaxonomies:Op,handleUpdatePriorities:Dm,handleUpdateTaxonomyDisplayLabels:Lm,pathValidation:yo,validatePaths:Mm,getCategoryPaths:so,customCategories:rs,setCustomCategories:Un,projectRoot:jt,projectName:Ke,mcpScriptPath:At,serverHostRoot:Zn,commentsEndRef:gi,currentTask:Up,currentTaskWorkstream:rd,currentTaskInitiative:pu,initiativeTemplates:hr,fetchInitiativeTemplates:ga,createInitiativeFromTemplate:kc,settingsModel:_y}}const jN="modulepreload",PN=function(e){return"/taskforce/"+e},uS={},Lo=function(t,r,n){let s=Promise.resolve();if(r&&r.length>0){let d=function(f){return Promise.all(f.map(p=>Promise.resolve(p).then(g=>({status:"fulfilled",value:g}),g=>({status:"rejected",reason:g}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=l?.nonce||l?.getAttribute("nonce");s=d(r.map(f=>{if(f=PN(f),f in uS)return;uS[f]=!0;const p=f.endsWith(".css"),g=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${f}"]${g}`))return;const h=document.createElement("link");if(h.rel=p?"stylesheet":jN,p||(h.as="script"),h.crossOrigin="",h.href=f,c&&h.setAttribute("nonce",c),document.head.appendChild(h),p)return new Promise((y,k)=>{h.addEventListener("load",y),h.addEventListener("error",()=>k(new Error(`Unable to preload CSS for ${f}`)))})}))}function i(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return s.then(l=>{for(const c of l||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})},EN="_filterGlow_t3a2j_8",NN="_floatingButton_t3a2j_18",MN="_badge_t3a2j_49",DN="_configBadge_t3a2j_66",LN="_configBadgeActive_t3a2j_76",ON="_configBadgeRevoked_t3a2j_82",BN="_configBadgeExpired_t3a2j_88",WN="_coreModal_t3a2j_97",$N="_header_t3a2j_103",FN="_headerTitle_t3a2j_118",UN="_brandIcon_t3a2j_136",zN="_brandHomeButton_t3a2j_142",HN="_brandHomeStatic_t3a2j_143",GN="_brandCloudSuffix_t3a2j_169",VN="_projectSlash_t3a2j_174",KN="_projectNameGroup_t3a2j_181",qN="_projectNameGroupHidden_t3a2j_188",YN="_projectName_t3a2j_181",ZN="_taskCountBadge_t3a2j_215",JN="_taskCountBadgeIcon_t3a2j_232",QN="_taskCountBadgeButton_t3a2j_236",XN="_taskCountBadgeActive_t3a2j_254",e1="_taskCountBadgeAlert_t3a2j_260",t1="_headerActions_t3a2j_266",r1="_sortDirectionBtn_t3a2j_273",a1="_sortDirectionBtnWidget_t3a2j_280",n1="_form_t3a2j_288",s1="_topRow_t3a2j_300",o1="_field_t3a2j_306",i1="_labelRow_t3a2j_312",c1="_label_t3a2j_312",l1="_manageLink_t3a2j_326",d1="_input_t3a2j_345",u1="_select_t3a2j_346",p1="_textarea_t3a2j_347",f1="_taskIdInlineLink_t3a2j_381",m1="_readOnly_t3a2j_400",h1="_selectWithConfig_t3a2j_408",g1="_configBtn_t3a2j_418",y1="_configBtnActive_t3a2j_448",k1="_hasPath_t3a2j_456",v1="_pathIndicator_t3a2j_461",w1="_formActions_t3a2j_467",b1="_hasCancel_t3a2j_474",S1="_submitBtn_t3a2j_478",A1="_cancelBtn_t3a2j_494",C1="_successMessage_t3a2j_526",I1="_errorMessage_t3a2j_532",_1="_successIcon_t3a2j_544",T1="_spinner_t3a2j_564",x1="_spin_t3a2j_564",R1="_boardRefreshIndicator_t3a2j_568",j1="_destructiveBtn_t3a2j_598",P1="_warningBtn_t3a2j_621",E1="_viewTab_t3a2j_644",N1="_loading_t3a2j_655",M1="_emptyState_t3a2j_661",D1="_taskList_t3a2j_671",L1="_referenceBadge_t3a2j_677",O1="_referenceBadgeLabel_t3a2j_698",B1="_referenceBadgeStatic_t3a2j_707",W1="_provisionalReferenceBadge_t3a2j_721",$1="_copiedReference_t3a2j_743",F1="_highlight_t3a2j_755",U1="_modal_t3a2j_767",z1="_priorityEmoji_t3a2j_775",H1="_metaItem_t3a2j_779",G1="_taskFormDateInput_t3a2j_793",V1="_metaBadge_t3a2j_803",K1="_complexityPill_t3a2j_818",q1="_complexityDots_t3a2j_822",Y1="_dot_t3a2j_828",Z1="_dotFilled_t3a2j_836",J1="_typePill_t3a2j_842",Q1="_type_bug_t3a2j_846",X1="_type_feature_t3a2j_850",eM="_type_chore_t3a2j_854",tM="_type_refactor_t3a2j_858",rM="_type_documentation_t3a2j_862",aM="_type_research_t3a2j_866",nM="_type_security_t3a2j_874",sM="_statusActionsGroup_t3a2j_878",oM="_statusActionsGroupCompact_t3a2j_884",iM="_statusSelectWrap_t3a2j_888",cM="_statusTaxonomyDropdownWrap_t3a2j_894",lM="_statusTaxonomyDropdown_t3a2j_894",dM="_statusTaxonomyDropdownCompact_t3a2j_902",uM="_statusTaxonomyDropdownIconOnly_t3a2j_906",pM="_taxonomyDropdownButton_t3a2j_911",fM="_taxonomyDropdownButtonContent_t3a2j_928",mM="_statusTaxonomyDropdownIconOnlyPanel_t3a2j_932",hM="_actionBtn_t3a2j_938",gM="_restoreTaskBtn_t3a2j_962",yM="_startWorkBtn_t3a2j_971",kM="_workingBtn_t3a2j_980",vM="_pulse_t3a2j_1",wM="_reviewBtn_t3a2j_986",bM="_reviewActiveBtn_t3a2j_996",SM="_reviewPill_t3a2j_1002",AM="_bulkArchiveBtn_t3a2j_1009",CM="_bulkDeleteBtn_t3a2j_1031",IM="_deleteBtn_t3a2j_1060",_M="_completeBtn_t3a2j_1072",TM="_completeActiveBtn_t3a2j_1082",xM="_deleteActiveBtn_t3a2j_1088",RM="_disabledBtn_t3a2j_1094",jM="_archiveList_t3a2j_1101",PM="_archiveHeader_t3a2j_1109",EM="_settingsTab_t3a2j_1120",NM="_settingsTabMcpOnly_t3a2j_1129",MM="_settingsTabs_t3a2j_1138",DM="_settingsLayout_t3a2j_1152",LM="_settingsLayoutMcpOnly_t3a2j_1159",OM="_settingsSidebar_t3a2j_1165",BM="_settingsSidebarHeader_t3a2j_1175",WM="_settingsSidebarNav_t3a2j_1184",$M="_settingsSidebarBtn_t3a2j_1193",FM="_settingsSidebarBtnActive_t3a2j_1217",UM="_settingsSidebarGroup_t3a2j_1224",zM="_settingsSidebarGroupBtn_t3a2j_1230",HM="_settingsSidebarGroupLabel_t3a2j_1234",GM="_settingsSidebarGroupChevron_t3a2j_1238",VM="_settingsSidebarSubnav_t3a2j_1244",KM="_settingsSidebarSubBtn_t3a2j_1251",qM="_appScrollbar_t3a2j_1274",YM="_settingsTabBtn_t3a2j_1278",ZM="_settingsTabBtnActive_t3a2j_1304",JM="_settingsContent_t3a2j_1310",QM="_mcpRegistrationHint_t3a2j_1336",XM="_mcpRegistrationPrompt_t3a2j_1347",eD="_mcpCodexTrustNote_t3a2j_1366",tD="_mcpCodexTrustHeader_t3a2j_1377",rD="_mcpCodexTrustTitle_t3a2j_1384",aD="_mcpCodexTrustCode_t3a2j_1390",nD="_mcpAuthRequiredCard_t3a2j_1405",sD="_mcpAuthRequiredIcon_t3a2j_1417",oD="_mcpAuthRequiredBody_t3a2j_1430",iD="_mcpAuthRequiredActions_t3a2j_1437",cD="_settingsToast_t3a2j_1481",lD="_settingsToastSuccess_t3a2j_1498",dD="_settingsToastError_t3a2j_1504",uD="_inputWithPrefix_t3a2j_1510",pD="_pathHint_t3a2j_1517",fD="_settingGroup_t3a2j_1530",mD="_settingTitle_t3a2j_1536",hD="_settingTitleRow_t3a2j_1545",gD="_settingTitleActionBtn_t3a2j_1552",yD="_themeOptions_t3a2j_1572",kD="_buttonGrid_t3a2j_1577",vD="_themeBtn_t3a2j_1589",wD="_activeTheme_t3a2j_1613",bD="_pathInputGroup_t3a2j_1621",SD="_saveSettingsBtn_t3a2j_1630",AD="_shortcutInputWrapper_t3a2j_1651",CD="_inputIcon_t3a2j_1656",ID="_settingHelper_t3a2j_1665",_D="_browseBtn_t3a2j_1672",TD="_inlineCategoryManager_t3a2j_1691",xD="_categoryManager_t3a2j_1702",RD="_categoryList_t3a2j_1708",jD="_categoryChip_t3a2j_1720",PD="_categoryChipLabel_t3a2j_1733",ED="_chipActionBtn_t3a2j_1741",ND="_removeCategoryBtn_t3a2j_1761",MD="_addCategoryForm_t3a2j_1781",DD="_addCategoryBtn_t3a2j_1786",LD="_filesList_t3a2j_1811",OD="_helpLink_t3a2j_1838",BD="_taskChildrenSummaryBadges_t3a2j_1857",WD="_taskChildrenProgressBar_t3a2j_1865",$D="_taskChildrenProgressBarSegmentDone_t3a2j_1876",FD="_taskChildrenProgressBarSegmentReview_t3a2j_1882",UD="_taskChildrenProgressBarSegmentInProgress_t3a2j_1888",zD="_taskChildrenProgressBarSegmentBlocked_t3a2j_1894",HD="_taskChildrenProgressText_t3a2j_1900",GD="_taskChildUnlinkBtn_t3a2j_1909",VD="_aboutText_t3a2j_1927",KD="_versionInfo_t3a2j_1934",qD="_filterBar_t3a2j_1942",YD="_kanbanHintText_t3a2j_1956",ZD="_searchContainer_t3a2j_1962",JD="_searchIcon_t3a2j_1969",QD="_searchInput_t3a2j_1977",XD="_searchActive_t3a2j_2003",eL="_searchCount_t3a2j_2008",tL="_clearSearchBtn_t3a2j_2024",rL="_filterRow_t3a2j_2046",aL="_sortLabel_t3a2j_2052",nL="_archiveToggle_t3a2j_2060",sL="_filterContainer_t3a2j_2097",oL="_filterButton_t3a2j_2102",iL="_filterActive_t3a2j_2127",cL="_filterDropdown_t3a2j_2133",lL="_filterSearch_t3a2j_2148",dL="_filterSearchIcon_t3a2j_2156",uL="_filterSearchInput_t3a2j_2165",pL="_filterEmpty_t3a2j_2177",fL="_filterOption_t3a2j_2184",mL="_filterDivider_t3a2j_2214",hL="_filterSelect_t3a2j_2220",gL="_filterToggleBtn_t3a2j_2261",yL="_inProgressToggle_t3a2j_2283",kL="_activeInProgress_t3a2j_2301",vL="_activeFilter_t3a2j_2310",wL="_resetFiltersBtn_t3a2j_2320",bL="_categoryChip_disabled_t3a2j_2353",SL="_categoryVisibilityToggle_t3a2j_2363",AL="_editCategoryInput_t3a2j_2376",CL="_categoryChipActionBtn_t3a2j_2387",IL="_categoryChipActionBtn_active_t3a2j_2405",_L="_categoryGroup_t3a2j_2410",TL="_categoryHeader_t3a2j_2418",xL="_categoryTitle_t3a2j_2432",RL="_categoryCount_t3a2j_2442",jL="_categoryItems_t3a2j_2448",PL="_selectPriority_low_t3a2j_2465",EL="_selectPriority_medium_t3a2j_2470",NL="_selectPriority_high_t3a2j_2475",ML="_selectPriority_critical_t3a2j_2480",DL="_levelSelect_t3a2j_2489",LL="_levelOption_t3a2j_2502",OL="_levelOptionFilled_t3a2j_2519",BL="_levelOption_priority_low_t3a2j_2526",WL="_levelOption_priority_medium_t3a2j_2531",$L="_levelOption_priority_high_t3a2j_2536",FL="_levelOption_priority_critical_t3a2j_2541",UL="_levelOption_complexity_tiny_t3a2j_2548",zL="_levelOption_complexity_low_t3a2j_2553",HL="_levelOption_complexity_medium_t3a2j_2558",GL="_levelOption_complexity_high_t3a2j_2563",VL="_levelOption_complexity_epic_t3a2j_2568",KL="_levelOptionActive_t3a2j_2575",qL="_levelOptionSelected_t3a2j_2580",YL="_levelLabel_t3a2j_2588",ZL="_levelLabelFadeIn_t3a2j_1",JL="_closeConfigBtn_t3a2j_2613",QL="_configItem_t3a2j_2635",XL="_settingsLabel_t3a2j_2641",e3="_settingsHint_t3a2j_2650",t3="_pathList_t3a2j_2657",r3="_pathChip_t3a2j_2664",a3="_pathValid_t3a2j_2677",n3="_pathInvalid_t3a2j_2682",s3="_pathValidIcon_t3a2j_2687",o3="_pathInvalidIcon_t3a2j_2692",i3="_pathText_t3a2j_2697",c3="_removePathBtn_t3a2j_2704",l3="_pathCount_t3a2j_2726",d3="_specialistSection_t3a2j_2737",u3="_toggleHeading_t3a2j_2745",p3="_dropdownList_t3a2j_2785",f3="_specialistBadge_t3a2j_2794",m3="_iconGrid_t3a2j_2824",h3="_iconPickerBtn_t3a2j_2835",g3="_iconPickerBtnActive_t3a2j_2854",y3="_categorySubConfig_t3a2j_2861",k3="_colorPickerRow_t3a2j_2869",v3="_colorPickerGrid_t3a2j_2875",w3="_colorSwatch_t3a2j_2882",b3="_colorSwatchActive_t3a2j_2901",S3="_categoryChipIcon_t3a2j_2907",A3="_fieldIconWrapper_t3a2j_2912",C3="_fieldIcon_t3a2j_2912",I3="_field_dynamic_t3a2j_2934",_3="_fieldIcon_dynamic_t3a2j_2940",T3="_categoryTitleIcon_t3a2j_2944",x3="_editActionsGroup_t3a2j_2949",R3="_stickyActionHeader_t3a2j_2956",j3="_taskNoticeAnchor_t3a2j_2973",P3="_taskHierarchyHeader_t3a2j_2979",E3="_taskHierarchyBadgeRow_t3a2j_2986",N3="_taskHierarchyDivider_t3a2j_2994",M3="_taskHierarchySegment_t3a2j_3000",D3="_taskHierarchyMeta_t3a2j_3007",L3="_taskHierarchyActionBtn_t3a2j_3020",O3="_taskWorkstreamPicker_t3a2j_3026",B3="_taskWorkstreamPickerIcon_t3a2j_3081",W3="_taskWorkstreamPickerPanel_t3a2j_3087",$3="_taskWorkstreamPickerOption_t3a2j_3091",F3="_taskSaveStatus_t3a2j_3113",U3="_taskSaveStatusCenter_t3a2j_3124",z3="_taskSaveStatusError_t3a2j_3132",H3="_primaryUpdateBtn_t3a2j_3136",G3="_secondaryHeaderBtn_t3a2j_3164",V3="_secondaryHeaderBtnDestructive_t3a2j_3185",K3="_attachmentCaptureContainer_t3a2j_3197",q3="_capturePrompt_t3a2j_3205",Y3="_previewContainer_t3a2j_3219",Z3="_previewHeader_t3a2j_3225",J3="_attachmentCapturePreview_t3a2j_3235",Q3="_actions_t3a2j_3242",X3="_primaryButton_t3a2j_3248",eO="_secondaryButton_t3a2j_3263",tO="_iconButton_t3a2j_3278",rO="_attachmentGrid_t3a2j_3300",aO="_attachmentCard_t3a2j_3306",nO="_attachmentPreviewContainer_t3a2j_3320",sO="_attachmentPreviewButton_t3a2j_3337",oO="_contextFileLink_t3a2j_3355",iO="_attachmentActions_t3a2j_3381",cO="_attachmentActionBtn_t3a2j_3396",lO="_attachmentActionBtnActive_t3a2j_3418",dO="_attachmentCaptionInput_t3a2j_3424",uO="_documentAttachmentCaptionInput_t3a2j_3425",pO="_hiddenInput_t3a2j_3445",fO="_contextMenuControl_t3a2j_3449",mO="_contextMenu_t3a2j_3449",hO="_contextAddMenu_t3a2j_3495",gO="_contextActionsMenu_t3a2j_3500",yO="_attachmentImageActionsMenu_t3a2j_3504",kO="_contextDestructiveMenuItem_t3a2j_3513",vO="_contextContent_t3a2j_3517",wO="_contextContentDropActive_t3a2j_3527",bO="_contextDropOverlay_t3a2j_3531",SO="_contextLinkComposer_t3a2j_3548",AO="_contextEmptyState_t3a2j_3555",CO="_contextGroupLabel_t3a2j_3565",IO="_contextNotice_t3a2j_3574",_O="_contextCaptionEditor_t3a2j_3579",TO="_attachmentCaptionLabel_t3a2j_3587",xO="_documentAttachmentList_t3a2j_3613",RO="_documentAttachmentItem_t3a2j_3619",jO="_documentAttachmentRow_t3a2j_3625",PO="_documentAttachmentLink_t3a2j_3634",EO="_documentAttachmentMain_t3a2j_3648",NO="_documentAttachmentReference_t3a2j_3656",MO="_documentAttachmentName_t3a2j_3661",DO="_brokenImage_t3a2j_3670",LO="_brokenImagePlaceholder_t3a2j_3678",OO="_regionOverlay_t3a2j_3692",BO="_selectionBox_t3a2j_3703",WO="_exportRow_t3a2j_3711",$O="_exportItem_t3a2j_3716",FO="_taxonomyDrillDown_t3a2j_3725",UO="_drillDownList_t3a2j_3735",zO="_drillDownSection_t3a2j_3743",HO="_drillDownSectionHeader_t3a2j_3749",GO="_drillDownSectionTitle_t3a2j_3756",VO="_drillDownItem_t3a2j_3765",KO="_drillDownItemDimmed_t3a2j_3787",qO="_drillDownItemActive_t3a2j_3795",YO="_drillDownItemInfo_t3a2j_3800",ZO="_drillDownItemText_t3a2j_3806",JO="_drillDownItemLabel_t3a2j_3811",QO="_drillDownItemSubtext_t3a2j_3816",XO="_addTaxonomyBtnSmall_t3a2j_3821",eB="_taxonomyDetailView_t3a2j_3843",tB="_slideIn_t3a2j_1",rB="_detailHeader_t3a2j_3863",aB="_detailTitle_t3a2j_3872",nB="_detailContent_t3a2j_3879",sB="_createOverlay_t3a2j_3886",oB="_createDialog_t3a2j_3898",iB="_zoomIn_t3a2j_1",cB="_dialogActions_t3a2j_3926",lB="_settingsGroup_t3a2j_3944",dB="_settingsItem_t3a2j_3950",uB="_mcpHealthCompactAlert_t3a2j_3956",pB="_mcpHealthUpdateRow_t3a2j_3957",fB="_mcpHealthBlockingAlert_t3a2j_3958",mB="_mcpHealthUpdateIcon_t3a2j_3986",hB="_mcpHealthCompactBody_t3a2j_3992",gB="_mcpHealthCompactActions_t3a2j_4009",yB="_mcpHealthStableAction_t3a2j_4015",kB="_mcpUpdateDialog_t3a2j_4020",vB="_mcpUpdateDialogIntro_t3a2j_4029",wB="_mcpUpdateRestartGuidance_t3a2j_4030",bB="_mcpUpdateVersionGrid_t3a2j_4037",SB="_mcpUpdateDiagnostics_t3a2j_4053",AB="_mcpUpdateLoading_t3a2j_4069",CB="_mcpUpdateNotice_t3a2j_4070",IB="_mcpUpdateCommands_t3a2j_4085",_B="_mcpUpdateSectionLabel_t3a2j_4091",TB="_mcpHealthCommandRow_t3a2j_4097",xB="_mcpHealthCommand_t3a2j_4097",RB="_mcpUpdateDialogActions_t3a2j_4140",jB="_mcpHealthCopyError_t3a2j_4146",PB="_settingLabelGroup_t3a2j_4180",EB="_settingLabel_t3a2j_4180",NB="_settingDescription_t3a2j_4192",MB="_settingInput_t3a2j_4199",DB="_codeBlockWrapper_t3a2j_4222",LB="_codeHeader_t3a2j_4231",OB="_codeHeaderActions_t3a2j_4242",BB="_codeLabel_t3a2j_4249",WB="_codeHeaderDescription_t3a2j_4257",$B="_mcpTokenCardBody_t3a2j_4265",FB="_mcpTokenFormGrid_t3a2j_4273",UB="_mcpTokenOutputWrap_t3a2j_4280",zB="_mcpTokenValueField_t3a2j_4287",HB="_mcpTokenValueText_t3a2j_4297",GB="_mcpTokenValueInput_t3a2j_4310",VB="_mcpTokenActionRow_t3a2j_4315",KB="_settingsCodeBlock_t3a2j_4323",qB="_copyBtn_t3a2j_4338",YB="_copyBtnActive_t3a2j_4359",ZB="_copyBtnNeutralActive_t3a2j_4365",JB="_headerDivider_t3a2j_4383",QB="_groupByContainer_t3a2j_4389",XB="_groupByLabel_t3a2j_4397",eW="_groupBySelect_t3a2j_4402",tW="_viewSwitcher_t3a2j_4424",rW="_selectWithIcon_t3a2j_4432",aW="_marginBottom16_t3a2j_4436",nW="_headerDraggable_t3a2j_4441",sW="_headerDragging_t3a2j_4445",oW="_filterSelectSort_t3a2j_4453",iW="_archiveRow_t3a2j_4457",cW="_taskScopeToggle_t3a2j_4463",lW="_taskScopeTabs_t3a2j_4476",dW="_taskScopeTab_t3a2j_4476",uW="_taskScopeTabActive_t3a2j_4521",pW="_taskToolbarAction_t3a2j_4529",fW="_overlayHighZ_t3a2j_4545",mW="_savedText_t3a2j_4555",hW="_shortcutInput_t3a2j_1651",gW="_saveSettingsBtnWrapper_t3a2j_4563",yW="_marginBottom12_t3a2j_4567",kW="_exportRowGrid_t3a2j_4571",vW="_settingSubtitleCustom_t3a2j_4576",wW="_capitalize_t3a2j_4582",bW="_marginTop12_t3a2j_4586",SW="_marginTop16_t3a2j_4590",AW="_labelGroupFlex_t3a2j_4594",CW="_codeBlockWrapperCustom_t3a2j_4600",IW="_kanbanWrapper_t3a2j_4606",_W="_kanbanContainer_t3a2j_4614",TW="_kanbanTopScroll_t3a2j_4636",xW="_kanbanTopScrollSpacer_t3a2j_4645",RW="_kanbanColumn_t3a2j_4649",jW="_kanbanColumnSticky_t3a2j_4665",PW="_kanbanColumnCollapsed_t3a2j_4671",EW="_kanbanColumnPast_t3a2j_4676",NW="_kanbanColumnSelectedDay_t3a2j_4681",MW="_kanbanHeader_t3a2j_4688",DW="_kanbanCount_t3a2j_4698",LW="_kanbanHeaderDraggable_t3a2j_4718",OW="_kanbanHeaderPanning_t3a2j_4722",BW="_kanbanQuickAdd_t3a2j_4726",WW="_kanbanColorDot_t3a2j_4747",$W="_kanbanDroppable_t3a2j_4759",FW="_kanbanDroppableScroll_t3a2j_4768",UW="_kanbanEmpty_t3a2j_4778",zW="_kanbanCard_t3a2j_4788",HW="_kanbanCardWrapper_t3a2j_4798",GW="_taxonomyDropdownActive_t3a2j_4806",VW="_kanbanCardWrapperRaised_t3a2j_4810",KW="_kanbanCardTitle_t3a2j_4814",qW="_kanbanBadges_t3a2j_4818",YW="_kanbanBadge_t3a2j_4818",ZW="_headerFlex_t3a2j_4834",JW="_marginBottom8_t3a2j_4841",QW="_marginBottom20_t3a2j_4845",XW="_configPanel_t3a2j_4849",e$="_configPanelLarge_t3a2j_4858",t$="_subLabelBlock_t3a2j_4862",r$="_subLabelBlock12_t3a2j_4869",a$="_flexBetween_t3a2j_4873",n$="_flexBetweenCenter_t3a2j_4880",s$="_deleteBtnSmall_t3a2j_4885",o$="_deleteBtnMedium_t3a2j_4891",i$="_trashIcon_t3a2j_4898",c$="_gridConfig_t3a2j_4902",l$="_flexColGap4_t3a2j_4909",d$="_flexColGap4Center_t3a2j_4915",u$="_flex1_t3a2j_4922",p$="_flexCol_t3a2j_4909",f$="_flexGrow1_t3a2j_4932",m$="_inputLabel_t3a2j_4936",h$="_inputLabelBlock_t3a2j_4940",g$="_checkboxInput_t3a2j_4946",y$="_configDividerMargin_t3a2j_4952",k$="_configDividerMargin24_t3a2j_4957",v$="_pathListMargin_t3a2j_4962",w$="_cancelBtnRed_t3a2j_4966",b$="_code_t3a2j_4222",S$="_workflowList_t3a2j_4993",A$="_workflowActions_t3a2j_5001",C$="_textBtn_t3a2j_5010",I$="_workflowGrid_t3a2j_5024",_$="_checkboxLabel_t3a2j_5032",T$="_checkboxSmall_t3a2j_5046",x$="_docWorkspace_t3a2j_5065",R$="_docIndexPanel_t3a2j_5076",j$="_docWorkspaceTrayMode_t3a2j_5088",P$="_docViewerPanel_t3a2j_5088",E$="_docWorkspaceTrayOpen_t3a2j_5093",N$="_docTrayPanel_t3a2j_5097",M$="_docTrayPanelOpen_t3a2j_5121",D$="_docSpinning_t3a2j_5129",L$="_docSpin_t3a2j_5129",O$="_docViewerEmpty_t3a2j_5148",B$="_agentsModuleRoot_t3a2j_5163",W$="_agentsModuleWithTray_t3a2j_5175",$$="_agentsModuleTrayOpen_t3a2j_5179",F$="_agentTrayPanel_t3a2j_5183",U$="_agentTrayPanelOpen_t3a2j_5206",z$="_agentTrayHeader_t3a2j_5214",H$="_agentTrayTitle_t3a2j_5229",G$="_agentTrayContent_t3a2j_5241",V$="_agentTrayContentInner_t3a2j_5249",K$="_agentsModuleContent_t3a2j_5253",q$="_taskforceAgentsModuleRoot_t3a2j_5261",Y$="_taskforceAgentsModuleMain_t3a2j_5272",Z$="_taskforceAgentsModuleTrayOpen_t3a2j_5280",J$="_taskforceAgentRosterHeader_t3a2j_5284",Q$="_taskforceAgentRosterTitle_t3a2j_5297",X$="_taskforceAgentRosterContent_t3a2j_5309",eF="_taskforceAgentLibraryPortal_t3a2j_5317",tF="_taskforceAgentBuilderNavigation_t3a2j_5323",rF="_taskforceAgentBuilderTabs_t3a2j_5346",aF="_taskforceAgentBuilderCreateBtn_t3a2j_5363",nF="_taskforceAgentBuilderTab_t3a2j_5346",sF="_taskforceAgentBuilderTabActive_t3a2j_5404",oF="_taskforceAgentBuilderPanel_t3a2j_5422",iF="_taskforceAgentBuilderEmpty_t3a2j_5430",cF="_taskforceAgentBuilderEmptyIcon_t3a2j_5439",lF="_taskforceAgentTestGrid_t3a2j_5451",dF="_taskforceAgentContextBanner_t3a2j_5458",uF="_taskforceAgentContextActions_t3a2j_5477",pF="_taskforceAssistantWorkspace_t3a2j_5501",fF="_taskforceAssistantWorkspaceContent_t3a2j_5511",mF="_taskforceAssistantWorkspaceOpen_t3a2j_5520",hF="_taskforceAssistantWorkspaceCollapsed_t3a2j_5524",gF="_taskforceModalWithAssistantPanel_t3a2j_5528",yF="_taskforceModalWithAssistantPanelCollapsed_t3a2j_5533",kF="_taskforceTaskModalOverlay_t3a2j_5537",vF="_taskforceAgentDrawerOverlay_t3a2j_5558",wF="_taskforceAgentDrawerOverlayCollapsed_t3a2j_5568",bF="_taskforceAgentDrawerPanel_t3a2j_5572",SF="_taskforceAgentDrawerHeader_t3a2j_5584",AF="_taskforceAgentDrawerAgentHeader_t3a2j_5594",CF="_taskforceAgentDrawerHeaderFallback_t3a2j_5595",IF="_taskforceAgentDrawerAgentAvatar_t3a2j_5603",_F="_taskforceAgentDrawerFallbackAvatar_t3a2j_5604",TF="_taskforceAgentDrawerAgentAvatarButton_t3a2j_5626",xF="_taskforceAgentDrawerAgentPicker_t3a2j_5650",RF="_taskforceAgentDrawerHeaderActions_t3a2j_5670",jF="_taskforceAgentDrawerLoading_t3a2j_5676",PF="_taskforceAgentDrawerSurface_t3a2j_5684",EF="_taskforceAgentDrawerControls_t3a2j_5694",NF="_taskforceAgentProfileTray_t3a2j_5701",MF="_taskforceAgentProfileTrayIn_t3a2j_1",DF="_taskforceAgentProfileTrayHeader_t3a2j_5713",LF="_taskforceAgentProfileTrayIdentity_t3a2j_5721",OF="_taskforceAgentProfileTrayDetails_t3a2j_5729",BF="_taskforceAgentDrawerChatControls_t3a2j_5795",WF="_taskforceAgentConversationRename_t3a2j_5803",$F="_taskforceAgentConversationRenameError_t3a2j_5815",FF="_taskforceAgentDrawerConversationList_t3a2j_5822",UF="_taskforceAgentDrawerPrompt_t3a2j_5828",zF="_taskforceAgentDrawerPromptStatus_t3a2j_5848",HF="_taskforceAgentDrawerMetrics_t3a2j_5856",GF="_taskforceAgentOutputStack_t3a2j_5881",VF="_taskforceAgentOutputPanel_t3a2j_5888",KF="_taskforceAgentTestTitle_t3a2j_5899",qF="_taskforceAgentTestNotice_t3a2j_5926",YF="_taskforceAgentTestError_t3a2j_5927",ZF="_taskforceAgentTestPending_t3a2j_5928",JF="_taskforceAgentTestActions_t3a2j_5961",QF="_taskforceAgentTestRestriction_t3a2j_5972",XF="_taskforceAgentTestResult_t3a2j_5979",e4="_taskforceAgentTestResultHeader_t3a2j_5989",t4="_taskforceAgentTestResponse_t3a2j_6007",r4="_taskforceAgentReadonlyField_t3a2j_6023",a4="_taskforceAgentAvatarPanel_t3a2j_6036",n4="_taskforceAgentAvatarEditControl_t3a2j_6048",s4="_taskforceAgentAvatarPreview_t3a2j_6054",o4="_taskforceAgentListAvatar_t3a2j_6055",i4="_taskforceAgentAvatarSyncing_t3a2j_6080",c4="_taskforceAgentAvatarSyncIcon_t3a2j_6084",l4="_taskforceAgentAvatarCopy_t3a2j_6097",d4="_taskforceAgentAvatarRole_t3a2j_6115",u4="_taskforceAgentToolbar_t3a2j_6135",p4="_taskforceAgentConversationSelect_t3a2j_6145",f4="_taskforceAgentList_t3a2j_6055",m4="_taskforceAgentListEmpty_t3a2j_6162",h4="_taskforceAgentSignatureColorField_t3a2j_6169",g4="_aiProfileColorPicker_t3a2j_6188",y4="_taskforceAgentBehaviorGrid_t3a2j_6193",k4="_taskforceAgentBehaviorWide_t3a2j_6199",v4="_taskforceAgentFieldHelper_t3a2j_6203",w4="_taskforceAgentPresentationGroup_t3a2j_6210",b4="_taskforceAgentLogList_t3a2j_6225",S4="_taskforceAgentLogEntry_t3a2j_6231",A4="_taskforceAgentToolDetails_t3a2j_6242",C4="_taskforceAgentToolActivity_t3a2j_6256",I4="_taskforceAgentToolActivityList_t3a2j_6284",_4="_taskforceAgentToolCall_t3a2j_6291",T4="_taskforceAgentToolCallFailed_t3a2j_6307",x4="_taskforceAgentToolCallName_t3a2j_6311",R4="_taskforceAgentToolCallStatus_t3a2j_6321",j4="_taskforceAgentToolDetailsGrid_t3a2j_6327",P4="_taskforceAgentLogSuccess_t3a2j_6362",E4="_taskforceAgentLogError_t3a2j_6366",N4="_taskforceAgentLogTime_t3a2j_6370",M4="_taskforceAgentConversationList_t3a2j_6376",D4="_taskforceAgentConversationBody_t3a2j_6395",L4="_taskforceAgentConversationMessage_t3a2j_6396",O4="_taskforceAgentConversationEmpty_t3a2j_6401",B4="_taskforceAgentConversationMessageUser_t3a2j_6442",W4="_taskforceAgentConversationMessageAssistant_t3a2j_6454",$4="_taskforceAgentMetaGrid_t3a2j_6469",F4="_marginTop24_t3a2j_6497",U4="_settingSubTitle_t3a2j_6501",z4="_dangerBtn_t3a2j_6510",H4="_aiProfilesExplorer_t3a2j_6526",G4="_aiProfilesRosterPanel_t3a2j_6535",V4="_aiProfilesRosterSummary_t3a2j_6546",K4="_aiProfileSeatSummary_t3a2j_6555",q4="_aiProfilesRosterState_t3a2j_6559",Y4="_aiProfilesListPane_t3a2j_6571",Z4="_aiProfilesList_t3a2j_6571",J4="_aiProfilesDetailViewport_t3a2j_6591",Q4="_aiProfilesSection_t3a2j_6598",X4="_aiProfilesSectionHeader_t3a2j_6604",e5="_aiProfileGroup_t3a2j_6612",t5="_aiProfileGroupSelected_t3a2j_6635",r5="_aiProfileGroupDuplicate_t3a2j_6642",a5="_aiProfileGroupHeader_t3a2j_6647",n5="_aiProfileGroupAvatar_t3a2j_6655",s5="_aiProfileGroupAvatarLogo_t3a2j_6677",o5="_aiProfileGroupIdentity_t3a2j_6689",i5="_aiProfileName_t3a2j_6698",c5="_aiProfileHandle_t3a2j_6706",l5="_aiProfileRole_t3a2j_6707",d5="_aiProfileSeatScopeIcon_t3a2j_6727",u5="_aiProfileGroupSignatureSwatch_t3a2j_6738",p5="_aiProfileSeatScopeIconDetail_t3a2j_6744",f5="_aiProfileSeatScopeIconCloud_t3a2j_6749",m5="_aiProfileSeatScopeIconLocal_t3a2j_6753",h5="_aiProfileDuplicateBadge_t3a2j_6757",g5="_aiProfileMergeSection_t3a2j_6769",y5="_aiProfileMergeRow_t3a2j_6776",k5="_aiProfileIdChip_t3a2j_6783",v5="_aiProfileKeepBadge_t3a2j_6795",w5="_aiProfileMergeActions_t3a2j_6809",b5="_aiProfileDetailPane_t3a2j_6816",S5="_aiProfileDetailCard_t3a2j_6822",A5="_aiProfileDetailHero_t3a2j_6835",C5="_aiProfileDetailIcon_t3a2j_6841",I5="_aiProfileDetailAvatar_t3a2j_6855",_5="_aiProfileDetailAvatarLogo_t3a2j_6859",T5="_aiProfileDetailHeading_t3a2j_6877",x5="_aiProfileDetailTitleRow_t3a2j_6882",R5="_aiProfileDetailTitle_t3a2j_6882",j5="_aiProfileDetailMetaRow_t3a2j_6897",P5="_aiProfileDetailHandle_t3a2j_6905",E5="_aiProfileDetailRole_t3a2j_6910",N5="_aiProfileDetailLinkedCount_t3a2j_6917",M5="_aiProfileDetailDescription_t3a2j_6922",D5="_aiProfileSignatureColor_t3a2j_6929",L5="_aiProfileSignatureSwatch_t3a2j_6939",O5="_aiProfileSignatureColorButton_t3a2j_6957",B5="_aiProfileColorOption_t3a2j_6984",W5="_aiProfileDetailDataList_t3a2j_6998",$5="_aiProfileDetailDataGroup_t3a2j_7007",F5="_aiProfileDetailDateGroup_t3a2j_7014",U5="_aiProfileDetailDataRow_t3a2j_7019",z5="_aiProfileDetailDataLabel_t3a2j_7028",H5="_aiProfileDetailDataValue_t3a2j_7035",G5="_aiProfileStatusSelect_t3a2j_7041",V5="_aiProfileInstanceSection_t3a2j_7083",K5="_aiProfileInstanceSectionHeader_t3a2j_7089",q5="_aiProfileInstanceList_t3a2j_7099",Y5="_aiProfileInstanceCard_t3a2j_7105",Z5="_aiProfileIdFooter_t3a2j_7118",J5="_aiProfileIdFooterValue_t3a2j_7128",Q5="_aiProfileDangerTextButton_t3a2j_7138",X5="_aiProfileInstanceTopRow_t3a2j_7170",eU="_aiProfileInstanceName_t3a2j_7177",tU="_aiProfileInstanceMeta_t3a2j_7184",rU="_aiProfileInlineError_t3a2j_7192",R={filterGlow:EN,floatingButton:NN,badge:MN,configBadge:DN,configBadgeActive:LN,configBadgeRevoked:ON,configBadgeExpired:BN,coreModal:WN,header:$N,headerTitle:FN,brandIcon:UN,brandHomeButton:zN,brandHomeStatic:HN,brandCloudSuffix:GN,projectSlash:VN,projectNameGroup:KN,projectNameGroupHidden:qN,projectName:YN,taskCountBadge:ZN,taskCountBadgeIcon:JN,taskCountBadgeButton:QN,taskCountBadgeActive:XN,taskCountBadgeAlert:e1,headerActions:t1,sortDirectionBtn:r1,sortDirectionBtnWidget:a1,form:n1,topRow:s1,field:o1,labelRow:i1,label:c1,manageLink:l1,input:d1,select:u1,textarea:p1,taskIdInlineLink:f1,readOnly:m1,selectWithConfig:h1,configBtn:g1,configBtnActive:y1,hasPath:k1,pathIndicator:v1,formActions:w1,hasCancel:b1,submitBtn:S1,cancelBtn:A1,successMessage:C1,errorMessage:I1,successIcon:_1,spinner:T1,spin:x1,boardRefreshIndicator:R1,destructiveBtn:j1,warningBtn:P1,viewTab:E1,loading:N1,emptyState:M1,taskList:D1,referenceBadge:L1,referenceBadgeLabel:O1,referenceBadgeStatic:B1,provisionalReferenceBadge:W1,copiedReference:$1,highlight:F1,modal:U1,priorityEmoji:z1,metaItem:H1,taskFormDateInput:G1,metaBadge:V1,complexityPill:K1,complexityDots:q1,dot:Y1,dotFilled:Z1,typePill:J1,type_bug:Q1,type_feature:X1,type_chore:eM,type_refactor:tM,type_documentation:rM,type_research:aM,"type_ui-ux":"_type_ui-ux_t3a2j_870",type_security:nM,statusActionsGroup:sM,statusActionsGroupCompact:oM,statusSelectWrap:iM,statusTaxonomyDropdownWrap:cM,statusTaxonomyDropdown:lM,statusTaxonomyDropdownCompact:dM,statusTaxonomyDropdownIconOnly:uM,taxonomyDropdownButton:pM,taxonomyDropdownButtonContent:fM,statusTaxonomyDropdownIconOnlyPanel:mM,actionBtn:hM,restoreTaskBtn:gM,startWorkBtn:yM,workingBtn:kM,pulse:vM,reviewBtn:wM,reviewActiveBtn:bM,reviewPill:SM,bulkArchiveBtn:AM,bulkDeleteBtn:CM,deleteBtn:IM,completeBtn:_M,completeActiveBtn:TM,deleteActiveBtn:xM,disabledBtn:RM,archiveList:jM,archiveHeader:PM,settingsTab:EM,settingsTabMcpOnly:NM,settingsTabs:MM,settingsLayout:DM,settingsLayoutMcpOnly:LM,settingsSidebar:OM,settingsSidebarHeader:BM,settingsSidebarNav:WM,settingsSidebarBtn:$M,settingsSidebarBtnActive:FM,settingsSidebarGroup:UM,settingsSidebarGroupBtn:zM,settingsSidebarGroupLabel:HM,settingsSidebarGroupChevron:GM,settingsSidebarSubnav:VM,settingsSidebarSubBtn:KM,appScrollbar:qM,settingsTabBtn:YM,settingsTabBtnActive:ZM,settingsContent:JM,mcpRegistrationHint:QM,mcpRegistrationPrompt:XM,mcpCodexTrustNote:eD,mcpCodexTrustHeader:tD,mcpCodexTrustTitle:rD,mcpCodexTrustCode:aD,mcpAuthRequiredCard:nD,mcpAuthRequiredIcon:sD,mcpAuthRequiredBody:oD,mcpAuthRequiredActions:iD,settingsToast:cD,settingsToastSuccess:lD,settingsToastError:dD,inputWithPrefix:uD,pathHint:pD,settingGroup:fD,settingTitle:mD,settingTitleRow:hD,settingTitleActionBtn:gD,themeOptions:yD,buttonGrid:kD,themeBtn:vD,activeTheme:wD,pathInputGroup:bD,saveSettingsBtn:SD,shortcutInputWrapper:AD,inputIcon:CD,settingHelper:ID,browseBtn:_D,inlineCategoryManager:TD,categoryManager:xD,categoryList:RD,categoryChip:jD,categoryChipLabel:PD,chipActionBtn:ED,removeCategoryBtn:ND,addCategoryForm:MD,addCategoryBtn:DD,filesList:LD,helpLink:OD,taskChildrenSummaryBadges:BD,taskChildrenProgressBar:WD,taskChildrenProgressBarSegmentDone:$D,taskChildrenProgressBarSegmentReview:FD,taskChildrenProgressBarSegmentInProgress:UD,taskChildrenProgressBarSegmentBlocked:zD,taskChildrenProgressText:HD,taskChildUnlinkBtn:GD,aboutText:VD,versionInfo:KD,filterBar:qD,kanbanHintText:YD,searchContainer:ZD,searchIcon:JD,searchInput:QD,searchActive:XD,searchCount:eL,clearSearchBtn:tL,filterRow:rL,sortLabel:aL,archiveToggle:nL,filterContainer:sL,filterButton:oL,filterActive:iL,filterDropdown:cL,filterSearch:lL,filterSearchIcon:dL,filterSearchInput:uL,filterEmpty:pL,filterOption:fL,filterDivider:mL,filterSelect:hL,filterToggleBtn:gL,inProgressToggle:yL,activeInProgress:kL,activeFilter:vL,resetFiltersBtn:wL,categoryChip_disabled:bL,categoryVisibilityToggle:SL,editCategoryInput:AL,categoryChipActionBtn:CL,categoryChipActionBtn_active:IL,categoryGroup:_L,categoryHeader:TL,categoryTitle:xL,categoryCount:RL,categoryItems:jL,selectPriority_low:PL,selectPriority_medium:EL,selectPriority_high:NL,selectPriority_critical:ML,"critical-glow":"_critical-glow_t3a2j_1",levelSelect:DL,levelOption:LL,levelOptionFilled:OL,levelOption_priority_low:BL,levelOption_priority_medium:WL,levelOption_priority_high:$L,levelOption_priority_critical:FL,levelOption_complexity_tiny:UL,levelOption_complexity_low:zL,levelOption_complexity_medium:HL,levelOption_complexity_high:GL,levelOption_complexity_epic:VL,levelOptionActive:KL,levelOptionSelected:qL,levelLabel:YL,levelLabelFadeIn:ZL,closeConfigBtn:JL,configItem:QL,settingsLabel:XL,settingsHint:e3,pathList:t3,pathChip:r3,pathValid:a3,pathInvalid:n3,pathValidIcon:s3,pathInvalidIcon:o3,pathText:i3,removePathBtn:c3,pathCount:l3,specialistSection:d3,toggleHeading:u3,dropdownList:p3,specialistBadge:f3,iconGrid:m3,iconPickerBtn:h3,iconPickerBtnActive:g3,categorySubConfig:y3,colorPickerRow:k3,colorPickerGrid:v3,colorSwatch:w3,colorSwatchActive:b3,categoryChipIcon:S3,fieldIconWrapper:A3,fieldIcon:C3,field_dynamic:I3,fieldIcon_dynamic:_3,categoryTitleIcon:T3,editActionsGroup:x3,stickyActionHeader:R3,taskNoticeAnchor:j3,taskHierarchyHeader:P3,taskHierarchyBadgeRow:E3,taskHierarchyDivider:N3,taskHierarchySegment:M3,taskHierarchyMeta:D3,taskHierarchyActionBtn:L3,taskWorkstreamPicker:O3,taskWorkstreamPickerIcon:B3,taskWorkstreamPickerPanel:W3,taskWorkstreamPickerOption:$3,taskSaveStatus:F3,taskSaveStatusCenter:U3,taskSaveStatusError:z3,primaryUpdateBtn:H3,secondaryHeaderBtn:G3,secondaryHeaderBtnDestructive:V3,attachmentCaptureContainer:K3,capturePrompt:q3,previewContainer:Y3,previewHeader:Z3,attachmentCapturePreview:J3,actions:Q3,primaryButton:X3,secondaryButton:eO,iconButton:tO,attachmentGrid:rO,attachmentCard:aO,attachmentPreviewContainer:nO,attachmentPreviewButton:sO,contextFileLink:oO,attachmentActions:iO,attachmentActionBtn:cO,attachmentActionBtnActive:lO,attachmentCaptionInput:dO,documentAttachmentCaptionInput:uO,hiddenInput:pO,contextMenuControl:fO,contextMenu:mO,contextAddMenu:hO,contextActionsMenu:gO,attachmentImageActionsMenu:yO,contextDestructiveMenuItem:kO,contextContent:vO,contextContentDropActive:wO,contextDropOverlay:bO,contextLinkComposer:SO,contextEmptyState:AO,contextGroupLabel:CO,contextNotice:IO,contextCaptionEditor:_O,attachmentCaptionLabel:TO,documentAttachmentList:xO,documentAttachmentItem:RO,documentAttachmentRow:jO,documentAttachmentLink:PO,documentAttachmentMain:EO,documentAttachmentReference:NO,documentAttachmentName:MO,brokenImage:DO,brokenImagePlaceholder:LO,regionOverlay:OO,selectionBox:BO,exportRow:WO,exportItem:$O,taxonomyDrillDown:FO,drillDownList:UO,drillDownSection:zO,drillDownSectionHeader:HO,drillDownSectionTitle:GO,drillDownItem:VO,drillDownItemDimmed:KO,drillDownItemActive:qO,drillDownItemInfo:YO,drillDownItemText:ZO,drillDownItemLabel:JO,drillDownItemSubtext:QO,addTaxonomyBtnSmall:XO,taxonomyDetailView:eB,slideIn:tB,detailHeader:rB,detailTitle:aB,detailContent:nB,createOverlay:sB,createDialog:oB,zoomIn:iB,dialogActions:cB,settingsGroup:lB,settingsItem:dB,mcpHealthCompactAlert:uB,mcpHealthUpdateRow:pB,mcpHealthBlockingAlert:fB,mcpHealthUpdateIcon:mB,mcpHealthCompactBody:hB,mcpHealthCompactActions:gB,mcpHealthStableAction:yB,mcpUpdateDialog:kB,mcpUpdateDialogIntro:vB,mcpUpdateRestartGuidance:wB,mcpUpdateVersionGrid:bB,mcpUpdateDiagnostics:SB,mcpUpdateLoading:AB,mcpUpdateNotice:CB,mcpUpdateCommands:IB,mcpUpdateSectionLabel:_B,mcpHealthCommandRow:TB,mcpHealthCommand:xB,mcpUpdateDialogActions:RB,mcpHealthCopyError:jB,settingLabelGroup:PB,settingLabel:EB,settingDescription:NB,settingInput:MB,codeBlockWrapper:DB,codeHeader:LB,codeHeaderActions:OB,codeLabel:BB,codeHeaderDescription:WB,mcpTokenCardBody:$B,mcpTokenFormGrid:FB,mcpTokenOutputWrap:UB,mcpTokenValueField:zB,mcpTokenValueText:HB,mcpTokenValueInput:GB,mcpTokenActionRow:VB,settingsCodeBlock:KB,copyBtn:qB,copyBtnActive:YB,copyBtnNeutralActive:ZB,headerDivider:JB,groupByContainer:QB,groupByLabel:XB,groupBySelect:eW,viewSwitcher:tW,selectWithIcon:rW,marginBottom16:aW,headerDraggable:nW,headerDragging:sW,filterSelectSort:oW,archiveRow:iW,taskScopeToggle:cW,taskScopeTabs:lW,taskScopeTab:dW,taskScopeTabActive:uW,taskToolbarAction:pW,overlayHighZ:fW,savedText:mW,shortcutInput:hW,saveSettingsBtnWrapper:gW,marginBottom12:yW,exportRowGrid:kW,settingSubtitleCustom:vW,capitalize:wW,marginTop12:bW,marginTop16:SW,labelGroupFlex:AW,codeBlockWrapperCustom:CW,kanbanWrapper:IW,kanbanContainer:_W,kanbanTopScroll:TW,kanbanTopScrollSpacer:xW,kanbanColumn:RW,kanbanColumnSticky:jW,kanbanColumnCollapsed:PW,kanbanColumnPast:EW,kanbanColumnSelectedDay:NW,kanbanHeader:MW,kanbanCount:DW,kanbanHeaderDraggable:LW,kanbanHeaderPanning:OW,kanbanQuickAdd:BW,kanbanColorDot:WW,kanbanDroppable:$W,kanbanDroppableScroll:FW,kanbanEmpty:UW,kanbanCard:zW,kanbanCardWrapper:HW,taxonomyDropdownActive:GW,kanbanCardWrapperRaised:VW,kanbanCardTitle:KW,kanbanBadges:qW,kanbanBadge:YW,headerFlex:ZW,marginBottom8:JW,marginBottom20:QW,configPanel:XW,configPanelLarge:e$,subLabelBlock:t$,subLabelBlock12:r$,flexBetween:a$,flexBetweenCenter:n$,deleteBtnSmall:s$,deleteBtnMedium:o$,trashIcon:i$,gridConfig:c$,flexColGap4:l$,flexColGap4Center:d$,flex1:u$,flexCol:p$,flexGrow1:f$,inputLabel:m$,inputLabelBlock:h$,checkboxInput:g$,configDividerMargin:y$,configDividerMargin24:k$,pathListMargin:v$,cancelBtnRed:w$,code:b$,workflowList:S$,workflowActions:A$,textBtn:C$,workflowGrid:I$,checkboxLabel:_$,checkboxSmall:T$,docWorkspace:x$,docIndexPanel:R$,docWorkspaceTrayMode:j$,docViewerPanel:P$,docWorkspaceTrayOpen:E$,docTrayPanel:N$,docTrayPanelOpen:M$,docSpinning:D$,docSpin:L$,docViewerEmpty:O$,agentsModuleRoot:B$,agentsModuleWithTray:W$,agentsModuleTrayOpen:$$,agentTrayPanel:F$,agentTrayPanelOpen:U$,agentTrayHeader:z$,agentTrayTitle:H$,agentTrayContent:G$,agentTrayContentInner:V$,agentsModuleContent:K$,taskforceAgentsModuleRoot:q$,taskforceAgentsModuleMain:Y$,taskforceAgentsModuleTrayOpen:Z$,taskforceAgentRosterHeader:J$,taskforceAgentRosterTitle:Q$,taskforceAgentRosterContent:X$,taskforceAgentLibraryPortal:eF,taskforceAgentBuilderNavigation:tF,taskforceAgentBuilderTabs:rF,taskforceAgentBuilderCreateBtn:aF,taskforceAgentBuilderTab:nF,taskforceAgentBuilderTabActive:sF,taskforceAgentBuilderPanel:oF,taskforceAgentBuilderEmpty:iF,taskforceAgentBuilderEmptyIcon:cF,taskforceAgentTestGrid:lF,taskforceAgentContextBanner:dF,taskforceAgentContextActions:uF,taskforceAssistantWorkspace:pF,taskforceAssistantWorkspaceContent:fF,taskforceAssistantWorkspaceOpen:mF,taskforceAssistantWorkspaceCollapsed:hF,taskforceModalWithAssistantPanel:gF,taskforceModalWithAssistantPanelCollapsed:yF,taskforceTaskModalOverlay:kF,taskforceAgentDrawerOverlay:vF,taskforceAgentDrawerOverlayCollapsed:wF,taskforceAgentDrawerPanel:bF,taskforceAgentDrawerHeader:SF,taskforceAgentDrawerAgentHeader:AF,taskforceAgentDrawerHeaderFallback:CF,taskforceAgentDrawerAgentAvatar:IF,taskforceAgentDrawerFallbackAvatar:_F,taskforceAgentDrawerAgentAvatarButton:TF,taskforceAgentDrawerAgentPicker:xF,taskforceAgentDrawerHeaderActions:RF,taskforceAgentDrawerLoading:jF,taskforceAgentDrawerSurface:PF,taskforceAgentDrawerControls:EF,taskforceAgentProfileTray:NF,taskforceAgentProfileTrayIn:MF,taskforceAgentProfileTrayHeader:DF,taskforceAgentProfileTrayIdentity:LF,taskforceAgentProfileTrayDetails:OF,taskforceAgentDrawerChatControls:BF,taskforceAgentConversationRename:WF,taskforceAgentConversationRenameError:$F,taskforceAgentDrawerConversationList:FF,taskforceAgentDrawerPrompt:UF,taskforceAgentDrawerPromptStatus:zF,taskforceAgentDrawerMetrics:HF,taskforceAgentOutputStack:GF,taskforceAgentOutputPanel:VF,taskforceAgentTestTitle:KF,taskforceAgentTestNotice:qF,taskforceAgentTestError:YF,taskforceAgentTestPending:ZF,taskforceAgentTestActions:JF,taskforceAgentTestRestriction:QF,taskforceAgentTestResult:XF,taskforceAgentTestResultHeader:e4,taskforceAgentTestResponse:t4,taskforceAgentReadonlyField:r4,taskforceAgentAvatarPanel:a4,taskforceAgentAvatarEditControl:n4,taskforceAgentAvatarPreview:s4,taskforceAgentListAvatar:o4,taskforceAgentAvatarSyncing:i4,taskforceAgentAvatarSyncIcon:c4,taskforceAgentAvatarCopy:l4,taskforceAgentAvatarRole:d4,taskforceAgentToolbar:u4,taskforceAgentConversationSelect:p4,taskforceAgentList:f4,taskforceAgentListEmpty:m4,taskforceAgentSignatureColorField:h4,aiProfileColorPicker:g4,taskforceAgentBehaviorGrid:y4,taskforceAgentBehaviorWide:k4,taskforceAgentFieldHelper:v4,taskforceAgentPresentationGroup:w4,taskforceAgentLogList:b4,taskforceAgentLogEntry:S4,taskforceAgentToolDetails:A4,taskforceAgentToolActivity:C4,taskforceAgentToolActivityList:I4,taskforceAgentToolCall:_4,taskforceAgentToolCallFailed:T4,taskforceAgentToolCallName:x4,taskforceAgentToolCallStatus:R4,taskforceAgentToolDetailsGrid:j4,taskforceAgentLogSuccess:P4,taskforceAgentLogError:E4,taskforceAgentLogTime:N4,taskforceAgentConversationList:M4,taskforceAgentConversationBody:D4,taskforceAgentConversationMessage:L4,taskforceAgentConversationEmpty:O4,taskforceAgentConversationMessageUser:B4,taskforceAgentConversationMessageAssistant:W4,taskforceAgentMetaGrid:$4,marginTop24:F4,settingSubTitle:U4,dangerBtn:z4,aiProfilesExplorer:H4,aiProfilesRosterPanel:G4,aiProfilesRosterSummary:V4,aiProfileSeatSummary:K4,aiProfilesRosterState:q4,aiProfilesListPane:Y4,aiProfilesList:Z4,aiProfilesDetailViewport:J4,aiProfilesSection:Q4,aiProfilesSectionHeader:X4,aiProfileGroup:e5,aiProfileGroupSelected:t5,aiProfileGroupDuplicate:r5,aiProfileGroupHeader:a5,aiProfileGroupAvatar:n5,aiProfileGroupAvatarLogo:s5,aiProfileGroupIdentity:o5,aiProfileName:i5,aiProfileHandle:c5,aiProfileRole:l5,aiProfileSeatScopeIcon:d5,aiProfileGroupSignatureSwatch:u5,aiProfileSeatScopeIconDetail:p5,aiProfileSeatScopeIconCloud:f5,aiProfileSeatScopeIconLocal:m5,aiProfileDuplicateBadge:h5,aiProfileMergeSection:g5,aiProfileMergeRow:y5,aiProfileIdChip:k5,aiProfileKeepBadge:v5,aiProfileMergeActions:w5,aiProfileDetailPane:b5,aiProfileDetailCard:S5,aiProfileDetailHero:A5,aiProfileDetailIcon:C5,aiProfileDetailAvatar:I5,aiProfileDetailAvatarLogo:_5,aiProfileDetailHeading:T5,aiProfileDetailTitleRow:x5,aiProfileDetailTitle:R5,aiProfileDetailMetaRow:j5,aiProfileDetailHandle:P5,aiProfileDetailRole:E5,aiProfileDetailLinkedCount:N5,aiProfileDetailDescription:M5,aiProfileSignatureColor:D5,aiProfileSignatureSwatch:L5,aiProfileSignatureColorButton:O5,aiProfileColorOption:B5,aiProfileDetailDataList:W5,aiProfileDetailDataGroup:$5,aiProfileDetailDateGroup:F5,aiProfileDetailDataRow:U5,aiProfileDetailDataLabel:z5,aiProfileDetailDataValue:H5,aiProfileStatusSelect:G5,aiProfileInstanceSection:V5,aiProfileInstanceSectionHeader:K5,aiProfileInstanceList:q5,aiProfileInstanceCard:Y5,aiProfileIdFooter:Z5,aiProfileIdFooterValue:J5,aiProfileDangerTextButton:Q5,aiProfileInstanceTopRow:X5,aiProfileInstanceName:eU,aiProfileInstanceMeta:tU,aiProfileInlineError:rU},aU="_standaloneWrapper_128c3_1",nU="_standalonePage_128c3_11",sU="_standaloneHeader_128c3_21",oU="_standaloneTitle_128c3_27",iU="_standaloneContent_128c3_31",cU="_workspaceToolRail_128c3_37",lU="_workspaceToolRailLeft_128c3_48",dU="_workspaceToolRailRight_128c3_57",uU="_workspaceToolRailMain_128c3_64",pU="_workspaceToolRailBottom_128c3_72",fU="_workspaceToolRailDivider_128c3_82",mU="_workspaceToolButton_128c3_89",hU="_headerTitleWidget_128c3_124",Fr={standaloneWrapper:aU,standalonePage:nU,standaloneHeader:sU,standaloneTitle:oU,standaloneContent:iU,workspaceToolRail:cU,workspaceToolRailLeft:lU,workspaceToolRailRight:dU,workspaceToolRailMain:uU,workspaceToolRailBottom:pU,workspaceToolRailDivider:fU,workspaceToolButton:mU,headerTitleWidget:hU},gU="_overlay_11v7l_1",yU="_browser_11v7l_16",kU="_header_11v7l_27",vU="_pathInfo_11v7l_36",wU="_actions_11v7l_52",bU="_list_11v7l_57",SU="_item_11v7l_63",AU="_itemCurrent_11v7l_80",CU="_itemFile_11v7l_86",IU="_empty_11v7l_90",Ea={overlay:gU,browser:yU,header:kU,pathInfo:vU,actions:wU,list:bU,item:SU,itemCurrent:AU,itemFile:CU,empty:IU},_U="_overlay_1hk7m_2",TU="_overlayHighZ_1hk7m_15",xU="_modal_1hk7m_20",RU="_draggableModal_1hk7m_46",jU="_draggableHeader_1hk7m_53",PU="_headerActions_1hk7m_61",EU="_modalContent_1hk7m_69",NU="_form_1hk7m_80",MU="_formActions_1hk7m_91",DU="_modalFooter_1hk7m_98",LU="_modalSizeSm_1hk7m_104",OU="_modalSizeMd_1hk7m_108",BU="_modalSizeMdWide_1hk7m_112",WU="_modalSizeLg_1hk7m_116",$U="_modalSizeXl_1hk7m_120",FU="_modalSizeFull_1hk7m_124",UU="_settingsViewModal_1hk7m_129",zU="_unsavedOverlay_1hk7m_148",HU="_unsavedModal_1hk7m_153",GU="_unsavedHeader_1hk7m_159",VU="_unsavedTitle_1hk7m_164",KU="_unsavedContent_1hk7m_168",qU="_unsavedText_1hk7m_172",YU="_unsavedActions_1hk7m_177",dr={overlay:_U,overlayHighZ:TU,modal:xU,draggableModal:RU,draggableHeader:jU,headerActions:PU,modalContent:EU,form:NU,formActions:MU,modalFooter:DU,modalSizeSm:LU,modalSizeMd:OU,modalSizeMdWide:BU,modalSizeLg:WU,modalSizeXl:$U,modalSizeFull:FU,settingsViewModal:UU,unsavedOverlay:zU,unsavedModal:HU,unsavedHeader:GU,unsavedTitle:VU,unsavedContent:KU,unsavedText:qU,unsavedActions:YU},ZU=90;function sI(e){const t=Date.parse(String(e||"").trim());return Number.isFinite(t)?new Date(t+ZU*24*60*60*1e3).toISOString():null}function oI(e,t){const r=o.useRef(t);o.useLayoutEffect(()=>{r.current=t},[t]);const n=o.useMemo(()=>tx(e),[e]),s=o.useMemo(()=>n,[n.revision]);return o.useMemo(()=>({resolve:s.resolve,activate:i=>r.current(i)}),[s])}function iI(e,t,r){const[n,s]=o.useState(()=>new Set),i=o.useMemo(()=>new Map(e.map(h=>[h.taskId,h])),[e]),l=o.useMemo(()=>t.map(h=>i.get(h)).filter(h=>!!h),[t,i]),c=o.useMemo(()=>new Set(l.map(h=>h.id)),[l]);o.useEffect(()=>{s(h=>{const y=r?new Set(Array.from(h).filter(k=>c.has(k))):new Set;return y.size===h.size&&Array.from(y).every(k=>h.has(k))?h:y})},[r,c]);const d=o.useMemo(()=>l.filter(h=>n.has(h.id)),[l,n]),f=o.useCallback((h,y)=>{s(k=>{const b=new Set(k);return y?b.add(h):b.delete(h),b})},[]),p=o.useCallback(()=>{s(new Set(l.map(h=>h.id)))},[l]),g=o.useCallback(()=>s(new Set),[]);return{selectedIds:n,selectedRecords:d,matchingRecords:l,selectedCount:d.length,allMatchingSelected:l.length>0&&d.length===l.length,someMatchingSelected:d.length>0&&d.length<l.length,toggle:f,selectAllMatching:p,clear:g}}const rv="taskforce:preview-context-attachment";function Ff(e,t){const r=new CustomEvent(rv,{detail:{attachment:e,...t},cancelable:!0});return!window.dispatchEvent(r)}async function cI(e,t){const r=t.fetcher||fetch,n=new URLSearchParams({workspaceId:t.workspaceId});if(e.kind==="image"){const c=await r(`/api/taskforce/annotated-attachments/images/${encodeURIComponent(e.token)}?${n.toString()}`,{credentials:"include",headers:t.headers});if(!c.ok)throw new Error("Image not found");const f=(await c.json()).target;if(!f?.assetId||!f.path)throw new Error("Image target is unavailable");return{path:f.path,assetId:f.assetId,displayName:f.displayName,referenceNumber:e.referenceNumber,referenceLabel:f.imageReferenceLabel||e.token,linkRole:"image"}}const s=await r(`/api/taskforce/documents?${n.toString()}`,{credentials:"include",headers:t.headers});if(!s.ok)throw new Error("Document list unavailable");const l=(await s.json()).documents?.find(c=>c.referenceNumber===e.referenceNumber||String(c.referenceLabel||"").toUpperCase()===e.token);if(!l?.apiUrl)throw new Error("Document not found");return{path:l.apiUrl,fsPath:l.fsPath,assetId:l.assetId,displayName:l.title,originalFilename:l.originalFilename||void 0,referenceNumber:e.referenceNumber,referenceLabel:l.referenceLabel||e.token,linkRole:"reference"}}const wi={workspaceId:"workspaceId",task:"task",activity:"activity",comment:"comment",initiative:"initiative",workstream:"workstream",image:"image",document:"document"};function JU(e){const t=String(e||"").trim();if(!t)return null;try{const r=new URL(t);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.origin}catch{return null}}function QU(e){const t=JU(e.applicationBaseUrl),r=String(e.workspaceId).trim(),n=String(e.id||"").trim();if(!t||!r||!n)return null;const s=new URL("/",t);s.searchParams.set(wi.workspaceId,r),s.searchParams.set(wi[e.target],n);const i=String(e.activityId||"").trim();return e.target==="task"&&i&&s.searchParams.set(wi.activity,i),s.toString()}function XU(e){const t=e.charAt(0).toUpperCase()+e.slice(1).toLowerCase(),r={Category:"Categories",Priority:"Priorities",Status:"Statuses"};return r[t]?r[t]:`${e}s`}function md({label:e,options:t,selected:r,onChange:n,variant:s="label",containerStyle:i,renderOptionContent:l,searchable:c=!1,searchPlaceholder:d="Search options...",noResultsText:f="No matching options."}){const[p,g]=o.useState(!1),[h,y]=o.useState(""),k=o.useRef(null),b=o.useRef(null),C=o.useRef(null),S=c&&h.trim()?t.filter(j=>j.label.toLocaleLowerCase().includes(h.trim().toLocaleLowerCase())):t;o.useEffect(()=>{const j=F=>{k.current&&!k.current.contains(F.target)&&g(!1)};return document.addEventListener("mousedown",j),()=>document.removeEventListener("mousedown",j)},[]),o.useEffect(()=>{p&&c&&C.current?.focus()},[p,c]);const w=j=>{r.includes(j)?n(r.filter(F=>F!==j)):n([...r,j])},T=t.length>0&&t.every(j=>{const F=s==="label"?j.label:j.value;return r.includes(F)}),E=!t.some(j=>{const F=s==="label"?j.label:j.value;return r.includes(F)}),x=()=>{n(T?[]:t.map(j=>s==="label"?j.label:j.value))},N=t.filter(j=>{const F=s==="label"?j.label:j.value;return r.includes(F)}).length,v=XU(e),V=T?`All ${v}`:E?`No ${v}`:N===1?`1 ${e}`:`${N} ${v}`,_=()=>{y(""),g(j=>!j)};return a.jsxs("div",{className:R.filterContainer,ref:k,style:i,children:[a.jsxs("button",{ref:b,type:"button",className:`${R.filterButton} ${T?"":R.filterActive}`,onClick:_,title:`Filter by ${e}`,"aria-expanded":p,children:[a.jsx("span",{children:V}),a.jsx(Nd,{size:14,style:{transform:p?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),p&&a.jsxs("div",{className:`${R.filterDropdown} ${R.appScrollbar} tf-scrollbar`,onKeyDown:j=>{j.key==="Escape"&&(j.preventDefault(),g(!1),b.current?.focus())},children:[c?a.jsxs("div",{className:R.filterSearch,children:[a.jsx(bg,{size:14,className:R.filterSearchIcon,"aria-hidden":"true"}),a.jsx("input",{ref:C,type:"search",role:"searchbox",className:`tf-field-shell ${R.filterSearchInput}`,value:h,placeholder:d,"aria-label":d,onChange:j=>y(j.target.value)})]}):null,a.jsxs("label",{className:R.filterOption,children:[a.jsx("input",{type:"checkbox",checked:T,onChange:x}),a.jsx("span",{style:{fontWeight:600},children:"Toggle All"})]}),a.jsx("div",{className:R.filterDivider}),S.map(j=>{const F=s==="label"?j.label:j.value,z=r.includes(F);return a.jsxs("label",{className:R.filterOption,children:[a.jsx("input",{type:"checkbox",checked:z,onChange:()=>w(F)}),l?l(j):a.jsx("span",{children:j.label})]},j.value)}),S.length===0?a.jsx("div",{className:R.filterEmpty,role:"status",children:f}):null]})]})}const e6="_taskItem_1vtr8_1",t6="_compressed_1vtr8_25",r6="_taskHeader_1vtr8_30",a6="_taskReferenceCluster_1vtr8_35",n6="_taskMeta_1vtr8_39",s6="_taskTitle_1vtr8_45",o6="_taskCover_1vtr8_61",i6="_taskItemRecentlyChanged_1vtr8_105",c6="_assigneeAvatarShared_1vtr8_145",l6="_assigneePicker_1vtr8_158",d6="_inProgress_1vtr8_218",u6="_onHold_1vtr8_219",p6="_readyForReview_1vtr8_220",f6="_completed_1vtr8_221",m6="_cancelled_1vtr8_234",h6="_readOnly_1vtr8_245",g6="_archived_1vtr8_254",y6="_taskContent_1vtr8_264",k6="_kanbanCardOverlay_1vtr8_273",v6="_deletedExpiry_1vtr8_294",w6="_taskReferenceDivider_1vtr8_319",b6="_taskReferenceSegment_1vtr8_326",S6="_taskActions_1vtr8_333",A6="_taskMetaCompact_1vtr8_358",C6="_taskMetaRow_1vtr8_365",I6="_taskMetaBadgeGroup_1vtr8_375",_6="_taskMetaIdentityGroup_1vtr8_388",T6="_taskDescription_1vtr8_396",x6="_taskLatestComment_1vtr8_405",R6="_taskLatestCommentHeader_1vtr8_419",j6="_taskCommentCount_1vtr8_436",P6="_taskLatestCommentText_1vtr8_446",E6="_taskMetaCategory_1vtr8_456",N6="_taskMetaType_1vtr8_462",M6="_taskMetaPriority_1vtr8_468",D6="_taskComplexityLabel_1vtr8_472",L6="_taskCancellationReason_1vtr8_477",O6="_archiveBadge_1vtr8_630",B6="_attachmentThumbnails_1vtr8_635",W6="_attachmentImageRow_1vtr8_642",$6="_attachmentDocumentList_1vtr8_649",F6="_attachmentThumbnail_1vtr8_635",U6="_contextDocThumb_1vtr8_684",z6="_contextDocMain_1vtr8_710",H6="_contextDocName_1vtr8_717",G6="_taskSpecialists_1vtr8_727",V6="_taxonomiesList_1vtr8_736",K6="_selected_1vtr8_797",q6="_selectionControl_1vtr8_802",mr={taskItem:e6,compressed:t6,taskHeader:r6,taskReferenceCluster:a6,taskMeta:n6,taskTitle:s6,taskCover:o6,taskItemRecentlyChanged:i6,assigneeAvatarShared:c6,assigneePicker:l6,inProgress:d6,onHold:u6,readyForReview:p6,completed:f6,cancelled:m6,readOnly:h6,archived:g6,taskContent:y6,kanbanCardOverlay:k6,deletedExpiry:v6,taskReferenceDivider:w6,taskReferenceSegment:b6,taskActions:S6,taskMetaCompact:A6,taskMetaRow:C6,taskMetaBadgeGroup:I6,taskMetaIdentityGroup:_6,taskDescription:T6,taskLatestComment:x6,taskLatestCommentHeader:R6,taskCommentCount:j6,taskLatestCommentText:P6,taskMetaCategory:E6,taskMetaType:N6,taskMetaPriority:M6,taskComplexityLabel:D6,taskCancellationReason:L6,archiveBadge:O6,attachmentThumbnails:B6,attachmentImageRow:W6,attachmentDocumentList:$6,attachmentThumbnail:F6,contextDocThumb:U6,contextDocMain:z6,contextDocName:H6,taskSpecialists:G6,taxonomiesList:V6,selected:K6,selectionControl:q6};function Y6(e){return function(t){return T0(t,e)}}const Z6="I-",J6=new RegExp("(?<![\\w-])(I-\\d+)(?![\\w-])","gi");function Uf(e){return Kf(Z6,e)}const Q6="_prose_1rd59_1",X6="_taskReference_1rd59_56",ez="_tableScroll_1rd59_72",tz="_blockScroll_1rd59_99",rz="_compactCodePreview_1rd59_115",az="_taskList_1rd59_194",nz="_taskListItem_1rd59_198",sz="_taskCheckbox_1rd59_202",oz="_compact_1rd59_115",iz="_compactHeading_1rd59_231",cz="_codeLanguage_1rd59_262",lz="_contentIndicator_1rd59_271",dz="_detail_1rd59_277",uz="_conversation_1rd59_300",pz="_conversationHeading_1rd59_313",fz="_document_1rd59_321",Vn={prose:Q6,taskReference:X6,tableScroll:ez,blockScroll:tz,compactCodePreview:rz,taskList:az,taskListItem:nz,taskCheckbox:sz,compact:oz,compactHeading:iz,codeLanguage:cz,contentIndicator:lz,detail:dz,conversation:uz,conversationHeading:pz,document:fz};function mz(e){const t=e.trim();if(!t)return"";if(/^(?:#|\/|\.\/|\.\.\/)/.test(t))return t;const r=t.match(/^([a-z][a-z0-9+.-]*):/i)?.[1]?.toLowerCase();return r?r==="http"||r==="https"||r==="mailto"?t:"":t}function pS(e){return/^(?:https?:)?\/\//i.test(String(e||""))}function hz(e){return String(e||"").match(/(?:^|\s)language-([\w-]+)/)?.[1]||""}const gz=({children:e,variant:t,className:r,taskReferences:n,imageReferences:s,documentOverrides:i})=>{if(!e)return null;if(i&&t!=="document")throw new Error("documentOverrides are only supported by the document Markdown variant.");const l=g=>{if(typeof g=="string"){const k=(C,S,w,T)=>{const E=Array.from(C.matchAll(S));if(!E.length)return[C];const x=[];let N=0;return E.forEach((v,V)=>{const _=v[1],j=v.index??-1;if(j<N)return;j>N&&x.push(C.slice(N,j));const F=w(_);x.push(F?T(F,_,`${_}-${j}-${V}`):_),N=j+_.length}),N<C.length&&x.push(C.slice(N)),x};let b=[g];if(n&&(b=b.flatMap(C=>typeof C=="string"?k(C,X0,n.resolve,(S,w,T)=>a.jsx("button",{type:"button",className:Vn.taskReference,onClick:E=>{E.preventDefault(),E.stopPropagation(),n.activate(S)},children:w},`task-${T}`)):[C])),s&&(b=b.flatMap(C=>typeof C=="string"?k(C,J6,s.resolve,(S,w,T)=>a.jsx("button",{type:"button",className:Vn.taskReference,onClick:E=>{E.preventDefault(),E.stopPropagation(),s.activate(S)},children:w},`image-${T}`)):[C])),n?.entityReferences){const C=n.entityReferences;b=b.flatMap(S=>typeof S=="string"?k(S,Y0,C.resolve,(w,T,E)=>a.jsx("button",{type:"button",className:Vn.taskReference,title:`Open ${w.kind} ${w.token}`,onClick:x=>{x.preventDefault(),x.stopPropagation(),C.activate(w)},children:T},`entity-${E}`)):[S])}return b.length===1?b[0]:b}if(Array.isArray(g))return g.map(l);if(!Y.isValidElement(g))return g;const h=g.props,y=typeof g.type=="string"?g.type:h.node?.tagName||"";return y==="a"||y==="button"||y==="code"||y==="pre"||y==="p"||h.children===void 0?g:Y.cloneElement(g,void 0,Y.Children.map(h.children,l))},c=(g,h)=>{const y=l(h);return t==="compact"?a.jsx("div",{className:Vn.compactHeading,children:y}):t==="conversation"?a.jsx("h3",{className:Vn.conversationHeading,children:y}):Y.createElement(`h${g}`,void 0,y)},d={h1:({children:g})=>c(1,g),h2:({children:g})=>c(2,g),h3:({children:g})=>c(3,g),h4:({children:g})=>c(4,g),h5:({children:g})=>c(5,g),h6:({children:g})=>c(6,g),p:({children:g})=>a.jsx("p",{children:l(g)}),ul:({children:g,className:h,node:y,...k})=>a.jsx("ul",{...k,className:`${h||""} ${String(h||"").includes("contains-task-list")?Vn.taskList:""}`.trim(),children:g}),ol:({children:g,className:h,node:y,...k})=>a.jsx("ol",{...k,className:`${h||""} ${String(h||"").includes("contains-task-list")?Vn.taskList:""}`.trim(),children:g}),li:({children:g,className:h,node:y,...k})=>{const b=String(h||"").includes("task-list-item");return a.jsx("li",{...k,className:`${h||""} ${b?Vn.taskListItem:""}`.trim(),children:l(g)})},input:({type:g,checked:h,node:y,...k})=>g!=="checkbox"?a.jsx("input",{type:g,checked:h,readOnly:!0,...k}):a.jsx("input",{...k,type:"checkbox",checked:!!h,readOnly:!0,className:Vn.taskCheckbox}),a:({href:g,children:h,node:y,...k})=>{if(!g)return a.jsx("span",{children:h});const b=pS(g);return a.jsx("a",{...k,href:g,...b?{target:"_blank",rel:"noopener noreferrer"}:{},onClick:C=>C.stopPropagation(),children:h})},strong:({children:g})=>a.jsx("strong",{children:g}),em:({children:g})=>a.jsx("em",{children:g}),code:({children:g,className:h,node:y,...k})=>a.jsx("code",{className:h,...k,children:g}),pre:({children:g})=>{const h=Y.Children.toArray(g).find(Y.isValidElement),y=hz(h?.props.className);return t==="compact"?a.jsxs("div",{className:Vn.compactCodePreview,children:[y?a.jsx("span",{className:Vn.codeLanguage,children:y}):null,a.jsx("pre",{children:g})]}):a.jsx("div",{className:Vn.blockScroll,children:a.jsx("pre",{children:g})})},blockquote:({children:g})=>a.jsx("blockquote",{children:g}),table:({children:g,node:h,...y})=>t==="compact"?a.jsx("span",{className:Vn.contentIndicator,children:"[Table]"}):a.jsx("div",{className:Vn.tableScroll,role:"region","aria-label":"Scrollable table",tabIndex:0,children:a.jsx("table",{...y,children:g})}),img:({src:g,alt:h})=>{const y=String(h||"").trim();if(t==="compact"||t==="conversation"){if(!y)return null;const k=`[Image: ${y}]`;if(!g)return a.jsx("span",{className:Vn.contentIndicator,children:k});const b=pS(g);return a.jsx("a",{href:g,className:Vn.contentIndicator,...b?{target:"_blank",rel:"noopener noreferrer"}:{},onClick:C=>C.stopPropagation(),children:k})}return a.jsx("img",{src:g,alt:y})},hr:()=>t==="compact"?null:a.jsx("hr",{})},f=t==="document"&&i?{...d,...i}:d,p=t==="document"?[sb]:[sb,R0];return a.jsx("div",{className:`${Vn.prose} ${Vn[t]} ${r||""}`.trim(),"data-markdown-surface":t,children:a.jsx(x0,{skipHtml:!0,remarkPlugins:p,rehypePlugins:[Y6],urlTransform:mz,components:f,children:e})})},Mg=Y.memo(gz);function nw({label:e,title:t,ariaLabel:r,copied:n=!1,disabled:s=!1,className:i="",onClick:l,children:c}){return a.jsx("button",{type:"button",className:`${R.referenceBadge} ${n?R.copiedReference:""} ${i}`.trim(),onClick:l,disabled:s,title:t,"aria-label":r,children:a.jsx("span",{className:R.referenceBadgeLabel,children:c??e})})}function Ou({copied:e,disabled:t=!1,label:r,onClick:n,title:s="Copy task reference",ariaLabel:i,className:l="",provisional:c=!1}){return a.jsx(nw,{copied:e,disabled:t,label:"",onClick:n,title:s,ariaLabel:i,className:`${c?R.provisionalReferenceBadge:""} ${l}`.trim(),children:r})}const yz=(e,t=10)=>{const r=rg[e?.toLowerCase()]||{icon:"FileCode"},n=Gs[r.icon]||jT;return a.jsx(n,{size:t})},kh=(e,t)=>{if(!e)return null;const r=t.trim();if(!r)return e;const s=Eg(r)?.match(/^(lt|t)-(\d+)$/),i=s?`${s[1]==="lt"?"l\\s*t":"t"}\\s*(?:-|\\s)?\\s*${s[2]}`:r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`^${i}$`,"i"),c=e.split(new RegExp(`(${i})`,"gi"));return a.jsx(a.Fragment,{children:c.map((d,f)=>l.test(d)?a.jsx("mark",{className:R.highlight,children:d},f):d)})};function zf(e){return e.trim().replace(/\\/g,"/")}function lI(e){return e.split("?")[0].split("#")[0]}function Dg(e){return typeof e=="string"?e:String(e.path||"").trim()}function dI(e){const r=lI(zf(e)).match(/\/api\/taskforce\/documents\/([^/]+)\/content$/i);if(!r?.[1])return null;try{return decodeURIComponent(r[1]).trim()||null}catch{return r[1].trim()||null}}function uI(e){if(!e.includes("/api/taskforce/context-link?path="))return null;try{const r=new URL(e,window.location.origin).searchParams.get("path");return r?zf(r):null}catch{return null}}function kz(e,t){const r=(t||(typeof e=="string"?"":e.fsPath||"")).trim();if(r)return zf(r);const n=Dg(e),s=uI(n);return s?zf(s):null}function vz(e,t){const r=String(typeof e=="string"?"":e.assetId||"").trim();if(r)return r;const n=Dg(e);return dI(n)}function pI(e,t){const r=Dg(e);return dI(r)?!0:[(t||(typeof e=="string"?"":e.fsPath||"")).trim(),typeof e=="string"?"":String(e.originalFilename||"").trim(),typeof e=="string"?"":String(e.displayName||"").trim(),typeof e=="string"?"":String(e.caption||"").trim(),uI(r)||"",r].some(s=>{if(!s)return!1;const i=lI(zf(s)).toLowerCase();return i.endsWith(".md")||i.endsWith(".markdown")})}function fI(e,t){const r=Dg(e),n=kz(e,t),s=vz(e);if(!n&&!s||!pI(e,n||void 0))return!1;const i=new CustomEvent("taskforce:open-markdown-document",{detail:{path:r,...n?{fsPath:n}:{},...s?{assetId:s}:{},...typeof e!="string"&&e.taskId?{taskId:e.taskId}:{}},cancelable:!0});return!window.dispatchEvent(i)}function mI(e,t){return e?JSON.stringify([String(e.taskId||"").trim(),String(e.assetId||"").trim(),String(t||"").trim()]):""}function wz(e){const t=mI(e.currentTarget,e.currentSessionId);return!t||t===e.lastHydratedIdentity}function bz(e){return e.trim().replace(/\\/g,"/")}function hI(e){return typeof e=="string"?e:String(e.path||"").trim()}function Sz(e){return/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(e)}function Az(e){return typeof e=="string"?bz(e).split("/").pop()||"Image attachment":String(e.caption||e.displayName||e.originalFilename||e.fsPath||e.path.split("/").pop()||"Image attachment").trim()}function gI(e,t){if(typeof e=="string")return!1;const r=String(e.assetId||"").trim(),n=hI(e);return!!(r&&n&&Sz(n))}function av(e,t){if(!gI(e))return!1;const r=e,n=String(t?.taskId||r.taskId||"").trim(),s=String(t?.taskReferenceLabel||"").trim(),i=String(r.assetId||"").trim(),l=Uf(r),c=String(t?.sessionId||"").trim(),d=hI(e),f=new CustomEvent("taskforce:open-annotated-attachment",{detail:{...n?{taskId:n}:{},...s?{taskReferenceLabel:s}:{},assetId:i,...l?{imageReferenceLabel:l}:{},...c?{sessionId:c}:{},path:d,displayName:Az(e)},cancelable:!0});return!window.dispatchEvent(f)}function fS(e,t){if(!e)return null;const r=String(e.taskId||"").trim(),n=String(e.assetId||"").trim(),s=String(e.path||"").trim(),i=String(e.displayName||"").trim()||"Image attachment";if(!n||!s)return null;const l=String(e.taskReferenceLabel||"").trim(),c=r?t.find(f=>f.id===r):void 0,d=r?l||hs(c)||r:void 0;return{...r?{taskId:r}:{},...d?{taskReferenceLabel:d}:{},assetId:n,imageReferenceLabel:String(e.imageReferenceLabel||"").trim()||void 0,sessionId:String(e.sessionId||"").trim()||void 0,path:s,displayName:i}}function og(e){const t=String(e||"").trim().replace(/\\/g,"/");if(!t)return"";const r=t.split("/").filter(Boolean);return r[r.length-1]||""}function sw(e){const t=String(e||"").trim(),r=t.lastIndexOf(".");return r<=0?{stem:t,ext:""}:{stem:t.slice(0,r),ext:t.slice(r)}}function yI(e,t){const r=String(e||"").trim(),n=String(t||"").trim();return r?n&&r.startsWith(`${n}-`)?r.slice(n.length+1):r.replace(/^asset-[a-z0-9-]+-/i,""):""}function Cz(e){return String(e||"").replace(/-\d{13,}$/g,"").replace(/[_-]+/g," ").replace(/\s+/g," ").trim()}function mS(e,t){const{stem:r,ext:n}=sw(og(e)),s=yI(r,t),i=Cz(s||r);return i?`${i}${n}`:og(e)||"Untitled document"}function pk(e,t){const r=String(e||"").trim();if(!r)return!0;const n=og(r),{stem:s}=sw(n),i=String(t||"").trim();if(i&&s.toLowerCase()===i.toLowerCase())return!0;const l=yI(s,t);return l?l!==s:!0}function Iz(e){const t=String(e.title||"").trim();if(t&&!pk(t,e.assetId))return t;const r=String(e.logicalName||"").trim();if(r&&!pk(r,e.assetId))return r;const n=String(e.displayName||"").trim();if(n&&!pk(n,e.assetId))return n;const s=String(e.originalFilename||"").trim();if(s)return mS(s,e.assetId);const i=String(e.fsPath||"").trim();return i?mS(i,e.assetId):"Untitled document"}function _z(e){return Iz(e)}function Tz(e){const t=_z(e),r=String(e.originalFilename||e.fsPath||"").trim(),n=sw(og(r)).ext;return n?t.toLowerCase().endsWith(n.toLowerCase())?t:`${t}${n}`:t}const xz="_taxonomyDropdown_1qrdm_1",Rz="_taxonomyDropdownActive_1qrdm_6",jz="_taxonomyDropdownButton_1qrdm_11",Pz="_taxonomyDropdownOpen_1qrdm_50",Ez="_taxonomyDropdownButtonContent_1qrdm_56",Nz="_taxonomyDropdownIcon_1qrdm_64",Mz="_taxonomyDropdownLabel_1qrdm_72",Dz="_taxonomyDropdownChevron_1qrdm_81",Lz="_taxonomyDropdownChevronOpen_1qrdm_87",Oz="_taxonomyDropdownPanel_1qrdm_91",Bz="_taxonomyDropdownOptions_1qrdm_111",Wz="_taxonomyDropdownSearch_1qrdm_117",$z="_taxonomyDropdownSearchIcon_1qrdm_125",Fz="_taxonomyDropdownSearchInput_1qrdm_134",Uz="_taxonomyDropdownEmpty_1qrdm_148",zz="_taxonomyDropdownActions_1qrdm_155",Hz="_taxonomyDropdownAction_1qrdm_155",Gz="_taxonomyDropdownPanelPortal_1qrdm_195",Vz="_taxonomyDropdownOption_1qrdm_111",Kz="_taxonomyDropdownOptionHighlighted_1qrdm_245",qz="_taxonomyDropdownOptionSelected_1qrdm_251",tn={taxonomyDropdown:xz,taxonomyDropdownActive:Rz,taxonomyDropdownButton:jz,taxonomyDropdownOpen:Pz,taxonomyDropdownButtonContent:Ez,taxonomyDropdownIcon:Nz,taxonomyDropdownLabel:Mz,taxonomyDropdownChevron:Dz,taxonomyDropdownChevronOpen:Lz,taxonomyDropdownPanel:Oz,taxonomyDropdownOptions:Bz,taxonomyDropdownSearch:Wz,taxonomyDropdownSearchIcon:$z,taxonomyDropdownSearchInput:Fz,taxonomyDropdownEmpty:Uz,taxonomyDropdownActions:zz,taxonomyDropdownAction:Hz,taxonomyDropdownPanelPortal:Gz,taxonomyDropdownOption:Vz,taxonomyDropdownOptionHighlighted:Kz,taxonomyDropdownOptionSelected:qz};function fk(e,t){const r=e||"var(--brand-primary)";return/^#[0-9a-f]{6}$/i.test(r)?`${r}${Math.round(t*255).toString(16).padStart(2,"0")}`:`color-mix(in srgb, ${r} ${Math.round(t*100)}%, transparent)`}function ai({value:e,options:t,onChange:r,placeholder:n="Select...",required:s=!1,disabled:i=!1,className:l="",ariaLabelledBy:c,ariaLabel:d,title:f,hideSelectedLabel:p=!1,hideChevron:g=!1,panelClassName:h="",portalPanel:y=!1,panelMinWidth:k,panelAlign:b="end",renderOptionContent:C,triggerContent:S,optionLabelColor:w,searchable:T=!1,searchPlaceholder:E="Search options...",noResultsText:x="No matching options.",panelActions:N=[]}){const[v,V]=o.useState(!1),[_,j]=o.useState(-1),[F,z]=o.useState({}),[M,O]=o.useState(),[Z,U]=o.useState(""),ve=o.useRef(null),te=o.useRef(null),ce=o.useRef(null),Le=o.useRef(null),Ie=o.useRef([]),Ye=o.useRef([]),ge=o.useRef(null),he=`taxonomy-listbox-${Y.useId().replace(/:/g,"")}`,Ae=t.find(Q=>String(Q.value)===String(e)),ye=Y.useMemo(()=>{const Q=Z.trim().toLocaleLowerCase();return!T||!Q?t:t.filter(H=>H.label.toLocaleLowerCase().includes(Q))},[t,Z,T]);o.useEffect(()=>{if(!v)return;const Q=H=>{const se=H.target,Pe=!!ve.current?.contains(se),ue=!!ce.current?.contains(se);!Pe&&!ue&&(V(!1),j(-1))};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[v]),o.useEffect(()=>{if(!v)j(-1);else{const Q=ye.findIndex(H=>String(H.value)===String(e));j(Q>=0?Q:ye.length>0?0:-1)}},[v,e,ye]),o.useEffect(()=>{v&&T&&ge.current?.focus()},[v,T]),o.useEffect(()=>{!v||_<0||Ie.current[_]?.scrollIntoView?.({block:"nearest"})},[_,v]),o.useEffect(()=>{if(!v||!y)return;const Q=Pe=>{const ue=te.current;if(!ue)return;const ne=ue.getBoundingClientRect(),Me=8,pe=window.innerWidth,le=window.innerHeight,Ce=Math.max(0,pe-Me*2);(Pe||Le.current===null)&&(Le.current=Math.min(Math.max(k||0,ne.width),Ce));const P=Math.min(Le.current,Ce),ee=b==="start"?ne.left:ne.right-P,Se=Math.min(Math.max(Me,ee),Math.max(Me,pe-P-Me)),_e=Math.max(0,le-ne.bottom-Me),ke=Math.max(0,ne.top-Me),Ze=Math.min(ce.current?.scrollHeight||280,280),st=_e>=Ze||_e>=ke,at=st?_e:ke;z({position:"fixed",top:st?ne.bottom:void 0,bottom:st?void 0:le-ne.top,left:Se,width:P,minWidth:P,maxWidth:Ce,maxHeight:Math.min(Ze,at),zIndex:2e3})},H=Pe=>{const ue=Pe.target;ue instanceof Node&&ce.current?.contains(ue)||Q(!1)},se=()=>Q(!0);return Le.current=null,Q(!0),window.addEventListener("resize",se),window.addEventListener("scroll",H,!0),()=>{window.removeEventListener("resize",se),window.removeEventListener("scroll",H,!0),Le.current=null}},[v,b,y,k]);const Ne=()=>{if(T&&U(""),y){const Q=ve.current?.closest("[data-theme]");O(Q?.dataset.theme)}V(!0)},ae=()=>{if(!i){if(v){V(!1);return}Ne()}},q=Q=>{r(Q.value),U(""),V(!1),te.current?.focus()},W=Q=>{Q.disabled||(Q.onSelect(),U(""),V(!1),te.current?.focus())},K=Q=>{if(i)return;const H=Q.currentTarget===ge.current;switch(Q.key){case"Enter":if(Q.preventDefault(),!v)Ne();else if(_>=0){const se=ye[_];se&&q(se)}break;case" ":if(H)return;if(Q.preventDefault(),!v)Ne();else if(_>=0){const se=ye[_];se&&q(se)}break;case"Escape":Q.preventDefault(),V(!1),te.current?.focus();break;case"ArrowDown":Q.preventDefault(),v?ye.length===0?j(-1):j(se=>se<ye.length-1?se+1:0):Ne();break;case"ArrowUp":Q.preventDefault(),v?ye.length===0?j(-1):j(se=>se>0?se-1:ye.length-1):Ne();break;case"Home":if(H)return;Q.preventDefault(),v&&j(ye.length>0?0:-1);break;case"End":if(H)return;Q.preventDefault(),v&&j(ye.length>0?ye.length-1:-1);break;case"Tab":if(v&&!Q.shiftKey&&N.length>0){Q.preventDefault(),Ye.current[0]?.focus();break}V(!1);break}},Re=(Q,H)=>{const se=Q.icon&&Gs[Q.icon]?Gs[Q.icon]:Td,Pe=Q.color?rn(Q.color):"var(--text-secondary)",ue=H?.hideLabel===!0;return a.jsxs(a.Fragment,{children:[a.jsx("span",{className:`taxonomyDropdownIcon ${tn.taxonomyDropdownIcon}`,style:{color:Pe},children:a.jsx(se,{size:16})}),!ue&&a.jsx("span",{className:`taxonomyDropdownLabel ${tn.taxonomyDropdownLabel}`,style:H?.labelColor?{color:H.labelColor}:void 0,children:Q.label})]})},we=(Q,H)=>!H?.hideLabel&&C?C(Q):Re(Q,H),ie=v?a.jsxs("div",{ref:ce,id:`${he}-panel`,className:`taxonomyDropdownPanel ${tn.taxonomyDropdownPanel} ${y?tn.taxonomyDropdownPanelPortal:""} ${h}`,"data-theme":y?M:void 0,style:y?F:void 0,children:[T?a.jsxs("div",{className:tn.taxonomyDropdownSearch,children:[a.jsx(bg,{size:15,className:tn.taxonomyDropdownSearchIcon,"aria-hidden":"true"}),a.jsx("input",{ref:ge,type:"search",role:"searchbox",className:`tf-field-shell ${tn.taxonomyDropdownSearchInput}`,value:Z,placeholder:E,"aria-label":E,"aria-controls":he,"aria-activedescendant":_>=0?`${he}-option-${_}`:void 0,onChange:Q=>U(Q.target.value),onKeyDown:K})]}):null,a.jsx("div",{id:he,className:`tf-scrollbar tf-scrollbar--compact ${tn.taxonomyDropdownOptions}`,role:"listbox","aria-labelledby":c,"aria-label":d,children:ye.map((Q,H)=>{const se=String(Q.value)===String(e),Pe=H===_;return a.jsx("div",{ref:ue=>{Ie.current[H]=ue},id:`${he}-option-${H}`,className:`taxonomyDropdownOption ${tn.taxonomyDropdownOption} ${se?`taxonomyDropdownOptionSelected ${tn.taxonomyDropdownOptionSelected}`:""} ${Pe?`taxonomyDropdownOptionHighlighted ${tn.taxonomyDropdownOptionHighlighted}`:""}`,role:"option","aria-selected":se,onClick:()=>q(Q),onMouseEnter:()=>j(H),style:(()=>{const ue=Q.color,Me=rn(ue)||"var(--brand-primary)";return{"--option-color":Me,"--option-border":fk(Me,.18),"--option-bg":fk(Me,.06)}})(),children:we(Q,{labelColor:w})},String(Q.value))})}),ye.length===0?a.jsx("div",{className:tn.taxonomyDropdownEmpty,role:"status",children:x}):null,N.length>0?a.jsx("div",{className:tn.taxonomyDropdownActions,role:"group","aria-label":"Actions",children:N.map((Q,H)=>{const se=Q.icon&&Gs[Q.icon]?Gs[Q.icon]:null;return a.jsxs("button",{ref:Pe=>{Ye.current[H]=Pe},type:"button",className:tn.taxonomyDropdownAction,disabled:Q.disabled,onClick:()=>W(Q),onKeyDown:Pe=>{Pe.key==="Escape"?(Pe.preventDefault(),V(!1),te.current?.focus()):Pe.key==="Tab"&&!Pe.shiftKey&&V(!1)},children:[se?a.jsx(se,{size:16,"aria-hidden":"true"}):null,a.jsx("span",{children:Q.label})]},Q.id)})}):null]}):null;return a.jsxs("div",{ref:ve,className:`taxonomyDropdown ${tn.taxonomyDropdown} ${v?`taxonomyDropdownActive ${tn.taxonomyDropdownActive}`:""} ${l}`,children:[a.jsxs("button",{ref:te,type:"button",className:`taxonomyDropdownButton ${tn.taxonomyDropdownButton} ${v?`taxonomyDropdownOpen ${tn.taxonomyDropdownOpen}`:""}`,onClick:ae,onKeyDown:K,disabled:i,role:"combobox","aria-haspopup":"listbox","aria-expanded":v,"aria-controls":he,"aria-activedescendant":v&&_>=0?`${he}-option-${_}`:void 0,"aria-labelledby":c,"aria-label":d,title:f,style:(()=>{if(!Ae)return{};const Q=Ae.color,H=rn(Q);return{"--field-bg":fk(H,.06)}})(),children:[a.jsx("span",{className:`taxonomyDropdownButtonContent ${tn.taxonomyDropdownButtonContent}`,children:S??(Ae?we(Ae,{hideLabel:p}):a.jsxs(a.Fragment,{children:[a.jsx("span",{className:`taxonomyDropdownIcon ${tn.taxonomyDropdownIcon}`,children:a.jsx(Td,{size:16})}),a.jsx("span",{className:`taxonomyDropdownLabel ${tn.taxonomyDropdownLabel}`,children:n})]}))}),!g&&a.jsx(Nd,{size:16,className:`taxonomyDropdownChevron ${tn.taxonomyDropdownChevron} ${v?`taxonomyDropdownChevronOpen ${tn.taxonomyDropdownChevronOpen}`:""}`})]}),y?ie?tc.createPortal(ie,document.body):null:ie]})}function ig({task:e,status:t,disabled:r=!1,actionDisabled:n,statusDisabled:s,compressed:i=!1,shortLabels:l=!1,showLabel:c=!0,onSetStatus:d,onStatusChange:f,onArchiveTask:p,onUnarchiveTask:g,archiveActionMode:h="auto"}){const y=e?.status||t||"task",b=h==="auto"?!!e&&(y==="done"||y==="cancelled")?"archive":"none":h,C=n??r,S=s??r,w=wd.map(N=>({...N,label:(i||l)&&N.shortLabel||N.label})),T=rn(wd.find(N=>N.value===y)?.color)||"var(--text-secondary)",E={"--field-border":T,"--field-text":T,"--field-hover-border":T,"--field-focus-border":T,"--field-focus-ring":`color-mix(in srgb, ${T} 18%, transparent)`},x=b==="archive"&&e?[{id:"archive-task",label:"Archive task",icon:"Archive",disabled:C||!p,onSelect:()=>p?.(e)}]:[];return a.jsxs("div",{className:`${R.statusActionsGroup} ${i?R.statusActionsGroupCompact:""}`,children:[b==="unarchive"&&a.jsx("button",{type:"button",className:`${R.actionBtn} ${R.restoreTaskBtn}`,onClick:()=>e&&!C&&g?.(e),disabled:C,title:"Unarchive task","aria-label":"Unarchive task",children:a.jsx(bi,{size:i?12:16})}),a.jsx("div",{className:`${R.statusSelectWrap} ${R.statusTaxonomyDropdownWrap}`,style:E,children:a.jsx(ai,{value:y,options:w,disabled:S||!e&&!f,ariaLabel:"Status",optionLabelColor:"var(--text-primary)",hideSelectedLabel:!c,hideChevron:!c,className:`${R.statusTaxonomyDropdown} ${i?R.statusTaxonomyDropdownCompact:""} ${c?"":R.statusTaxonomyDropdownIconOnly}`,panelClassName:c?"":R.statusTaxonomyDropdownIconOnlyPanel,portalPanel:!c,panelMinWidth:c?void 0:144,panelActions:x,onChange:N=>{const v=N;if(e){d?.(e,v);return}f?.(v)}})})]})}function Yz(e){return e==="taskId"?"Task":e==="title"?"Title":e==="description"?"Description":e==="assignee"?"Assigned to":e==="ownerId"?"Owner":e==="status"?"Status":e==="scheduledDate"?"Scheduled date":e==="dueDate"?"Due date":e==="workstreamId"?"Workstream":e==="initiativeId"?"Initiative":e}function Zz(e){return e==="task"?"Task":e.replace(/[-_]+/g," ").replace(/\s+/g," ").trim().replace(/\b\w/g,t=>t.toUpperCase())}function ps(e,t,r){const n=r?.(t,e);if(typeof n=="string")return n;if(e==null||e==="")return"none";if(Array.isArray(e)){const s=e.map(i=>ps(i,t,r)).filter(Boolean);return s.length>0?s.join(", "):"none"}return typeof e=="object"?"updated":t==="status"?Zz(String(e)):String(e)}function hS(e){return Array.isArray(e)?e.map((t,r)=>{const n=t&&typeof t=="object"?t:{},s=Number(n.order);return{id:String(n.id||"").trim(),title:String(n.title||"").trim(),isCompleted:!!n.isCompleted,order:Number.isFinite(s)?s:r}}):[]}function Jz(e){const t=hS(e?.from),r=hS(e?.to),n=new Map(t.map(l=>[l.id||l.title,l])),s=new Map(r.map(l=>[l.id||l.title,l]));for(const[l,c]of s.entries()){const d=n.get(l);if(!d)return c.title?`Checklist item added: ${c.title}`:"Checklist item added";if(d.isCompleted!==c.isCompleted)return c.title?c.isCompleted?`Checklist item completed: ${c.title}`:`Checklist item reopened: ${c.title}`:c.isCompleted?"Checklist item completed":"Checklist item reopened"}for(const[l,c]of n.entries())if(!s.has(l))return c.title?`Checklist item removed: ${c.title}`:"Checklist item removed";return t.length===r.length&&t.every(l=>s.has(l.id||l.title))&&t.some((c,d)=>{const f=r[d];return(c.id||c.title)!==(f?.id||f?.title)})?"Checklist reordered":"Checklist updated"}function ow(e){return e.split(/[?#]/,1)[0]||e}function gS(e){const t=ow(e).replace(/\\/g,"/"),r=t.split("/").filter(Boolean);return r[r.length-1]||t}function Qz(e){return/\.(png|jpe?g|webp|gif)$/i.test(ow(e))}function Xz(e){return e.includes("/api/taskforce/documents/")?!0:/\.(pdf|txt|md|markdown|csv|json|docx?|html?|js|jsx|ts|tsx|css|py|java|go|rs|sh)$/i.test(ow(e))}function yS(e){return Array.isArray(e)?e.flatMap((t,r)=>{const n=t&&typeof t=="object"?t:null,s=typeof t=="string"?t:String(n?.path||"").trim(),i=String(n?.fsPath||"").trim(),l=String(n?.assetId||"").trim(),c=String(n?.referenceLabel||"").trim(),d=[n?.displayName,n?.originalFilename,n?.caption,c,i?gS(i):"",s?gS(s):""].map(h=>String(h||"").trim()).find(Boolean)||`Attachment ${r+1}`,f=l||i||s||`${d}:${r}`,p=[s,i,String(n?.originalFilename||"").trim(),String(n?.displayName||"").trim(),c].filter(Boolean),g=p.some(h=>Qz(h))?"image":c.startsWith("D-")||p.some(h=>Xz(h))?"document":"attachment";return[{key:f,label:d,kind:g}]}):[]}function e8(e,t){return t===1?e:e==="image"?"images":e==="document"?"documents":"attachments"}function vh(e){if(e.length===0)return"attachments";const t=e.reduce((n,s)=>(n[s.kind]+=1,n),{image:0,document:0,attachment:0}),r=Object.entries(t).filter(([,n])=>n>0).map(([n,s])=>s===1?n:`${s} ${e8(n,s)}`);return r.length===1?r[0]:e.length<=3&&r.length<=2?r.join(" and "):`${e.length} attachments`}function ul(e){return e&&e.charAt(0).toUpperCase()+e.slice(1)}function mk(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean):[]}function t8(e){if(Array.isArray(e.from)||Array.isArray(e.to)||!["fromCount","toCount","added","removed","updated"].some(c=>Object.prototype.hasOwnProperty.call(e,c)))return null;const r=mk(e.added),n=mk(e.removed),s=mk(e.updated);if(r.length===1&&n.length===0&&s.length===0)return`Attachment attached: ${r[0]}`;if(n.length===1&&r.length===0&&s.length===0)return`Attachment removed: ${n[0]}`;if(r.length===1&&n.length===1&&s.length===0)return`Attachment replaced: ${n[0]} -> ${r[0]}`;if(s.length===1&&r.length===0&&n.length===0)return`Attachment updated: ${s[0]}`;if(s.length>0&&r.length===0&&n.length===0)return`${s.length} attachments updated`;if(r.length>0||n.length>0){const c=[...r.length>0?[`${r.length} ${r.length===1?"attachment":"attachments"} attached`]:[],...n.length>0?[`${n.length} ${n.length===1?"attachment":"attachments"} removed`]:[],...s.length>0?[`${s.length} ${s.length===1?"attachment":"attachments"} updated`]:[]];return ul(c.join(", "))}const i=Number(e.fromCount),l=Number(e.toCount);if(Number.isSafeInteger(i)&&i>=0&&Number.isSafeInteger(l)&&l>=0){const c=l-i;if(c===1)return"Attachment attached";if(c>1)return`${c} attachments attached`;if(c===-1)return"Attachment removed";if(c<-1)return`${Math.abs(c)} attachments removed`}return"Attachment details updated"}function r8(e){const t=e?t8(e):null;if(t)return t;const r=yS(e?.from),n=yS(e?.to),s=new Map(r.map(f=>[f.key,f])),i=new Map(n.map(f=>[f.key,f])),l=n.filter(f=>!s.has(f.key)),c=r.filter(f=>!i.has(f.key));if(l.length===1&&c.length===0)return`${ul(l[0].kind)} attached: ${l[0].label}`;if(c.length===1&&l.length===0)return`${ul(c[0].kind)} removed: ${c[0].label}`;if(l.length>0&&c.length===0)return`${ul(vh(l))} attached`;if(c.length>0&&l.length===0)return`${ul(vh(c))} removed`;if(l.length===1&&c.length===1)return`${ul(l[0].kind)} replaced: ${c[0].label} -> ${l[0].label}`;if(l.length>0||c.length>0)return`${ul(vh(l))} attached, ${vh(c)} removed`;const d=n.filter(f=>{const p=s.get(f.key);return p&&p.label!==f.label});if(d.length===1&&r.length===1&&n.length===1){const f=s.get(d[0].key);return`${ul(d[0].kind)} renamed: ${f?.label||"Attachment"} -> ${d[0].label}`}return"Attachment details updated"}function cg(e,t,r){if(e==="checklistItems")return Jz(t);if(e==="attachments")return r8(t);const n=Yz(e);if(e==="title")return`${n}: updated`;if(e==="description"){const s=ps(t?.from,e,r)!=="none",i=ps(t?.to,e,r)!=="none";return!s&&i?`${n}: added`:s&&!i?`${n}: cleared`:`${n}: updated`}return`${n}: ${ps(t?.from,e,r)} -> ${ps(t?.to,e,r)}`}function kI(e,t){const r=e.details?.changes||{},n=Object.keys(r);if(e.action==="task-created")return"Task created";if(e.action==="task-comment-added")return"Comment added";if(e.action==="task-archived")return"Task marked done";if(e.action==="task-cancelled")return"Task cancelled";if(e.action==="task-unarchived")return"Task restored";if(e.action==="task-status-changed"&&r.status)return`Status changed: ${ps(r.status.from,"status",t)} -> ${ps(r.status.to,"status",t)}`;if(e.action==="task-schedule-changed")return r.scheduledDate?`Scheduled date changed: ${ps(r.scheduledDate.from,"scheduledDate",t)} -> ${ps(r.scheduledDate.to,"scheduledDate",t)}`:r.dueDate?`Due date changed: ${ps(r.dueDate.from,"dueDate",t)} -> ${ps(r.dueDate.to,"dueDate",t)}`:"Schedule updated";if(e.action==="task-relationship-changed"&&r.workstreamId)return`Workstream changed: ${ps(r.workstreamId.from,"workstreamId",t)} -> ${ps(r.workstreamId.to,"workstreamId",t)}`;if(e.action==="task-relationship-changed"&&r.initiativeId)return`Initiative changed: ${ps(r.initiativeId.from,"initiativeId",t)} -> ${ps(r.initiativeId.to,"initiativeId",t)}`;if(e.action==="task-attachments-changed")return r.attachments?cg("attachments",r.attachments,t):"Attachments updated";if(n.length===1){const s=n[0],i=r[s];return cg(s,i,t)}return n.length>1?`${n.length} fields updated`:"Task updated"}function Hee(e,t){if(e.taskId||e.entityType==="task")return kI(e,t);const r=e.details?.changes||{},n=Object.keys(r),s=e.entityType==="initiative"?"Initiative":"Workstream",i=typeof e.details?.taskTitle=="string"&&e.details.taskTitle.trim().length>0?e.details.taskTitle.trim():null;return e.action==="initiative-created"?"Initiative created":e.action==="initiative-archived"?"Initiative archived":e.action==="initiative-unarchived"?"Initiative restored":e.action==="workstream-created"?"Workstream created":e.action==="workstream-archived"?"Workstream archived":e.action==="workstream-unarchived"?"Workstream restored":e.action==="workstream-task-added"?i?`Task added: ${i}`:"Task added":e.action==="workstream-task-removed"?i?`Task removed: ${i}`:"Task removed":e.action==="workstream-relationship-changed"&&r.initiativeId?`Initiative changed: ${ps(r.initiativeId.from,"initiativeId",t)} -> ${ps(r.initiativeId.to,"initiativeId",t)}`:(e.action==="initiative-attachments-changed"||e.action==="workstream-attachments-changed")&&r.attachments?cg("attachments",r.attachments,t):n.length===1?cg(n[0],r[n[0]],t):n.length>1?`${n.length} fields updated`:e.action==="initiative-updated"||e.action==="workstream-updated"?`${s} updated`:`${s} activity updated`}function lg(e){const t=Date.parse(String(e.timestamp||""));return Number.isFinite(t)?t:null}function a8(e){const t=e.details?.changes||{},r=Object.keys(t);if(e.action==="task-status-changed"&&t.status)return"status";if(e.action==="task-schedule-changed"){if(t.scheduledDate)return"scheduledDate";if(t.dueDate)return"dueDate"}if(e.action==="task-relationship-changed"){if(t.workstreamId)return"workstreamId";if(t.initiativeId)return"initiativeId"}return e.action==="task-attachments-changed"&&t.attachments?"attachments":r.length===1?r[0]:null}function Gee(e){if(e.taskId||e.entityType==="task")return a8(e);const t=e.details?.changes||{},r=Object.keys(t);return(e.action==="workstream-task-added"||e.action==="workstream-task-removed")&&e.details?.taskId?"taskId":e.action==="workstream-relationship-changed"&&t.initiativeId?"initiativeId":(e.action==="initiative-attachments-changed"||e.action==="workstream-attachments-changed")&&t.attachments?"attachments":r.length===1?r[0]:null}function vI(e){const t=new Map,r=new Set,n=s=>{if(s.type==="event"&&s.event.action==="task-comment-added"||s.type==="event"&&s.event.action==="task-updated"&&s.event.details?.saveSource==="autosave"&&Object.keys(s.event.details?.changes||{}).length===0)return;const i=s.type==="comment"?`comment:${String(s.comment.id||s.id).replace(/^comment:/,"")}`:`event:${String(s.event.id||s.id).replace(/^event:/,"")}`;t.set(i,{...s,id:i}),s.type==="comment"&&r.add(String(s.comment.id||s.id).replace(/^comment:/,""))};return Array.isArray(e.activity)&&e.activity.forEach(n),Array.isArray(e.comments)&&e.comments.forEach(s=>{const i=String(s.id||"").trim();!i||r.has(i)||n({id:`comment:${i}`,type:"comment",timestamp:s.timestamp,comment:s})}),[...t.values()].sort((s,i)=>{const l=lg(s),c=lg(i);return l!==null&&c!==null&&l!==c?l-c:l!==null&&c===null?-1:l===null&&c!==null?1:String(s.id||"").localeCompare(String(i.id||""))})}function iw(e){return vI(e)}function n8(e){const t=iw(e);return t.length===0?null:[...t].sort((r,n)=>{const s=lg(r),i=lg(n);return s!==null&&i!==null&&s!==i?i-s:s!==null&&i===null?-1:s===null&&i!==null?1:String(n.id||"").localeCompare(String(r.id||""))})[0]||null}function s8(e,t){return e?e.type==="comment"?e.comment.text:kI(e.event,t):""}const wI="/taskforce/assets/antigravity-DRKQga2U.png",bI="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%20viewBox='0%200%202406%202406'%3e%3cpath%20d='M1%20578.4C1%20259.5%20259.5%201%20578.4%201h1249.1c319%200%20577.5%20258.5%20577.5%20577.4V2406H578.4C259.5%202406%201%202147.5%201%201828.6V578.4z'%20fill='%2374aa9c'/%3e%3cpath%20id='a'%20d='M1107.3%20299.1c-197.999%200-373.9%20127.3-435.2%20315.3L650%20743.5v427.9c0%2021.4%2011%2040.4%2029.4%2051.4l344.5%20198.515V833.3h.1v-27.9L1372.7%20604c33.715-19.52%2070.44-32.857%20108.47-39.828L1447.6%20450.3C1361%20353.5%201237.1%20298.5%201107.3%20299.1zm0%20117.5-.6.6c79.699%200%20156.3%2027.5%20217.6%2078.4-2.5%201.2-7.4%204.3-11%206.1L952.8%20709.3c-18.4%2010.4-29.4%2030-29.4%2051.4V1248l-155.1-89.4V755.8c-.1-187.099%20151.601-338.9%20339-339.2z'%20fill='%23fff'/%3e%3cuse%20xlink:href='%23a'%20transform='rotate(60%201203%201203)'/%3e%3cuse%20xlink:href='%23a'%20transform='rotate(120%201203%201203)'/%3e%3cuse%20xlink:href='%23a'%20transform='rotate(180%201203%201203)'/%3e%3cuse%20xlink:href='%23a'%20transform='rotate(240%201203%201203)'/%3e%3cuse%20xlink:href='%23a'%20transform='rotate(300%201203%201203)'/%3e%3c/svg%3e",SI="data:image/svg+xml,%3csvg%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eClaude%3c/title%3e%3cpath%20d='M4.709%2015.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0%2011.784l.055-.352.48-.321.686.06%201.52.103%202.278.158%201.652.097%202.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686%201.908%201.476%202.491%201.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97%202.97%200%2001-.104-.729L6.283.134%206.696%200l.996.134.42.364.62%201.414%201.002%202.229%201.555%203.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286%201.851-.559%202.903-.364%201.942h.212l.243-.242.985-1.306%201.652-2.064.73-.82.85-.904.547-.431h1.033l.76%201.129-.34%201.166-1.064%201.347-.881%201.142-1.264%201.7-.79%201.36.073.11.188-.02%202.856-.606%201.543-.28%201.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061%201.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093%201.068%202.006%201.81%202.509%202.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649%202.345%203.521.122%201.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674%207.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434%201.967-2.18%202.945-1.726%201.845-.414.164-.717-.37.067-.662.401-.589%202.388-3.036%201.44-1.882.93-1.086-.006-.158h-.055L4.132%2018.56l-1.13.146-.487-.456.061-.746.231-.243%201.908-1.312-.006.006z'%20fill='%23D97757'%20fill-rule='nonzero'%3e%3c/path%3e%3c/svg%3e",AI="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTYgMjU2IiByb2xlPSJpbWciIGFyaWEtbGFiZWxsZWRieT0idGl0bGUiPgogIDx0aXRsZSBpZD0idGl0bGUiPkNsYXVkZSBDb2RlIENsYXcnZCBtYXNjb3Q8L3RpdGxlPgogIDxyZWN0IHdpZHRoPSIyNTYiIGhlaWdodD0iMjU2IiBmaWxsPSIjZDk3NzU3Ii8+CiAgPGcKICAgIGZpbGw9IiNmN2YzZWUiCiAgICBmb250LWZhbWlseT0iTWVubG8sIE1vbmFjbywgQ29uc29sYXMsICdMaWJlcmF0aW9uIE1vbm8nLCBtb25vc3BhY2UiCiAgICBmb250LXNpemU9IjM1IgogICAgZm9udC13ZWlnaHQ9IjcwMCIKICAgIHRleHQtYW5jaG9yPSJtaWRkbGUiCiAgPgogICAgPHRleHQgeD0iMTI4IiB5PSIxMDIiPiYjeDI1OTA7JiN4MjU5QjsmI3gyNTg4OyYjeDI1ODg7JiN4MjU4ODsmI3gyNTlDOyYjeDI1OEM7PC90ZXh0PgogICAgPHRleHQgeD0iMTI4IiB5PSIxMzciPiYjeDI1OUQ7JiN4MjU5QzsmI3gyNTg4OyYjeDI1ODg7JiN4MjU4ODsmI3gyNTg4OyYjeDI1ODg7JiN4MjU5QjsmI3gyNTk4OzwvdGV4dD4KICAgIDx0ZXh0IHg9IjEyOCIgeT0iMTcyIiB4bWw6c3BhY2U9InByZXNlcnZlIj4gICYjeDI1OTg7JiN4MjU5ODsgJiN4MjU5RDsmI3gyNTlEOyAgPC90ZXh0PgogIDwvZz4KPC9zdmc+Cg==",CI="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='UTF-8'?%3e%3csvg%20width='92px'%20height='96px'%20viewBox='0%200%2092%2096'%20version='1.1'%20xmlns='http://www.w3.org/2000/svg'%20xmlns:xlink='http://www.w3.org/1999/xlink'%3e%3ctitle%3eGroup%20Copy%202%3c/title%3e%3cg%20id='Page-1'%20stroke='none'%20stroke-width='1'%20fill='none'%20fill-rule='evenodd'%3e%3cg%20id='icon-copy'%20transform='translate(-34,%20-40)'%20fill='%2324292F'%3e%3cg%20id='Group-Copy-2'%20transform='translate(34,%2040.5)'%3e%3cg%20id='Group-3-Copy-4'%20transform='translate(0,%200)'%3e%3cpath%20d='M65.4492701,16.3%20C76.3374701,16.3%2085.1635558,25.16479%2085.1635558,36.1%20L85.1635558,42.7%20L90.9027661,54.1647464%20C91.4694141,55.2966923%2091.4668177,56.6300535%2090.8957658,57.7597839%20L85.1635558,69.1%20L85.1635558,75.7%20C85.1635558,86.63554%2076.3374701,95.5%2065.4492701,95.5%20L26.0206986,95.5%20C15.1328272,95.5%206.30641291,86.63554%206.30641291,75.7%20L6.30641291,69.1%20L0.448507752,57.7954874%20C-0.14693501,56.6464093%20-0.149634367,55.2802504%200.441262896,54.1288283%20L6.30641291,42.7%20L6.30641291,36.1%20C6.30641291,25.16479%2015.1328272,16.3%2026.0206986,16.3%20L65.4492701,16.3%20Z%20M62.9301895,22%20L29.189529,22%20C19.8723267,22%2012.3191987,29.5552188%2012.3191987,38.875%20L12.3191987,44.5%20L7.44288578,53.9634655%20C6.84794449,55.1180686%206.85066096,56.4896598%207.45017099,57.6418974%20L12.3191987,67%20L12.3191987,72.625%20C12.3191987,81.9450625%2019.8723267,89.5%2029.189529,89.5%20L62.9301895,89.5%20C72.2476729,89.5%2079.8005198,81.9450625%2079.8005198,72.625%20L79.8005198,67%20L84.5682187,57.6061395%20C85.1432011,56.473244%2085.1458141,55.1345713%2084.5752587,53.9994398%20L79.8005198,44.5%20L79.8005198,38.875%20C79.8005198,29.5552188%2072.2476729,22%2062.9301895,22%20Z'%20id='Combined-Shape'%20fill-rule='nonzero'%3e%3c/path%3e%3ccircle%20id='Oval'%20cx='45.7349843'%20cy='11'%20r='11'%3e%3c/circle%3e%3c/g%3e%3crect%20id='Rectangle-Copy'%20stroke='%2324292F'%20stroke-width='8'%20x='31'%20y='44.5'%20width='5'%20height='22'%20rx='2.5'%3e%3c/rect%3e%3crect%20id='Rectangle-Copy-2'%20stroke='%2324292F'%20stroke-width='8'%20x='55'%20y='44.5'%20width='5'%20height='22'%20rx='2.5'%3e%3c/rect%3e%3c/g%3e%3c/g%3e%3c/g%3e%3c/svg%3e",II="data:image/svg+xml,%3csvg%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eCodex%3c/title%3e%3cpath%20d='M19.503%200H4.496A4.496%204.496%200%20000%204.496v15.007A4.496%204.496%200%20004.496%2024h15.007A4.496%204.496%200%200024%2019.503V4.496A4.496%204.496%200%200019.503%200z'%20fill='%23fff'%3e%3c/path%3e%3cpath%20d='M9.064%203.344a4.578%204.578%200%20012.285-.312c1%20.115%201.891.54%202.673%201.275.01.01.024.017.037.021a.09.09%200%2000.043%200%204.55%204.55%200%20013.046.275l.047.022.116.057a4.581%204.581%200%20012.188%202.399c.209.51.313%201.041.315%201.595a4.24%204.24%200%2001-.134%201.223.123.123%200%2000.03.115c.594.607.988%201.33%201.183%202.17.289%201.425-.007%202.71-.887%203.854l-.136.166a4.548%204.548%200%2001-2.201%201.388.123.123%200%2000-.081.076c-.191.551-.383%201.023-.74%201.494-.9%201.187-2.222%201.846-3.711%201.838-1.187-.006-2.239-.44-3.157-1.302a.107.107%200%2000-.105-.024c-.388.125-.78.143-1.204.138a4.441%204.441%200%2001-1.945-.466%204.544%204.544%200%2001-1.61-1.335c-.152-.202-.303-.392-.414-.617a5.81%205.81%200%2001-.37-.961%204.582%204.582%200%2001-.014-2.298.124.124%200%2000.006-.056.085.085%200%2000-.027-.048%204.467%204.467%200%2001-1.034-1.651%203.896%203.896%200%2001-.251-1.192%205.189%205.189%200%2001.141-1.6c.337-1.112.982-1.985%201.933-2.618.212-.141.413-.251.601-.33.215-.089.43-.164.646-.227a.098.098%200%2000.065-.066%204.51%204.51%200%2001.829-1.615%204.535%204.535%200%20011.837-1.388zm3.482%2010.565a.637.637%200%20000%201.272h3.636a.637.637%200%20100-1.272h-3.636zM8.462%209.23a.637.637%200%2000-1.106.631l1.272%202.224-1.266%202.136a.636.636%200%20101.095.649l1.454-2.455a.636.636%200%2000.005-.64L8.462%209.23z'%20fill='url(%23lobe-icons-codex-_R_0_)'%3e%3c/path%3e%3cdefs%3e%3clinearGradient%20gradientUnits='userSpaceOnUse'%20id='lobe-icons-codex-_R_0_'%20x1='12'%20x2='12'%20y1='3'%20y2='21'%3e%3cstop%20stop-color='%23B1A7FF'%3e%3c/stop%3e%3cstop%20offset='.5'%20stop-color='%237A9DFF'%3e%3c/stop%3e%3cstop%20offset='1'%20stop-color='%233941FF'%3e%3c/stop%3e%3c/linearGradient%3e%3c/defs%3e%3c/svg%3e",_I="/taskforce/assets/cursor-BM_3k4Y4.svg",TI="/taskforce/assets/gemini-cli-icon-dBAVjCcn.png",o8="data:image/svg+xml,%3csvg%20width='28'%20height='28'%20viewBox='0%200%2028%2028'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cpath%20d='M14%2028C14%2026.0633%2013.6267%2024.2433%2012.88%2022.54C12.1567%2020.8367%2011.165%2019.355%209.905%2018.095C8.645%2016.835%207.16333%2015.8433%205.46%2015.12C3.75667%2014.3733%201.93667%2014%200%2014C1.93667%2014%203.75667%2013.6383%205.46%2012.915C7.16333%2012.1683%208.645%2011.165%209.905%209.905C11.165%208.645%2012.1567%207.16333%2012.88%205.46C13.6267%203.75667%2014%201.93667%2014%200C14%201.93667%2014.3617%203.75667%2015.085%205.46C15.8317%207.16333%2016.835%208.645%2018.095%209.905C19.355%2011.165%2020.8367%2012.1683%2022.54%2012.915C24.2433%2013.6383%2026.0633%2014%2028%2014C26.0633%2014%2024.2433%2014.3733%2022.54%2015.12C20.8367%2015.8433%2019.355%2016.835%2018.095%2018.095C16.835%2019.355%2015.8317%2020.8367%2015.085%2022.54C14.3617%2024.2433%2014%2026.0633%2014%2028Z'%20fill='url(%23gemini-gradient)'/%3e%3cdefs%3e%3cradialGradient%20id='gemini-gradient'%20cx='0'%20cy='0'%20r='1'%20gradientUnits='userSpaceOnUse'%20gradientTransform='translate(2.77876%2011.3795)%20rotate(18.6832)%20scale(29.8025%20238.737)'%3e%3cstop%20offset='0.0671246'%20stop-color='%239168C0'/%3e%3cstop%20offset='0.342551'%20stop-color='%235684D1'/%3e%3cstop%20offset='0.672076'%20stop-color='%231BA1E3'/%3e%3c/radialGradient%3e%3c/defs%3e%3c/svg%3e",nv="/taskforce/assets/grok-BuodbWaG.svg",xI="data:image/svg+xml,%3csvg%20width='1200'%20height='1200'%20viewBox='0%200%201200%201200'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3crect%20width='1200'%20height='1200'%20rx='260'%20fill='%239046FF'/%3e%3cmask%20id='mask0_1106_4856'%20style='mask-type:luminance'%20maskUnits='userSpaceOnUse'%20x='272'%20y='202'%20width='655'%20height='796'%3e%3cpath%20d='M926.578%20202.793H272.637V997.857H926.578V202.793Z'%20fill='white'/%3e%3c/mask%3e%3cg%20mask='url(%23mask0_1106_4856)'%3e%3cpath%20d='M398.554%20818.914C316.315%201001.03%20491.477%201046.74%20620.672%20940.156C658.687%201059.66%20801.052%20970.473%20852.234%20877.795C964.787%20673.567%20919.318%20465.357%20907.64%20422.374C827.637%20129.443%20427.623%20128.946%20358.8%20423.865C342.651%20475.544%20342.402%20534.18%20333.458%20595.051C328.986%20625.86%20325.507%20645.488%20313.83%20677.785C306.873%20696.424%20297.68%20712.819%20282.773%20740.645C259.915%20783.881%20269.604%20867.113%20387.87%20823.883L399.051%20818.914H398.554Z'%20fill='white'/%3e%3cpath%20d='M636.123%20549.353C603.328%20549.353%20598.359%20510.097%20598.359%20486.742C598.359%20465.623%20602.086%20448.977%20609.293%20438.293C615.504%20428.852%20624.697%20424.131%20636.123%20424.131C647.555%20424.131%20657.492%20428.852%20664.447%20438.541C672.398%20449.474%20676.623%20466.12%20676.623%20486.742C676.623%20525.998%20661.471%20549.353%20636.375%20549.353H636.123Z'%20fill='black'/%3e%3cpath%20d='M771.24%20549.353C738.445%20549.353%20733.477%20510.097%20733.477%20486.742C733.477%20465.623%20737.203%20448.977%20744.41%20438.293C750.621%20428.852%20759.814%20424.131%20771.24%20424.131C782.672%20424.131%20792.609%20428.852%20799.564%20438.541C807.516%20449.474%20811.74%20466.12%20811.74%20486.742C811.74%20525.998%20796.588%20549.353%20771.492%20549.353H771.24Z'%20fill='black'/%3e%3c/g%3e%3c/svg%3e",RI="data:image/svg+xml,%3csvg%20height='1em'%20style='flex:none;line-height:1'%20viewBox='0%200%2024%2024'%20width='1em'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3eMistral%3c/title%3e%3cpath%20d='M3.428%203.4h3.429v3.428H3.428V3.4zm13.714%200h3.43v3.428h-3.43V3.4z'%20fill='gold'%3e%3c/path%3e%3cpath%20d='M3.428%206.828h6.857v3.429H3.429V6.828zm10.286%200h6.857v3.429h-6.857V6.828z'%20fill='%23FFAF00'%3e%3c/path%3e%3cpath%20d='M3.428%2010.258h17.144v3.428H3.428v-3.428z'%20fill='%23FF8205'%3e%3c/path%3e%3cpath%20d='M3.428%2013.686h3.429v3.428H3.428v-3.428zm6.858%200h3.429v3.428h-3.429v-3.428zm6.856%200h3.43v3.428h-3.43v-3.428z'%20fill='%23FA500F'%3e%3c/path%3e%3cpath%20d='M0%2017.114h10.286v3.429H0v-3.429zm13.714%200H24v3.429H13.714v-3.429z'%20fill='%23E10500'%3e%3c/path%3e%3c/svg%3e",jI="data:image/svg+xml,%3csvg%20fill='%231FB8CD'%20role='img'%20viewBox='0%200%2024%2024'%20xmlns='http://www.w3.org/2000/svg'%3e%3ctitle%3ePerplexity%3c/title%3e%3cpath%20d='M22.3977%207.0896h-2.3106V.0676l-7.5094%206.3542V.1577h-1.1554v6.1966L4.4904%200v7.0896H1.6023v10.3976h2.8882V24l6.932-6.3591v6.2005h1.1554v-6.0469l6.9318%206.1807v-6.4879h2.8882V7.0896zm-3.4657-4.531v4.531h-5.355l5.355-4.531zm-13.2862.0676%204.8691%204.4634H5.6458V2.6262zM2.7576%2016.332V8.245h7.8476l-6.1149%206.1147v1.9723H2.7576zm2.8882%205.0404v-3.8852h.0001v-2.6488l5.7763-5.7764v7.0111l-5.7764%205.2993zm12.7086.0248-5.7766-5.1509V9.0618l5.7766%205.7766v6.5588zm2.8882-5.0652h-1.733v-1.9723L13.3948%208.245h7.8478v8.087z'/%3e%3c/svg%3e",PI="/taskforce/assets/vscode-C_7wk1WI.svg",EI="data:image/svg+xml,%3csvg%20width='1024'%20height='1024'%20viewBox='0%200%201024%201024'%20fill='none'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%20clip-path='url(%23clip0_109_63)'%3e%3crect%20width='1024'%20height='1024'%20fill='%23F9F3E9'/%3e%3cpath%20d='M897.246%20286.869H889.819C850.735%20286.808%20819.017%20318.46%20819.017%20357.539V515.589C819.017%20547.15%20792.93%20572.716%20761.882%20572.716C743.436%20572.716%20725.02%20563.433%20714.093%20547.85L552.673%20317.304C539.28%20298.16%20517.486%20286.747%20493.895%20286.747C457.094%20286.747%20423.976%20318.034%20423.976%20356.657V515.619C423.976%20547.181%20398.103%20572.746%20366.842%20572.746C348.335%20572.746%20329.949%20563.463%20319.021%20547.881L138.395%20289.882C134.316%20284.038%20125.154%20286.93%20125.154%20294.052V431.892C125.154%20438.862%20127.285%20445.619%20131.272%20451.34L309.037%20705.2C319.539%20720.204%20335.033%20731.344%20352.9%20735.392C397.616%20745.557%20438.77%20711.135%20438.77%20667.278V508.406C438.77%20476.845%20464.339%20451.279%20495.904%20451.279H495.995C515.02%20451.279%20532.857%20460.562%20543.785%20476.145L705.235%20706.661C718.659%20725.835%20739.327%20737.218%20763.983%20737.218C801.606%20737.218%20833.841%20705.9%20833.841%20667.308V508.376C833.841%20476.815%20859.41%20451.249%20890.975%20451.249H897.276C901.233%20451.249%20904.43%20448.053%20904.43%20444.097V294.021C904.43%20290.065%20901.233%20286.869%20897.276%20286.869H897.246Z'%20fill='%230B100F'/%3e%3c/g%3e%3cdefs%3e%3cclipPath%20id='clip0_109_63'%3e%3crect%20width='1024'%20height='1024'%20rx='100'%20fill='white'/%3e%3c/clipPath%3e%3c/defs%3e%3c/svg%3e",cw={general:{id:"general",label:"General",generatedOption:!0},antigravity:{id:"antigravity",label:"Antigravity",logoKey:"antigravity",surfaceHint:"coding_tool",generatedOption:!0,signatureColor:"#e49d25"},"claude-code":{id:"claude-code",label:"Claude Code CLI",logoKey:"claude-code",surfaceHint:"cli",generatedOption:!0,signatureColor:"#d97757"},"claude-chat":{id:"claude-chat",label:"Claude Chat",logoKey:"claude-chat",surfaceHint:"chat_app",signatureColor:"#d97757"},cline:{id:"cline",label:"Cline",logoKey:"cline",surfaceHint:"ide",generatedOption:!0,signatureColor:"#25a9e4"},codex:{id:"codex",label:"Codex",logoKey:"codex",surfaceHint:"cli",generatedOption:!0,signatureColor:"#6366f1"},cursor:{id:"cursor",label:"Cursor",logoKey:"cursor",surfaceHint:"ide",generatedOption:!0,signatureColor:"#186e95"},"gemini-cli":{id:"gemini-cli",label:"Gemini CLI",logoKey:"gemini-cli",surfaceHint:"cli",generatedOption:!0,signatureColor:"#4285f4"},grok:{id:"grok",label:"Grok CLI",logoKey:"grok",surfaceHint:"cli",generatedOption:!0,signatureColor:"#181b95"},"grok-chat":{id:"grok-chat",label:"Grok",logoKey:"grok-chat",surfaceHint:"chat_app",signatureColor:"#181b95"},"gemini-chat":{id:"gemini-chat",label:"Gemini Spark",logoKey:"gemini-chat",surfaceHint:"chat_app",signatureColor:"#4285f4"},"mistral-chat":{id:"mistral-chat",label:"Mistral Vibe",logoKey:"mistral-chat",surfaceHint:"chat_app",signatureColor:"#fa520f"},"perplexity-chat":{id:"perplexity-chat",label:"Perplexity",logoKey:"perplexity-chat",surfaceHint:"chat_app",signatureColor:"#1fb8cd"},kiro:{id:"kiro",label:"Kiro",logoKey:"kiro",surfaceHint:"ide",generatedOption:!0,signatureColor:"#7c3aed"},openclaw:{id:"openclaw",label:"OpenClaw",surfaceHint:"agent",generatedOption:!0},vscode:{id:"vscode",label:"VS Code / Copilot",logoKey:"vscode",surfaceHint:"ide",generatedOption:!0,signatureColor:"#256ee4"},windsurf:{id:"windsurf",label:"Windsurf",logoKey:"windsurf",surfaceHint:"ide",generatedOption:!0,signatureColor:"#189587"},"chatgpt-desktop":{id:"chatgpt-desktop",label:"ChatGPT Desktop",logoKey:"chatgpt-desktop",surfaceHint:"chat_app",signatureColor:"#10a37f"}};function i8(e){const t=String(e||"").trim().toLowerCase();return t==="claude-desktop"?"claude-chat":Object.prototype.hasOwnProperty.call(cw,t)?t:null}function NI(e){const t=i8(e);return t?cw[t]:null}function Vee(){return Object.values(cw).filter(e=>e.generatedOption).map(({id:e,label:t})=>({id:e,label:t}))}function c8(e){const t=e?.providerMetadata?.taskforce;return!t||typeof t!="object"||Array.isArray(t)?"":String(t.taskforceAgentId||"").trim()}function MI(e){return!!c8(e)}function Kee(e){if(!e||e.archivedAt||e.mergedIntoProfileId||MI(e)||e.surfaceType!=="agent")return!1;const t=e.providerMetadata?.connection,r=t&&typeof t=="object"&&!Array.isArray(t)?t.clientId:null,n=NI(r);return!(n?.logoKey||n?.surfaceHint&&n.surfaceHint!=="agent")}const l8={antigravity:wI,"chatgpt-desktop":bI,"claude-code":AI,"claude-chat":SI,"grok-chat":nv,"gemini-chat":o8,"mistral-chat":RI,"perplexity-chat":jI,cline:CI,codex:II,cursor:_I,"gemini-cli":TI,grok:nv,kiro:xI,vscode:PI,windsurf:EI};function d8(e){if(!e||MI(e))return"";const t=e.providerMetadata?.connection,r=t&&typeof t=="object"&&!Array.isArray(t)?t.clientId:null,n=NI(r);if(n?.logoKey)return l8[n.logoKey];if(!["chat_app","ide","cli","coding_tool"].includes(String(e.surfaceType||"")))return"";const s=[e.username,e.name].map(i=>String(i||"").toLowerCase()).join(" ");return!s.trim()||s.includes("openclaw")||s.includes("hermes agent")?"":s.includes("chatgpt")?bI:s.includes("claude code")?AI:s.includes("claude desktop")?SI:s.includes("cline")?CI:s.includes("codex")?II:s.includes("cursor")?_I:s.includes("cascade")||s.includes("windsurf")?EI:s.includes("antigravity")?wI:s.includes("gemini")?TI:s.includes("grok")?nv:s.includes("mistral")||s.includes("le chat")?RI:s.includes("perplexity")?jI:s.includes("kiro")?xI:s.includes("visual studio code")||s.includes("vs code")||s.includes("vscode")?PI:""}function u8(e,t,r){const n=typeof e=="string"?e.trim():"";if(!n||n.startsWith("data:")||n.startsWith("blob:"))return n;const s=Number(t),i=Number.isFinite(s)&&s>0?String(Math.floor(s)):typeof r=="string"&&r.trim().length>0?r.trim():"";if(!i)return n;const[l,c=""]=n.split("#"),d=l.includes("?")?"&":"?";return`${l}${d}v=${encodeURIComponent(i)}${c?`#${c}`:""}`}function DI(e,t){const r=String(e||"").trim(),n=String(t||"").trim(),[s,i]=o.useState(r||n);return o.useEffect(()=>{i(r||n)},[r,n]),{activeImageUrl:s,handleImageError:()=>{if(s&&n&&s!==n){i(n);return}i("")}}}const p8="_identity_1owqe_1",f8="_avatar_1owqe_9",m8="_person_1owqe_17",h8="_provider_1owqe_21",g8="_unassigned_1owqe_25",y8="_card_1owqe_31",k8="_label_1owqe_51",hd={identity:p8,avatar:f8,person:m8,provider:h8,unassigned:g8,card:y8,label:k8};function Lg({option:e,size:t=22,variant:r="default",unassignedIcon:n}){const s=Nv(e.value),i=s?"":u8(e.avatarUrl,e.avatarRevision,e.avatarUpdatedAt),l=!s&&e.kind==="agent"?d8({name:e.label,username:e.username,surfaceType:e.surfaceType,providerMetadata:e.providerMetadata}):"",{activeImageUrl:c,handleImageError:d}=DI(i,l),f=Gs,p=s?qf:e.icon,g=s&&n?n:p&&f[p]?f[p]:Td,h=s?Math.max(13,Math.round(t*.56)):Math.max(14,t-6),y=rn(e.color)||(e.kind==="member"?"var(--color-green-500, #22c55e)":"var(--text-secondary, #888)");return a.jsx("span",{className:`${hd.avatar} ${l?hd.provider:hd.person} ${s?hd.unassigned:""} ${r==="card"?hd.card:""}`.trim(),style:{width:t,height:t,color:c?void 0:y,"--assignee-avatar-color":y},"data-assignee-avatar":r,"aria-hidden":"true",children:c?a.jsx("img",{src:c,alt:"",onError:d}):a.jsx(g,{size:h,strokeWidth:s?1.6:void 0})})}function qu({option:e,size:t=22}){return a.jsxs("span",{className:hd.identity,children:[a.jsx(Lg,{option:e,size:t}),a.jsx("span",{className:hd.label,children:e.label})]})}const LI=Object.freeze(["Target","Route","Flag","Rocket","Briefcase","Folder","Layers","Map","Compass","Landmark","BookOpen","Lightbulb","Wrench","Shield","Bug","Palette","Camera","Music","Heart","Globe","Users","Sparkles","FlaskConical","Code"]),OI=Object.freeze(["red","orange","amber","green","teal","sky","blue","indigo","violet"]),v8=new Set(LI),w8=new Set(OI);function b8(e){if(e==null||e==="")return null;const t=typeof e=="string"?e.trim():"";return v8.has(t)?t:null}function S8(e){if(e==null||e==="")return null;const t=typeof e=="string"?e.trim().toLowerCase():"";return w8.has(t)?t:null}function A8(e){const t=b8(e.icon),r=S8(e.color);return{icon:t||(e.entityType==="initiative"?"Target":"Route"),color:r,customized:!!(t||r)}}function kS(e){return e?`var(--planning-identity-${e})`:"var(--planning-progress-empty)"}const C8="_root_kfvfr_1",I8="_trigger_kfvfr_6",_8="_marker_kfvfr_20",T8="_card_kfvfr_31",x8="_inline_kfvfr_32",R8="_detail_kfvfr_33",j8="_disabled_kfvfr_34",P8="_popover_kfvfr_36",E8="_colorGrid_kfvfr_48",N8="_colorOption_kfvfr_55",M8="_iconOption_kfvfr_66",D8="_iconGrid_kfvfr_70",L8="_selected_kfvfr_91",O8="_divider_kfvfr_100",B8="_reset_kfvfr_106",Hs={root:C8,trigger:I8,marker:_8,card:T8,inline:x8,detail:R8,disabled:j8,popover:P8,colorGrid:E8,colorOption:N8,iconOption:M8,iconGrid:D8,selected:L8,divider:O8,reset:B8},vS={Target:ZT,Route:YT,Flag:qT,Rocket:KT,Briefcase:VT,Folder:Qi,Layers:Vh,Map:GT,Compass:HT,Landmark:zT,BookOpen:UT,Lightbulb:FT,Wrench:$T,Shield:WT,Bug:BT,Palette:OT,Camera:LT,Music:DT,Heart:MT,Globe:NT,Users:Mh,Sparkles:nA,FlaskConical:ET,Code:PT};function Jf({entityType:e,entityId:t,icon:r,color:n,disabled:s=!1,size:i="card",onChange:l}){const[c,d]=Y.useState(!1),[f,p]=Y.useState(!1),[g,h]=Y.useState(null),[y,k]=Y.useState(),[b,C]=Y.useState({top:0,left:0}),S=Y.useRef(null),w=Y.useRef(null),T=Y.useRef(null),E=g&&Object.prototype.hasOwnProperty.call(g,"icon")?g.icon:r,x=g&&Object.prototype.hasOwnProperty.call(g,"color")?g.color:n,N=A8({entityType:e,icon:E,color:x}),v=vS[N.icon],V=!s&&!!l;Y.useEffect(()=>{if(!c)return;const F=z=>{const M=z.target;!S.current?.contains(M)&&!T.current?.contains(M)&&d(!1)};return document.addEventListener("pointerdown",F),()=>document.removeEventListener("pointerdown",F)},[c]),Y.useLayoutEffect(()=>{if(!c)return;const F=()=>{const z=w.current?.getBoundingClientRect();if(!z)return;k(w.current?.closest("[data-theme]")?.dataset.theme);const M=T.current?.getBoundingClientRect(),O=M?.width||248,Z=M?.height||320,U=8,ve=8,te=Math.max(ve,Math.min(z.left,window.innerWidth-O-ve)),ce=z.bottom+U,Le=ce+Z<=window.innerHeight-ve?ce:Math.max(ve,z.top-Z-U);C({top:Le,left:te})};return F(),window.addEventListener("resize",F),window.addEventListener("scroll",F,!0),()=>{window.removeEventListener("resize",F),window.removeEventListener("scroll",F,!0)}},[c]),Y.useEffect(()=>{if(!g)return;const F=!Object.prototype.hasOwnProperty.call(g,"icon")||(g.icon??null)===(r??null),z=!Object.prototype.hasOwnProperty.call(g,"color")||(g.color??null)===(n??null);F&&z&&h(null)},[n,r,g]);const _=async F=>{if(!(!l||f)){h(z=>({...z,...F})),p(!0);try{await l(F)}catch{h(null)}finally{p(!1)}}},j=a.jsx("span",{className:`${Hs.marker} ${Hs[i]} ${s?Hs.disabled:""}`.trim(),style:{color:kS(N.color)},"aria-hidden":"true",children:a.jsx(v,{size:i==="detail"?26:i==="inline"?18:24,strokeWidth:1.9})});return V?a.jsxs("div",{ref:S,className:Hs.root,onClick:F=>F.stopPropagation(),children:[a.jsx("button",{ref:w,type:"button",className:Hs.trigger,onClick:()=>d(F=>!F),onKeyDown:F=>F.stopPropagation(),"aria-label":`Change ${e} icon and color`,"aria-expanded":c,disabled:f,children:j}),c?tc.createPortal(a.jsxs("div",{ref:T,className:Hs.popover,role:"dialog","aria-label":`${e} icon and color`,"aria-busy":f,"data-theme":y,style:b,onClick:F=>F.stopPropagation(),onKeyDown:F=>F.stopPropagation(),children:[a.jsx("div",{className:Hs.colorGrid,"aria-label":"Colors",children:OI.map(F=>a.jsx("button",{type:"button",className:`${Hs.colorOption} ${N.color===F?Hs.selected:""}`.trim(),style:{backgroundColor:kS(F)},onClick:()=>{_({color:F})},"aria-label":`${F} color`,"aria-pressed":N.color===F,disabled:f},F))}),a.jsx("div",{className:Hs.divider}),a.jsx("div",{className:Hs.iconGrid,"aria-label":"Icons",children:LI.map(F=>{const z=vS[F];return a.jsx("button",{type:"button",className:`${Hs.iconOption} ${N.icon===F?Hs.selected:""}`.trim(),onClick:()=>{_({icon:F})},"aria-label":F,"aria-pressed":N.icon===F,disabled:f,children:a.jsx(z,{size:18,strokeWidth:1.8})},F)})}),a.jsx("div",{className:Hs.divider}),a.jsx("button",{type:"button",className:Hs.reset,onClick:()=>{_({icon:null,color:null})},disabled:!N.customized||f,children:"Reset to default"})]}),document.body):null]}):j}function BI({workstreams:e,onSelect:t,disabled:r=!1}){const n=Y.useMemo(()=>e.filter(l=>!l.isArchived),[e]),s=Y.useMemo(()=>new Map(n.map(l=>[l.id,l])),[n]),i=Y.useMemo(()=>n.map(l=>({value:l.id,label:`${zu(l)||l.id} — ${l.title}`})),[n]);return a.jsx(ai,{value:"",options:i,onChange:l=>{const c=s.get(String(l));c&&t(c)},placeholder:"Select workstream…",ariaLabel:"Link task to workstream",title:i.length>0?"Link to workstream":"No workstreams available",disabled:r||i.length===0,className:R.taskWorkstreamPicker,panelClassName:R.taskWorkstreamPickerPanel,portalPanel:!0,panelAlign:"start",panelMinWidth:280,searchable:!0,searchPlaceholder:"Search workstreams…",noResultsText:"No matching workstreams.",hideChevron:!0,triggerContent:a.jsx("span",{className:R.taskWorkstreamPickerIcon,children:a.jsx(Bu,{size:13,"aria-hidden":"true"})}),renderOptionContent:l=>{const c=s.get(String(l.value));return c?a.jsxs("span",{className:R.taskWorkstreamPickerOption,children:[a.jsx(Jf,{entityType:"workstream",entityId:c.id,icon:c.icon,color:c.color,size:"inline",disabled:!0}),a.jsx("span",{children:zu(c)||c.id}),a.jsx("span",{children:c.title})]}):l.label}})}const W8="_root_evk0k_1",$8="_compact_evk0k_21",F8="_outline_evk0k_26",U8="_foldFill_evk0k_47",z8="_foldLine_evk0k_56",H8="_label_evk0k_60",Cu={root:W8,compact:$8,outline:F8,foldFill:U8,foldLine:z8,label:H8};function G8({label:e,compact:t=!1,accentColor:r}){const n=r?{"--document-type-accent":r}:void 0;return a.jsxs("span",{className:`${Cu.root} ${t?Cu.compact:""}`.trim(),style:n,"aria-hidden":"true",children:[a.jsxs("svg",{className:Cu.outline,viewBox:"0 0 28 28",focusable:"false",children:[a.jsx("path",{d:"M2 0.75h18.25l7 7V26q0 1.25-1.25 1.25H2Q0.75 27.25 0.75 26V2Q0.75 0.75 2 0.75Z"}),a.jsx("path",{className:Cu.foldFill,d:"M20.25 0.75v7h7Z"}),a.jsx("path",{className:Cu.foldLine,d:"M20.25 0.75v7h7"})]}),a.jsx("span",{className:Cu.label,children:e})]})}const{MessageSquare:V8,Gauge:K8,ClipboardList:q8,HelpCircle:Y8}=Gs,Z8=({task:e,searchQuery:t="",copiedId:r=null,taxonomies:n=[],types:s=[],priorities:i=[],categories:l=[],assigneeOptions:c=[],workstreams:d=[],taskWorkstream:f=null,taskInitiative:p=null,workspaceId:g=null,isOverlay:h=!1,isArchived:y=!1,readOnlyMode:k=null,isRecentlyChanged:b=!1,selectable:C=!1,selected:S=!1,onSelectionChange:w,onClick:T,onCopyId:E,onToggleInProgress:x,onToggleReview:N,onToggleComplete:v,onToggleCancel:V,onSetStatus:_,onArchiveTask:j,onUnarchive:F,onDelete:z,deleteActionTitle:M,taskReferences:O,onAssigneeChange:Z,onWorkstreamChange:U,compressed:ve=!1,showStatusLabel:te=!1})=>{const ce=xv(e),Le=ce.label||(ce.isProvisional?"Pending":""),Ie=ce.isProvisional,Ye=!!ce.label,ge=zu(f)||f?.id||"",he=KC(p)||p?.id||"",Ae=i.find($=>String($.value)===String(e.priority)),ye=Po(e.status),Ne=rn(ye.color),ae=l.find($=>$.value===e.category||$.label===e.category),q=typeof e.complexity=="number"?e.complexity:Number(e.complexity??3),W=Number.isFinite(q)?Math.max(1,Math.min(5,Math.round(q))):3,K={1:"Tiny",2:"Low",3:"Mid",4:"High",5:"Epic"},Re={1:"tiny",2:"low",3:"medium",4:"high",5:"epic"},we=K[W],ie=`var(--complexity-${Re[W]})`,Q=Of(e.assignee,c),H=Y.useMemo(()=>{const $=String(e.assignee||"").trim();if(!$||$===Cd.value)return Cd;const Ke=BA(c,e.assignee).find(Ge=>String(Ge.value||"").trim()===$);if(Ke)return Ke;const Qe=jk($);return{...Cd,value:$,label:Q,icon:Qe==="agent"?"Bot":"User",color:Qe==="agent"?"#8b5cf6":"#22c55e",kind:Qe}},[Q,c,e.assignee]),se=Y.useMemo(()=>n8(e),[e]),Pe=k||(e.isDeleted?"deleted":y?"archived":null),ue=Pe!==null,ne=Y.useMemo(()=>{if(Pe!=="deleted"||!e.deletedExpiresAt)return"";const $=new Date(e.deletedExpiresAt);return Number.isNaN($.getTime())?"":`Trash expires ${$.toLocaleString()}`},[Pe,e.deletedExpiresAt]),Me=!ue&&!h&&!!Z&&c.length>0,pe=!ue&&!h&&!!U,[le,Ce]=Y.useState(!1),P=Y.useCallback(($,Ke)=>{const Qe=String(Ke||"").trim();if(Qe){if($==="assignee")return Of(Qe,c);if($==="workstreamId"&&Qe===f?.id)return ge||f.id;if($==="initiativeId"&&Qe===p?.id)return he||p.id}},[c,he,p,f,ge]),ee=Y.useMemo(()=>s8(se,P),[P,se]),Se=Y.useMemo(()=>iw(e).filter($=>$.type==="comment").length,[e]),_e=[mr.taskItem,e.status==="on-hold"?mr.onHold:"",e.status==="in-progress"?mr.inProgress:"",e.status==="review"?mr.readyForReview:"",e.status==="done"?mr.completed:"",e.status==="cancelled"?mr.cancelled:"",b?mr.taskItemRecentlyChanged:"",h?mr.kanbanCardOverlay:"",ue?mr.readOnly:"",y?mr.archived:"",ve?mr.compressed:"",S?mr.selected:""].filter(Boolean).join(" "),ke=rn(Ae?.color),Ze=s.find($=>$.value===e.type),st=rn(Ze?.color)||rE(e.type),at=$=>{const Ke=typeof $=="string"?$:$.path,Qe=typeof $=="string"?"":($.fsPath||"").trim(),Ge=typeof $=="string"?"":($.displayName||"").trim(),At=typeof $=="string"?"":($.originalFilename||"").trim(),Nt=typeof $=="string"?"":($.caption||"").trim();return[Qe,At,Ge,Nt,Ke].some(Qt=>/\.(png|jpe?g|webp|gif)(\?|#|$)/i.test(Qt))},oe=$=>{const Ke=typeof $=="string"?$:$.path,Qe=Ke.includes("/api/taskforce/documents/"),Ge=typeof $=="string"?"":($.displayName||"").trim();if(Qe&&typeof $!="string")return Tz({displayName:$.displayName,originalFilename:$.originalFilename,fsPath:$.fsPath,assetId:$.assetId||null});const At=typeof $=="string"?"":($.caption||"").trim();if(At)return At;if(Ge)return Ge;const Nt=typeof $=="string"?"":($.originalFilename||"").trim();return Nt||Ke.split("?")[0].split("#")[0].split("/").pop()||"Context file"},We=$=>{const Ke=typeof $=="string"?$:$.path,Qe=typeof $=="string"?"":($.fsPath||"").trim(),Ge=typeof $=="string"?"":($.caption||"").trim(),At=typeof $=="string"?"":($.originalFilename||"").trim(),Nt=[];if(Qe&&Nt.push(Qe),At&&Nt.push(At),Ge&&Nt.push(Ge),Ke.includes("/api/taskforce/context-link?path="))try{const Qt=new URL(Ke,"http://localhost").searchParams.get("path");Qt&&Nt.push(Qt)}catch{}Nt.push(Ke);for(const Bt of Nt){const Xt=Bt.split("?")[0].split("#")[0].split("/").pop()||"",nt=Xt.lastIndexOf(".");if(nt<=0||nt===Xt.length-1)continue;const Mt=Xt.slice(nt+1);if(Mt)return Mt.slice(0,5).toUpperCase()}return"FILE"},G={"--task-status-color":Ne||"var(--border-primary)","--task-card-tint-color":ue?"transparent":Ne||"transparent","--task-change-glow-color":Ne||"var(--brand-primary)",...Ne?{borderColor:Ne}:{}},Be=$=>$.replace(/\b\w/g,Ke=>Ke.toUpperCase()),Xe=Zf(n,[e]),ze=e.checklistItems||[],qe=ze.length,Te=qe>0?ze.filter($=>$.isCompleted).length:0,fe=($,Ke)=>{$.stopPropagation(),E?.($,Ke)},Ee=async $=>{if(!U||le)return!1;Ce(!0);try{return await U(e,$)!==!1}finally{Ce(!1)}},$e=$=>{const Ke=typeof $=="string"?$:$.path;return/^https?:\/\//i.test(Ke)?(window.open(Ke,"_blank"),!0):Ff($,{ownerType:"task",ownerId:e.id,ownerReferenceLabel:Le,workspaceId:g})},rt=ve||h||!e.cardCoverAssetId?null:(e.attachments||[]).find($=>typeof $!="string"&&String($.assetId||"").trim()===e.cardCoverAssetId&&$.linkRole==="image"&&at($))||null,kt=rt?`${rt.assetId||""}:${rt.path}`:"",xe=(e.attachments||[]).filter($=>!rt||typeof $=="string"||$.assetId!==rt.assetId),[St,jt]=Y.useState(!1);return Y.useEffect(()=>{jt(!1)},[kt]),a.jsxs("div",{className:_e,onClick:()=>T?.(e),style:G,"data-task-card":"true",children:[a.jsxs("div",{className:mr.taskHeader,children:[C&&a.jsx("label",{className:mr.selectionControl,onClick:$=>$.stopPropagation(),onPointerDown:$=>$.stopPropagation(),children:a.jsx("input",{type:"checkbox",checked:S,onChange:$=>w?.($.target.checked),"aria-label":`Select ${Le||e.title} for restore`})}),a.jsxs("div",{className:mr.taskReferenceCluster,children:[p?a.jsxs(a.Fragment,{children:[a.jsx(Ou,{copied:r===he,onClick:$=>fe($,he),disabled:!he,title:p.title,ariaLabel:`Copy initiative reference ${he}: ${p.title}`,className:y?mr.archiveBadge:"",label:he}),a.jsx("span",{className:mr.taskReferenceDivider,children:"/"})]}):null,f?a.jsxs(a.Fragment,{children:[a.jsx(Ou,{copied:r===ge,onClick:$=>fe($,ge),disabled:!ge,title:f.title,ariaLabel:`Copy workstream reference ${ge}: ${f.title}`,className:y?mr.archiveBadge:"",label:ge}),a.jsx("span",{className:mr.taskReferenceDivider,children:"/"})]}):null,pe&&!f?a.jsx("div",{className:mr.taskReferenceSegment,onClick:$=>$.stopPropagation(),onPointerDown:$=>$.stopPropagation(),onKeyDown:$=>$.stopPropagation(),children:a.jsx(BI,{workstreams:d,disabled:le,onSelect:$=>{Ee($.id)}})}):null,Le?a.jsx("div",{className:mr.taskReferenceSegment,onClick:$=>$.stopPropagation(),onPointerDown:$=>$.stopPropagation(),onKeyDown:$=>$.stopPropagation(),children:a.jsx(Ou,{copied:Ye&&r===ce.label,onClick:$=>fe($,ce.label),disabled:!Ye,title:Ie?"Temporary identifier — replaced after synchronization.":"Copy task reference",ariaLabel:Ie?`Copy temporary task reference ${Le}`:void 0,className:y?mr.archiveBadge:"",label:kh(Le,t),provisional:Ie})}):null]}),a.jsx("div",{className:mr.taskActions,onClick:$=>$.stopPropagation(),children:ue?F||z?a.jsxs(a.Fragment,{children:[F&&a.jsx("button",{type:"button",className:R.actionBtn,onClick:()=>F(e.id),title:Pe==="deleted"?`Restore to ${e.isArchived===!0?"Archived":"Active"}`:"Restore archived task",children:a.jsx(bi,{size:16})}),z&&a.jsx("button",{type:"button",className:`${R.actionBtn} ${R.deleteBtn}`,onClick:()=>z(e.id),title:M||(Pe==="deleted"?"Delete Permanently":"Move to Trash"),children:a.jsx(Vf,{size:16})})]}):null:a.jsx(ig,{task:e,compressed:ve,shortLabels:!0,showLabel:te,onSetStatus:($,Ke)=>{if(_){_($,Ke);return}if(Ke==="in-progress"){x?.($);return}if(Ke==="review"){N?.($);return}if(Ke==="done"){v?.($);return}Ke==="cancelled"&&V?.($)},onArchiveTask:j})})]}),rt&&!St&&a.jsx("button",{type:"button",className:mr.taskCover,"aria-label":`Preview ${oe(rt)}`,onPointerDown:$=>$.stopPropagation(),onClick:$=>{$.stopPropagation(),!$e(rt)&&(av(rt,{taskId:e.id,taskReferenceLabel:Le})||window.open(rt.path,"_blank"))},children:a.jsx("img",{src:rt.path,alt:rt.caption||rt.displayName||rt.originalFilename||e.title,loading:"lazy",decoding:"async",onError:()=>jt(!0)})}),a.jsxs("div",{className:mr.taskContent,children:[ue&&a.jsx("div",{className:`${mr.taskMeta} ${mr.taskMetaCompact}`}),a.jsxs("div",{children:[a.jsxs("div",{className:mr.taskTitle,style:ve?{fontSize:"13px",lineHeight:"1.4"}:{},children:[Pe==="archived"&&"✓ ",Pe==="deleted"&&"Deleted: ",kh(e.title,t)]}),ne&&a.jsx("div",{className:mr.deletedExpiry,title:"Trash items are permanently deleted 90 days after deletion.",children:ne}),e.description&&!ue&&!ve&&a.jsx("div",{className:mr.taskDescription,children:a.jsx(Mg,{variant:"compact",taskReferences:O,children:e.description})})]}),xe.length>0&&!ue&&!ve&&a.jsxs("div",{className:mr.attachmentThumbnails,children:[a.jsx("div",{className:mr.attachmentImageRow,children:xe.map(($,Ke)=>{const Qe=typeof $=="string"?$:$.path;return at($)?a.jsx("button",{type:"button",className:mr.attachmentThumbnail,"aria-label":`Preview ${oe($)}`,onPointerDown:Ge=>Ge.stopPropagation(),onClick:Ge=>{Ge.stopPropagation(),!$e($)&&(av(typeof $=="string"?{path:Qe}:$,{taskId:e.id,taskReferenceLabel:Le})||window.open(Qe,"_blank"))},children:a.jsx("img",{src:Qe,alt:`Attachment ${Ke}`})},Ke):null})}),a.jsx("div",{className:mr.attachmentDocumentList,children:xe.map(($,Ke)=>{const Qe=typeof $=="string"?$:$.path,Ge=typeof $=="string"?void 0:$.fsPath,At=oe($);if(at($))return null;const Nt=We($),Bt=aE(Nt);return a.jsxs("button",{type:"button",className:mr.contextDocThumb,onPointerDown:Qt=>Qt.stopPropagation(),onClick:Qt=>{if(Qt.stopPropagation(),$e($))return;const Xt=typeof $=="string"?{path:$,taskId:e.id}:{...$,taskId:e.id};fI(Xt,Ge)||window.open(Qe,"_blank")},title:At,"aria-label":`${At} ${Nt}`,style:{"--context-doc-accent":Bt},children:[a.jsx(G8,{label:Nt,accentColor:Bt,compact:!0}),a.jsx("span",{className:mr.contextDocMain,children:a.jsx("span",{className:mr.contextDocName,children:At})})]},Ke)})})]}),e.status==="cancelled"&&e.canceledReason&&!ve&&a.jsxs("div",{className:mr.taskCancellationReason,children:[a.jsx("strong",{children:"Cancellation Reason:"})," ",kh(e.canceledReason,t)]}),(ee||Se>0)&&!ue&&!ve&&a.jsxs("div",{className:mr.taskLatestComment,"data-task-activity-summary":"true",children:[a.jsxs("div",{className:mr.taskLatestCommentHeader,children:[a.jsx("strong",{children:ee?"Latest Activity:":"Activity:"}),Se>0&&a.jsxs("span",{className:`${R.metaBadge} ${mr.taskCommentCount}`,title:`${Se} ${Se===1?"comment":"comments"}`,"aria-label":`${Se} ${Se===1?"comment":"comments"}`,children:[a.jsx(V8,{size:12,"aria-hidden":"true"}),a.jsx("span",{children:Se})]})]}),ee&&a.jsx("div",{className:mr.taskLatestCommentText,title:ee,children:kh(ee,t)})]}),!ue&&Xe.length>0&&!ve&&a.jsx("div",{className:`${mr.taskSpecialists} ${mr.taxonomiesList}`,children:Xe.map($=>{const Ke=e.taxonomies?.[$.id];return Ke?(Array.isArray(Ke)?Ke:[Ke]).map(Ge=>{const At=$.options.find(nt=>nt.value===Ge);if(!At)return null;const Nt=Gs[At.icon||"Layers"]||Vh,Bt=rn(At.color)||"var(--text-primary)",Qt=$.status==="retired"?`${$.label} (Retired)`:$.label,Xt=At.status==="retired"?`${At.label} (Retired)`:At.label;return a.jsx("span",{className:R.specialistBadge,style:{borderColor:`${Bt}50`,backgroundColor:`${Bt}15`,color:Bt},title:`${Qt}: ${Be(Xt)}`,children:a.jsx(Nt,{size:10})},`${$.id}-${Ge}`)}):null})}),a.jsx("div",{className:mr.taskMeta,children:ue?a.jsx("span",{children:e.category}):a.jsx(a.Fragment,{children:a.jsxs("div",{className:mr.taskMetaRow,style:ve?{marginBottom:0}:void 0,children:[a.jsxs("div",{className:mr.taskMetaBadgeGroup,"data-task-meta-primary":"true",children:[(()=>{const $=rn(ae?.color),Ke=ae?.icon||"Folder",Qe=Gs[Ke]||Qi;return a.jsx("span",{className:`${R.metaBadge} ${mr.taskMetaCategory}`,title:Be(e.category),style:{color:$||"var(--text-secondary)",backgroundColor:$?`${$}15`:"var(--bg-tertiary)",borderColor:$?`${$}40`:"transparent"},children:a.jsx(Qe,{size:14})})})(),a.jsx("span",{className:`${R.metaBadge} ${mr.taskMetaType} ${R[`type_${e.type}`]||""}`,title:Be(e.type||fo),style:{color:`var(--type-color, ${st})`,backgroundColor:`color-mix(in srgb, var(--type-color, ${st}), transparent 90%)`,borderColor:`color-mix(in srgb, var(--type-color, ${st}), transparent 75%)`},children:Ze?.icon?(()=>{const $=Gs[Ze.icon]||Y8;return a.jsx($,{size:14})})():yz(e.type,14)}),Ae&&a.jsx("span",{className:`${R.metaBadge} ${mr.taskMetaPriority}`,style:{color:ke||"var(--text-secondary)",backgroundColor:ke?`${ke}15`:"var(--bg-tertiary)",borderColor:ke?`${ke}40`:"var(--border-color)"},title:`${Ae.label}`,children:(()=>{const $=Ae.icon||"AlertCircle",Ke=Gs[$]||JT;return a.jsx(Ke,{size:14})})()}),qe>0&&a.jsxs("span",{className:R.metaBadge,title:`${Te}/${qe} checklist items complete`,style:{color:"var(--text-muted)",backgroundColor:"var(--bg-tertiary)",borderColor:"var(--border-primary)",gap:"4px",padding:"0 8px"},children:[a.jsx(q8,{size:14}),a.jsx("span",{children:`${Te}/${qe}`})]})]}),a.jsxs("div",{className:mr.taskMetaIdentityGroup,"data-task-meta-identity":"true",children:[a.jsxs("span",{className:R.metaBadge,title:`AI-estimated complexity: ${we} (${W}/5)`,style:{color:ie,backgroundColor:`color-mix(in srgb, ${ie}, transparent 88%)`,borderColor:`color-mix(in srgb, ${ie}, transparent 72%)`,gap:"4px",padding:"0 8px"},children:[a.jsx(K8,{size:14}),!ve&&a.jsx("span",{className:mr.taskComplexityLabel,children:we})]}),(()=>{const $=H.kind==="unassigned",Ke=a.jsx("span",{className:mr.assigneeAvatarShared,"data-task-assignee":"true","aria-hidden":Me?"true":void 0,"aria-label":Me?void 0:$?"Unassigned":`Assigned to ${Q}`,children:a.jsx(Lg,{option:H,size:ve?32:36,variant:"card",unassignedIcon:Me?ri:void 0})});return Me?a.jsx("div",{className:mr.assigneePicker,title:$?"Assign task":Q,onClick:Qe=>Qe.stopPropagation(),onPointerDown:Qe=>Qe.stopPropagation(),onKeyDown:Qe=>Qe.stopPropagation(),children:a.jsx(ai,{value:e.assignee||"unassigned",options:c,onChange:Qe=>Z?.(e,String(Qe)),ariaLabel:$?"Assign task":`Reassign task currently assigned to ${Q}`,hideChevron:!0,portalPanel:!0,panelMinWidth:240,searchable:!0,searchPlaceholder:"Search assignees...",noResultsText:"No assignees found.",renderOptionContent:Qe=>{const Ge=c.find(At=>String(At.value)===String(Qe.value));return Ge?a.jsx(qu,{option:Ge}):Qe.label},triggerContent:Ke})}):a.jsx("span",{title:Q,children:Ke})})()]})]})})})]})]})},Hf=Y.memo(Z8),dg="168px",Iu=[{value:"open",label:"Open"},{value:"archived",label:"Archived"},{value:"deleted",label:"Deleted"}];function J8(){return a.jsx("span",{style:{fontSize:"12px",fontWeight:600,color:"var(--text-secondary)",marginRight:"4px"},children:bt("standalone.filtersCaps")})}function of({label:e,options:t,selected:r,onChange:n,variant:s="label",renderOptionContent:i,searchable:l=!1,searchPlaceholder:c,noResultsText:d}){return a.jsx(md,{label:e,options:t,selected:r,onChange:n,variant:s,renderOptionContent:i,searchable:l,searchPlaceholder:c,noResultsText:d,containerStyle:{flex:`0 0 ${dg}`,maxWidth:dg}})}function Q8({onClick:e,disabled:t,label:r="Reset filters"}){return a.jsx("button",{type:"button",className:"tf-control-icon",onClick:e,disabled:t,"aria-label":r,title:r,children:a.jsx(bi,{size:14,"aria-hidden":"true"})})}function wS({label:e,options:t,selected:r,onChange:n,allLabel:s,title:i}){const[l,c]=Y.useState(!1),d=Y.useRef(null),f=t.find(h=>h.value===r),p=f?.selectedLabel||f?.label||s;Y.useEffect(()=>{const h=y=>{d.current&&!d.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const g=h=>{n(h),c(!1)};return a.jsxs("div",{className:R.filterContainer,ref:d,style:{flex:`0 0 ${dg}`,maxWidth:dg},children:[a.jsxs("button",{type:"button",className:`${R.filterButton} ${r?R.filterActive:""}`,onClick:()=>c(h=>!h),title:i||`Filter by ${e}`,"aria-haspopup":"listbox","aria-expanded":l,children:[a.jsx("span",{children:p}),a.jsx(Nd,{size:14,style:{transform:l?"rotate(180deg)":"none",transition:"transform 0.2s",opacity:.5}})]}),l&&a.jsxs("div",{className:`${R.filterDropdown} ${R.appScrollbar} tf-scrollbar`,role:"listbox","aria-label":e,children:[a.jsxs("button",{type:"button",className:R.filterOption,onClick:()=>g(""),"aria-selected":!r,children:[a.jsx(Si,{size:14,style:{opacity:r?0:1}}),a.jsx("span",{style:{fontWeight:r?500:600},children:s})]}),a.jsx("div",{className:R.filterDivider}),t.map(h=>{const y=h.value===r;return a.jsxs("button",{type:"button",className:R.filterOption,onClick:()=>g(h.value),"aria-selected":y,children:[a.jsx(Si,{size:14,style:{opacity:y?1:0}}),a.jsx("span",{style:{fontWeight:y?600:500},children:h.label})]},h.value)})]})]})}function WI({scope:e,onScopeChange:t,className:r,labelClassName:n}){const s=Y.useRef([]),i=(l,c)=>{let d;l.key==="ArrowRight"?d=(c+1)%Iu.length:l.key==="ArrowLeft"?d=(c-1+Iu.length)%Iu.length:l.key==="Home"?d=0:l.key==="End"&&(d=Iu.length-1),d!==void 0&&(l.preventDefault(),s.current[d]?.focus(),t(Iu[d].value))};return a.jsxs("div",{className:[R.taskScopeToggle,r].filter(Boolean).join(" "),children:[a.jsx("span",{className:n,children:"Scope"}),a.jsx("div",{className:R.taskScopeTabs,role:"tablist","aria-label":"Task scope",children:Iu.map((l,c)=>{const d=e===l.value;return a.jsx("button",{ref:f=>{s.current[c]=f},type:"button",className:`${R.taskScopeTab} ${d?R.taskScopeTabActive:""}`,onClick:()=>t(l.value),onKeyDown:f=>i(f,c),role:"tab","aria-selected":d,tabIndex:d?0:-1,title:`Show ${l.label.toLowerCase()} tasks`,children:l.label},l.value)})})]})}function X8({onClick:e,disabled:t=!1,className:r,title:n="Permanently delete all deleted tasks",children:s="Delete All Permanently"}){return a.jsxs("button",{type:"button",className:r,onClick:e,disabled:t,title:n,children:[a.jsx(Vf,{size:14}),s]})}const{Search:bS,ClipboardList:e9,ChevronRight:t9,ChevronDown:r9,Folder:a9,Archive:n9,RotateCcw:s9,X:o9,Plus:i9,ArrowUpDown:c9,Trash2:l9}=Gs,d9=new Map,u9=new Set,$I=o.forwardRef((e,t)=>{const{tasks:r,archivedTasks:n,categories:s,types:i,priorities:l,taxonomyDisplayLabels:c,assigneeOptions:d=[],workstreams:f=[],initiatives:p=[],workspaceId:g=null,searchQuery:h,filterCategories:y,filterTypes:k,filterPriorities:b,filterStatus:C,filterAssignees:S=[],filterTaxonomies:w,sortBy:T,sortOrder:E,showArchive:x,taskScope:N,collapsedCategories:v,loadingTasks:V,filteredTasks:_,filteredArchive:j,groupedTasks:F,filteredDeletedTasks:z=[],groupedDeletedTasks:M={},copiedId:O,recentlyChangedTaskIds:Z=[],showTaskCardStatusLabel:U=!1,deletedTaskRecordByTaskId:ve=d9,selectedDeletedRecordIds:te=u9,onDeletedSelectionChange:ce,trashControls:Le,onSearchChange:Ie,onFilterCategoriesChange:Ye,onFilterTypesChange:ge,onFilterPrioritiesChange:he,onFilterStatusChange:Ae,onFilterAssigneesChange:ye,onTaxonomyFilterChange:Ne,onSortByChange:ae,onSortOrderChange:q,onShowArchiveChange:W,onTaskScopeChange:K,onClearFilters:Re,onToggleCategory:we,onEditTask:ie,onUpdateTask:Q,taskReferences:H,onCopyId:se,onToggleInProgress:Pe,onToggleReview:ue,onToggleComplete:ne,onToggleCancel:Me,onSetStatus:pe,onArchiveTask:le,onBulkArchive:Ce,onUnarchive:P,onDelete:ee,onFetchArchive:Se,onAddTaskToCategory:_e,supplementalTasks:ke=[],taxonomies:Ze}=e,st=Y.useMemo(()=>new Set(Z),[Z]),at=Y.useMemo(()=>new Map(f.map($=>[$.id,$])),[f]),oe=Y.useMemo(()=>new Map(p.map($=>[$.id,$])),[p]),We=Y.useCallback($=>{const Ke=$.workstreamId&&at.get($.workstreamId)||null,Qe=Ke?.initiativeId&&oe.get(Ke.initiativeId)||null;return{taskWorkstream:Ke,taskInitiative:Qe}},[oe,at]),G=Y.useMemo(()=>[...r,...n,...ke],[n,ke,r]),Be=Y.useCallback(($,Ke)=>Q($.id,{assignee:Ke}),[Q]),Xe=!!K,ze=K,qe=N??(x?"archived":"open"),Te=Xe?qe==="archived"?j:qe==="deleted"?z:_:_,fe=Xe?qe==="archived"?{Archived:j}:qe==="deleted"?M:F:F,Ee=Xe?qe==="deleted"?"deleted":qe==="archived"?"archived":null:null,$e=Eg(h),rt=h?$e?`No task found for ${$e.toUpperCase()}`:bt("taskList.noMatchingTasks"):qe==="archived"?"No archived tasks found.":qe==="deleted"?"No deleted tasks found.":bt("taskList.noActiveTasks"),kt=Y.useMemo(()=>{const $=s.filter(Qe=>!Qe.disabled),Ke=s.filter(Qe=>Qe.disabled&&G.some(Ge=>Ge.category===Qe.value));return[...$,...Ke.filter(Qe=>!$.some(Ge=>Ge.value===Qe.value))].map(Qe=>({value:Qe.value,label:Qe.disabled?`${Qe.label} (Legacy)`:Qe.label}))},[s,G]),xe=Y.useMemo(()=>{const $=i.filter(Qe=>Qe.status!=="retired"),Ke=i.filter(Qe=>Qe.status==="retired"&&G.some(Ge=>Ge.type===Qe.value));return[...$,...Ke.filter(Qe=>!$.some(Ge=>Ge.value===Qe.value))].map(Qe=>({value:Qe.value,label:Qe.status==="retired"?`${Qe.label} (Retired)`:Qe.label}))},[G,i]),St=Y.useMemo(()=>Zf(Ze,G).filter($=>$.filterEnabled!==!1).map($=>({...$,options:Qv($,G)})),[G,Ze]),jt=Y.useMemo(()=>[{value:"created",label:bt("taskList.sortCreated")},{value:"updated",label:bt("taskList.sortUpdated")},{value:"priority",label:bt("taskList.sortPriority")},...ZC(Ze,G)],[G,bt,Ze]);return a.jsxs("div",{className:R.viewTab,ref:t,children:[a.jsxs("div",{className:R.filterBar,children:[a.jsxs("div",{className:R.searchContainer,children:[a.jsx(bS,{size:16,className:R.searchIcon}),a.jsx("input",{type:"text",className:R.searchInput,placeholder:bt("taskList.searchPlaceholder"),value:h,onChange:$=>Ie($.target.value)}),h&&a.jsx("button",{className:R.clearSearchBtn,onClick:()=>Ie(""),title:bt("taskList.clearSearchTitle"),children:a.jsx(o9,{size:14})})]}),a.jsxs("div",{className:R.filterRow,children:[a.jsx(md,{label:c?.category||bt("taskList.categoryLabel"),options:kt,selected:y,onChange:Ye,variant:"value"}),a.jsx(md,{label:c?.type||bt("taskList.typeLabel"),options:xe,selected:k,onChange:ge,variant:"value"})]}),a.jsxs("div",{className:R.filterRow,children:[a.jsx(md,{label:c?.priority||bt("taskList.priorityLabel"),options:l,selected:b,onChange:he,variant:"value"}),a.jsx(md,{label:bt("taskList.statusLabel"),options:rc,selected:C,onChange:Ae,variant:"value"}),a.jsx(md,{label:bt("taskList.assigneeLabel"),options:d,selected:S,onChange:$=>ye?.($),variant:"value",renderOptionContent:$=>{const Ke=d.find(Qe=>String(Qe.value)===String($.value));return Ke?a.jsx(qu,{option:Ke,size:20}):$.label}})]}),St.map($=>a.jsx(md,{label:$.status==="retired"?`${$.label} (Retired)`:$.label,options:$.options.map(Ke=>({...Ke,label:Ke.status==="retired"?`${Ke.label} (Retired)`:Ke.label})),selected:w[$.id]||[],onChange:Ke=>Ne($.id,Ke),variant:"value"},$.id)),a.jsxs("div",{className:R.filterRow,children:[a.jsxs("div",{className:R.sortLabel,children:[a.jsx(c9,{size:14,style:{marginRight:"4px"}})," ",bt("taskList.sortByLabel")]}),a.jsx("select",{value:T,onChange:$=>ae($.target.value),className:`${R.filterSelect} ${R.filterSelectSort} `,children:jt.map($=>a.jsx("option",{value:$.value,children:$.label},$.value))}),a.jsx("button",{className:`${R.resetFiltersBtn} ${R.sortDirectionBtnWidget}`,onClick:q,title:bt(E==="desc"?"taskList.sortDirectionDescTitle":"taskList.sortDirectionAscTitle"),children:E==="desc"?a.jsx(gv,{size:14}):a.jsx(sA,{size:14})}),a.jsx("button",{className:R.resetFiltersBtn,onClick:Re,title:bt("taskList.resetFiltersTitle"),children:a.jsx(s9,{size:14})})]}),a.jsxs("div",{className:`${R.filterRow} ${R.archiveRow} `,children:[qe==="open"?a.jsxs("button",{className:`${R.bulkArchiveBtn} ${r.some($=>$.status==="done"||$.status==="cancelled")?"":R.disabledBtn} `,onClick:()=>r.some($=>$.status==="done"||$.status==="cancelled")&&Ce(),disabled:!r.some($=>$.status==="done"||$.status==="cancelled"),title:r.some($=>$.status==="done"||$.status==="cancelled")?bt("taskList.archiveAllTitle"):bt("taskList.noTasksToArchiveTitle"),children:[a.jsx(n9,{size:12}),a.jsx("span",{children:bt("taskList.archiveFinished")})]}):qe==="deleted"?a.jsx("div",{}):a.jsx("div",{}),Xe?a.jsx(WI,{scope:qe,onScopeChange:$=>{ze?.($),$==="archived"?W(!0):x&&W(!1)},className:R.archiveToggle}):a.jsxs("label",{className:R.archiveToggle,children:[a.jsx("input",{type:"checkbox","aria-label":"Archived",checked:x,onChange:$=>{W($.target.checked),$.target.checked&&Se()}}),a.jsx("span",{children:"Include Archive"})]})]}),qe==="deleted"&&Le]}),V&&r.length===0?a.jsx("div",{className:R.loading,children:a.jsx(za,{size:24,className:R.spinner})}):Te.length===0&&!V?a.jsxs("div",{className:R.emptyState,children:[h?a.jsx(bS,{size:48}):qe==="deleted"?a.jsx(l9,{size:48}):a.jsx(e9,{size:48}),a.jsx("p",{children:rt})]}):a.jsx("div",{className:R.taskList,style:{opacity:V?.6:1,transition:"opacity 0.2s ease"},children:Object.entries(fe).map(([$,Ke])=>{if(Ke.length===0)return null;const Qe=v[$];return a.jsxs("div",{className:R.categoryGroup,children:[a.jsx("div",{className:R.categoryHeader,onClick:()=>we($),children:a.jsxs("div",{className:R.categoryTitle,children:[Qe?a.jsx(t9,{size:16}):a.jsx(r9,{size:16}),(()=>{const Ge=s.find(Bt=>Bt.label===$),At=Ge?.icon&&Hu[Ge.icon]?Hu[Ge.icon]:a9,Nt=rn(Ge?.color)||"var(--color-purple, #8b5cf6)";return a.jsx(At,{size:16,className:R.categoryTitleIcon,style:{color:Nt}})})(),$,a.jsxs("span",{className:R.categoryCount,children:["(",Ke.length,")"]}),_e&&a.jsx("button",{className:R.kanbanQuickAdd,onClick:Ge=>{Ge.stopPropagation(),_e($)},title:bt("taskList.addTaskToCategoryTitle",{category:$}),style:{marginLeft:"auto"},disabled:Ee!==null,children:a.jsx(i9,{size:14})})]})}),!Qe&&a.jsx("div",{className:R.categoryItems,children:Ke.map(Ge=>(()=>{const{taskWorkstream:At,taskInitiative:Nt}=We(Ge),Bt=Ee==="deleted"?ve.get(Ge.id):void 0;return a.jsx(Hf,{task:Ge,taskWorkstream:At,taskInitiative:Nt,workspaceId:g,searchQuery:h,copiedId:O,taxonomies:Ze,types:i,priorities:l,assigneeOptions:d,workstreams:f,onClick:ie,onAssigneeChange:Be,onWorkstreamChange:(Qt,Xt)=>Q(Qt.id,{workstreamId:Xt}),taskReferences:H,onCopyId:se,onToggleInProgress:Pe,onToggleReview:ue,onToggleComplete:ne,onToggleCancel:Me,onSetStatus:pe,onArchiveTask:le,onUnarchive:Ee?P:void 0,onDelete:Ee?ee:void 0,categories:s,isRecentlyChanged:st.has(Ge.id),readOnlyMode:Ee,selectable:!!(Bt&&ce),selected:!!(Bt&&te.has(Bt.id)),onSelectionChange:Bt?Qt=>ce?.(Bt.id,Qt):void 0,showStatusLabel:U},Ge.id)})())})]},$)})}),!Xe&&x&&j.length>0&&a.jsxs("div",{className:R.archiveList,children:[a.jsx("div",{className:R.archiveHeader,children:"Archived"}),j.map($=>(()=>{const{taskWorkstream:Ke,taskInitiative:Qe}=We($);return a.jsx(Hf,{task:$,taskWorkstream:Ke,taskInitiative:Qe,workspaceId:g,searchQuery:h,copiedId:O,isArchived:!0,types:i,assigneeOptions:d,workstreams:f,onClick:ie,onCopyId:se,onSetStatus:pe,onUnarchive:P,onDelete:ee,deleteActionTitle:"Delete Permanently",taskReferences:H,categories:s,showStatusLabel:U},$.id)})())]})]})});$I.displayName="TaskList";const p9="_formNotice_1h100_1",f9="_markdownPreview_1h100_12",m9="_descriptionField_1h100_18",h9="_descriptionImageStatus_1h100_22",g9="_descriptionImageError_1h100_23",y9="_taskFormLifecycle_1h100_46",k9="_taskFormMetaDivider_1h100_51",v9="_taskFormMetaGrid_1h100_58",w9="_compactMetaGrid_1h100_59",b9="_compactMetaSection_1h100_65",S9="_compactMetaField_1h100_71",A9="_compactMetaFieldHint_1h100_85",C9="_workflowAssignmentField_1h100_89",I9="_workflowAssignmentLabels_1h100_93",_9="_workflowAssignmentControls_1h100_94",T9="_workflowAssignmentSelector_1h100_101",x9="_workflowAssignmentError_1h100_110",R9="_workflowExecutionToggle_1h100_121",j9="_workflowExecutionVersion_1h100_147",P9="_workflowExecutionPanel_1h100_168",E9="_workflowExecutionHeader_1h100_176",N9="_workflowExecutionEyebrow_1h100_195",M9="_workflowExecutionSummary_1h100_196",D9="_workflowExecutionSpinner_1h100_206",L9="_workflowExecutionSteps_1h100_239",O9="_workflowExecutionStepCurrent_1h100_261",B9="_workflowExecutionStepMarker_1h100_266",W9="_workflowExecutionStepCompleted_1h100_277",$9="_workflowExecutionStepState_1h100_278",F9="_workflowExecutionStepBody_1h100_282",U9="_workflowExecutionStepTitle_1h100_286",z9="_workflowExecutionStepMeta_1h100_308",H9="_workflowExecutionEmpty_1h100_310",G9="_formFieldsetReset_1h100_350",V9="_formLayoutWithSidebar_1h100_357",K9="_formMainColumn_1h100_365",q9="_activitySidebar_1h100_372",Y9="_activitySidebarHeader_1h100_382",Z9="_activitySidebarTitle_1h100_389",J9="_taskFormDateRow_1h100_398",Q9="_taskFormDateLabel_1h100_405",X9="_taskFormDateValue_1h100_413",e7="_taskFormMetaStack_1h100_421",t7="_taskFormMetaActor_1h100_427",r7="_taskFormDateWarning_1h100_433",a7="_taskFormDateError_1h100_439",n7="_helpHeader_1h100_445",s7="_helpClose_1h100_456",o7="_markdownHelp_1h100_470",i7="_helpGrid_1h100_479",c7="_helpGridItem_1h100_485",l7="_settingsHint_1h100_497",d7="_sectionBlock_1h100_503",u7="_specialistSectionWithoutTaxonomies_1h100_509",p7="_softSectionSurface_1h100_514",f7="_stackedList_1h100_521",m7="_stackedListSpaced_1h100_526",h7="_checklistInputGroup_1h100_530",g7="_checklistRow_1h100_537",y7="_checklistRowDragging_1h100_546",k7="_checklistHandleBtn_1h100_550",v7="_checklistCheckboxBtn_1h100_573",w7="_checklistCheckboxBtnChecked_1h100_593",b7="_checklistItemText_1h100_598",S7="_checklistItemTextCompleted_1h100_606",A7="_checklistRemoveBtn_1h100_611",C7="_specialistChip_1h100_643",I7="_specialistChipActive_1h100_666",_7="_commentPanel_1h100_676",T7="_activitySidebarPanel_1h100_690",x7="_commentThread_1h100_698",R7="_activityTimelineRegion_1h100_702",j7="_activityLoadingThread_1h100_711",P7="_newActivityNotice_1h100_715",E7="_newActivityButton_1h100_723",N7="_emptyComments_1h100_767",M7="_activitySkeletonItem_1h100_781",D7="_activitySkeletonMeta_1h100_787",L7="_activitySkeletonBody_1h100_788",O7="_commentInputArea_1h100_912",B7="_commentInput_1h100_912",W7="_sendCommentBtn_1h100_955",$7="_taxonomyFieldsGrid_1h100_998",F7="_markdownPreviewContainer_1h100_1005",U7="_descriptionSurface_1h100_1010",gt={formNotice:p9,markdownPreview:f9,descriptionField:m9,descriptionImageStatus:h9,descriptionImageError:g9,taskFormLifecycle:y9,taskFormMetaDivider:k9,taskFormMetaGrid:v9,compactMetaGrid:w9,compactMetaSection:b9,compactMetaField:S9,compactMetaFieldHint:A9,workflowAssignmentField:C9,workflowAssignmentLabels:I9,workflowAssignmentControls:_9,workflowAssignmentSelector:T9,workflowAssignmentError:x9,workflowExecutionToggle:R9,workflowExecutionVersion:j9,workflowExecutionPanel:P9,workflowExecutionHeader:E9,workflowExecutionEyebrow:N9,workflowExecutionSummary:M9,workflowExecutionSpinner:D9,workflowExecutionSteps:L9,workflowExecutionStepCurrent:O9,workflowExecutionStepMarker:B9,workflowExecutionStepCompleted:W9,workflowExecutionStepState:$9,workflowExecutionStepBody:F9,workflowExecutionStepTitle:U9,workflowExecutionStepMeta:z9,workflowExecutionEmpty:H9,formFieldsetReset:G9,formLayoutWithSidebar:V9,formMainColumn:K9,activitySidebar:q9,activitySidebarHeader:Y9,activitySidebarTitle:Z9,taskFormDateRow:J9,taskFormDateLabel:Q9,taskFormDateValue:X9,taskFormMetaStack:e7,taskFormMetaActor:t7,taskFormDateWarning:r7,taskFormDateError:a7,helpHeader:n7,helpClose:s7,markdownHelp:o7,helpGrid:i7,helpGridItem:c7,settingsHint:l7,sectionBlock:d7,specialistSectionWithoutTaxonomies:u7,softSectionSurface:p7,stackedList:f7,stackedListSpaced:m7,checklistInputGroup:h7,checklistRow:g7,checklistRowDragging:y7,checklistHandleBtn:k7,checklistCheckboxBtn:v7,checklistCheckboxBtnChecked:w7,checklistItemText:b7,checklistItemTextCompleted:S7,checklistRemoveBtn:A7,specialistChip:C7,specialistChipActive:I7,commentPanel:_7,activitySidebarPanel:T7,commentThread:x7,activityTimelineRegion:R7,activityLoadingThread:j7,newActivityNotice:P7,newActivityButton:E7,emptyComments:N7,activitySkeletonItem:M7,activitySkeletonMeta:D7,activitySkeletonBody:L7,commentInputArea:O7,commentInput:B7,sendCommentBtn:W7,taxonomyFieldsGrid:$7,markdownPreviewContainer:F7,descriptionSurface:U7};function hk({label:e,value:t,options:r,onChange:n,type:s="priority",hideLabel:i=!1,showSelectedLabel:l=!0}){const c=r.find(d=>String(d.value)===String(t));return a.jsxs("div",{className:R.field,children:[!i&&a.jsxs("div",{className:R.labelRow,children:[a.jsx("label",{className:R.label,children:e}),l&&c&&a.jsx("span",{className:R.levelLabel,style:{color:rn(c.color)||(s==="priority"?`var(--priority-${t})`:s==="complexity"?`var(--complexity-${t})`:"var(--text-secondary)"),backgroundColor:(rn(c.color)?`${rn(c.color)}25`:void 0)||(s==="priority"?`color-mix(in srgb, var(--priority-${t}), transparent 85%)`:s==="complexity"?`color-mix(in srgb, var(--complexity-${t}), transparent 85%)`:"rgba(255,255,255,0.05)")},children:c.label})]}),a.jsx("div",{className:R.levelSelect,children:r.map((d,f)=>{const p=r.findIndex(y=>String(y.value)===String(t)),g=f<=p,h=String(d.value)===String(t);return a.jsx("button",{type:"button",className:`${R.levelOption} ${g?R.levelOptionFilled:""} ${g?R[`levelOption_${s}_${d.value}`]:""} ${h?R.levelOptionSelected:""}`,onClick:()=>n(d.value),title:d.label,style:{opacity:g?1:.15,backgroundColor:g?rn(d.color)||(s==="priority"?`var(--priority-${d.value})`:s==="complexity"?`var(--complexity-${d.value})`:"var(--text-primary)"):void 0,color:g?s==="priority"&&String(d.value).toLowerCase()==="medium"?"black":"white":void 0,boxShadow:g&&(s==="priority"&&(String(d.value).toLowerCase()==="critical"||d.value===4)||s==="complexity"&&(String(d.value).toLowerCase()==="epic"||d.value===5))?`0 0 12px ${s==="priority"?"rgba(239, 68, 68, 0.6)":"rgba(217, 70, 239, 0.6)"}`:void 0}},String(d.value))})})]})}const SS=new Map;function z7(e){const t=e instanceof Date?e:new Date(e);return Number.isNaN(t.getTime())?null:t}function H7(e,t){const r=Object.entries(t).sort(([n],[s])=>n.localeCompare(s));return JSON.stringify([e,r])}function ug(e,t,r){const n=z7(e);if(!n)return"";const s=r??NA(),i=H7(s,t);let l=SS.get(i);return l||(l=new Intl.DateTimeFormat(s,t),SS.set(i,l)),l.format(n)}function G7(e){return new Promise((t,r)=>{const n=new FileReader;n.onload=()=>t(String(n.result||"")),n.onerror=()=>r(n.error||new Error("Failed to read file")),n.readAsDataURL(e)})}async function wh(e,t){try{const n=await(typeof e.clone=="function"?e.clone():e).json().catch(()=>null),s=String(n?.error||n?.message||"").trim();if(s)return s}catch{}try{const n=(await(typeof e.clone=="function"?e.clone():e).text().catch(()=>"")).trim();if(n)return n}catch{}return t}async function V7(e,t){const r=String(t.workspaceId||"").trim(),n=String(t.ownerId||"").trim(),s={ownerType:t.ownerType,ownerId:n||null,taskId:t.ownerType==="task"&&n||null},i=String(t.draftUploadId||"").trim(),l=i&&t.uploadPurpose?{draftUploadId:i,uploadPurpose:t.uploadPurpose}:{},c=globalThis.crypto?.randomUUID?.()||`context-upload-${Date.now()}-${Math.random().toString(16).slice(2)}`,d=()=>({"Content-Type":"application/json",...r?{"x-taskforce-workspace-id":r}:{},"x-taskforce-operation-id":c});let f=null,p=null;const g=await fetch("/api/taskforce/context-upload/init",{method:"POST",headers:d(),body:JSON.stringify({originalName:e.name,mimeType:e.type||"application/octet-stream",size:e.size,...s,...l,workspaceId:r||null})});if(g.ok){const h=await g.json();if(h?.success&&typeof h?.uploadUrl=="string"&&typeof h?.path=="string"){let y=!1;try{const k=await fetch(h.uploadUrl,{method:String(h.method||"PUT"),headers:h.headers||{"Content-Type":e.type||"application/octet-stream"},body:e});if(!k.ok)p=await wh(k,`Upload failed for ${e.name}`);else{y=!0;const b=await fetch("/api/taskforce/context-upload/finalize",{method:"POST",headers:d(),body:JSON.stringify({relativePath:h.relativePath,mimeType:e.type||"application/octet-stream",originalName:e.name,size:e.size,...s,...l,workspaceId:r||null})});if(!b.ok)throw new Error(await wh(b,`Upload failed for ${e.name}`));f=await b.json().catch(()=>null)}}catch(k){if(y)throw k;p=k instanceof Error?k.message:`Upload failed for ${e.name}`}}else h?.success&&typeof h?.path=="string"&&(f=h)}else p=await wh(g,`Upload failed for ${e.name}`);if(!f){const h=await G7(e),y=await fetch("/api/taskforce/context-upload",{method:"POST",headers:d(),body:JSON.stringify({file:h,originalName:e.name,...s,...l,workspaceId:r||null})});if(!y.ok){const k=await wh(y,`Upload failed for ${e.name}`);throw new Error(p&&p!==k?`${k} (${p})`:k)}f=await y.json()}if(!f?.success||!f?.path)throw new Error(`Upload failed for ${e.name}`);return{path:f.path,fsPath:f.fsPath,caption:typeof f.caption=="string"&&f.caption.trim().length>0?f.caption:e.name,displayName:typeof f.displayName=="string"?f.displayName:void 0,originalFilename:typeof f.originalFilename=="string"?f.originalFilename:e.name,assetId:typeof f.assetId=="string"?f.assetId:void 0,referenceNumber:typeof f.referenceNumber=="number"?f.referenceNumber:null,referenceLabel:typeof f.referenceLabel=="string"?f.referenceLabel:void 0,taskId:t.ownerType==="task"&&typeof f.taskId=="string"?f.taskId:null,timestamp:typeof f.timestamp=="string"&&f.timestamp.trim().length>0?f.timestamp:new Date().toISOString()}}class Mc extends Error{constructor(t,r){super(t),this.code=r,this.name="WorkflowManagerApiError"}}async function ni(e,t,r){const n=new Headers(t?.headers||void 0);t?.body&&n.set("Content-Type","application/json");const s=String(r?.workspaceId||"").trim();s&&s!=="default"&&n.set("x-taskforce-workspace-id",s);const i=await Yx(e,{credentials:"include",...t,headers:n},r?.apiBaseUrl),l=await i.json().catch(()=>({}));if(!i.ok||l.success===!1)throw new Mc(String(l.error||`Workflow request failed (${i.status}).`),l.code);return l}async function K7(e){const t=await ni("/api/taskforce/workflows",void 0,e);return Array.isArray(t.workflows)?t.workflows:[]}async function bh(e,t){return(await ni(`/api/taskforce/tasks/${encodeURIComponent(e)}/workflow`,void 0,t)).assignment||null}async function q7(e,t){if(t?.runtimeMode!=="local"||!e.assignmentSnapshot)return e.taskSnapshot||null;try{return(await ni(`/api/taskforce/workflow-executions/${encodeURIComponent(e.executionId)}/apply-cloud-state`,{method:"POST",body:JSON.stringify({assignment:e.assignmentSnapshot,taskAuthoritative:e.taskAuthoritative})},{workspaceId:t?.workspaceId})).task||null}catch{return null}}async function Y7(e,t,r,n,s){const i=await ni(`/api/taskforce/workflow-executions/${encodeURIComponent(e)}/complete-step?taskforceCloud=1`,{method:"POST",body:JSON.stringify({idempotencyKey:t,...n?{evidenceCommentId:n}:{},...s?{expectedStepId:s}:{}})},r);if(!i.result)throw new Mc("The workflow step result was not returned.");let l=i.result.taskSnapshot||null;return i.result.assignmentSnapshot&&i.result.route!=="local-outbox"&&(l=await q7({executionId:e,taskId:i.result.execution.taskId,assignmentSnapshot:i.result.assignmentSnapshot,taskSnapshot:i.result.taskSnapshot,taskAuthoritative:i.result.taskAuthoritative},r)),i.result.taskSnapshot&&yE({workspaceId:r?.workspaceId,taskId:i.result.taskSnapshot.id,reason:"workflow-step",...l?{authoritativeTask:l}:{}}),i.result}async function AS(e,t,r){const n=await ni(`/api/taskforce/tasks/${encodeURIComponent(e)}/workflow`,{method:"POST",body:JSON.stringify(t)},r);if(!n.assignment)throw new Mc("The workflow assignment was not returned.");return n.assignment}async function Z7(e,t,r){const n=await ni(`/api/taskforce/tasks/${encodeURIComponent(e)}/workflow`,{method:"PUT",body:JSON.stringify(t)},r);if(!n.assignment)throw new Mc("The workflow assignment was not returned.");return n.assignment}async function J7(e,t){await ni(`/api/taskforce/tasks/${encodeURIComponent(e)}/workflow`,{method:"DELETE"},t)}async function qee(e){const t=await ni(`/api/taskforce/workflows/${encodeURIComponent(e)}`);if(!t.workflow)throw new Mc("Workflow details were not returned.");return t.workflow}async function Yee(e){const t=await ni("/api/taskforce/workflows",{method:"POST",body:JSON.stringify(e)});if(!t.workflow)throw new Mc("The new workflow was not returned.");return t.workflow}async function Zee(e,t){const r=await ni(`/api/taskforce/workflows/${encodeURIComponent(e)}/draft`,{method:"PUT",body:JSON.stringify(t)});if(!r.workflow)throw new Mc("The saved workflow draft was not returned.");return r.workflow}async function Jee(e){const t=await ni(`/api/taskforce/workflows/${encodeURIComponent(e)}/publish`,{method:"POST"});if(!t.workflow)throw new Mc("The published workflow was not returned.");return t.workflow}async function Qee(e){const t=await ni(`/api/taskforce/workflows/${encodeURIComponent(e)}/draft`,{method:"POST"});if(!t.workflow)throw new Mc("The new workflow draft was not returned.");return t.workflow}const gk="__none__";function Q7(e){return e.charAt(0).toUpperCase()+e.slice(1)}function X7({taskId:e,workspaceId:t,taskStatus:r,taskUpdatedAt:n,comments:s=[],assigneeOptions:i=[],currentActorId:l,apiBaseUrl:c,runtimeMode:d="local",disabled:f=!1,onActivatePendingWorkflow:p,onActiveOwnerChange:g}){const[h,y]=Y.useState([]),[k,b]=Y.useState(null),[C,S]=Y.useState(!0),[w,T]=Y.useState(!1),[E,x]=Y.useState(!1),[N,v]=Y.useState(!1),[V,_]=Y.useState(0),[j,F]=Y.useState(""),z=Y.useRef(0),M=Y.useRef(null),O=Y.useRef({taskId:e,revision:`${e}:${n||""}`}),Z=Y.useMemo(()=>({workspaceId:t,apiBaseUrl:c,runtimeMode:d}),[c,d,t]);Y.useEffect(()=>{const pe=++z.current;return S(!0),T(!1),x(!1),F(""),y([]),b(null),v(!1),_(0),M.current=null,Promise.allSettled([K7(Z),bh(e,Z)]).then(([le,Ce])=>{pe===z.current&&(le.status==="fulfilled"&&y(le.value.filter(P=>P.template.status==="active"&&!!P.latestPublishedVersion)),Ce.status==="fulfilled"&&b(Ce.value),Ce.status==="rejected"?F(String(Ce.reason?.message||"Unable to load workflow assignment.")):!Ce.value&&le.status==="rejected"&&F(String(le.reason?.message||"Unable to load workflows.")),S(!1))}),()=>{z.current+=1}},[Z,e]);const U=k?.execution.taskId===e?k:null,ve=U?["pending","running","paused"].includes(U.execution.status):!1,te=ve?U:null,ce=U&&!h.some(({template:pe})=>pe.id===U.template.id)?[{template:U.template,draftVersionId:null,latestPublishedVersion:{id:U.version.id,versionNumber:U.version.versionNumber,publishedAt:U.version.publishedAt}},...h]:h,Le=[...!U||ve?[{value:gk,label:"None"}]:[],...ce.map(({template:pe})=>({value:pe.id,label:pe.name}))],Ie=te?.execution.status==="pending",Ye=!f&&!C&&!w&&(!te||Ie),ge=U?.template.id||gk,he=Y.useMemo(()=>[...U?.steps||[]].sort((pe,le)=>pe.position-le.position),[U?.steps]),Ae=U?.execution.currentStepId&&he.find(pe=>pe.id===U.execution.currentStepId)||null,ye=U?.execution.currentStepId?he.findIndex(pe=>pe.id===U.execution.currentStepId):-1,Ne=U?.execution.status==="completed",ae=Y.useMemo(()=>new Set((U?.events||[]).filter(pe=>pe.eventType==="step-completed"&&pe.stepId).map(pe=>pe.stepId)),[U?.events]),q=te?.execution.status==="pending"?(he.find(pe=>pe.isRequired)||he[0])?.id:null,W=`task-workflow-execution-${e}`,K=C?"Loading...":j&&!U?"Unavailable":U?Q7(U.execution.status):"Not assigned",Re=U?.version.versionNumber?`V${U.version.versionNumber}`:null,we=K.replace(/\.+$/,""),ie=U?`Status: ${we}${Re?`, ${Re}`:""}. ${N?"Hide":"View"} workflow execution.`:`Status: ${we}.`,Q=!f&&!E&&te?.execution.status==="running"&&Ae?.ownerType==="user"&&!!l&&Ae.ownerId===l,H=Ne&&h.find(({template:pe})=>pe.id===U?.template.id)||null,se=!!(!f&&!w&&H?.latestPublishedVersion);Y.useEffect(()=>{const pe=te?.execution.id||null;if(!pe||te?.execution.status!=="pending"||r!=="in-progress"||!p||M.current===pe)return;M.current=pe;const le=z.current;T(!0),F(""),Promise.resolve(p()).then(async()=>{const Ce=await bh(e,Z);if(le!==z.current)return;if(Ce?.execution.status==="pending")throw new Error("Workflow is still pending. Retry to start it.");const P=Ce?.steps.find(ee=>ee.id===Ce.execution.currentStepId);P?.ownerId&&g?.(P.ownerId),b(Ce)}).catch(Ce=>{le===z.current&&(M.current=null,F(String(Ce?.message||"Unable to start workflow.")))}).finally(()=>{le===z.current&&T(!1)})},[V,te,p,g,Z,e,r]);const Pe=Y.useCallback(pe=>pe?Of(pe,i):"Unassigned",[i]);Y.useEffect(()=>{O.current.taskId!==e&&(O.current={taskId:e,revision:`${e}:${n||""}`})},[e,n]),Y.useEffect(()=>{const pe=`${e}:${n||""}`;if(pe===O.current.revision||r!=="in-progress"||!Ie)return;O.current={taskId:e,revision:pe};const le=z.current;bh(e,Z).then(Ce=>{le===z.current&&b(Ce)}).catch(Ce=>{le===z.current&&F(String(Ce?.message||"Unable to refresh workflow assignment."))})},[Ie,Z,e,r,n]),Y.useEffect(()=>{if(typeof window>"u")return;const pe=le=>{const Ce=le.detail;if(Ce?.reason!=="workflow-step")return;const P=String(Ce.workspaceId||"").trim(),ee=String(t||"").trim();if(ee&&P!==ee||String(Ce.taskId||"").trim()!==e)return;const _e=++z.current;bh(e,Z).then(ke=>{_e===z.current&&(b(ke),F(""))}).catch(ke=>{_e===z.current&&F(String(ke?.message||"Unable to refresh workflow assignment."))})};return window.addEventListener(Pd,pe),()=>window.removeEventListener(Pd,pe)},[Z,e,t]);const ue=async pe=>{const le=String(pe);if(!Ye||le===ge)return;const Ce=z.current;T(!0),F("");try{if(le===gk){if(await J7(e,Z),Ce!==z.current)return;b(null);return}const P=h.find(({template:ke})=>ke.id===le),ee=P?.latestPublishedVersion;if(!P||!ee)return;const Se={workflowTemplateId:P.template.id,workflowVersionId:ee.id},_e=te?await Z7(e,Se,Z):await AS(e,Se,Z);if(Ce!==z.current)return;b(_e)}catch(P){if(Ce!==z.current)return;F(String(P?.message||"Unable to assign workflow."))}finally{Ce===z.current&&T(!1)}},ne=async()=>{if(!te||!Q)return;const pe=[...te.events||[]].reverse().find(P=>P.eventType==="step-started"&&P.stepId===Ae?.id)?.createdAt||te.execution.startedAt||te.execution.createdAt,le=Ae?.requiresCommentEvidence&&[...s].reverse().find(P=>P.author===l&&P.text.trim().length>0&&Date.parse(P.timestamp)>=Date.parse(pe))||null;if(Ae?.requiresCommentEvidence&&!le){F("Add a task comment for this workflow step before completing it.");return}const Ce=z.current;x(!0),F("");try{const P=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2)}`,ee=await Y7(te.execution.id,P,Z,le?.id,Ae?.id);if(Ce!==z.current)return;b(Se=>Se&&{...Se,execution:ee.execution,events:ee.events})}catch(P){if(Ce!==z.current)return;F(String(P?.message||"Unable to complete workflow step."))}finally{Ce===z.current&&x(!1)}},Me=async()=>{const pe=H?.latestPublishedVersion;if(!se||!H||!pe)return;const le=z.current;T(!0),F("");try{const Ce=await AS(e,{workflowTemplateId:H.template.id,workflowVersionId:pe.id},Z);if(le!==z.current)return;b(Ce)}catch(Ce){if(le!==z.current)return;F(String(Ce?.message||"Unable to run workflow again."))}finally{le===z.current&&T(!1)}};return a.jsxs("div",{className:`${R.field} ${gt.compactMetaField} ${gt.workflowAssignmentField}`,children:[a.jsxs("div",{className:gt.workflowAssignmentLabels,children:[a.jsx("label",{id:"task-workflow-label",className:R.label,children:"Workflow"}),a.jsx("span",{id:"task-workflow-status-label",className:R.label,children:"Status"})]}),a.jsxs("div",{className:gt.workflowAssignmentControls,children:[a.jsx(ai,{value:ge,options:Le,onChange:pe=>{ue(pe)},placeholder:C?"Loading workflows...":"None",ariaLabelledBy:"task-workflow-label",disabled:!Ye||Le.length===1&&!te,portalPanel:!0,panelMinWidth:280,panelAlign:"start",className:gt.workflowAssignmentSelector}),a.jsxs("button",{type:"button",className:gt.workflowExecutionToggle,onClick:()=>v(pe=>!pe),"aria-expanded":U?N:void 0,"aria-controls":U?W:void 0,"aria-label":ie,disabled:!U,children:[a.jsxs("span",{children:[K,Re?a.jsxs("span",{className:gt.workflowExecutionVersion,children:[" · ",Re]}):null]}),U?N?a.jsx(Nd,{size:13,"aria-hidden":"true"}):a.jsx(xd,{size:13,"aria-hidden":"true"}):null]})]}),U&&N?a.jsxs("section",{id:W,className:gt.workflowExecutionPanel,"aria-label":"Workflow execution",children:[a.jsxs("div",{className:gt.workflowExecutionHeader,children:[a.jsxs("div",{children:[a.jsx("span",{className:gt.workflowExecutionEyebrow,children:"Workflow execution"}),a.jsx("strong",{children:U.version.name||U.template.name})]}),Ne&&H?a.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>{Me()},disabled:!se,children:[w?a.jsx(za,{size:14,className:gt.workflowExecutionSpinner,"aria-hidden":"true"}):a.jsx(bi,{size:14,"aria-hidden":"true"}),"Run again"]}):null]}),a.jsxs("dl",{className:gt.workflowExecutionSummary,children:[a.jsxs("div",{children:[a.jsx("dt",{children:"Current step"}),a.jsx("dd",{children:Ne?"Completed":Ae?.name||(U.execution.status==="pending"?"Not started":"Not available")})]}),a.jsxs("div",{children:[a.jsx("dt",{children:"Owner"}),a.jsx("dd",{children:!Ne&&Ae?Pe(Ae.ownerId):"Unassigned"})]}),a.jsxs("div",{children:[a.jsx("dt",{children:"Version"}),a.jsx("dd",{children:U.version.versionNumber?`V${U.version.versionNumber}`:"Published"})]})]}),a.jsx("ol",{className:`${gt.workflowExecutionSteps} tf-scrollbar`,children:he.map((pe,le)=>{const Ce=ae.has(pe.id),P=!Ne&&pe.id===U.execution.currentStepId,ee=!Ce&&!P&&ye>=0&&le<ye,Se=[Ce?gt.workflowExecutionStepCompleted:"",P?gt.workflowExecutionStepCurrent:""].filter(Boolean).join(" ")||void 0;return a.jsxs("li",{className:Se,"aria-current":P?"step":void 0,children:[a.jsx("span",{className:gt.workflowExecutionStepMarker,"aria-hidden":"true",children:Ce?a.jsx(QT,{size:16}):P?a.jsx(XT,{size:17}):a.jsx(e0,{size:15})}),a.jsxs("span",{className:gt.workflowExecutionStepBody,children:[a.jsxs("span",{className:gt.workflowExecutionStepTitle,children:[a.jsx("span",{children:le+1}),a.jsx("strong",{children:pe.name})]}),a.jsxs("span",{className:gt.workflowExecutionStepMeta,children:[Pe(pe.ownerId)," · ",pe.isRequired?"Required":"Optional"]})]}),a.jsx("span",{className:gt.workflowExecutionStepState,children:Ce?"Completed":ee?"Skipped":P&&(Q||E)?a.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>{ne()},disabled:E,children:[E?a.jsx(za,{size:14,className:gt.workflowExecutionSpinner,"aria-hidden":"true"}):a.jsx(Si,{size:14,"aria-hidden":"true"}),"Complete Step"]}):P?"Current":pe.id===q?"Starts here":"Upcoming"})]},pe.id)})}),he.length===0?a.jsx("p",{className:gt.workflowExecutionEmpty,children:"No steps are available for this workflow version."}):null]}):null,j?a.jsxs("span",{className:gt.workflowAssignmentError,role:"alert",children:[j,Ie&&r==="in-progress"&&p?a.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>_(pe=>pe+1),disabled:w,children:"Retry"}):null]}):null]})}const eH="_header_g17dz_1",tH="_title_g17dz_15",rH="_actions_g17dz_24",aH="_toggle_g17dz_30",Sh={header:eH,title:tH,actions:rH,toggle:aH};function _f({label:e,count:t,showZeroCount:r=!1,actions:n,expanded:s,expandedTitle:i,collapsedTitle:l,onToggle:c,className:d="",controlsId:f}){const p=typeof t=="number"&&(r||t>0),g=s?Nd:xd;return a.jsxs("div",{className:`${Sh.header} ${d}`.trim(),children:[a.jsxs("span",{className:Sh.title,children:[e,p?` (${t})`:""]}),n?a.jsx("span",{className:Sh.actions,children:n}):null,a.jsx("button",{type:"button",className:`tf-control-icon ${Sh.toggle}`.trim(),onClick:c,"aria-expanded":s,"aria-controls":f,"aria-label":s?i:l,title:s?i:l,children:a.jsx(g,{size:14,"aria-hidden":"true"})})]})}const nH="system:unverified-comment-import",FI="Imported comment",UI="This comment was recovered during synchronization, but its author could not be verified.";function zI(e){return String(e||"").trim().toLowerCase()===nH}const yk=280,sH=48,oH=Y.lazy(()=>Lo(()=>import("./EntityActivityTimeline-BtSTq0ON.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.EntityActivityTimeline}))),iH=Y.lazy(()=>Lo(()=>import("./TaskContextUpload-CB3ol0sN.js"),__vite__mapDeps([7,1,8,2,3,4,5,9])).then(e=>({default:e.TaskContextUpload})));function cH({count:e}){const t=Math.max(2,Math.min(e||3,4));return a.jsx("div",{className:`${gt.commentThread} ${gt.activityLoadingThread}`.trim(),"aria-busy":"true","aria-live":"polite","aria-label":"Loading activity",children:Array.from({length:t},(r,n)=>a.jsxs("div",{className:gt.activitySkeletonItem,children:[a.jsx("div",{className:gt.activitySkeletonMeta}),a.jsx("div",{className:gt.activitySkeletonBody})]},n))})}function lH({id:e,item:t,onToggle:r,onRemove:n}){const{attributes:s,listeners:i,setNodeRef:l,transform:c,transition:d,isDragging:f}=Cv({id:e}),p={transform:Sg.Transform.toString(c),transition:d,opacity:f?.88:1};return a.jsxs("div",{ref:l,style:p,className:`${gt.checklistRow} ${f?gt.checklistRowDragging:""}`.trim(),children:[a.jsx("button",{type:"button",className:gt.checklistHandleBtn,title:"Reorder checklist item","aria-label":"Reorder checklist item",...s,...i,children:a.jsx(yv,{size:14})}),a.jsx("button",{type:"button",className:`${gt.checklistCheckboxBtn} ${t.isCompleted?gt.checklistCheckboxBtnChecked:""}`.trim(),onClick:r,title:t.isCompleted?"Mark incomplete":"Mark complete","aria-label":t.isCompleted?"Mark checklist item incomplete":"Mark checklist item complete",children:t.isCompleted?a.jsx(Si,{size:14,strokeWidth:2.1}):null}),a.jsx("span",{className:`${gt.checklistItemText} ${t.isCompleted?gt.checklistItemTextCompleted:""}`.trim(),children:t.title}),a.jsx("button",{type:"button",className:gt.checklistRemoveBtn,onClick:n,title:"Remove checklist item","aria-label":"Remove checklist item",children:a.jsx(Mo,{size:15,strokeWidth:1.9})})]})}function HI(e){const{editingTaskId:t,initialActivityEntryId:r,title:n,description:s,category:i,type:l,priority:c,complexity:d,manualComplexityEnabled:f=!1,assignee:p,scheduledDate:g,dueDate:h,checklistItems:y,comments:k,newCommentText:b,contextFiles:C,currentWorkspaceId:S,descriptionImageDraftId:w,currentActorId:T,apiBaseUrl:E,runtimeMode:x="local",showImageReviews:N=!1,descriptionFocused:v,showMarkdownHelp:V,checklistEnabled:_=!0,formTaxonomies:j,onTaxonomyChange:F,onOpenSettings:z,categories:M,types:O,priorities:Z,taxonomyDisplayLabels:U,assigneeOptions:ve,taxonomies:te,workstreams:ce=[],initiatives:Le=[],copiedId:Ie,onTitleChange:Ye,onTitleDraftChange:ge,onDescriptionChange:he,onDescriptionDraftChange:Ae,onCategoryChange:ye,onTypeChange:Ne,onPriorityChange:ae,onComplexityChange:q,onAssigneeChange:W,onScheduledDateChange:K,onDueDateChange:Re,onChecklistItemsChange:we,onNewCommentTextChange:ie,onDescriptionFocusedChange:Q,onShowMarkdownHelpChange:H,onSubmit:se,onAddComment:Pe,onDescriptionImageUploadStart:ue,onAddContextFile:ne,onRemoveContextFile:Me,onUpdateContextCaption:pe,onSetCardCover:le,cardCoverDisabled:Ce,onOpenContextImage:P,onCopyId:ee,onToggleInProgress:Se,onToggleReview:_e,onToggleComplete:ke,onToggleCancel:Ze,onSetStatus:st,onArchiveTask:at,onUnarchive:oe,taskReferences:We,currentTask:G,commentsEndRef:Be}=e,Xe=ge||Ye,ze=Ae||he,qe=hs(G),Te=Y.useRef(null),fe=Y.useRef(null),Ee=Y.useRef(s),$e=Y.useRef(t),rt=`${String(S||"").trim()}\0${t||""}`,kt=Y.useRef(rt),xe=Y.useRef(0);kt.current!==rt&&(kt.current=rt,xe.current+=1);const[St,jt]=Y.useState(!1),$=Y.useRef(null),[Ke,Qe]=Y.useState(null);Y.useLayoutEffect(()=>{const me=$e.current!==t;Te.current&&(me||document.activeElement!==Te.current)&&(Te.current.value=n),fe.current&&(me||document.activeElement!==fe.current)&&(fe.current.value=s,Ee.current=s),$e.current=t},[s,t,n]),Y.useEffect(()=>($.current=null,jt(!1),Qe(null),()=>{xe.current+=1}),[rt]);const Ge=Y.useMemo(()=>{if(!P)return;const me=new Map;return C.forEach(it=>{if(typeof it=="string")return;const mt=Uf(it);mt&&me.set(mt.toLowerCase(),it)}),{resolve:it=>me.get(it.toLowerCase())||null,activate:P}},[C,P]),At=Y.useMemo(()=>K2(te,j),[te,j]),Nt=Y.useMemo(()=>{const me=M.find(sr=>sr.value===Lu),it={value:Lu,label:me?.label||Ag,icon:me?.icon||"HelpCircle",color:me?.color||"var(--text-secondary)"},mt=M.find(sr=>sr.value===i),Ht=M.filter(sr=>!sr.disabled||sr.value===mt?.value).filter(sr=>sr.value!==Lu).map(sr=>({value:sr.value,label:sr.disabled?`${sr.label} (Legacy)`:sr.label,icon:sr.icon,color:sr.color}));return[it,...Ht]},[M,i]),Bt=Y.useMemo(()=>{const me=O.find(mt=>mt.value===l);return O.filter(mt=>mt.status!=="retired"||mt.value===me?.value).map(mt=>({value:mt.value,label:mt.status==="retired"?`${mt.label} (Retired)`:mt.label,icon:mt.icon||"Box",color:mt.color||"violet-500"}))},[O,l]),Qt=me=>me&&ug(me,{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit"})||null,Xt=Qt(G?.createdAt),nt=Qt(G?.updatedAt||G?.createdAt),Mt=Qt(G?.completedAt),ur=Y.useMemo(()=>{const me=new Date,it=me.getFullYear(),mt=String(me.getMonth()+1).padStart(2,"0"),ht=String(me.getDate()).padStart(2,"0");return`${it}-${mt}-${ht}`},[]),je=!!(h&&g&&h<g),ot=!!(h&&h<ur&&(!G||G.status!=="done"&&G.status!=="cancelled")),pt=y.filter(me=>me.isCompleted).length,[Ve,lt]=Y.useState(""),[It,wt]=Y.useState(!0),[$t,Yt]=Y.useState(!1),qt=Y.useRef(null),er=Y.useRef(null),_t=!!G?.isArchived,Dt=!!G?.isDeleted,Tt=_t||Dt,Xr=Y.useRef(null),Rr=Y.useRef(null),la=Y.useRef(null),sa=Y.useRef(null),ea=Y.useRef(null),Ur=Y.useRef(null),Ft=Y.useRef(null),ft=Y.useRef(!0),[Rt,_r]=Y.useState(!1),u=Y.useRef(new Map),Pt=Y.useRef(void 0),pr=Y.useRef(0),Yr=vv(Mf(wv,{activationConstraint:{distance:6}}));Y.useLayoutEffect(()=>{const me=Xr.current;if(!me)return;const it=Pt.current;if(it===t)return;it!==void 0&&u.current.set(it,pr.current);const mt=u.current.get(t)??0;me.scrollTop=mt,pr.current=mt,Pt.current=t},[t]),Y.useLayoutEffect(()=>{wt(!0)},[t]),Y.useEffect(()=>{$t&&qt.current?.focus()},[$t]),Y.useEffect(()=>{Yt(!1),lt("")},[t]),Y.useEffect(()=>{It||(Yt(!1),lt(""))},[It]);const tr=Y.useCallback(me=>{const it=me.currentTarget.scrollTop;pr.current=it,u.current.set(t,it)},[t]),$r=()=>{const me=Ve.trim();if(!me)return;const it=new Date().toISOString();we([...y,{id:`checklist-draft-${it}-${y.length}`,taskId:t||"",title:me,isCompleted:!1,order:y.length,createdAt:it,updatedAt:it}]),lt(""),Yt(!1),window.requestAnimationFrame(()=>er.current?.focus())},Lt=()=>{if($t){qt.current?.focus();return}It||wt(!0),Yt(!0)},zr=(me=!0)=>{Yt(!1),lt(""),me&&window.requestAnimationFrame(()=>er.current?.focus())},Ir=async(me,it,mt)=>{const ht=xe.current,Ht=t,sr=()=>xe.current===ht&&kt.current===rt;Qe(null);const wa=[];let fr=0,or=null;for(const Tr of me){if(Tr.size>10*1024*1024){fr+=1,or="Images must be 10 MB or smaller.";continue}try{const ha=await V7(Tr,{ownerType:"task",ownerId:Ht,workspaceId:S,...!Ht&&w?{draftUploadId:w,uploadPurpose:"task-description-draft"}:{}});if(!sr())return;const ba=Uf(ha);if(!ba)throw new Error("The uploaded image did not receive an image reference.");ne(ha),Fj({workspaceId:String(S||"").trim()||"default",ownerType:"task",ownerId:Ht,taskId:Ht,reason:"upload"}),wa.push(ba)}catch(ha){fr+=1,or=ha instanceof Error?ha.message:"The image could not be added."}}if(sr()){if(wa.length>0){const Tr=Ee.current,ha=Math.min(it,Tr.length),ba=Math.min(Math.max(mt,ha),Tr.length),nn=Tr.slice(0,ha),kr=Tr.slice(ba),ho=nn&&!/\s$/.test(nn)?`
3
+ `:"",wn=kr&&!/^\s/.test(kr)?`
4
+ `:"",Bn=`${ho}${wa.join(`
5
+ `)}${wn}`,Wn=`${nn}${Bn}${kr}`,Ta=nn.length+Bn.length;Ee.current=Wn,fe.current&&(fe.current.value=Wn),ze(Wn),he(Wn),window.requestAnimationFrame(()=>{fe.current?.focus(),fe.current?.setSelectionRange(Ta,Ta)})}if(fr>0){const Tr=wa.length>0?`${fr} image${fr===1?"":"s"} could not be added.`:or||(me.length===1?"The image could not be added.":"The images could not be added.");Qe(Tr)}}},Kt=(me,it,mt)=>{if(me.length===0||$.current)return $.current||Promise.resolve();jt(!0);const ht=Ir(me,it,mt);return $.current=ht,ue?.(ht),ht.then(()=>{$.current===ht&&($.current=null,jt(!1))},()=>{$.current===ht&&($.current=null,jt(!1))}),ht},Jr=me=>Array.from(me.items).filter(it=>it.kind==="file"&&/^(?:image\/(?:png|jpeg|webp))$/i.test(it.type)).map(it=>it.getAsFile()).filter(it=>!!it),Br=me=>Array.from(me.files).filter(it=>/^(?:image\/(?:png|jpeg|webp))$/i.test(it.type)),nr=me=>Array.from(me.items||[]).some(it=>it.kind==="file"&&/^(?:image\/(?:png|jpeg|webp))$/i.test(it.type))||Br(me).length>0,Zr=me=>{nr(me.dataTransfer)&&(me.preventDefault(),me.dataTransfer.dropEffect="copy")},He=Y.useCallback(me=>{const{active:it,over:mt}=me;if(!mt||it.id===mt.id)return;const ht=y.findIndex(fr=>fr.id===it.id),Ht=y.findIndex(fr=>fr.id===mt.id);if(ht<0||Ht<0)return;const sr=new Date().toISOString(),wa=gA(y,ht,Ht).map((fr,or)=>({...fr,order:or,updatedAt:sr}));we(wa)},[y,we]),Ca=me=>{const it=String(me||"").trim(),mt=me.trim().replace(/^ai-profile-/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ");return!mt||mt==="ai"||it.toLowerCase().startsWith("ai-profile-")?"AI Agent":`AI Agent - ${mt.split(" ").map(Ht=>Ht.charAt(0).toUpperCase()+Ht.slice(1)).join(" ")}`},da=BA(ve,p),ir=Y.useMemo(()=>new Map(da.map(me=>[String(me.value),me])),[da]),ut=Y.useMemo(()=>{const me=[G?.assigneeActor,G?.createdByActor].filter(Boolean);return new Map(me.map(it=>[String(it.id),it]))},[G?.assigneeActor,G?.createdByActor]),ka=Y.useMemo(()=>new Map(ce.map(me=>[me.id,zu(me)||me.id])),[ce]),Wt=Y.useMemo(()=>new Map(Le.map(me=>[me.id,KC(me)||me.id])),[Le]),rr=Y.useMemo(()=>iw({activity:G?.activity,comments:k}),[k,G?.activity]),oa=(me,it)=>{const mt=String(it||"").trim();if(mt){if(me==="assignee")return Of(mt,da);if(me==="workstreamId")return ka.get(mt);if(me==="initiativeId")return Wt.get(mt)}},Mr=Y.useCallback((me,it,mt)=>{if(mt&&mt.trim())return mt.trim();const ht=String(me||"").trim();if(!ht)return it==="ai"?"AI Agent":bt("taskForm.you");const Ht=ut.get(ht);if(Ht?.label)return Ht.label;const sr=ir.get(ht)||ir.get(ht.toLowerCase());return sr?.label?sr.label:it==="ai"?Ca(ht):Of(ht,da)||ht},[ut,ir,Ca,da]),vn=Y.useCallback(({actorId:me,actorType:it,actorProfile:mt,fallbackKind:ht})=>{const Ht=String(me||"").trim();if(zI(Ht))return{kind:"system",label:FI,ActorIcon:oA,description:UI};const sr=Ht.toLowerCase(),wa=ut.get(Ht),fr=ir.get(Ht)||ir.get(sr),or=mt||wa||fr||null,Tr=it==="system"?"system":it==="ai"||or?.kind==="ai"?"agent":it==="human"||or?.kind==="human"?"member":fr?.kind==="agent"?"agent":fr?.kind==="member"?"member":ht||(sr===""||sr==="user"||sr==="human"?"member":"agent"),ha=Tr==="system"?"System":Mr(Ht,Tr==="agent"?"ai":"human",or?.label||null),ba=or?.color,nn=String(or?.icon||(Tr==="agent"?"Bot":Tr==="member"?"User":"ClipboardList")),kr=Hu[nn]||(Tr==="agent"?yd:Tr==="member"?Du:iA);return{kind:Tr,label:ha,color:ba,ActorIcon:kr,isCurrentActorHint:Tr==="member"&&(sr===""||sr==="user"||sr==="human")}},[ut,ir,Mr]),En=Y.useMemo(()=>{const me=rr[rr.length-1];if(!me)return null;if(me.type==="comment"){const mt=me.comment;return Mr(mt.author,mt.actor?.kind==="ai"?"ai":mt.actor?.kind==="human"?"human":null,mt.actor?.label||null)}const it=me.event;return Mr(it.actor,it.actorType,it.actorProfile?.label||null)},[Mr,rr]),Ga=Y.useMemo(()=>{if(!G?.completedAt)return null;for(const it of rr){if(it.type!=="event")continue;const mt=it.event,ht=mt.details?.changes?.status?.to;if(ht==="done"||ht==="cancelled")return Mr(mt.actor,mt.actorType,mt.actorProfile?.label||null)}return En},[G?.completedAt,En,Mr,rr]),Hr=G?.createdByActor?.label||Mr(G?.createdBy||null,G?.createdByActor?.kind==="ai"?"ai":G?.createdByActor?.kind==="human"?"human":null,G?.createdByActor?.label||null),Na=En,ta=rr.length,ua=rr.filter(me=>me.type==="comment").length,Qr=rr[0]?.id||null,br=rr[ta-1]?.id||null,yr=String(r||"").trim(),Gr=t&&yr?`${t}\0${yr}`:null,Kr=Y.useCallback(me=>({taskId:t,count:ta,firstItemId:Qr,lastItemId:br,scrollHeight:me.scrollHeight,scrollTop:me.scrollTop}),[ta,t,Qr,br]),dt=Y.useCallback(()=>{const me=Rr.current;me&&(me.scrollTop=me.scrollHeight,ft.current=!0,_r(!1),Ft.current=Kr(me))},[Kr]),Ma=Y.useCallback(()=>{const me=Rr.current,it=la.current;return!me||!it||!Gr||sa.current===Gr?!1:(it.scrollIntoView?.({block:"center",inline:"nearest"}),it.focus({preventScroll:!0}),ft.current=!1,_r(!1),sa.current=Gr,Ft.current=Kr(me),!0)},[Gr,Kr]),Zt=Y.useCallback(me=>{la.current=me,me&&Ma()},[Ma]),Sr=Y.useCallback(me=>{Ur.current?.(me.currentTarget)},[]),va=Y.useCallback(me=>{const mt=me.scrollHeight-me.scrollTop-me.clientHeight<=sH;ft.current=mt,mt&&_r(!1),Ft.current=Kr(me)},[Kr]);Y.useLayoutEffect(()=>{Ur.current=va},[va]);const Ya=Y.useCallback(me=>{if(ea.current?.disconnect(),ea.current=null,Rr.current=me,!!me&&(Gr&&sa.current!==Gr?ft.current=!1:(me.scrollTop=me.scrollHeight,ft.current=!0),_r(!1),typeof ResizeObserver<"u")){const it=new ResizeObserver(()=>{const mt=Rr.current;mt&&Ur.current?.(mt)});it.observe(me),ea.current=it}},[Gr,t]);Y.useLayoutEffect(()=>{sa.current=null},[Gr]),Y.useLayoutEffect(()=>{if(!t)return;const me=Rr.current;if(!me)return;const it=Ft.current,mt=it?.taskId!==t,ht=!!(it&&ta>it.count),Ht=!!(it&&ht&&it.lastItemId===br&&it.firstItemId!==Qr);if(Gr&&Ma()){Ft.current=Kr(me);return}mt||ft.current?dt():Ht&&it?me.scrollTop=it.scrollTop+(me.scrollHeight-it.scrollHeight):ht&&_r(!0),Ft.current=Kr(me);const sr=window.requestAnimationFrame(()=>{mt||ft.current?dt():Ft.current=Kr(me)});return()=>window.cancelAnimationFrame(sr)},[ta,Gr,Kr,t,Qr,br,dt,Ma]);const Ar=Y.useCallback(()=>{dt(),Pe()},[Pe,dt]),ma=a.jsxs("aside",{className:gt.activitySidebar,"aria-label":bt("taskForm.commentsSectionTitle"),children:[a.jsx("div",{className:gt.activitySidebarHeader,children:a.jsxs("h2",{className:gt.activitySidebarTitle,children:[bt("taskForm.commentsSectionTitle")," (",ua,")"]})}),a.jsxs("div",{className:`${gt.commentPanel} ${gt.activitySidebarPanel} tf-surface-panel`.trim(),children:[a.jsxs("div",{className:gt.activityTimelineRegion,children:[a.jsx(Y.Suspense,{fallback:a.jsx(cH,{count:ta}),children:a.jsx(oH,{activity:G?.activity,comments:k,formatFieldValue:oa,resolveActorPresentation:vn,currentActorId:T,taskReferences:We,emptyMessage:bt(t?"taskForm.noComments":"taskForm.noActivity"),listClassName:gt.commentThread,emptyClassName:gt.emptyComments,listRef:Ya,endRef:Be,onScroll:Sr,targetEntryId:yr,targetEntryRef:Zt})}),Rt?a.jsx("div",{className:gt.newActivityNotice,role:"status","aria-live":"polite",children:a.jsxs("button",{type:"button",className:gt.newActivityButton,onClick:dt,"aria-label":bt("taskForm.newActivityAriaLabel"),children:[a.jsx(gv,{size:14,"aria-hidden":"true"}),a.jsx("span",{children:bt("taskForm.newActivity")})]})}):null]}),a.jsxs("div",{className:gt.commentInputArea,children:[a.jsx("textarea",{className:`${gt.commentInput} tf-field-shell`,placeholder:t?bt("taskForm.commentPlaceholder"):"Comments become available after saving",value:b,onChange:me=>ie(me.target.value),disabled:!t||Tt,onKeyDown:me=>{me.key==="Enter"&&!me.shiftKey&&(me.preventDefault(),Ar())},rows:3}),a.jsx("button",{type:"button",className:`${gt.sendCommentBtn} tf-control-icon`,onClick:Ar,disabled:!t||Tt||!b.trim(),"aria-label":"Send comment",title:"Send comment",children:a.jsx(t0,{size:16,"aria-hidden":"true"})})]})]})]});return a.jsxs("form",{ref:Xr,onSubmit:se,onScroll:tr,className:`${R.form} ${R.appScrollbar} tf-scrollbar`,children:[Tt&&a.jsx("div",{className:`${gt.formNotice} tf-text-helper`,children:Dt?"Deleted tasks are read-only. Restore the task to make changes.":"Archived tasks are read-only. Unarchive the task to make changes."}),a.jsxs("div",{className:gt.formLayoutWithSidebar,children:[a.jsx("fieldset",{disabled:Tt,className:gt.formFieldsetReset,children:a.jsxs("div",{className:gt.formMainColumn,children:[a.jsxs("div",{className:R.field,children:[a.jsx("label",{className:R.label,children:"Title"}),a.jsx("input",{ref:Te,type:"text",defaultValue:n,onChange:me=>{const it=me.target.value;Xe(it)},onBlur:me=>{me.currentTarget.value!==n&&Ye(me.currentTarget.value)},placeholder:"What needs to be done?",className:R.input,required:!0,maxLength:255,autoFocus:!0})]}),a.jsxs("div",{className:`${R.field} ${gt.descriptionField}`,children:[a.jsxs("div",{className:R.labelRow,children:[a.jsx("label",{className:R.label,children:"Description"}),a.jsx("button",{type:"button",className:R.helpLink,onClick:()=>H(!V),title:"Markdown Help",tabIndex:-1,children:a.jsx(Td,{size:14})})]}),V&&a.jsxs("div",{className:gt.markdownHelp,children:[a.jsxs("div",{className:gt.helpHeader,children:[a.jsx("span",{children:"Markdown Guide"}),a.jsx("button",{onClick:()=>H(!1),className:gt.helpClose,children:a.jsx(Mo,{size:12})})]}),a.jsxs("div",{className:gt.helpGrid,children:[a.jsx("div",{children:a.jsx("code",{children:"**bold**"})}),a.jsx("div",{children:a.jsx("code",{children:"_italic_"})}),a.jsx("div",{children:a.jsx("code",{children:"- list"})}),a.jsx("div",{children:a.jsx("code",{children:"1. list"})}),a.jsx("div",{className:gt.helpGridItem,children:a.jsx("code",{children:"`inline code`"})}),a.jsxs("div",{className:gt.helpGridItem,children:[a.jsx("code",{children:"```"}),a.jsx("br",{}),a.jsx("code",{children:"code block"}),a.jsx("br",{}),a.jsx("code",{children:"```"})]}),a.jsx("div",{children:a.jsx("code",{children:"[link](url)"})})]})]}),v||!s?a.jsx("textarea",{ref:fe,className:`${R.textarea} ${gt.descriptionSurface}`,placeholder:"What needs to be done? (Markdown supported)",defaultValue:s,onChange:me=>{const it=me.target.value;Ee.current=it,ze(it)},onFocus:()=>Q(!0),onBlur:me=>{me.currentTarget.value!==s&&he(me.currentTarget.value),Q(!1)},onPaste:me=>{const it=Jr(me.clipboardData);if(it.length===0)return;me.preventDefault();const mt=me.currentTarget;Kt(it,mt.selectionStart,mt.selectionEnd)},onDragOver:Zr,onDrop:me=>{const it=Br(me.dataTransfer);if(it.length===0)return;me.preventDefault(),me.stopPropagation();const mt=me.currentTarget;Kt(it,mt.selectionStart,mt.selectionEnd)},rows:9,autoFocus:v}):a.jsx("div",{className:`${R.textarea} ${gt.descriptionSurface} ${gt.markdownPreview} ${gt.markdownPreviewContainer}`,onClick:()=>Q(!0),onDragOver:Zr,onDrop:me=>{const it=Br(me.dataTransfer);it.length!==0&&(me.preventDefault(),me.stopPropagation(),Q(!0),Kt(it,s.length,s.length))},children:a.jsx(Mg,{variant:"detail",taskReferences:We,imageReferences:Ge,children:s})}),St&&a.jsx("div",{className:gt.descriptionImageStatus,role:"status",children:"Adding image to Context…"}),Ke&&a.jsx("div",{className:gt.descriptionImageError,role:"alert",children:Ke})]}),a.jsxs("div",{className:gt.compactMetaSection,children:[a.jsxs("div",{className:gt.compactMetaGrid,children:[a.jsxs("div",{className:`${R.field} ${gt.compactMetaField}`,children:[a.jsx("label",{id:"category-label",className:R.label,children:U?.category||"Category"}),a.jsx(ai,{value:i,options:Nt,onChange:me=>ye(String(me)),required:!0,ariaLabelledBy:"category-label",portalPanel:!0,panelMinWidth:yk,panelAlign:"start"})]}),a.jsxs("div",{className:`${R.field} ${gt.compactMetaField}`,children:[a.jsx("label",{id:"type-label",className:R.label,children:U?.type||"Type"}),a.jsx(ai,{value:l,options:Bt,onChange:me=>Ne(String(me)),ariaLabelledBy:"type-label",portalPanel:!0,panelMinWidth:yk,panelAlign:"start"})]}),a.jsxs("div",{className:`${R.field} ${gt.compactMetaField}`,children:[a.jsx("label",{htmlFor:"task-form-scheduled-date",className:R.label,children:bt("taskForm.scheduledLabel")}),a.jsx("input",{id:"task-form-scheduled-date",type:"date",value:g,onChange:me=>K(me.target.value),className:`${R.input} ${R.taskFormDateInput}`})]}),a.jsxs("div",{className:`${R.field} ${gt.compactMetaField}`,children:[a.jsx("label",{id:"assignee-label",className:R.label,children:"Assigned To"}),a.jsx(ai,{value:p||"unassigned",options:da,onChange:me=>W(String(me)),ariaLabelledBy:"assignee-label",portalPanel:!0,panelMinWidth:yk,panelAlign:"start",searchable:!0,searchPlaceholder:"Search assignees...",noResultsText:"No assignees found.",renderOptionContent:me=>{const it=ir.get(String(me.value));return it?a.jsx(qu,{option:it}):me.label}})]}),a.jsx("div",{className:gt.compactMetaField,children:a.jsx(hk,{label:U?.priority||"Priority",options:Z,value:c,onChange:ae,type:"priority",showSelectedLabel:!1})}),a.jsxs("div",{className:`${R.field} ${gt.compactMetaField}`,children:[a.jsx("label",{htmlFor:"task-form-due-date",className:R.label,children:bt("taskForm.dueLabel")}),a.jsx("input",{id:"task-form-due-date",type:"date",value:h,onChange:me=>Re(me.target.value),className:`${R.input} ${R.taskFormDateInput}`}),je&&a.jsx("span",{className:`${gt.taskFormDateWarning} ${gt.compactMetaFieldHint}`,children:bt("taskForm.dueBeforeScheduled")}),ot&&a.jsx("span",{className:`${gt.taskFormDateError} ${gt.compactMetaFieldHint}`,children:bt("taskForm.overdue")})]}),f&&a.jsx("div",{className:gt.compactMetaField,children:a.jsx(hk,{label:"Complexity",options:[{value:1,label:"Tiny",color:"#10b981",icon:"Gauge"},{value:2,label:"Low",color:"#14b8a6",icon:"Gauge"},{value:3,label:"Medium",color:"#3b82f6",icon:"Gauge"},{value:4,label:"High",color:"#8b5cf6",icon:"Gauge"},{value:5,label:"Epic",color:"#d946ef",icon:"Gauge"}],value:d,onChange:q,type:"general"})})]}),t&&a.jsx(X7,{taskId:t,workspaceId:S,taskStatus:G?.status,taskUpdatedAt:G?.updatedAt,comments:k,assigneeOptions:da,currentActorId:T,apiBaseUrl:E,runtimeMode:x,disabled:!!(G?.isArchived||G?.isDeleted),onActivatePendingWorkflow:G&&st?()=>st(G,"in-progress",{allowSameStatus:!0}):void 0,onActiveOwnerChange:W})]}),a.jsxs("div",{className:gt.sectionBlock,children:[At.length>0&&a.jsx("div",{className:gt.taxonomyFieldsGrid,children:At.map(me=>{const it=j[me.id],mt=Array.isArray(it)?it.map(Ht=>String(Ht)):it!=null&&it!==""?[String(it)]:[],ht=me.options.filter(Ht=>Ht.status!=="retired"||mt.includes(String(Ht.value)));return a.jsxs("div",{className:R.field,children:[a.jsx("label",{className:R.label,children:me.label}),me.description&&a.jsx("div",{className:`${gt.settingsHint} tf-text-helper`,children:me.description}),me.widgetType==="level"?a.jsx(hk,{label:me.label,options:ht.map(Ht=>({...Ht,label:Ht.status==="retired"?`${Ht.label} (Retired)`:Ht.label})),value:j[me.id]||"",onChange:Ht=>F(me.id,Ht),type:"general",hideLabel:!0}):me.multiSelect?a.jsx("div",{className:`${R.dropdownList} ${gt.softSectionSurface}`,children:ht.map(Ht=>{const sr=String(Ht.value),wa=mt.includes(sr);return a.jsxs("button",{type:"button",className:`${gt.specialistChip} ${wa?gt.specialistChipActive:""}`,onClick:()=>{const fr=wa?mt.filter(or=>or!==sr):[...mt,sr];F(me.id,fr)},title:wa?"Click to remove":"Click to add",children:[wa&&a.jsx(Si,{size:12}),Ht.status==="retired"?`${Ht.label} (Retired)`:Ht.label]},sr)})}):a.jsxs("div",{className:R.fieldIconWrapper,style:{"--field-color":"var(--text-primary)","--field-border":"rgba(255, 255, 255, 0.1)","--field-bg":"rgba(255, 255, 255, 0.02)"},children:[(()=>{const Ht=me.options.find(fr=>String(fr.value)===String(j[me.id])),sr=Ht?.icon&&Gs[Ht.icon]?Gs[Ht.icon]:Td,wa=Ht?.color||"var(--text-secondary)";return a.jsx("div",{className:R.fieldIcon,style:{color:rn(wa)},children:a.jsx(sr,{size:16})})})(),a.jsxs("select",{value:j[me.id]||"",onChange:Ht=>F(me.id,Ht.target.value),className:`${R.select} ${R.field_dynamic}`,required:me.isRequired,children:[a.jsxs("option",{value:"",children:["Select ",me.label,"..."]}),ht.map(Ht=>a.jsx("option",{value:Ht.value,children:Ht.status==="retired"?`${Ht.label} (Retired)`:Ht.label},Ht.value))]})]})]},me.id)})}),_&&a.jsxs("div",{className:`${R.specialistSection} ${At.length===0?gt.specialistSectionWithoutTaxonomies:""}`.trim(),children:[a.jsx(_f,{label:`Checklist${y.length>0?` (${pt}/${y.length})`:""}`,expanded:It,expandedTitle:"Hide checklist",collapsedTitle:"Show checklist",onToggle:()=>{const me=!It;wt(me),me||zr(!1)},actions:a.jsx("div",{className:R.contextMenuControl,children:a.jsx("button",{ref:er,type:"button",className:"tf-control-icon","aria-label":"Add checklist item",title:"Add checklist item","aria-expanded":$t,onClick:Lt,children:a.jsx(ri,{size:14,"aria-hidden":"true"})})})}),It&&($t||y.length>0)&&a.jsxs("div",{className:`${R.dropdownList} ${gt.stackedList} ${gt.stackedListSpaced}`,children:[$t&&a.jsxs("div",{className:`${R.pathInputGroup} ${gt.checklistInputGroup}`,children:[a.jsx("input",{ref:qt,type:"text",className:R.input,placeholder:"Add checklist item",value:Ve,onChange:me=>lt(me.target.value),onKeyDown:me=>{me.key==="Enter"&&(me.preventDefault(),me.stopPropagation(),$r()),me.key==="Escape"&&(me.preventDefault(),me.stopPropagation(),zr())}}),a.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:$r,disabled:!Ve.trim(),"aria-label":"Confirm checklist item",title:"Add checklist item",children:a.jsx(Si,{size:14,"aria-hidden":"true"})}),a.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",onClick:()=>zr(),"aria-label":"Cancel checklist item",title:"Cancel",children:a.jsx(Mo,{size:14,"aria-hidden":"true"})})]}),y.length>0&&a.jsx(bv,{sensors:Yr,collisionDetection:yA,onDragEnd:He,children:a.jsx(Sv,{items:y.map(me=>me.id),strategy:Av,children:y.map((me,it)=>a.jsx(lH,{id:me.id||`checklist-${it}`,item:me,onToggle:()=>{const mt=new Date().toISOString();we(y.map((ht,Ht)=>Ht===it?{...ht,isCompleted:!ht.isCompleted,updatedAt:mt}:ht))},onRemove:()=>we(y.filter((mt,ht)=>ht!==it).map((mt,ht)=>({...mt,order:ht})))},me.id||`checklist-${it}`))})})]})]})]}),a.jsxs("div",{children:[a.jsx(Y.Suspense,{fallback:null,children:a.jsx(iH,{taskId:t,taskReferenceLabel:qe,workspaceId:S,apiBaseUrl:E,showImageReviews:N&&!!G,contextFiles:C,onAddContextFile:ne,onRemoveContextFile:Me,onUpdateContextCaption:pe,cardCoverAssetId:G?.cardCoverAssetId,onSetCardCover:le,cardCoverDisabled:Ce})}),a.jsx("div",{className:`${gt.taskFormLifecycle} ${gt.taskFormMetaDivider}`,children:a.jsx("div",{className:gt.taskFormMetaGrid,children:G&&a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:gt.taskFormDateRow,children:[a.jsx("span",{className:gt.taskFormDateLabel,children:bt("taskForm.createdLabel")}),a.jsxs("span",{className:gt.taskFormMetaStack,children:[a.jsx("span",{className:gt.taskFormDateValue,children:Xt||bt("taskForm.emptyValue")}),a.jsx("span",{className:gt.taskFormMetaActor,children:Hr?`by ${Hr}`:bt("taskForm.emptyValue")})]})]}),a.jsxs("div",{className:gt.taskFormDateRow,children:[a.jsx("span",{className:gt.taskFormDateLabel,children:bt("taskForm.updatedLabel")}),a.jsxs("span",{className:gt.taskFormMetaStack,children:[a.jsx("span",{className:gt.taskFormDateValue,children:nt||bt("taskForm.emptyValue")}),a.jsx("span",{className:gt.taskFormMetaActor,children:Na?`by ${Na}`:bt("taskForm.emptyValue")})]})]}),a.jsxs("div",{className:gt.taskFormDateRow,children:[a.jsx("span",{className:gt.taskFormDateLabel,children:bt("taskForm.completedLabel")}),a.jsxs("span",{className:gt.taskFormMetaStack,children:[a.jsx("span",{className:gt.taskFormDateValue,children:Mt||bt("taskForm.emptyValue")}),a.jsx("span",{className:gt.taskFormMetaActor,children:Ga?`by ${Ga}`:bt("taskForm.emptyValue")})]})]})]})})})]})]})}),ma]})]})}function vf({ariaExpanded:e,ariaLabel:t,children:r,disabled:n=!1,onClick:s,title:i}){return a.jsx("button",{type:"button",className:`${R.referenceBadge} ${R.taskHierarchyActionBtn}`,onClick:s,disabled:n,title:i,"aria-label":t,"aria-expanded":e,children:r})}function GI({editingTaskId:e,loading:t,submitDisabled:r=!1,autoSaveState:n="idle",title:s,status:i="task",onStatusChange:l,showCreateSubmit:c=!0,handleSubmit:d,handleCopyId:f,copiedId:p,tasks:g,currentTask:h,currentTaskWorkstream:y,currentTaskInitiative:k,workstreams:b=[],onWorkstreamInputChange:C,onSetWorkstreamForCurrentTask:S,handleToggleInProgress:w,handleToggleReview:T,handleToggleComplete:E,handleToggleCancel:x,handleSetStatus:N,handleArchiveTask:v,handleUnarchiveTask:V,handleRestoreDeletedTask:_,handlePermanentlyDeleteDeletedTask:j,onAskAgent:F}){const z=h??(e&&g.find(ye=>ye.id===e)||null),M=!!z?.isArchived,O=!!z?.isDeleted,Z=Y.useMemo(()=>{if(!O||!z?.deletedExpiresAt)return"";const ye=new Date(z.deletedExpiresAt);return Number.isNaN(ye.getTime())?"":`Trash expires ${ye.toLocaleString()}`},[z?.deletedExpiresAt,O]),U=xv(z),ve=U.label||(U.isProvisional?"Pending":""),te=U.isProvisional,ce=!!U.label,Le=y?zu(y)||y.id:"",Ie=k?fs(k)||k.id:"",Ye=Y.useCallback(ye=>{C?.(zu(ye)||ye.id),e&&S?.(ye.id)},[e,S,C]),ge=Y.useCallback(()=>{C?.(""),e&&S?.(null)},[e,S,C]),he=y?a.jsx(vf,{onClick:ge,disabled:t||M||O,title:"Unlink task from workstream",ariaLabel:"Unlink task from workstream",children:a.jsx(Sf,{size:13})}):null,Ae=a.jsx("div",{className:R.taskHierarchyHeader,children:a.jsxs("div",{className:R.taskHierarchyBadgeRow,children:[k?a.jsx("span",{className:R.taskHierarchySegment,children:a.jsx(Ou,{copied:p===Ie,onClick:ye=>f(ye,Ie),disabled:t,title:k.title,ariaLabel:`Copy initiative reference ${Ie}: ${k.title}`,label:Ie})}):null,y?a.jsxs("span",{className:R.taskHierarchySegment,children:[k?a.jsx("span",{className:R.taskHierarchyDivider,children:"/"}):null,a.jsx(Ou,{copied:p===Le,onClick:ye=>f(ye,Le),disabled:t,title:y.title,ariaLabel:`Copy workstream reference ${Le}: ${y.title}`,label:Le})]}):a.jsx(BI,{workstreams:b,onSelect:Ye,disabled:t||M||O}),!ve&&he?a.jsxs("span",{className:R.taskHierarchySegment,children:[a.jsx("span",{className:R.taskHierarchyDivider,children:"/"}),he]}):null,ve?a.jsxs("span",{className:R.taskHierarchySegment,children:[y?a.jsx("span",{className:R.taskHierarchyDivider,children:"/"}):null,he,a.jsx(Ou,{copied:ce&&p===U.label,onClick:ye=>f(ye,U.label),disabled:t||!ce,title:te?"Temporary identifier — replaced after synchronization.":bt("actionHeader.copyTaskIdTitle"),ariaLabel:te?`Copy temporary task reference ${ve}`:void 0,label:ve,provisional:te})]}):null,Z?a.jsx("span",{className:R.taskHierarchyMeta,title:"Trash items are permanently deleted 90 days after deletion.",children:Z}):null]})});return a.jsxs("div",{className:R.stickyActionHeader,children:[Ae,e?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:R.taskSaveStatusCenter,children:a.jsx("div",{className:`${R.taskSaveStatus} ${n==="error"?R.taskSaveStatusError:""}`,"aria-live":"polite",children:n==="saving"?a.jsxs(a.Fragment,{children:[a.jsx(za,{size:14,className:R.spinner}),a.jsx("span",{children:"Saving…"})]}):n==="saved"?a.jsx("span",{children:"Saved"}):n==="error"?a.jsx("span",{children:"Save failed"}):null})}),a.jsxs("div",{className:R.editActionsGroup,children:[F&&z?a.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>F(z),disabled:t,title:"Ask a Taskforce Agent about this task","aria-label":"Ask a Taskforce Agent about this task",children:a.jsx(yd,{size:16})}):null,O&&z?.deletedRecordId?a.jsxs(a.Fragment,{children:[_&&a.jsx("button",{type:"button",className:R.actionBtn,onClick:()=>_(z.deletedRecordId||""),disabled:t,title:"Restore deleted task","aria-label":"Restore deleted task",children:a.jsx(bi,{size:16})}),j&&a.jsx("button",{type:"button",className:`${R.actionBtn} ${R.deleteBtn}`,onClick:()=>j(z.deletedRecordId||""),disabled:t,title:"Permanently delete deleted task","aria-label":"Permanently delete deleted task",children:a.jsx(Vf,{size:16})})]}):a.jsx(ig,{task:z,disabled:t,statusDisabled:t||M,archiveActionMode:M?"unarchive":"auto",onSetStatus:(ye,Ne)=>{if(N){N(ye,Ne);return}if(Ne==="in-progress"){w(ye);return}if(Ne==="review"){T(ye);return}if(Ne==="done"){E(ye);return}Ne==="cancelled"&&x(ye)},onArchiveTask:v,onUnarchiveTask:ye=>V?.(ye.id)})]})]}):a.jsxs(a.Fragment,{children:[a.jsx("div",{className:R.taskSaveStatusCenter}),a.jsxs("div",{className:R.editActionsGroup,children:[a.jsx(ig,{status:i,disabled:t,archiveActionMode:"none",onStatusChange:l}),c?a.jsxs("button",{type:"button",onClick:ye=>d(ye),disabled:t||r||!s.trim(),className:R.primaryUpdateBtn,title:bt("actionHeader.addTaskTitle"),children:[t?a.jsx(za,{size:16,className:R.spinner}):a.jsx(ri,{size:16}),bt("actionHeader.addTask")]}):null]})]})]})}function dH(e={x:0,y:0}){const[t,r]=o.useState(e),[n,s]=o.useState(!1),[i,l]=o.useState({x:0,y:0}),[c,d]=o.useState(0),f=o.useRef(null),p=o.useCallback(y=>{const k=y.target;if(!(k.closest("button")||k.closest("input")||k.closest("select")||k.closest("textarea")||k.closest('[role="button"]')||k.closest(".no-drag"))){if(f.current){const b=f.current.getBoundingClientRect();d(b.top-t.y)}s(!0),l({x:y.clientX-t.x,y:y.clientY-t.y})}},[t]),g=o.useCallback(y=>{if(n){let k=y.clientX-i.x,b=y.clientY-i.y;b<-c&&(b=-c),r({x:k,y:b})}},[n,i,c]),h=o.useCallback(()=>{s(!1)},[]);return o.useEffect(()=>(n?(window.addEventListener("mousemove",g),window.addEventListener("mouseup",h)):(window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",h)),()=>{window.removeEventListener("mousemove",g),window.removeEventListener("mouseup",h)}),[n,g,h]),{position:t,isDragging:n,handleMouseDown:p,modalRef:f,setPosition:r}}const Tf=[];let cf=0,kk="";function uH(e){return Tf.push(e),()=>{const t=Tf.lastIndexOf(e);t>=0&&Tf.splice(t,1)}}function pH(){return cf===0&&(kk=document.body.style.overflow,document.body.style.overflow="hidden"),cf+=1,()=>{cf=Math.max(0,cf-1),cf===0&&(document.body.style.overflow=kk,kk="")}}function Do({isOpen:e,onClose:t,title:r,children:n,footer:s,size:i="md",theme:l=Kh,className:c,overlayStyle:d,headerActions:f,draggable:p=!1,isSettings:g=!1,closeOnOverlayClick:h=!0,closeDisabled:y=!1}){const k=o.useRef(null),b=o.useRef(null),C=o.useRef(t),S=o.useRef(y),w=o.useRef(Symbol("taskforce-modal")),T=o.useId(),{position:E,isDragging:x,handleMouseDown:N,modalRef:v}=dH();if(C.current=t,S.current=y,o.useEffect(()=>{if(e)return uH(w.current)},[e]),o.useEffect(()=>{const _=j=>{if(Tf[Tf.length-1]!==w.current)return;if(j.key==="Escape"&&e&&!S.current){C.current();return}if(j.key!=="Tab"||!e||!v.current)return;const F=Array.from(v.current.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'));if(F.length===0){j.preventDefault(),v.current.focus();return}const z=F[0],M=F[F.length-1];j.shiftKey&&document.activeElement===z?(j.preventDefault(),M.focus()):!j.shiftKey&&document.activeElement===M&&(j.preventDefault(),z.focus())};return e&&(b.current=document.activeElement instanceof HTMLElement?document.activeElement:null,window.requestAnimationFrame(()=>{(v.current?.querySelector("[data-modal-initial-focus]")??v.current?.querySelector("button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled])")??v.current)?.focus()})),window.addEventListener("keydown",_),()=>{window.removeEventListener("keydown",_),b.current?.focus()}},[e,v]),o.useEffect(()=>{if(e)return pH()},[e]),!e)return null;const V={sm:dr.modalSizeSm,md:dr.modalSizeMd,mdWide:dr.modalSizeMdWide,lg:dr.modalSizeLg,xl:dr.modalSizeXl,full:dr.modalSizeFull};return tc.createPortal(a.jsx("div",{className:`${dr.overlay} ${c||""} ${dr.overlayHighZ}`,style:d,ref:k,onClick:_=>{h&&!y&&_.target===k.current&&t()},children:a.jsxs("div",{ref:v,className:`tf-surface-modal tf-modal-shell ${dr.modal} tf-scrollbar-scope ${V[i]} ${p?dr.draggableModal:""} ${g?dr.settingsViewModal:""}`,role:"dialog","aria-modal":"true","aria-labelledby":T,tabIndex:-1,"data-theme":l,style:{transform:p?`translate(${E.x}px, ${E.y}px)`:void 0,transition:x?"none":"transform 0.3s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.3s ease-out"},children:[a.jsxs("div",{className:`tf-modal-header ${p?dr.draggableHeader:""}`,onMouseDown:p?N:void 0,style:{cursor:p?x?"grabbing":"grab":"default"},children:[a.jsx("div",{className:"tf-modal-title",id:T,children:r}),a.jsxs("div",{className:dr.headerActions,children:[f,a.jsx("button",{className:"tf-control-icon",onClick:t,disabled:y,title:"Close","aria-label":"Close",children:a.jsx(Mo,{size:20})})]})]}),a.jsx("div",{className:dr.modalContent,children:n}),s&&a.jsx("div",{className:`${dr.formActions} ${dr.modalFooter}`,children:s})]})}),document.body)}const fH="_toolbar_1nqyq_1",mH="_masterSelection_1nqyq_13",hH="_selectedCount_1nqyq_32",gH="_actionButton_1nqyq_36",yH="_emptyButton_1nqyq_47",kH="_dialogBody_1nqyq_52",vH="_destinationSummary_1nqyq_62",wH="_hint_1nqyq_66",bH="_progress_1nqyq_70",SH="_failures_1nqyq_77",AH="_spinner_1nqyq_102",Ro={toolbar:fH,masterSelection:mH,selectedCount:hH,actionButton:gH,emptyButton:yH,dialogBody:kH,destinationSummary:vH,hint:wH,progress:bH,failures:SH,spinner:AH};function VI({theme:e,selectedRecords:t,matchingCount:r,allMatchingSelected:n,someMatchingSelected:s,fullTrashCount:i,onSelectAllMatching:l,onClearSelection:c,onRestore:d,onEmptyEntireTrash:f}){const p=o.useRef(null),[g,h]=o.useState(!1),[y,k]=o.useState("previous"),[b,C]=o.useState(!1),[S,w]=o.useState(null),T=o.useMemo(()=>t.filter(j=>j.taskSnapshot.isArchived===!0).length,[t]),E=t.length-T;o.useEffect(()=>{p.current&&(p.current.indeterminate=s)},[s]);const x=async()=>{if(t.length===0||b)return;C(!0),w({requested:t.length,completed:0,succeeded:[],failed:[]});const j=await d(t,y,w);w(j),C(!1),j.failed.length===0&&(h(!1),w(null))},N=j=>{k(j),w(null),h(!0)},v=y==="archive",V=v?t.length:T,_=v?0:E;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:Ro.toolbar,"aria-label":"Trash restore selection",children:[a.jsxs("label",{className:Ro.masterSelection,children:[a.jsx("input",{ref:p,type:"checkbox",checked:n,disabled:r===0||b,onChange:j=>{j.target.checked?l():c()},"aria-label":"Select all matching deleted tasks"}),a.jsxs("span",{className:Ro.selectedCount,children:[t.length," selected"]})]}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:c,disabled:t.length===0||b,"aria-label":"Clear selected tasks",title:"Clear selection",children:a.jsx(Mo,{size:15,"aria-hidden":"true"})}),a.jsxs("button",{type:"button",className:`tf-control-icon ${Ro.actionButton}`,onClick:()=>N("previous"),disabled:t.length===0||b,children:[a.jsx(bi,{size:15,"aria-hidden":"true"}),"Restore"]}),a.jsxs("button",{type:"button",className:`tf-control-icon ${Ro.actionButton}`,onClick:()=>N("archive"),disabled:t.length===0||b,title:"Restore selected tasks directly to Archive",children:[a.jsx(Sd,{size:15,"aria-hidden":"true"}),"Restore to archive"]}),f&&a.jsxs("button",{type:"button",className:`tf-control-icon ${Ro.actionButton} ${Ro.emptyButton}`,onClick:f,disabled:i===0||b,title:i>0?`Permanently delete all ${i} tasks in Trash; filters and selection do not limit this action.`:"Trash is already empty",children:[a.jsx(Vf,{size:14,"aria-hidden":"true"}),"Empty Trash"]})]}),a.jsx(Do,{isOpen:g,onClose:()=>{b||(h(!1),w(null))},closeDisabled:b,closeOnOverlayClick:!b,size:"sm",theme:e,title:v?"Restore selected tasks to Archive?":"Restore selected tasks?",footer:a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>{h(!1),w(null)},disabled:b,children:"Cancel"}),a.jsxs("button",{type:"button",className:"tf-button-primary tf-button-compact","data-modal-initial-focus":!0,onClick:()=>{x()},disabled:b||t.length===0,children:[b?a.jsx(za,{size:15,className:Ro.spinner}):v?a.jsx(Sd,{size:15}):a.jsx(bi,{size:15}),S?.failed.length?"Retry failed":v?"Restore to archive":"Restore"]})]}),children:a.jsxs("div",{className:Ro.dialogBody,children:[a.jsxs("p",{children:["Restore ",t.length," task",t.length===1?"":"s","?"]}),a.jsxs("p",{className:Ro.destinationSummary,children:[V," to Archived · ",_," to Active"]}),a.jsx("p",{className:Ro.hint,children:v?"Active tasks will be marked Done and restored directly to Archive. Cancelled tasks remain Cancelled.":"Each task returns to the lifecycle state it had before deletion."}),S&&a.jsxs("div",{className:Ro.progress,"aria-live":"polite",children:[a.jsxs("strong",{children:[S.completed," / ",S.requested," completed"]}),S.failed.length>0&&a.jsxs("div",{className:Ro.failures,children:[a.jsxs("p",{children:[S.failed.length," failed and remain selected:"]}),a.jsx("ul",{children:S.failed.slice(0,8).map(j=>a.jsxs("li",{children:[a.jsx("span",{children:j.title||j.taskId}),a.jsx("span",{children:j.message})]},j.deletedRecordId))}),S.failed.length>8&&a.jsxs("p",{children:["And ",S.failed.length-8," more."]})]})]})]})})]})}const CH="_topNoticeLayer_1yiif_1",IH="_taskNoticeLayer_1yiif_13",_H="_topNotice_1yiif_1",TH="_topNoticeMessage_1yiif_37",xH="_topNoticeSuccess_1yiif_43",RH="_topNoticeError_1yiif_44",jH="_topNoticeInfo_1yiif_45",PH="_topNoticeDismiss_1yiif_63",xc={topNoticeLayer:CH,taskNoticeLayer:IH,topNotice:_H,topNoticeMessage:TH,topNoticeSuccess:xH,topNoticeError:RH,topNoticeInfo:jH,topNoticeDismiss:PH};function pg({notice:e,onDismiss:t,placement:r="top"}){if(!e)return null;const n=e.tone==="error"?xc.topNoticeError:e.tone==="success"?xc.topNoticeSuccess:xc.topNoticeInfo,s=e.tone==="error"?"alert":"status",i=r==="task"?`${xc.topNoticeLayer} ${xc.taskNoticeLayer}`:xc.topNoticeLayer;return a.jsx("div",{className:i,children:a.jsxs("div",{className:`${xc.topNotice} ${n}`,role:s,"aria-live":e.tone==="error"?"assertive":"polite",children:[e.tone==="error"?a.jsx(Rd,{size:14}):e.tone==="success"?a.jsx(Si,{size:14}):a.jsx(r0,{size:14}),a.jsx("span",{className:xc.topNoticeMessage,children:e.message}),e.actionLabel&&e.onAction&&a.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:e.onAction,children:e.actionLabel}),t&&a.jsx("button",{type:"button",className:xc.topNoticeDismiss,onClick:t,"aria-label":"Dismiss notice",title:"Dismiss notice",children:a.jsx(Mo,{size:14})})]})})}const EH="D-";function NH(e){return Kf(EH,e)}const MH="_overlay_ey7rx_1",DH="_dialog_ey7rx_13",LH="_header_ey7rx_32",OH="_footer_ey7rx_33",BH="_titleGroup_ey7rx_53",WH="_secondaryActions_ey7rx_54",$H="_typeIcon_ey7rx_61",FH="_titleText_ey7rx_66",UH="_title_ey7rx_53",zH="_referenceBadge_ey7rx_79",HH="_content_ey7rx_83",GH="_image_ey7rx_93",VH="_pdf_ey7rx_100",KH="_textPreview_ey7rx_107",qH="_codePreview_ey7rx_108",YH="_message_ey7rx_125",ZH="_unavailable_ey7rx_126",JH="_secondaryLink_ey7rx_145",Pn={overlay:MH,dialog:DH,header:LH,footer:OH,titleGroup:BH,secondaryActions:WH,typeIcon:$H,titleText:FH,title:UH,referenceBadge:zH,content:HH,image:GH,pdf:VH,textPreview:KH,codePreview:qH,message:YH,unavailable:ZH,secondaryLink:JH},QH=/\.(?:md|markdown|txt|csv|json|js|ts|tsx|css|py|java|go|rs|sh)(?:[?#]|$)/i,XH=/\.(?:png|jpe?g|webp|gif)(?:[?#]|$)/i,eG=/\.pdf(?:[?#]|$)/i;function tG(e){return typeof e=="string"?e:e.path}function rG(e){return typeof e=="string"?e.split("/").pop()||"Context attachment":e.caption||e.displayName||e.originalFilename||e.fsPath?.split("/").pop()||e.path.split("/").pop()||"Context attachment"}function aG(e){return typeof e=="string"?[e]:[e.path,e.fsPath,e.originalFilename,e.displayName,e.caption].filter(t=>!!t)}function nG(e,t){const r=e.includes("?")?"&":"?";return`${e}${r}download=1&filename=${encodeURIComponent(t)}`}function sG(e){return e.ownerType!=="task"?e.attachment:typeof e.attachment=="string"?{path:e.attachment,taskId:e.ownerId||null}:{...e.attachment,taskId:e.ownerId||e.attachment.taskId||null}}function KI({theme:e}){const[t,r]=o.useState(null),[n,s]=o.useState(""),[i,l]=o.useState(!1),[c,d]=o.useState(null),[f,p]=o.useState(!1),g=o.useRef(null),h=o.useRef(null),y=o.useRef(null),k=o.useRef(0),b=o.useId();o.useEffect(()=>{const Z=U=>{const ve=U;ve.detail?.attachment&&(ve.preventDefault(),k.current+=1,y.current!==null&&(window.clearTimeout(y.current),y.current=null),p(!1),r(ve.detail))};return window.addEventListener(rv,Z),()=>window.removeEventListener(rv,Z)},[]),o.useEffect(()=>()=>{k.current+=1,y.current!==null&&window.clearTimeout(y.current)},[]),o.useEffect(()=>{if(!t)return;h.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const Z=U=>{if(U.key==="Escape"){U.preventDefault(),U.stopPropagation(),r(null);return}if(U.key!=="Tab"||!g.current)return;const ve=Array.from(g.current.querySelectorAll('button:not([disabled]), [href], iframe, [tabindex]:not([tabindex="-1"])'));if(ve.length===0){U.preventDefault(),g.current.focus();return}const te=ve[0],ce=ve[ve.length-1];U.shiftKey&&document.activeElement===te?(U.preventDefault(),ce.focus()):!U.shiftKey&&document.activeElement===ce&&(U.preventDefault(),te.focus())};return window.addEventListener("keydown",Z,!0),window.requestAnimationFrame(()=>g.current?.focus()),()=>{window.removeEventListener("keydown",Z,!0),h.current?.focus()}},[t]);const C=t?tG(t.attachment):"",S=t?aG(t.attachment):[],w=/^https?:\/\//i.test(C),T=S.some(Z=>XH.test(Z)),E=S.some(Z=>eG.test(Z)),x=S.some(Z=>QH.test(Z))&&!w,N=S.some(Z=>/\.(?:md|markdown)(?:[?#]|$)/i.test(Z));if(o.useEffect(()=>{if(s(""),d(null),!t||!x){l(!1);return}const Z=new AbortController;return l(!0),fetch(C,{signal:Z.signal,headers:t.workspaceId?{"x-taskforce-workspace-id":t.workspaceId}:void 0}).then(async U=>{if(!U.ok)throw new Error("Preview unavailable");s(await U.text())}).catch(U=>{U instanceof DOMException&&U.name==="AbortError"||d(U instanceof Error?U.message:"Preview unavailable")}).finally(()=>{Z.signal.aborted||l(!1)}),()=>Z.abort()},[x,C,t]),!t)return null;const v=rG(t.attachment),V=typeof t.attachment=="string"?null:t.attachment,_=T?Uf(V):NH(V),j=sG(t),F=T&&gI(j,{taskId:t.ownerType==="task"?t.ownerId:null,taskReferenceLabel:t.ownerReferenceLabel}),z=!T&&pI(j,typeof j=="string"?void 0:j.fsPath),M=async()=>{if(!_)return;const Z=k.current;try{await navigator.clipboard.writeText(_)}catch{if(k.current!==Z)return;const U=document.createElement("textarea");U.value=_,document.body.appendChild(U),U.select(),document.execCommand("copy"),U.remove()}k.current===Z&&(p(!0),y.current!==null&&window.clearTimeout(y.current),y.current=window.setTimeout(()=>{k.current===Z&&(p(!1),y.current=null)},1200))},O=()=>{if(F?av(j,{taskId:t.ownerType==="task"?t.ownerId:null,taskReferenceLabel:t.ownerReferenceLabel}):fI(j,typeof j=="string"?void 0:j.fsPath)){r(null);return}window.open(C,"_blank","noopener,noreferrer")};return tc.createPortal(a.jsx("div",{className:Pn.overlay,"data-theme":e,onMouseDown:Z=>{Z.target===Z.currentTarget&&r(null)},children:a.jsxs("div",{ref:g,className:Pn.dialog,role:"dialog","aria-modal":"true","aria-labelledby":b,tabIndex:-1,children:[a.jsxs("header",{className:Pn.header,children:[a.jsxs("div",{className:Pn.titleGroup,children:[a.jsx("span",{className:Pn.typeIcon,"aria-hidden":"true",children:T?a.jsx(cA,{size:16}):a.jsx(Ef,{size:16})}),a.jsxs("div",{className:Pn.titleText,children:[a.jsx("div",{className:Pn.title,id:b,children:v}),_&&a.jsx(nw,{label:_,copied:f,onClick:()=>{M()},title:v,ariaLabel:f?`Copied ${_}`:`Copy ${_}`,className:Pn.referenceBadge})]})]}),a.jsx("button",{type:"button",className:"tf-control-icon","aria-label":"Close preview",title:"Close preview",onClick:()=>r(null),children:a.jsx(Mo,{size:18})})]}),a.jsxs("div",{className:Pn.content,children:[T&&a.jsx("img",{className:Pn.image,src:C,alt:v}),E&&a.jsx("iframe",{className:Pn.pdf,src:C,title:`Preview ${v}`}),x&&i&&a.jsx("div",{className:Pn.message,children:"Loading preview…"}),x&&c&&a.jsx("div",{className:Pn.message,children:c}),x&&!i&&!c&&(N?a.jsx("div",{className:Pn.textPreview,children:a.jsx(Mg,{variant:"detail",children:n})}):a.jsx("pre",{className:Pn.codePreview,children:n})),!T&&!E&&!x&&a.jsxs("div",{className:Pn.unavailable,children:[a.jsx(Ef,{size:34,"aria-hidden":"true"}),a.jsx("strong",{children:"Preview unavailable"}),a.jsx("span",{children:"This file type can be opened or downloaded instead."})]})]}),a.jsxs("footer",{className:Pn.footer,children:[a.jsxs("div",{className:Pn.secondaryActions,children:[!w&&a.jsxs("a",{className:Pn.secondaryLink,href:nG(C,v),target:"_blank",rel:"noreferrer",children:[a.jsx(a0,{size:14})," Download"]}),(w||!F&&!z)&&a.jsxs("a",{className:Pn.secondaryLink,href:C,target:"_blank",rel:"noreferrer",children:[a.jsx(tb,{size:14})," Open original"]})]}),(F||z)&&a.jsxs("button",{type:"button",className:"tf-button-primary tf-button-compact",onClick:O,children:[F?a.jsx(n0,{size:14}):a.jsx(tb,{size:14}),F?"Open in Image Notes":"Open"]})]})]})}),document.body)}const oG=Y.lazy(()=>Lo(()=>import("./TaskSettings-g4ECKNOz.js"),__vite__mapDeps([10,1,2,3,4,5,11])).then(e=>({default:e.TaskSettings})));function iG(e){const{activeTab:t,setActiveTab:r,isOpen:n,setIsOpen:s,currentTheme:i,setCurrentTheme:l,saveSettings:c,pathSaved:d,keyShortcut:f,setKeyShortcut:p,jsonBackupEnabled:g,setJsonBackupEnabled:h,mcpHostRoot:y,setMcpHostRoot:k,settingsSection:b,setSettingsSection:C,projectRoot:S,projectName:w,mcpScriptPath:T,serverHostRoot:E,showFolderBrowser:x,setShowFolderBrowser:N,folders:v,files:V,currentBrowsePath:_,fetchFolders:j,browserTarget:F,setBrowserTarget:z,handleSelectPath:M,handleAddPath:O,handleRemovePath:Z,tasks:U,loadingTasks:ve,archivedTasks:te,deletedTasks:ce,activeCategories:Le,activeTypes:Ie,priorities:Ye,taxonomyDisplayLabels:ge,taxonomies:he,searchQuery:Ae,setSearchQuery:ye,filterCategories:Ne,setFilterCategories:ae,filterTypes:q,setFilterTypes:W,filterPriorities:K,setFilterPriorities:Re,filterStatus:we,setFilterStatus:ie,filterAssignees:Q,setFilterAssignees:H,assigneeOptions:se,filterTaxonomies:Pe,setFilterTaxonomies:ue,sortBy:ne,setSortBy:Me,sortOrder:pe,toggleSortOrder:le,showArchive:Ce,setShowArchive:P,taskScope:ee,setTaskScope:Se,clearFilters:_e,filteredTasks:ke,filteredArchive:Ze,groupedTasks:st,collapsedCategories:at,setCollapsedCategories:oe,handleEdit:We,handleDelete:G,handleCopyId:Be,handleUpdateTask:Xe,handleToggleComplete:ze,handleToggleCancel:qe,handleToggleInProgress:Te,handleToggleReview:fe,handleSetStatus:Ee,handleArchiveTask:$e,handleBulkArchive:rt,handleUnarchive:kt,handleRestoreDeletedTask:xe,handleRestoreSelectedDeletedTasks:St,handlePermanentlyDeleteDeletedTask:jt,handleEmptyDeletedTasks:$,fetchArchive:Ke,editingTaskId:Qe,loading:Ge,error:At,clearTaskError:Nt,title:Bt,setTitle:Qt,setTitleDraft:Xt,description:nt,setDescription:Mt,setDescriptionDraft:ur,checklistItems:je,setChecklistItems:ot,category:pt,setCategory:Ve,type:lt,setType:It,priority:wt,setPriority:$t,complexity:Yt,setComplexity:qt,status:er,setStatus:_t,manualComplexityEnabled:Dt,checklistDropdownEnabled:Tt,showTaskCardStatusLabel:Xr,assignee:Rr,setAssignee:la,scheduledDate:sa,setScheduledDate:ea,dueDate:Ur,setDueDate:Ft,workstreamInput:ft,setWorkstreamInput:Rt,formTaxonomies:_r,setFormTaxonomies:u,comments:Pt,newCommentText:pr,setNewCommentText:Yr,attachments:tr,setAttachments:$r,setAttachmentsDirty:Lt,descriptionImageUploadPending:zr,descriptionImageDraftId:Ir,registerDescriptionImageUpload:Kt,descriptionFocused:Jr,setDescriptionFocused:Br,showMarkdownHelp:nr,setShowMarkdownHelp:Zr,handleSubmit:He,resetForm:Ca,discardDescriptionImageDraft:da,handleAddComment:ir,handleSetWorkstreamForCurrentTask:ut,handleOpenTaskById:ka,autoSaveState:Wt,unsavedModalOpen:rr,setUnsavedModalOpen:oa,pendingNavigation:Mr,handleNavigation:vn,handleClose:En,scheduleWarningPrompt:Ga,confirmScheduleWarning:Hr,cancelScheduleWarning:Na,uiNotice:ta,pushNotice:ua,clearNotice:Qr,taskReturnTrail:br,clearReturnToParentTask:yr,returnToPreviousTask:Gr,copiedId:Kr,recentlyChangedTaskIds:dt,tasksScrollRef:Ma,setTasksScrollPos:Zt,currentTask:Sr,currentTaskWorkstream:va,currentTaskInitiative:Ya,handleUpdateCategory:Ar,handleRemoveCategory:ma,handleSaveCategory:me,handleUpdateCategoryIcon:it,handleUpdateCategoryColor:mt,handleSaveType:ht,handleRemoveType:Ht,handleUpdateTaxonomies:sr,handleUpdatePriorities:wa,pathValidation:fr,validatePaths:or,getCategoryPaths:Tr,commentsEndRef:ha,currentWorkspaceId:ba,authUserId:nn,settingsModel:kr,onHeaderMouseDown:ho,isDragging:wn}=e,Bn=oI(U,ka),Wn=o.useCallback(vt=>{if(vt.kind==="initiative"||vt.kind==="workstream"){const ga=vt.kind==="initiative"?e.initiatives.find(Za=>Za.referenceNumber===vt.referenceNumber):e.workstreams.find(Za=>Za.referenceNumber===vt.referenceNumber);if(!ga){ua(`${vt.token} could not be found.`,"error");return}const ia=QU({applicationBaseUrl:window.location.origin,workspaceId:String(ba||"default").trim()||"default",target:vt.kind,id:ga.id});if(!ia){ua(`${vt.token} could not be opened.`,"error");return}window.open(ia,"_blank","noopener,noreferrer");return}const hr=String(ba||"default").trim()||"default";cI(vt,{workspaceId:hr}).then(ga=>{Ff(ga,{ownerType:"task",ownerId:Sr?.id||null,ownerReferenceLabel:hs(Sr),workspaceId:hr})}).catch(()=>{ua(`${vt.token} could not be opened.`,"error")})},[Sr,ba,e.initiatives,e.workstreams,ua]),Ta=o.useMemo(()=>({...Bn,entityReferences:{resolve:_A,activate:Wn}}),[Wn,Bn]),Ms=o.useRef(null),[Vs,Ks]=Y.useState(0);o.useLayoutEffect(()=>{if(t==="tasks"&&Ma.current&&Vs>0){const vt=setTimeout(()=>{Ma.current&&(Ma.current.scrollTop=Vs)},50);return()=>clearTimeout(vt)}},[t,Vs,U]);const ys=vt=>{Me(vt)},$n=()=>{vn(()=>{if(t==="add"||t==="settings"){if(t==="add"&&Gr())return;t==="add"&&br.length>0&&yr(),t==="add"&&Ca(),r("tasks")}else e.onClose?e.onClose():En()})},Ia=()=>{oa(!1),t==="add"&&!Qe&&da(),Mr?(t==="add"&&Ca(),Mr()):r("tasks")},fn=async()=>{await He({preventDefault:()=>{}}),oa(!1),Mr&&Mr()},xa=(vt,hr)=>{u(ga=>({...ga,[vt]:hr}))},ks=o.useCallback(vt=>{Ca(),Ve(vt),vn(()=>{r("add")})},[Ca,Ve,r,vn]),sn=Y.useMemo(()=>ce.map(vt=>({...vt.taskSnapshot,isDeleted:!0,deletedRecordId:vt.id,deletedAt:vt.deletedAt,deletedExpiresAt:sI(vt.deletedAt)})),[ce]),mn=Y.useMemo(()=>new globalThis.Map(ce.map(vt=>[vt.taskId,vt])),[ce]),on=Y.useMemo(()=>{const vt=Ng(Ae),hr={categories:Le,types:Ie,priorities:Ye,assigneeOptions:se,taxonomies:he},ga=Le.every(vr=>Ne.includes(vr.value)),ia=Ie.every(vr=>q.includes(vr.value)),Za=Array.from(new Set(K.map(vr=>Number(vr)).filter(vr=>Number.isFinite(vr)))),ca=Ye.map(vr=>Number(vr.value)).filter(vr=>Number.isFinite(vr)).every(vr=>Za.includes(vr)),Fa=["task","in-progress","review","done","cancelled","on-hold"].every(vr=>we.includes(vr)),Jn=se.length>0&&se.every(vr=>Q.includes(vr.value)),La=Zf(he,sn);return sn.filter(vr=>{const Ja=ag(vr,vt,hr),Qn=ga||Ne.includes(vr.category),cn=ca||Za.includes(Yh(vr.priority)),bn=ia||q.includes(vr.type||fo),Ra=Fa||we.includes(vr.status),Zs=Jn||Q.includes(vr.assignee||"unassigned"),Xn=Object.entries(Pe).every(([es,pa])=>{const Sn=La.find(Oa=>Oa.id===es);if(!Sn||Qv(Sn,sn).every(Oa=>pa.includes(Oa.value)))return!0;const ws=vr.taxonomies?.[es];return ws?Array.isArray(ws)?ws.some(Oa=>pa.includes(Oa)):pa.includes(ws):pa.includes("")});return Ja&&Qn&&cn&&bn&&Ra&&Zs&&Xn}).sort((vr,Ja)=>ng(vr,Ja,ne,pe,he))},[Le,Ie,te,se,sn,Q,Ne,K,we,Pe,q,Ye,Ae,ne,pe,he,U]),Zn=Y.useMemo(()=>{const vt={};return on.forEach(hr=>{const ia=Le.find(Za=>Za.value===hr.category||Za.label===hr.category)?.label||hr.category||"General";vt[ia]||(vt[ia]=[]),vt[ia].push(hr)}),vt},[Le,on]),Da=iI(ce,on.map(vt=>vt.id),ee==="deleted"),qs=ee==="archived"?Ze.length:ee==="deleted"?on.length:ke.length;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{ref:Ms,className:`${dr.modal} ${R.coreModal} ${t==="settings"?dr.settingsViewModal:""}`,"data-theme":i,children:[a.jsxs("div",{className:"tf-modal-header",onMouseDown:ho,style:{cursor:ho?wn?"grabbing":"grab":"default"},children:[a.jsxs("div",{className:`tf-modal-title ${Fr.headerTitleWidget}`,children:["Taskforce",w&&a.jsxs(a.Fragment,{children:[a.jsx("span",{className:R.projectSlash,children:"/"}),a.jsx("span",{className:R.projectName,style:{fontSize:"14px",padding:"1px 6px"},children:w})]}),a.jsx("span",{className:R.taskCountBadge,title:ee==="deleted"?"Trash tasks — automatically deleted after 90 days":`${ee.charAt(0).toUpperCase()+ee.slice(1)} tasks`,children:qs})]}),a.jsxs("div",{className:dr.headerActions,children:[t==="tasks"&&a.jsx(a.Fragment,{children:a.jsx("button",{className:"tf-control-icon",onClick:()=>{vn(()=>{Ca(),r("add")})},title:"Add New Task","aria-label":"Add New Task",children:a.jsx(ri,{size:18})})}),a.jsx("button",{className:`tf-control-icon ${t==="settings"?"tf-control-icon-active":""}`,onClick:()=>{t!=="settings"&&vn(()=>{r("settings")})},title:"Settings","aria-label":"Settings",children:a.jsx(Nf,{size:18})}),a.jsx("button",{className:"tf-control-icon",onClick:$n,title:t==="tasks"?"Close":"Back to Tasks","aria-label":t==="tasks"?"Close":"Back to Tasks",children:t==="tasks"?a.jsx(Mo,{size:20}):a.jsx(s0,{size:20})})]})]}),a.jsx(pg,{notice:t==="add"?null:ta,onDismiss:Qr}),a.jsx(KI,{theme:i}),t==="add"&&a.jsxs("div",{className:R.taskNoticeAnchor,children:[a.jsx(GI,{editingTaskId:Qe,loading:Ge,submitDisabled:zr,autoSaveState:Wt,title:Bt,status:er,onStatusChange:_t,currentTask:Sr,currentTaskWorkstream:va,currentTaskInitiative:Ya,workstreams:e.workstreams,onWorkstreamInputChange:Rt,onSetWorkstreamForCurrentTask:ut,handleSubmit:He,handleCopyId:Be,copiedId:Kr,tasks:U,handleToggleInProgress:Te,handleToggleReview:fe,handleToggleComplete:ze,handleToggleCancel:qe,handleSetStatus:Ee,handleArchiveTask:$e,handleUnarchiveTask:vt=>{if(Sr?.isDeleted){const hr=mn.get(vt);hr&&xe(hr.id,hr.taskId);return}kt(vt)},handleRestoreDeletedTask:vt=>{const hr=ce.find(ga=>ga.id===vt);xe(vt,hr?.taskId)},handlePermanentlyDeleteDeletedTask:vt=>{jt(vt)}}),a.jsx(pg,{notice:At?{message:At,tone:"error"}:ta,onDismiss:()=>{Nt(),Qr()},placement:"task"})]}),t==="tasks"&&a.jsx($I,{ref:Ma,tasks:U,archivedTasks:te,categories:Le,types:Ie,priorities:Ye,workspaceId:ba,taxonomyDisplayLabels:ge,taxonomies:he,searchQuery:Ae,filterCategories:Ne,filterTypes:q,filterPriorities:K,filterStatus:we,filterAssignees:Q,assigneeOptions:se,filterTaxonomies:Pe,sortBy:ne,sortOrder:pe,showArchive:Ce,taskScope:ee,collapsedCategories:at,loadingTasks:ve,filteredTasks:ke,filteredArchive:Ze,groupedTasks:st,filteredDeletedTasks:on,groupedDeletedTasks:Zn,deletedTaskRecordByTaskId:mn,selectedDeletedRecordIds:Da.selectedIds,onDeletedSelectionChange:Da.toggle,trashControls:a.jsx(VI,{theme:i,selectedRecords:Da.selectedRecords,matchingCount:Da.matchingRecords.length,allMatchingSelected:Da.allMatchingSelected,someMatchingSelected:Da.someMatchingSelected,fullTrashCount:ce.length,onSelectAllMatching:Da.selectAllMatching,onClearSelection:Da.clear,onRestore:St,onEmptyEntireTrash:()=>{confirm(`Permanently delete all ${ce.length} tasks in Trash? Filters and selection do not limit this action. This cannot be undone.`)&&$()}}),copiedId:Kr,recentlyChangedTaskIds:dt,showTaskCardStatusLabel:Xr,workstreams:e.workstreams,initiatives:e.initiatives,onSearchChange:ye,onFilterCategoriesChange:vt=>ae(vt),onFilterTypesChange:vt=>W(vt),onFilterPrioritiesChange:Re,onFilterStatusChange:ie,onFilterAssigneesChange:vt=>H(vt),onTaxonomyFilterChange:(vt,hr)=>ue(ga=>({...ga,[vt]:hr})),onSortByChange:ys,onSortOrderChange:le,onShowArchiveChange:P,onTaskScopeChange:Se,onClearFilters:_e,onToggleCategory:vt=>oe(hr=>({...hr,[vt]:!hr[vt]})),onEditTask:We,onUpdateTask:Xe,taskReferences:Ta,onCopyId:Be,onToggleInProgress:Te,onToggleReview:fe,onToggleComplete:ze,onToggleCancel:qe,onSetStatus:Ee,onArchiveTask:$e,onBulkArchive:rt,onUnarchive:vt=>{const hr=mn.get(vt);if(hr){xe(hr.id,hr.taskId);return}kt(vt)},onDelete:vt=>{const hr=mn.get(vt);if(hr){jt(hr.id);return}G(vt)},onDeleteAllDeleted:()=>{$()},onFetchArchive:Ke,onAddTaskToCategory:ks,supplementalTasks:sn}),t==="add"&&a.jsx(HI,{editingTaskId:Qe,initialActivityEntryId:e.initialActivityEntryId,title:Bt,description:nt,checklistItems:je,category:pt,type:lt,priority:wt,complexity:Yt,manualComplexityEnabled:Dt,assignee:Rr,scheduledDate:sa,dueDate:Ur,formTaxonomies:_r,onTaxonomyChange:xa,taxonomies:he,comments:Pt,newCommentText:pr,contextFiles:tr,currentWorkspaceId:ba,descriptionImageDraftId:Ir,currentActorId:nn,apiBaseUrl:"",descriptionFocused:Jr,showMarkdownHelp:nr,checklistEnabled:Tt,categories:Le,types:Ie,priorities:Ye,taxonomyDisplayLabels:ge,assigneeOptions:se,workstreams:e.workstreams,initiatives:e.initiatives,copiedId:Kr,onTitleChange:Qt,onTitleDraftChange:Xt,onDescriptionChange:Mt,onDescriptionDraftChange:ur,onChecklistItemsChange:ot,onCategoryChange:Ve,onTypeChange:It,onPriorityChange:$t,onComplexityChange:qt,onAssigneeChange:la,onScheduledDateChange:ea,onDueDateChange:Ft,onNewCommentTextChange:Yr,onDescriptionFocusedChange:Br,onShowMarkdownHelpChange:Zr,onOpenSettings:vt=>{vn(()=>{C(vt),r("settings")})},onSubmit:He,onDescriptionImageUploadStart:Kt,commentsEndRef:ha,onAddComment:()=>ir(pr),taskReferences:Ta,onAddContextFile:vt=>{Lt(!0),$r(hr=>[...hr,vt])},onRemoveContextFile:async vt=>{Lt(!0),$r(hr=>hr.filter((ga,ia)=>ia!==vt))},onUpdateContextCaption:(vt,hr)=>{Lt(!0),$r(ga=>ga.map((ia,Za)=>Za!==vt?ia:typeof ia=="string"?{path:ia,caption:hr,timestamp:new Date().toISOString()}:{...ia,caption:hr}))},onOpenContextImage:vt=>{Ff(vt,{ownerType:"task",ownerId:Qe,ownerReferenceLabel:hs(Sr),workspaceId:ba})},onCopyId:Be,onToggleInProgress:Te,onToggleReview:fe,onToggleComplete:ze,onToggleCancel:qe,onArchiveTask:$e,onUnarchive:vt=>{if(Sr?.isDeleted){const hr=mn.get(vt);hr&&xe(hr.id,hr.taskId);return}kt(vt)},currentTask:Sr}),t==="settings"&&a.jsx(o.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2rem"},children:a.jsx(za,{size:20,className:R.spinner})}),children:a.jsx(oG,{settingsModel:kr,onSectionChange:C})})]}),x&&tc.createPortal(a.jsx("div",{className:Ea.overlay,children:a.jsxs("div",{className:Ea.browser,children:[a.jsxs("div",{className:Ea.header,children:[a.jsxs("div",{className:Ea.pathInfo,children:[a.jsx(Qi,{size:14}),a.jsx("span",{children:_||"Project Root"})]}),a.jsxs("div",{className:Ea.actions,children:[_&&a.jsx("button",{className:R.helpLink,onClick:()=>{const vt=_.split("/").filter(Boolean);vt.pop(),j(vt.length?vt.join("/")+"/":"")},children:"Back"}),a.jsx("button",{className:R.helpLink,onClick:()=>N(!1),children:"Close"})]})]}),a.jsxs("div",{className:Ea.list,children:[F&&typeof F=="object"&&a.jsxs("div",{className:`${Ea.item} ${Ea.itemCurrent}`,onClick:()=>M(_),children:[a.jsx(Si,{size:14})," Select Current: ./",_||"(root)"]}),v.map(vt=>a.jsxs("div",{className:Ea.item,onClick:()=>j(_+vt+"/"),children:[a.jsx(Qi,{size:14})," ",vt,"/"]},vt)),V.map(vt=>a.jsxs("div",{className:`${Ea.item} ${Ea.itemFile}`,onClick:()=>M(_+vt),children:[a.jsx(Ef,{size:14})," ",vt]},vt)),v.length===0&&V.length===0&&a.jsx("div",{className:`${Ea.item} ${Ea.empty}`,children:"No items found"})]})]})}),document.body),rr&&a.jsx("div",{className:`${dr.overlay} ${dr.unsavedOverlay}`,children:a.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${dr.modal} ${dr.unsavedModal}`,"data-theme":i,children:[a.jsx("div",{className:`tf-modal-header ${dr.unsavedHeader}`,children:a.jsxs("div",{className:`tf-modal-title ${dr.unsavedTitle}`,children:[a.jsx(Rd,{size:20}),"Unsaved Changes"]})}),a.jsx("div",{className:`${dr.form} ${dr.unsavedContent}`,children:a.jsx("p",{className:dr.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),a.jsxs("div",{className:`${dr.formActions} ${dr.unsavedActions}`,children:[a.jsx("button",{className:R.cancelBtn,onClick:()=>oa(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),a.jsx("button",{className:R.destructiveBtn,onClick:Ia,title:"Discard unsaved changes and leave",children:"Discard"}),a.jsxs("button",{className:R.submitBtn,onClick:fn,disabled:Ge,title:"Save changes and leave",children:[Ge?a.jsx(za,{size:16,className:R.spinner}):a.jsx(lA,{size:16}),"Save"]})]})]})}),Ga&&a.jsx("div",{className:`${dr.overlay} ${dr.unsavedOverlay}`,children:a.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${dr.modal} ${dr.unsavedModal}`,"data-theme":i,children:[a.jsx("div",{className:`tf-modal-header ${dr.unsavedHeader}`,children:a.jsxs("div",{className:`tf-modal-title ${dr.unsavedTitle}`,children:[a.jsx(Rd,{size:20}),"Date Warning"]})}),a.jsxs("div",{className:`${dr.form} ${dr.unsavedContent}`,children:[a.jsx("p",{className:dr.unsavedText,children:"Due date is before scheduled date."}),a.jsxs("p",{style:{margin:0,fontSize:"12px",color:"var(--text-muted)"},children:["Due: ",Ga.dueDate," · Scheduled: ",Ga.scheduledDate]})]}),a.jsxs("div",{className:`${dr.formActions} ${dr.unsavedActions}`,children:[a.jsx("button",{className:R.cancelBtn,onClick:Na,children:"Go Back"}),a.jsx("button",{className:R.submitBtn,onClick:Hr,children:"Save Anyway"})]})]})})]})}const cG="_accountMenuWrap_1mocf_1",lG="_avatarBtn_1mocf_5",dG="_avatarBadge_1mocf_9",uG="_avatarImage_1mocf_24",pG="_avatarIcon_1mocf_30",fG="_accountMenu_1mocf_1",mG="_accountMenuItem_1mocf_48",hG="_accountMenuItemActive_1mocf_68",gG="_accountMenuSection_1mocf_73",yG="_accountMenuSectionLabel_1mocf_79",kG="_accountMenuMeta_1mocf_88",vG="_accountMenuHint_1mocf_93",wG="_accountIdentityEmail_1mocf_99",bG="_accountIdentityBlock_1mocf_104",SG="_accountIdentityMetaLine_1mocf_109",AG="_accountIdentityMetaAction_1mocf_116",CG="_accountIdentityMetaValue_1mocf_125",IG="_accountIdentityMetaLabel_1mocf_130",_G="_accountMenuError_1mocf_159",TG="_accountHubCard_1mocf_165",xG="_profileAvatarEditor_1mocf_172",RG="_profileEditLayout_1mocf_178",jG="_profileFieldStack_1mocf_185",PG="_profileFieldLabel_1mocf_191",lr={accountMenuWrap:cG,avatarBtn:lG,avatarBadge:dG,avatarImage:uG,avatarIcon:pG,accountMenu:fG,accountMenuItem:mG,accountMenuItemActive:hG,accountMenuSection:gG,accountMenuSectionLabel:yG,accountMenuMeta:kG,accountMenuHint:vG,accountIdentityEmail:wG,accountIdentityBlock:bG,accountIdentityMetaLine:SG,accountIdentityMetaAction:AG,accountIdentityMetaValue:CG,accountIdentityMetaLabel:IG,accountMenuError:_G,accountHubCard:TG,profileAvatarEditor:xG,profileEditLayout:RG,profileFieldStack:jG,profileFieldLabel:PG},EG="_authBlockedBanner_1virb_1",NG="_loginView_1virb_10",MG="_loginCard_1virb_20",DG="_loginCloseBtn_1virb_34",LG="_loginLogo_1virb_56",OG="_authBrandRow_1virb_62",BG="_setupHeaderRow_1virb_68",WG="_runtimeIconBadge_1virb_75",$G="_loginTitle_1virb_94",FG="_loginTitleAccent_1virb_105",UG="_loginSubtitle_1virb_109",zG="_loginError_1virb_115",HG="_loginField_1virb_121",GG="_loginFieldLabel_1virb_126",VG="_loginInput_1virb_133",KG="_loginPrimaryBtn_1virb_149",qG="_authPrimaryActions_1virb_154",YG="_registerConsent_1virb_159",ZG="_registerConsentLink_1virb_167",JG="_authModeSwitch_1virb_177",QG="_authModeSwitchLink_1virb_184",XG="_authModeLinks_1virb_199",eV="_authSecondaryActions_1virb_207",tV="_authModeLink_1virb_199",rV="_optionGrid_1virb_236",aV="_optionGroup_1virb_242",nV="_optionRow_1virb_247",sV="_inlineHint_1virb_254",oV="_actionRowEnd_1virb_260",iV="_oauthProviders_1virb_267",cV="_oauthDivider_1virb_274",lV="_oauthButtons_1virb_290",dV="_oauthButton_1virb_290",Je={authBlockedBanner:EG,loginView:NG,loginCard:MG,loginCloseBtn:DG,loginLogo:LG,authBrandRow:OG,setupHeaderRow:BG,runtimeIconBadge:WG,loginTitle:$G,loginTitleAccent:FG,loginSubtitle:UG,loginError:zG,loginField:HG,loginFieldLabel:GG,loginInput:VG,loginPrimaryBtn:KG,authPrimaryActions:qG,registerConsent:YG,registerConsentLink:ZG,authModeSwitch:JG,authModeSwitchLink:QG,authModeLinks:XG,authSecondaryActions:eV,authModeLink:tV,optionGrid:rV,optionGroup:aV,optionRow:nV,inlineHint:sV,actionRowEnd:oV,oauthProviders:iV,oauthDivider:cV,oauthButtons:lV,oauthButton:dV},uV="_modalBody_xo2lt_1",pV="_mutedText_xo2lt_5",fV="_sectionText_xo2lt_10",mV="_modalActionsEnd_xo2lt_50",hV="_helpModalBody_xo2lt_56",gV="_helpHero_xo2lt_60",yV="_helpHeroIcon_xo2lt_67",kV="_helpHeroCopy_xo2lt_79",vV="_supportContactCard_xo2lt_84",wV="_supportContactHeader_xo2lt_90",bV="_supportEmailAddress_xo2lt_97",SV="_supportActionRow_xo2lt_112",AV="_supportAction_xo2lt_112",CV="_supportPanel_xo2lt_123",IV="_supportPanelHeader_xo2lt_132",_V="_memberRow_xo2lt_150",TV="_memberTitle_xo2lt_156",xV="_memberActions_xo2lt_160",RV="_selectRole_xo2lt_167",jV="_selectPermission_xo2lt_171",PV="_inviteRow_xo2lt_175",EV="_listHeading_xo2lt_179",NV="_auditList_xo2lt_184",MV="_auditPager_xo2lt_190",DV="_labelFixed_xo2lt_197",Or={modalBody:uV,mutedText:pV,sectionText:fV,modalActionsEnd:mV,helpModalBody:hV,helpHero:gV,helpHeroIcon:yV,helpHeroCopy:kV,supportContactCard:vV,supportContactHeader:wV,supportEmailAddress:bV,supportActionRow:SV,supportAction:AV,supportPanel:CV,supportPanelHeader:IV,memberRow:_V,memberTitle:TV,memberActions:xV,selectRole:RV,selectPermission:jV,inviteRow:PV,listHeading:EV,auditList:NV,auditPager:MV,labelFixed:DV};function LV({isOpen:e,theme:t,onClose:r,onConfirm:n}){return a.jsx(Do,{isOpen:e,onClose:r,title:"New Workspace",size:"sm",theme:t,draggable:!0,footer:a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:R.cancelBtn,onClick:r,children:"Cancel"}),a.jsx("button",{type:"button",className:R.submitBtn,onClick:n,children:"Start Setup"})]}),children:a.jsx("div",{className:`${dr.form} ${Or.modalBody}`,children:a.jsx("p",{className:Or.sectionText,children:"Create and configure a new workspace."})})})}const OV="_editableAvatarButton_1qp11_1",BV="_editableAvatarImage_1qp11_47",WV="_editableAvatarFallback_1qp11_54",$V="_editableAvatarBadge_1qp11_65",FV="_editableAvatarProgress_1qp11_91",UV="_editableAvatarProgressError_1qp11_108",ld={editableAvatarButton:OV,editableAvatarImage:BV,editableAvatarFallback:WV,editableAvatarBadge:$V,editableAvatarProgress:FV,editableAvatarProgressError:UV};function zV({label:e,imageUrl:t,fallbackImageUrl:r,fallback:n,accentColor:s,size:i=52,width:l,height:c,radius:d,editBadgeSize:f,editIconSize:p=16,disabled:g=!1,loading:h=!1,loadingLabel:y="Updating profile photo",error:k=!1,errorLabel:b="Profile photo update failed",className:C="",onClick:S}){const{activeImageUrl:w,handleImageError:T}=DI(t,r),E=l??i,x=c??i,N=typeof d=="number"?`${d}px`:d,v=typeof f=="number"?`${f}px`:f;return a.jsxs("button",{type:"button",className:`${ld.editableAvatarButton} ${C}`.trim(),"aria-label":e,"aria-busy":h,title:e,onClick:S,disabled:g,style:{"--editable-avatar-size":`${i}px`,"--editable-avatar-width":`${E}px`,"--editable-avatar-height":`${x}px`,...N?{"--editable-avatar-radius":N}:{},...v?{"--editable-avatar-badge-size":v}:{},...s?{"--editable-avatar-accent":s}:{}},children:[w?a.jsx("img",{src:w,alt:"",className:ld.editableAvatarImage,onError:T}):a.jsx("span",{className:ld.editableAvatarFallback,children:n}),a.jsx("span",{className:ld.editableAvatarBadge,"aria-hidden":"true",children:a.jsx(dA,{size:p})}),h?a.jsx("span",{className:ld.editableAvatarProgress,role:"status","aria-label":y,children:a.jsx(za,{size:Math.max(16,Math.round(i*.24))})}):k?a.jsx("span",{className:`${ld.editableAvatarProgress} ${ld.editableAvatarProgressError}`,role:"status","aria-label":b,children:a.jsx(Rd,{size:Math.max(16,Math.round(i*.24))})}):null]})}const HV="_modalBody_1t6q4_1",GV="_layout_1t6q4_5",VV="_sectionTabs_1t6q4_11",KV="_sectionTab_1t6q4_11",qV="_sectionPanel_1t6q4_55",YV="_section_1t6q4_11",ZV="_sectionHeader_1t6q4_65",JV="_cardHeader_1t6q4_66",QV="_planSummary_1t6q4_67",XV="_intervalRow_1t6q4_68",eK="_sectionCard_1t6q4_81",tK="_sectionActions_1t6q4_87",rK="_inlineActions_1t6q4_88",aK="_loginMethodList_1t6q4_96",nK="_loginMethodRow_1t6q4_101",sK="_loginMethodIcon_1t6q4_110",oK="_loginMethodCopy_1t6q4_122",iK="_addPasswordForm_1t6q4_137",cK="_linkProviderBlock_1t6q4_138",lK="_fieldLabel_1t6q4_145",dK="_planName_1t6q4_157",qr={modalBody:HV,layout:GV,sectionTabs:VV,sectionTab:KV,sectionPanel:qV,section:YV,sectionHeader:ZV,cardHeader:JV,planSummary:QV,intervalRow:XV,sectionCard:eK,sectionActions:tK,inlineActions:rK,loginMethodList:aK,loginMethodRow:nK,loginMethodIcon:sK,loginMethodCopy:oK,addPasswordForm:iK,linkProviderBlock:cK,fieldLabel:lK,planName:dK},uK=new Set(["active","trialing","grace"]),CS={CHECKOUT_SESSION_EXPIRED:"Your previous checkout expired. Choose a plan to continue.",CHECKOUT_SESSION_SUPERSEDED:"A newer checkout replaced your previous checkout. Choose a plan to continue."},Ah={planSelectionRequired:"Choose a plan to continue.",checkoutPending:"Complete checkout to continue.",misconfigured:"Onboarding policy is misconfigured. Contact support or a system administrator.",missingEntitlement:"No entitlement is linked to this account."};function Ed(e){return String(e||"").trim()}function qI(e){return Ed(e).toLowerCase()}function pK(e){return Ed(e).toLowerCase()}function fK(e){return!!(Ed(e?.stripeCustomerId)||Ed(e?.stripeSubscriptionId))}function mK(e){const t=Ed(e?.trialEnd||e?.effectiveUntil);if(t){const r=new Date(t);if(!Number.isNaN(r.getTime()))return r.getTime()<=Date.now()?"Your trial end date has passed. Billing status is updating.":`Your trial is active through ${r.toLocaleString()}.`}return"Your trial is active. Continue to Taskforce or manage billing anytime."}function hK(e){return uK.has(qI(e))}function sv(e,t){const r=qI(e?.entitlementState),n=pK(e?.gate||t),s=Ed(e?.billingConflictCode).toUpperCase(),i=Ed(e?.message),l=hK(r),c=fK(e);return s==="CHECKOUT_SESSION_EXPIRED"?{entitlementState:r||null,gate:n||null,isActive:!1,allowReturnToApp:!1,statusTone:"info",message:CS.CHECKOUT_SESSION_EXPIRED,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:c,markCurrentPlan:!1}:s==="CHECKOUT_SESSION_SUPERSEDED"?{entitlementState:r||null,gate:n||null,isActive:!1,allowReturnToApp:!1,statusTone:"info",message:CS.CHECKOUT_SESSION_SUPERSEDED,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:c,markCurrentPlan:!1}:r==="trialing"?{entitlementState:r,gate:n||null,isActive:!0,allowReturnToApp:!0,statusTone:"success",message:mK(e),primaryAction:c?"manage_billing":"none",primaryLabel:c?"Manage Billing":null,showManageBilling:c,markCurrentPlan:!0}:l?{entitlementState:r||null,gate:n||null,isActive:!0,allowReturnToApp:!0,statusTone:"success",message:i||null,primaryAction:"none",primaryLabel:null,showManageBilling:c,markCurrentPlan:!0}:r==="suspended"?{entitlementState:r,gate:n||null,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:"Your access is suspended because billing needs attention. Update billing to restore access.",primaryAction:c?"manage_billing":"open_plans",primaryLabel:c?"Manage Billing":"Open Plans",showManageBilling:c,markCurrentPlan:!1}:r==="canceled"?{entitlementState:r,gate:n||null,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:"Your access has ended. Choose a plan to reactivate your workspace.",primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:c,markCurrentPlan:!1}:r==="pending_plan_selection"||e?.planSelectionRequired===!0||n==="plan_selection_required"?{entitlementState:r||"pending_plan_selection",gate:n||"plan_selection_required",isActive:!1,allowReturnToApp:!1,statusTone:"info",message:i||Ah.planSelectionRequired,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:!1,markCurrentPlan:!1}:r==="checkout_pending"||n==="checkout_pending"?{entitlementState:r||"checkout_pending",gate:n||"checkout_pending",isActive:!1,allowReturnToApp:!1,statusTone:"info",message:i||Ah.checkoutPending,primaryAction:"open_plans",primaryLabel:"Open Plans",showManageBilling:c,markCurrentPlan:!1}:n==="misconfigured"?{entitlementState:r||null,gate:n,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:Ah.misconfigured,primaryAction:"none",primaryLabel:null,showManageBilling:!1,markCurrentPlan:!1}:n==="missing_entitlement"?{entitlementState:r||null,gate:n,isActive:!1,allowReturnToApp:!1,statusTone:"error",message:Ah.missingEntitlement,primaryAction:"choose_plan",primaryLabel:"Choose Plan",showManageBilling:!1,markCurrentPlan:!1}:{entitlementState:r||null,gate:n||null,isActive:!1,allowReturnToApp:!1,statusTone:i?"error":"info",message:i||null,primaryAction:"none",primaryLabel:null,showManageBilling:c,markCurrentPlan:!1}}const ov=12,iv=256,gK=new Set(["12345678","123456789","1234567890","admin123","changeme","letmein","letmein123","password","password1","password12","password123","password1234","qwerty","qwerty123","welcome","welcome123"]),yK=e=>String(e||"").trim().toLowerCase().replace(/[^a-z0-9]/g,"");function kK(e){const t=new Set,r=String(e?.email||"").trim().toLowerCase(),n=String(e?.displayName||"").trim().toLowerCase();if(r.includes("@")){const s=r.split("@")[0]||"",i=s.replace(/[^a-z0-9]/g,"");i.length>=4&&t.add(i);for(const l of s.split(/[^a-z0-9]+/))l.length>=4&&t.add(l)}for(const s of n.split(/[^a-z0-9]+/))s.length>=4&&t.add(s);return[...t]}function YI(){return[`Use at least ${ov} characters.`,`Use no more than ${iv} characters.`,"Avoid common passwords or obvious patterns.","Do not include your email or display name."]}function cv(e,t){const r=String(e||"");if(!r)return{ok:!1,code:"PASSWORD_REQUIRED",message:"Password is required."};if(r.length<ov)return{ok:!1,code:"PASSWORD_TOO_SHORT",message:`Password must be at least ${ov} characters.`};if(r.length>iv)return{ok:!1,code:"PASSWORD_TOO_LONG",message:`Password must be no more than ${iv} characters.`};const n=yK(r);return gK.has(n)?{ok:!1,code:"PASSWORD_TOO_COMMON",message:"Choose a less common password."}:kK(t).some(i=>n.includes(i))?{ok:!1,code:"PASSWORD_CONTAINS_PERSONAL_INFO",message:"Password cannot contain your email or display name."}:{ok:!0}}const IS={password:"Email & Password",google:"Google",github:"GitHub",apple:"Apple"},vK=[{id:"profile",label:"Profile",icon:Du},{id:"security",label:"Sign-in & Security",icon:o0},{id:"billing",label:"Plan & Billing",icon:i0}];function wK(e){const t=String(e||"").trim();return t?t.replace(/[_-]+/g," ").replace(/\b\w/g,r=>r.toUpperCase()):"Not available"}function bK({isOpen:e,theme:t,displayName:r,email:n,avatarDisplayUrl:s,accountBadgeInitial:i,profileSaveBusy:l,profileAvatarBusy:c,profileSaveError:d,profileSaveNotice:f,cloudAuthEnabled:p,availableAuthProviders:g,billingLoading:h,billingError:y,billingActionError:k,billingNotice:b,billingActionBusy:C,billingIntervalChoice:S,accountProfileSummary:w,onClose:T,onSaveProfile:E,onDisplayNameChange:x,onOpenAvatarManager:N,onFetchLoginMethods:v,onUnlinkLoginMethod:V,onAddPassword:_,onChangePassword:j,onLinkProvider:F,onBillingIntervalChange:z,onRefreshBilling:M,onUpdateInterval:O,onManageBilling:Z,onOpenPlans:U}){const[ve,te]=o.useState("profile"),[ce,Le]=o.useState([]),[Ie,Ye]=o.useState(!1),[ge,he]=o.useState(null),[Ae,ye]=o.useState(null),[Ne,ae]=o.useState(null),[q,W]=o.useState(!1),[K,Re]=o.useState(""),[we,ie]=o.useState(!1),[Q,H]=o.useState(null),[se,Pe]=o.useState(!1),[ue,ne]=o.useState(!1),[Me,pe]=o.useState(""),[le,Ce]=o.useState(""),[P,ee]=o.useState(""),[Se,_e]=o.useState(!1),[ke,Ze]=o.useState(null),[st,at]=o.useState(!1),oe=sv(w),We=YI(),G=String(w?.planName||w?.planId||"No plan selected").trim()||"No plan selected",Be=new Set(ce.map(xe=>xe.provider)),Xe=Be.has("password"),ze=g.filter(xe=>xe!=="password"&&!Be.has(xe));o.useEffect(()=>{e&&(te("profile"),ae(null),W(!1),Re(""),H(null),Pe(!1),ne(!1),pe(""),Ce(""),ee(""),Ze(null),at(!1))},[e]),o.useEffect(()=>{ve!=="security"&&(ne(!1),pe(""),Ce(""),ee(""),Ze(null))},[ve]),o.useEffect(()=>{if(!e||ve!=="security"||!p)return;let xe=!1;return Ye(!0),he(null),v().then(St=>{xe||(Ye(!1),St.success&&St.methods?Le(St.methods):he(St.error||"Failed to load login methods."))}),()=>{xe=!0}},[ve,p,e,v]);const qe=async xe=>{ye(xe),ae(null);const St=await V(xe);if(ye(null),!St.success){ae(St.error||"Unable to remove this login method.");return}Le(jt=>jt.filter($=>$.provider!==xe))},Te=async()=>{const xe=cv(K,{email:n,displayName:r});if(!xe.ok){H(xe.message||"Password does not meet the password policy.");return}ie(!0),H(null);const St=await _(K);if(ie(!1),!St.success){H(St.code==="IDENTITY_ALREADY_EXISTS"?"A password login already exists. Use Forgot Password from sign-in to recover it.":St.error||"Failed to add password.");return}Pe(!0),Re(""),W(!1);const jt=await v();jt.success&&jt.methods&&Le(jt.methods)},fe=async()=>{if(le!==P){Ze("New passwords do not match.");return}const xe=cv(le,{email:n,displayName:r});if(!xe.ok){Ze(xe.message||"Password does not meet the password policy.");return}_e(!0),Ze(null),at(!1);const St=await j(Me,le);if(_e(!1),!St.success){Ze(St.error||"Failed to change password.");return}pe(""),Ce(""),ee(""),ne(!1),at(!0);const jt=await v();jt.success&&jt.methods&&Le(jt.methods)},Ee=()=>{if(oe.primaryAction==="manage_billing"){Z();return}U()},$e=()=>a.jsxs("section",{className:qr.section,"aria-labelledby":"account-profile-heading",children:[a.jsx("div",{className:qr.sectionHeader,children:a.jsxs("div",{children:[a.jsx("h2",{className:"tf-heading-card",id:"account-profile-heading",children:"Profile"}),a.jsx("p",{className:"tf-text-secondary",children:"Manage how you appear across Taskforce."})]})}),a.jsxs("div",{className:`${qr.sectionCard} tf-surface-panel`,children:[a.jsxs("div",{className:lr.profileEditLayout,children:[a.jsx("div",{className:lr.profileAvatarEditor,children:a.jsx(zV,{label:"Edit profile photo",imageUrl:s,fallback:i,disabled:l||c,onClick:N})}),a.jsxs("div",{className:lr.profileFieldStack,children:[a.jsxs("label",{className:lr.profileFieldLabel,children:[a.jsx("span",{children:"Display name"}),a.jsx("input",{className:R.input,type:"text",value:r,onChange:xe=>x(xe.target.value),placeholder:"Display name",disabled:l})]}),a.jsxs("label",{className:lr.profileFieldLabel,children:[a.jsx("span",{children:"Email"}),a.jsx("input",{className:R.input,type:"email",value:n,readOnly:!0,disabled:!0})]})]})]}),d&&a.jsx("p",{className:"tf-text-error",role:"alert",children:d}),f&&!d&&a.jsx("p",{className:"tf-text-secondary",role:"status",children:f}),a.jsx("div",{className:qr.sectionActions,children:a.jsx("button",{type:"button",className:"tf-button-primary tf-button-compact",onClick:E,disabled:l||c||!r.trim(),children:l?"Saving…":"Save profile"})})]})]}),rt=()=>a.jsxs("section",{className:qr.section,"aria-labelledby":"account-security-heading",children:[a.jsx("div",{className:qr.sectionHeader,children:a.jsxs("div",{children:[a.jsx("h2",{className:"tf-heading-card",id:"account-security-heading",children:"Sign-in & Security"}),a.jsx("p",{className:"tf-text-secondary",children:"Manage the methods you use to sign in to your account."})]})}),a.jsxs("div",{className:`${qr.sectionCard} tf-surface-panel`,children:[a.jsx("div",{className:qr.cardHeader,children:a.jsxs("div",{children:[a.jsx("h3",{className:"tf-heading-card",children:"Login methods"}),a.jsx("p",{className:"tf-text-secondary",children:"Keep at least one sign-in method connected."})]})}),Ie&&a.jsx("p",{className:"tf-text-secondary",children:"Loading login methods…"}),ge&&a.jsx("p",{className:"tf-text-error",role:"alert",children:ge}),Ne&&a.jsx("p",{className:"tf-text-error",role:"alert",children:Ne}),se&&a.jsx("p",{className:"tf-text-secondary",role:"status",children:"Password login added."}),st&&a.jsx("p",{className:"tf-text-secondary",role:"status",children:"Password changed."}),!Ie&&ce.length>0&&a.jsx("div",{className:qr.loginMethodList,children:ce.map(xe=>a.jsxs("div",{className:qr.loginMethodRow,children:[a.jsx("span",{className:qr.loginMethodIcon,"aria-hidden":"true",children:xe.provider==="password"?a.jsx(c0,{size:16}):a.jsx(Bu,{size:16})}),a.jsxs("span",{className:qr.loginMethodCopy,children:[a.jsx("strong",{children:IS[xe.provider]||xe.provider}),xe.providerEmail&&a.jsx("span",{children:xe.providerEmail})]}),ce.length>1&&a.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",disabled:Ae===xe.provider,onClick:()=>{qe(xe.provider)},children:Ae===xe.provider?"Removing…":"Remove"})]},xe.provider))}),!Ie&&!ge&&Xe&&!ue&&a.jsx("div",{className:qr.sectionActions,children:a.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>{ne(!0),at(!1),Ze(null)},children:"Change password"})}),ue&&a.jsxs("div",{className:qr.addPasswordForm,children:[a.jsxs("label",{className:qr.fieldLabel,children:[a.jsx("span",{children:"Current password"}),a.jsx("input",{type:"password",className:R.input,value:Me,onChange:xe=>pe(xe.target.value),disabled:Se,autoComplete:"current-password"})]}),a.jsxs("label",{className:qr.fieldLabel,children:[a.jsx("span",{children:"New password"}),a.jsx("input",{type:"password",className:R.input,value:le,onChange:xe=>Ce(xe.target.value),disabled:Se,autoComplete:"new-password"})]}),a.jsxs("label",{className:qr.fieldLabel,children:[a.jsx("span",{children:"Confirm new password"}),a.jsx("input",{type:"password",className:R.input,value:P,onChange:xe=>ee(xe.target.value),disabled:Se,autoComplete:"new-password"})]}),a.jsx("p",{className:"tf-text-helper",children:We.join(" ")}),ke&&a.jsx("p",{className:"tf-text-error",role:"alert",children:ke}),a.jsxs("div",{className:qr.inlineActions,children:[a.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>{ne(!1),pe(""),Ce(""),ee(""),Ze(null)},disabled:Se,children:"Cancel"}),a.jsx("button",{type:"button",className:"tf-button-primary tf-button-compact",onClick:()=>{fe()},disabled:Se||!Me||!le||!P,children:Se?"Changing…":"Change password"})]})]}),!Ie&&!ge&&!Xe&&!q&&a.jsx("div",{className:qr.sectionActions,children:a.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>{W(!0),Pe(!1),H(null)},children:"Add password login"})}),q&&a.jsxs("div",{className:qr.addPasswordForm,children:[a.jsxs("label",{className:qr.fieldLabel,children:[a.jsx("span",{children:"New password"}),a.jsx("input",{type:"password",className:R.input,placeholder:"Use 12+ characters",value:K,onChange:xe=>Re(xe.target.value),disabled:we,autoComplete:"new-password"})]}),a.jsx("p",{className:"tf-text-helper",children:We.join(" ")}),Q&&a.jsx("p",{className:"tf-text-error",role:"alert",children:Q}),a.jsxs("div",{className:qr.inlineActions,children:[a.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>{W(!1),Re(""),H(null)},disabled:we,children:"Cancel"}),a.jsx("button",{type:"button",className:"tf-button-primary tf-button-compact",onClick:()=>{Te()},disabled:we||!K,children:we?"Saving…":"Save password"})]})]}),!Ie&&!ge&&ze.length>0&&a.jsxs("div",{className:qr.linkProviderBlock,children:[a.jsx("p",{className:"tf-label-micro",children:"Link another account"}),a.jsx("div",{className:qr.inlineActions,children:ze.map(xe=>a.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>F(xe),children:[a.jsx(Bu,{size:15}),IS[xe]||xe]},xe))})]})]})]}),kt=()=>a.jsxs("section",{className:qr.section,"aria-labelledby":"account-billing-heading",children:[a.jsxs("div",{className:qr.sectionHeader,children:[a.jsxs("div",{children:[a.jsx("h2",{className:"tf-heading-card",id:"account-billing-heading",children:"Plan & Billing"}),a.jsx("p",{className:"tf-text-secondary",children:"Review your plan and open the secure billing portal."})]}),a.jsxs("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:M,disabled:C||h,children:[a.jsx(uA,{size:14}),"Refresh"]})]}),a.jsxs("div",{className:`${qr.sectionCard} tf-surface-panel`,children:[h&&a.jsx("p",{className:"tf-text-secondary",children:"Loading billing status…"}),y&&a.jsx("p",{className:"tf-text-error",role:"alert",children:y}),k&&a.jsx("p",{className:"tf-text-error",role:"alert",children:k}),b&&a.jsx("p",{className:"tf-text-secondary",role:"status",children:b}),a.jsxs("div",{className:qr.planSummary,children:[a.jsxs("div",{children:[a.jsx("p",{className:"tf-label-micro",children:"Current plan"}),a.jsx("strong",{className:qr.planName,children:G})]}),a.jsx("span",{className:`tf-chip ${oe.isActive?"tf-chip-success":"tf-chip-neutral"}`,children:wK(w?.entitlementState)})]}),oe.message&&a.jsx("p",{className:oe.statusTone==="error"?"tf-text-error":"tf-text-secondary",children:oe.message}),w?.stripeSubscriptionId&&a.jsxs("div",{className:qr.intervalRow,children:[a.jsxs("label",{className:qr.fieldLabel,children:[a.jsx("span",{children:"Billing interval"}),a.jsxs("select",{className:R.input,value:S,onChange:xe=>z(xe.target.value==="year"?"year":"month"),disabled:C,children:[a.jsx("option",{value:"month",children:"Monthly"}),a.jsx("option",{value:"year",children:"Yearly"})]})]}),a.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:O,disabled:C,children:"Update interval"})]}),a.jsxs("div",{className:qr.sectionActions,children:[(oe.primaryAction==="manage_billing"||oe.primaryAction==="none")&&a.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:U,disabled:C,children:"View plans"}),oe.showManageBilling&&oe.primaryAction!=="manage_billing"&&a.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:Z,disabled:C,children:"Manage billing"}),oe.primaryLabel&&a.jsx("button",{type:"button",className:"tf-button-primary tf-button-compact",onClick:Ee,disabled:C,children:C?"Working…":oe.primaryLabel})]})]})]});return a.jsx(Do,{isOpen:e,onClose:T,title:"Account Settings",size:"mdWide",theme:t,draggable:!0,children:a.jsx("div",{className:`${dr.form} ${qr.modalBody}`,children:a.jsxs("div",{className:qr.layout,children:[a.jsx("div",{className:qr.sectionTabs,role:"tablist","aria-label":"Account settings sections","aria-orientation":"vertical",children:vK.map(xe=>{const St=xe.icon,jt=xe.id===ve;return a.jsxs("button",{type:"button",role:"tab",id:`account-settings-tab-${xe.id}`,"aria-controls":`account-settings-panel-${xe.id}`,"aria-selected":jt,className:qr.sectionTab,onClick:()=>te(xe.id),children:[a.jsx(St,{size:16}),a.jsx("span",{children:xe.label})]},xe.id)})}),a.jsxs("div",{className:qr.sectionPanel,role:"tabpanel",id:`account-settings-panel-${ve}`,"aria-labelledby":`account-settings-tab-${ve}`,children:[ve==="profile"&&$e(),ve==="security"&&rt(),ve==="billing"&&kt()]})]})})})}var _S=(e,t,r,n,s,i)=>{if(i===0)e.rect(t,r,n,s);else{let l=n-i,c=s-i;e.translate(t,r),e.arc(i,i,i,Math.PI,Math.PI*1.5),e.lineTo(l,0),e.arc(l,i,i,Math.PI*1.5,Math.PI*2),e.lineTo(n,c),e.arc(l,c,i,Math.PI*2,Math.PI*.5),e.lineTo(i,s),e.arc(i,c,i,Math.PI*.5,Math.PI),e.closePath(),e.translate(-t,-r)}},SK=(e,t,r,n,s,i)=>{e.fillStyle=i;let l=n/3,c=s/3;e.fillRect(t,r,1,s),e.fillRect(l+t,r,1,s),e.fillRect(l*2+t,r,1,s),e.fillRect(l*3+t,r,1,s),e.fillRect(l*4+t,r,1,s),e.fillRect(t,r,n,1),e.fillRect(t,c+r,n,1),e.fillRect(t,c*2+r,n,1),e.fillRect(t,c*3+r,n,1),e.fillRect(t,c*4+r,n,1)},AK=e=>!!e.match(/^\s*data:([a-z]+\/[a-z]+(;[a-z-]+=[a-z-]+)?)?(;base64)?,[a-z0-9!$&',()*+;=\-._~:@/?%\s]*\s*$/i),ZI=(e,t)=>new Promise((r,n)=>{let s=new Image;s.addEventListener("load",()=>r(s)),s.addEventListener("error",n),!AK(e)&&t&&(s.crossOrigin=t),s.src=e}),CK=e=>new Promise((t,r)=>{let n=new FileReader;n.addEventListener("load",s=>{try{if(!s?.target?.result)throw Error("No image data");t(ZI(s.target.result))}catch(i){r(i)}}),n.readAsDataURL(e)}),IK=typeof File<"u",TS=e=>Math.PI/180*e,xS={x:.5,y:.5},_K=class{constructor(e){this.imageState=xS,this.config={border:25,borderRadius:0,scale:1,rotate:0,color:[0,0,0,.5],backgroundColor:"",borderColor:void 0,showGrid:!1,gridColor:"#666",disableBoundaryChecks:!1,disableHiDPIScaling:!1,disableCanvasRotation:!0,crossOrigin:void 0,...e},this.pixelRatio=typeof window<"u"&&window.devicePixelRatio&&!this.config.disableHiDPIScaling?window.devicePixelRatio:1}getPixelRatio(){return this.pixelRatio}getImageState(){return this.imageState}setImageState(e){this.imageState=e}updateConfig(e){this.config={...this.config,...e}}isVertical(){return!this.config.disableCanvasRotation&&this.config.rotate%180!=0}getBorders(e){let t=e??this.config.border;return Array.isArray(t)?t:[t,t]}getDimensions(){let{width:e,height:t,rotate:r,border:n}=this.config,s={width:0,height:0},[i,l]=this.getBorders(n);return this.isVertical()?(s.width=t,s.height=e):(s.width=e,s.height=t),s.width+=i*2,s.height+=l*2,{canvas:s,rotate:r,width:e,height:t,border:n}}getXScale(){if(!this.imageState.width||!this.imageState.height)throw Error("Image dimension is unknown.");let e=this.config.width/this.config.height,t=this.imageState.width/this.imageState.height;return Math.min(1,e/t)}getYScale(){if(!this.imageState.width||!this.imageState.height)throw Error("Image dimension is unknown.");let e=this.config.height/this.config.width,t=this.imageState.height/this.imageState.width;return Math.min(1,e/t)}getCroppingRect(e){if(!this.imageState.width||!this.imageState.height)return{x:0,y:0,width:1,height:1};let t=e||{x:this.imageState.x,y:this.imageState.y},r=1/this.config.scale*this.getXScale(),n=1/this.config.scale*this.getYScale(),s={x:t.x-r/2,y:t.y-n/2,width:r,height:n},i=0,l=1-s.width,c=0,d=1-s.height;return(this.config.disableBoundaryChecks||r>1||n>1)&&(i=-s.width,l=1,c=-s.height,d=1),{...s,x:Math.max(i,Math.min(s.x,l)),y:Math.max(c,Math.min(s.y,d))}}getInitialSize(e,t){let r,n,s=this.getDimensions();return s.height/s.width>t/e?(r=s.height,n=r/t*e):(n=s.width,r=n/e*t),{height:r,width:n}}async loadImage(e){let t;if(IK&&e instanceof File)t=await CK(e);else if(typeof e=="string")t=await ZI(e,this.config.crossOrigin);else throw Error("Invalid image source");let r={...this.getInitialSize(t.width,t.height),resource:t,x:.5,y:.5};return this.imageState=r,r}clearImage(){this.imageState=xS}calculatePosition(e=this.imageState,t){let[r,n]=this.getBorders(t);if(!e.width||!e.height)throw Error("Image dimension is unknown.");let s=this.getCroppingRect(),i=e.width*this.config.scale,l=e.height*this.config.scale,c=-s.x*i,d=-s.y*l;return this.isVertical()?(c+=n,d+=r):(c+=r,d+=n),{x:c,y:d,height:l,width:i}}paint(e){e.save(),e.scale(this.pixelRatio,this.pixelRatio),e.translate(0,0),e.fillStyle="rgba("+this.config.color.slice(0,4).join(",")+")";let t=this.config.borderRadius,r=this.getDimensions(),[n,s]=this.getBorders(r.border),i=r.canvas.height,l=r.canvas.width;t=Math.max(t,0),t=Math.min(t,l/2-n,i/2-s),e.beginPath(),_S(e,n,s,l-n*2,i-s*2,t),e.rect(l,0,-l,i),e.fill("evenodd"),this.config.borderColor&&(e.strokeStyle="rgba("+this.config.borderColor.slice(0,4).join(",")+")",e.lineWidth=1,e.beginPath(),_S(e,n+.5,s+.5,l-n*2-1,i-s*2-1,t),e.stroke()),this.config.showGrid&&SK(e,n,s,l-n*2,i-s*2,this.config.gridColor),e.restore()}paintImage(e,t,r,n=this.pixelRatio){if(!t.resource)return;let s=this.calculatePosition(t,r);e.save(),e.translate(e.canvas.width/2,e.canvas.height/2),e.rotate(this.config.rotate*Math.PI/180),e.translate(-(e.canvas.width/2),-(e.canvas.height/2)),this.isVertical()&&e.translate((e.canvas.width-e.canvas.height)/2,(e.canvas.height-e.canvas.width)/2),e.scale(n,n),e.globalCompositeOperation="destination-over",e.drawImage(t.resource,s.x,s.y,s.width,s.height),this.config.backgroundColor&&(e.fillStyle=this.config.backgroundColor,e.fillRect(0,0,e.canvas.width,e.canvas.height)),e.restore()}getImage(){let e=this.getCroppingRect(),t=this.imageState;if(!t.resource)throw Error("No image resource available, please report this to: https://github.com/mosch/react-avatar-editor/issues");e.x*=t.resource.width,e.y*=t.resource.height,e.width*=t.resource.width,e.height*=t.resource.height;let r=document.createElement("canvas");this.isVertical()?(r.width=Math.round(e.height),r.height=Math.round(e.width)):(r.width=Math.round(e.width),r.height=Math.round(e.height));let n=r.getContext("2d");if(!n)throw Error("No context found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return n.translate(r.width/2,r.height/2),n.rotate(this.config.rotate*Math.PI/180),n.translate(-(r.width/2),-(r.height/2)),this.isVertical()&&n.translate((r.width-r.height)/2,(r.height-r.width)/2),this.config.backgroundColor&&(n.fillStyle=this.config.backgroundColor,n.fillRect(0,0,r.width,r.height)),n.drawImage(t.resource,-e.x,-e.y),r}getImageScaledToCanvas(){let e=this.getDimensions(),t=this.imageState,r=document.createElement("canvas");if(this.isVertical()?(r.width=e.height,r.height=e.width):(r.width=e.width,r.height=e.height),!t.resource)return r;let n=r.getContext("2d");if(!n)return r;let s=this.calculatePosition(t,0);return n.save(),n.translate(r.width/2,r.height/2),n.rotate(this.config.rotate*Math.PI/180),n.translate(-(r.width/2),-(r.height/2)),this.isVertical()&&n.translate((r.width-r.height)/2,(r.height-r.width)/2),this.config.backgroundColor&&(n.fillStyle=this.config.backgroundColor,n.fillRect(0,0,r.width,r.height)),n.drawImage(t.resource,s.x,s.y,s.width,s.height),n.restore(),r}calculateDragPosition(e,t,r,n){let s=r-e,i=n-t;if(!this.imageState.width||!this.imageState.height)throw Error("Image dimension is unknown.");let l=this.imageState.width*this.config.scale,c=this.imageState.height*this.config.scale,{x:d,y:f}=this.getCroppingRect();d*=l,f*=c;let p=this.config.rotate;p%=360,p=p<0?p+360:p;let g=Math.cos(TS(p)),h=Math.sin(TS(p)),y=d+s*g+i*h,k=f+-s*h+i*g,b=1/this.config.scale*this.getXScale(),C=1/this.config.scale*this.getYScale();return{x:y/l+b/2,y:k/c+C/2}}},RS=()=>{},TK=()=>{let e=!1;try{let t=Object.defineProperty({},"passive",{get:function(){e=!0}});window.addEventListener("test",RS,t),window.removeEventListener("test",RS,t)}catch{e=!1}return e},JI=o.forwardRef((e,t)=>{let{scale:r=1,rotate:n=0,border:s=25,borderRadius:i=0,width:l=200,height:c=200,color:d=[0,0,0,.5],showGrid:f=!1,gridColor:p="#666",disableBoundaryChecks:g=!1,disableHiDPIScaling:h=!1,disableCanvasRotation:y=!0,image:k,position:b,backgroundColor:C,crossOrigin:S,onLoadStart:w,onLoadFailure:T,onLoadSuccess:E,onImageReady:x,onImageChange:N,onMouseUp:v,onMouseMove:V,onPositionChange:_,borderColor:j,style:F}=e,z=o.useRef(null),M=o.useRef(new _K({width:l,height:c,border:s,borderRadius:i,scale:r,rotate:n,color:d,backgroundColor:C,borderColor:j,showGrid:f,gridColor:p,disableBoundaryChecks:g,disableHiDPIScaling:h,disableCanvasRotation:y,crossOrigin:S})),O=o.useRef(!1),Z=o.useRef(void 0),U=o.useRef(void 0),[ve,te]=o.useState(!1),[ce,Le]=o.useState(!1),[Ie,Ye]=o.useState(M.current.getImageState()),ge=o.useRef(v);ge.current=v;let he=o.useRef(V);he.current=V;let Ae=o.useRef(_);Ae.current=_,o.useEffect(()=>{M.current.updateConfig({width:l,height:c,border:s,borderRadius:i,scale:r,rotate:n,color:d,backgroundColor:C,borderColor:j,showGrid:f,gridColor:p,disableBoundaryChecks:g,disableHiDPIScaling:h,disableCanvasRotation:y,crossOrigin:S})},[l,c,s,i,r,n,d,C,j,f,p,g,h,y,S]);let ye=o.useCallback(()=>{if(!z.current)throw Error("No canvas found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return z.current},[]),Ne=o.useCallback(()=>{let se=ye().getContext("2d");if(!se)throw Error("No context found, please report this to: https://github.com/mosch/react-avatar-editor/issues");return se},[ye]),ae=o.useCallback(async se=>{Le(!0),w?.();try{let Pe=await M.current.loadImage(se);O.current=!1,te(!1),Ye(Pe),x?.(),E?.(Pe)}catch{T?.()}finally{Le(!1)}},[w,x,E,T]),q=o.useCallback(()=>{let se=ye();Ne().clearRect(0,0,se.width,se.height),M.current.clearImage(),Ye(M.current.getImageState())},[ye,Ne]),W=o.useCallback(()=>{let se=Ne(),Pe=ye();se.clearRect(0,0,Pe.width,Pe.height),M.current.paint(se),M.current.paintImage(se,Ie,s)},[Ne,ye,Ie,s,l,c,i,r,n,d,C,j,f,p,g,h,y,S]),K=o.useCallback(se=>{se.preventDefault(),O.current=!0,Z.current=void 0,U.current=void 0,te(!0)},[]),Re=o.useCallback(()=>{O.current=!0,Z.current=void 0,U.current=void 0,te(!0)},[]);o.useImperativeHandle(t,()=>({getImage:()=>M.current.getImage(),getImageScaledToCanvas:()=>M.current.getImageScaledToCanvas(),getCroppingRect:()=>M.current.getCroppingRect()}),[]),o.useEffect(()=>{let se=Ne();k&&ae(k),M.current.paint(se);let Pe=Me=>{if(!O.current)return;Me.cancelable&&Me.preventDefault();let pe="targetTouches"in Me?Me.targetTouches[0].pageX:Me.clientX,le="targetTouches"in Me?Me.targetTouches[0].pageY:Me.clientY,Ce=Z.current,P=U.current;if(Z.current=pe,U.current=le,Ce!==void 0&&P!==void 0){let ee=M.current.getImageState();if(ee.width&&ee.height){let Se=M.current.calculateDragPosition(pe,le,Ce,P);Ae.current?.(Se);let _e={...ee,...Se};M.current.setImageState(_e),Ye(_e)}}he.current?.(Me)},ue=()=>{O.current&&(O.current=!1,te(!1),ge.current?.())},ne=TK()?{passive:!1}:!1;return document.addEventListener("mousemove",Pe,ne),document.addEventListener("mouseup",ue,ne),document.addEventListener("touchmove",Pe,ne),document.addEventListener("touchend",ue,ne),()=>{document.removeEventListener("mousemove",Pe,!1),document.removeEventListener("mouseup",ue,!1),document.removeEventListener("touchmove",Pe,!1),document.removeEventListener("touchend",ue,!1)}},[]),o.useEffect(()=>{k?ae(k):!k&&Ie.x!==.5&&Ie.y!==.5&&q()},[k,l,c,C]),o.useEffect(()=>{W()},[W]),o.useEffect(()=>{if(!ce)return;let se=z.current;if(!se)return;let Pe=se.getContext("2d");if(!Pe)return;let ue,ne=performance.now(),Me=pe=>{let le=(pe-ne)/1e3,Ce=.03+Math.sin(le*2.5)*.02+.02;Pe.save(),Pe.clearRect(0,0,se.width,se.height),Pe.fillStyle=`rgba(255,255,255,${Ce})`,Pe.fillRect(0,0,se.width,se.height),Pe.restore(),ue=requestAnimationFrame(Me)};return ue=requestAnimationFrame(Me),()=>cancelAnimationFrame(ue)},[ce]);let we=o.useRef({image:k,width:l,height:c,position:b,scale:r,rotate:n,imageX:Ie.x,imageY:Ie.y});o.useEffect(()=>{let se=we.current;(se.image!==k||se.width!==l||se.height!==c||se.position!==b||se.scale!==r||se.rotate!==n||se.imageX!==Ie.x||se.imageY!==Ie.y)&&(N?.(),we.current={image:k,width:l,height:c,position:b,scale:r,rotate:n,imageX:Ie.x,imageY:Ie.y})},[k,l,c,b,r,n,Ie.x,Ie.y,N]);let ie=M.current.getDimensions(),Q=M.current.getPixelRatio(),H={width:ie.canvas.width,height:ie.canvas.height,cursor:ve?"grabbing":"grab",touchAction:"none",maxWidth:"none",maxHeight:"none"};return Y.createElement("canvas",{width:ie.canvas.width*Q,height:ie.canvas.height*Q,onMouseDown:K,onTouchStart:Re,style:{...H,...F},ref:z})});JI.displayName="AvatarEditor";const xK="_avatarManagerBody_1bfoi_1",RK="_editorPanel_1bfoi_7",jK="_editorFrame_1bfoi_13",PK="_gifPreviewImage_1bfoi_21",EK="_emptyPreview_1bfoi_28",NK="_controlPanel_1bfoi_41",MK="_zoomField_1bfoi_47",DK="_zoomSlider_1bfoi_52",LK="_actionGrid_1bfoi_57",OK="_fileInput_1bfoi_71",BK="_messageStack_1bfoi_75",WK="_footerActions_1bfoi_80",Qo={avatarManagerBody:xK,editorPanel:RK,editorFrame:jK,gifPreviewImage:PK,emptyPreview:EK,controlPanel:NK,zoomField:MK,zoomSlider:DK,actionGrid:LK,fileInput:OK,messageStack:BK,footerActions:WK},vk=512,$K=48,Ch=512;function jS(e,t,r){return new Promise(n=>{e.toBlob(n,t,r)})}function FK(e,t){const r=String(e).trim()||"avatar",n=r.lastIndexOf(".");return n<=0?`${r}${t}`:`${r.slice(0,n)}${t}`}async function UK(e,t){const r=e.getImageScaledToCanvas(),n=document.createElement("canvas");n.width=Ch,n.height=Ch;const s=n.getContext("2d");if(!s)throw new Error("Image editing requires a 2D canvas context.");s.drawImage(r,0,0,Ch,Ch);const l=await jS(n,"image/webp",.9)||await jS(n,"image/jpeg",.9);if(!l)throw new Error("Unable to prepare profile photo.");const c=l.type||"image/jpeg",d=c==="image/webp"?".webp":".jpg";return new File([l],FK(t,d),{type:c,lastModified:Date.now()})}function zK({isOpen:e,theme:t,title:r="Edit Photo",currentImageUrl:n,editorImageUrl:s="",fallbackInitial:i,accept:l,busy:c,generating:d=!1,generateLabel:f="Generate",hasPendingImage:p,canRemove:g,error:h,notice:y,onClose:k,onApplyImage:b,onGenerateImage:C,onRemoveImage:S,onDiscardPendingImage:w}){const T=o.useRef(null),E=o.useRef(null),x=o.useRef(!1),N=o.useRef(!1),[v,V]=o.useState(null),[_,j]=o.useState(""),[F,z]=o.useState(1.1),[M,O]=o.useState(!1),[Z,U]=o.useState(null),[ve,te]=o.useState(null);o.useEffect(()=>{e||(V(null),j(""),z(1.1),O(!1),N.current=!1,U(null),te(null))},[e]),o.useEffect(()=>{e&&(O(!1),N.current=!1)},[n,s,e]),o.useEffect(()=>{if(!v){j("");return}const W=URL.createObjectURL(v);return j(W),()=>URL.revokeObjectURL(W)},[v]);const ce=_||s||n,Le=v?.name||"avatar",Ie=String(i||"").trim().charAt(0).toUpperCase(),Ye=Z||h,ge=ve||y,he=c||d,Ae=o.useCallback(W=>{if(U(null),te(null),!!W){if(!W.type.startsWith("image/")){U("Profile photo must be an image file.");return}W.type==="image/gif"&&te("Animated GIFs will upload without repositioning."),V(W),z(1.1),O(!1),N.current=!1}},[]),ye=o.useCallback(async()=>{U(null);const W=T.current;if(v?.type==="image/gif"){await b(v)&&k();return}if(!W||!ce){U("Choose a profile photo first.");return}try{const K=await UK(W,Le);await b(K,v,{preserveExistingSource:!v&&!!s})&&k()}catch(K){U(K instanceof Error?K.message:"Unable to prepare profile photo.")}},[n,ce,s,b,k,v,Le]),Ne=o.useCallback(async()=>{if(!(!C||he||x.current)){x.current=!0,U(null),te(null);try{await C()&&(V(null),z(1.1),O(!1),N.current=!1)}catch(W){U(W instanceof Error?W.message:"Unable to generate profile photo.")}finally{x.current=!1}}},[he,C]),ae=p||!!v||M,q=o.useMemo(()=>a.jsxs("div",{className:Qo.footerActions,children:[a.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:k,disabled:c,children:"Cancel"}),a.jsx("button",{type:"button",className:"tf-button-primary tf-button-compact",onClick:()=>{ye()},disabled:he||!ae,children:c?"Applying...":"Apply Changes"})]}),[c,ae,ye,he,k]);return a.jsx(Do,{isOpen:e,onClose:k,title:r,size:"md",theme:t,draggable:!0,footer:q,children:a.jsxs("div",{className:Qo.avatarManagerBody,children:[a.jsxs("div",{className:Qo.editorPanel,children:[a.jsx("div",{className:`tf-surface-inset ${Qo.editorFrame}`,onPointerDown:()=>{ce&&v?.type!=="image/gif"&&(N.current=!0)},children:v?.type==="image/gif"&&_?a.jsx("img",{src:_,alt:"",className:Qo.gifPreviewImage}):ce?a.jsx(JI,{ref:T,image:ce,width:vk,height:vk,border:$K,borderRadius:vk/2,scale:F,color:[15,15,26,.72],backgroundColor:"transparent",onPositionChange:()=>{N.current&&O(!0)},style:{width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",display:"block",borderRadius:"var(--radius-lg)",boxShadow:"var(--box-shadow-sm)"},disableCanvasRotation:!0}):a.jsx("div",{className:Qo.emptyPreview,"aria-hidden":"true",children:Ie})}),a.jsxs("div",{className:Qo.controlPanel,children:[a.jsx("input",{ref:E,type:"file","aria-label":"Choose profile photo",accept:l,className:Qo.fileInput,onChange:W=>Ae(W.target.files?.[0]||null),disabled:he}),a.jsxs("div",{className:Qo.actionGrid,children:[a.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>E.current?.click(),disabled:he,children:[a.jsx(l0,{size:16}),"Choose"]}),p&&w&&a.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:w,disabled:he,children:[a.jsx(bi,{size:16}),"Discard"]}),C&&a.jsxs("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:()=>{Ne()},disabled:he,"aria-busy":d,children:[d?a.jsx(za,{size:16,className:R.spinner}):a.jsx(nA,{size:16}),d?"Generating":f]}),g&&S&&a.jsxs("button",{type:"button",className:"tf-button-destructive tf-button-compact",onClick:S,disabled:he,children:[a.jsx(Vf,{size:16}),"Remove"]})]}),a.jsxs("label",{className:`tf-field-stack ${Qo.zoomField}`,children:[a.jsx("span",{className:"tf-field-label",children:"Zoom"}),a.jsx("input",{type:"range",min:"1",max:"3",step:"0.01",value:F,onChange:W=>{z(Number(W.target.value)),O(!0)},className:Qo.zoomSlider,disabled:he||!ce||v?.type==="image/gif"})]})]})]}),(Ye||ge)&&a.jsxs("div",{className:Qo.messageStack,children:[Ye&&a.jsx("p",{className:"tf-text-error",children:Ye}),ge&&!Ye&&a.jsx("p",{className:"tf-text-helper",children:ge})]})]})})}const lv="support@taskforcehq.ai";function Ih(e){return String(e||"").trim()}function HK(e={}){const t=Ih(e.workspaceName),r=Ih(e.workspaceId),n=Ih(e.accountLabel),s=Ih(e.runtimeMode),i=[t?`Workspace: ${t}`:"",r?`Workspace ID: ${r}`:"",n?`Account: ${n}`:"",s?`Runtime: ${s}`:""].filter(Boolean),l=["Hi Taskforce team,","","I need help with:","",i.length>0?"Context:":"",...i,(i.length>0,""),"What happened:",""].filter((d,f,p)=>d!==""||p[f-1]!==""),c=new URLSearchParams({subject:"Taskforce support request",body:l.join(`
6
+ `)});return`mailto:${lv}?${c.toString()}`}function GK({isOpen:e,theme:t,onClose:r,onOpenSettings:n,supportMailtoHref:s}){const[i,l]=o.useState("idle"),c=async()=>{try{await navigator.clipboard.writeText(lv),l("copied"),window.setTimeout(()=>l("idle"),1600)}catch{l("failed"),window.setTimeout(()=>l("idle"),2200)}};return a.jsx(Do,{isOpen:e,onClose:r,title:"Help & Support",size:"sm",theme:t,draggable:!0,children:a.jsxs("div",{className:`${dr.form} ${Or.modalBody} ${Or.helpModalBody}`,children:[a.jsxs("div",{className:Or.helpHero,children:[a.jsx("span",{className:Or.helpHeroIcon,"aria-hidden":"true",children:a.jsx(d0,{size:20})}),a.jsxs("div",{className:Or.helpHeroCopy,children:[a.jsx("h2",{className:"tf-heading-card",children:"How can we help?"}),a.jsx("p",{className:"tf-text-secondary",children:"Tell us what you were trying to do, what happened, and any workspace context that could help us reproduce it."})]})]}),a.jsxs("section",{className:`${Or.supportContactCard} tf-surface-panel`,"aria-labelledby":"support-email-heading",children:[a.jsx("div",{className:Or.supportContactHeader,children:a.jsxs("div",{children:[a.jsx("h3",{className:"tf-label-micro",id:"support-email-heading",children:"Email support"}),a.jsx("a",{className:Or.supportEmailAddress,href:s,children:lv})]})}),a.jsxs("div",{className:Or.supportActionRow,children:[a.jsxs("a",{className:`tf-button-primary tf-button-compact ${Or.supportAction}`,href:s,children:[a.jsx(u0,{size:15}),"Email Support"]}),a.jsxs("button",{className:`tf-button-secondary tf-button-compact ${Or.supportAction}`,onClick:()=>{c()},type:"button",children:[i==="copied"?a.jsx(Si,{size:15}):a.jsx(pA,{size:15}),i==="copied"?"Copied":i==="failed"?"Copy failed":"Copy address"]})]})]}),a.jsxs("section",{className:Or.supportPanel,"aria-labelledby":"support-settings-heading",children:[a.jsxs("div",{className:Or.supportPanelHeader,children:[a.jsx(Nf,{size:17,"aria-hidden":"true"}),a.jsxs("div",{children:[a.jsx("h3",{className:"tf-heading-card",id:"support-settings-heading",children:"Check workspace settings"}),a.jsx("p",{className:"tf-text-secondary",children:"Common workspace, appearance, and setup options are available in Settings."})]})]}),a.jsxs("button",{className:`tf-button-secondary tf-button-compact ${Or.supportAction}`,onClick:n,type:"button",children:[a.jsx(Nf,{size:15}),"Open Settings"]})]})]})})}function VK({prompt:e,theme:t,onClose:r,onConfirm:n}){return a.jsx(Do,{isOpen:!!e,onClose:r,title:"Date Warning",size:"sm",theme:t,draggable:!1,closeOnOverlayClick:!1,children:a.jsxs("div",{className:`${R.form} tf-inline-stack-sm`,style:{padding:"16px",gap:"12px"},children:[a.jsx("p",{className:"tf-text-body",children:"Due date is before scheduled date."}),e&&a.jsxs("p",{className:"tf-text-helper",children:["Due: ",e.dueDate," · Scheduled: ",e.scheduledDate]}),a.jsxs("div",{className:R.formActions,children:[a.jsx("button",{className:R.cancelBtn,onClick:r,children:"Go Back"}),a.jsx("button",{className:R.submitBtn,onClick:n,children:"Save Anyway"})]})]})})}function KK({isOpen:e,theme:t,onClose:r,onConfirm:n}){return a.jsx(Do,{isOpen:e,onClose:r,title:"Cloud Sync Warning",size:"sm",theme:t,draggable:!1,closeOnOverlayClick:!1,children:a.jsxs("div",{className:`${R.form} tf-inline-stack-sm`,style:{padding:"16px",gap:"12px"},children:[a.jsx("p",{className:"tf-text-body",children:"Turning on cloud sync can renumber task, document, and image references to match the cloud workspace."}),a.jsxs("p",{className:"tf-text-helper",children:["Labels like ",a.jsx("code",{children:"T-12"}),", ",a.jsx("code",{children:"D-4"}),", and ",a.jsx("code",{children:"IMG-2"})," may change. Plain file attachments are not renumbered."]}),a.jsxs("div",{className:R.formActions,children:[a.jsx("button",{className:R.cancelBtn,onClick:r,children:"Go Back"}),a.jsx("button",{className:R.submitBtn,onClick:n,children:"Enable Sync Anyway"})]})]})})}const qK="_syncStatusOverlay_qjzsr_1",YK="_syncStatusModal_qjzsr_5",ZK="_syncStatusTop_qjzsr_10",JK="_syncStatusMetaHeader_qjzsr_19",QK="_syncStatusBadge_qjzsr_26",XK="_syncStatusLabel_qjzsr_40",eq="_syncToggle_qjzsr_51",tq="_syncToggleControl_qjzsr_58",rq="_syncToggleControlEnabled_qjzsr_74",aq="_syncToggleControlDisabled_qjzsr_80",nq="_syncToggleControlBusy_qjzsr_84",sq="_syncToggleControlBlocked_qjzsr_89",oq="_syncToggleInput_qjzsr_94",iq="_syncToggleState_qjzsr_107",cq="_syncToggleStateOn_qjzsr_121",lq="_syncToggleStateOff_qjzsr_125",dq="_syncToggleThumb_qjzsr_134",uq="_syncStatusOverview_qjzsr_145",pq="_syncStatusEventsPanel_qjzsr_146",fq="_syncStatusAdvanced_qjzsr_147",mq="_syncStatusOverviewRow_qjzsr_158",hq="_syncStatusSummaryValue_qjzsr_172",gq="_syncStatusValue_qjzsr_173",yq="_syncStatusIssueRow_qjzsr_181",kq="_syncStatusIssueRowError_qjzsr_185",vq="_syncStatusValueMuted_qjzsr_189",wq="_syncStatusValueError_qjzsr_196",bq="_syncStatusKeyMetrics_qjzsr_203",Sq="_syncStatusCompactGrid_qjzsr_204",Aq="_syncStatusCompactItem_qjzsr_217",Cq="_syncStatusAdvancedContent_qjzsr_258",Iq="_syncStatusDiagnosticsList_qjzsr_265",_q="_syncStatusOwnershipControl_qjzsr_271",Tq="_syncStatusDiagnosticRow_qjzsr_292",xq="_syncStatusPanelHeader_qjzsr_314",Rq="_syncStatusPanelMeta_qjzsr_321",jq="_syncStatusMismatchPanel_qjzsr_327",Pq="_syncStatusMismatchItem_qjzsr_337",Eq="_syncStatusEventFilters_qjzsr_356",Nq="_syncStatusEventFilterActive_qjzsr_383",Mq="_syncStatusEventsList_qjzsr_388",Dq="_syncStatusEventItem_qjzsr_398",Lq="_syncStatusEventItemError_qjzsr_405",Oq="_syncStatusEventItemMuted_qjzsr_410",Bq="_syncStatusEventLine_qjzsr_414",Wq="_syncStatusFooter_qjzsr_424",$q="_syncStatusFooterPrimary_qjzsr_433",Et={syncStatusOverlay:qK,syncStatusModal:YK,syncStatusTop:ZK,syncStatusMetaHeader:JK,syncStatusBadge:QK,syncStatusLabel:XK,syncToggle:eq,syncToggleControl:tq,syncToggleControlEnabled:rq,syncToggleControlDisabled:aq,syncToggleControlBusy:nq,syncToggleControlBlocked:sq,syncToggleInput:oq,syncToggleState:iq,syncToggleStateOn:cq,syncToggleStateOff:lq,syncToggleThumb:dq,syncStatusOverview:uq,syncStatusEventsPanel:pq,syncStatusAdvanced:fq,syncStatusOverviewRow:mq,syncStatusSummaryValue:hq,syncStatusValue:gq,syncStatusIssueRow:yq,syncStatusIssueRowError:kq,syncStatusValueMuted:vq,syncStatusValueError:wq,syncStatusKeyMetrics:bq,syncStatusCompactGrid:Sq,syncStatusCompactItem:Aq,syncStatusAdvancedContent:Cq,syncStatusDiagnosticsList:Iq,syncStatusOwnershipControl:_q,syncStatusDiagnosticRow:Tq,syncStatusPanelHeader:xq,syncStatusPanelMeta:Rq,syncStatusMismatchPanel:jq,syncStatusMismatchItem:Pq,syncStatusEventFilters:Eq,syncStatusEventFilterActive:Nq,syncStatusEventsList:Mq,syncStatusEventItem:Dq,syncStatusEventItemError:Lq,syncStatusEventItemMuted:Oq,syncStatusEventLine:Bq,syncStatusFooter:Wq,syncStatusFooterPrimary:$q};function QI(e){return/\btaskforce session is invalid\b|\bauthenticated taskforce session is required\b/i.test(e||"")}function Fq(e){if(!e)return null;const t=e.snapshot;if(e.phase!=="ready"){if(t?.state.ownershipMode==="browser-gateway"&&e.phase!=="error")return null;const ce=e.phase==="error",Le=QI(e.errorMessage);return{header:{actionable:!0,status:ce?"attention":"syncing",syncEnabledLabel:"unknown",summary:ce?"The shared sync coordinator status is unavailable.":"Reading shared sync coordinator status.",recommendedAction:ce?Le?"Sign out and sign back in, then retry sync.":"Retry sync. If the coordinator remains unavailable, restart the local server.":"Wait for the coordinator status check to finish.",lastError:e.errorMessage||(ce?"Coordinator status unavailable.":"None")},pendingLocalChanges:"Unknown",incomingCloudChanges:"Not checked",stage:ce?"unavailable":"checking coordinator",lastPullAt:null,lastPushAt:null,lastSyncedAt:null,busy:e.phase==="attaching",repairBusy:!1,diagnostics:[{label:"Coordinator",value:e.errorMessage||e.phase}]}}if(!t||t.state.ownershipMode!=="server")return null;const r=t.workspace,n=r?.runner||null,s=n?.checkpoint?.checkpoint||null,i=r?.outbox||null,l=i?.operationStates,c=l?.stale||0,d=l?.blocked??i?.blocked??0,f=l?.retryScheduled||0,p=!!(i?.recovery&&i.recovery.state!=="completed"),g=i?.attachmentApplyObligations?.open||0,h=t.credential.status!=="ready",y=t.state.transitionState!=="idle",k=!n||!n.running||!n.acceptingWork||!s,b=s?.controlState==="error"||!!s?.lastError,C=s?.controlState==="retry-wait"||f>0,S=t.permits.recoveryObligations,w=s?.pendingV2Push||null,T=w?.lastBatchProgress||null,E=Math.max(0,(w?.frozenPayload.changes.length||0)-(T?.completedChanges||0)),x=!!(T&&(T.failureDomain==="content"||T.failureDomain==="mixed")&&E>0),N=!!(s?.syncEnabled&&s.syncPhase==="attach-cloud"&&!s.lastPullAt),v=!!(n?.queuedCommandCount||["starting","pulling","pushing","repairing","stopping"].includes(s?.controlState||"")||(l?.inFlight??i?.inFlight??0)>0),V=v||(i?.pending||0)>0,_=x&&!v,j=v,F=s?.controlState==="repairing";let z="healthy",M="Sync is healthy.",O="No action needed.",Z=s?.lastError||"None";if(h)z="attention",M="Sync is paused because the coordinator credential is unavailable.",O="Sign in again, then retry sync.";else if(y)z="syncing",M="Sync ownership is changing safely.",O="Wait for the coordinator transition to finish.";else if(k)z="attention",M="The shared sync runner is unavailable.",O="Retry sync. If the runner does not recover, restart the local server.";else if(g>0)z="attention",M=`${g} incoming attachment ${g===1?"change is":"changes are"} waiting for content.`,O=s&&!s.syncEnabled?"Turn on sync to resume automatic attachment hydration.":"Wait for the scheduled attachment hydration retry.",Z=i?.attachmentApplyObligations?.lastError||Z;else if(S>0||d>0||c>0||p)z="attention",M="Durable local changes need reconciliation.",O=s&&!s.syncEnabled?"Turn on sync, then press Repair to reconcile and replay supported changes.":"Press Repair to reconcile and replay supported changes.";else if(_){z="attention";const ce=T.failureDomain==="content"?"content":"push";M=`${T.failedChangeCount} ${ce} ${T.failedChangeCount===1?"change is":"changes are"} waiting to retry; ${E} total push ${E===1?"change remains":"changes remain"}.`,O=s&&!s.syncEnabled?"Turn on sync to resume the bounded content retry.":"Wait for the scheduled content retry, or press Retry now."}else s&&!s.syncEnabled?(z="off",M="Workspace sync is turned off.",O="Turn on sync when you are ready to connect this workspace.",Z="None"):b&&!v?(z="attention",M=s?.lastError||"The shared sync runner reported an error.",O="Press Retry now. If the same issue returns, press Repair."):C?(z="attention",M="Sync is waiting for a scheduled retry.",O="Wait for the retry, or press Retry now."):N?(z="attention",M="The initial cloud baseline has not completed.",O="Keep sync enabled until the first cloud check completes."):V&&(z="syncing",M="The shared sync runner is processing workspace changes.",O="Wait for the current transfer to finish.");const U=s?.lastPullAt?s.controlState==="pulling"?"Checking — total unknown":"No known backlog at last check":s?.controlState==="pulling"?"Checking — total unknown":"Not checked",ve=i?i.activeDepth+E:w?E:"Unknown",te=s?.controlState||"unavailable";return{header:{actionable:!0,status:z,syncEnabledLabel:s?.syncEnabled?"yes":"no",summary:M,recommendedAction:O,lastError:Z},pendingLocalChanges:ve,incomingCloudChanges:U,stage:te,lastPullAt:s?.lastPullAt||null,lastPushAt:s?.lastPushAt||null,lastSyncedAt:s?.lastSyncedAt||null,busy:j,repairBusy:F,diagnostics:[{label:"Coordinator",value:`Generation ${t.state.coordinatorGeneration}; server-owned`},{label:"Durable outbox",value:i?`${l?.pending??i.pending} pending, ${f} retry scheduled, ${l?.inFlight??i.inFlight} in flight, ${c} stale, ${d} blocked`:"Unavailable"},{label:"Recovery obligations",value:String(S)},{label:"Attachment apply obligations",value:i?.attachmentApplyObligations?`${i.attachmentApplyObligations.open} open, ${i.attachmentApplyObligations.due} due, ${i.attachmentApplyObligations.totalAttempts} attempts`:"Unavailable"},{label:"Content push backlog",value:x?`${T.failedChangeCount} blocked ${T.failureDomain==="content"?"content":"push"} ${T.failedChangeCount===1?"change":"changes"}; ${E} total push ${E===1?"change remains":"changes remain"}; ${T.completedBatches}/${T.totalBatches} batches settled`:"None"},{label:"Oldest actionable change",value:i?.oldestActionableAt||"None"},{label:"Local data version",value:String(t.state.localDataVersion)}]}}function Uq(e){switch(e){case"auth-required":return{summary:"Sync is paused until you sign in again.",recommendedAction:"Sign in, then press Sync to retry."};case"attach-cloud":return{summary:"This workspace still needs its first cloud pull before local pushes can run.",recommendedAction:"Keep this window open for the first cloud pull. If it seems stuck, press Repair."};case"provision-local":return{summary:"This workspace is still doing its first cloud upload before normal pulls can run.",recommendedAction:"Keep this window open until the first cloud upload finishes."};case"repair-active":return{summary:"Repair is already running for this workspace.",recommendedAction:"Wait for repair to finish before retrying sync."};case"retry-pending":return{summary:"Sync hit a temporary problem and is waiting for its scheduled retry.",recommendedAction:"Wait for the automatic retry, or press Sync to retry now."};case"lease-held":return{summary:"Another local window is already syncing this workspace.",recommendedAction:"Use a single local window for sync, or close the other syncing window."};case"invalid-workspace":return{summary:"Workspace setup is required before sync can run.",recommendedAction:"Open or create a named workspace before retrying sync."};case"cloud-auth-unconfigured":return{summary:"Cloud sync is unavailable because cloud authentication is not configured.",recommendedAction:"Configure cloud authentication before turning on sync."};case"runtime-not-local":return{summary:"Workspace sync controls are only available in the local runtime.",recommendedAction:"Open this workspace in the local app to manage sync."};case"sync-disabled":return{summary:"Workspace sync is currently turned off.",recommendedAction:"Turn on sync when you are ready to connect this workspace to cloud."};default:return null}}function zq(e){const t=e.runtimeMode==="local"&&e.isAuthenticated;if(t){const r=Math.max(0,Number(e.coordinatorRecoveryObligations||0)),n=Uq(e.retryBlockedReason||e.pullBlockedReason||e.pushBlockedReason||null);return r>0&&e.retryBlockedReason!=="auth-required"&&e.pullBlockedReason!=="auth-required"&&e.pushBlockedReason!=="auth-required"&&e.retryBlockedReason!=="repair-active"&&e.pullBlockedReason!=="repair-active"&&e.pushBlockedReason!=="repair-active"?{actionable:t,status:"attention",syncEnabledLabel:e.workspaceCloudSyncEnabled?"yes":"no",summary:`${r} durable sync recovery obligation${r===1?"":"s"} remain.`,recommendedAction:e.workspaceCloudSyncEnabled?"Press Repair to reconcile the durable sync ledger.":"Turn on sync, then press Repair to reconcile the durable sync ledger.",lastError:e.workspaceSyncError}:{actionable:t,status:e.workspaceSyncStatus,syncEnabledLabel:e.workspaceCloudSyncEnabled?"yes":"no",summary:n?.summary||e.workspaceSyncSummary,recommendedAction:n?.recommendedAction||e.workspaceSyncRecommendedAction,lastError:e.workspaceSyncError}}return{actionable:t,status:"off",syncEnabledLabel:"no",summary:"Sign in to enable workspace sync controls on this device.",recommendedAction:"Sign in to manage workspace sync for this workspace.",lastError:"Sign in to enable workspace sync controls on this device."}}function Hq({isOpen:e,theme:t,currentWorkspaceLabel:r,syncStatus:n,syncStatusMeta:s,workspaceCloudSyncEnabled:i,syncControlBusy:l,canManageWorkspaceSync:c,workspaceSyncSummary:d,workspaceSyncRecommendedAction:f,workspaceSyncRepairBusy:p,referenceMismatchCount:g,syncStageLabel:h,workspaceSyncPendingChanges:y,incomingCloudChanges:k,formattedLastSyncTime:b,formattedLastPullTime:C,formattedLastPushTime:S,syncLastError:w,activeReferenceMismatchSummaries:T,syncDiagnosticsSummary:E,syncEventRows:x,syncEventsListRef:N,workspaceSyncRepairQueued:v,workspaceSyncBusy:V,workspaceSyncCopied:_,coordinatorOwnershipMode:j,coordinatorOwnershipTransferBusy:F,coordinatorOwnershipTransferDisabled:z,onClose:M,onToggleWorkspaceSync:O,onRepairSync:Z,onCopyReport:U,onRetrySync:ve,onTransferCoordinatorOwnership:te}){const[ce,Le]=o.useState("all");o.useEffect(()=>{e&&Le("all")},[e]);const Ie=n==="attention",Ye=p?g>0?`Repair is reconciling cloud state, including ${g} reference mismatch${g===1?"":"es"}.`:"Repair is reconciling workspace state from the cloud.":Ie&&w!=="None"?w:Ie?d:"No active issue.",ge=!p&&Ie&&w!=="None",he=/\banother local taskforce process owns workspace synchronization\b/i.test(w),Ae=QI(w),ye=i&&!he&&!Ae&&(Ie||V||p||v),Ne=i&&!he&&!Ae&&(V||Ie||/\bpress sync\b/i.test(f)),ae=o.useMemo(()=>ce==="issues"?x.filter(W=>W.tone==="error"):x,[ce,x]),q=a.jsxs("div",{className:Et.syncStatusFooter,children:[a.jsxs("button",{className:R.cancelBtn,onClick:U,title:"Copy the current sync manager report for support or AI troubleshooting.",children:[a.jsx(pA,{size:14}),a.jsx("span",{children:_?"Copied":"Copy Report"})]}),a.jsxs("div",{className:Et.syncStatusFooterPrimary,children:[a.jsx("button",{className:R.cancelBtn,onClick:Z,disabled:!ye||p||v,title:p?"Repair is running now.":v?"Repair is queued and will start when the current sync finishes.":i?he?"Repair is unavailable in this process. Use the Taskforce process that owns workspace synchronization.":Ae?"Sign out and sign back in before running Repair.":V?"Queue a repair to start automatically when the current sync finishes.":ye?"Advanced recovery: clear the saved pull cursor and re-fetch cloud state from the beginning.":"Repair is available when sync needs attention.":"Turn on workspace sync before running Repair.",children:p?a.jsxs(a.Fragment,{children:[a.jsx(za,{size:14,className:R.spinner}),"Repairing..."]}):v?"Repair Queued":"Repair"}),a.jsx("button",{className:R.submitBtn,onClick:ve,disabled:!Ne||V,title:V?"A sync request is already running.":i?he?"Retry is unavailable in this process. Use the Taskforce process that owns workspace synchronization.":Ae?"Sign out and sign back in before retrying sync.":Ne?"Retry workspace synchronization now.":"No retry is currently needed.":"Turn on workspace sync before retrying.",children:V?a.jsxs(a.Fragment,{children:[a.jsx(za,{size:14,className:R.spinner}),"Syncing..."]}):a.jsxs(a.Fragment,{children:[a.jsx(uA,{size:14}),"Retry now"]})})]})]});return a.jsx(Do,{isOpen:e,onClose:M,title:"Sync Manager",size:"mdWide",theme:t,draggable:!0,className:Et.syncStatusOverlay,footer:q,children:a.jsxs("div",{className:`${dr.form} ${Et.syncStatusModal}`,children:[a.jsxs("div",{className:Et.syncStatusTop,children:[a.jsxs("div",{className:Et.syncStatusMetaHeader,children:[a.jsx("div",{className:Et.syncStatusBadge,style:{borderColor:s.border,background:s.background,color:s.color},children:s.label}),a.jsxs("span",{className:Et.syncStatusLabel,children:["Workspace: ",a.jsx("code",{children:r})]})]}),a.jsx("label",{className:Et.syncToggle,children:a.jsxs("span",{className:[Et.syncToggleControl,i?Et.syncToggleControlEnabled:Et.syncToggleControlDisabled,l?Et.syncToggleControlBusy:"",c?"":Et.syncToggleControlBlocked].filter(Boolean).join(" "),children:[a.jsx("input",{className:Et.syncToggleInput,type:"checkbox",role:"switch","aria-label":"Enable Sync",checked:i,disabled:!c||l,onChange:W=>O(W.target.checked)}),a.jsx("span",{className:`${Et.syncToggleState} ${Et.syncToggleStateOn}`,children:"On"}),a.jsx("span",{className:`${Et.syncToggleState} ${Et.syncToggleStateOff}`,children:"Off"}),a.jsx("span",{className:Et.syncToggleThumb})]})})]}),a.jsxs("section",{className:Et.syncStatusOverview,"aria-label":"Sync status",children:[a.jsxs("div",{className:Et.syncStatusOverviewRow,children:[a.jsx("span",{className:Et.syncStatusLabel,children:"Health"}),a.jsx("span",{className:Et.syncStatusSummaryValue,children:d})]}),a.jsxs("div",{className:Et.syncStatusOverviewRow,children:[a.jsx("span",{className:Et.syncStatusLabel,children:"Next step"}),a.jsx("span",{className:Et.syncStatusSummaryValue,children:f})]}),a.jsxs("div",{className:[Et.syncStatusOverviewRow,Et.syncStatusIssueRow,ge?Et.syncStatusIssueRowError:""].filter(Boolean).join(" "),children:[a.jsxs("span",{className:Et.syncStatusLabel,children:[ge?a.jsx(Rd,{size:12}):null,"Current issue"]}),a.jsx("span",{className:ge?Et.syncStatusValueError:Et.syncStatusValueMuted,children:Ye})]})]}),a.jsxs("div",{className:Et.syncStatusKeyMetrics,children:[a.jsxs("div",{className:Et.syncStatusCompactItem,children:[a.jsx("span",{className:Et.syncStatusLabel,children:"Outgoing local changes"}),a.jsx("span",{className:Et.syncStatusValue,children:y})]}),a.jsxs("div",{className:Et.syncStatusCompactItem,children:[a.jsx("span",{className:Et.syncStatusLabel,children:"Incoming cloud changes"}),a.jsx("span",{className:Et.syncStatusValue,children:k})]}),a.jsxs("div",{className:Et.syncStatusCompactItem,children:[a.jsx("span",{className:Et.syncStatusLabel,children:"Last cloud check"}),a.jsx("span",{className:Et.syncStatusValue,children:C})]})]}),a.jsxs("details",{className:Et.syncStatusAdvanced,children:[a.jsxs("summary",{children:[a.jsx("span",{children:"Advanced diagnostics"}),a.jsx(Nd,{size:16,"aria-hidden":"true"})]}),a.jsxs("div",{className:Et.syncStatusAdvancedContent,children:[a.jsxs("div",{className:Et.syncStatusCompactGrid,children:[a.jsxs("div",{className:Et.syncStatusCompactItem,children:[a.jsx("span",{className:Et.syncStatusLabel,children:"Stage"}),a.jsx("span",{className:Et.syncStatusValue,children:h})]}),a.jsxs("div",{className:Et.syncStatusCompactItem,children:[a.jsx("span",{className:Et.syncStatusLabel,children:"Last upload"}),a.jsx("span",{className:Et.syncStatusValue,children:S})]}),a.jsxs("div",{className:Et.syncStatusCompactItem,children:[a.jsx("span",{className:Et.syncStatusLabel,children:"Last successful transfer"}),a.jsx("span",{className:Et.syncStatusValue,children:b})]})]}),a.jsx("div",{className:Et.syncStatusDiagnosticsList,children:E.map(W=>a.jsxs("div",{className:Et.syncStatusDiagnosticRow,children:[a.jsx("span",{className:Et.syncStatusLabel,children:W.label}),a.jsx("span",{className:Et.syncStatusValue,children:W.value})]},W.label))}),j?a.jsxs("div",{className:Et.syncStatusOwnershipControl,children:[a.jsxs("div",{children:[a.jsx("span",{className:Et.syncStatusLabel,children:"Sync coordinator"}),a.jsx("span",{className:Et.syncStatusValue,children:j==="server"?"Local server owns background synchronization.":"This browser owns background synchronization."})]}),a.jsx("button",{className:R.cancelBtn,type:"button",onClick:te,disabled:F||z,title:F?"Sync ownership is transferring.":z?"Finish active sync or recovery work before transferring ownership.":j==="server"?"Return background synchronization to this browser.":"Move background synchronization to the local Taskforce server.",children:F?a.jsxs(a.Fragment,{children:[a.jsx(za,{size:14,className:R.spinner}),"Transferring..."]}):j==="server"?"Use browser sync":"Use server sync"})]}):null,g>0&&a.jsxs("div",{className:Et.syncStatusMismatchPanel,children:[a.jsxs("div",{className:Et.syncStatusPanelHeader,children:[a.jsx("span",{className:Et.syncStatusLabel,children:"Identifier integrity"}),a.jsxs("span",{className:Et.syncStatusPanelMeta,children:[g," mismatch",g===1?"":"es"," detected"]})]}),a.jsx("span",{className:Et.syncStatusValue,children:"Cloud-backed sync preserved the incoming cloud reference and renumbered the displaced local item."}),T.map(W=>a.jsxs("div",{className:Et.syncStatusMismatchItem,children:[a.jsx("span",{className:Et.syncStatusValue,children:W.pathLabel}),W.refsLabel?a.jsx("span",{className:Et.syncStatusPanelMeta,children:W.refsLabel}):null]},W.key))]})]})]}),a.jsxs("section",{className:Et.syncStatusEventsPanel,"aria-label":"Recent sync events",children:[a.jsxs("div",{className:Et.syncStatusPanelHeader,children:[a.jsx("span",{className:Et.syncStatusLabel,children:"Recent events"}),a.jsxs("div",{className:Et.syncStatusEventFilters,"aria-label":"Filter recent events",children:[a.jsx("button",{type:"button",className:ce==="all"?Et.syncStatusEventFilterActive:"","aria-pressed":ce==="all",onClick:()=>Le("all"),children:"All"}),a.jsx("button",{type:"button",className:ce==="issues"?Et.syncStatusEventFilterActive:"","aria-pressed":ce==="issues",onClick:()=>Le("issues"),children:"Issues"})]})]}),a.jsx("div",{ref:N,className:Et.syncStatusEventsList,children:ae.length>0?ae.map(W=>a.jsx("div",{className:[Et.syncStatusEventItem,W.tone==="error"?Et.syncStatusEventItemError:"",W.tone==="muted"?Et.syncStatusEventItemMuted:""].filter(Boolean).join(" "),children:a.jsx("span",{className:Et.syncStatusEventLine,children:W.text})},W.key)):a.jsx("div",{className:`${Et.syncStatusEventItem} ${Et.syncStatusEventItemMuted}`,children:a.jsx("span",{className:Et.syncStatusEventLine,children:"No issues in recent events."})})})]})]})})}function Gq({isOpen:e,theme:t,teamPlanMode:r,teamMgmtError:n,teamManagementTab:s,teamUsersLoading:i,teamUsers:l,teamActionBusyUserId:c,teamInviteFeedback:d,teamInviteEmail:f,teamInviteRole:p,teamInvitePermissionMode:g,teamInviteBusy:h,pendingInvites:y,teamAuditLoading:k,teamAuditEvents:b,teamAuditPage:C,teamAuditPages:S,teamAuditHasMore:w,onClose:T,onOpenMembersTab:E,onOpenInvitesTab:x,onOpenAuditTab:N,onMemberRoleChange:v,onMemberPermissionChange:V,onToggleMemberDisabled:_,onRevokeInvite:j,onRemoveMember:F,onInviteEmailChange:z,onInviteRoleChange:M,onInvitePermissionModeChange:O,onSubmitInvite:Z,onLoadAuditPrevious:U,onLoadAuditNext:ve}){return a.jsx(Do,{isOpen:e,onClose:T,title:"Team Management",size:"md",theme:t,draggable:!0,children:a.jsxs("div",{className:`${dr.form} ${Or.modalBody}`,children:[r==="personal"&&a.jsx("p",{className:Je.loginError,children:"Team management is only available in TEAM accounts."}),n&&a.jsx("p",{className:Je.loginError,children:n}),a.jsxs("div",{className:`${R.settingsTabs} tf-scrollbar tf-scrollbar--track-transparent tf-scrollbar--compact`,children:[a.jsx("button",{className:`${R.settingsTabBtn} ${s==="members"?R.settingsTabBtnActive:""}`,onClick:E,children:"Members"}),a.jsx("button",{className:`${R.settingsTabBtn} ${s==="invites"?R.settingsTabBtnActive:""}`,onClick:x,children:"Invites"}),a.jsx("button",{className:`${R.settingsTabBtn} ${s==="audit"?R.settingsTabBtnActive:""}`,onClick:N,children:"Audit Log"})]}),s==="members"&&a.jsxs("div",{className:lr.accountHubCard,children:[i&&a.jsx("p",{className:Or.mutedText,children:"Loading members..."}),!i&&l.length===0&&a.jsx("p",{className:Or.mutedText,children:"No users found."}),!i&&l.map(te=>a.jsxs("div",{className:Or.memberRow,children:[a.jsx("div",{className:Or.memberTitle,children:te.displayName||te.email}),a.jsxs("div",{className:lr.accountMenuMeta,children:[te.email," · ",te.status,te.disabled?" · deactivated":""]}),a.jsxs("div",{className:Or.memberActions,children:[a.jsxs("select",{className:`${R.input} ${Or.selectRole}`,value:te.role,onChange:ce=>v(te.userId,ce.target.value),disabled:c===te.userId,children:[a.jsx("option",{value:"owner",children:"Owner"}),a.jsx("option",{value:"admin",children:"Admin"}),a.jsx("option",{value:"member",children:"Member"})]}),te.role==="member"&&a.jsxs("select",{className:`${R.input} ${Or.selectPermission}`,value:te.permissionMode,onChange:ce=>V(te.userId,ce.target.value),disabled:c===te.userId,children:[a.jsx("option",{value:"read-write",children:"Read / Write"}),a.jsx("option",{value:"read-only",children:"Read Only"})]}),a.jsx("button",{className:R.cancelBtn,disabled:c===te.userId,onClick:()=>_(te.userId,!te.disabled),children:te.disabled?"Reactivate":"Deactivate"}),te.status==="invited"&&a.jsx("button",{className:R.cancelBtn,disabled:c===te.userId,onClick:()=>j(te.userId),children:"Revoke Invite"}),a.jsx("button",{className:R.cancelBtn,disabled:c===te.userId,onClick:()=>F(te.userId),children:"Remove"})]})]},te.userId))]}),s==="invites"&&a.jsxs("div",{className:lr.accountHubCard,children:[d&&a.jsx("p",{className:Or.sectionText,children:d}),a.jsxs("div",{className:R.pathInputGroup,children:[a.jsx("label",{className:`${R.label} ${Or.labelFixed}`,children:"Email"}),a.jsx("input",{className:R.input,value:f,onChange:te=>z(te.target.value),placeholder:"name@example.com"})]}),a.jsxs("div",{className:R.pathInputGroup,children:[a.jsx("label",{className:`${R.label} ${Or.labelFixed}`,children:"Role"}),a.jsxs("select",{className:`${R.input} ${Or.selectRole}`,value:p,onChange:te=>M(te.target.value==="admin"?"admin":"member"),children:[a.jsx("option",{value:"member",children:"Member"}),a.jsx("option",{value:"admin",children:"Admin"})]}),p==="member"&&a.jsxs("select",{className:`${R.input} ${Or.selectPermission}`,value:g,onChange:te=>O(te.target.value==="read-only"?"read-only":"read-write"),children:[a.jsx("option",{value:"read-write",children:"Read / Write"}),a.jsx("option",{value:"read-only",children:"Read Only"})]}),a.jsx("button",{className:R.submitBtn,disabled:h||!f.trim()||r!=="team",onClick:Z,children:h?"Sending...":"Send Invite"})]}),a.jsxs("div",{className:Or.inviteRow,children:[a.jsx("div",{className:Or.listHeading,children:"Pending Invites"}),y.length===0&&a.jsx("p",{className:Or.mutedText,children:"No pending invites."}),y.map(te=>a.jsxs("div",{className:Or.memberRow,children:[a.jsx("div",{className:Or.memberTitle,children:te.displayName||te.email}),a.jsxs("div",{className:lr.accountMenuMeta,children:[te.email," · ",te.role]})]},te.userId))]})]}),s==="audit"&&a.jsxs("div",{className:lr.accountHubCard,children:[k&&a.jsx("p",{className:Or.mutedText,children:"Loading audit entries..."}),!k&&b.length===0&&a.jsx("p",{className:Or.mutedText,children:"No audit events for this workspace."}),!k&&a.jsx("div",{className:Or.auditList,children:b.map(te=>a.jsxs("div",{className:Or.memberRow,children:[a.jsx("div",{className:lr.accountMenuMeta,children:new Date(te.createdAt).toLocaleString()}),a.jsx("div",{className:Or.memberTitle,children:te.action}),a.jsxs("div",{className:lr.accountMenuMeta,children:[te.actorUserId," (",te.actorRole,")"]})]},te.id))}),a.jsxs("div",{className:Or.auditPager,children:[a.jsx("button",{className:R.cancelBtn,disabled:k||C===0,onClick:U,children:"Previous"}),a.jsxs("span",{className:lr.accountMenuMeta,children:["Page ",C+1," of ",S]}),a.jsx("button",{className:R.cancelBtn,disabled:k||!w||C+1>=S,onClick:ve,children:"Next"})]})]}),a.jsx("div",{className:`${dr.formActions} ${Or.modalActionsEnd}`,children:a.jsx("button",{className:R.cancelBtn,onClick:T,children:"Close"})})]})})}const Vq="_title_j8q8h_1",Kq="_message_j8q8h_8",qq="_actions_j8q8h_14",wk={title:Vq,message:Kq,actions:qq};function Yq({isOpen:e,onKeepEditing:t,onDiscard:r,title:n="Unsaved Changes",message:s="Discard your unsaved workflow changes?",theme:i}){return a.jsx(Do,{isOpen:e,onClose:t,title:a.jsxs("span",{className:wk.title,children:[a.jsx(Rd,{size:18})," ",n]}),size:"sm",closeOnOverlayClick:!1,theme:i,footer:a.jsxs("div",{className:wk.actions,children:[a.jsx("button",{type:"button",className:"tf-button-secondary",onClick:t,"data-modal-initial-focus":!0,children:"Keep Editing"}),a.jsx("button",{type:"button",className:"tf-button-destructive",onClick:r,children:"Discard"})]}),children:a.jsx("p",{className:wk.message,children:s})})}const XI=e=>{const t=e.status||"task";return t==="done"||t==="cancelled"?"completed":t},Zq=(e,t,r)=>{if(XI(e)===t)return null;const s={status:t};return t==="task"||t==="on-hold"?(s.inProgress=!1,s.readyForReview=!1,s.completed=!1,s.cancelled=!1,s.completedAt=null,s):t==="in-progress"?(s.inProgress=!0,s.readyForReview=!1,s.completed=!1,s.cancelled=!1,s.completedAt=null,s):t==="review"?(s.inProgress=!1,s.readyForReview=!0,s.completed=!1,s.cancelled=!1,s.completedAt=null,s):t==="done"||t==="completed"?(s.status="done",s.inProgress=!1,s.readyForReview=!1,s.completed=!0,s.cancelled=!1,s.completedAt=r,s):(t==="cancelled"&&(s.status="cancelled"),s)},Jq=({targetTasks:e,overTaskId:t,isBelowOverItem:r})=>{if(!t)return e.length;const n=e.findIndex(s=>s.id===t);return n<0?e.length:n+(r?1:0)},e_=(e,t=new Map)=>{const r=new Map(t);return e.forEach((n,s)=>{r.set(n.id,{...r.get(n.id)||{},orderInDay:s})}),r},lw=e=>Array.from(e.entries()).map(([t,r])=>({taskId:t,updates:r})),t_=({sourceColumnId:e,targetColumnId:t,sourceTasks:r,updates:n})=>!e||e===t?n:e_(r,n),Qq=({activeTask:e,sourceColumnId:t,targetTasks:r,sourceTasks:n,insertAt:s})=>{const i=[...r];i.splice(s,0,e);let l=new Map;return i.forEach((c,d)=>{if(c.id===e.id){l.set(c.id,{...l.get(c.id)||{},...e.scheduledDate?{scheduledDate:null,scheduledWeekKey:null}:{},orderInDay:d});return}l.set(c.id,{...l.get(c.id)||{},orderInDay:d})}),l=t_({sourceColumnId:t,targetColumnId:"backlog",sourceTasks:n,updates:l}),lw(l)},Xq=({activeTask:e,targetTasks:t,insertAt:r})=>{const n=[...t];return n.splice(r,0,e),lw(e_(n))},eY=({activeTask:e,sourceColumnId:t,targetColumnId:r,targetTasks:n,sourceTasks:s,insertAt:i,scheduledDate:l,scheduledWeekKey:c})=>{const d=[...n];d.splice(i,0,e);let f=new Map;return d.forEach((p,g)=>{if(p.id===e.id){f.set(p.id,{...f.get(p.id)||{},scheduledDate:l,scheduledWeekKey:c,orderInDay:g});return}f.set(p.id,{...f.get(p.id)||{},orderInDay:g})}),f=t_({sourceColumnId:t,targetColumnId:r,sourceTasks:s,updates:f}),lw(f)},tY=({activeTask:e,sourceColumnId:t,targetColumnId:r,targetTasks:n,sourceTasks:s,overTaskId:i,isBelowOverItem:l,scheduleDates:c,parseToIsoWeekKey:d,todayDate:f})=>{const p=["mon","tue","wed","thu","fri","sat","sun"];if(!(r==="backlog"||r==="expired"||p.includes(r)))return null;const h=Jq({targetTasks:n,overTaskId:i,isBelowOverItem:l});if(r==="expired")return t!=="expired"?null:{kind:"updates",updates:Xq({activeTask:e,targetTasks:n,insertAt:h})};if(r==="backlog")return{kind:"updates",updates:Qq({activeTask:e,sourceColumnId:t,targetTasks:n,sourceTasks:s,insertAt:h})};if(!p.includes(r))return null;const y=c[r];return y?!(e.status==="done"||e.status==="cancelled")&&y<f?{kind:"blocked",reason:"Only completed work can be scheduled in the past."}:{kind:"updates",updates:eY({activeTask:e,sourceColumnId:t,targetColumnId:r,targetTasks:n,sourceTasks:s,insertAt:h,scheduledDate:y,scheduledWeekKey:d(y)}),selectedDate:y}:null},Uh="expired::",rY=new Map,aY=new Set;function nY({tasks:e,columns:t,groupBy:r,searchQuery:n,copiedId:s,taxonomies:i,types:l,priorities:c,assigneeOptions:d=[],onUpdateTask:f,onTaskClick:p,taskReferences:g,onCopyId:h,onToggleInProgress:y,onToggleReview:k,onToggleComplete:b,onToggleCancel:C,onSetStatus:S,onArchiveTask:w,onUnarchive:T,onDelete:E,allTasks:x=[],onAddTaskToColumn:N,emptyColumnMode:v="show",filterCategories:V=[],filterTypes:_=[],filterPriorities:j=[],filterStatus:F=[],filterAssignees:z=[],filtersReady:M=!0,scheduleFilteredTaskIds:O,categories:Z=[],compressed:U=!1,readOnlyMode:ve=null,recentlyChangedTaskIds:te=[],scheduleDates:ce,onScheduleDaySelected:Le,persistedScrollLeft:Ie,onScrollLeftChange:Ye,sortBy:ge="created",sortOrder:he="desc",planningDropTargets:Ae=null,onAssignTaskToWorkstream:ye,onAssignWorkstreamToInitiative:Ne,showTaskCardStatusLabel:ae=!1,workstreams:q=[],initiatives:W=[],workspaceId:K=null,deletedTaskRecordByTaskId:Re=rY,selectedDeletedRecordIds:we=aY,onDeletedSelectionChange:ie}){const[Q,H]=o.useState(null),[se,Pe]=o.useState(!1),[ue,ne]=o.useState(!1),Me=o.useMemo(()=>new Set(te),[te]),pe=o.useMemo(()=>new Map(q.map(je=>[je.id,je])),[q]),le=o.useMemo(()=>new Map(W.map(je=>[je.id,je])),[W]),Ce=o.useCallback(je=>{const ot=je.workstreamId&&pe.get(je.workstreamId)||null,pt=ot?.initiativeId&&le.get(ot.initiativeId)||null;return{taskWorkstream:ot,taskInitiative:pt}},[le,pe]),P=o.useMemo(()=>new Set(e.map(je=>je.id)),[e]),ee=o.useCallback(je=>je.startsWith(Uh)?je.slice(Uh.length):je,[]),Se=o.useCallback(je=>P.has(ee(je)),[P,ee]),_e=o.useMemo(()=>new Set(O||[]),[O]),ke=o.useRef(null),Ze=o.useCallback(je=>{const ot=je?.data?.current||{},pt=String(je?.id||"");let Ve=String(ot.taskId||""),lt=String(ot.workstreamId||"");!Ve&&pt&&Se(pt)&&(Ve=ee(pt)),!lt&&pt.startsWith("planning-workstream:")&&(lt=pt.slice(20));let It=String(ot.type||"");return It||(Ve?It="task-card":lt&&(It="planning-workstream")),{activeId:pt,type:It,taskId:Ve,workstreamId:lt}},[ee,Se]),st=vv(Mf(wv,{activationConstraint:{distance:10}}),Mf(vA,{coordinateGetter:kA})),at=XI,oe=o.useMemo(()=>{const je=new Date,ot=je.getFullYear(),pt=String(je.getMonth()+1).padStart(2,"0"),Ve=String(je.getDate()).padStart(2,"0");return`${ot}-${pt}-${Ve}`},[]),We=o.useMemo(()=>{const je=Ve=>{const lt=Ve.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!lt)return null;const It=new Date(Date.UTC(Number(lt[1]),Number(lt[2])-1,Number(lt[3]))),wt=It.getUTCDay()||7;It.setUTCDate(It.getUTCDate()+4-wt);const $t=new Date(Date.UTC(It.getUTCFullYear(),0,1)),Yt=Math.ceil(((It.getTime()-$t.getTime())/864e5+1)/7);return`${It.getUTCFullYear()}-W${String(Yt).padStart(2,"0")}`};return{dates:{...(()=>{const Ve=new Date,lt=Ve.getDay(),It=lt===0?-6:1-lt,wt=new Date(Ve);wt.setDate(Ve.getDate()+It);const $t=er=>{const _t=er.getFullYear(),Dt=String(er.getMonth()+1).padStart(2,"0"),Tt=String(er.getDate()).padStart(2,"0");return`${_t}-${Dt}-${Tt}`},Yt={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return["mon","tue","wed","thu","fri","sat","sun"].forEach((er,_t)=>{const Dt=new Date(wt);Dt.setDate(wt.getDate()+_t),Yt[er]=$t(Dt)}),Yt})(),...ce||{}},parseToIsoWeekKey:je}},[ce]),G=je=>{const ot=je.scheduledDate||null;return ot?new Map([[We.dates.mon,"mon"],[We.dates.tue,"tue"],[We.dates.wed,"wed"],[We.dates.thu,"thu"],[We.dates.fri,"fri"],[We.dates.sat,"sat"],[We.dates.sun,"sun"]]).get(ot)||"__offweek":"backlog"},Be=o.useMemo(()=>{if(r==="schedule")return[];const je=new Set(t.map(lt=>String(lt.value))),ot=new Set(t.map(lt=>lt.label)),pt=[],Ve=lt=>{const It=r==="status"?at(lt):lt[r],wt=String(It??"");if(!wt||je.has(wt)||ot.has(wt))return null;if(r==="category"){const $t=Z.find(Yt=>Yt.value===wt||Yt.label===wt);return{value:wt,label:$t?.label||wt,icon:$t?.icon||"Folder",color:$t?.color}}if(r==="type"){const $t=l?.find(Yt=>Yt.value===wt||Yt.label===wt);return{value:wt,label:$t?.label||wt,icon:$t?.icon||"CheckSquare",color:$t?.color}}if(r==="priority"){const $t=c?.find(Yt=>Number(Yt.value)===Number(wt));return{value:Number.isFinite(Number(wt))?Number(wt):wt,label:$t?.label||wt,icon:$t?.icon||"Flag",color:$t?.color}}if(r==="complexity")return{value:Number.isFinite(Number(wt))?Number(wt):wt,label:wt,icon:"Gauge"};if(r==="status")return{value:wt,label:wt,icon:"Circle"};if(r==="assignee"){const $t=d.find(Yt=>Yt.value===wt);return{value:wt,label:$t?.label||wt,icon:$t?.icon==="HelpCircle"?"Circle":$t?.icon,color:$t?.color}}return{value:wt,label:wt}};for(const lt of e){const It=Ve(lt);It&&(pt.push(It),je.add(String(It.value)),ot.add(It.label))}return pt},[d,Z,r,t,c,e,l]),Xe=o.useMemo(()=>[...t,...Be],[Be,t]),ze=o.useMemo(()=>{const je=new Map;for(const ot of Xe)je.set(String(ot.value),ot),je.has(ot.label)||je.set(ot.label,ot);return je},[Xe]),qe=o.useMemo(()=>{const je={};return Xe.forEach(pt=>{je[String(pt.value)]=0}),(x.length>0?x:e).forEach(pt=>{let Ve="";if(r==="status")Ve=at(pt);else if(r==="schedule")Ve=G(pt);else{const It=pt[r];Ve=String(It??"")}const lt=ze.get(Ve);if(lt&&je[String(lt.value)]++,r==="schedule"){const It=pt.status==="done"||pt.status==="cancelled";pt.scheduledDate&&!It&&pt.scheduledDate<oe&&ze.has("expired")&&(je.expired=(je.expired||0)+1)}}),je},[x,e,Xe,r,ze,oe]),Te=o.useMemo(()=>{const je={};if(Xe.forEach(ot=>{je[String(ot.value)]=[]}),e.forEach(ot=>{let pt="";if(r==="status")pt=at(ot);else if(r==="schedule")pt=G(ot);else{const lt=ot[r];pt=String(lt??"")}const Ve=ze.get(pt);if(Ve){if(r==="schedule"&&String(Ve.value)==="backlog"&&!_e.has(ot.id))return;je[String(Ve.value)].push(ot)}if(r==="schedule"){const lt=ot.status==="done"||ot.status==="cancelled";ot.scheduledDate&&!lt&&ot.scheduledDate<oe&&je.expired&&je.expired.push(ot)}}),r==="schedule"){const ot=(Ve,lt)=>{const It=typeof Ve.orderInDay=="number"?Ve.orderInDay:Number.MAX_SAFE_INTEGER,wt=typeof lt.orderInDay=="number"?lt.orderInDay:Number.MAX_SAFE_INTEGER;return It!==wt?It-wt:String(Ve.createdAt||"").localeCompare(String(lt.createdAt||""))},pt=(Ve,lt)=>ng(Ve,lt,ge,he,i);Object.keys(je).forEach(Ve=>{if(Ve==="backlog"||Ve==="expired"){je[Ve].sort(pt);return}je[Ve].sort(ot)})}return je},[e,Xe,r,ze,_e,oe,ge,he,i]),fe=Q?ee(Q):null,Ee=fe?e.find(je=>je.id===fe):null,$e=o.useRef(null),rt=o.useRef(null),kt=o.useRef({pointerId:null,startX:0,startY:0,startScrollLeft:0,didPan:!1}),xe=o.useRef(-1),St=(je,ot)=>M?r==="category"?!V.includes(String(je)):r==="type"?!_.includes(String(je)):r==="priority"?!j.some(pt=>Number(pt)===Number(je)):r==="status"?String(je)==="completed"?!F.includes("done")&&!F.includes("cancelled"):!F.includes(String(je)):r==="assignee"?!z.includes(String(je)):!1:!1,jt=o.useMemo(()=>{let Ve=0;return Xe.forEach((lt,It)=>{const wt=Te[String(lt.value)]||[],$t=St(lt.value,lt.label),Yt=r!=="schedule"&&v==="hide"&&wt.length===0;if($t||Yt)return;const qt=v==="collapse"&&wt.length===0;Ve+=qt?72:320,Ve+=4}),Ve},[Xe,Te,v,r,V,_,j,F,z,M]),$=o.useCallback(je=>{if(!Ye)return;const ot=Math.max(0,Math.round(je));ot!==xe.current&&(xe.current=ot,Ye(ot))},[Ye]);o.useEffect(()=>{const je=$e.current,ot=rt.current;if(!je||!ot)return;let pt=!1,Ve=!1;const lt=()=>{!je||Ve||(pt=!0,je.scrollLeft=ot.scrollLeft,$(ot.scrollLeft),setTimeout(()=>pt=!1,0))},It=()=>{!ot||pt||(Ve=!0,ot.scrollLeft=je.scrollLeft,$(je.scrollLeft),setTimeout(()=>Ve=!1,0))};return ot.addEventListener("scroll",lt),je.addEventListener("scroll",It),()=>{ot.removeEventListener("scroll",lt),je.removeEventListener("scroll",It)}},[$]);const Ke=o.useRef(!1);o.useEffect(()=>{if(Ke.current)return;if(typeof Ie!="number"||!Number.isFinite(Ie)){Ke.current=!0;return}const je=$e.current,ot=rt.current;if(!je||!ot)return;const pt=Math.max(0,je.scrollWidth-je.clientWidth),Ve=Math.min(Math.max(0,Ie),pt);je.scrollLeft=Ve,ot.scrollLeft=Ve,Ke.current=!0},[Ie,jt]),o.useEffect(()=>{const je=()=>{const ot=$e.current;if(!ot){ne(!1);return}ne(ot.scrollWidth>ot.clientWidth+4)};return je(),window.addEventListener("resize",je),()=>{window.removeEventListener("resize",je)}},[jt,Xe.length,Te]),o.useEffect(()=>{const je=pt=>{const Ve=kt.current;if(Ve.pointerId===null||Ve.pointerId!==pt.pointerId)return;const lt=pt.clientX-Ve.startX,It=pt.clientY-Ve.startY;if(!Ve.didPan){if(Math.abs(lt)<7||Math.abs(lt)<Math.abs(It))return;Ve.didPan=!0,Pe(!0),document.body.style.userSelect="none"}const wt=Ve.startScrollLeft-lt;$e.current&&($e.current.scrollLeft=wt),rt.current&&(rt.current.scrollLeft=wt),pt.preventDefault()},ot=()=>{const pt=kt.current;pt.pointerId!==null&&(pt.pointerId=null,pt.didPan=!1,se&&(Pe(!1),document.body.style.userSelect=""))};return window.addEventListener("pointermove",je),window.addEventListener("pointerup",ot),window.addEventListener("pointercancel",ot),()=>{window.removeEventListener("pointermove",je),window.removeEventListener("pointerup",ot),window.removeEventListener("pointercancel",ot),document.body.style.userSelect=""}},[se]);const Qe=je=>{!ue||je.target?.closest('button, a, input, select, textarea, [role="button"], [data-no-header-pan="true"]')||(kt.current.pointerId=je.pointerId,kt.current.startX=je.clientX,kt.current.startY=je.clientY,kt.current.startScrollLeft=$e.current?.scrollLeft||0,kt.current.didPan=!1)},Ge=je=>{H(je.active.id)},At=je=>{const ot=Ze(je.active),pt=String(je.over?.data?.current?.type||"");ot.type==="task-card"&&pt.startsWith("planning-")?ke.current=`${String(je.over?.id||"")}:${pt}`:ke.current&&(ke.current=null)},Nt=je=>{const{active:ot,over:pt}=je;ke.current=null,H(null);const Ve=Ze(ot),lt=Ve.type,It=String(pt?.data?.current?.type||""),wt=Ve.taskId,$t=Ve.workstreamId,Yt=String(pt?.data?.current?.workstreamId||""),qt=String(pt?.data?.current?.initiativeId||"");if(lt==="task-card"&&It==="planning-workstream-target"&&wt&&Yt){ye?.(wt,Yt);return}if(lt==="planning-workstream"){if(It==="planning-initiative-target"&&$t&&qt){Ne?.($t,qt);return}return}const er=String(ot.id),_t=pt?String(pt.id):null,Dt=ee(er);_t&&ee(_t);const Tt=e.find(Ft=>Ft.id===Dt);if(!Tt||!_t)return;const Xr=Bt(er),la=String(ot?.data?.current?.sortable?.containerId||"")||Xr,ea=String(pt?.data?.current?.sortable?.containerId||"")||Bt(_t);if(!ea)return;const Ur=ze.get(ea)||Xe.find(Ft=>String(Ft.value)===ea||Ft.label===ea);if(Ur){if(r==="schedule"){const Rt=String(Ur.value),_r=_t&&Se(_t)?ee(_t):null,u=pt?.rect,pr=ot.rect.current.translated||ot.rect.current.initial,Yr=!!(u&&pr&&pr.top+pr.height/2>u.top+u.height/2),tr=(Te[Rt]||[]).filter(zr=>zr.id!==Dt),$r=(Te[String(la)]||[]).filter(zr=>zr.id!==Dt),Lt=tY({activeTask:Tt,sourceColumnId:la,targetColumnId:Rt,targetTasks:tr,sourceTasks:$r,overTaskId:_r,isBelowOverItem:Yr,scheduleDates:We.dates,parseToIsoWeekKey:We.parseToIsoWeekKey,todayDate:oe});if(!Lt)return;if(Lt.kind==="blocked"){window.alert(Lt.reason);return}Lt.updates.forEach(({taskId:zr,updates:Ir})=>f(zr,Ir)),Lt.selectedDate&&Le?.(Lt.selectedDate);return}let Ft=Ur.value;if(r==="status"){const Rt=String(Ft),_r=Zq(Tt,Rt,new Date().toISOString());_r&&f(Tt.id,_r);return}(r==="priority"||r==="complexity")&&(Ft=Number(Ft));const ft=Tt[r];if(String(ft??"")!==String(Ft??"")){const Rt={[r]:Ft};f(Tt.id,Rt)}}},Bt=je=>{if(ze.has(je)){const Ve=ze.get(je);return Ve?String(Ve.value):je}if(r==="schedule"&&je.startsWith(Uh))return"expired";const ot=ee(je),pt=e.find(Ve=>Ve.id===ot);if(pt){let Ve="";r==="status"?Ve=at(pt):r==="schedule"?Ve=G(pt):Ve=String(pt[r]??"");const lt=ze.get(Ve);return lt?String(lt.value):null}return null},Qt={sideEffects:E0({styles:{active:{opacity:"0"}}})},Xt=je=>{try{const ot=P0(je);if(ot.length>0){const pt=ot.find(Yt=>String(Yt.id).startsWith("planning-"));if(pt)return[pt];const Ve=je.pointerCoordinates;if(!Ve)return[ot[0]];const lt=ot.filter(Yt=>{const qt=String(Yt.id);return Se(qt)&&qt!==Q});if(lt.length===0){const qt=ot.filter(Dt=>{const Tt=String(Dt.id);return!Se(Tt)}).find(Dt=>!!Bt(String(Dt.id)))||null,er=qt?Bt(String(qt.id)):null,_t=(je.droppableContainers||[]).filter(Dt=>{const Tt=String(Dt.id);return!Se(Tt)||Tt===Q?!1:er?Bt(Tt)===er:!0});if(_t.length>0){const Dt=ob({...je,droppableContainers:_t});if(Dt.length>0)return[Dt[0]]}return qt?[qt]:[ot[0]]}const It=lt;let wt=It[0],$t=Number.POSITIVE_INFINITY;for(const Yt of It){const qt=je.droppableRects?.get(Yt.id);if(!qt)continue;const er=qt.left+qt.width/2,_t=qt.top+qt.height/2,Dt=Ve.x-er,Tt=Ve.y-_t,Xr=Dt*Dt+Tt*Tt;Xr<$t&&($t=Xr,wt=Yt)}return[wt]}return ob(je)}catch(ot){return console.error("[TaskKanban] collision detection error",ot),[]}},nt=o.useCallback((je,ot)=>f(je.id,{assignee:ot}),[f]),Mt=o.useCallback((je,ot)=>ye?ye(je.id,ot):f(je.id,{workstreamId:ot}),[ye,f]),ur=o.useMemo(()=>({searchQuery:n,copiedId:s,taxonomies:i,types:l,priorities:c,workspaceId:K,assigneeOptions:d,workstreams:q,onAssigneeChange:nt,onWorkstreamChange:Mt,onCopyId:h,onToggleInProgress:y,onToggleReview:k,onToggleComplete:b,onToggleCancel:C,onSetStatus:S,onArchiveTask:w,onUnarchive:T,onDelete:E,taskReferences:g,categories:Z,readOnlyMode:ve,resolveTaskHierarchy:Ce,groupBy:r,showStatusLabel:ae,deletedTaskRecordByTaskId:Re,selectedDeletedRecordIds:we,onDeletedSelectionChange:ie}),[d,Z,s,Re,r,nt,Mt,w,h,E,ie,S,C,b,y,k,T,c,ve,Ce,n,we,ae,g,i,l,K,q]);return a.jsxs(bv,{sensors:st,collisionDetection:Xt,onDragStart:Ge,onDragOver:At,onDragEnd:Nt,onDragCancel:je=>{ke.current=null,H(null)},children:[Ae,a.jsxs("div",{className:R.kanbanWrapper,children:[a.jsx("div",{ref:rt,className:`${R.kanbanTopScroll} tf-scrollbar`,children:a.jsx("div",{className:R.kanbanTopScrollSpacer,style:{width:`${jt}px`}})}),a.jsx("div",{className:R.kanbanContainer,ref:$e,children:Xe.map(je=>{const ot=Te[String(je.value)]||[],pt=St(je.value,je.label),Ve=r!=="schedule"&&v==="hide"&&ot.length===0,lt=r==="schedule",It=lt&&Xe.some(Tt=>String(Tt.value)==="backlog"),wt=lt&&String(je.value)==="backlog",$t=lt&&String(je.value)==="expired",Yt=Te.backlog||[],er=v==="collapse"&&Yt.length===0?72:320,_t=wt?0:$t?It?er+4:0:void 0,Dt=wt?6:$t?5:void 0;return pt||Ve?null:a.jsx(sY,{id:String(je.value),title:je.label,color:je.color,icon:je.icon,assigneeOption:r==="assignee"?d.find(Tt=>String(Tt.value)===String(je.value)):void 0,tasks:ot,activeId:Q,activeTaskId:fe,totalCount:qe[String(je.value)],onAddTask:()=>N?.(r,je.value),onTaskClick:p,commonCardProps:ur,changedTaskIdSet:Me,collapseEmpty:v==="collapse",compressed:U,onHeaderPointerDown:Qe,isHeaderPanning:se,headerPanEnabled:ue,stickyLeft:_t,stickyZIndex:Dt,isPast:!!je.isPast,isSelected:!!je.isSelected,isWeekend:!!je.isWeekend,disableSorting:!1,scheduleDate:r==="schedule"?We.dates[String(je.value)]:void 0,onScheduleDaySelected:Le},String(je.value))})})]}),tc.createPortal(a.jsx(j0,{dropAnimation:Qt,children:Ee?(()=>{const{taskWorkstream:je,taskInitiative:ot}=Ce(Ee);return a.jsx(Hf,{task:Ee,taskWorkstream:je,taskInitiative:ot,isOverlay:!0,...ur,isArchived:Ee.isArchived,categories:Z,compressed:U,isRecentlyChanged:Me.has(Ee.id)})})():null}),document.body)]})}const sY=Y.memo(function({id:t,title:r,color:n,icon:s,assigneeOption:i,tasks:l,activeId:c=null,activeTaskId:d=null,totalCount:f,onAddTask:p,onTaskClick:g,commonCardProps:h,changedTaskIdSet:y,collapseEmpty:k,compressed:b,onHeaderPointerDown:C,isHeaderPanning:S=!1,headerPanEnabled:w=!1,stickyLeft:T,stickyZIndex:E,isPast:x=!1,isSelected:N=!1,isWeekend:v=!1,disableSorting:V=!1,scheduleDate:_,onScheduleDaySelected:j}){const{setNodeRef:F}=Iv({id:t,data:{type:"Column"}}),z=k&&l.length===0,M=d?l.filter(te=>te.id!==d):l,O=typeof T=="number",Z=o.useRef(null),U=te=>t==="expired"?`${Uh}${te}`:te,ve=te=>{if(!_||!j)return;const ce=te.target;ce&&(ce.closest('[data-task-card="true"]')||ce.closest(`.${R.kanbanCardWrapper}`)||j(_))};return a.jsxs("div",{ref:F,className:`${R.kanbanColumn} ${z?R.kanbanColumnCollapsed:""} ${O?R.kanbanColumnSticky:""} ${x?R.kanbanColumnPast:""} ${N?R.kanbanColumnSelectedDay:""} ${v?R.kanbanColumnWeekend:""}`,style:O?{left:`${T}px`,zIndex:E??4}:void 0,onClick:ve,children:[a.jsxs("div",{className:`${R.kanbanHeader} ${w?R.kanbanHeaderDraggable:""} ${S?R.kanbanHeaderPanning:""}`,style:{borderTopColor:rn(n)||"var(--color-purple)"},onPointerDown:C,children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",minWidth:0,overflow:"hidden"},children:[i?a.jsx(Lg,{option:i,size:20}):(()=>{const te=s&&Hu[s]?Hu[s]:Qi,ce=rn(n)||"var(--color-purple)";return a.jsx(te,{size:16,style:{color:ce}})})(),!z&&a.jsx("span",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:r})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"8px",flexShrink:0},children:[(!z||f>0)&&a.jsx("span",{className:R.kanbanCount,children:z?f:`${l.length} / ${f}`}),!h.readOnlyMode&&a.jsx("button",{className:"tf-control-icon tf-control-icon-compact",onClick:te=>{te.stopPropagation(),p()},title:`Add task to ${r}`,"aria-label":`Add task to ${r}`,"data-no-header-pan":"true",children:a.jsx(ri,{size:14})})]})]}),a.jsx("div",{className:R.kanbanDroppable,children:a.jsx("div",{className:`${R.kanbanDroppableScroll} ${R.appScrollbar} tf-scrollbar`,ref:Z,children:V?M.map(te=>a.jsx("div",{className:R.kanbanCardWrapper,children:(()=>{const{taskWorkstream:ce,taskInitiative:Le}=h.resolveTaskHierarchy?.(te)||{},Ie=h.deletedTaskRecordByTaskId?.get(te.id);return a.jsx(Hf,{task:te,taskWorkstream:ce,taskInitiative:Le,onClick:g,...h,isArchived:te.isArchived,readOnlyMode:h.readOnlyMode||null,compressed:b,isRecentlyChanged:!1,selectable:!!(Ie&&h.onDeletedSelectionChange),selected:!!(Ie&&h.selectedDeletedRecordIds?.has(Ie.id)),onSelectionChange:Ie?Ye=>h.onDeletedSelectionChange?.(Ie.id,Ye):void 0})})()},te.id)):a.jsx(Sv,{id:t,items:M.map(te=>U(te.id)),strategy:Av,children:M.map(te=>a.jsx(oY,{sortableId:U(te.id),task:te,onClick:g,commonCardProps:h,compressed:b,isRecentlyChanged:y.has(te.id)},U(te.id)))})})})]})}),oY=Y.memo(function({sortableId:t,task:r,onClick:n,commonCardProps:s,compressed:i,isRecentlyChanged:l=!1}){const c=!!s?.readOnlyMode,{attributes:d,listeners:f,setNodeRef:p,transform:g,transition:h,isDragging:y}=Cv({id:t,disabled:c,data:{type:"task-card",taskId:r.id}}),k={transform:Sg.Transform.toString(g),transition:h,opacity:y?0:1,pointerEvents:y?"none":"auto"},b=s?.groupBy==="schedule",C=!b&&l;return a.jsx("div",{ref:p,style:k,...c?{}:d,...c?{}:f,className:`${R.kanbanCardWrapper} ${C?R.kanbanCardWrapperRaised:""}`,children:(()=>{const{taskWorkstream:S,taskInitiative:w}=s.resolveTaskHierarchy?.(r)||{},T=s.deletedTaskRecordByTaskId?.get(r.id);return a.jsx(Hf,{task:r,taskWorkstream:S,taskInitiative:w,onClick:n,...s,isArchived:r.isArchived,readOnlyMode:s?.readOnlyMode||null,compressed:i,isRecentlyChanged:b?!1:l,selectable:!!(T&&s.onDeletedSelectionChange),selected:!!(T&&s.selectedDeletedRecordIds?.has(T.id)),onSelectionChange:T?E=>s.onDeletedSelectionChange?.(T.id,E):void 0})})()})});function iY(e,t,r){const n=String(t);if(e==="category"){const s=r.categories.find(i=>String(i.value)===n||i.label===n);return s?{category:s.label}:{}}return e==="type"?{type:n}:e==="priority"?Number.isFinite(Number(t))?{priority:Number(t)}:{}:e==="complexity"?Number.isFinite(Number(t))?{complexity:Number(t)}:{}:e==="assignee"?n.trim().length>0?{assignee:n}:{}:e==="status"?n==="completed"?{status:"done"}:n==="task"||n==="on-hold"||n==="in-progress"||n==="review"||n==="done"||n==="cancelled"?{status:n}:{}:e==="schedule"?n==="backlog"||n==="expired"?{}:{scheduledDate:n}:{}}function cY({authUserId:e,taskScope:t,workspaceId:r}){const[n,s]=o.useState(null);o.useEffect(()=>{s(null)},[e,r]),o.useEffect(()=>{t!=="open"&&s(null)},[t]);const i=o.useCallback(c=>{s(d=>d===c?null:c)},[]),l=o.useCallback(()=>{s(null)},[]);return{taskHeaderQuickFilter:n,toggleTaskHeaderQuickFilter:i,clearTaskHeaderQuickFilter:l}}function lY(e,t,r,n){return e.status==="done"||e.status==="cancelled"||String(e.assignee||"").trim()!==r?!1:t==="overdue"?!!(e.dueDate&&e.dueDate<n):!0}function fg(e,t){return e==="deleted"?!1:e==="archived"?t:!t}function PS(e,t){return t===null?e:e.filter(r=>t.has(r.id))}function dY(e,t,r){const n=t.filter(c=>fg(r,!!c.isArchived)),s=r==="deleted"?[]:e.filter(c=>fg(r,!!c.isArchived)?!0:r!=="archived"?!1:n.some(d=>d.initiativeId===c.id)).map(c=>({...c,workstreams:n.filter(d=>d.initiativeId===c.id)})),i=n.filter(c=>!c.initiativeId),l=[...s.flatMap(c=>c.workstreams),...i];return{initiatives:s,standaloneWorkstreams:i,visibleWorkstreams:l,initiativeById:new Map(s.map(c=>[c.id,c])),workstreamById:new Map(l.map(c=>[c.id,c]))}}function r_(e){return typeof e.occurredAt=="string"&&e.occurredAt.trim().length>0?e.occurredAt:"unknown-time"}function uY(e){return typeof e.eventType=="string"&&e.eventType.trim().length>0?e.eventType.trim():"sync"}function pY(e){const t=jg(e.details),r=t?t.source:null;return typeof r=="string"?r.trim():""}function ES(e){const t=String(e||"").trim();switch(t){case"auth-required":return"sign in required";case"lease-held":return"another window is already syncing";case"sync-disabled":return"sync is turned off";case"attach-cloud":return"initial cloud pull required";case"provision-local":return"initial cloud upload required";default:return t.length>0?t.replace(/-/g," "):"blocked"}}function NS(e){const t=String(e||"").trim();switch(t){case"attach-cloud":return"initial cloud pull";case"provision-local":return"initial cloud upload";case"active":return"active sync";case"error":return"error recovery";case"idle":return"idle sync";default:return t.length>0?t.replace(/-/g," "):"sync"}}function mg(e){if(e==null)return null;const t=Number(e);return Number.isFinite(t)?Math.max(0,Math.floor(t)):null}function MS(e,t,r){const n=mg(e);if(n===null)return null;const s=mg(t),i=n===1&&(s===null||s===1)?r:`${r}s`;return`${n}${s===null?"":`/${s}`} ${i}`}function fY(e,t){const r=mg(e);if(r===null)return null;const n=r>=1024*1024?`${(r/(1024*1024)).toFixed(1)} MiB`:r>=1024?`${(r/1024).toFixed(1)} KiB`:`${r} B`;return String(t||"")==="content-bodies"?`${n} content`:n}function mY(e){const t=r_(e),r=jg(e.details),n=pY(e);if(n==="server-runner.transfer"){const s=r?.transfer&&typeof r.transfer=="object"?r.transfer:{},i=String(s.direction||"").trim(),l=String(s.operation||e.eventType||"sync").trim(),c=String(s.outcome||e.status||"").trim()==="error"?"failed":"succeeded",d=[MS(s.processedChanges,s.knownTotalChanges,"change"),MS(s.processedPages,s.knownTotalPages,"page"),fY(s.transferredBytes,s.transferredBytesScope)].filter(g=>!!g),f=mg(s.durationMs),p=c==="failed"&&typeof e.errorMessage=="string"&&e.errorMessage.trim()?`: ${e.errorMessage.trim()}`:"";return`${t} ${i?`${i} `:""}${l} ${c}${d.length>0?` (${d.join(", ")})`:""}${f===null?"":` in ${f}ms`}${p}`}return n==="retry.blocked"?`${t} manual retry blocked: ${ES(r?.reason)} during ${NS(r?.phase)}`:n==="repair.started"?`${t} manual repair started: ${NS(r?.repairPhase)} selected`:n==="repair.blocked"?`${t} manual repair blocked: ${ES(r?.reason)}`:null}function Gu(e,t=0){const r=String(e.id??"").trim();return r?`id:${r}`:[String(e.occurredAt||"").trim()||"unknown-time",String(e.eventType||"").trim()||"sync",String(e.status||"").trim()||"unknown-status",String(e.statusCode??""),String(e.changeCount??""),String(e.requestMs??""),String(e.errorMessage||"").trim(),xC(e.details),String(t)].join("|")}function hY(e,t,r=15){const n=new Map;for(const[s,i]of e.entries())n.set(Gu(i,s),i);for(const[s,i]of t.entries())n.set(Gu(i,s),i);return Array.from(n.values()).sort((s,i)=>String(i.occurredAt||"").localeCompare(String(s.occurredAt||""))).slice(0,Math.max(1,r))}function gY(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(Gu(e[r],r)!==Gu(t[r],r))return!1;return!0}function a_(e){const t=mY(e);if(t)return t;const r=r_(e),n=uY(e),s=e.status==="error"?"failed":"succeeded",i=Number(e.changeCount),l=Number.isFinite(i)?` (${Math.max(0,Math.floor(i))} change${Math.floor(i)===1?"":"s"})`:"",c=Number(e.requestMs),d=Number.isFinite(c)?` in ${Math.max(0,Math.floor(c))}ms`:"",f=Number(e.statusCode),p=Number.isFinite(f)?` [${Math.floor(f)}]`:"",g=typeof e.errorMessage=="string"&&e.errorMessage.trim().length>0?`: ${e.errorMessage.trim()}`:"";return`${r} ${n} ${s}${l}${d}${p}${g}`}function yY(e){const t=a_(e),r=String(e.occurredAt||"").trim();if(!r||!t.startsWith(r))return t;const n=new Date(r);return Number.isNaN(n.getTime())?t:`${n.toLocaleString()}${t.slice(r.length)}`}function kY(e){return e.status==="error"?null:[String(e.eventType||"").trim()||"sync",String(e.status||"").trim()||"unknown-status",String(e.statusCode??""),String(e.changeCount??""),String(e.errorMessage||"").trim(),xC(e.details)].join("|")}function zh(e){if(!e)return"Never";const t=new Date(e);return Number.isNaN(t.getTime())?"Never":t.toLocaleString()}function n_(e){switch(e){case"off":return{label:"Off",icon:"off",color:"#94a3b8",border:"rgba(148, 163, 184, 0.35)",background:"rgba(148, 163, 184, 0.12)"};case"syncing":return{label:"Syncing",icon:"cloud",color:"#60a5fa",border:"rgba(96, 165, 250, 0.35)",background:"rgba(59, 130, 246, 0.12)"};case"attention":return{label:"Needs Attention",icon:"cloud",color:"#fda4af",border:"rgba(253, 164, 175, 0.4)",background:"rgba(239, 68, 68, 0.12)"};default:return{label:"Healthy",icon:"cloud",color:"#86efac",border:"rgba(134, 239, 172, 0.4)",background:"rgba(34, 197, 94, 0.12)"}}}function vY(e,t){return n_(t?e:"off")}function s_(e,t,r){if(t)return"Repairing";if(r&&e==="error")return"Recovering";switch(e){case"provision-local":return"Initial cloud upload";case"attach-cloud":return"Initial cloud pull";case"active":return"Active";case"error":return"Error";default:return"Idle"}}function wY(e){return[{label:"AI profile snapshot",value:`${e.aiProfileSnapshotCount} local profile${e.aiProfileSnapshotCount===1?"":"s"}`},{label:"AI profile raw response",value:`${e.aiProfileSnapshotRawCount} from route`},{label:"Last pushed AI profiles",value:`${e.lastPushedAiProfileCount} tracked`},{label:"AI watermark map",value:`${e.lastPushedAiProfileWatermarkCount} tracked`},{label:"Document snapshot",value:`${e.documentSnapshotCount} local doc${e.documentSnapshotCount===1?"":"s"}`},{label:"Asset snapshot",value:`${e.assetSnapshotCount} local asset${e.assetSnapshotCount===1?"":"s"}`},{label:"Queued full AI sync",value:e.forceFullAiProfilePushQueued?"Yes":"No"},{label:"Durable outbox",value:e.durableOutbox?e.durableOutbox.operationStates?`${e.durableOutbox.operationStates.pending} pending, ${e.durableOutbox.operationStates.retryScheduled} retry scheduled, ${e.durableOutbox.operationStates.inFlight} in flight, ${e.durableOutbox.operationStates.stale} stale, ${e.durableOutbox.operationStates.blocked} blocked`:`${e.durableOutbox.pending} pending, ${e.durableOutbox.inFlight} in flight, ${e.durableOutbox.blocked} blocked`:"Unavailable"},{label:"Durable recovery",value:(()=>{const t=e.durableOutbox?.recovery?`${e.durableOutbox.recovery.state}; ${e.durableOutbox.recovery.replayAccepted}/${e.durableOutbox.recovery.replayTotal} replayed`:null,r=e.coordinatorRecoveryObligations||0,n=r>0?`${r} coordinator obligations open`:null;return[t,n].filter(Boolean).join(", ")||"None"})()},{label:"AI snapshot last fetch",value:zh(e.aiProfileSnapshotLastFetchAt)},{label:"AI snapshot fetch error",value:e.aiProfileSnapshotLastFetchError||"None"},{label:"AI snapshot skip reason",value:e.aiProfileSnapshotLastSkipReason||"None"}]}function bY({syncRecentEvents:e,syncRecentEventsError:t,syncRecentEventsLoading:r}){if(r&&e.length===0)return[{key:"loading",text:"Loading recent sync events...",tone:"muted"}];if(t)return[{key:"error",text:t,tone:"error"}];if(e.length===0)return[{key:"empty",text:"No recent sync events recorded.",tone:"muted"}];const n=[];for(const[s,i]of e.entries()){const l=kY(i),c=n[n.length-1];if(l&&c?.signature===l){c.repeatCount+=1,c.text=`${c.baseText} × ${c.repeatCount}`;continue}const d=yY(i);n.push({key:Gu(i,s),text:d,tone:i.status==="error"?"error":"default",signature:l,repeatCount:1,baseText:d})}return n.map(({signature:s,repeatCount:i,baseText:l,...c})=>c)}function o_(e){const t=[];for(const r of e){if(String(r.errorMessage||"").toLowerCase().includes("reference number mismatch")){t.push(r);continue}if(String(r.status||"").toLowerCase()==="success")break}return t}function SY(e){return o_(e).length}function AY(e){return o_(e).map((t,r)=>{const n=t.details&&typeof t.details=="object"?t.details:null,s=String(n?.path||"").trim(),i=String(n?.referenceLabel||"").trim(),l=String(n?.taskTitle||n?.existingTaskTitle||"").trim(),c=Number(n?.existingReferenceNumber),d=Number(n?.incomingReferenceNumber),f=s||l||i||`Mismatch ${r+1}`,p=Number.isFinite(c)||Number.isFinite(d)?`Existing ${Number.isFinite(c)?c:"?"} vs incoming ${Number.isFinite(d)?d:"?"}`:i?`Both claimed ${i}`:null;return{key:Gu(t,r),pathLabel:f,refsLabel:p}})}function CY({currentWorkspaceId:e,syncStatusLabel:t,workspaceSyncSummary:r,workspaceSyncRecommendedAction:n,formattedLastSyncTime:s,formattedLastPullTime:i,formattedLastPushTime:l,workspaceSyncDiagnostics:c,workspaceSyncPendingChanges:d,syncLastError:f,syncStageLabel:p,referenceMismatchCount:g,syncRecentEvents:h}){const y=["Taskforce Sync Manager",`Workspace ID: ${e}`,`Status: ${t}`,`Summary: ${r}`,`Recommended action: ${n}`,`Last successful sync: ${s}`,`Last pull from cloud: ${i}`,`Last push to cloud: ${l}`,`Last error at: ${zh(c.lastErrorAt)}`,`Pending local changes: ${d}`,`Last error: ${f}`,`Sync stage: ${p}`,`Push blocked reason: ${c.pushBlockedReason||"None"}`,`Pull blocked reason: ${c.pullBlockedReason||"None"}`,`Retry blocked reason: ${c.retryBlockedReason||"None"}`,`Repair active: ${c.repairActive?"Yes":"No"}`,`Push in flight: ${c.pushInFlight?"Yes":"No"}`,`Pull in flight: ${c.pullInFlight?"Yes":"No"}`,`Retry pending: ${c.retryPending?"Yes":"No"}`,`AI profile snapshot: ${c.aiProfileSnapshotCount}`,`AI profile raw response: ${c.aiProfileSnapshotRawCount}`,`Last pushed AI profiles tracked: ${c.lastPushedAiProfileCount}`,`AI profile watermarks tracked: ${c.lastPushedAiProfileWatermarkCount}`,`AI snapshot last fetch: ${zh(c.aiProfileSnapshotLastFetchAt)}`,`AI snapshot fetch error: ${c.aiProfileSnapshotLastFetchError||"None"}`,`AI snapshot skip reason: ${c.aiProfileSnapshotLastSkipReason||"None"}`,`Document snapshot: ${c.documentSnapshotCount}`,`Asset snapshot: ${c.assetSnapshotCount}`,`Reference mismatches detected: ${g}`,`Queued full AI sync: ${c.forceFullAiProfilePushQueued?"Yes":"No"}`,`Durable outbox pending: ${c.durableOutbox?.pending??"Unavailable"}`,`Durable outbox in flight: ${c.durableOutbox?.inFlight??"Unavailable"}`,`Durable outbox blocked: ${c.durableOutbox?.blocked??"Unavailable"}`,`Durable outbox retry scheduled: ${c.durableOutbox?.operationStates?.retryScheduled??"Unavailable"}`,`Durable outbox stale: ${c.durableOutbox?.operationStates?.stale??"Unavailable"}`,`Durable outbox oldest active: ${zh(c.durableOutbox?.oldestActiveCreatedAt)}`,`Durable outbox blocked error code: ${c.durableOutbox?.blockedErrorCode||"None"}`,`Durable recovery state: ${c.durableOutbox?.recovery?.state||"None"}`,`Durable recovery replay total: ${c.durableOutbox?.recovery?.replayTotal??0}`,`Durable recovery replay pending: ${c.durableOutbox?.recovery?.replayPending??0}`,`Durable recovery replay in flight: ${c.durableOutbox?.recovery?.replayInFlight??0}`,`Durable recovery replay blocked: ${c.durableOutbox?.recovery?.replayBlocked??0}`,`Durable recovery replay accepted: ${c.durableOutbox?.recovery?.replayAccepted??0}`,`Durable recovery obligations (coordinator): ${c.coordinatorRecoveryObligations??"Unavailable"}`],k=h.map(b=>a_(b));return[...y,"","Recent sync events",...k.length>0?k:["No recent sync events recorded."]].join(`
7
+ `)}const DS="/api/taskforce/account/profile-summary",IY=9e4,ju=new Map;function _h(){return typeof performance<"u"?performance.now():Date.now()}function i_(e,t){const r=String(e||"").trim();if(!r)return"";const n=String(t||"").trim();return n?`${r}::${n}`:r}function LS(e,t){ju.delete(i_(e,t?.identityKey))}async function _Y(e,t){const r=String(e||"").trim(),n=i_(e,t?.identityKey);if(!n||!r)return null;const s=t?.force===!0,i=Date.now(),l=ju.get(n);if(!s&&l?.payload!==void 0&&i-l.fetchedAt<IY)return wr("account_profile_summary_cache_hit",{url:r,cacheKey:n,ageMs:i-l.fetchedAt}),l.payload;if(!s&&l?.promise)return wr("account_profile_summary_request_reused",{url:r,cacheKey:n}),l.promise;const c=_h(),d=(async()=>{const f=await fetch(r,{method:"GET",credentials:"include"});if(!f.ok)throw new Error(String((await f.json().catch(()=>({})))?.error||"Failed to load account summary."));const g=await f.json().catch(()=>({}))||null;return ju.set(n,{payload:g,fetchedAt:Date.now(),promise:null}),wr("account_profile_summary_loaded",{url:r,cacheKey:n,durationMs:Math.round(_h()-c),fromCache:!1}),g})().catch(f=>{const p=l?.payload??null;if(p)return ju.set(n,{payload:p,fetchedAt:l?.fetchedAt??Date.now(),promise:null}),wr("account_profile_summary_failed",{url:r,cacheKey:n,durationMs:Math.round(_h()-c),error:f instanceof Error?f.message:String(f||"Unknown error"),returnedStale:!0}),p;throw ju.delete(n),wr("account_profile_summary_failed",{url:r,cacheKey:n,durationMs:Math.round(_h()-c),error:f instanceof Error?f.message:String(f||"Unknown error"),returnedStale:!1}),f});return ju.set(n,{payload:l?.payload??null,fetchedAt:l?.fetchedAt??0,promise:d}),d}const TY=512,xY=5*1024*1024,RY=[.9,.82,.74,.66,.58],jY=[.9,.82,.74,.66,.58],PY=[1,.85,.7,.55,.4],EY=new Set(["image/png","image/jpeg","image/webp"]);function NY(e,t){const r=document.createElement("canvas");return r.width=Math.max(1,Math.round(e)),r.height=Math.max(1,Math.round(t)),r}async function MY(e){const t=URL.createObjectURL(e);try{const r=await new Promise((n,s)=>{const i=new Image;i.onload=()=>n(i),i.onerror=()=>s(new Error("Failed to load image.")),i.src=t});return{width:r.naturalWidth||r.width,height:r.naturalHeight||r.height,source:r}}finally{URL.revokeObjectURL(t)}}async function DY(e){const t=NY(e.width,e.height),r=t.getContext("2d");if(!r)throw new Error("Image optimization requires a 2D canvas context.");return r.drawImage(e.image.source,0,0,t.width,t.height),await new Promise((n,s)=>{t.toBlob(i=>{if(i){n(i);return}s(new Error("Failed to encode resized image."))},e.type,e.quality)})}const LY={loadImage:MY,renderToBlob:DY};function OS(e,t){return e==="image/png"?".png":e==="image/jpeg"?".jpg":e==="image/webp"?".webp":(t.includes(".")?t.slice(t.lastIndexOf(".")):"")||".img"}function BS(e,t){const r=String(e||"").trim();if(!r)return`avatar${t}`;const n=r.lastIndexOf(".");return n<=0?`${r}${t}`:`${r.slice(0,n)}${t}`}function OY(e){const t=e==="image/jpeg"?"image/jpeg":"image/webp";return Array.from(new Set([t,"image/webp","image/jpeg"]))}function BY(e){return e==="image/webp"?RY:e==="image/jpeg"?jY:[void 0]}async function WY(e,t,r=LY){const n=Number.isFinite(t?.maxBytes)&&(t?.maxBytes||0)>0?Math.floor(t?.maxBytes):xY,s=Number.isFinite(t?.maxDimension)&&(t?.maxDimension||0)>0?Math.floor(t?.maxDimension):TY;if(!EY.has(e.type))return{file:e,optimized:!1,exceededLimit:e.size>n};const i=await r.loadImage(e),l=Math.max(i.width,i.height,1);if(e.size<=n&&l<=s)return{file:e,optimized:!1,exceededLimit:!1};const c=Math.min(1,s/l);let d=null;for(const p of PY){const g=Math.min(1,c*p),h=Math.max(1,Math.round(i.width*g)),y=Math.max(1,Math.round(i.height*g));for(const k of OY(e.type))for(const b of BY(k)){const C=await r.renderToBlob({image:i,width:h,height:y,type:k,quality:b});if((!d||C.size<d.size)&&(d=C),C.size<=n)return{file:new File([C],BS(e.name,OS(C.type||k,e.name)),{type:C.type||k,lastModified:e.lastModified}),optimized:!0,exceededLimit:!1}}}if(!d)return{file:e,optimized:!1,exceededLimit:!0};const f=new File([d],BS(e.name,OS(d.type||e.type,e.name)),{type:d.type||e.type,lastModified:e.lastModified});return{file:f,optimized:f.size<e.size,exceededLimit:f.size>n}}function $Y(e,t){return Array.from([...e,...t].reduce((r,n)=>r.set(n.id,n),new Map).values())}function c_(e){return e.status==="done"||e.status==="cancelled"}function FY({isArchived:e,tasks:t,dataReady:r}){return{archiveReady:r&&!e&&t.length>0&&t.every(c_),activeTaskCount:t.filter(n=>!n.isArchived).length,activeWorkstreamCount:0}}function UY({isArchived:e,workstreams:t,dataReady:r}){const n=t.flatMap(s=>s.tasks||[]);return{archiveReady:r&&!e&&t.length>0&&n.length>0&&n.every(c_),activeTaskCount:n.filter(s=>!s.isArchived).length,activeWorkstreamCount:t.filter(s=>!s.isArchived).length}}async function l_({workstream:e,allowEmpty:t=!1,archiveTask:r,archiveWorkstream:n}){if(e.isArchived)return!0;const s=e.tasks||[];if(!t&&s.length===0||s.some(i=>i.status!=="done"&&i.status!=="cancelled"))return!1;for(const i of s)if(!i.isArchived&&!await r(i.id))return!1;return await n(e.id),!0}async function zY({workstreams:e,archiveTask:t,archiveWorkstream:r,archiveInitiative:n,initiativeId:s}){const i=e.flatMap(l=>l.tasks||[]);if(e.length===0||i.length===0||i.some(l=>l.status!=="done"&&l.status!=="cancelled"))return!1;for(const l of e)if(!await l_({workstream:l,allowEmpty:!0,archiveTask:t,archiveWorkstream:r}))return!1;return await n(s),!0}function d_({isArchived:e,taskCount:t,completedTaskCount:r,archiveReady:n,entityType:s,activeWorkstreamCount:i=0}){return e?{mode:"archived"}:t===0?s==="initiative"&&i>0?{mode:"blocked",remainingKind:"workstream"}:{mode:"empty"}:Math.max(0,t-r)>0?{mode:"blocked",remainingKind:"task"}:n?{mode:"ready"}:{mode:"checking"}}const dv="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg2IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1IDg3LjY1ODkyMyIKICAgdmVyc2lvbj0iMS4xIgogICBpZD0ic3ZnMSIKICAgeG1sOnNwYWNlPSJwcmVzZXJ2ZSIKICAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcwogICAgIGlkPSJkZWZzMSIgLz48ZwogICAgIGlkPSJsYXllcjEiCiAgICAgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTMwLjk2ODgxLC04NzIuMDY2NjgpIj48ZwogICAgICAgaWQ9ImcxLTctMS02LTItMS05IgogICAgICAgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aAogICAgICAgICBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIKICAgICAgICAgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiCiAgICAgICAgIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJUIiAvPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmVuZDtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6ZW5kO2ZpbGw6I2ZmOGEwMDtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6I2ZmOGEwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIgogICAgICAgICBkPSJtIDE1My41Mzg4OCwxNjQuNTI2NiBoIC0zLjUwNjc0IHYgLTEzLjYzNzMzIGggMTAuODEyNDUgdiAyLjcyNzQ2IGggLTcuMzA1NzEgdiAzLjIxNDUyIGggNS43NDcxNiB2IDIuNzI3NDYgaCAtNS43NDcxNiB6IgogICAgICAgICBpZD0idGV4dDEtOS04LTQtMy03LTItNyIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",u_="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB3aWR0aD0iMzY2LjY3Nzg5IgogICBoZWlnaHQ9IjMzMS4zMDkzMyIKICAgdmlld0JveD0iMCAwIDk3LjAxNjg1OCA4Ny42NTg5MjMiCiAgIHZlcnNpb249IjEuMSIKICAgaWQ9InN2ZzEiCiAgIHhtbDpzcGFjZT0icHJlc2VydmUiCiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnMKICAgICBpZD0iZGVmczEiIC8+PGcKICAgICBpZD0ibGF5ZXIxIgogICAgIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcKICAgICAgIGlkPSJnMS03LTEtNi0yLTEiCiAgICAgICB0cmFuc2Zvcm09Im1hdHJpeCg0Ljk4MTU0NzksMCwwLDQuOTg1NTgyMiwtNjkwLjYwODc4LDQ2LjUyNDE0OCkiPjxwYXRoCiAgICAgICAgIHN0eWxlPSJmb250LXN0eWxlOml0YWxpYztmb250LXdlaWdodDpib2xkO2ZvbnQtc2l6ZToxOS40ODE5cHg7bGluZS1oZWlnaHQ6Mi41O2ZvbnQtZmFtaWx5OidSdXNzbyBPbmUnOy1pbmtzY2FwZS1mb250LXNwZWNpZmljYXRpb246J1J1c3NvIE9uZSBNZWRpdW0gSXRhbGljJzt0ZXh0LWFsaWduOmNlbnRlcjtsZXR0ZXItc3BhY2luZzowcHg7dGV4dC1hbmNob3I6bWlkZGxlO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojMDAwMDAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTQ5LjQ0MDY2LDE2MS4xOTUwNSBoIC0zLjUwNjc0IHYgLTEwLjkwOTg2IGggLTQuMDkxMiB2IC0yLjcyNzQ3IGggMTEuNjg5MTQgdiAyLjcyNzQ3IGggLTQuMDkxMiB6IgogICAgICAgICBpZD0idGV4dDEtNC0zLTMtMS0wIgogICAgICAgICB0cmFuc2Zvcm09InNrZXdYKC0xNSkiCiAgICAgICAgIGFyaWEtbGFiZWw9IlQiIC8+PHBhdGgKICAgICAgICAgc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiCiAgICAgICAgIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiCiAgICAgICAgIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIKICAgICAgICAgdHJhbnNmb3JtPSJza2V3WCgtMTUpIgogICAgICAgICBhcmlhLWxhYmVsPSJGIiAvPjwvZz48L2c+PC9zdmc+Cg==",WS="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHdpZHRoPSIxMDAwIiBoZWlnaHQ9IjEwMDAiPjxzdHlsZT4KICAgICNsaWdodC1pY29uIHsKICAgICAgZGlzcGxheTogaW5saW5lOwogICAgfQogICAgI2RhcmstaWNvbiB7CiAgICAgIGRpc3BsYXk6IG5vbmU7CiAgICB9CgogICAgQG1lZGlhIChwcmVmZXJzLWNvbG9yLXNjaGVtZTogZGFyaykgewogICAgICAjbGlnaHQtaWNvbiB7CiAgICAgICAgZGlzcGxheTogbm9uZTsKICAgICAgfQogICAgICAjZGFyay1pY29uIHsKICAgICAgICBkaXNwbGF5OiBpbmxpbmU7CiAgICAgIH0KICAgIH0KICA8L3N0eWxlPjxnIGlkPSJsaWdodC1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODkyNTA0ODkwMzI3LDAsMCwyLjcyNzE4OTI1MDQ4OTAzMjcsMCw0OC4yMjgzNzgzMTg2MzgxOSkiPjxzdmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiB2ZXJzaW9uPSIxLjEiIHdpZHRoPSIzNjYuNjc3ODkiIGhlaWdodD0iMzMxLjMwOTMzIiB2aWV3Qm94PSIwIDAgOTcuMDE2ODU4IDg3LjY1ODkyMyIgaWQ9InN2ZzEiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxkZWZzIGlkPSJkZWZzMSI+PC9kZWZzPjxnIGlkPSJsYXllcjEiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDE4Ni4xOTU2MywtNzgwLjY1NTczKSI+PGcgaWQ9ImcxLTctMS02LTItMSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTY5MC42MDg3OCw0Ni41MjQxNDgpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsLXJ1bGU6ZXZlbm9kZDtzdHJva2U6IzAwMDAwMDtzdHJva2Utd2lkdGg6MC42MTM2MDQ7c3Ryb2tlLWxpbmVjYXA6cm91bmQ7c3Ryb2tlLWxpbmVqb2luOnJvdW5kIiBkPSJtIDE0OS40NDA2NiwxNjEuMTk1MDUgaCAtMy41MDY3NCB2IC0xMC45MDk4NiBoIC00LjA5MTIgdiAtMi43Mjc0NyBoIDExLjY4OTE0IHYgMi43Mjc0NyBoIC00LjA5MTIgeiIgaWQ9InRleHQxLTQtMy0zLTEtMCIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMiIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJGIj48L3BhdGg+PC9nPjwvZz48L3N2Zz48L2c+PC9nPjwvc3ZnPjwvZz48ZyBpZD0iZGFyay1pY29uIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB4bWxuczp4bGluaz0iaHR0cDovL3d3dy53My5vcmcvMTk5OS94bGluayIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+PGc+PGcgdHJhbnNmb3JtPSJtYXRyaXgoMi43MjcxODk0NzM2MTU4ODcsMCwwLDIuNzI3MTg5NDczNjE1ODg3LDAsNDguMjI4MzQxMzU2NjMzOTA1KSI+PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgd2lkdGg9IjM2Ni42Nzc4NiIgaGVpZ2h0PSIzMzEuMzA5MzMiIHZpZXdCb3g9IjAgMCA5Ny4wMTY4NSA4Ny42NTg5MjMiIGlkPSJzdmcxIiB4bWw6c3BhY2U9InByZXNlcnZlIiB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcyBpZD0iZGVmczEiPjwvZGVmcz48ZyBpZD0ibGF5ZXIxIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMzAuOTY4ODEsLTg3Mi4wNjY2OCkiPjxnIGlkPSJnMS03LTEtNi0yLTEtOSIgdHJhbnNmb3JtPSJtYXRyaXgoNC45ODE1NDc5LDAsMCw0Ljk4NTU4MjIsLTYzNS4zODE5NiwxMzcuOTM1MTIpIj48cGF0aCBzdHlsZT0iZm9udC1zdHlsZTppdGFsaWM7Zm9udC13ZWlnaHQ6Ym9sZDtmb250LXNpemU6MTkuNDgxOXB4O2xpbmUtaGVpZ2h0OjIuNTtmb250LWZhbWlseTonUnVzc28gT25lJzstaW5rc2NhcGUtZm9udC1zcGVjaWZpY2F0aW9uOidSdXNzbyBPbmUgTWVkaXVtIEl0YWxpYyc7dGV4dC1hbGlnbjpjZW50ZXI7bGV0dGVyLXNwYWNpbmc6MHB4O3RleHQtYW5jaG9yOm1pZGRsZTtmaWxsOiNmZmZmZmY7ZmlsbC1ydWxlOmV2ZW5vZGQ7c3Ryb2tlOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjAuNjEzNjA0O3N0cm9rZS1saW5lY2FwOnJvdW5kO3N0cm9rZS1saW5lam9pbjpyb3VuZCIgZD0ibSAxNDkuNDQwNjYsMTYxLjE5NTA1IGggLTMuNTA2NzQgdiAtMTAuOTA5ODYgaCAtNC4wOTEyIHYgLTIuNzI3NDcgaCAxMS42ODkxNCB2IDIuNzI3NDcgaCAtNC4wOTEyIHoiIGlkPSJ0ZXh0MS00LTMtMy0xLTAtMyIgdHJhbnNmb3JtPSJza2V3WCgtMTUpIiBhcmlhLWxhYmVsPSJUIj48L3BhdGg+PHBhdGggc3R5bGU9ImZvbnQtc3R5bGU6aXRhbGljO2ZvbnQtd2VpZ2h0OmJvbGQ7Zm9udC1zaXplOjE5LjQ4MTlweDtsaW5lLWhlaWdodDoyLjU7Zm9udC1mYW1pbHk6J1J1c3NvIE9uZSc7LWlua3NjYXBlLWZvbnQtc3BlY2lmaWNhdGlvbjonUnVzc28gT25lIE1lZGl1bSBJdGFsaWMnO3RleHQtYWxpZ246ZW5kO2xldHRlci1zcGFjaW5nOjBweDt0ZXh0LWFuY2hvcjplbmQ7ZmlsbDojZmY4YTAwO2ZpbGwtcnVsZTpldmVub2RkO3N0cm9rZTojZmY4YTAwO3N0cm9rZS13aWR0aDowLjYxMzYwNDtzdHJva2UtbGluZWNhcDpyb3VuZDtzdHJva2UtbGluZWpvaW46cm91bmQiIGQ9Im0gMTUzLjUzODg4LDE2NC41MjY2IGggLTMuNTA2NzQgdiAtMTMuNjM3MzMgaCAxMC44MTI0NSB2IDIuNzI3NDYgaCAtNy4zMDU3MSB2IDMuMjE0NTIgaCA1Ljc0NzE2IHYgMi43Mjc0NiBoIC01Ljc0NzE2IHoiIGlkPSJ0ZXh0MS05LTgtNC0zLTctMi03IiB0cmFuc2Zvcm09InNrZXdYKC0xNSkiIGFyaWEtbGFiZWw9IkYiPjwvcGF0aD48L2c+PC9nPjwvc3ZnPjwvZz48L2c+PC9zdmc+PC9nPjwvc3ZnPg==";function HY({projectName:e,currentWorkspaceId:t,brandLabel:r="TaskForce",brandHomeLabel:n="Go to Kanban",onBrandClick:s,runtimeMode:i="local",theme:l=Kh,meta:c,actions:d}){const f=o.useRef(null),p=o.useRef(null),[g,h]=o.useState(!0),y=IA(l)?u_:dv,k=String(e||"").trim(),b=String(t||"").trim(),C=b.toLowerCase(),S=!!(k&&(i!=="cloud"||C&&C!=="default")),w=o.useCallback(()=>{if(!S){h(!0);return}const v=f.current,V=p.current;if(!v||!V)return;const _=v.getBoundingClientRect().width,j=V.getBoundingClientRect().width;if(_<=0||j<=0)return;const F=window.getComputedStyle(v),z=Number.parseFloat(F.columnGap||F.gap||"0")||0,M=Array.from(v.children).filter(U=>{if(U===V)return!1;const ve=U.getBoundingClientRect();return ve.width>0&&ve.height>0}),Z=M.reduce((U,ve)=>U+ve.getBoundingClientRect().width,0)+j+z*M.length;h(Z<=_)},[S]);o.useLayoutEffect(()=>{w();const v=f.current,V=p.current;if(!v||!V)return;if(typeof ResizeObserver>"u")return window.addEventListener("resize",w),()=>window.removeEventListener("resize",w);const _=new ResizeObserver(w);return _.observe(v),_.observe(V),()=>_.disconnect()},[w,k,c]);const T=S&&g,E=()=>{if(!b||typeof navigator>"u")return;const v=navigator.clipboard;v?.writeText&&v.writeText(b).catch(()=>{})},x=v=>{v.key!=="Enter"&&v.key!==" "||(v.preventDefault(),E())},N=a.jsxs(a.Fragment,{children:[a.jsx("img",{src:y,alt:"Taskforce Logo",className:R.brandIcon,onError:v=>{const V=v.currentTarget;V.src!==WS?V.src=WS:V.style.display="none"}}),a.jsx("span",{children:r}),i==="cloud"&&a.jsx("span",{className:R.brandCloudSuffix,children:"HQ"})]});return a.jsxs("div",{className:`${R.header} ${Fr.standaloneHeader}`,children:[a.jsxs("div",{ref:f,className:`${R.headerTitle} ${Fr.standaloneTitle}`,children:[s?a.jsx("button",{type:"button",className:R.brandHomeButton,onClick:s,title:n,"aria-label":n,children:N}):a.jsx("span",{className:R.brandHomeStatic,children:N}),S&&a.jsxs("span",{ref:p,className:`${R.projectNameGroup} ${T?"":R.projectNameGroupHidden}`.trim(),"aria-hidden":T?void 0:!0,children:[a.jsx("span",{className:R.projectSlash,children:"/"}),a.jsx("span",{className:R.projectName,title:T&&b?`Workspace ID: ${b}`:void 0,role:T&&b?"button":void 0,tabIndex:T&&b?0:void 0,onClick:E,onMouseDown:v=>v.preventDefault(),onKeyDown:x,children:k})]}),c]}),a.jsx("div",{className:R.headerActions,style:{gap:"16px"},children:d})]})}function Ji(e){return`${e.type}:${e.id}`}function GY(e){if(!Array.isArray(e))return;const t=new Set,r=[];for(const n of e){if(!n||typeof n!="object"||Array.isArray(n))continue;const s=n.type,i=n.id;if(s!=="initiative"&&s!=="workstream"||typeof i!="string")continue;const l=i.trim();if(!l)continue;const c={type:s,id:l},d=Ji(c);t.has(d)||(t.add(d),r.push(c))}return r}function VY(e,t){const r=Ji(t);return e.some(s=>Ji(s)===r)?e.filter(s=>Ji(s)!==r):[...e,t]}const KY="taskforce.uiState.layout.v1",qY=/^\d{4}-\d{2}-\d{2}$/,YY=/^\d{4}-\d{2}$/;function ZY(e){const t=String(e.workspaceId||"default").trim()||"default",r=String(e.userId||"anonymous").trim()||"anonymous",n=_g(`user:${r}`);return`${e.runtimeMode}:${t}:user:${n}`}function Vu(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function Th(e){if(!Array.isArray(e))return;const t=Array.from(new Set(e.filter(r=>typeof r=="string").map(r=>r.trim()).filter(Boolean)));return t.length>0?t:[]}function Gf(e){if(!(typeof e!="number"||!Number.isFinite(e)||e<0))return Math.round(e)}function JY(e,t){if(!Vu(e))return;const r=Object.entries(e).map(([n,s])=>{const i=n.trim(),l=Gf(s);return i&&l!==void 0?[i,l]:null}).filter(n=>n!==null).slice(-50);return Object.fromEntries(r)}function QY(e){if(!Vu(e))return null;const t=typeof e.zoomLevel=="number"&&Number.isFinite(e.zoomLevel)?Math.min(4,Math.max(.25,e.zoomLevel)):void 0,r=Gf(e.scrollLeft),n=Gf(e.scrollTop);return t===void 0||r===void 0||n===void 0?null:{zoomLevel:t,scrollLeft:r,scrollTop:n}}function XY(e){if(!Vu(e))return;const t=Object.entries(e).map(([r,n])=>{const s=r.trim(),i=QY(n);return s&&i?[s,i]:null}).filter(r=>r!==null).slice(-50);return Object.fromEntries(t)}function eZ(e){if(e===null)return null;if(!Vu(e)||e.type!=="initiative"&&e.type!=="workstream"||typeof e.id!="string")return;const t=e.id.trim();return t?{type:e.type,id:t}:null}function p_(e){if(!Vu(e))return null;const t={},r=y=>{typeof e[y]=="boolean"&&(t[y]=e[y])};["scheduleShowWeekends","scheduleShowBacklog","scheduleOnlyExpired","scheduleSidebarOpen","showFilters","documentTrayOpen","imageTrayOpen","agentTrayOpen","taskforceAgentRosterTrayOpen","taskforceAgentDrawerOpen","taskforceAgentPanelCollapsed","planningDrawerOpen","planningTreeCollapsed","planningPrimaryCollapsed","planningSecondaryCollapsed","planningFavoritesSectionCollapsed","planningInitiativesSectionCollapsed","planningWorkstreamsSectionCollapsed"].forEach(y=>r(y)),(e.planningNavigatorSort==="default"||e.planningNavigatorSort==="title"||e.planningNavigatorSort==="owner"||e.planningNavigatorSort==="progress")&&(t.planningNavigatorSort=e.planningNavigatorSort),(e.planningTaskArrangeMode==="execution"||e.planningTaskArrangeMode==="ready"||e.planningTaskArrangeMode==="priority")&&(t.planningTaskArrangeMode=e.planningTaskArrangeMode);const n=GY(e.planningFavorites);n&&(t.planningFavorites=n),typeof e.scheduleSelectedDate=="string"&&qY.test(e.scheduleSelectedDate)&&(t.scheduleSelectedDate=e.scheduleSelectedDate),typeof e.scheduleCalendarMonth=="string"&&YY.test(e.scheduleCalendarMonth)&&(t.scheduleCalendarMonth=e.scheduleCalendarMonth);const s=Gf(e.scheduleScrollLeft);s!==void 0&&(t.scheduleScrollLeft=s);const i=Th(e.documentTypeFilters);i&&(t.documentTypeFilters=i);const l=Th(e.documentAttachmentFilters);l&&(t.documentAttachmentFilters=l),typeof e.documentSortField=="string"&&(t.documentSortField=e.documentSortField),(e.documentSortOrder==="asc"||e.documentSortOrder==="desc")&&(t.documentSortOrder=e.documentSortOrder);const c=Th(e.documentPinnedDocIds)?.slice(-50);c&&(t.documentPinnedDocIds=c),typeof e.documentSearchQuery=="string"&&(t.documentSearchQuery=e.documentSearchQuery),typeof e.documentSelectedDocId=="string"?t.documentSelectedDocId=e.documentSelectedDocId.trim()||null:e.documentSelectedDocId===null&&(t.documentSelectedDocId=null);const d=JY(e.documentScrollByDocId);d&&(t.documentScrollByDocId=d);const f=Gf(e.documentListScrollTop);f!==void 0&&(t.documentListScrollTop=f);const p=Th(e.planningExpandedInitiativeIds);p&&(t.planningExpandedInitiativeIds=p);const g=eZ(e.planningDrawerDetail);g!==void 0&&(t.planningDrawerDetail=g),typeof e.planningNestedWorkstreamDetailId=="string"?t.planningNestedWorkstreamDetailId=e.planningNestedWorkstreamDetailId.trim()||null:e.planningNestedWorkstreamDetailId===null&&(t.planningNestedWorkstreamDetailId=null),Vu(e.annotatedTarget)?t.annotatedTarget=e.annotatedTarget:e.annotatedTarget===null&&(t.annotatedTarget=null),typeof e.annotatedSessionId=="string"?t.annotatedSessionId=e.annotatedSessionId.trim()||null:e.annotatedSessionId===null&&(t.annotatedSessionId=null);const h=XY(e.annotatedViewportByContextKey);return h&&(t.annotatedViewportByContextKey=h),t}function tZ(e,t){if(!e)return{state:t,localFallbackPatch:{}};const r={},n=r;for(const[s,i]of Object.entries(e))Object.prototype.hasOwnProperty.call(t,s)||(n[s]=i);return{state:{...e,...t},localFallbackPatch:r}}function Og(e,t){return Object.is(e,t)?!0:JSON.stringify(e)===JSON.stringify(t)}function rZ(e,t){const r={},n=r;for(const[s,i]of Object.entries(t))Og(e[s],i)||(n[s]=i);return r}function aZ(e,t){return Object.entries(t).every(([r,n])=>Object.prototype.hasOwnProperty.call(e,r)&&Og(e[r],n))}function $S(e,t){const r=e;for(const[n,s]of Object.entries(t))Og(r[n],s)&&delete r[n]}function f_(e){const t=Rv(e);return`${KY}.${t}`}function xh(e){const t=String(e.currentWorkspaceId||"").trim();return!e.useCloudProxy||!t||t==="default"?e.headers:{...e.headers||{},"x-taskforce-workspace-id":t}}function nZ(e){if(typeof window>"u")return null;try{const t=window.localStorage.getItem(f_(e));return t?p_(JSON.parse(t)):null}catch{return null}}function FS(e,t){if(!(typeof window>"u"))try{window.localStorage.setItem(f_(t),JSON.stringify(e))}catch{}}function sZ(e){const{currentWorkspaceId:t,loadKey:r,enabled:n=!0,headers:s,useCloudProxy:i=!1,remotePlanningFavoritesAuthoritative:l=!1,snapshot:c,onApplyState:d}=e,[f,p]=o.useState(""),g=o.useRef(""),h=o.useRef(0),y=o.useRef(c),k=o.useRef(c),b=o.useRef({}),C=o.useRef(null),S=o.useRef(d);return o.useEffect(()=>{S.current=d},[d]),o.useEffect(()=>{y.current=c},[c]),o.useEffect(()=>{if(!n){g.current="",h.current=0,k.current=y.current,b.current={},C.current=null,p("");return}if(g.current===r)return;g.current=r,h.current=0,k.current=y.current,b.current={},C.current=null,p("");let w=!1;const T=h.current,E=nZ(r),x=!!E;return E&&(C.current={source:y.current,target:E},S.current(E),p(r)),(async()=>{try{const v=new URLSearchParams({key:"layout"});t&&v.set("workspaceId",t),i&&v.set("taskforceCloud","1");const V=await fetch(`/api/taskforce/ui-state?${v.toString()}`,{method:"GET",credentials:"include",headers:xh({headers:s,currentWorkspaceId:t,useCloudProxy:i})}),_=V.ok?await V.json().catch(()=>({})):{},j=p_(_?.state),F=j&&l?{...j,planningFavorites:j.planningFavorites??[]}:j;if(!w&&F&&h.current===T){const{state:z,localFallbackPatch:M}=tZ(E,F);C.current={source:y.current,target:z},S.current(z),FS(z,r),Object.keys(M).length>0&&await Af({stateKey:"layout",workspaceId:t,headers:xh({headers:s,currentWorkspaceId:t,useCloudProxy:i}),patch:M,dedupeScope:r,useCloudProxy:i})}}catch{}finally{!w&&!x&&(C.current||(k.current=y.current),p(r))}})(),()=>{w=!0}},[t,n,s,r,l,i]),o.useEffect(()=>{if(f!==r)return;const w=C.current;if(w){if(aZ(c,w.target)){k.current=c,C.current=null;return}if(Og(c,w.source))return;C.current=null}const T=rZ(k.current,c);if(k.current=c,Object.keys(T).length===0)return;h.current+=1,FS(c,r),Object.assign(b.current,T);const E=window.setTimeout(async()=>{const x={...b.current};if(Object.keys(x).length!==0)try{const N=await Af({stateKey:"layout",workspaceId:t,headers:xh({headers:s,currentWorkspaceId:t,useCloudProxy:i}),patch:x,dedupeScope:r,useCloudProxy:i});(N.skipped&&N.reason==="unchanged"||!N.skipped&&N.response?.ok&&N.payload?.success!==!1)&&$S(b.current,x)}catch{}},250);return()=>window.clearTimeout(E)},[t,s,r,f,c,i]),o.useEffect(()=>{if(typeof window>"u"||f!==r)return;const w=()=>{const E={...b.current};Object.keys(E).length!==0&&Af({stateKey:"layout",workspaceId:t,headers:xh({headers:s,currentWorkspaceId:t,useCloudProxy:i}),patch:E,keepalive:!0,dedupeScope:r,useCloudProxy:i}).then(x=>{(x.skipped&&x.reason==="unchanged"||!x.skipped&&x.response?.ok&&x.payload?.success!==!1)&&$S(b.current,E)}).catch(()=>{})},T=()=>{document.visibilityState==="hidden"&&w()};return window.addEventListener("pagehide",w),document.addEventListener("visibilitychange",T),()=>{window.removeEventListener("pagehide",w),document.removeEventListener("visibilitychange",T)}},[t,s,r,f,i]),{ready:n&&f===r}}function oZ({value:e,placeholder:t,active:r=!1,onChange:n,onClear:s,clearTitle:i}){return a.jsxs("div",{className:R.searchContainer,style:{width:"240px"},children:[a.jsx(bg,{size:16,className:R.searchIcon}),a.jsx("input",{type:"text",className:`${R.searchInput} ${r?R.searchActive:""}`,placeholder:t,value:e,onChange:l=>n(l.target.value)}),e&&s&&a.jsx("button",{className:R.clearSearchBtn,onClick:s,title:i,children:a.jsx("span",{"aria-hidden":"true",children:"×"})})]})}function US({label:e,value:t,options:r,onChange:n,trailingAction:s,width:i}){return a.jsxs("div",{className:R.groupByContainer,style:i?{width:i}:void 0,children:[a.jsx("span",{className:R.groupByLabel,children:e}),a.jsx("select",{className:`${R.select} ${R.groupBySelect}`,value:t,onChange:l=>n(l.target.value),children:r.map(l=>a.jsx("option",{value:l.value,children:l.label},String(l.value)))}),s]})}function Rh({actions:e}){return a.jsx(a.Fragment,{children:e.map(t=>a.jsx("button",{className:`tf-control-icon ${t.active?"tf-control-icon-active":""} ${t.className||""}`.trim(),onClick:t.onClick,title:t.title,disabled:t.disabled,"aria-disabled":t.ariaDisabled,"aria-expanded":t.ariaExpanded,"aria-controls":t.ariaControls,children:t.icon},t.key))})}function zS(){return a.jsx("div",{className:R.headerDivider})}function iZ({icon:e,label:t,onClick:r,disabled:n=!1}){return a.jsxs("button",{className:R.primaryUpdateBtn,onClick:r,disabled:n,children:[e," ",t]})}function cZ({children:e,id:t}){return a.jsx("div",{id:t,className:R.filterToolbar,style:{padding:"8px 24px",borderBottom:"1px solid var(--border-primary)",background:"var(--bg-secondary)",boxShadow:"0 4px 18px rgba(8, 10, 24, 0.12)",display:"flex",alignItems:"center",gap:"12px",flexWrap:"wrap",position:"relative",zIndex:50},children:e})}function lZ({categoryFilterOptions:e,typeFilterOptions:t,priorities:r,taxonomyDisplayLabels:n,filterCategories:s,setFilterCategories:i,filterTypes:l,setFilterTypes:c,filterPriorities:d,setFilterPriorities:f,filterStatus:p,setFilterStatus:g,filterAssignees:h,setFilterAssignees:y,assigneeOptions:k,initiativeFilterOptions:b=[],selectedInitiativeId:C="",setSelectedInitiativeId:S=()=>{},workstreamFilterOptions:w=[],selectedWorkstreamId:T="",setSelectedWorkstreamId:E=()=>{},taskScope:x,setTaskScope:N,showArchive:v,setShowArchive:V,onDeleteAllDeleted:_,clearFilters:j,clearFiltersDisabled:F=!1}){return a.jsxs(a.Fragment,{children:[a.jsx(J8,{}),a.jsx(of,{label:n?.category||bt("standalone.categoryLabel"),options:e,selected:s,onChange:z=>i(z),variant:"value"}),a.jsx(of,{label:n?.type||bt("standalone.typeLabel"),options:t,selected:l,onChange:z=>c(z),variant:"value"}),a.jsx(of,{label:n?.priority||bt("standalone.priorityLabel"),options:r,selected:d,onChange:z=>f(z),variant:"value"}),a.jsx(of,{label:bt("standalone.statusLabel"),options:rc,selected:p,onChange:z=>g(z),variant:"value"}),a.jsx(of,{label:bt("standalone.assigneeLabel"),options:k,selected:h,onChange:z=>y(z),variant:"value",searchable:!0,searchPlaceholder:"Search assignees...",noResultsText:"No assignees found.",renderOptionContent:z=>{const M=k.find(O=>String(O.value)===String(z.value));return M?a.jsx(qu,{option:M,size:20}):z.label}}),a.jsx("div",{className:R.headerDivider,style:{height:"16px",margin:"0 8px"}}),a.jsx(wS,{label:"Initiative",options:b,selected:C,onChange:S,allLabel:"All Initiatives",title:"Filter by initiative"}),a.jsx(wS,{label:"Workstream",options:w,selected:T,onChange:E,allLabel:"All Workstreams",title:"Filter by workstream"}),a.jsx(Q8,{onClick:j,disabled:F,label:"Reset task filters and sort"}),a.jsx("div",{style:{flex:1}}),x==="deleted"&&_&&a.jsx(X8,{onClick:_,className:`${R.bulkArchiveBtn} ${R.taskToolbarAction} ${R.bulkDeleteBtn}`,title:"Empty trash",children:"Empty Trash"}),a.jsx(WI,{scope:x,onScopeChange:z=>{N(z),z==="archived"?V(!0):v&&V(!1)},className:R.groupByContainer,labelClassName:R.groupByLabel})]})}function dZ(e){return a.jsx(cZ,{id:e.id,children:a.jsx(lZ,{...e})})}const uZ="_drawer_rku50_1",pZ="_drawerBody_rku50_5",fZ="_paneShell_rku50_13",mZ="_collapsedPaneShell_rku50_22",hZ="_collapsedPaneHeader_rku50_31",gZ="_collapsedPaneLabel_rku50_43",yZ="_collapsedPaneMuted_rku50_53",kZ="_treePane_rku50_66",vZ="_treePaneSplit_rku50_76",wZ="_detailPane_rku50_80",bZ="_paneHeader_rku50_90",SZ="_paneHeaderLabel_rku50_104",AZ="_paneContent_rku50_118",CZ="_sectionTitle_rku50_132",IZ="_sectionHeaderRow_rku50_141",_Z="_headerActionGroup_rku50_148",TZ="_toggleActive_rku50_155",xZ="_archiveVisibilityToggle_rku50_161",RZ="_sectionGroup_rku50_167",jZ="_navigatorControls_rku50_173",PZ="_navigatorSearchRow_rku50_179",EZ="_navigatorSearch_rku50_179",NZ="_navigatorClearSearch_rku50_223",MZ="_navigatorOptions_rku50_244",DZ="_navigatorOptionField_rku50_255",LZ="_navigatorOptionLabel_rku50_262",OZ="_navigatorDropdown_rku50_268",BZ="_navigatorDropdownTrigger_rku50_282",WZ="_navigatorEmpty_rku50_295",$Z="_scopeSummary_rku50_324",FZ="_treeList_rku50_361",UZ="_treeChildren_rku50_374",zZ="_treeTaskChildren_rku50_384",HZ="_visuallyHidden_rku50_388",GZ="_treeRow_rku50_408",VZ="_detailChildCard_rku50_409",KZ="_treeRowShell_rku50_429",qZ="_treeRowShellDraggable_rku50_434",YZ="_treeRowArchived_rku50_441",ZZ="_rowButton_rku50_446",JZ="_treeRowDetailOpen_rku50_451",QZ="_treeRowDropReady_rku50_469",XZ="_treeRowDropActive_rku50_473",eJ="_treeRowDropMode_rku50_479",tJ="_treeChevron_rku50_479",rJ="_scopeButton_rku50_481",aJ="_favoriteButton_rku50_482",nJ="_treeRowShellDropMode_rku50_483",sJ="_dragHandle_rku50_483",oJ="_treeRowDragging_rku50_487",iJ="_rowDragGutter_rku50_495",cJ="_rowBody_rku50_502",lJ="_rowContent_rku50_525",dJ="_rowTopRow_rku50_535",uJ="_rowReferenceActions_rku50_544",pJ="_rowActions_rku50_559",fJ="_emptyPanel_rku50_603",mJ="_emptyPanelTitle_rku50_612",hJ="_emptyPanelText_rku50_618",gJ="_loadingState_rku50_624",yJ="_loadingRow_rku50_630",kJ="_loadingBadge_rku50_642",vJ="_loadingTitle_rku50_643",wJ="_loadingMeta_rku50_644",bJ="_failureState_rku50_665",SJ="_failureStateCompact_rku50_674",AJ="_failureCopy_rku50_678",CJ="_relationshipState_rku50_704",IJ="_relationshipStateTitle_rku50_715",_J="_relationshipStateText_rku50_721",TJ="_relationshipPaneContentEmpty_rku50_728",xJ="_relationshipStateEmpty_rku50_738",RJ="_detailHero_rku50_752",jJ="_detailReferenceRow_rku50_759",PJ="_detailTitle_rku50_766",EJ="_detailTopRow_rku50_773",NJ="_detailTopActions_rku50_780",MJ="_detailDescription_rku50_788",DJ="_detailDescriptionMarkdown_rku50_801",LJ="_detailOwnerField_rku50_811",OJ="_detailOwnerLabel_rku50_817",BJ="_detailSummaryMeta_rku50_823",WJ="_passiveGuidance_rku50_827",$J="_editorCard_rku50_842",FJ="_inlineEditorCard_rku50_849",UJ="_editorSelect_rku50_854",zJ="_ownerSelect_rku50_858",HJ="_editorField_rku50_862",GJ="_editorLabel_rku50_868",VJ="_editorActions_rku50_874",KJ="_listCard_rku50_894",qJ="_activityTimelineList_rku50_903",YJ="_activityTimelineEmpty_rku50_909",ZJ="_sectionDropReady_rku50_913",JJ="_sectionDropActive_rku50_918",QJ="_sectionDropMode_rku50_924",XJ="_linkPickerRow_rku50_928",eQ="_editorRelationshipRow_rku50_929",tQ="_relationshipRecovery_rku50_936",rQ="_listItem_rku50_952",aQ="_listItemButton_rku50_961",nQ="_detailCardButton_rku50_970",sQ="_listItemText_rku50_976",oQ="_detailChildCardSelected_rku50_1000",iQ="_detailChildCardArchived_rku50_1008",cQ="_detailChildReferenceRow_rku50_1013",lQ="_detailChildCardTopRow_rku50_1019",dQ="_detailChildActions_rku50_1035",uQ="_relationshipPickerRow_rku50_1044",pQ="_detailTitleRow_rku50_1049",fQ="_editorIdentityField_rku50_1056",Ue={drawer:uZ,drawerBody:pZ,paneShell:fZ,collapsedPaneShell:mZ,collapsedPaneHeader:hZ,collapsedPaneLabel:gZ,collapsedPaneMuted:yZ,treePane:kZ,treePaneSplit:vZ,detailPane:wZ,paneHeader:bZ,paneHeaderLabel:SZ,paneContent:AZ,sectionTitle:CZ,sectionHeaderRow:IZ,headerActionGroup:_Z,toggleActive:TZ,archiveVisibilityToggle:xZ,sectionGroup:RZ,navigatorControls:jZ,navigatorSearchRow:PZ,navigatorSearch:EZ,navigatorClearSearch:NZ,navigatorOptions:MZ,navigatorOptionField:DZ,navigatorOptionLabel:LZ,navigatorDropdown:OZ,navigatorDropdownTrigger:BZ,navigatorEmpty:WZ,scopeSummary:$Z,treeList:FZ,treeChildren:UZ,treeTaskChildren:zZ,visuallyHidden:HZ,treeRow:GZ,detailChildCard:VZ,treeRowShell:KZ,treeRowShellDraggable:qZ,treeRowArchived:YZ,rowButton:ZZ,treeRowDetailOpen:JZ,treeRowDropReady:QZ,treeRowDropActive:XZ,treeRowDropMode:eJ,treeChevron:tJ,scopeButton:rJ,favoriteButton:aJ,treeRowShellDropMode:nJ,dragHandle:sJ,treeRowDragging:oJ,rowDragGutter:iJ,rowBody:cJ,rowContent:lJ,rowTopRow:dJ,rowReferenceActions:uJ,rowActions:pJ,emptyPanel:fJ,emptyPanelTitle:mJ,emptyPanelText:hJ,loadingState:gJ,loadingRow:yJ,loadingBadge:kJ,loadingTitle:vJ,loadingMeta:wJ,failureState:bJ,failureStateCompact:SJ,failureCopy:AJ,relationshipState:CJ,relationshipStateTitle:IJ,relationshipStateText:_J,relationshipPaneContentEmpty:TJ,relationshipStateEmpty:xJ,detailHero:RJ,detailReferenceRow:jJ,detailTitle:PJ,detailTopRow:EJ,detailTopActions:NJ,detailDescription:MJ,detailDescriptionMarkdown:DJ,detailOwnerField:LJ,detailOwnerLabel:OJ,detailSummaryMeta:BJ,passiveGuidance:WJ,editorCard:$J,inlineEditorCard:FJ,editorSelect:UJ,ownerSelect:zJ,editorField:HJ,editorLabel:GJ,editorActions:VJ,listCard:KJ,activityTimelineList:qJ,activityTimelineEmpty:YJ,sectionDropReady:ZJ,sectionDropActive:JJ,sectionDropMode:QJ,linkPickerRow:XJ,editorRelationshipRow:eQ,relationshipRecovery:tQ,listItem:rQ,listItemButton:aQ,detailCardButton:nQ,listItemText:sQ,detailChildCardSelected:oQ,detailChildCardArchived:iQ,detailChildReferenceRow:cQ,detailChildCardTopRow:lQ,detailChildActions:dQ,relationshipPickerRow:uQ,detailTitleRow:pQ,editorIdentityField:fQ},mQ="_description_ued10_1",hQ="_visuallyHidden_ued10_6",hg={description:mQ,visuallyHidden:hQ},gQ=Y.lazy(()=>Lo(()=>import("./EntityActivityTimeline-BtSTq0ON.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.EntityActivityTimeline}))),yQ=Y.lazy(()=>Lo(()=>import("./ContextAttachmentManager-B8boOs6Q.js"),__vite__mapDeps([8,1,2,3,4,5])).then(e=>({default:e.ContextAttachmentManager})));function m_(){return a.jsx("span",{className:hg.visuallyHidden,"aria-hidden":"true",children:"Loading planning details"})}function kQ({description:e,label:t,taskReferences:r,className:n,markdownClassName:s}){const i=String(e||"").trim();return i?a.jsx("div",{className:`${hg.description} ${n||""}`.trim(),role:"region",tabIndex:0,"aria-label":`${t} description`,children:a.jsx(Mg,{variant:"detail",className:s,taskReferences:r,children:i})}):null}function vQ({entityType:e,entityId:t,referenceLabel:r,workspaceId:n,attachments:s,onAddAttachment:i,onRemoveAttachment:l,onUpdateAttachmentCaption:c,readOnly:d=!1,defaultExpanded:f=!0}){return a.jsx(Y.Suspense,{fallback:a.jsx(m_,{}),children:a.jsx(yQ,{ownerType:e,ownerId:t,ownerReferenceLabel:r,workspaceId:n,attachments:s||[],onAddAttachment:p=>i?.(p),onRemoveAttachment:p=>l?.(p),onUpdateAttachmentCaption:(p,g)=>c?.(p,g),readOnly:d,defaultExpanded:f})})}function wQ({entityType:e,item:t,assigneeOptions:r,currentActorId:n,taskReferences:s,parentInitiative:i=null,defaultExpanded:l=!1,listClassName:c,emptyClassName:d,hydrationState:f,onRetryHydration:p}){const[g,h]=Y.useState(l);Y.useEffect(()=>{h(l)},[l,e,t.id]),Y.useEffect(()=>{if(!(f?.status!=="error"||!p))return window.addEventListener("online",p),()=>window.removeEventListener("online",p)},[f?.status,p]);const y=Y.useMemo(()=>{const E=new Map;for(const x of r){const N=String(x.value||"").trim();N&&(E.set(N,x),E.set(N.toLowerCase(),x))}return E},[r]),k=Y.useCallback((E,x,N)=>{if(N&&N.trim())return N.trim();const v=String(E||"").trim();return v?y.get(v)?.label||y.get(v.toLowerCase())?.label||v:x==="ai"?"AI Agent":"You"},[y]),b=Y.useCallback(E=>{const x=String(E.actorId||"").trim();if(zI(x))return{kind:"system",label:FI,ActorIcon:oA,description:UI};const N=y.get(x)||y.get(x.toLowerCase()),v=E.actorProfile||N||null,V=E.actorType==="system"?"system":E.actorType==="ai"||v?.kind==="ai"||N?.kind==="agent"?"agent":E.actorType==="human"||v?.kind==="human"||N?.kind==="member"?"member":E.fallbackKind||"member",_=String(v&&"icon"in v&&v.icon?v.icon:V==="agent"?"Bot":V==="member"?"User":"ClipboardList"),j=Hu[_]||(V==="agent"?yd:V==="member"?Du:iA);return{kind:V,label:V==="system"?"System":k(x,V==="agent"?"ai":"human",v&&"label"in v&&v.label||null),color:v&&"color"in v&&v.color||void 0,ActorIcon:j,isCurrentActorHint:V==="member"&&(x===""||x.toLowerCase()==="user"||x.toLowerCase()==="human")}},[y,k]),C=Y.useCallback((E,x)=>{const N=String(x||"").trim();if(N){if(E==="ownerId")return y.get(N)?.label||y.get(N.toLowerCase())?.label||N;if(E==="initiativeId"&&i&&N===i.id)return fs(i)||i.title}},[y,i]),S=Y.useMemo(()=>vI({activity:t.activity,comments:t.comments}).length,[t.activity,t.comments]),w=Y.useCallback(()=>{h(E=>{const x=!E;return x&&f?.status==="error"&&p?.(),x})},[f?.status,p]),T=f?.error?`${f.error} Retry activity refresh`:"Retry activity refresh";return a.jsxs(a.Fragment,{children:[a.jsx(_f,{label:"Activity",count:S,showZeroCount:!0,expanded:g,expandedTitle:"Hide activity",collapsedTitle:"Show activity",onToggle:w,actions:f?.status==="error"&&p?a.jsx("button",{type:"button",className:"tf-control-icon",onClick:p,"aria-label":"Retry activity refresh",title:T,children:a.jsx(bi,{size:13,"aria-hidden":"true"})}):null}),f?.status==="loading"?a.jsx("span",{className:hg.visuallyHidden,role:"status","aria-live":"polite",children:"Loading latest activity…"}):null,f?.status==="error"?a.jsx("span",{className:hg.visuallyHidden,role:"status","aria-live":"polite",children:"Activity could not be refreshed. Existing activity is still shown."}):null,g?a.jsx(Y.Suspense,{fallback:a.jsx(m_,{}),children:a.jsx(gQ,{activity:t.activity,comments:t.comments,formatFieldValue:C,resolveActorPresentation:b,currentActorId:n,taskReferences:s,emptyMessage:`No ${e} activity yet.`,listClassName:c,emptyClassName:d})}):null]})}const bQ="_identity_1yyv1_1",SQ="_avatar_1yyv1_9",AQ="_picker_1yyv1_16",CQ="_identityDropdown_1yyv1_17",jh={identity:bQ,avatar:SQ,picker:AQ,identityDropdown:CQ};function h_({role:e,option:t,label:r,value:n,options:s=[],onChange:i,disabled:l=!1}){const[c,d]=Y.useState(!1),f=String(t?.label||r||"").trim(),p=t||(f?{...Cd,value:f,label:f,icon:"User",kind:"member"}:Cd),g=e==="owner"?`Owner: ${p.label}`:`Assigned to ${p.label}`,h=e==="owner"?`Change owner currently set to ${p.label}`:`Reassign task currently assigned to ${p.label}`,y=Y.useMemo(()=>$u(s),[s]),k=Y.useMemo(()=>new Map(y.map(S=>[S.value,S])),[y]),b=a.jsx("span",{className:jh.identity,title:i&&!l?h:g,"aria-label":g,children:a.jsx("span",{className:jh.avatar,children:a.jsx(Lg,{option:p,size:22,variant:"card"})})});if(!i||l)return b;const C=String(n||t?.value||Cd.value);return a.jsx("span",{className:jh.picker,onClick:S=>S.stopPropagation(),onPointerDown:S=>S.stopPropagation(),onKeyDown:S=>S.stopPropagation(),children:a.jsx(ai,{value:C,options:y,onChange:async S=>{d(!0);try{await i(String(S))}catch{}finally{d(!1)}},disabled:c,ariaLabel:h,className:jh.identityDropdown,hideChevron:!0,portalPanel:!0,panelAlign:"end",panelMinWidth:240,searchable:!0,searchPlaceholder:e==="owner"?"Search owners...":"Search assignees...",noResultsText:e==="owner"?"No owners found.":"No assignees found.",renderOptionContent:S=>{const w=k.get(String(S.value));return w?a.jsx(qu,{option:w}):S.label},triggerContent:b})})}const IQ="_referenceBadgeButton_1ko1c_1",_Q="_referenceBadgeStatic_1ko1c_2",TQ="_summaryLayout_1ko1c_8",xQ="_summaryContent_1ko1c_17",RQ="_title_1ko1c_29",jQ="_meta_1ko1c_43",PQ="_cardFooter_1ko1c_54",EQ="_cardFooterMeta_1ko1c_63",NQ="_noTasks_1ko1c_71",MQ="_scopeCount_1ko1c_79",DQ="_contextCount_1ko1c_84",LQ="_progressTrack_1ko1c_91",OQ="_progressSegment_1ko1c_100",BQ="_progressSegmentCancelled_1ko1c_106",WQ="_progressSegmentTodo_1ko1c_110",$Q="_progressFill_1ko1c_114",Es={referenceBadgeButton:IQ,referenceBadgeStatic:_Q,summaryLayout:TQ,summaryContent:xQ,title:RQ,meta:jQ,cardFooter:PQ,cardFooterMeta:EQ,noTasks:NQ,scopeCount:MQ,contextCount:DQ,progressTrack:LQ,progressSegment:OQ,progressSegmentCancelled:BQ,progressSegmentTodo:WQ,progressFill:$Q},FQ=["done","review","in-progress","on-hold","cancelled","task"];function _d({label:e,entityType:t,entityName:r,interactive:n=!0,provisional:s=!1,pending:i=!1}){const[l,c]=Y.useState(!1),d=s||i?R.provisionalReferenceBadge:"",f=r?.trim(),p=Y.useCallback(async g=>{g.stopPropagation();try{await navigator.clipboard.writeText(e),c(!0),window.setTimeout(()=>c(!1),1200)}catch{c(!1)}},[e]);return!n||i?a.jsx("span",{className:`${R.referenceBadge} ${R.referenceBadgeStatic} ${Es.referenceBadgeStatic} ${d}`.trim(),title:i?"Canonical reference pending synchronization.":f||(s?"Temporary identifier — replaced after synchronization.":void 0),children:a.jsx("span",{children:e})}):a.jsx(nw,{copied:l,label:e,onClick:p,title:f||(s?"Temporary identifier — replaced after synchronization.":`Copy ${t} reference`),ariaLabel:l?`Copied ${s?"temporary ":""}${t} reference`:s?`Copy temporary ${t} reference ${e}`:`Copy ${t} reference`,className:`${Es.referenceBadgeButton} ${d}`.trim(),children:e})}function g_({children:e}){return a.jsx("span",{className:Es.title,"data-planning-card-title":"true",children:e})}function y_({children:e,className:t=""}){return a.jsx("span",{className:`${Es.meta} ${t}`.trim(),children:e})}function k_(){return a.jsx("span",{className:Es.noTasks,children:"No tasks yet"})}function v_({children:e,identity:t}){return a.jsxs("div",{className:Es.cardFooter,children:[a.jsx("div",{className:Es.cardFooterMeta,children:e}),t]})}function w_({count:e}){const t=Math.max(0,Number(e)||0),r=`${t} context ${t===1?"item":"items"}`;return a.jsxs("span",{className:Es.contextCount,"aria-label":r,title:r,children:[a.jsx(p0,{size:12,"aria-hidden":"true"}),a.jsx("span",{"aria-hidden":"true",children:t})]})}function b_({value:e,label:t,statusCounts:r}){const n=Math.min(100,Math.max(0,Number(e)||0)),s=FQ.map(d=>{const f=Math.max(0,Number(r?.[d])||0),p=Po(d);return{status:d,count:f,label:p.shortLabel||p.label,color:d==="task"||d==="cancelled"?void 0:rn(p.color)}}),i=s.reduce((d,f)=>d+f.count,0),l=s.filter(d=>d.count>0).map(d=>`${d.label}: ${d.count}`).join(", "),c=l?`${t}. ${l}`:t;return a.jsx("div",{className:Es.progressTrack,role:"progressbar","aria-label":c,title:l||void 0,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":n,children:i>0?s.map(d=>d.count>0?a.jsx("span",{"aria-hidden":"true","data-progress-status":d.status,className:`${Es.progressSegment} ${d.status==="cancelled"?Es.progressSegmentCancelled:""} ${d.status==="task"?Es.progressSegmentTodo:""}`.trim(),style:{width:`${d.count/i*100}%`,backgroundColor:d.color}},d.status):null):a.jsx("span",{className:Es.progressFill,style:{width:`${n}%`},"aria-hidden":"true"})})}function S_({item:e,workstreamCount:t,className:r=""}){const n=e.taskCount>0,s=Math.max(0,Number(t)||0);return a.jsxs(y_,{className:r,children:[t!==void 0?a.jsxs(a.Fragment,{children:[a.jsxs("span",{className:Es.scopeCount,children:[s," ",s===1?"workstream":"workstreams"]}),a.jsx("span",{"aria-hidden":"true",children:"•"})]}):null,n?a.jsxs(a.Fragment,{children:[a.jsxs("span",{children:[e.completedTaskCount," of ",e.taskCount," complete"]}),a.jsx("span",{"aria-hidden":"true",children:"•"})]}):null,a.jsx(w_,{count:e.attachmentCount})]})}function A_({item:e,entityType:t,workstreamCount:r,ownerOption:n,ownerOptions:s,onChangeOwner:i,onChangeIdentity:l}){const c=e.taskCount>0;return a.jsxs("div",{className:Es.summaryLayout,children:[a.jsx(Jf,{entityType:t,entityId:e.id,icon:e.icon,color:e.color,disabled:!!e.isArchived,onChange:l}),a.jsxs("div",{className:Es.summaryContent,children:[a.jsx(g_,{children:e.title}),c?a.jsx(b_,{value:e.progressPercent,label:`${e.title}: ${e.progressPercent}% resolved`,statusCounts:e.statusCounts}):null,a.jsxs(v_,{identity:a.jsx(h_,{role:"owner",option:n,label:e.ownerLabel,value:e.ownerId,options:s,onChange:i,disabled:!!e.isArchived}),children:[c?null:a.jsx(k_,{}),a.jsx(S_,{item:e,workstreamCount:t==="initiative"?r:void 0})]})]})]})}const UQ="_card_6phn6_1",zQ="_content_6phn6_34",HQ="_compact_6phn6_52",GQ="_archived_6phn6_57",VQ="_referenceRow_6phn6_75",KQ="_topRow_6phn6_85",qQ="_actions_6phn6_101",dd={card:UQ,content:zQ,compact:HQ,archived:GQ,referenceRow:VQ,topRow:KQ,actions:qQ};function C_({task:e,assigneeOption:t,assigneeOptions:r,showStatusLabel:n,onOpen:s,onAssigneeChange:i,onStatusChange:l,referenceAction:c,actions:d,feedback:f,referenceInteractive:p=!0,compact:g=!1}){const h=xv(e),y=h.label,k=Po(e.status),b=k.value==="task"?"":k.shortLabel||k.label,C=rn(k.color),S=y?`Open task ${y}: ${e.title}`:`Open task ${e.title}`,w=T=>{!s||T.key!=="Enter"&&T.key!==" "||(T.preventDefault(),s())};return a.jsxs("div",{className:`${dd.card} ${g?dd.compact:""} ${e.isArchived?dd.archived:""}`.trim(),"data-task-status":k.value,style:{"--planning-task-status-color":C},children:[a.jsxs("div",{className:dd.topRow,children:[a.jsxs("div",{className:dd.referenceRow,children:[c,y?a.jsx(_d,{label:y,entityType:"task",interactive:p,provisional:h.isProvisional}):a.jsx("span",{"aria-hidden":"true"})]}),a.jsxs("div",{className:dd.actions,onClick:T=>T.stopPropagation(),children:[d,a.jsx(ig,{status:k.value,disabled:!!e.isArchived||!l,compressed:!0,shortLabels:!0,showLabel:n,archiveActionMode:"none",onStatusChange:l})]})]}),f,a.jsxs("div",{role:s?"button":void 0,tabIndex:s?0:void 0,className:dd.content,onClick:s,onKeyDown:w,"aria-label":s?S:void 0,children:[a.jsx(g_,{children:e.title}),a.jsx(v_,{identity:a.jsx(h_,{role:"assignee",option:t,value:e.assignee,options:r,onChange:i,disabled:!!e.isArchived}),children:a.jsxs(y_,{children:[b?a.jsxs(a.Fragment,{children:[b,a.jsx("span",{"aria-hidden":"true",children:" • "})]}):null,a.jsx(w_,{count:e.attachmentCount}),e.isArchived?a.jsxs(a.Fragment,{children:[a.jsx("span",{"aria-hidden":"true",children:" • "}),"archived"]}):null]})})]})]})}const bk=Object.freeze([{value:"execution",label:"Execution order",description:"Shared order planned for this workstream."},{value:"ready",label:"Ready first",description:"Shows tasks with completed prerequisites first."},{value:"priority",label:"Priority",description:"Shows higher-priority tasks first."}]);function YQ(e){return e==="ready"||e==="priority"?e:"execution"}function ZQ(e,t){const r=new Set(t);if(r.size!==t.length)throw new Error("Visible task order contains duplicate task ids.");if(e.filter(i=>r.has(i.id)).length!==r.size)throw new Error("Visible task order contains tasks outside this workstream.");let s=0;return e.map(i=>r.has(i.id)?t[s++]:i.id)}function wf(e){const t=Po(e.status).value;return t==="done"||t==="cancelled"}function dw(e,t){const r=typeof e.workstreamOrder=="number"&&Number.isFinite(e.workstreamOrder)?e.workstreamOrder:Number.POSITIVE_INFINITY,n=typeof t.workstreamOrder=="number"&&Number.isFinite(t.workstreamOrder)?t.workstreamOrder:Number.POSITIVE_INFINITY;return r!==n?r-n:String(e.createdAt||"").localeCompare(String(t.createdAt||""))||e.id.localeCompare(t.id)}function HS(e,t){return e.dependencyState?e.dependencyState==="ready":(e.prerequisiteTaskIds||[]).every(r=>Po(t.get(r)?.status).value==="done")}function gg(e){return e.map((t,r)=>({task:t,index:r})).sort((t,r)=>dw(t.task,r.task)||t.index-r.index).map(({task:t})=>t)}function JQ(e,t){const r=new Set(e.map(f=>f.id)),n=new Map,s=new Map(e.map(f=>[f.id,0]));for(const f of e)for(const p of f.prerequisiteTaskIds||[]){const g=t.get(p);!g||wf(g)||!r.has(p)||(n.set(p,[...n.get(p)||[],f.id]),s.set(f.id,(s.get(f.id)||0)+1))}const i=new Map(e.map(f=>[f.id,f])),l=gg(e.filter(f=>s.get(f.id)===0)),c=[];for(;l.length>0;){const f=l.shift();c.push(f);for(const p of n.get(f.id)||[]){const g=(s.get(p)||0)-1;if(s.set(p,g),g===0){const h=i.get(p);h&&(l.push(h),l.sort(dw))}}}if(c.length===e.length)return c;const d=new Set(c.map(f=>f.id));return[...c,...gg(e.filter(f=>!d.has(f.id)))]}function uv(e,t){const r=new Map(e.map(n=>[n.id,n]));if(t==="ready"){const n=e.filter(l=>!wf(l)),s=gg(n.filter(l=>HS(l,r))),i=JQ(n.filter(l=>!HS(l,r)),r);return[...s,...i,...gg(e.filter(wf))]}return e.map((n,s)=>({task:n,index:s})).sort((n,s)=>{const i=n.task,l=s.task,c=Number(wf(i))-Number(wf(l));if(c)return c;if(t==="priority"){const d=Number(l.priority||0)-Number(i.priority||0);if(d)return d}return dw(i,l)||n.index-s.index}).map(({task:n})=>n)}const QQ="_control_1n99m_1",uw={control:QQ},XQ="_trigger_11iyx_1",eX={trigger:XQ};function tX({value:e,onChange:t}){const r=bk.find(n=>n.value===e)||bk[0];return a.jsx(ai,{value:e,options:[...bk],onChange:n=>t(n),ariaLabel:"Arrange workstream tasks",className:uw.control,portalPanel:!0,panelAlign:"end",triggerContent:a.jsxs("span",{className:eX.trigger,title:r.description,children:[a.jsx(kv,{size:14,"aria-hidden":"true"}),a.jsx("span",{children:r.label})]})})}const rX="_list_oepxi_1",aX="_item_oepxi_6",nX="_grip_oepxi_13",sX="_card_oepxi_40",xf={list:rX,item:aX,grip:nX,card:sX};function oX(e){const t=Cv({id:e.task.id,disabled:e.disabled});return a.jsxs("div",{ref:t.setNodeRef,className:xf.item,style:{transform:Sg.Transform.toString(t.transform),transition:t.transition},children:[a.jsx("button",{type:"button",className:xf.grip,disabled:e.disabled,"aria-label":`Reorder ${e.task.title}`,title:"Drag to change execution order",...t.attributes,...t.listeners,children:a.jsx(yv,{size:15,"aria-hidden":"true"})}),a.jsx("div",{className:xf.card,children:e.children})]})}function iX(e){const[t,r]=Y.useState(()=>e.tasks.map(p=>p.id)),[n,s]=Y.useState(!1),i=e.tasks.map(p=>p.id).join("\0");Y.useEffect(()=>r(e.tasks.map(p=>p.id)),[i]);const l=vv(Mf(wv,{activationConstraint:{distance:6}}),Mf(vA,{coordinateGetter:kA})),c=Y.useMemo(()=>{const p=new Map(e.tasks.map(g=>[g.id,g]));return t.map(g=>p.get(g)).filter(g=>!!g)},[t,e.tasks]),d=e.mode==="execution"&&!!e.onReorder,f=Y.useCallback(async p=>{if(!d||n||!p.over||p.active.id===p.over.id)return;const g=t,h=g.indexOf(String(p.active.id)),y=g.indexOf(String(p.over.id));if(h<0||y<0)return;const k=new Map(c.map(S=>[S.id,S])),b=S=>S?.status==="done"||S?.status==="cancelled";if(b(k.get(g[h]))!==b(k.get(g[y])))return;const C=gA(g,h,y);r(C),s(!0);try{await e.onReorder?.(C)}catch{r(g)}finally{s(!1)}},[d,t,c,e,n]);return d?a.jsx(bv,{sensors:l,collisionDetection:yA,onDragEnd:p=>{f(p)},children:a.jsx(Sv,{items:t,strategy:Av,children:a.jsx("div",{className:`${xf.list} ${e.className||""}`.trim(),"aria-busy":n||void 0,children:c.map(p=>a.jsx(oX,{task:p,disabled:n,children:e.children(p)},p.id))})})}):a.jsx("div",{className:`${xf.list} ${e.className||""}`.trim(),children:e.tasks.map(p=>a.jsx(Y.Fragment,{children:e.children(p)},p.id))})}const cX="_prompt_16ixe_1",lX="_actions_16ixe_20",GS={prompt:cX,actions:lX};function pv({entityType:e,title:t,activeTaskCount:r=0,activeWorkstreamCount:n=0,busy:s,onCancel:i,onConfirm:l}){const c=[r>0?`${r} completed/cancelled ${r===1?"task":"tasks"}`:"",e==="initiative"&&n>0?`${n} ${n===1?"workstream":"workstreams"}`:""].filter(Boolean),d=c.length===0?"":c.length===1?`${c[0]} and `:`${c.join(", ")}, and `;return a.jsxs("div",{className:`${GS.prompt} tf-surface-inset`,role:"group","aria-label":`Confirm archive ${e} ${t}`,children:[a.jsxs("span",{children:["Archive ",d,"this ",e,"?"]}),a.jsxs("div",{className:GS.actions,children:[a.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",disabled:s,onClick:i,title:"Cancel archive","aria-label":"Cancel archive",children:a.jsx(Mo,{size:14,"aria-hidden":"true"})}),a.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",disabled:s,onClick:l,title:"Confirm archive","aria-label":s?"Archiving":"Confirm archive",children:a.jsx(Si,{size:14,"aria-hidden":"true"})})]})]})}const dX="_title_sy4bx_1",uX="_content_sy4bx_7",pX="_help_sy4bx_17",fX="_actions_sy4bx_22",Ph={title:dX,content:uX,help:pX,actions:fX};function mX({item:e,busy:t,theme:r,onCancel:n,onConfirm:s}){return a.jsx(Do,{isOpen:!!e,onClose:n,closeDisabled:t,closeOnOverlayClick:!1,size:"sm",theme:r,title:a.jsxs("span",{className:Ph.title,children:[a.jsx(Sf,{size:17,"aria-hidden":"true"}),"Unlink ",e?.entityType||"item"]}),footer:a.jsxs("div",{className:Ph.actions,children:[a.jsx("button",{type:"button",className:"tf-button-secondary",disabled:t,onClick:n,"data-modal-initial-focus":!0,children:"Cancel"}),a.jsx("button",{type:"button",className:"tf-button-destructive",disabled:t,onClick:s,children:t?"Unlinking…":"Unlink"})]}),children:e?a.jsxs("div",{className:Ph.content,children:[a.jsxs("p",{children:["Unlink ",a.jsx("strong",{children:e.referenceLabel})," ",e.title," from ",e.parentLabel,"?"]}),a.jsx("p",{className:Ph.help,children:"The item will remain available and can be linked again later."})]}):null})}const hX="_triggerAction_ssrgo_1",gX="_triggerSelection_ssrgo_2",yX="_iconPicker_ssrgo_9",kX="_option_ssrgo_20",vX="_optionTopRow_ssrgo_27",wX="_optionTitle_ssrgo_38",bX="_optionMeta_ssrgo_47",ud={triggerAction:hX,triggerSelection:gX,iconPicker:yX,option:kX,optionTopRow:vX,optionTitle:wX,optionMeta:bX};function yg({options:e,selectedId:t="",entityLabel:r,onSelect:n,disabled:s=!1,className:i="",iconTrigger:l=!1,triggerTitle:c}){const d=Y.useMemo(()=>new Map(e.map(h=>[h.id,h])),[e]),f=Y.useMemo(()=>e.map(h=>({value:h.id,label:[h.referenceLabel,h.title,h.meta].filter(Boolean).join(" ")})),[e]),p=d.get(t),g=`Link ${r}`;return a.jsx(ai,{value:t,options:f,onChange:h=>{const y=d.get(String(h));y&&n(y)},disabled:s||e.length===0,className:`${l?`${ud.iconPicker} ${R.taskWorkstreamPicker}`:uw.control} ${i}`.trim(),portalPanel:!0,panelAlign:"start",panelMinWidth:320,searchable:!0,searchPlaceholder:`Search ${r}s by title or reference`,noResultsText:`No matching ${r}s.`,ariaLabel:g,title:l?c||g:void 0,hideChevron:l,triggerContent:l?a.jsx(Bu,{size:14,"aria-hidden":"true"}):p?a.jsxs("span",{className:ud.triggerSelection,children:[a.jsx(_d,{label:p.referenceLabel,entityType:r,entityName:p.title}),a.jsx("span",{children:p.title})]}):a.jsxs("span",{className:ud.triggerAction,children:[a.jsx(Bu,{size:14,"aria-hidden":"true"}),a.jsx("span",{children:g})]}),renderOptionContent:h=>{const y=d.get(String(h.value));return y?a.jsxs("span",{className:ud.option,children:[a.jsxs("span",{className:ud.optionTopRow,children:[r!=="task"?a.jsx(Jf,{entityType:r,entityId:y.id,icon:y.icon,color:y.color,size:"inline",disabled:!0}):null,a.jsx(_d,{label:y.referenceLabel,entityType:r,entityName:y.title}),a.jsx("span",{className:ud.optionTitle,children:y.title})]}),y.meta?a.jsx("span",{className:ud.optionMeta,children:y.meta}):null]}):h.label},placeholder:g})}function I_(e,t){const r=String(t||"").trim(),n=new Map;for(const s of e){const i=String(s?.value||"").trim();if(!i||i==="unassigned"||typeof s.archivedAt=="string"&&s.archivedAt.trim().length>0)continue;const l=String(s.label||i).trim()||i,c=String(s.kind||"").trim().toLowerCase(),d=String(s.username||"").trim().toLowerCase(),f=c==="agent"?`agent:${d||l.toLowerCase()}`:`value:${i}`;(!n.has(f)||i===r)&&n.set(f,{...s,value:i,label:l})}return Array.from(n.values()).sort((s,i)=>s.label.localeCompare(i.label,void 0,{sensitivity:"base"}))}function ec(e){const t=e.kind==="agent"?"agent":e.kind==="member"?"member":"unassigned";return{value:e.value,label:e.label,icon:e.icon||(t==="agent"?"Bot":t==="member"?"User":qf),color:e.color||(t==="agent"?"var(--brand-primary)":t==="member"?"var(--status-success)":xg),kind:t,avatarUrl:e.avatarUrl,avatarRevision:e.avatarRevision,avatarUpdatedAt:e.avatarUpdatedAt,username:e.username,surfaceType:e.surfaceType,providerMetadata:e.providerMetadata,archivedAt:e.archivedAt}}function pw({value:e,options:t,leadingOptions:r=[],includeUnassigned:n=!0,onChange:s,disabled:i,ariaLabel:l,className:c}){const d=Y.useMemo(()=>{const p=r.map(y=>({...y,value:String(y.value||"").trim(),label:String(y.label||y.value||"").trim()})).filter(y=>y.value&&y.label),g=new Set(p.map(y=>y.value)),h=I_(t,e).filter(y=>!g.has(y.value));return[...p,...n?[{value:"",label:"Unassigned",icon:qf,color:xg,kind:"unassigned"}]:[],...h]},[n,r,t,e]),f=Y.useMemo(()=>new Map(d.map(p=>[p.value,ec(p)])),[d]);return a.jsx(ai,{value:e,options:d.map(p=>({value:p.value,label:p.label,icon:p.icon||void 0,color:p.color||void 0})),onChange:p=>s(String(p)),disabled:i,ariaLabel:l,className:c,portalPanel:!0,panelAlign:"start",panelMinWidth:240,searchable:!0,searchPlaceholder:"Search owners...",noResultsText:"No owners found.",renderOptionContent:p=>{const g=f.get(String(p.value));return g?a.jsx(qu,{option:g}):p.label}})}const VS=[{value:"default",label:"Default order"},{value:"title",label:"Title"},{value:"owner",label:"Owner"},{value:"progress",label:"Progress"}];function Hh(e,t,r){if(t==="all")return!0;const n=String(e.ownerId||"").trim();return t==="unassigned"?!n:t==="mine"?!!r&&n===r:n===t}function Gh(e,t,r){if(!r)return!0;const n=t==="initiative"?fs(e):Eo(e);return e.title.toLocaleLowerCase().includes(r)||n.toLocaleLowerCase().includes(r)}function Sk({item:e,entityType:t,showArchivedPlanning:r,searchQuery:n,ownerFilter:s,currentOwnerId:i}){return(r||!e.isArchived)&&Hh(e,s,i.trim())&&Gh(e,t,n.trim().toLocaleLowerCase())}function Eh(e,t){return t==="default"?e:e.map((r,n)=>({item:r,index:n})).sort((r,n)=>{let s=0;if(t==="title")s=r.item.title.localeCompare(n.item.title,void 0,{sensitivity:"base"});else if(t==="owner"){const i=String(r.item.ownerLabel||"").trim(),l=String(n.item.ownerLabel||"").trim();!i&&l?s=1:i&&!l?s=-1:s=i.localeCompare(l,void 0,{sensitivity:"base"})}else s=n.item.progressPercent-r.item.progressPercent;return s||r.index-n.index}).map(({item:r})=>r)}function SX({initiatives:e,standaloneWorkstreams:t,showArchivedPlanning:r,searchQuery:n,ownerFilter:s,currentOwnerId:i,sort:l}){const c=n.trim().toLocaleLowerCase(),d=!!c||s!=="all",f=i.trim(),g=e.filter(C=>r||!C.isArchived).flatMap(C=>{const S=(C.allWorkstreams||C.workstreams).filter(V=>r||!V.isArchived);if(!d)return[{initiative:C,workstreams:Eh(S,l)}];const w=Hh(C,s,f),T=Gh(C,"initiative",c),E=w&&T,x=S.filter(V=>Hh(V,s,f)),N=x.filter(V=>Gh(V,"workstream",c)),v=E&&c?x:N;return!E&&v.length===0?[]:[{initiative:C,workstreams:Eh(v,l)}]}),h=new Map(g.map(C=>[C.initiative.id,C])),y=Eh(g.map(({initiative:C})=>C),l).map(C=>h.get(C.id)),k=t.filter(C=>(r||!C.isArchived)&&Hh(C,s,f)&&Gh(C,"workstream",c)),b=Eh(k,l);return{initiatives:y,standaloneWorkstreams:b,hasCriteria:d,resultCount:y.length+y.reduce((C,S)=>C+S.workstreams.length,0)+b.length}}const Rf=392,ac=392,Ak=56,__=1280,AX=Rf+ac;function CX(e,t=0){const r=Math.max(0,e-t);return r>=__?"wide":r>=AX?"medium":"narrow"}function IX(e){const t=Y.useCallback(()=>typeof window>"u"?__+e:window.innerWidth,[e]),[r,n]=Y.useState(t);return Y.useEffect(()=>{const s=()=>n(t());return s(),window.addEventListener("resize",s),()=>window.removeEventListener("resize",s)},[t]),{viewportWidth:r,availableWidth:Math.max(0,r-e),layoutMode:CX(r,e)}}function T_(e,t,r,n,s){return(e?Ak:Rf)+(t?r?Ak:ac:0)+(n?s?Ak:ac:0)}function Ck({visible:e,disabled:t,disabledLabel:r,itemLabel:n,onToggle:s}){const i=e?`Hide archived ${n}`:`Show archived ${n}`,l=t?r||`No archived ${n}`:i;return a.jsx("button",{type:"button",className:`tf-control-icon ${Ue.archiveVisibilityToggle} ${e?Ue.toggleActive:""}`.trim(),title:l,"aria-label":l,"aria-pressed":e,disabled:t,onClick:s,children:e?a.jsx(fA,{size:15,"aria-hidden":"true"}):a.jsx(f0,{size:15,"aria-hidden":"true"})})}function KS(e){return e.type==="initiative"?(e.item.allWorkstreams||e.item.workstreams).filter(t=>!!t.isArchived).length:(e.item.tasks||[]).filter(t=>!!t.isArchived).length}function lf({rowId:e,rowType:t,referenceLabel:r,item:n,ownerOption:s,ownerOptions:i,workstreamCount:l,active:c,isArchived:d=!1,detailOpen:f=!1,canExpand:p=!1,expanded:g=!1,controlsId:h,onToggleExpand:y,onToggleScope:k,onOpenDetails:b,onChangeOwner:C,onChangeIdentity:S,initiativeLinkOptions:w=[],onLinkInitiative:T,favorite:E,favoriteReady:x,onToggleFavorite:N,onArchiveReady:v,hierarchyInteractions:V=!0}){const{title:_}=n,[j,F]=Y.useState(!1),[z,M]=Y.useState(!1),[O,Z]=Y.useState(!1),{active:U}=wA(),ve=String(U?.data?.current?.type||""),te=V&&t==="workstream"&&ve==="task-card",ce=V&&t==="initiative"&&ve==="planning-workstream",Le=t==="workstream"?"planning-workstream-target":"planning-initiative-target",{setNodeRef:Ie,isOver:Ye}=Iv({id:`${Le}:${e}`,data:t==="workstream"?{type:Le,workstreamId:e}:{type:Le,initiativeId:e},disabled:!V}),ge=V&&t==="workstream",{attributes:he,listeners:Ae,setNodeRef:ye,setActivatorNodeRef:Ne,transform:ae,isDragging:q}=N0({id:`planning-workstream:${e}`,data:{type:"planning-workstream",workstreamId:e},disabled:!ge}),W=ge&&ae?{transform:Sg.Translate.toString(ae)}:void 0,K=te||ce,Re=t==="initiative"?"workstreams":"tasks",we=p&&!!y,ie=p?`${g?"Collapse":"Expand"} ${Re} for ${_}`:`No ${Re} for ${_}`,Q=!!(n.archiveReady&&!d&&v),H=Y.useRef({}),[se,Pe]=Y.useState("favorite"),ue=Y.useMemo(()=>[...x?["favorite"]:[],...Q?["archive"]:[],"scope",...we?["disclosure"]:[]],[Q,we,x]),ne=ue.includes(se)?se:ue[0];Y.useEffect(()=>{ne&&ne!==se&&Pe(ne)},[se,ne]);const Me=Y.useCallback(_e=>{Pe(_e)},[]),pe=Y.useCallback(_e=>{if(!["ArrowLeft","ArrowRight","Home","End"].includes(_e.key))return;const Ze=_e.target.closest("[data-planning-row-action]")?.dataset.planningRowAction;if(!Ze||!ue.includes(Ze))return;_e.preventDefault();const st=ue.indexOf(Ze),at=_e.key==="Home"?0:_e.key==="End"?ue.length-1:_e.key==="ArrowRight"?(st+1)%ue.length:(st-1+ue.length)%ue.length,oe=ue[at];Pe(oe),H.current[oe]?.focus()},[ue]),le=async()=>{if(!(!v||z)){M(!0);try{await v()&&F(!1)}finally{M(!1)}}},Ce=async _e=>{if(!(!T||O)){Z(!0);try{await T(_e)}finally{Z(!1)}}},P=t==="workstream"&&!!T,ee=d||O||w.length===0,Se=d?"Unarchive this workstream before linking an initiative":w.length===0?"No initiatives available":"Link initiative";return a.jsxs("div",{ref:ye,style:W,className:`${Ue.treeRowShell} ${ge?Ue.treeRowShellDraggable:""} ${q?Ue.treeRowDragging:""} ${K?Ue.treeRowShellDropMode:""}`.trim(),"data-planning-draggable-row":ge||void 0,children:[ge?a.jsx("div",{className:Ue.rowDragGutter,"data-planning-drag-gutter":"true",children:a.jsx("button",{type:"button",ref:Ne,className:Ue.dragHandle,title:"Drag onto an initiative to move this workstream","aria-label":`Move workstream ${_} to an initiative`,"data-planning-drag-handle":"true",...he,...Ae,children:a.jsx(yv,{size:15,"aria-hidden":"true"})})}):null,a.jsx("div",{ref:Ie,className:`${Ue.treeRow} ${d?Ue.treeRowArchived:""} ${f?Ue.treeRowDetailOpen:""} ${K?Ue.treeRowDropReady:""} ${Ye?Ue.treeRowDropActive:""} ${K?Ue.treeRowDropMode:""}`,"data-board-scoped":c||void 0,children:a.jsxs("div",{className:Ue.rowContent,children:[a.jsxs("div",{className:Ue.rowTopRow,children:[a.jsxs("div",{className:Ue.rowReferenceActions,children:[P?a.jsx(yg,{options:w,entityLabel:"initiative",onSelect:_e=>{Ce(_e)},disabled:ee,iconTrigger:!0,triggerTitle:Se}):null,a.jsx(_d,{label:r||"Reference pending",entityType:t,entityName:_,pending:!r})]}),a.jsxs("div",{className:Ue.rowActions,role:"toolbar","aria-label":`${t==="initiative"?"Initiative":"Workstream"} actions for ${_}`,"aria-orientation":"horizontal",onKeyDown:pe,children:[a.jsx("button",{type:"button",ref:_e=>{H.current.favorite=_e},className:`tf-control-icon tf-control-icon-compact ${Ue.favoriteButton} ${E?"tf-control-icon-active":""}`.trim(),onClick:N,onFocus:()=>Me("favorite"),disabled:!x,tabIndex:ne==="favorite"?0:-1,"data-planning-row-action":"favorite",title:x?E?`Remove ${t} from Favorites`:`Add ${t} to Favorites`:"Loading Favorites","aria-label":x?E?`Remove ${t} ${_} from Favorites`:`Add ${t} ${_} to Favorites`:`Loading Favorites for ${t} ${_}`,"aria-pressed":E,children:a.jsx(m0,{size:14,fill:E?"currentColor":"none","aria-hidden":"true"})}),Q?a.jsx("button",{type:"button",ref:_e=>{H.current.archive=_e},className:"tf-control-icon tf-control-icon-compact",onClick:()=>F(!0),onFocus:()=>Me("archive"),tabIndex:ne==="archive"?0:-1,"data-planning-row-action":"archive",title:`Archive completed ${t}`,"aria-label":`Archive completed ${t} ${_}`,"aria-expanded":j,children:a.jsx(Sd,{size:14,"aria-hidden":"true"})}):null,a.jsx("button",{type:"button",ref:_e=>{H.current.scope=_e},className:`tf-control-icon tf-control-icon-compact ${Ue.scopeButton} ${c?"tf-control-icon-active":""}`.trim(),onClick:k,onFocus:()=>Me("scope"),tabIndex:ne==="scope"?0:-1,"data-planning-row-action":"scope",title:c?"Clear board scope":"Scope board to this item","aria-label":c?`Clear board scope for ${_}`:`Scope board to ${_}`,"aria-pressed":c,children:a.jsx(h0,{size:14,"aria-hidden":"true"})}),a.jsx("button",{type:"button",ref:_e=>{H.current.disclosure=_e},className:`tf-control-icon tf-control-icon-compact ${Ue.treeChevron}`.trim(),onClick:we?y:void 0,onFocus:()=>Me("disclosure"),tabIndex:ne==="disclosure"?0:-1,"data-planning-row-action":"disclosure",title:ie,"aria-label":ie,"aria-expanded":we?g:!1,"aria-controls":we&&g?h:void 0,disabled:!we,children:g&&we?a.jsx(Nd,{size:14,"aria-hidden":"true"}):a.jsx(xd,{size:14,"aria-hidden":"true"})})]})]}),a.jsx("div",{className:Ue.rowBody,children:a.jsx("div",{role:"button",tabIndex:0,className:Ue.rowButton,onClick:b,onKeyDown:_e=>{_e.key!=="Enter"&&_e.key!==" "||(_e.preventDefault(),b())},"aria-label":`View ${t} details for ${_}`,"aria-pressed":f,children:a.jsx(A_,{item:n,entityType:t,workstreamCount:l,ownerOption:s?ec(s):void 0,ownerOptions:i.map(ec),onChangeOwner:C,onChangeIdentity:S})})}),j?a.jsx(pv,{entityType:t,title:_,activeTaskCount:n.archiveActiveTaskCount,activeWorkstreamCount:n.archiveActiveWorkstreamCount,busy:z,onCancel:()=>F(!1),onConfirm:()=>{le()}}):null]})})]})}function _X({task:e,assigneeOption:t,assigneeOptions:r,showTaskCardStatusLabel:n,onOpenTaskById:s,onChangeTaskAssignee:i,onSetTaskStatus:l,onArchivePlanningTask:c}){const[d,f]=Y.useState(!1),p=Po(e.status).value,g=!e.isArchived&&(p==="done"||p==="cancelled")&&!!c;return a.jsx("div",{className:`${Ue.listItemButton} ${Ue.detailCardButton}`.trim(),children:a.jsx(C_,{task:e,assigneeOption:t?ec(t):void 0,assigneeOptions:r.map(ec),showStatusLabel:n,onOpen:s?()=>s(e.id):void 0,onAssigneeChange:i?h=>i(e.id,h):void 0,onStatusChange:l?h=>l(e.id,h):void 0,actions:g?a.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",disabled:d,onClick:async h=>{h.stopPropagation(),f(!0);try{await c?.(e.id)}finally{f(!1)}},title:"Archive task","aria-label":`Archive task ${hs(e)||e.title}`,children:a.jsx(Sd,{size:14,"aria-hidden":"true"})}):void 0,compact:!0})})}function df({label:e,onExpand:t,muted:r=!1}){return a.jsx("div",{className:`${Ue.paneShell} ${Ue.collapsedPaneShell} ${r?Ue.collapsedPaneMuted:""}`.trim(),"data-relationship-state":r?"missing":void 0,children:a.jsxs("div",{className:Ue.collapsedPaneHeader,children:[a.jsx("button",{type:"button",className:"tf-control-icon",onClick:t,title:`Expand ${e}`,"aria-label":`Expand ${e} pane`,children:a.jsx(xd,{size:16,"aria-hidden":"true"})}),a.jsx("span",{className:Ue.collapsedPaneLabel,children:e})]})})}function qS({label:e,title:t,description:r,onCollapse:n,action:s,paneRef:i}){const l=!r&&!s;return a.jsxs("div",{ref:i,"data-planning-pane":`${e.toLowerCase()}-relationship`,className:`${Ue.paneShell} ${R.appScrollbar} tf-scrollbar ${Ue.detailPane}`.trim(),style:{flex:`0 0 ${ac}px`,width:`${ac}px`,minWidth:`${ac}px`,maxWidth:`${ac}px`},children:[a.jsxs("div",{className:Ue.paneHeader,children:[a.jsx("h2",{className:Ue.paneHeaderLabel,tabIndex:-1,"data-planning-pane-heading":!0,children:e}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:n,"aria-label":`Collapse ${e} pane`,title:`Collapse ${e} pane`,children:a.jsx(po,{size:16,"aria-hidden":"true"})})]}),a.jsx("div",{className:`${Ue.paneContent} ${l?Ue.relationshipPaneContentEmpty:""}`.trim(),children:a.jsxs("div",{className:`${Ue.relationshipState} ${l?Ue.relationshipStateEmpty:""}`.trim(),"data-relationship-display":l?"empty":"detail",children:[a.jsx("span",{className:Ue.relationshipStateTitle,children:t}),r?a.jsx("p",{className:Ue.relationshipStateText,children:r}):null,s?a.jsx("button",{type:"button",className:"tf-button-secondary tf-button-compact",onClick:s.onClick,children:s.label}):null]})})]})}function TX({initiatives:e,standaloneWorkstreams:t,planningLoadState:r,taskScope:n,showArchivedPlanning:s,currentOwnerId:i,assigneeOptions:l,showTaskCardStatusLabel:c=!1,taskArrangeMode:d="execution",activeInitiativeId:f,activeWorkstreamId:p,navigatorSort:g,navigatorSortReady:h,onNavigatorSortChange:y,planningFavorites:k,onTogglePlanningFavorite:b,favoritesSectionCollapsed:C,initiativesSectionCollapsed:S,workstreamsSectionCollapsed:w,onToggleFavoritesSection:T,onToggleInitiativesSection:E,onToggleWorkstreamsSection:x,expandedInitiativeIds:N,detail:v,secondaryPane:V,onCreateInitiative:_,onCreateWorkstream:j,onToggleInitiative:F,onSelectInitiative:z,onSelectWorkstream:M,onOpenInitiativeDetails:O,onOpenWorkstreamDetails:Z,onOpenNestedWorkstreamDetails:U,onOpenTaskById:ve,onSetTaskStatus:te,onChangePlanningOwner:ce,onChangePlanningIdentity:Le=()=>{},onChangeTaskAssignee:Ie,onArchivePlanningTask:Ye,onArchiveResolvedWorkstream:ge,onArchiveResolvedInitiative:he,linkOptions:Ae,onAssignInitiativeToWorkstream:ye,onRetryPlanning:Ne}){const[ae,q]=Y.useState(""),[W,K]=Y.useState("all"),[Re,we]=Y.useState(!1),[ie,Q]=Y.useState(()=>new Set),[H,se]=Y.useState(()=>new Set),Pe=Y.useMemo(()=>new Map(l.filter(G=>!String(G.archivedAt||"").trim()).map(G=>[String(G.value||"").trim(),G])),[l]),ue=Y.useMemo(()=>{const G=String(i||"").trim(),Be=G?I_(l,G).find(Xe=>Xe.value===G):void 0;return[{value:"all",label:"All owners",icon:"Users",color:"var(--text-secondary)",kind:"unassigned"},...G?[{...Be,value:"mine",label:"Owned by me",icon:Be?.icon||"User",color:Be?.color||"var(--text-secondary)",kind:Be?.kind||"member"}]:[],{value:"unassigned",label:"Unassigned",icon:qf,color:xg,kind:"unassigned"}]},[l,i]),ne=Y.useMemo(()=>SX({initiatives:e,standaloneWorkstreams:t,showArchivedPlanning:s,searchQuery:ae,ownerFilter:W,currentOwnerId:String(i||""),sort:g}),[i,e,g,W,ae,s,t]),Me=Y.useMemo(()=>new Set(k.map(Ji)),[k]),pe=Y.useMemo(()=>{const G=new Map(e.filter(Xe=>Sk({item:Xe,entityType:"initiative",showArchivedPlanning:s,searchQuery:ae,ownerFilter:W,currentOwnerId:String(i||"")})).map(Xe=>[Xe.id,Xe])),Be=new Map;return e.forEach(Xe=>{(Xe.allWorkstreams||Xe.workstreams).forEach(ze=>{Sk({item:ze,entityType:"workstream",showArchivedPlanning:s,searchQuery:ae,ownerFilter:W,currentOwnerId:String(i||"")})&&Be.set(ze.id,{item:ze,parentInitiativeId:Xe.id})})}),t.forEach(Xe=>{Sk({item:Xe,entityType:"workstream",showArchivedPlanning:s,searchQuery:ae,ownerFilter:W,currentOwnerId:String(i||"")})&&Be.set(Xe.id,{item:Xe,parentInitiativeId:null})}),k.reduce((Xe,ze)=>{if(ze.type==="initiative"){const Te=G.get(ze.id);return Te&&Xe.push({favorite:ze,item:Te,parentInitiativeId:null}),Xe}const qe=Be.get(ze.id);return qe&&Xe.push({favorite:ze,...qe}),Xe},[])},[i,e,W,k,ae,s,t]);if(n==="deleted")return a.jsxs("div",{className:Ue.scopeSummary,role:"status",children:[a.jsx("strong",{children:"Planning is not shown in Trash"}),a.jsx("span",{children:"Switch the task scope away from Trash to manage initiatives and workstreams."})]});if(r.status==="loading")return a.jsx(xX,{});if(r.status==="error")return a.jsx(Nh,{title:"Planning unavailable",message:r.error||"Planning could not be loaded.",retrying:r.isRefreshing,onRetry:Ne});const le=e.filter(G=>!!G.isArchived).length,Ce=t.filter(G=>!!G.isArchived).length,P=e.length>0||t.length>0,ee=ne.hasCriteria||g!=="default",Se=()=>{q(""),K("all"),h&&y("default")},_e=G=>{Q(Be=>{const Xe=new Set(Be);return Xe.has(G)?Xe.delete(G):Xe.add(G),Xe})},ke=G=>{se(Be=>{const Xe=new Set(Be);return Xe.has(G)?Xe.delete(G):Xe.add(G),Xe})},Ze=(G,Be=ie.has(G.id),Xe=`planning-tasks-${G.id}`,ze=`Tasks in ${G.title}`)=>{if(!Be)return null;const qe=G.tasks||[],Te=uv(s?qe:qe.filter(fe=>!fe.isArchived),d);return a.jsx("ul",{id:Xe,className:`${Ue.treeChildren} ${Ue.treeTaskChildren}`.trim(),"aria-label":ze,children:Te.length>0?Te.map(fe=>a.jsx("li",{children:a.jsx(_X,{task:fe,assigneeOption:fe.assignee?Pe.get(fe.assignee):void 0,assigneeOptions:l,showTaskCardStatusLabel:c,onOpenTaskById:ve,onSetTaskStatus:te,onChangeTaskAssignee:Ie,onArchivePlanningTask:Ye})},fe.id)):a.jsx("li",{className:Ue.passiveGuidance,children:"Archived tasks are hidden."})})},st=ne.hasCriteria?"No matching initiatives":le>0?"No active initiatives":"No initiatives yet",at=ne.hasCriteria?"No initiatives match the current planning search and owner filter.":le>0?`${le} archived ${le===1?"initiative is":"initiatives are"} hidden. Use the archive visibility control above to view ${le===1?"it":"them"}.`:a.jsxs(a.Fragment,{children:["Initiatives give larger efforts a clear home without crowding the task board. Use the ",a.jsx("code",{children:"+"})," action above to create the first one."]}),oe=ne.hasCriteria?"No matching standalone workstreams":Ce>0?"No active standalone workstreams":"No standalone workstreams yet",We=ne.hasCriteria?"No standalone workstreams match the current planning search and owner filter.":Ce>0?`${Ce} archived standalone ${Ce===1?"workstream is":"workstreams are"} hidden. Use the archive visibility control above to view ${Ce===1?"it":"them"}.`:a.jsxs(a.Fragment,{children:["Smaller projects can still use workstreams without needing initiative-level structure. Use the ",a.jsx("code",{children:"+"})," action above to add one."]});return a.jsxs(a.Fragment,{children:[r.status==="partial"&&r.collections.initiatives==="ready"&&r.collections.workstreams==="ready"?a.jsx(Nh,{compact:!0,title:"Planning may be incomplete",message:r.error||"The latest planning refresh did not finish. Existing data is still shown.",retrying:r.isRefreshing,onRetry:Ne}):null,P?a.jsxs("div",{className:Ue.navigatorControls,children:[a.jsxs("div",{className:Ue.navigatorSearchRow,children:[a.jsxs("div",{className:Ue.navigatorSearch,children:[a.jsx(bg,{size:14,"aria-hidden":"true"}),a.jsx("span",{className:Ue.visuallyHidden,children:"Search planning"}),a.jsx("input",{type:"search",value:ae,onChange:G=>q(G.target.value),placeholder:"Search initiatives and workstreams","aria-label":"Search planning"}),ae?a.jsx("button",{type:"button",className:Ue.navigatorClearSearch,onClick:()=>q(""),"aria-label":"Clear planning search",title:"Clear search",children:a.jsx(Mo,{size:13,"aria-hidden":"true"})}):null]}),a.jsx("button",{type:"button",className:`tf-control-icon ${Re||W!=="all"||g!=="default"?Ue.toggleActive:""}`.trim(),"aria-label":"Filter and sort planning",title:"Filter and sort planning","aria-expanded":Re,"aria-controls":"planning-navigator-options",onClick:()=>we(G=>!G),children:a.jsx(mA,{size:15,"aria-hidden":"true"})})]}),Re?a.jsxs("div",{id:"planning-navigator-options",className:Ue.navigatorOptions,children:[a.jsxs("div",{className:Ue.navigatorOptionField,children:[a.jsx("span",{className:Ue.navigatorOptionLabel,children:"Owner"}),a.jsx(pw,{value:W,options:l,leadingOptions:ue,includeUnassigned:!1,onChange:K,disabled:!1,ariaLabel:"Filter planning by owner",className:Ue.navigatorDropdown})]}),a.jsxs("div",{className:Ue.navigatorOptionField,children:[a.jsx("span",{className:Ue.navigatorOptionLabel,children:"Sort"}),a.jsx(ai,{value:g,options:VS,onChange:G=>y(String(G)),disabled:!h,ariaLabel:"Sort planning",className:Ue.navigatorDropdown,portalPanel:!0,panelAlign:"start",triggerContent:a.jsxs("span",{className:Ue.navigatorDropdownTrigger,children:[a.jsx(kv,{size:14,"aria-hidden":"true"}),a.jsx("span",{children:VS.find(G=>G.value===g)?.label})]}),renderOptionContent:G=>G.label})]}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:Se,disabled:!ee,"aria-label":"Reset planning filters and sort",title:"Reset planning filters and sort",children:a.jsx(bi,{size:14,"aria-hidden":"true"})})]}):null,a.jsxs("span",{className:Ue.visuallyHidden,role:"status","aria-live":"polite",children:[ne.resultCount," planning ",ne.resultCount===1?"result":"results"]})]}):null,ne.hasCriteria&&ne.resultCount===0?a.jsxs("div",{className:Ue.navigatorEmpty,role:"status",children:[a.jsx("strong",{children:"No planning matches"}),a.jsx("span",{children:"Try another title or reference, or clear the owner filter."}),a.jsx("button",{type:"button",onClick:Se,children:"Clear search and filters"})]}):a.jsxs(a.Fragment,{children:[pe.length>0?a.jsxs("div",{className:Ue.sectionGroup,children:[a.jsx(_f,{label:"Favorites",count:pe.length,expanded:!C,expandedTitle:"Collapse favorites",collapsedTitle:"Expand favorites",onToggle:T,controlsId:"planning-favorites-section"}),a.jsx("ul",{id:"planning-favorites-section",className:Ue.treeList,"aria-label":"Favorite planning items",hidden:C,children:pe.map(({favorite:G,item:Be,parentInitiativeId:Xe})=>{const ze=G.type==="initiative"?v?.type==="initiative"&&v.item.id===Be.id:v?.type==="workstream"&&v.item.id===Be.id||V?.kind==="detail"&&V.detail.item.id===Be.id,qe=G.type==="initiative"?Be:null,Te=G.type==="workstream"?Be:null,fe=qe?qe.allWorkstreams||qe.workstreams:[],Ee=fe.filter(xe=>s||!xe.isArchived),$e=`favorite:${G.type}:${Be.id}`,rt=H.has($e),kt=`planning-${$e.replaceAll(":","-")}-children`;return a.jsxs("li",{children:[a.jsx(lf,{rowId:`favorite:${G.type}:${Be.id}`,rowType:G.type,referenceLabel:G.type==="initiative"?fs(Be):Eo(Be),item:Be,ownerOption:Be.ownerId?Pe.get(Be.ownerId):void 0,ownerOptions:l,onChangeOwner:xe=>ce(G.type,Be.id,xe==="unassigned"?"":xe),onChangeIdentity:xe=>Le(G.type,Be.id,xe),workstreamCount:qe?Ee.length:void 0,active:G.type==="initiative"?f===Be.id&&!p:p===Be.id,isArchived:!!Be.isArchived,detailOpen:ze,canExpand:G.type==="initiative"?fe.length>0:!!Te?.tasks?.length,expanded:rt,controlsId:kt,onToggleExpand:()=>ke($e),onToggleScope:()=>{G.type==="initiative"?z(Be.id):M(Be.id,Xe)},favoriteReady:h,onOpenDetails:()=>{G.type==="initiative"?O(Be.id):Xe?(O(Xe),U(Be.id)):Z(Be.id)},favorite:!0,onToggleFavorite:()=>b(G),onArchiveReady:G.type==="initiative"?he?()=>he(Be.id):void 0:ge?()=>ge(Be.id):void 0,hierarchyInteractions:!1,initiativeLinkOptions:G.type==="workstream"&&!Xe?Ae.initiatives:void 0,onLinkInitiative:G.type==="workstream"&&!Xe?xe=>ye(Be.id,xe.referenceLabel):void 0}),qe&&rt?a.jsx("ul",{id:kt,className:Ue.treeChildren,"aria-label":`Workstreams in favorite ${qe.title}`,children:Ee.length>0?Ee.map(xe=>{const St=`${$e}:workstream:${xe.id}`,jt=H.has(St),$=`planning-${St.replaceAll(":","-")}-children`;return a.jsxs("li",{children:[a.jsx(lf,{rowId:St,rowType:"workstream",referenceLabel:Eo(xe),item:xe,ownerOption:xe.ownerId?Pe.get(xe.ownerId):void 0,ownerOptions:l,onChangeOwner:Ke=>ce("workstream",xe.id,Ke==="unassigned"?"":Ke),onChangeIdentity:Ke=>Le("workstream",xe.id,Ke),active:p===xe.id,isArchived:!!xe.isArchived,detailOpen:v?.type==="workstream"&&v.item.id===xe.id||V?.kind==="detail"&&V.detail.item.id===xe.id,canExpand:!!xe.tasks?.length,expanded:jt,controlsId:$,onToggleExpand:()=>ke(St),onToggleScope:()=>M(xe.id,qe.id),onOpenDetails:()=>{O(qe.id),U(xe.id)},favorite:Me.has(Ji({type:"workstream",id:xe.id})),favoriteReady:h,onToggleFavorite:()=>b({type:"workstream",id:xe.id}),onArchiveReady:ge?()=>ge(xe.id):void 0,hierarchyInteractions:!1}),Ze(xe,jt,$,`Tasks in favorite ${qe.title} / ${xe.title}`)]},xe.id)}):a.jsx("li",{className:Ue.passiveGuidance,children:"Archived workstreams are hidden."})}):null,Te?Ze(Te,rt,kt,`Tasks in favorite ${Te.title}`):null]},Ji(G))})})]}):null,a.jsxs("div",{className:Ue.sectionGroup,children:[a.jsx(_f,{label:"Initiatives",count:ne.initiatives.length,showZeroCount:!0,actions:r.collections.initiatives==="ready"?a.jsx("button",{type:"button",className:"tf-control-icon",title:"Create initiative","aria-label":"Create initiative",onClick:_,children:a.jsx(ri,{size:15})}):null,expanded:!S,expandedTitle:"Collapse initiatives",collapsedTitle:"Expand initiatives",onToggle:E,controlsId:S?void 0:"planning-initiatives-section"}),S?null:a.jsx("ul",{id:"planning-initiatives-section",className:Ue.treeList,"aria-label":"Initiatives",children:r.collections.initiatives==="error"?a.jsx("li",{children:a.jsx(Nh,{compact:!0,title:"Initiatives unavailable",message:"Initiatives could not be loaded.",retrying:r.isRefreshing,onRetry:Ne})}):ne.initiatives.length===0?a.jsxs("li",{className:Ue.emptyPanel,children:[a.jsx("div",{className:Ue.emptyPanelTitle,children:st}),a.jsx("div",{className:Ue.emptyPanelText,children:at})]}):ne.initiatives.map(({initiative:G,workstreams:Be})=>{const Xe=G.allWorkstreams||G.workstreams,ze=s?Xe:Xe.filter(fe=>!fe.isArchived),qe=Be,Te=ne.hasCriteria?qe.length>0:N.has(G.id);return a.jsxs("li",{children:[a.jsx(lf,{rowId:G.id,rowType:"initiative",referenceLabel:fs(G),item:G,ownerOption:G.ownerId?Pe.get(G.ownerId):void 0,ownerOptions:l,onChangeOwner:fe=>ce("initiative",G.id,fe==="unassigned"?"":fe),onChangeIdentity:fe=>Le("initiative",G.id,fe),workstreamCount:ze.length,active:f===G.id&&!p,isArchived:!!G.isArchived,detailOpen:v?.type==="initiative"&&v.item.id===G.id,canExpand:Xe.length>0,expanded:Te,controlsId:`planning-children-${G.id}`,onToggleExpand:()=>F(G.id),onToggleScope:()=>z(G.id),onOpenDetails:()=>O(G.id),favorite:Me.has(Ji({type:"initiative",id:G.id})),favoriteReady:h,onToggleFavorite:()=>b({type:"initiative",id:G.id}),onArchiveReady:he?()=>he(G.id):void 0}),Te&&qe.length>0&&a.jsx("ul",{id:`planning-children-${G.id}`,className:Ue.treeChildren,"aria-label":`Workstreams in ${G.title}`,children:qe.map(fe=>a.jsxs("li",{children:[a.jsx(lf,{rowId:fe.id,rowType:"workstream",referenceLabel:Eo(fe),item:fe,ownerOption:fe.ownerId?Pe.get(fe.ownerId):void 0,ownerOptions:l,onChangeOwner:Ee=>ce("workstream",fe.id,Ee==="unassigned"?"":Ee),onChangeIdentity:Ee=>Le("workstream",fe.id,Ee),active:p===fe.id,isArchived:!!fe.isArchived,detailOpen:v?.type==="workstream"&&v.item.id===fe.id||V?.kind==="detail"&&V.detail.item.id===fe.id,canExpand:(fe.tasks||[]).length>0,expanded:ie.has(fe.id),controlsId:`planning-tasks-${fe.id}`,onToggleExpand:()=>_e(fe.id),onToggleScope:()=>M(fe.id,G.id),onOpenDetails:()=>{O(G.id),U(fe.id)},favorite:Me.has(Ji({type:"workstream",id:fe.id})),favoriteReady:h,onToggleFavorite:()=>b({type:"workstream",id:fe.id}),onArchiveReady:ge?()=>ge(fe.id):void 0}),Ze(fe)]},fe.id))})]},G.id)})})]}),a.jsxs("div",{className:Ue.sectionGroup,children:[a.jsx(_f,{label:"Workstreams",count:ne.standaloneWorkstreams.length,showZeroCount:!0,actions:r.collections.workstreams==="ready"?a.jsx("button",{type:"button",className:"tf-control-icon",title:"Create workstream","aria-label":"Create workstream",onClick:j,children:a.jsx(ri,{size:15})}):null,expanded:!w,expandedTitle:"Collapse workstreams",collapsedTitle:"Expand workstreams",onToggle:x,controlsId:w?void 0:"planning-workstreams-section"}),w?null:a.jsx("ul",{id:"planning-workstreams-section",className:Ue.treeList,"aria-label":"Standalone workstreams",children:r.collections.workstreams==="error"?a.jsx("li",{children:a.jsx(Nh,{compact:!0,title:"Workstreams unavailable",message:"Workstreams could not be loaded.",retrying:r.isRefreshing,onRetry:Ne})}):ne.standaloneWorkstreams.length===0?a.jsxs("li",{className:Ue.emptyPanel,children:[a.jsx("div",{className:Ue.emptyPanelTitle,children:oe}),a.jsx("div",{className:Ue.emptyPanelText,children:We})]}):ne.standaloneWorkstreams.map(G=>a.jsxs("li",{children:[a.jsx(lf,{rowId:G.id,rowType:"workstream",referenceLabel:Eo(G),item:G,ownerOption:G.ownerId?Pe.get(G.ownerId):void 0,ownerOptions:l,onChangeOwner:Be=>ce("workstream",G.id,Be==="unassigned"?"":Be),onChangeIdentity:Be=>Le("workstream",G.id,Be),active:p===G.id,isArchived:!!G.isArchived,detailOpen:v?.type==="workstream"&&v.item.id===G.id||V?.kind==="detail"&&V.detail.item.id===G.id,canExpand:(G.tasks||[]).length>0,expanded:ie.has(G.id),controlsId:`planning-tasks-${G.id}`,onToggleExpand:()=>_e(G.id),onToggleScope:()=>M(G.id,null),onOpenDetails:()=>Z(G.id),favorite:Me.has(Ji({type:"workstream",id:G.id})),favoriteReady:h,onToggleFavorite:()=>b({type:"workstream",id:G.id}),onArchiveReady:ge?()=>ge(G.id):void 0,initiativeLinkOptions:Ae.initiatives,onLinkInitiative:Be=>ye(G.id,Be.referenceLabel)}),Ze(G)]},G.id))})]})]})]})}function xX(){return a.jsxs("div",{className:Ue.loadingState,role:"status","aria-live":"polite",children:[a.jsx("span",{className:Ue.visuallyHidden,children:"Loading planning"}),[0,1,2].map(e=>a.jsxs("div",{className:Ue.loadingRow,"aria-hidden":"true",children:[a.jsx("span",{className:Ue.loadingBadge}),a.jsx("span",{className:Ue.loadingTitle}),a.jsx("span",{className:Ue.loadingMeta})]},e))]})}function Nh({title:e,message:t,retrying:r,onRetry:n,compact:s=!1}){return a.jsxs("div",{className:`${Ue.failureState} ${s?Ue.failureStateCompact:""} tf-surface-inset`.trim(),role:"alert",children:[a.jsxs("div",{className:Ue.failureCopy,children:[a.jsx("strong",{children:e}),a.jsx("span",{children:t})]}),a.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",disabled:r,onClick:n,children:r?"Retrying…":"Retry"})]})}function YS({detail:e,showArchivedChildren:t,inlineEditor:r,selectedChildWorkstreamId:n,currentWorkspaceId:s,currentActorId:i,theme:l,onOpenNestedWorkstreamDetails:c,onArchivePlanningTask:d,onArchiveResolvedWorkstream:f,onArchiveResolvedEntity:p,onEdit:g,onChangeOwner:h,onChangePlanningOwner:y,onChangePlanningIdentity:k,onArchive:b,onUnarchive:C,onCreateTaskInWorkstream:S,onCreateWorkstreamInInitiative:w,onOpenTaskById:T,onChangeTaskAssignee:E,taskReferences:x,onAssignTaskToWorkstream:N,onAssignInitiativeToWorkstream:v,onAttachTaskToWorkstreamByReference:V,onAttachWorkstreamToInitiativeByReference:_,onAddPlanningContextFile:j,onRemovePlanningContextFile:F,onUpdatePlanningContextCaption:z,parentInitiative:M=null,assigneeOptions:O,linkOptions:Z,showTaskCardStatusLabel:U=!1,taskArrangeMode:ve="execution",onTaskArrangeModeChange:te=()=>{},onReorderWorkstreamTasks:ce,onSetTaskStatus:Le,hydrationState:Ie,onRetryHydration:Ye}){const ge=Y.useId(),[he,Ae]=Y.useState(!1),[ye,Ne]=Y.useState(!1),[ae,q]=Y.useState(null),[W,K]=Y.useState(null),[Re,we]=Y.useState(!1),[ie,Q]=Y.useState(null),[H,se]=Y.useState(!1),[Pe,ue]=Y.useState(!1),[ne,Me]=Y.useState(!1),[pe,le]=Y.useState(null),[Ce,P]=Y.useState(String(e.item.ownerId||"")),[ee,Se]=Y.useState(!1),{active:_e}=wA(),ke=String(_e?.data?.current?.type||""),Ze=e.type==="workstream"&&ke==="task-card",st=e.type==="initiative"&&ke==="planning-workstream",at=e.type==="initiative"?"planning-initiative-target":"planning-workstream-target",{setNodeRef:oe,isOver:We}=Iv({id:`${at}:detail:${e.item.id}`,data:e.type==="initiative"?{type:at,initiativeId:e.item.id}:{type:at,workstreamId:e.item.id}}),G=e.type==="initiative"?"Workstreams":"Tasks",Be=Y.useMemo(()=>{if(e.type!=="initiative")return[];const nt=new Set(e.item.workstreams.map(ur=>ur.id)),Mt=(e.item.allWorkstreams||[]).filter(ur=>!!ur.isArchived&&!nt.has(ur.id));return[...e.item.workstreams,...Mt]},[e.item,e.type]),Xe=Y.useMemo(()=>e.type!=="workstream"?[]:e.item.tasks||[],[e.item,e.type]),ze=Y.useMemo(()=>new Map(O.filter(nt=>!String(nt.archivedAt||"").trim()).map(nt=>[String(nt.value||"").trim(),nt])),[O]),qe=t?Be:Be.filter(nt=>!nt.isArchived),Te=uv(t?Xe:Xe.filter(nt=>!nt.isArchived),ve),fe=e.type==="initiative"?qe.length:Te.length,Ee=e.type==="initiative"?"Initiative":"Workstream",$e=e.type==="initiative"?fs(e.item):Eo(e.item),rt=d_({entityType:e.type,isArchived:e.item.isArchived,taskCount:e.item.taskCount,completedTaskCount:e.item.completedTaskCount,archiveReady:e.item.archiveReady,activeWorkstreamCount:e.item.archiveActiveWorkstreamCount}),kt=rt.mode==="archived"?`Unarchive ${Ee.toLowerCase()}`:rt.mode==="blocked"?`Archive unavailable — active ${rt.remainingKind==="task"?"tasks":"workstreams"} remain`:rt.mode==="checking"?"Archive availability is still loading":`Archive ${Ee.toLowerCase()}`;Y.useEffect(()=>{Ae(!1),Ne(!1),q(null),K(null),we(!1),ue(!1)},[e.item.id,e.type]),Y.useEffect(()=>{P(String(e.item.ownerId||""))},[e.item.id,e.item.ownerId,e.type]);const xe=Y.useCallback(async nt=>{if(!h||ee||nt===Ce)return;const Mt=Ce;P(nt),Se(!0);try{await h(nt)}catch{P(Mt)}finally{Se(!1)}},[ee,h,Ce]),St=Y.useCallback(async()=>{if(!(!p||ne)){Me(!0);try{await p(e.item.id)&&ue(!1)}finally{Me(!1)}}},[ne,e.item.id,p]),jt=e.type==="initiative"?!!_:!!V,$=Y.useCallback(async nt=>{if(he)return;const Mt=e.type==="initiative"?_:V;if(Mt){Ae(!0);try{await Mt(e.item.id,nt.referenceLabel)}finally{Ae(!1)}}},[e.item.id,e.type,he,V,_]),Ke=Y.useCallback(async nt=>{if(!(!v||e.type!=="workstream"||Re)){we(!0);try{await v(e.item.id,nt.referenceLabel)!==!1&&Ne(!1)}finally{we(!1)}}},[e.item.id,e.type,Re,v]),Qe=e.type==="workstream"&&M?fs(M):"",Ge=Y.useMemo(()=>new Set(e.type==="initiative"?Be.map(nt=>nt.id):Xe.map(nt=>nt.id)),[Be,e.type,Xe]),At=Y.useMemo(()=>(e.type==="initiative"?Z.workstreams:Z.tasks).filter(nt=>!Ge.has(nt.id)),[e.type,Z.tasks,Z.workstreams,Ge]),Nt=Y.useCallback(async()=>{if(!(!ae||Re)){we(!0);try{if(ae.entityType==="workstream"){if(!v)return;const nt=e.type==="initiative"?$e:Qe;if(await v?.(ae.id,null)===!1)return;K({entityType:ae.entityType,id:ae.id,message:`${ae.referenceLabel} removed from its initiative.`,onUndo:async()=>{if(!nt)return;await v?.(ae.id,nt)!==!1&&K(null)}})}else{if(!N||await N(ae.id,null)===!1)return;K({entityType:ae.entityType,id:ae.id,message:`${ae.referenceLabel} removed from this workstream.`,onUndo:async()=>{await N(ae.id,e.item.id)!==!1&&K(null)}})}q(null)}finally{we(!1)}}},[e.item.id,e.type,$e,Re,v,N,Qe,ae]),Bt=Y.useCallback(async()=>{if(!(!W||Re)){we(!0);try{await W.onUndo()}finally{we(!1)}}},[Re,W]),Qt=Y.useCallback((nt,Mt)=>W?.entityType===nt&&W.id===Mt?a.jsxs("div",{className:Ue.relationshipRecovery,role:"status",children:[a.jsx("span",{children:W.message}),a.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",disabled:Re,onClick:()=>{Bt()},children:Re?"Restoring…":"Undo"})]}):null,[Bt,Re,W]),Xt=W&&!Ge.has(W.id)?a.jsxs("div",{className:Ue.relationshipRecovery,role:"status",children:[a.jsx("span",{children:W.message}),a.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",disabled:Re,onClick:()=>{Bt()},children:Re?"Restoring…":"Undo"})]}):null;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:Ue.detailHero,children:[a.jsxs("div",{className:Ue.detailTopRow,children:[a.jsxs("div",{className:Ue.detailReferenceRow,children:[e.type==="workstream"?a.jsx(a.Fragment,{children:Qe?a.jsxs(a.Fragment,{children:[a.jsx(_d,{label:Qe,entityType:"initiative",entityName:M?.title}),a.jsx("span",{className:R.taskHierarchyDivider,children:"/"}),r?null:a.jsx(vf,{disabled:!v,onClick:()=>{q({entityType:"workstream",id:e.item.id,referenceLabel:$e,title:e.item.title,parentLabel:M?`${fs(M)} ${M.title}`.trim():Qe})},title:"Unlink workstream from initiative",ariaLabel:"Unlink workstream from initiative",children:a.jsx(Sf,{size:14,"aria-hidden":"true"})})]}):null}):null,e.type==="workstream"&&!Qe&&!r?a.jsx(vf,{disabled:!v,onClick:()=>Ne(!0),title:"Link initiative",ariaLabel:"Link initiative",ariaExpanded:ye,children:a.jsx(Bu,{size:14,"aria-hidden":"true"})}):null,a.jsx(_d,{label:$e||"Reference pending",entityType:e.type,entityName:e.item.title,pending:!$e})]}),a.jsx("div",{className:Ue.detailTopActions,children:r?a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",onClick:r.onCancel,disabled:r.isSubmitting,children:"Cancel"}),a.jsx("button",{type:"submit",form:ge,className:"tf-button-primary tf-button-compact",disabled:r.isSubmitting,children:r.isSubmitting?"Saving…":"Save"})]}):a.jsxs(a.Fragment,{children:[a.jsx("button",{type:"button",className:"tf-control-icon",disabled:rt.mode==="blocked"||rt.mode==="checking",onClick:()=>{rt.mode==="archived"?C?.():rt.mode==="empty"?b?.():rt.mode==="ready"&&ue(!0)},title:kt,"aria-label":kt,"aria-expanded":rt.mode==="ready"?Pe:void 0,children:rt.mode==="archived"?a.jsx(bi,{size:14,"aria-hidden":"true"}):a.jsx(Sd,{size:14,"aria-hidden":"true"})}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>{Ne(!1),g()},title:`Edit ${Ee.toLowerCase()} details`,"aria-label":`Edit ${Ee.toLowerCase()} details`,children:a.jsx(dA,{size:14,"aria-hidden":"true"})})]})})]}),Pe&&rt.mode==="ready"?a.jsx(pv,{entityType:e.type,title:e.item.title,activeTaskCount:e.item.archiveActiveTaskCount,activeWorkstreamCount:e.item.archiveActiveWorkstreamCount,busy:ne,onCancel:()=>ue(!1),onConfirm:()=>{St()}}):null,e.type==="workstream"?Qt("workstream",e.item.id):null,e.type==="workstream"&&!Qe&&ye?a.jsxs("div",{className:Ue.relationshipPickerRow,role:"group","aria-label":"Link workstream to initiative",children:[a.jsx(yg,{options:Z.initiatives,entityLabel:"initiative",onSelect:Ke,disabled:!v||Re}),a.jsx("button",{type:"button",className:"tf-control-icon tf-control-icon-compact",disabled:Re,onClick:()=>Ne(!1),title:"Cancel initiative link","aria-label":"Cancel initiative link",children:a.jsx(Mo,{size:14,"aria-hidden":"true"})})]}):null,r?a.jsx(fv,{editor:r.editor,draftTitle:r.draftTitle,draftDescription:r.draftDescription,draftOwner:r.draftOwner,draftInitiativeId:r.draftInitiativeId,assigneeOptions:O,initiativeLinkOptions:Z.initiatives,draftInitiativeSummary:r.draftInitiativeSummary,onChangeDraftTitle:r.onChangeDraftTitle,onChangeDraftDescription:r.onChangeDraftDescription,onChangeDraftOwner:r.onChangeDraftOwner,onChangeDraftInitiativeId:r.onChangeDraftInitiativeId,onCancel:r.onCancel,onSubmit:r.onSubmit,isSubmitting:r.isSubmitting,inline:!0,formId:ge}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:Ue.detailTitleRow,children:[a.jsx(Jf,{entityType:e.type,entityId:e.item.id,icon:e.item.icon,color:e.item.color,size:"detail",disabled:!!e.item.isArchived,onChange:k?nt=>k(e.type,e.item.id,nt):void 0}),a.jsx("h3",{className:Ue.detailTitle,children:e.item.title})]}),a.jsx(kQ,{description:e.item.description,label:Ee,taskReferences:x,className:`${Ue.detailDescription} ${R.appScrollbar} tf-scrollbar`.trim(),markdownClassName:Ue.detailDescriptionMarkdown})]}),a.jsxs("div",{className:Ue.detailOwnerField,children:[a.jsx("span",{className:Ue.detailOwnerLabel,children:"Owner"}),a.jsx(pw,{value:Ce,disabled:!h||ee,onChange:nt=>{xe(nt)},ariaLabel:`${Ee} owner`,options:O,className:`${uw.control} ${Ue.ownerSelect}`})]}),e.item.taskCount>0?a.jsx(b_,{value:e.item.progressPercent,label:`${e.item.progressPercent}% resolved`,statusCounts:e.item.statusCounts}):a.jsx(k_,{}),a.jsx(S_,{item:e.item,workstreamCount:e.type==="initiative"?e.item.workstreamCount??e.item.workstreams.length:void 0,className:Ue.detailSummaryMeta}),e.item.taskCount>0?a.jsx("span",{className:Ue.passiveGuidance,children:"Lifetime progress includes archived tasks."}):null]}),a.jsxs("div",{ref:oe,className:`${Ue.listCard} ${Ze||st?Ue.sectionDropReady:""} ${We?Ue.sectionDropActive:""} ${Ze||st?Ue.sectionDropMode:""}`.trim(),children:[a.jsxs("div",{className:Ue.sectionHeaderRow,children:[a.jsxs("div",{className:Ue.sectionTitle,children:[G," (",fe,")"]}),a.jsx("div",{className:Ue.headerActionGroup,children:e.type==="initiative"?a.jsx("button",{type:"button",className:"tf-control-icon",title:"Create workstream in this initiative","aria-label":"Create workstream in this initiative",onClick:()=>w?.(e.item.id),children:a.jsx(ri,{size:15})}):a.jsx("button",{type:"button",className:"tf-control-icon",title:"Create task in this workstream","aria-label":"Create task in this workstream",onClick:()=>S?.(e.item.id),children:a.jsx(ri,{size:15})})})]}),a.jsx("div",{className:Ue.linkPickerRow,children:a.jsx(yg,{options:At,entityLabel:e.type==="initiative"?"workstream":"task",onSelect:$,disabled:!jt||he})}),e.type==="workstream"?a.jsx(tX,{value:ve,onChange:te}):null,e.type==="initiative"?qe.length>0?qe.map(nt=>{const Mt=Eo(nt),ur=()=>c?.(nt.id),je=n===nt.id,ot=ie===nt.id,pt=async()=>{if(!(!f||H)){se(!0);try{await f(nt.id)&&Q(null)}finally{se(!1)}}};return a.jsx("div",{className:`${Ue.listItemButton} ${Ue.detailCardButton}`.trim(),children:a.jsxs("div",{className:`${Ue.listItem} ${Ue.detailChildCard} ${je?Ue.detailChildCardSelected:""} ${nt.isArchived?Ue.detailChildCardArchived:""}`.trim(),children:[a.jsxs("div",{className:Ue.detailChildCardTopRow,children:[a.jsxs("div",{className:Ue.detailChildReferenceRow,children:[a.jsx(vf,{disabled:!v,onClick:Ve=>{Ve.stopPropagation(),q({entityType:"workstream",id:nt.id,referenceLabel:Mt,title:nt.title,parentLabel:`${$e} ${e.item.title}`.trim()})},title:`Unlink ${Mt||nt.title} from initiative`,ariaLabel:`Unlink ${Mt||nt.title} from initiative`,children:a.jsx(Sf,{size:14,"aria-hidden":"true"})}),Mt?a.jsx(_d,{label:Mt,entityType:"workstream",entityName:nt.title}):a.jsx("span",{"aria-hidden":"true"})]}),a.jsx("div",{className:Ue.detailChildActions,onClick:Ve=>Ve.stopPropagation(),children:nt.archiveReady&&!nt.isArchived&&f?a.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>Q(nt.id),title:"Archive completed workstream","aria-label":`Archive completed workstream ${nt.title}`,"aria-expanded":ot,children:a.jsx(Sd,{size:14,"aria-hidden":"true"})}):null})]}),Qt("workstream",nt.id),ot?a.jsx(pv,{entityType:"workstream",title:nt.title,activeTaskCount:nt.archiveActiveTaskCount,busy:H,onCancel:()=>Q(null),onConfirm:()=>{pt()}}):null,a.jsx("div",{role:"button",tabIndex:0,"aria-current":je?"true":void 0,className:Ue.listItemText,onClick:ur,onKeyDown:Ve=>{Ve.key!=="Enter"&&Ve.key!==" "||(Ve.preventDefault(),ur())},children:a.jsx(A_,{item:nt,entityType:"workstream",ownerOption:nt.ownerId&&ze.has(nt.ownerId)?ec(ze.get(nt.ownerId)):void 0,ownerOptions:O.map(ec),onChangeOwner:y?Ve=>y("workstream",nt.id,Ve==="unassigned"?"":Ve):void 0,onChangeIdentity:k?Ve=>k("workstream",nt.id,Ve):void 0})})]})},nt.id)}):a.jsx("div",{className:Ue.passiveGuidance,children:"No workstreams are linked to this initiative."}):Te.length>0?a.jsx(iX,{tasks:Te,mode:ve,onReorder:ce?nt=>ce(e.item.id,ZQ(uv(Xe,"execution"),nt)):void 0,children:nt=>{const Mt=hs(nt)||nt.id,ur=Po(nt.status);return a.jsx("div",{className:`${Ue.listItemButton} ${Ue.detailCardButton}`.trim(),children:a.jsx(C_,{task:nt,assigneeOption:nt.assignee&&ze.has(nt.assignee)?ec(ze.get(nt.assignee)):void 0,assigneeOptions:O.map(ec),showStatusLabel:U,onOpen:T?()=>T(nt.id):void 0,onAssigneeChange:E?je=>E(nt.id,je):void 0,onStatusChange:Le?je=>Le(nt.id,je):void 0,feedback:Qt("task",nt.id),referenceAction:a.jsx(vf,{disabled:!N,onClick:je=>{je.stopPropagation(),q({entityType:"task",id:nt.id,referenceLabel:Mt,title:nt.title,parentLabel:`${$e} ${e.item.title}`.trim()})},title:`Unlink ${Mt||nt.title} from workstream`,ariaLabel:`Unlink ${Mt||nt.title} from workstream`,children:a.jsx(Sf,{size:14,"aria-hidden":"true"})}),actions:!nt.isArchived&&(ur.value==="done"||ur.value==="cancelled")&&d?a.jsx("button",{type:"button",className:"tf-control-icon",disabled:pe===nt.id,onClick:async je=>{je.stopPropagation(),le(nt.id);try{await d(nt.id)}finally{le(null)}},title:"Archive task","aria-label":`Archive task ${Mt||nt.title}`,children:a.jsx(Sd,{size:14,"aria-hidden":"true"})}):void 0})},nt.id)}}):a.jsx("div",{className:Ue.passiveGuidance,children:"No tasks are linked to this workstream."}),Xt]}),a.jsx("div",{className:Ue.listCard,children:a.jsx(vQ,{entityType:e.type,entityId:e.item.id,referenceLabel:$e,workspaceId:s,attachments:e.item.attachments,readOnly:!!e.item.isArchived,onAddAttachment:nt=>j?.(e.type,e.item.id,nt),onRemoveAttachment:nt=>F?.(e.type,e.item.id,nt),onUpdateAttachmentCaption:(nt,Mt)=>z?.(e.type,e.item.id,nt,Mt)})}),a.jsx("div",{className:Ue.listCard,children:a.jsx(wQ,{entityType:e.type,item:e.item,assigneeOptions:O.map(ec),currentActorId:i,taskReferences:x,parentInitiative:M,listClassName:Ue.activityTimelineList,emptyClassName:Ue.activityTimelineEmpty,hydrationState:Ie,onRetryHydration:Ye})}),a.jsx(mX,{item:ae,busy:Re,theme:l,onCancel:()=>q(null),onConfirm:()=>{Nt()}})]})}function fv({editor:e,draftTitle:t,draftDescription:r,draftOwner:n,draftInitiativeId:s,draftIcon:i,draftColor:l,assigneeOptions:c,initiativeLinkOptions:d,draftInitiativeSummary:f,onChangeDraftTitle:p,onChangeDraftDescription:g,onChangeDraftOwner:h,onChangeDraftInitiativeId:y,onChangeDraftIcon:k,onChangeDraftColor:b,onCancel:C,onSubmit:S,isSubmitting:w,inline:T=!1,formId:E}){const x=e.entityType==="initiative"?"Initiative":"Workstream",N=Y.useId(),v=Y.useId(),V=Y.useId(),_=Y.useRef(null),[j,F]=Y.useState(null),z=w?e.mode==="create"?`Creating ${x}...`:`Saving ${x}...`:e.mode==="create"?`Create ${x}`:`Save ${x}`,M=Y.useCallback(Z=>{if(Z.preventDefault(),!t.trim()){F(`${x} title is required.`),_.current?.focus();return}F(null),S()},[t,x,S]),O=Y.useCallback(Z=>{!T||Z.key!=="Escape"||w||(Z.preventDefault(),C())},[T,w,C]);return a.jsxs("form",{id:E,className:`${Ue.editorCard} ${T?Ue.inlineEditorCard:""}`.trim(),onSubmit:M,onKeyDown:O,noValidate:!0,children:[e.mode==="create"&&k&&b?a.jsxs("div",{className:Ue.editorIdentityField,children:[a.jsx(Jf,{entityType:e.entityType,entityId:"create-preview",icon:i,color:l||"blue",size:"detail",onChange:Z=>{Object.prototype.hasOwnProperty.call(Z,"icon")&&k(Z.icon??null),Object.prototype.hasOwnProperty.call(Z,"color")&&b(Z.color??null)}}),a.jsx("span",{children:"Choose an icon and color"})]}):null,a.jsxs("div",{className:Ue.editorField,children:[a.jsxs("label",{className:Ue.editorLabel,htmlFor:N,children:[x," title"]}),a.jsx("input",{ref:_,id:N,"data-planning-editor-title":!0,className:R.input,disabled:w,required:!0,"aria-invalid":j?"true":void 0,"aria-describedby":j?v:void 0,value:t,onChange:Z=>{j&&F(null),p(Z.target.value)},placeholder:e.entityType==="initiative"?"Enter initiative title":"Enter workstream title"}),j?a.jsx("p",{id:v,className:"tf-text-error",children:j}):null]}),a.jsxs("div",{className:Ue.editorField,children:[a.jsxs("label",{className:Ue.editorLabel,htmlFor:V,children:[x," description"]}),a.jsx("textarea",{id:V,className:R.textarea,disabled:w,value:r,onChange:Z=>g(Z.target.value),placeholder:e.entityType==="initiative"?"Describe the broader outcome this initiative is meant to achieve.":"Describe the lane of work this workstream will coordinate.",rows:5})]}),e.entityType==="workstream"&&a.jsxs("div",{className:Ue.editorField,children:[a.jsx("span",{className:Ue.editorLabel,children:"Initiative"}),a.jsxs("div",{className:Ue.editorRelationshipRow,children:[a.jsx(yg,{options:d,selectedId:f?.id||"",entityLabel:"initiative",disabled:w,onSelect:Z=>y(Z.referenceLabel)}),s.trim()?a.jsx("button",{type:"button",className:"tf-button-ghost tf-button-compact",disabled:w,onClick:()=>y(""),children:"Remove"}):null]})]}),T?null:a.jsxs("div",{className:Ue.editorField,children:[a.jsxs("span",{className:Ue.editorLabel,children:[x," owner"]}),a.jsx(pw,{disabled:w,value:n,onChange:h,ariaLabel:`${x} owner`,options:c,className:Ue.editorSelect})]}),T?null:a.jsxs("div",{className:Ue.editorActions,children:[a.jsx("button",{type:"button",className:R.secondaryHeaderBtn,onClick:C,disabled:w,children:"Cancel"}),a.jsx("button",{type:"submit",className:R.primaryUpdateBtn,disabled:w,children:z})]})]})}function RX({open:e,leftOffset:t=0,returnFocusRef:r,onWidthChange:n,initiatives:s,standaloneWorkstreams:i,planningLoadState:l,onRetryPlanning:c,taskScope:d,activeInitiativeId:f,activeWorkstreamId:p,navigatorSort:g,navigatorSortReady:h,onNavigatorSortChange:y,taskArrangeMode:k="execution",onTaskArrangeModeChange:b=()=>{},onReorderWorkstreamTasks:C,planningFavorites:S,onTogglePlanningFavorite:w,favoritesSectionCollapsed:T,initiativesSectionCollapsed:E,workstreamsSectionCollapsed:x,onToggleFavoritesSection:N,onToggleInitiativesSection:v,onToggleWorkstreamsSection:V,expandedInitiativeIds:_,detail:j,editor:F,secondaryEditor:z=null,secondaryPane:M,primaryHydrationState:O,secondaryHydrationState:Z,onRetryPrimaryHydration:U,onRetrySecondaryHydration:ve,currentWorkspaceId:te,currentOwnerId:ce,theme:Le,assigneeOptions:Ie,linkOptions:Ye,showTaskCardStatusLabel:ge=!1,draftInitiativeSummary:he,draftTitle:Ae,draftDescription:ye,draftOwner:Ne,draftInitiativeId:ae,draftIcon:q=null,draftColor:W=null,onChangeDraftTitle:K,onChangeDraftDescription:Re,onChangeDraftOwner:we,onChangeDraftInitiativeId:ie,onChangeDraftIcon:Q=()=>{},onChangeDraftColor:H=()=>{},onCollapseTreePane:se,onExpandTreePane:Pe,onCollapsePrimaryPane:ue,onExpandPrimaryPane:ne,onCollapseSecondaryPane:Me,onExpandSecondaryPane:pe,onBackFromSecondary:le,treeCollapsed:Ce,primaryCollapsed:P,secondaryCollapsed:ee,onCancelEditor:Se,onCancelSecondaryEditor:_e,onSubmitEditor:ke,isSubmittingEditor:Ze,onCreateInitiative:st,onCreateWorkstream:at,onToggleInitiative:oe,onSelectInitiative:We,onSelectWorkstream:G,onOpenInitiativeDetails:Be,onOpenWorkstreamDetails:Xe,onOpenNestedWorkstreamDetails:ze,onEditInitiative:qe,onEditWorkstream:Te,onChangePlanningOwner:fe,onChangePlanningIdentity:Ee=()=>{},onChangeTaskAssignee:$e,onArchiveInitiative:rt,onUnarchiveInitiative:kt,onArchiveWorkstream:xe,onUnarchiveWorkstream:St,onArchivePlanningTask:jt,onArchiveResolvedWorkstream:$,onArchiveResolvedInitiative:Ke,onCreateTaskInWorkstream:Qe,onCreateWorkstreamInInitiative:Ge,onAssignInitiativeToWorkstream:At,onOpenTaskById:Nt,onSetTaskStatus:Bt,taskReferences:Qt,onAssignTaskToWorkstream:Xt,onAttachTaskToWorkstreamByReference:nt,onAttachWorkstreamToInitiativeByReference:Mt,onAddPlanningContextFile:ur,onRemovePlanningContextFile:je,onUpdatePlanningContextCaption:ot}){const pt=F?.mode==="edit"&&j&&F.entityType===j.type&&F.targetId===j.item.id?F:null,Ve=z?.mode==="edit"&&M?.kind==="detail"&&z.entityType===M.detail.type&&z.targetId===M.detail.item.id?z:null,lt=F&&!pt?F:null,It=!!(j||lt),wt=!!M,$t=lt?.entityType||j?.type||null,Yt=$t==="initiative",qt=$t==="workstream",[er,_t]=Y.useState(!1),[Dt,Tt]=Y.useState(!1),[Xr,Rr]=Y.useState(!1),[la,sa]=Y.useState({initiative:!1,workstream:!1}),ea=Y.useMemo(()=>{const br=[...s.flatMap(yr=>yr.allWorkstreams||yr.workstreams),...i];return s.filter(yr=>!!yr.isArchived).length+br.filter(yr=>!!yr.isArchived).length+br.reduce((yr,Gr)=>yr+(Gr.tasks||[]).filter(Kr=>!!Kr.isArchived).length,0)},[s,i]),{availableWidth:Ur,layoutMode:Ft}=IX(t),ft=Ft==="wide",Rt=ft&&Ce,_r=ft&&P,u=ft&&ee,Yr=T_(Rt,!0,Yt?_r:!er,!0,qt?_r:wt?u:!Dt),tr=Ft!=="narrow"||!It&&!wt,$r=It&&(ft||!wt),Lt=wt,Ir=ft?Yr:Ft==="medium"?Rf+($r||Lt?ac:0):Ur,Kt=Math.max(0,Math.min(Ir,Ur)),Jr=Math.max(0,Kt-(tr?Rf:0)),Br=lt?lt.entityType==="initiative"?lt.mode==="create"?"New Initiative":"Edit Initiative":lt.mode==="create"?"New Workstream":"Edit Workstream":j?.type==="initiative"?"Initiative":"Workstream",nr=M?.kind==="editor"?M.editor.mode==="create"?"New Workstream":"Edit Workstream":"Workstream",Zr=lt?null:j,He=M?.kind==="detail"?M.detail:null,Ca=Y.useCallback(br=>{sa(yr=>({...yr,[br]:!yr[br]}))},[]),da=Y.useCallback(br=>{const yr=String(br.initiativeId||"").trim();return yr&&s.find(Gr=>Gr.id===yr)||null},[s]),ir=Y.useRef(null),ut=Y.useRef(null),ka=Y.useRef(null),Wt=Y.useRef(null),rr=Y.useRef(null),oa=Y.useRef(e),Mr=Y.useRef(""),vn=Ve?`secondary:inline-editor:${Ve.targetId}`:M?`secondary:${M.kind}:${M.kind==="detail"?M.detail.item.id:`${M.editor.mode}:${M.editor.entityType}:${M.editor.mode==="edit"?M.editor.targetId:""}`}`:pt?`primary:inline-editor:${pt.targetId}`:lt?`primary:editor:${lt.mode}:${lt.entityType}:${lt.mode==="edit"?lt.targetId:""}`:j?`primary:detail:${j.type}:${j.item.id}`:"tree";Y.useEffect(()=>{const br=oa.current;if(oa.current=e,br&&!e){r?.current?.focus(),Mr.current="";return}if(!e||br&&Mr.current===vn)return;Mr.current=vn;const yr=Lt?ka.current:$r?ut.current:ir.current,Gr=window.requestAnimationFrame(()=>{(yr?.querySelector("[data-planning-editor-title]")||yr?.querySelector("[data-planning-pane-heading]"))?.focus()});return()=>window.cancelAnimationFrame(Gr)},[vn,e,r,$r,Lt]);const En=Y.useCallback(()=>{if(F){Se();return}j?.type==="initiative"&&Be(""),j?.type==="workstream"&&Xe("")},[j,F,Se,Be,Xe]),Ga=Y.useCallback(br=>({flex:`0 0 ${br}px`,width:`${br}px`,minWidth:`${br}px`,maxWidth:`${br}px`}),[]);Y.useEffect(()=>{n?.(Kt)},[Kt,n]),Y.useEffect(()=>{er&&Wt.current?.querySelector("[data-planning-pane-heading]")?.focus()},[er]),Y.useEffect(()=>{Dt&&rr.current?.querySelector("[data-planning-pane-heading]")?.focus()},[Dt]);const Hr=j?.type==="workstream"?j.item:null,Na=Hr?da(Hr):he,ta=!!(Na||String(Hr?.initiativeId||"").trim()),ua=Na?{title:Na.title,description:Hr?`${Hr.title} belongs to this initiative.`:"This workstream will belong to the selected initiative.",action:Hr?{label:"Open initiative",onClick:()=>Be(Na.id)}:void 0}:Hr&&ta?{title:"Initiative unavailable",description:`${Hr.title} is assigned to an initiative that is not available in the current planning data.`}:Hr?{title:"Not linked to an initiative"}:{title:"No initiative selected"},Qr={title:"No workstream selected"};return a.jsx("aside",{className:Ue.drawer,"aria-label":"Planning","aria-hidden":!e,inert:!e,"data-layout":Ft,style:{position:"absolute",top:0,left:e?`${t}px`:`${t-Kt-24}px`,bottom:0,width:`${Kt}px`,minWidth:0,maxWidth:`calc(100vw - ${t}px)`,borderRight:"1px solid var(--border-color)",background:"var(--bg-secondary)",boxSizing:"border-box",display:"flex",flexDirection:"column",zIndex:35,overflow:"hidden",pointerEvents:e?"auto":"none",transition:"left 220ms cubic-bezier(0.4, 0, 0.2, 1)",willChange:"left"},children:a.jsxs("div",{className:Ue.drawerBody,children:[tr&&(Rt?a.jsx(df,{label:"Planning",onExpand:Pe}):a.jsxs("div",{ref:ir,"data-planning-pane":"tree",className:`${Ue.paneShell} ${R.appScrollbar} tf-scrollbar ${Ue.treePane} ${It&&!P?Ue.treePaneSplit:""}`.trim(),style:Ga(Ft==="narrow"?Kt:Rf),children:[a.jsxs("div",{className:Ue.paneHeader,children:[a.jsx("h2",{className:Ue.paneHeaderLabel,tabIndex:-1,"data-planning-pane-heading":!0,children:"Planning"}),a.jsxs("div",{className:Ue.headerActionGroup,children:[a.jsx(Ck,{visible:Xr,disabled:d==="deleted"||ea===0,disabledLabel:d==="deleted"?"Archive visibility unavailable in Trash":void 0,itemLabel:"planning items",onToggle:()=>Rr(br=>!br)}),ft?a.jsx("button",{type:"button",className:"tf-control-icon",onClick:se,"aria-label":"Collapse Planning pane",title:"Collapse Planning pane",children:a.jsx(po,{size:16,"aria-hidden":"true"})}):null]})]}),a.jsx("div",{className:Ue.paneContent,"aria-busy":l.status==="loading"||l.isRefreshing,children:a.jsx(TX,{initiatives:s,standaloneWorkstreams:i,planningLoadState:l,taskScope:d,showArchivedPlanning:Xr,currentOwnerId:ce,assigneeOptions:Ie,showTaskCardStatusLabel:ge,taskArrangeMode:k,activeInitiativeId:f,activeWorkstreamId:p,navigatorSort:g,navigatorSortReady:h,onNavigatorSortChange:y,planningFavorites:S,onTogglePlanningFavorite:w,favoritesSectionCollapsed:T,initiativesSectionCollapsed:E,workstreamsSectionCollapsed:x,onToggleFavoritesSection:N,onToggleInitiativesSection:v,onToggleWorkstreamsSection:V,expandedInitiativeIds:_,detail:j,secondaryPane:M,onCreateInitiative:st,onCreateWorkstream:at,onToggleInitiative:oe,onSelectInitiative:We,onSelectWorkstream:G,onOpenInitiativeDetails:Be,onOpenWorkstreamDetails:Xe,onOpenNestedWorkstreamDetails:ze,onOpenTaskById:Nt,onSetTaskStatus:Bt,onChangePlanningOwner:fe,onChangePlanningIdentity:Ee,onChangeTaskAssignee:$e,onArchivePlanningTask:jt,onArchiveResolvedWorkstream:$,onArchiveResolvedInitiative:Ke,linkOptions:Ye,onAssignInitiativeToWorkstream:At,onRetryPlanning:c})})]})),ft&&!Yt&&(er?a.jsx(qS,{label:"Initiative",title:ua.title,description:ua.description,action:ua.action,onCollapse:()=>_t(!1),paneRef:Wt}):a.jsx(df,{label:"Initiative",muted:!ta,onExpand:()=>_t(!0)})),$r&&(_r?a.jsx(df,{label:$t==="initiative"?"Initiative":"Workstream",onExpand:ne}):a.jsxs("div",{ref:ut,"data-planning-pane":"primary",className:`${Ue.paneShell} ${R.appScrollbar} tf-scrollbar ${Ue.detailPane}`.trim(),style:Ga(ft?ac:Jr),children:[a.jsxs("div",{className:Ue.paneHeader,children:[Ft==="narrow"?a.jsx("button",{type:"button",className:"tf-control-icon",onClick:En,"aria-label":"Back to Planning",title:"Back to Planning",children:a.jsx(po,{size:16,"aria-hidden":"true"})}):null,a.jsx("h2",{className:Ue.paneHeaderLabel,tabIndex:-1,"data-planning-pane-heading":!0,children:Br}),a.jsxs("div",{className:Ue.headerActionGroup,children:[Zr?a.jsx(Ck,{visible:la[Zr.type],disabled:KS(Zr)===0,itemLabel:Zr.type==="initiative"?"workstreams":"tasks",onToggle:()=>Ca(Zr.type)}):null,ft?a.jsx("button",{type:"button",className:"tf-control-icon",onClick:ue,"aria-label":`Collapse ${Br} pane`,title:`Collapse ${Br} pane`,children:a.jsx(po,{size:16,"aria-hidden":"true"})}):null]})]}),a.jsx("div",{className:Ue.paneContent,"aria-busy":O?.status==="loading",children:lt?a.jsx(fv,{editor:lt,draftTitle:Ae,draftDescription:ye,draftOwner:Ne,draftInitiativeId:ae,draftIcon:q,draftColor:W,assigneeOptions:Ie,initiativeLinkOptions:Ye.initiatives,draftInitiativeSummary:he,onChangeDraftTitle:K,onChangeDraftDescription:Re,onChangeDraftOwner:we,onChangeDraftInitiativeId:ie,onChangeDraftIcon:Q,onChangeDraftColor:H,onCancel:Se,onSubmit:ke,isSubmitting:Ze}):j?a.jsx(YS,{detail:j,showArchivedChildren:la[j.type],inlineEditor:pt?{editor:pt,draftTitle:Ae,draftDescription:ye,draftOwner:Ne,draftInitiativeId:ae,draftInitiativeSummary:he,onChangeDraftTitle:K,onChangeDraftDescription:Re,onChangeDraftOwner:we,onChangeDraftInitiativeId:ie,onCancel:Se,onSubmit:ke,isSubmitting:Ze}:null,selectedChildWorkstreamId:M?.kind==="detail"?M.detail.item.id:null,currentWorkspaceId:te,currentActorId:ce,theme:Le,assigneeOptions:Ie,linkOptions:Ye,showTaskCardStatusLabel:ge,taskArrangeMode:k,onTaskArrangeModeChange:b,onReorderWorkstreamTasks:C,hydrationState:O,onRetryHydration:U,onSetTaskStatus:j.type==="workstream"?Bt:void 0,onArchivePlanningTask:j.type==="workstream"?jt:void 0,onArchiveResolvedWorkstream:j.type==="initiative"?$:void 0,onArchiveResolvedEntity:j.type==="initiative"?Ke:$,onOpenNestedWorkstreamDetails:j.type==="initiative"?ze:void 0,onCreateTaskInWorkstream:j.type==="workstream"?Qe:void 0,onCreateWorkstreamInInitiative:j.type==="initiative"?Ge:void 0,onOpenTaskById:j.type==="workstream"?Nt:void 0,onChangeTaskAssignee:j.type==="workstream"?$e:void 0,taskReferences:Qt,onAssignTaskToWorkstream:j.type==="workstream"?Xt:void 0,onAssignInitiativeToWorkstream:At,onAttachTaskToWorkstreamByReference:j.type==="workstream"?nt:void 0,onAttachWorkstreamToInitiativeByReference:j.type==="initiative"?Mt:void 0,parentInitiative:j.type==="workstream"?da(j.item):null,onEdit:()=>j.type==="initiative"?qe(j.item.id):Te(j.item.id),onChangeOwner:br=>fe(j.type,j.item.id,br),onChangePlanningOwner:fe,onChangePlanningIdentity:Ee,onArchive:()=>j.type==="initiative"?rt(j.item.id):xe(j.item.id),onUnarchive:()=>j.type==="initiative"?kt(j.item.id):St(j.item.id),onAddPlanningContextFile:ur,onRemovePlanningContextFile:je,onUpdatePlanningContextCaption:ot}):null})]})),ft&&!qt&&!wt&&(Dt?a.jsx(qS,{label:"Workstream",title:Qr.title,description:Qr.description,action:Qr.action,onCollapse:()=>Tt(!1),paneRef:rr}):a.jsx(df,{label:"Workstream",muted:!0,onExpand:()=>Tt(!0)})),Lt&&(u?a.jsx(df,{label:"Workstream",onExpand:pe}):a.jsxs("div",{ref:ka,"data-planning-pane":"secondary",className:`${Ue.paneShell} ${R.appScrollbar} tf-scrollbar ${Ue.detailPane}`.trim(),style:Ga(ft?ac:Jr),children:[a.jsxs("div",{className:Ue.paneHeader,children:[ft?null:a.jsx("button",{type:"button",className:"tf-control-icon",onClick:Ve&&_e||le,"aria-label":Ve?"Cancel workstream editing":`Back to ${Br}`,title:Ve?"Cancel workstream editing":`Back to ${Br}`,children:a.jsx(po,{size:16,"aria-hidden":"true"})}),a.jsx("h2",{className:Ue.paneHeaderLabel,tabIndex:-1,"data-planning-pane-heading":!0,children:nr}),a.jsxs("div",{className:Ue.headerActionGroup,children:[He?a.jsx(Ck,{visible:la.workstream,disabled:KS(He)===0,itemLabel:"tasks",onToggle:()=>Ca("workstream")}):null,ft?a.jsx("button",{type:"button",className:"tf-control-icon",onClick:Me,"aria-label":`Collapse ${nr} pane`,title:`Collapse ${nr} pane`,children:a.jsx(po,{size:16,"aria-hidden":"true"})}):null]})]}),a.jsx("div",{className:Ue.paneContent,"aria-busy":Z?.status==="loading",children:M?.kind==="editor"?a.jsx(fv,{editor:M.editor,draftTitle:Ae,draftDescription:ye,draftOwner:Ne,draftInitiativeId:ae,draftIcon:q,draftColor:W,assigneeOptions:Ie,initiativeLinkOptions:Ye.initiatives,draftInitiativeSummary:he,onChangeDraftTitle:K,onChangeDraftDescription:Re,onChangeDraftOwner:we,onChangeDraftInitiativeId:ie,onChangeDraftIcon:Q,onChangeDraftColor:H,onCancel:le,onSubmit:ke,isSubmitting:Ze}):M?a.jsx(YS,{detail:M.detail,showArchivedChildren:la.workstream,inlineEditor:Ve?{editor:Ve,draftTitle:Ae,draftDescription:ye,draftOwner:Ne,draftInitiativeId:ae,draftInitiativeSummary:he,onChangeDraftTitle:K,onChangeDraftDescription:Re,onChangeDraftOwner:we,onChangeDraftInitiativeId:ie,onCancel:_e||le,onSubmit:ke,isSubmitting:Ze}:null,currentWorkspaceId:te,currentActorId:ce,theme:Le,assigneeOptions:Ie,linkOptions:Ye,showTaskCardStatusLabel:ge,taskArrangeMode:k,onTaskArrangeModeChange:b,onReorderWorkstreamTasks:C,hydrationState:Z,onRetryHydration:ve,onSetTaskStatus:Bt,onArchivePlanningTask:jt,onArchiveResolvedEntity:$,onCreateTaskInWorkstream:Qe,onOpenTaskById:Nt,onChangeTaskAssignee:$e,taskReferences:Qt,onAssignTaskToWorkstream:Xt,onAssignInitiativeToWorkstream:At,onAttachTaskToWorkstreamByReference:nt,parentInitiative:da(M.detail.item),onEdit:()=>Te(M.detail.item.id),onChangeOwner:br=>fe("workstream",M.detail.item.id,br),onChangePlanningOwner:fe,onChangePlanningIdentity:Ee,onArchive:()=>xe(M.detail.item.id),onUnarchive:()=>St(M.detail.item.id),onAddPlanningContextFile:ur,onRemovePlanningContextFile:je,onUpdatePlanningContextCaption:ot}):null})]}))]})})}function jX(e,t,r){const n=String(t||"").trim();if(n)return e.some(l=>l.id===n)?{initiativeId:n,invalid:!1}:{initiativeId:null,invalid:!0};const s=r.trim();if(!s)return{initiativeId:null,invalid:!1};const i=Zk(e,s);return i?{initiativeId:i.id,invalid:!1}:{initiativeId:null,invalid:!0}}function PX(e){return e.taskScope==="open"&&e.summaryCount>0&&(e.loadingTasks||e.activeTaskCount===0||!e.archiveHydrated)}const EX={"annotated_attachments.workspace_access":{enabled:!0,description:"Annotated Attachment workspace readiness gate.",owner:"taskforce",removalMilestone:"Annotated Attachment GA"},"documents.workspace_access":{enabled:!0,description:"Document Manager/editor workspace readiness gate.",owner:"taskforce",removalMilestone:"Document Manager GA"},"workflow_manager.workspace_access":{enabled:!1,description:"Workflow Manager workspace readiness gate.",owner:"taskforce",removalMilestone:"Workflow Manager GA"},"taskforce_agents.workspace_access":{enabled:!1,description:"Taskforce Agents workspace readiness gate.",owner:"taskforce",removalMilestone:"Taskforce Agents workspace GA"},"ai_profiles.workspace_access":{enabled:!0,description:"AI Profiles workspace readiness gate.",owner:"taskforce",removalMilestone:"AI Profiles workspace GA"},"planning.workspace_access":{enabled:!1,description:"Planning workspace readiness gate.",owner:"taskforce",removalMilestone:"Planning workspace GA"}},jf="annotated_attachments.workspace_access",Pf="documents.workspace_access",kg="workflow_manager.workspace_access",gd="taskforce_agents.workspace_access",vg="ai_profiles.workspace_access",wg="planning.workspace_access",NX=Object.entries(EX).reduce((e,[t,r])=>(e[t]={key:t,enabled:!!r.enabled,description:String(r.description||""),owner:String(r.owner||""),removalMilestone:String(r.removalMilestone||"")},e),{});function MX(e){const t=String(e||"").trim();return t&&NX[t]||null}function DX(e){const t=MX(e);return t?t.enabled?{featureKey:e,allowed:!0,source:"app_gate",code:"OK"}:{featureKey:e,allowed:!1,source:"app_gate",code:"APP_GATE_DISABLED"}:{featureKey:e,allowed:!0,source:"none",code:"OK"}}function _u(e){return DX(e.featureKey)}const pd={tasks:"Tasks",planning:"Planning",docs:"Documents",annotate:"Image Notes",workflowManager:"Workflow Manager",taskforceAgents:"Taskforce Agents",aiProfiles:"AI Profiles"},LX=["tasks","planning","docs","annotate","workflowManager","taskforceAgents","aiProfiles"];function OX(e){const t=e?.featureAccess||{},r={tasks:{id:"tasks",label:pd.tasks,featureKey:null,enabled:!0,fallbackModuleId:"tasks"},planning:{id:"planning",label:pd.planning,featureKey:wg,enabled:t[wg]?.allowed??!1,fallbackModuleId:"tasks"},docs:{id:"docs",label:pd.docs,featureKey:Pf,enabled:t[Pf]?.allowed??!0,fallbackModuleId:"tasks"},annotate:{id:"annotate",label:pd.annotate,featureKey:jf,enabled:t[jf]?.allowed??!1,fallbackModuleId:"tasks"},workflowManager:{id:"workflowManager",label:pd.workflowManager,featureKey:kg,enabled:t[kg]?.allowed??!1,fallbackModuleId:"tasks"},taskforceAgents:{id:"taskforceAgents",label:pd.taskforceAgents,featureKey:gd,enabled:t[gd]?.allowed??!1,fallbackModuleId:"tasks"},aiProfiles:{id:"aiProfiles",label:pd.aiProfiles,featureKey:vg,enabled:t[vg]?.allowed??!1,fallbackModuleId:"tasks"}};return LX.map(n=>r[n])}function BX(e){switch(e){case"planning":return{mode:e,moduleId:"planning",layoutVariant:"planning-module",headerSections:[],primaryAction:null};case"docs":return{mode:e,moduleId:"docs",layoutVariant:"docs-minimal",headerSections:[],primaryAction:null};case"annotate":return{mode:e,moduleId:"annotate",layoutVariant:"annotated-module",headerSections:[],primaryAction:null};case"workflowManager":return{mode:e,moduleId:"workflowManager",layoutVariant:"workflow-manager-module",headerSections:[],primaryAction:null};case"taskforceAgents":return{mode:e,moduleId:"taskforceAgents",layoutVariant:"taskforce-agents-module",headerSections:[],primaryAction:null};case"aiProfiles":return{mode:e,moduleId:"aiProfiles",layoutVariant:"ai-profiles-module",headerSections:[],primaryAction:null};default:return{mode:"tasks",moduleId:"tasks",layoutVariant:"tasks-default",headerSections:["search","sort","divider-primary","grouping","divider-secondary","task-display-actions"],primaryAction:"add-task"}}}function ZS(e,t){const r=e==="agents"?"aiProfiles":e,n=t.find(s=>s.id===r);return n?n.enabled?n.id:n.fallbackModuleId:"tasks"}const WX="_weekLabel_vet2o_1",$X="_sectionTitle_vet2o_6",FX="_calendarHeader_vet2o_11",UX="_monthLabel_vet2o_18",zX="_weekdayGrid_vet2o_23",HX="_weekdayLabel_vet2o_30",GX="_calendarGrid_vet2o_36",VX="_calendarDay_vet2o_42",KX="_calendarDayDot_vet2o_55",qX="_jumpRow_vet2o_67",YX="_displaySection_vet2o_73",ZX="_toggleLabel_vet2o_79",JX="_expiredSummary_vet2o_87",QX="_actionButton_vet2o_95",Kn={weekLabel:WX,sectionTitle:$X,calendarHeader:FX,monthLabel:UX,weekdayGrid:zX,weekdayLabel:HX,calendarGrid:GX,calendarDay:VX,calendarDayDot:KX,jumpRow:qX,displaySection:YX,toggleLabel:ZX,expiredSummary:JX,actionButton:QX},JS=["mon","tue","wed","thu","fri","sat","sun"],XX={mon:"Mon",tue:"Tue",wed:"Wed",thu:"Thu",fri:"Fri",sat:"Sat",sun:"Sun"};function bd(e){const t=e.getFullYear(),r=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return`${t}-${r}-${n}`}function bf(e){const t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return null;const r=new Date(Number(t[1]),Number(t[2])-1,Number(t[3]));return Number.isNaN(r.getTime())?null:r}function mv(e,t){const r=e.getDay(),n=t==="sunday"?-r:r===0?-6:1-r,s=new Date(e);return s.setHours(0,0,0,0),s.setDate(s.getDate()+n),s}function eee(e,t){return t==="sunday"?{sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}[e]:{mon:0,tue:1,wed:2,thu:3,fri:4,sat:5,sun:6}[e]}function x_(e,t){const r=new Date(e);return r.setDate(e.getDate()+t),r}function tee(e){const t=e.match(/^(\d{4})-(\d{2})-(\d{2})$/);if(!t)return null;const r=new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3]))),n=r.getUTCDay()||7;r.setUTCDate(r.getUTCDate()+4-n);const s=new Date(Date.UTC(r.getUTCFullYear(),0,1)),i=Math.ceil(((r.getTime()-s.getTime())/864e5+1)/7);return`${r.getUTCFullYear()}-W${String(i).padStart(2,"0")}`}const hv=320;function ree({open:e,onClose:t,scheduleSelectedDate:r,setScheduleSelectedDate:n,scheduleCalendarMonth:s,setScheduleCalendarMonth:i,scheduleShowWeekends:l,setScheduleShowWeekends:c,scheduleShowBacklog:d,setScheduleShowBacklog:f,scheduleOnlyExpired:p,setScheduleOnlyExpired:g,expiredScheduledCount:h,overdueDueCount:y,expiredLeafCandidates:k,expiredRecoveryCandidates:b,onMoveExpiredToSelectedWeek:C,onMoveExpiredToBacklog:S,scheduleBulkBusy:w,globalWeekStartsOn:T,resolvedLocale:E,todayDateOnly:x,scheduleBaseTasks:N,scheduleWeekStart:v,scheduleWeekLabel:V}){const _=Y.useMemo(()=>{const[O,Z]=s.split("-"),U=Number(O),ve=Number(Z);if(!Number.isInteger(U)||!Number.isInteger(ve)||ve<1||ve>12){const te=bf(r)||new Date;return new Date(te.getFullYear(),te.getMonth(),1)}return new Date(U,ve-1,1)},[s,r]),j=Y.useMemo(()=>ug(_,{month:"long",year:"numeric"},E),[_,E]),F=Y.useMemo(()=>{const O=mv(_,T);return Array.from({length:42},(Z,U)=>x_(O,U))},[_,T]),z=Y.useMemo(()=>{const O=new Map;for(const Z of N){const U=Z.scheduledDate||"";if(!U)continue;const te=!(Z.status==="done"||Z.status==="cancelled")&&U<x,ce=O.get(U);ce?(ce.count+=1,te&&(ce.hasExpired=!0)):O.set(U,{count:1,hasExpired:te})}return O},[N,x]),M=Y.useMemo(()=>T==="sunday"?["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]:["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],[T]);return a.jsxs("aside",{className:`${R.appScrollbar} tf-scrollbar tf-sidebar-shell`,style:{transform:e?"translateX(0)":"translateX(108%)",pointerEvents:e?"auto":"none",transition:"transform 220ms cubic-bezier(0.4, 0, 0.2, 1)",willChange:"transform",width:`${hv}px`,minWidth:`${hv}px`},children:[a.jsxs("div",{className:"tf-sidebar-header",children:[a.jsxs("div",{className:"tf-sidebar-title",children:[a.jsx(g0,{size:16}),a.jsx("span",{children:"Schedule Controls"})]}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:t,title:"Hide Schedule Sidebar",children:a.jsx(xd,{size:16})})]}),a.jsxs("div",{className:Kn.weekLabel,children:["Week of ",V]}),a.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[a.jsxs("div",{className:Kn.calendarHeader,children:[a.jsx("button",{className:"tf-control-icon",onClick:()=>{const O=new Date(_);O.setMonth(_.getMonth()-1),i(`${O.getFullYear()}-${String(O.getMonth()+1).padStart(2,"0")}`)},title:"Previous month",children:a.jsx(po,{size:14})}),a.jsx("div",{className:Kn.monthLabel,children:j}),a.jsx("button",{className:"tf-control-icon",onClick:()=>{const O=new Date(_);O.setMonth(_.getMonth()+1),i(`${O.getFullYear()}-${String(O.getMonth()+1).padStart(2,"0")}`)},title:"Next month",children:a.jsx(xd,{size:14})})]}),a.jsx("div",{className:Kn.weekdayGrid,children:M.map(O=>a.jsx("div",{className:Kn.weekdayLabel,children:O},O))}),a.jsx("div",{className:Kn.calendarGrid,children:F.map(O=>{const Z=bd(O),U=O.getMonth()!==_.getMonth(),ve=mv(O,T),te=bd(ve)===bd(v),ce=Z===r,Le=Z===x,Ie=Z<x,Ye=z.get(Z),ge=!!Ye,he=!!Ye?.hasExpired;return a.jsxs("button",{onClick:()=>{n(Z),i(`${O.getFullYear()}-${String(O.getMonth()+1).padStart(2,"0")}`)},className:Kn.calendarDay,style:{"--calendar-day-border":ce?"1px solid #2563eb":Le?"1px solid rgba(245, 158, 11, 0.95)":"1px solid transparent","--calendar-day-background":ce?"rgba(59,130,246,0.22)":Le?"rgba(245,158,11,0.16)":te?"rgba(59,130,246,0.18)":"transparent","--calendar-day-color":U?"var(--text-helper)":"var(--text-primary)","--calendar-day-font-weight":ce||Le?700:500,"--calendar-day-opacity":Ie?.42:1},title:`${Le?`${Z} (Today)`:Z}`+(ge?` • ${Ye?.count} scheduled`:"")+(he?" • includes expired":""),children:[O.getDate(),ge&&a.jsx("span",{className:Kn.calendarDayDot,style:{"--calendar-dot-background":he?"#ef4444":"#3b82f6","--calendar-dot-opacity":U?.6:.95}})]},Z)})}),a.jsx("div",{className:Kn.jumpRow,children:a.jsx("button",{className:"tf-control-icon",onClick:()=>{const O=new Date;n(bd(O)),i(`${O.getFullYear()}-${String(O.getMonth()+1).padStart(2,"0")}`)},title:"Jump to current week",children:"Today"})})]}),a.jsxs("div",{className:`tf-sidebar-section tf-surface-panel ${Kn.displaySection}`,children:[a.jsx("div",{className:Kn.sectionTitle,children:"Display"}),a.jsxs("label",{className:Kn.toggleLabel,children:[a.jsx("input",{type:"checkbox",checked:l,onChange:O=>c(O.target.checked)}),"Show weekends"]}),a.jsxs("label",{className:Kn.toggleLabel,children:[a.jsx("input",{type:"checkbox",checked:d,onChange:O=>f(O.target.checked)}),"Show backlog"]}),a.jsxs("label",{className:Kn.toggleLabel,children:[a.jsx("input",{type:"checkbox",checked:p,onChange:O=>g(O.target.checked)}),"Only expired/overdue"]})]}),h>0&&a.jsxs("div",{className:"tf-sidebar-section tf-surface-panel",children:[a.jsx("div",{className:Kn.sectionTitle,children:"Expired Tasks"}),a.jsxs("div",{className:Kn.expiredSummary,children:[a.jsxs("span",{children:[h," expired"]}),a.jsxs("span",{children:[y," overdue"]})]}),a.jsx("button",{className:`tf-control-icon ${Kn.actionButton}`,onClick:C,disabled:w||k.length===0,title:"Move expired leaf tasks to the selected week while keeping weekday alignment",children:w?"Working...":"Schedule to selected week"}),a.jsx("button",{className:`tf-control-icon ${Kn.actionButton}`,onClick:S,disabled:w||b.length===0,title:"Unschedule expired/overdue tasks back to backlog",children:w?"Working...":"Unschedule to backlog"})]})]})}const aee=[{value:"implementation-plan",label:"Plans"},{value:"review",label:"Reviews"},{value:"walkthrough",label:"Walkthroughs"},{value:"planning",label:"Planning"},{value:"other",label:"Other"}],nee=[{value:"attached",label:"Attached"},{value:"unattached",label:"Unattached"}];function R_(e,t){return e&&(t==="owner"||t==="admin")}function see(e,t,r){return R_(e,t)&&r==="team"}function oee({isOpen:e,workspaceId:t,refreshKeys:r}){const[n,s]=o.useState([]),[i,l]=o.useState(!1),[c,d]=o.useState(null),f=o.useRef(null),p=o.useRef(null);o.useLayoutEffect(()=>{p.current=cee(f.current,p.current)},[n]);const g=o.useCallback(async()=>{const h=await fetch(`/api/taskforce/sync/events?workspace_id=${encodeURIComponent(t)}&limit=15`,{method:"GET",credentials:"include"});if(!h.ok)throw new Error(`Failed to load sync events (${h.status})`);const y=await h.json().catch(()=>({}));return Array.isArray(y?.events)?y.events.filter(k=>k&&typeof k=="object"):[]},[t]);return o.useEffect(()=>{if(!e)return;let h=!1;const y=n.length===0;return y&&l(!0),g().then(k=>{h||(p.current=iee(f.current),s(b=>{const C=b.length===0?k:hY(b,k,15);return gY(b,C)?b:C}),d(null))}).catch(k=>{if(h)return;const b=k instanceof Error&&k.message.trim().length>0?k.message.trim():"Unable to load recent sync events.";d(b),y&&s([])}).finally(()=>{h||y&&l(!1)}),()=>{h=!0}},[e,g,...r]),{syncRecentEvents:n,syncRecentEventsLoading:i,syncRecentEventsError:c,syncEventsListRef:f,loadRecentSyncEvents:g}}function iee(e){return e&&e.scrollTop>8?{scrollTop:e.scrollTop,scrollHeight:e.scrollHeight}:null}function cee(e,t){if(!t||!e)return null;const r=e.scrollHeight-t.scrollHeight;return e.scrollTop=t.scrollTop+Math.max(0,r),null}function lee({currentWorkspaceId:e,syncStatusLabel:t,workspaceSyncSummary:r,workspaceSyncRecommendedAction:n,formattedLastSyncTime:s,formattedLastPullTime:i,formattedLastPushTime:l,workspaceSyncDiagnostics:c,workspaceSyncPendingChanges:d,syncLastError:f,workspaceSyncPhase:p,referenceMismatchCount:g,syncRecentEvents:h,loadRecentSyncEvents:y,pushNotice:k,resetWorkspaceSyncCursorAndPull:b,workspaceSyncBusy:C,durableRepairQueueAvailable:S=!1}){const[w,T]=o.useState(!1),[E,x]=o.useState(!1),[N,v]=o.useState(!1),V=o.useCallback(async()=>{try{const F=h.length>0?h:await y(),z=CY({currentWorkspaceId:e,syncStatusLabel:t,workspaceSyncSummary:r,workspaceSyncRecommendedAction:n,formattedLastSyncTime:s,formattedLastPullTime:i,formattedLastPushTime:l,workspaceSyncDiagnostics:c,workspaceSyncPendingChanges:d,syncLastError:f,syncStageLabel:s_(p,w,C),referenceMismatchCount:g,syncRecentEvents:F});await navigator.clipboard.writeText(z),v(!0),window.setTimeout(()=>{v(!1)},1800),k("Sync details copied to clipboard.","success")}catch{v(!1),k("Failed to copy sync details.","error")}},[e,i,l,s,y,k,g,f,h,t,c,p,d,n,r,C,w]),_=o.useCallback(async()=>{x(!1),T(!0);try{await b()}finally{T(!1)}},[b]),j=o.useCallback(()=>{if(!w){if(C&&!S){x(!0);return}_()}},[S,_,C,w]);return o.useEffect(()=>{E&&(C||w||_())},[_,C,w,E]),{workspaceSyncRepairBusy:w,workspaceSyncRepairQueued:E,workspaceSyncCopied:N,handleCopySyncDetails:V,handleQueueOrRunRepairSync:j}}function dee({canManageWorkspaceSync:e,workspaceCloudSyncEnabled:t,saveWorkspaceCloudSyncSettings:r}){const[n,s]=o.useState(!1),[i,l]=o.useState(!1),[c,d]=o.useState(!1),[f,p]=o.useState(null),g=o.useCallback(async S=>{if(e){p(null),d(!0);try{const w=await r({enabled:S});w.success||p(w.error||(S?"Failed to enable sync.":"Failed to disable sync."))}finally{d(!1)}}},[e,r]),h=o.useCallback(async S=>{if(S&&!t){l(!0);return}await g(S)},[g,t]),y=o.useCallback(()=>{l(!1)},[]),k=o.useCallback(()=>{l(!1),g(!0)},[g]),b=o.useCallback(()=>{s(!0)},[]),C=o.useCallback(()=>{s(!1)},[]);return{showSyncStatusModal:n,showSyncEnableWarning:i,workspaceSyncToggleBusy:c,workspaceSyncError:f,syncControlBusy:c,openSyncStatusModal:b,closeSyncStatusModal:C,handleWorkspaceSyncToggle:h,cancelSyncEnableWarning:y,confirmSyncEnableWarning:k}}const QS=Y.lazy(()=>Lo(()=>import("./TaskSettings-g4ECKNOz.js"),__vite__mapDeps([10,1,2,3,4,5,11])).then(e=>({default:e.TaskSettings}))),uee=Y.lazy(()=>Lo(()=>import("./AnnotatedAttachmentWorkspace-DVZk5Tln.js"),__vite__mapDeps([12,1,4,13,2,14,3,5,15])).then(e=>({default:e.AnnotatedAttachmentWorkspaceShell}))),pee=Y.lazy(()=>Lo(()=>import("./DocumentWorkspace-DXH4XUsB.js"),__vite__mapDeps([16,1,13,2,14,3,4,5,17])).then(e=>({default:e.DocumentWorkspaceShell}))),XS=Y.lazy(()=>Lo(()=>import("./TaskforceAgentsModule-BazdUwxZ.js"),__vite__mapDeps([18,1,19,2,3,4,5,20])).then(e=>({default:e.TaskforceAgentsModule}))),fee=Y.lazy(()=>Lo(()=>import("./WorkflowManagerModule-DWFspC-o.js"),__vite__mapDeps([21,1,2,3,4,5,22])).then(e=>({default:e.WorkflowManagerModule}))),mee=Y.lazy(()=>Lo(()=>import("./AiProfilesModule-C3i0LOxe.js"),__vite__mapDeps([23,1,19,2,3,4,5])).then(e=>({default:e.AiProfilesModule}))),hee=Y.lazy(()=>Lo(()=>import("./PlanningModule-BPVyEa-f.js"),__vite__mapDeps([24,1,2,3,4,5,25])).then(e=>({default:e.PlanningModule}))),gee=Y.lazy(()=>Lo(()=>import("./PlansPage-ChqgxALc.js"),__vite__mapDeps([26,1,2,5,3,4,27])).then(e=>({default:e.PlansPage})));function eA(e,t,r){const n=t.trim();if(!n)return e;const s={...e};return delete s[n],s[n]=r,Object.fromEntries(Object.entries(s).slice(-50))}const yee="image/png,image/jpeg,image/webp,image/gif",kee=5*1024*1024,Ik=56,vee=e=>e;function wee(e,t){const r=Tg(e);if(r)return lb(r).label.toUpperCase();for(const n of t){const s=String(n||"").trim();if(!s)continue;const i=Pv(s);if(i)return lb(i).label.toUpperCase();let l=s.toLowerCase();try{l=new URL(s.includes("://")?s:`https://${s}`).hostname.toLowerCase()}catch{l=s.toLowerCase()}if(!(l.includes("localhost")||l.includes("127.0.0.1")||l.includes("::1")))return l.toUpperCase()}return"UNKNOWN"}function uf(){return typeof performance<"u"?performance.now():Date.now()}function bee(e){const n=bA(),s=SA(),i=o.useMemo(()=>new URLSearchParams(s.search),[s.search]),l=String(i.get("screen")||"").trim().toLowerCase()==="plans",c=o.useCallback(m=>{const A=new URLSearchParams(s.search);A.set("screen","plans");for(const[B,be]of Object.entries(m||{}))be==null||String(be).trim()===""?A.delete(B):A.set(B,String(be));n(`/?${A.toString()}${s.hash||""}`)},[s.hash,s.search,n]),d=o.useCallback(()=>{const m=new URLSearchParams(s.search);m.delete("screen"),m.delete("gate"),m.delete("checkout"),m.delete("planId"),m.delete("planVersionId"),m.delete("interval");const A=m.toString();n(`${s.pathname==="/"?"/":s.pathname}${A?`?${A}`:""}${s.hash||""}`)},[s.hash,s.pathname,s.search,n]),{activeTab:f,setActiveTab:p,activeCategories:g,groupBy:h,setGroupBy:y,activeWorkspaceModule:k,setActiveWorkspaceModule:b,emptyColumnMode:C,setEmptyColumnMode:S,zenMode:w,setZenMode:T,filterStatus:E,setFilterStatus:x,tasks:N,handleEdit:v,handleSubmit:V,resetForm:_,discardDescriptionImageDraft:j,handleUpdateTask:F,handleSetStatus:z,editingTaskId:M,loading:O,error:Z,title:U,setTitle:ve,setTitleDraft:te,description:ce,setDescription:Le,setDescriptionDraft:Ie,checklistItems:Ye,setChecklistItems:ge,category:he,setCategory:Ae,type:ye,setType:Ne,priority:ae,setPriority:q,complexity:W,setComplexity:K,status:Re,setStatus:we,assignee:ie,setAssignee:Q,scheduledDate:H,setScheduledDate:se,dueDate:Pe,setDueDate:ue,workstreamInput:ne,setWorkstreamInput:Me,manualComplexityEnabled:pe,checklistDropdownEnabled:le,showTaskCardStatusLabel:Ce,formTaxonomies:P,setFormTaxonomies:ee,comments:Se,newCommentText:_e,setNewCommentText:ke,attachments:Ze,setAttachments:st,attachmentsDirty:at,setAttachmentsDirty:oe,descriptionImageUploadPending:We,descriptionImageDraftId:G,registerDescriptionImageUpload:Be,descriptionFocused:Xe,setDescriptionFocused:ze,showMarkdownHelp:qe,setShowMarkdownHelp:Te,handleAddComment:fe,handleSetWorkstreamForCurrentTask:Ee,handleOpenTaskById:$e,taxonomies:rt,activeTypes:kt,priorities:xe,taxonomyDisplayLabels:St,copiedId:jt,handleCopyId:$,handleToggleInProgress:Ke,handleToggleComplete:Qe,handleToggleReview:Ge,handleToggleCancel:At,handleArchiveTask:Nt,handleDelete:Bt,handleUnarchive:Qt,handleRestoreDeletedTask:Xt,handleRestoreSelectedDeletedTasks:nt,handlePermanentlyDeleteDeletedTask:Mt,handleEmptyDeletedTasks:ur,fetchTasks:je,searchQuery:ot,setSearchQuery:pt,filterCategories:Ve,setFilterCategories:lt,filterTypes:It,setFilterTypes:wt,filterPriorities:$t,setFilterPriorities:Yt,filterAssignees:qt,setFilterAssignees:er,hasInitedFilters:_t,assigneeOptions:Dt,taskScope:Tt,setTaskScope:Xr,compressedCards:Rr,setCompressedCards:la,sortBy:sa,setSortBy:ea,clearFilters:Ur,settingsModel:Ft,configLoaded:ft,currentTheme:Rt,setCurrentTheme:_r,pathSaved:u,saveSettings:Pt,keyShortcut:pr,setKeyShortcut:Yr,globalWeekStartsOn:tr,locale:$r,jsonBackupEnabled:Lt,setJsonBackupEnabled:zr,mcpHostRoot:Ir,setMcpHostRoot:Kt,settingsSection:Jr,setSettingsSection:Br,runtimeMode:nr,workspaceSwitchingEnabled:Zr,cloudAuthConfigured:He,authRequiredForApi:Ca,authBlocked:da,isAuthenticated:ir,authUserId:ut,authWorkspaceId:ka,authUserEmail:Wt,authUserDisplayName:rr,authUserAvatarUrl:oa,authSessionResolved:Mr,realtimeSyncEnabled:vn,realtimeSyncFlagSource:En,workspaceCloudSyncEnabled:Ga,workspaceSyncPhase:Hr,workspaceSyncStatus:Na,workspaceSyncSummary:ta,workspaceSyncRecommendedAction:ua,workspaceSyncBusy:Qr,workspaceSyncPendingChanges:br,localCoordinatorStatus:yr,transferLocalCoordinatorOwnership:Gr,saveWorkspaceCloudSyncSettings:Kr,pushNotice:dt,userGlobalSyncStatus:Ma,workspaceLastSuccessfulSyncAt:Zt,workspaceLastPullAt:Sr,workspaceLastPushAt:va,workspaceLastErrorAt:Ya,userGlobalSyncError:Ar,workspaceLastErrorMessage:ma,retryWorkspaceCloudSync:me,resetWorkspaceSyncCursorAndPull:it,getWorkspaceSyncDiagnostics:mt,currentWorkspaceId:ht,currentWorkspaceRole:Ht,availableWorkspaces:sr,switchWorkspace:wa,updateCurrentUserProfile:fr,resolveCloudAuthUrl:or=vee,logout:Tr,fetchLoginMethods:ha,unlinkLoginMethod:ba,addPasswordToAccount:nn,changePassword:kr,beginOAuthLogin:ho,beginOAuthLink:wn,availableAuthProviders:Bn,projectRoot:Wn,projectName:Ta,mcpScriptPath:Ms,serverHostRoot:Vs,showFolderBrowser:Ks,setShowFolderBrowser:ys,folders:$n,files:Ia,currentBrowsePath:fn,fetchFolders:xa,browserTarget:ks,setBrowserTarget:sn,handleSelectPath:mn,handleAddPath:on,handleRemovePath:Zn,handleUpdateCategory:Da,handleRemoveCategory:qs,handleSaveCategory:vt,handleUpdateCategoryIcon:hr,handleUpdateCategoryColor:ga,handleSaveType:ia,handleRemoveType:Za,handleUpdateTaxonomies:Ys,handleUpdatePriorities:ca,pathValidation:vs,taskforceAgentId:Fa,setTaskforceAgentId:Jn,taskforceAgentConversationId:La,setTaskforceAgentConversationId:vr,taskforceAgentConversationByAgentId:Ja,setTaskforceAgentConversationByAgentId:Qn,uiStateReady:cn,initiativeTemplates:bn,fetchInitiativeTemplates:Ra,createInitiativeFromTemplate:Zs,uiNotice:Xn,clearNotice:es,clearTaskError:pa,taskReturnTrail:Sn,clearReturnToParentTask:ln,returnToPreviousTask:An,tasksScrollRef:ws,setTasksScrollPos:Oa,commentsEndRef:Va,autoSaveState:de,unsavedModalOpen:yt,setUnsavedModalOpen:ar,pendingNavigation:gr,handleNavigation:Pr,currentTask:ra,currentTaskWorkstream:Fn,currentTaskInitiative:Qa,scheduleWarningPrompt:Ai,confirmScheduleWarning:Cn,cancelScheduleWarning:si}=e,Nn=oI(N,$e),bs=$r||NA();o.useEffect(()=>{const m=String(Ta||"").trim();document.title=m?`Taskforce - ${m}`:"Taskforce"},[Ta]);const Oo=()=>{ar(!1),f==="add"&&!M&&j(),gr?(f==="add"&&_(),gr()):(f==="add"&&_(),p("tasks"))},Vt=async()=>{await V({preventDefault:()=>{}}),ar(!1),gr&&gr()},[Sa,hn]=o.useState(!1),[aa,Ds]=o.useState(!0),[Mn,Ls]=o.useState(!1),[Ss,go]=o.useState(!0),[ts,rs]=o.useState(bd(new Date)),[Un,na]=o.useState(()=>{const m=new Date;return`${m.getFullYear()}-${String(m.getMonth()+1).padStart(2,"0")}`}),[Js,yo]=o.useState(0),[Bo,oi]=o.useState(!1),[ii,as]=o.useState(!1),[Ka,In]=o.useState(!1),Ci=o.useRef(null),[As,Ii]=o.useState(!0),[_n,Wo]=o.useState(!0),[_a,Cs]=o.useState(!0),[jr,nc]=o.useState(!0),[Xa,dn]=o.useState(!0),[Is,Md]=o.useState(!1),[kl,Tn]=o.useState(null),_i=o.useRef(!1),zn=o.useRef(null),[_s,Qs]=o.useState(Ik),[ko,$o]=o.useState(!1),[ns,ci]=o.useState(!1),[li,vo]=o.useState(!1),[sc,vl]=o.useState(!1),[Dc,ss]=o.useState(!1),[Vr,Dd]=o.useState(!1),[Dn,Os]=o.useState("default"),[Ts,wo]=o.useState("execution"),[wl,bl]=o.useState([]),[D,L]=o.useState(""),[Ct,zt]=o.useState(""),[xt,Oe]=o.useState(new Set),[ya,Jt]=o.useState(null),[Aa,xn]=o.useState(null),[Bs,xs]=o.useState({}),[ja,di]=o.useState(null),[Ti,Fo]=o.useState(null),[Ld,oc]=o.useState(""),[Sl,ic]=o.useState(""),[Yu,cc]=o.useState(""),[Rn,ui]=o.useState(""),[Lc,Al]=o.useState(null),[Oc,Cl]=o.useState(null),[Bg,xi]=o.useState(!1),Od=o.useRef({taskId:null,attachments:[]}),en=o.useMemo(()=>bd(new Date),[]),Ba=String(ut||"").trim(),{taskHeaderQuickFilter:os,toggleTaskHeaderQuickFilter:Qf,clearTaskHeaderQuickFilter:Xf}=cY({authUserId:Ba,workspaceId:ht,taskScope:Tt}),em=o.useRef(new Map),Bd=o.useRef(new Map),[Zu,tm]=o.useState(()=>aee.map(m=>m.value)),[Wd,rm]=o.useState(()=>nee.map(m=>m.value)),[Ju,am]=o.useState("updated"),[Qu,$d]=o.useState("desc"),[Il,Fd]=o.useState([]),[_l,Bc]=o.useState(""),[Ri,Tl]=o.useState(null),[xl,Xu]=o.useState({}),[Ud,ep]=o.useState(0),[nm,Rl]=o.useState(null),[sm,Wc]=o.useState(null),[jl,pi]=o.useState(null),[zd,lc]=o.useState(null),[Hd,Pl]=o.useState({}),[om,ji]=o.useState(0),El=o.useRef(null),[bo,im]=o.useState({}),Xs=o.useRef(!1),eo=o.useRef(null),fi=o.useRef(null),tp=o.useRef(null),rp=o.useRef(new Set);o.useEffect(()=>{Od.current={taskId:M||null,attachments:Ze}},[M,Ze]);const Uo=o.useCallback(m=>{const A=M||null,B=Od.current,be=B.taskId===A?B.attachments:Ze,De=m(be);Od.current={taskId:A,attachments:De},st(De),oe(!0),A&&F(A,{attachments:De}).then(Ot=>{const xr=Od.current;Ot!==!1&&xr.taskId===A&&xr.attachments===De&&oe(!1)}).catch(()=>{})},[Ze,M,F,st,oe]),dc=o.useMemo(()=>{const m={},A=String(ht||"").trim();return nr==="cloud"&&A&&A!=="default"&&(m["x-taskforce-workspace-id"]=A),m},[nr,ht]),mi=o.useMemo(()=>ZY({runtimeMode:nr,workspaceId:ht,userId:Ba}),[ht,Ba,nr]),Gd=o.useRef(mi),ap=Gd.current===mi,Ws=ap?jl:null,Nl=ap?zd:null,zo=o.useMemo(()=>`taskforce:task-origin-workspace-module:${mi}`,[mi]),Ml=o.useMemo(()=>nr==="cloud"?Mr:ft,[Mr,ft,nr]),Dl=o.useRef(!1),Ll=o.useRef(!1),Ol=o.useCallback(m=>{const A=String(m||"").trim();if(!(!A||typeof window>"u")){Dl.current=!0;try{window.sessionStorage.setItem(zo,A)}catch{}}},[zo]),hi=o.useCallback(()=>{if(Dl.current=!1,!(typeof window>"u"))try{window.sessionStorage.removeItem(zo)}catch{}},[zo]);o.useEffect(()=>{eo.current=jl},[jl]),o.useEffect(()=>{fi.current=zd},[zd]),o.useEffect(()=>{Gd.current!==mi&&(Gd.current=mi,eo.current=null,fi.current=null,tp.current=null,pi(null),lc(null))},[mi]);const gi=o.useMemo(()=>({[Pf]:_u({featureKey:Pf}),[jf]:_u({featureKey:jf}),[kg]:_u({featureKey:kg}),[gd]:_u({featureKey:gd}),[vg]:_u({featureKey:vg}),[wg]:_u({featureKey:wg})}),[nr]),Ho=o.useMemo(()=>OX({featureAccess:gi}),[gi]),Cr=o.useMemo(()=>ZS(k,Ho),[k,Ho]),np=Ka||Cr==="planning";o.useEffect(()=>{np&&e.ensureArchiveHydrated(!0)},[np,e.ensureArchiveHydrated,ht]);const[to,uc]=o.useState(!1),[Pi,pc]=o.useState(!1),[cm,Bl]=o.useState(null),[lm,Vd]=o.useState(null),sp=o.useCallback(m=>{Vd(m)},[]),Wl=o.useCallback(m=>{const A=String(m.agentId||"").trim(),B=String(m.conversationId||"").trim();Jn(A),vr(B),A&&Qn(be=>{if(B)return be[A]===B?be:{...be,[A]:B};if(!be[A])return be;const De={...be};return delete De[A],De})},[Qn,vr,Jn]),Ei=gi[Pf]?.allowed??!1,$c=gi[jf]?.allowed??!1,$l=gi[gd]?.allowed??!1,op="Documents is not available in this build yet.",ip="Annotate is not available in this build yet.",So=o.useCallback(m=>{if(f!=="add"){m();return}Pr(()=>{as(!1),_(),p("tasks"),m()})},[f,Pr,_,p]);o.useEffect(()=>{const m=A=>{const B=A,be=B.detail?.fsPath,De=String(B.detail?.assetId||"").trim()||null;if(!(!be&&!De)){if(B.preventDefault(),!Ei){dt(op,"error");return}So(()=>{Ol(B.detail?.taskId),Rl(be||null),Wc(De),b("docs")})}};return window.addEventListener("taskforce:open-markdown-document",m),()=>{window.removeEventListener("taskforce:open-markdown-document",m)}},[Ei,op,So,dt,Ol,b]),o.useEffect(()=>{Cr!==k&&b(Cr)},[k,Cr,b]),o.useEffect(()=>{Cr==="docs"&&Ei||(Rl(null),Wc(null))},[Ei,Cr]),o.useEffect(()=>{if(!Ll.current&&!(Cr!=="docs"&&Cr!=="annotate")&&(Ll.current=!0,!(Dl.current||typeof window>"u")))try{if(!String(window.sessionStorage.getItem(zo)||"").trim())return;window.sessionStorage.removeItem(zo),b("tasks")}catch{}},[Cr,b,zo]),o.useEffect(()=>{Ll.current=!1,Dl.current=!1},[zo]);const dm=o.useCallback(m=>{typeof m.scheduleShowWeekends=="boolean"&&hn(m.scheduleShowWeekends),typeof m.scheduleShowBacklog=="boolean"&&Ds(m.scheduleShowBacklog),typeof m.scheduleOnlyExpired=="boolean"&&Ls(m.scheduleOnlyExpired),typeof m.scheduleSidebarOpen=="boolean"&&go(m.scheduleSidebarOpen),typeof m.scheduleSelectedDate=="string"&&rs(m.scheduleSelectedDate),typeof m.scheduleCalendarMonth=="string"&&na(m.scheduleCalendarMonth),typeof m.scheduleScrollLeft=="number"&&yo(m.scheduleScrollLeft),typeof m.showFilters=="boolean"&&oi(m.showFilters),Array.isArray(m.documentTypeFilters)&&tm(m.documentTypeFilters),Array.isArray(m.documentAttachmentFilters)&&rm(m.documentAttachmentFilters),(m.documentSortField==="updated"||m.documentSortField==="reference"||m.documentSortField==="name"||m.documentSortField==="size"||m.documentSortField==="created")&&am(m.documentSortField),(m.documentSortOrder==="asc"||m.documentSortOrder==="desc")&&$d(m.documentSortOrder),Array.isArray(m.documentPinnedDocIds)&&Fd(m.documentPinnedDocIds),typeof m.documentSearchQuery=="string"&&Bc(m.documentSearchQuery),(typeof m.documentSelectedDocId=="string"||m.documentSelectedDocId===null)&&Tl(m.documentSelectedDocId),Xu(m.documentScrollByDocId&&typeof m.documentScrollByDocId=="object"?m.documentScrollByDocId:{}),typeof m.documentListScrollTop=="number"&&ep(m.documentListScrollTop),typeof m.planningDrawerOpen=="boolean"&&In(m.planningDrawerOpen),typeof m.documentTrayOpen=="boolean"&&Ii(m.documentTrayOpen),typeof m.imageTrayOpen=="boolean"&&Wo(m.imageTrayOpen),typeof m.agentTrayOpen=="boolean"&&Cs(m.agentTrayOpen),typeof m.taskforceAgentRosterTrayOpen=="boolean"&&nc(m.taskforceAgentRosterTrayOpen),typeof m.taskforceAgentDrawerOpen=="boolean"&&uc(m.taskforceAgentDrawerOpen),typeof m.taskforceAgentPanelCollapsed=="boolean"&&pc(m.taskforceAgentPanelCollapsed),typeof m.planningTreeCollapsed=="boolean"&&$o(m.planningTreeCollapsed),typeof m.planningPrimaryCollapsed=="boolean"&&ci(m.planningPrimaryCollapsed),typeof m.planningSecondaryCollapsed=="boolean"&&vo(m.planningSecondaryCollapsed),vl(!!m.planningFavoritesSectionCollapsed),ss(!!m.planningInitiativesSectionCollapsed),Dd(!!m.planningWorkstreamsSectionCollapsed),(m.planningNavigatorSort==="default"||m.planningNavigatorSort==="title"||m.planningNavigatorSort==="owner"||m.planningNavigatorSort==="progress")&&Os(m.planningNavigatorSort),wo(YQ(m.planningTaskArrangeMode)),bl(Array.isArray(m.planningFavorites)?m.planningFavorites:[]),Array.isArray(m.planningExpandedInitiativeIds)&&Oe(new Set(m.planningExpandedInitiativeIds)),m.planningDrawerDetail!==void 0&&Jt(m.planningDrawerDetail),(typeof m.planningNestedWorkstreamDetailId=="string"||m.planningNestedWorkstreamDetailId===null)&&xn(m.planningNestedWorkstreamDetailId);const A=m.annotatedTarget&&typeof m.annotatedTarget=="object"?m.annotatedTarget:null,B=A&&typeof m.annotatedSessionId=="string"?m.annotatedSessionId:null;wz({currentTarget:eo.current,currentSessionId:fi.current,lastHydratedIdentity:tp.current})&&(eo.current=A,fi.current=B,tp.current=mI(A,B),pi(A),lc(B)),Pl(m.annotatedViewportByContextKey&&typeof m.annotatedViewportByContextKey=="object"?m.annotatedViewportByContextKey:{})},[]),Wg=o.useMemo(()=>({scheduleShowWeekends:Sa,scheduleShowBacklog:aa,scheduleOnlyExpired:Mn,scheduleSidebarOpen:Ss,scheduleSelectedDate:ts,scheduleCalendarMonth:Un,scheduleScrollLeft:Js,showFilters:Bo,documentTypeFilters:Zu,documentAttachmentFilters:Wd,documentSortField:Ju,documentSortOrder:Qu,documentPinnedDocIds:Il,documentSearchQuery:_l,documentSelectedDocId:Ri,documentScrollByDocId:xl,documentListScrollTop:Ud,documentTrayOpen:As,imageTrayOpen:_n,agentTrayOpen:_a,taskforceAgentRosterTrayOpen:jr,taskforceAgentDrawerOpen:to,taskforceAgentPanelCollapsed:Pi,planningDrawerOpen:Ka,planningTreeCollapsed:ko,planningPrimaryCollapsed:ns,planningSecondaryCollapsed:li,planningFavoritesSectionCollapsed:sc,planningInitiativesSectionCollapsed:Dc,planningWorkstreamsSectionCollapsed:Vr,planningNavigatorSort:Dn,planningTaskArrangeMode:Ts,planningFavorites:wl,planningExpandedInitiativeIds:Array.from(xt),planningDrawerDetail:ya,planningNestedWorkstreamDetailId:Aa,annotatedTarget:Ws,annotatedSessionId:Nl,annotatedViewportByContextKey:Hd}),[Sa,aa,Mn,Ss,ts,Un,Js,Bo,Zu,Wd,Ju,Qu,Il,_l,Ri,xl,Ud,As,_n,_a,jr,to,Pi,Ka,ko,ns,li,sc,Dc,Vr,Dn,Ts,wl,xt,ya,Aa,Ws,Nl,Hd]);o.useEffect(()=>{bl([])},[mi]);const{ready:cp}=sZ({currentWorkspaceId:ht,loadKey:mi,enabled:nr!=="cloud"||Mr,headers:dc,remotePlanningFavoritesAuthoritative:!!Ba&&Ba!=="anonymous",useCloudProxy:nr==="local"&&!!Ba&&Ba!=="anonymous",snapshot:Wg,onApplyState:dm});o.useEffect(()=>{h==="schedule"&&go(!0)},[h]);const{showArchive:fc,setShowArchive:Fl,fetchArchive:$g,filteredArchive:um}=e,Ul=o.useMemo(()=>um.map(m=>({...m,isArchived:!0})),[um]),is=o.useMemo(()=>e.archivedTasks.map(m=>({...m,isArchived:!0})),[e.archivedTasks]),yi=o.useMemo(()=>[...e.searchAgnosticTasks,...is],[is,e.searchAgnosticTasks]),pm=o.useCallback(m=>{const A=String(m||"").trim();if(!A)return"";const B=yi.find(be=>be.id===A);return hs(B)||""},[yi]),Fg=o.useCallback(m=>{const A=String(m||"").trim();if(!A)return"";const B=String(bo[A]||"").trim();if(B)return B;for(const be of yi)for(const De of be.attachments||[]){if(!De||typeof De!="object"||String(De.assetId||"").trim()!==A)continue;const Ot=Uf({referenceNumber:typeof De.referenceNumber=="number"?De.referenceNumber:null,referenceLabel:String(De.referenceLabel||"").trim()||null});if(Ot)return Ot}return""},[yi,bo]);o.useEffect(()=>{const m=A=>{const B=A,be=fS(B.detail,yi);if(be){if(B.preventDefault(),!$c){dt(ip,"error");return}So(()=>{eo.current=be;const De=String(be.sessionId||"").trim()||null;fi.current=De,pi(be),lc(De),ji(Ot=>Ot+1),Ol(be.taskId),b("annotate")})}};return window.addEventListener("taskforce:open-annotated-attachment",m),()=>{window.removeEventListener("taskforce:open-annotated-attachment",m)}},[yi,$c,ip,So,dt,Ol,b]),o.useEffect(()=>{if(!Ws)return;const m=fS(Ws,yi);m&&(m.taskReferenceLabel===Ws.taskReferenceLabel&&m.imageReferenceLabel===Ws.imageReferenceLabel||pi(m))},[yi,Ws]),o.useEffect(()=>{const m=eo.current,A=String(m?.assetId||"").trim();if(!A)return;const B=String(bo[A]||"").trim();B&&B!==String(m?.imageReferenceLabel||"").trim()&&pi(be=>!be||String(be.assetId||"").trim()!==A?be:{...be,imageReferenceLabel:B})},[bo,Ws]),o.useEffect(()=>{if(!Ml)return;const A=String(Ws?.assetId||"").trim();if(!A||rp.current.has(A)||String(bo[A]||"").trim())return;let B=!1;rp.current.add(A);const be=String(ht||"default").trim()||"default",De=new URLSearchParams({workspaceId:be});return(async()=>{try{const xr=await fetch(`/api/taskforce/annotated-attachments/images/${encodeURIComponent(A)}?${De.toString()}`,{method:"GET",credentials:"include",headers:dc});if(!xr.ok)return;const Lr=await xr.json().catch(()=>({})),Ln=String(Lr?.target?.imageReferenceLabel||"").trim();if(!Ln||B)return;im(fa=>fa[A]===Ln?fa:{...fa,[A]:Ln})}catch{}finally{rp.current.delete(A)}})(),()=>{B=!0}},[Ml,bo,ht,Ws,dc]);const Go=o.useMemo(()=>e.deletedTasks.map(m=>({...m.taskSnapshot,isDeleted:!0,deletedRecordId:m.id,deletedAt:m.deletedAt,deletedExpiresAt:sI(m.deletedAt)})),[e.deletedTasks]),Ni=o.useMemo(()=>{const m=new Map;return e.deletedTasks.forEach(A=>{m.set(A.taskSnapshot.id,A)}),m},[e.deletedTasks]),Kd=o.useMemo(()=>{const m=Go,A=Ng(ot),B={categories:g,types:kt,priorities:xe,assigneeOptions:e.assigneeOptions,taxonomies:rt},be=g.every(fa=>Ve.includes(fa.value)),De=kt.every(fa=>It.includes(fa.value)),Ot=new Set($t.map(fa=>String(fa))),xr=xe.every(fa=>Ot.has(String(fa.value))),Lr=new Set(E.map(fa=>String(fa))),Ln=rc.every(fa=>Lr.has(String(fa.value)));return m.filter(fa=>{const cl=ag(fa,A,B),vu=be||Ve.includes(fa.category),wu=De||It.includes(fa.type||fo),Ym=xr||Ot.has(String(fa.priority)),Zm=Ln||Lr.has(String(fa.status)),Jm=qt.length===0||qt.includes(fa.assignee||"unassigned");return cl&&vu&&wu&&Ym&&Zm&&Jm})},[g,kt,Go,qt,Ve,$t,E,It,xe,ot]),zl=o.useMemo(()=>[...e.tasks,...is,...Go],[is,Go,e.tasks]),lp=o.useMemo(()=>{const m=g.filter(B=>!B.disabled).map(B=>({value:B.value,label:B.label})),A=g.filter(B=>B.disabled&&zl.some(be=>be.category===B.value)).map(B=>({value:B.value,label:`${B.label} (Legacy)`}));return[...m,...A]},[g,zl]),dp=o.useMemo(()=>{const m=kt.filter(B=>B.status!=="retired").map(B=>({value:B.value,label:B.label})),A=kt.filter(B=>B.status==="retired"&&zl.some(be=>(be.type||fo)===B.value)).map(B=>({value:B.value,label:`${B.label} (Retired)`}));return[...m,...A]},[kt,zl]),fm=o.useCallback(m=>os?m.filter(A=>lY(A,os,Ba,en)):m,[Ba,os,en]),Fc=o.useMemo(()=>fm(e.filteredTasks),[fm,e.filteredTasks]),Uc=o.useMemo(()=>Tt==="archived"?Ul:Tt==="deleted"?Kd:fc?[...Fc,...Ul]:Fc,[Ul,Kd,Fc,fc,Tt]),up=o.useMemo(()=>Tt==="open"?os?Fc:e.tasks.filter(m=>!m.isArchived):Uc,[Uc,e.tasks,Fc,os,Tt]),mm=o.useMemo(()=>new Set(Uc.map(m=>m.id)),[Uc]),hm=o.useMemo(()=>Tt==="archived"?is:Tt==="deleted"?Go:fc?[...e.tasks,...is]:e.tasks,[is,Go,e.tasks,fc,Tt]),mc=o.useMemo(()=>{const m=new Map;for(const A of is)m.set(A.id,A);for(const A of Go)m.set(A.id,A);for(const A of e.tasks)m.set(A.id,A);return Array.from(m.values())},[is,Go,e.tasks]),zc=o.useMemo(()=>{const m=new Map;return mc.forEach(A=>m.set(A.id,A)),m},[mc]),pp=o.useMemo(()=>{const m=new Map;Dt.forEach(be=>{m.set(String(be.value),be.label)});const A=String(ut||"").trim(),B=String(rr||Wt||"").trim();return A&&B&&m.set(A,B),m},[Dt,rr,Wt,ut]),Ut=o.useMemo(()=>{const m=new Map;e.workspaceTaskRelationships.forEach(ct=>{if(ct.deletedAt||ct.kind!=="dependency")return;const Nr=m.get(ct.sourceTaskId)||[];Nr.push(ct.targetTaskId),m.set(ct.sourceTaskId,Nr)});const A=$Y(e.tasks,is),B=new Map(A.map(ct=>[ct.id,ct])),be=ct=>{const Nr=m.get(ct)||[];if(Nr.length===0)return"ready";let Wa=!1;for(const Gi of Nr){const Vi=B.get(Gi);if(!Vi||Po(Vi.status).value==="cancelled"){Wa=!0;continue}if(Po(Vi.status).value!=="done")return"blocked"}return Wa?"invalid":"ready"},De=A,Ot=A,xr=(ct,Nr)=>({progressPercent:ct>0?Math.round(Nr/ct*100):0,taskCount:ct,completedTaskCount:Nr}),Lr=ct=>{const Nr={task:0,"on-hold":0,"in-progress":0,review:0,done:0,cancelled:0};return ct.forEach(Wa=>{Nr[Po(Wa.status).value]+=1}),Nr},Ln=ct=>{const Nr=Lr([]);return ct.forEach(Wa=>{Object.entries(Wa.statusCounts||{}).forEach(([Gi,Vi])=>{Nr[Gi]+=Number(Vi)||0})}),Nr},fa=PX({taskScope:Tt,summaryCount:e.planningBootstrapTaskSummaries.length,loadingTasks:e.loadingTasks,activeTaskCount:e.tasks.length,archiveHydrated:e.archiveHydratedWorkspaceId===ht}),cl=new Map,vu=new Map,wu=new Map;fa?e.planningBootstrapTaskSummaries.forEach(ct=>{const Nr=(ct.tasks||[]).map(Wa=>({...Wa,prerequisiteTaskIds:m.get(Wa.id)||[],dependencyState:be(Wa.id)}));cl.set(ct.workstreamId,{...ct,tasks:Nr}),vu.set(ct.workstreamId,Nr),wu.set(ct.workstreamId,Lr(Nr))}):(De.forEach(ct=>{const Nr=String(ct.workstreamId||"").trim();if(!Nr)return;const Wa=cl.get(Nr)||{workstreamId:Nr,taskCount:0,completedTaskCount:0,tasks:[]};Wa.taskCount+=1,(ct.status==="done"||ct.status==="cancelled")&&(Wa.completedTaskCount+=1);const Gi=wu.get(Nr)||Lr([]);Gi[Po(ct.status).value]+=1,wu.set(Nr,Gi),cl.set(Nr,Wa)}),Ot.forEach(ct=>{const Nr=String(ct.workstreamId||"").trim();if(!Nr)return;const Wa=vu.get(Nr)||[];Wa.push({id:ct.id,referenceNumber:ct.referenceNumber??null,localReferenceNumber:ct.localReferenceNumber??null,referenceLabel:ct.referenceLabel,title:ct.title,createdAt:ct.createdAt,status:ct.status||null,priority:Number(ct.priority)||0,workstreamOrder:ct.workstreamOrder??null,prerequisiteTaskIds:m.get(ct.id)||[],dependencyState:be(ct.id),assignee:ct.assignee||null,attachmentCount:Array.isArray(ct.attachments)?ct.attachments.length:0,isArchived:!!ct.isArchived}),vu.set(Nr,Wa)}));const Ym=new Map,Zm=new Map,Jm=new Map,Hy=new Map,AT=ct=>{const Nr=cl.get(ct.id),Wa=vu.get(ct.id)||Nr?.tasks||[],Gi=xr(Nr?.taskCount||0,Nr?.completedTaskCount||0),Vi=FY({isArchived:!!ct.isArchived,tasks:Wa,dataReady:!fa}),Qm={id:ct.id,referenceNumber:ct.referenceNumber??null,title:ct.title,description:String(ct.description||"").trim()||void 0,ownerId:ct.ownerId?String(ct.ownerId):null,ownerLabel:ct.ownerId?pp.get(String(ct.ownerId))||String(ct.ownerId):null,icon:ct.icon??null,color:ct.color??null,...Gi,statusCounts:wu.get(ct.id)||Lr([]),initiativeId:ct.initiativeId||null,commentCount:Array.isArray(ct.comments)?ct.comments.length:0,comments:Array.isArray(ct.comments)?ct.comments:[],activity:Array.isArray(ct.activity)?ct.activity:[],entityEvents:Array.isArray(ct.entityEvents)?ct.entityEvents:[],attachmentCount:Array.isArray(ct.attachments)?ct.attachments.length:0,attachments:Array.isArray(ct.attachments)?ct.attachments:[],isArchived:!!ct.isArchived,archiveReady:Vi.archiveReady,archiveActiveTaskCount:Vi.activeTaskCount,tasks:Wa};if(Ym.set(ct.id,Wa.map(ll=>ll.id)),ct.initiativeId){Zm.set(ct.id,ct.initiativeId);const ll=Hy.get(ct.initiativeId)||[];ll.push(Qm),Hy.set(ct.initiativeId,ll)}return Qm},Gy=e.workstreams.map(AT),CT=Gy.filter(ct=>fg(Tt,!!ct.isArchived)),Vy=e.initiatives.map(ct=>{const Nr=Hy.get(ct.id)||[],Wa=Nr.filter(Zp=>fg(Tt,!!Zp.isArchived)),Gi=Nr.reduce((Zp,Ky)=>Zp+Ky.taskCount,0),Vi=Nr.reduce((Zp,Ky)=>Zp+Ky.completedTaskCount,0),Qm=xr(Gi,Vi),ll=UY({isArchived:!!ct.isArchived,workstreams:Nr,dataReady:!fa});return{id:ct.id,referenceNumber:ct.referenceNumber??null,title:ct.title,description:String(ct.description||"").trim()||void 0,ownerId:ct.ownerId?String(ct.ownerId):null,ownerLabel:ct.ownerId?pp.get(String(ct.ownerId))||String(ct.ownerId):null,icon:ct.icon??null,color:ct.color??null,...Qm,statusCounts:Ln(Nr),workstreamCount:Wa.length,workstreams:Wa,allWorkstreams:Nr,commentCount:Array.isArray(ct.comments)?ct.comments.length:0,comments:Array.isArray(ct.comments)?ct.comments:[],activity:Array.isArray(ct.activity)?ct.activity:[],entityEvents:Array.isArray(ct.entityEvents)?ct.entityEvents:[],attachmentCount:Array.isArray(ct.attachments)?ct.attachments.length:0,attachments:Array.isArray(ct.attachments)?ct.attachments:[],isArchived:!!ct.isArchived,archiveReady:ll.archiveReady,archiveActiveTaskCount:ll.activeTaskCount,archiveActiveWorkstreamCount:ll.activeWorkstreamCount}}),{initiatives:eb,standaloneWorkstreams:IT,initiativeById:_T,workstreamById:TT}=dY(Vy,CT,Tt),xT=Gy.filter(ct=>!ct.initiativeId);return eb.forEach(ct=>{Jm.set(ct.id,ct.workstreams.flatMap(Nr=>(Nr.tasks||[]).map(Wa=>Wa.id)))}),{initiatives:eb,standaloneWorkstreams:IT,allInitiatives:Vy,allStandaloneWorkstreams:xT,allInitiativeById:new Map(Vy.map(ct=>[ct.id,ct])),allWorkstreamById:new Map(Gy.map(ct=>[ct.id,ct])),workstreamTaskIds:Ym,workstreamInitiativeIds:Zm,initiativeTaskIds:Jm,workstreamById:TT,initiativeById:_T}},[is,ht,e.archiveHydratedWorkspaceId,pp,e.initiatives,e.loadingTasks,e.planningBootstrapTaskSummaries,e.workspaceTaskRelationships,e.tasks,e.workstreams,Tt]),gm=o.useMemo(()=>Ut.initiatives.map(m=>{const A=fs(m);return{value:m.id,label:A||m.title}}),[Ut.initiatives]),fp=o.useMemo(()=>{const m=(De,Ot)=>De.title.localeCompare(Ot.title,void 0,{sensitivity:"base"}),A=Array.from(Ut.allInitiativeById.values()).filter(De=>!De.isArchived).map(De=>({id:De.id,referenceLabel:fs(De)||De.id,title:De.title,icon:De.icon,color:De.color,meta:`${De.workstreamCount||0} workstream${De.workstreamCount===1?"":"s"}`})).sort(m),B=Array.from(Ut.allWorkstreamById.values()).filter(De=>!De.isArchived).map(De=>({id:De.id,referenceLabel:Eo(De)||De.id,title:De.title,icon:De.icon,color:De.color,meta:De.initiativeId?`In ${Ut.allInitiativeById.get(De.initiativeId)?.title||"another initiative"}`:"Standalone workstream"})).sort(m),be=mc.filter(De=>!De.isArchived&&!De.isDeleted).map(De=>({id:De.id,referenceLabel:hs(De)||De.id,title:De.title,meta:De.workstreamId?`In ${Ut.allWorkstreamById.get(De.workstreamId)?.title||"another workstream"}`:"Unassigned to a workstream"})).sort(m);return{initiatives:A,workstreams:B,tasks:be}},[mc,Ut.allInitiativeById,Ut.allWorkstreamById]),qd=o.useMemo(()=>{const A=(D?Ut.initiativeById.get(D)?.workstreams||[]:Ut.initiatives.flatMap(be=>be.workstreams)).map(be=>{const De=Eo(be);return{value:be.id,label:De||be.title}}),B=D?[]:Ut.standaloneWorkstreams.map(be=>{const De=Eo(be);return{value:be.id,label:De||be.title}});return[...A,...B]},[Ut.initiativeById,Ut.initiatives,Ut.standaloneWorkstreams,D]),Hc=o.useMemo(()=>Ct?new Set(Ut.workstreamTaskIds.get(Ct)||[]):D?new Set(Ut.initiativeTaskIds.get(D)||[]):null,[Ut.initiativeTaskIds,Ut.workstreamTaskIds,D,Ct]),ym=o.useMemo(()=>{if(!ya)return null;if(ya.type==="initiative"){const A=Ut.allInitiativeById.get(ya.id);return A?{type:"initiative",item:A}:null}const m=Ut.allWorkstreamById.get(ya.id);return m?{type:"workstream",item:m}:null},[ya,Ut.allInitiativeById,Ut.allWorkstreamById]),Yd=o.useMemo(()=>{if(!Aa)return null;const m=Ut.allWorkstreamById.get(Aa);return m?{type:"workstream",item:m}:null},[Aa,Ut.allWorkstreamById]),km=o.useMemo(()=>Ti?.mode==="create"?{kind:"editor",editor:Ti}:Yd?{kind:"detail",detail:Yd}:null,[Yd,Ti]),Gc=ya?Bs[`${ya.type}:${ya.id}`]:void 0,Ug=Aa?Bs[`workstream:${Aa}`]:void 0,mp=T_(ko,!!(ym||ja),ns,!!km,li),[hp,Zd]=o.useState(mp),zg=o.useMemo(()=>{if(!Rn.trim())return null;const m=Ut.allInitiativeById.get(Rn);return m||Zk(Ut.allInitiatives,Rn)},[Rn,Ut.allInitiativeById,Ut.allInitiatives]);o.useEffect(()=>{D&&!Ut.initiativeById.has(D)&&L(""),Ct&&!Ut.workstreamById.has(Ct)&&zt("")},[Ut.initiativeById,Ut.workstreamById,D,Ct]);const Ao=o.useMemo(()=>h==="schedule"?up:Uc,[h,Uc,up]),Vc=o.useMemo(()=>h!=="schedule"||!Mn?Ao:Ao.filter(m=>{if(m.status==="done"||m.status==="cancelled")return!1;const B=!!m.scheduledDate&&m.scheduledDate<en,be=!!m.dueDate&&m.dueDate<en;return B||be}),[h,Mn,Ao,en]),vm=o.useMemo(()=>PS(Vc,Hc),[Vc,Hc]),Vo=iI(e.deletedTasks,vm.map(m=>m.id),Tt==="deleted"),wm=o.useMemo(()=>PS(hm,Hc),[hm,Hc]),gp=o.useMemo(()=>Array.from(mm),[mm]),Hg=o.useCallback(m=>{rs(m);const A=bf(m);A&&na(`${A.getFullYear()}-${String(A.getMonth()+1).padStart(2,"0")}`)},[]),hc=o.useCallback(m=>{h==="schedule"&&yo(m)},[h]),bm=o.useCallback(m=>{if(Tt==="deleted"){const A=Ni.get(m);if(!A)return;Xt(A.id,A.taskId);return}Qt(m)},[Ni,Xt,Qt,Tt]),Jd=o.useCallback(m=>{if(Tt==="deleted"){const A=Ni.get(m);if(!A||!window.confirm("Permanently delete this task? This cannot be undone."))return;Mt(A.id);return}Bt(m)},[Ni,Bt,Mt,Tt]),gc=o.useMemo(()=>h!=="schedule"?[]:Ao.filter(m=>{if(m.status==="done"||m.status==="cancelled")return!1;const B=!!m.scheduledDate&&m.scheduledDate<en,be=!!m.dueDate&&m.dueDate<en;return B||be}),[h,Ao,en]),Qd=o.useMemo(()=>h!=="schedule"?0:Ao.filter(m=>m.status==="done"||m.status==="cancelled"?!1:!!m.scheduledDate&&m.scheduledDate<en).length,[h,Ao,en]),Hl=o.useMemo(()=>h!=="schedule"?0:Ao.filter(m=>m.status==="done"||m.status==="cancelled"?!1:!!m.dueDate&&m.dueDate<en).length,[h,Ao,en]),Gl=o.useMemo(()=>!Ba||Ba==="anonymous"?0:N.filter(m=>m.status==="done"||m.status==="cancelled"?!1:String(m.assignee||"").trim()===Ba).length,[Ba,N]),Kc=o.useMemo(()=>!Ba||Ba==="anonymous"?0:N.filter(m=>m.status==="done"||m.status==="cancelled"||String(m.assignee||"").trim()!==Ba?!1:!!m.dueDate&&m.dueDate<en).length,[Ba,N,en]),yc=o.useMemo(()=>h!=="schedule"?[]:Ao.filter(m=>m.status==="done"||m.status==="cancelled"?!1:!!m.scheduledDate&&m.scheduledDate<en),[h,Ao,en]),Mi=gc,[Di,Vl]=o.useState(!1),yp=()=>{Pr(()=>{An()||(f==="add"&&Sn.length>0&&ln(),as(!1),f==="add"&&_(),p("tasks"))})};o.useEffect(()=>{f!=="add"&&as(!1)},[f]);const qc=o.useCallback(async(m,A,B)=>{m.status===A&&!B?.allowSameStatus||await z(m,A)},[z]),kp=o.useCallback(async(m,A)=>{const B=zc.get(m);if(!B){dt("Task details are still loading.","info");return}await qc(B,A),await e.fetchPlanningEntities()},[qc,zc,e.fetchPlanningEntities,dt]),vp=o.useCallback(async(m,A)=>{await F(m,{assignee:A})!==!1&&await e.fetchPlanningEntities()},[F,e.fetchPlanningEntities]),Yc=o.useCallback(async m=>{const A=zc.get(m);return A?A.isArchived?!0:A.status!=="done"&&A.status!=="cancelled"?(dt("Only completed or cancelled tasks can be archived from Planning.","error"),!1):Nt(A):(dt("Task details are still loading.","info"),!1)},[Nt,zc,dt]),Gg=o.useCallback(async m=>{const A=await Yc(m);return A&&(await e.fetchPlanningEntities(),dt("Task archived","success")),A},[Yc,e.fetchPlanningEntities,dt]),wp=o.useCallback(async m=>{const A=Ut.allWorkstreamById.get(m);if(!A?.archiveReady)return dt("This workstream is no longer ready to archive.","error"),!1;try{return await l_({workstream:A,archiveTask:Yc,archiveWorkstream:e.archiveWorkstream})?(dt("Completed tasks and workstream archived","success"),!0):(dt("Workstream archive stopped safely. Resolve any remaining tasks and retry.","error"),!1)}catch(B){return dt(B instanceof Error?`Workstream archive stopped safely: ${B.message}`:"Workstream archive stopped safely. Retry to archive the remaining items.","error"),!1}},[Yc,Ut.allWorkstreamById,e.archiveWorkstream,dt]),Xd=o.useCallback(async m=>{const A=Ut.allInitiativeById.get(m);if(!A?.archiveReady)return dt("This initiative is no longer ready to archive.","error"),!1;try{return await zY({initiativeId:A.id,workstreams:A.allWorkstreams||A.workstreams,archiveTask:Yc,archiveWorkstream:e.archiveWorkstream,archiveInitiative:e.archiveInitiative})?(dt("Completed tasks, workstreams, and initiative archived","success"),!0):(dt("Initiative archive stopped safely. Resolve any remaining tasks and retry.","error"),!1)}catch(B){return dt(B instanceof Error?`Initiative archive stopped safely: ${B.message}`:"Initiative archive stopped safely. Retry to archive the remaining items.","error"),!1}},[Yc,Ut.allInitiativeById,e.archiveInitiative,e.archiveWorkstream,dt]),Sm=o.useCallback(async(m,A)=>{const B=m==="initiative"?Ut.allInitiativeById.get(A):Ut.allWorkstreamById.get(A);if(!B)return dt(`${m==="initiative"?"Initiative":"Workstream"} not found.`,"error"),!1;const be=d_({entityType:m,isArchived:B.isArchived,taskCount:B.taskCount,completedTaskCount:B.completedTaskCount,archiveReady:B.archiveReady,activeWorkstreamCount:B.archiveActiveWorkstreamCount});if(be.mode==="archived")return!0;if(be.mode==="ready")return m==="initiative"?Xd(A):wp(A);if(be.mode!=="empty")return dt(be.mode==="blocked"?`Archive unavailable while active ${be.remainingKind==="task"?"tasks":"workstreams"} remain.`:"Archive availability is still loading.","error"),!1;try{return m==="initiative"?await e.archiveInitiative(A):await e.archiveWorkstream(A),dt(`${m==="initiative"?"Initiative":"Workstream"} archived`,"success"),!0}catch(De){return dt(De instanceof Error?De.message:`Failed to archive ${m}.`,"error"),!1}},[Xd,wp,Ut.allInitiativeById,Ut.allWorkstreamById,e.archiveInitiative,e.archiveWorkstream,dt]),Am=o.useCallback(async(m,A)=>{try{return m==="initiative"?await e.unarchiveInitiative(A):await e.unarchiveWorkstream(A),dt(`${m==="initiative"?"Initiative":"Workstream"} unarchived`,"success"),!0}catch(B){return dt(B instanceof Error?B.message:`Failed to unarchive ${m}.`,"error"),!1}},[e.unarchiveInitiative,e.unarchiveWorkstream,dt]),Vg=o.useCallback((m,A)=>{_();const B=iY(m,A,{categories:g});B.category&&Ae(B.category),B.type&&Ne(B.type),typeof B.priority=="number"&&q(B.priority),typeof B.complexity=="number"&&K(B.complexity),B.assignee&&Q(B.assignee),B.status&&we(B.status),B.scheduledDate&&se(B.scheduledDate),p("add")},[_,g,Ae,Ne,q,K,we,Q,se,p]);Y.useEffect(()=>{E&&!E.includes("done")&&x(m=>[...m,"done"])},[]);const[Kg,bp]=o.useState(!1),[Li,$s]=o.useState(!1),[Oi,Bi]=o.useState(!1),Cm=o.useRef(!1),[qg,Kl]=o.useState(!1),[cs,Zc]=o.useState(!1),[eu,Fs]=o.useState(""),[Im,Sp]=o.useState(!1),[tu,Jc]=o.useState(!1),[Yg,ru]=o.useState("members"),[Co,au]=o.useState(null),[Ap,nu]=o.useState("unknown"),[_m,Cp]=o.useState(!1),[Zg,ql]=o.useState(null),[Jg,ro]=o.useState(null),[Qg,Tm]=o.useState(!1),[Ip,Xg]=o.useState([]),[ey,xm]=o.useState(null),[_p,Rm]=o.useState(""),[su,ty]=o.useState("member"),[Tp,jm]=o.useState("read-write"),[ry,Yl]=o.useState(!1),[ao,qa]=o.useState(null),[kc,ay]=o.useState(0),[ny,Pm]=o.useState(!1),[ou,sy]=o.useState([]),[oy,iy]=o.useState(!1),[cy,ly]=o.useState(1),[jn,xp]=o.useState(null),[Rp,un]=o.useState(!1),[vc,Qc]=o.useState(null),[Io,Wi]=o.useState(!1),[Xc,no]=o.useState(null),[el,tl]=o.useState(!1),[rl,_o]=o.useState(null),[Us,dy]=o.useState("month"),[$i,jp]=o.useState(""),[Pp,Ko]=o.useState(""),[ls,wc]=o.useState(null),[Em,Nm]=o.useState(!1),[Fi,Ui]=o.useState(!1),[Ep,so]=o.useState(null),[Mm,oo]=o.useState(null),Np=25,Mp=o.useRef(null),al=o.useRef(null),iu=o.useRef({billing:!1,teamManagement:!1}),nl=o.useRef(null);o.useEffect(()=>{nl.current=jn},[jn]),o.useEffect(()=>{if(!Li)return;const m=A=>{Mp.current?.contains(A.target)||$s(!1)};return document.addEventListener("mousedown",m),()=>document.removeEventListener("mousedown",m)},[Li]);const uy=nr==="cloud"&&Zr&&ir,bc=ir&&(nr==="cloud"||He),Dp=nr==="local"&&ir,Lp=yr?.phase==="ready"&&yr.snapshot?.state.ownershipMode==="server"?yr.snapshot.workspace?.runner?.checkpoint?.checkpoint.syncEnabled:null,Zl=typeof Lp=="boolean"?Lp:Ga,{showSyncStatusModal:Op,showSyncEnableWarning:Dm,workspaceSyncError:py,syncControlBusy:fy,openSyncStatusModal:Lm,closeSyncStatusModal:sl,handleWorkspaceSyncToggle:Om,cancelSyncEnableWarning:my,confirmSyncEnableWarning:hy}=dee({canManageWorkspaceSync:Dp,workspaceCloudSyncEnabled:Zl,saveWorkspaceCloudSyncSettings:Kr}),Jl=o.useMemo(()=>{const m=sr.find(be=>be.id===ht),A=String(m?.name||"").trim();if(A)return A;if(nr==="local"){const be=String(Ta||"").trim();if(be)return be}return String(ht||"").trim()||"Workspace"},[sr,ht,Ta,nr]),ol=R_(bc,Co),To=see(bc,Co,Ap),il=String(rr||"").trim(),io=String(oa||"").trim(),Sc=String(Wt||"").trim(),Ql=il||Sc,gy=Ql.length>0,Bm=Sc.length>0,yy=o.useMemo(()=>HK({workspaceName:Jl,workspaceId:ht,accountLabel:Ql||Sc,runtimeMode:nr}),[Sc,Ql,ht,Jl,nr]),Wm=(Ql||Sc||"").trim(),cu=ir&&Mr&&Wm.length>0?Wm.charAt(0).toUpperCase():"",Fm=io,ky=ir&&Mr&&Fm.length>0,Xl=String(Pp||io).trim(),Ac=String(jn?.planName||jn?.planId||"").trim(),vy=Ac.length>0,qo=String(jn?.workspaceId||ka||ht||"").trim(),Bp=nr==="cloud"?"CLOUD":"LOCAL",lu=e.config?.apiBaseUrl||"",Wp=o.useMemo(()=>wee(e.config?.cloudEnvironment,[String(e.config?.cloudBaseUrl||""),String(e.config?.cloudAuthBaseUrl||""),String(e.config?.apiBaseUrl||""),String(e.config?.baseUrl||"")]),[e.config?.cloudEnvironment,e.config?.cloudBaseUrl,e.config?.cloudAuthBaseUrl,e.config?.apiBaseUrl,e.config?.baseUrl]),du=He&&!Mr;o.useEffect(()=>{Oi&&!Cm.current&&(jp(il),Ko(io),wc(null),so(null),oo(null)),Cm.current=Oi},[io,il,Oi]);const zi=o.useCallback(async m=>{const A=String(m||"").trim();if(!(!A||!He))try{await fetch(or("/api/taskforce/auth/profile/avatar/discard"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:A})})}catch{}},[He,or]),wy=o.useCallback(()=>{const m=ls;Bi(!1),Kl(!1),so(null),oo(null),wc(null),Ko(io),m&&zi(m)},[io,zi,ls]),by=o.useCallback(async m=>{if(!m||!He)return!1;if(!m.type.startsWith("image/"))return so("Profile photo must be an image file."),oo(null),!1;Nm(!0),so(null),oo(null);try{const A=await WY(m,{maxBytes:kee});if(A.exceededLimit){const fa=m.type==="image/gif"?"Animated GIF profile photos must be 5 MB or smaller.":"Profile photo must be 5 MB or smaller.";throw new Error(fa)}const B=A.file,be=await fetch(or("/api/taskforce/auth/profile/avatar/init"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({originalName:B.name,mimeType:B.type,size:B.size})}),De=await be.json().catch(()=>({}));if(!be.ok||!De?.success||typeof De?.draftId!="string"||typeof De?.relativePath!="string")throw new Error(De?.error||"Failed to start avatar upload.");if(!(await fetch(or("/api/taskforce/auth/profile/avatar/upload"),{method:"POST",headers:{"Content-Type":B.type||"application/octet-stream","x-taskforce-avatar-draft-id":De.draftId},credentials:"include",body:B})).ok)throw new Error("Failed to upload avatar.");const xr=await fetch(or("/api/taskforce/auth/profile/avatar/finalize"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({draftId:De.draftId,relativePath:De.relativePath})}),Lr=await xr.json().catch(()=>({}));if(!xr.ok||!Lr?.success||typeof Lr?.draftId!="string")throw new Error(Lr?.error||"Failed to finalize avatar upload.");const Ln=ls;return wc(Lr.draftId),Ko(typeof Lr?.avatarUrl=="string"?Lr.avatarUrl:""),oo(null),Ln&&Ln!==Lr.draftId&&zi(Ln),!0}catch(A){return so(A instanceof Error?A.message:"Failed to upload profile photo."),!1}finally{Nm(!1)}},[He,zi,ls,or]),Sy=o.useCallback(()=>{if(!ls)return;const m=ls;wc(null),Ko(io),oo(null),so(null),zi(m)},[io,zi,ls]),Ay=o.useCallback(()=>{const m=ls;wc(null),Ko(""),oo(io?"Profile photo will be removed when you save.":null),so(null),m&&zi(m)},[io,zi,ls]),Cy=o.useCallback(async()=>{const m=$i.trim();if(!m){so("Display name is required."),oo(null);return}Ui(!0),so(null),oo(null);const A=await fr({displayName:m,avatarDraftId:ls,clearAvatar:!ls&&!Pp&&!!io});if(!A.success){so(A.error||"Failed to update profile."),Ui(!1);return}oo("Profile updated."),wc(null),Ko(""),Ui(!1),Kl(!1)},[io,ls,Pp,$i,fr]),xo=o.useCallback(()=>{const m={},A=String(qo||"").trim();A&&(m["x-taskforce-workspace-id"]=A);const B=Co||Ht;return(B==="owner"||B==="admin"||B==="member"||B==="read-only")&&(m["x-taskforce-workspace-role"]=B),m},[Ht,qo,Co]),Um=o.useCallback(m=>{const A=ir,B=m==="account_menu"&&bc;al.current=uf(),iu.current={billing:A,teamManagement:B},wr("account_surface_opened",{surface:m,expectsBilling:A,expectsTeamManagement:B}),!A&&!B&&(wr("account_surface_ready",{surface:m,durationMs:0,teamManagementVisible:!1,billingPlanId:null}),al.current=null)},[bc,ir]),ed=o.useCallback(m=>{const A=iu.current;if(A[m]=!1,A.billing||A.teamManagement)return;const B=al.current;B!==null&&(wr("account_surface_ready",{surface:Oi?"account_settings":Li?"account_menu":"closed",durationMs:Math.round(uf()-B),teamManagementVisible:To,billingPlanId:String(jn?.planId||"").trim()||null}),al.current=null)},[jn?.planId,To,Li,Oi]),ki=o.useCallback(async m=>{const A=or(DS);if(!ir)return xp(null),Qc(null),au(null),nu("unknown"),Cp(!1),ql(null),LS(A,{identityKey:ut}),ed("billing"),ed("teamManagement"),null;const B=uf();un(!0),Qc(null),Cp(bc),ql(null);try{const be=await _Y(A,{identityKey:ut,force:m?.force===!0}),De=be?.workspaceRole==="owner"||be?.workspaceRole==="admin"||be?.workspaceRole==="member"||be?.workspaceRole==="read-only"?be.workspaceRole:null,Ot=be?.teamPlanMode==="team"||be?.teamPlanMode==="personal"?be.teamPlanMode:"unknown";return xp(be),au(De),nu(Ot),ql(null),wr("account_profile_summary_resolved",{durationMs:Math.round(uf()-B),planId:String(be?.planId||"").trim()||null,gate:String(be?.gate||"").trim()||null,teamManagementAllowed:be?.teamManagementAllowed===!0}),be}catch(be){const De=be instanceof Error?be.message:"Failed to load account summary.",Ot=!!nl.current;return Qc(De),Ot?ql(null):(au(null),nu("unknown"),ql(De)),wr("account_profile_summary_failed",{durationMs:Math.round(uf()-B),error:De,preservedSummary:Ot}),nl.current}finally{un(!1),Cp(!1),ed("billing"),ed("teamManagement")}},[ut,bc,ir,ed,or]),zm=o.useCallback(m=>{xp(m);const A=m?.workspaceRole==="owner"||m?.workspaceRole==="admin"||m?.workspaceRole==="member"||m?.workspaceRole==="read-only"?m.workspaceRole:null,B=m?.teamPlanMode==="team"||m?.teamPlanMode==="personal"?m.teamPlanMode:"unknown";au(A),nu(B)},[]),$p=o.useMemo(()=>sv(jn).allowReturnToApp,[jn]),Fp=o.useCallback(async()=>{const m=new URLSearchParams;m.set("screen","plans"),m.set("interval",Us);const A=String(jn?.planId||"").trim(),B=String(jn?.planVersionId||"").trim();A&&m.set("planId",A),B&&m.set("planVersionId",B),n(`/?${m.toString()}`)},[jn?.planId,jn?.planVersionId,Us,n]),Hm=o.useCallback(async()=>{no(null),_o(null),Wi(!0);try{const m=await fetch(or("/api/taskforce/billing/portal-session"),{method:"POST",credentials:"include"}),A=await m.json().catch(()=>({}));if(!m.ok){no(String(A?.error||"Failed to create portal session."));return}const B=String(A?.url||"").trim();if(!B){no("Portal session did not return a redirect URL.");return}window.location.assign(B)}catch{no("Failed to open billing portal.")}finally{Wi(!1)}},[or]),Iy=o.useCallback(async()=>{no(null),_o(null),Wi(!0);try{const m=String(jn?.planVersionId||"").trim();if(!m){no("No active plan version is linked to this account.");return}const A=await fetch(or("/api/taskforce/billing/subscription"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({planVersionId:m,interval:Us})}),B=await A.json().catch(()=>({}));if(!A.ok){no(String(B?.error||"Failed to update subscription interval."));return}_o("Subscription updated."),LS(or(DS),{identityKey:ut}),await ki()}catch{no("Failed to update subscription interval.")}finally{Wi(!1)}},[jn?.planVersionId,ut,Us,ki,or]);o.useEffect(()=>{!ir||!Mr||ki()},[Mr,ir,ki]),o.useEffect(()=>{!Oi&&!Li||ki()},[ki,Li,Oi]);const td=o.useCallback(async()=>{if(ol){Tm(!0),ro(null);try{const m=await fetch("/api/taskforce/admin/users",{method:"GET",credentials:"include",headers:xo()}),A=await m.json().catch(()=>({}));if(!m.ok){ro(A?.error||"Failed to load workspace users.");return}const B=Array.isArray(A?.users)?A.users:[],be={owner:0,admin:1,member:2,"read-only":3},De=B.map(Ot=>({userId:String(Ot?.userId||""),email:String(Ot?.email||""),displayName:typeof Ot?.displayName=="string"?Ot.displayName:null,role:Ot?.role==="owner"||Ot?.role==="admin"||Ot?.role==="member"||Ot?.role==="read-only"?Ot.role:"member",permissionMode:Ot?.permissionMode==="read-only"?"read-only":"read-write",status:String(Ot?.status||"active"),disabled:Ot?.disabled===!0}));De.sort((Ot,xr)=>{const Lr=(be[Ot.role]??99)-(be[xr.role]??99);return Lr!==0?Lr:(Ot.displayName||Ot.email).localeCompare(xr.displayName||xr.email,void 0,{sensitivity:"base"})}),Xg(De)}catch{ro("Failed to load workspace users.")}finally{Tm(!1)}}},[ol,xo]),Cc=o.useCallback(async m=>{if(!ol)return;const A=Math.max(0,Math.floor(m));Pm(!0),ro(null);try{const B=A*Np,be=await fetch(`/api/taskforce/admin/workspace-audit-logs?limit=${Np}&offset=${B}`,{method:"GET",credentials:"include",headers:xo()}),De=await be.json().catch(()=>({}));if(!be.ok){ro(De?.error||"Failed to load workspace audit log.");return}const Ot=Array.isArray(De?.events)?De.events:[];sy(Ot.map(Lr=>({id:String(Lr?.id||""),action:String(Lr?.action||""),actorUserId:String(Lr?.actorUserId||""),actorRole:String(Lr?.actorRole||""),createdAt:String(Lr?.createdAt||Lr?.ts||"")}))),ay(A);const xr=Math.max(1,Number(De?.pages||1));ly(xr),iy(A+1<xr)}catch{ro("Failed to load workspace audit log.")}finally{Pm(!1)}},[ol,xo]),uu=o.useCallback(async()=>{await Promise.all([td(),Cc(kc)])},[td,Cc,kc]),Up=o.useCallback((m="login")=>{const A=`${s.pathname}${s.search}${s.hash}`,B=!A||A==="/login"||!A.startsWith("/")?"/":A;$s(!1),Bi(!1),sl(),n(`/login?mode=${m}&next=${encodeURIComponent(B)}`)},[sl,s.hash,s.pathname,s.search,n]),rd=o.useCallback(m=>{$s(!1),Sp(!1);const A=new URLSearchParams({step:"workspace"});m?.intent==="create-workspace"&&A.set("intent","create-workspace"),n(`/setup?${A.toString()}`,{replace:!0})},[n]),pu=o.useCallback(async()=>{if(el)return;if(tl(!0),!ir){try{d()}finally{tl(!1)}return}const m=nl.current;if(m&&!sv(m).allowReturnToApp){tl(!1);return}d(),(async()=>{try{const A=await e.continueAfterCommercialOnboarding();if(!A.success){dt(A.error||"Unable to finish onboarding.","error"),A.destination==="login"&&n("/login",{replace:!0});return}A.destination==="setup"&&rd()}finally{tl(!1)}})()},[nl,d,ir,n,rd,el,e,dt]),_y=o.useCallback(()=>{if(l){pu();return}Pr(()=>{hi(),b("tasks"),In(!1),Jt(null),xn(null),di(null),as(!1),f==="add"&&_(),p("tasks"),(s.pathname!=="/"||s.search)&&n("/")})},[f,hi,Pr,pu,l,s.pathname,s.search,n,_,p,b]),Gm=o.useCallback(m=>{Qf(m),Xr("open"),Fl(!1),b("tasks"),l&&d()},[d,l,b,Fl,Xr,Qf]),Vm=o.useCallback(async m=>{if(!(!m||cs)){if(Is&&!_i.current){Tn(()=>()=>{Vm(m)});return}Fs(""),Zc(!0);try{const A=await wa(m);if(!A.success){if(A.code==="WORKSPACE_NOT_FOUND"||A.code==="WORKSPACE_ID_REQUIRED"){rd();return}Fs(A.error||"Failed to switch workspace.");return}await je(!0),$s(!1)}finally{Zc(!1)}}},[wa,cs,je,rd,Is]),fw=o.useCallback(async()=>{$s(!1),Jc(!0),ru("members"),((await ki())?.teamManagementAllowed??To)&&(await td(),await Cc(0))},[To,ki,Cc,td]),I=o.useCallback(async(m,A)=>{ro(null),xm(m);try{const B=await A(),be=await B.json().catch(()=>({}));if(!B.ok){ro(be?.error||"Team management action failed.");return}await uu()}catch{ro("Team management action failed.")}finally{xm(null)}},[uu]),X=o.useCallback(async()=>{const m=_p.trim();if(m){Yl(!0),ro(null),qa(null);try{const A=await fetch("/api/taskforce/admin/users/invite",{method:"POST",headers:{"Content-Type":"application/json",...xo()},credentials:"include",body:JSON.stringify({workspaceId:qo,email:m,role:su,permissionMode:su==="member"?Tp:"read-write"})}),B=await A.json().catch(()=>({}));if(!A.ok){ro(B?.error||"Failed to send invite.");return}Rm(""),B?.inviteEmailSent===!1?qa(`Invite created, but email delivery failed${B?.inviteEmailError?`: ${String(B.inviteEmailError)}`:"."}`):qa("Invite sent."),await uu()}catch{ro("Failed to send invite.")}finally{Yl(!1)}}},[ht,uu,xo,_p,Tp,su]),re=o.useMemo(()=>ot.trim().length>0,[ot]),J=o.useMemo(()=>Ip.filter(m=>m.status==="invited"),[Ip]),Fe=o.useMemo(()=>{const m=Ve.length!==g.length,A=It.length!==kt.length,B=$t.length!==xe.length,be=E.length!==rc.length,De=qt.length!==Dt.length,Ot=os!==null,xr=D.length>0,Lr=Ct.length>0;return m||A||B||be||De||Ot||xr||Lr},[g.length,kt.length,Dt.length,qt.length,Ve.length,$t.length,E.length,It.length,xe.length,D,Ct,os]),et=Cr,tt=o.useMemo(()=>BX(et),[et]);o.useLayoutEffect(()=>{if(!to&&f!=="add")return;const m=()=>{const be=zn.current,De=be?Math.ceil(be.getBoundingClientRect().bottom):Ik;Qs(Math.max(Ik,De))};m(),window.addEventListener("resize",m);const A=zn.current,B=typeof ResizeObserver<"u"?new ResizeObserver(m):null;return B&&A&&B.observe(A),()=>{window.removeEventListener("resize",m),B?.disconnect()}},[f,to]),o.useEffect(()=>{$l||uc(!1)},[$l]);const Gt=tt.moduleId==="tasks"&&Fe,cr=re||Fe,Dr=Tt==="archived"?is.length:Tt==="deleted"?Go.length:N.length,Wr=Tt==="archived"?Ul.length:Tt==="deleted"?Kd.length:Fc.length,Er=cr?`${Wr}/${Dr}`:`${Dr}`,Ua=cr?`${Tt.charAt(0).toUpperCase()+Tt.slice(1)} tasks matching current filters`:Tt==="deleted"?"Trash tasks — automatically deleted after 90 days":`${Tt.charAt(0).toUpperCase()+Tt.slice(1)} tasks`,Rs=nr==="local"&&ir,gn=o.useCallback(m=>{if(!m)return"Never";const A=new Date(m);return Number.isNaN(A.getTime())?"Never":A.toLocaleString()},[]),zs=o.useMemo(()=>gn(Zt),[gn,Zt]);o.useMemo(()=>gn(Sr),[gn,Sr]),o.useMemo(()=>gn(va),[gn,va]);const zp=py||ma||Ar||"None",Yo=mt(),Zo=yr?.snapshot?.permits.recoveryObligations||0,Km=o.useMemo(()=>zq({runtimeMode:nr,isAuthenticated:ir,workspaceSyncStatus:Na,workspaceCloudSyncEnabled:Ga,workspaceSyncSummary:ta,workspaceSyncRecommendedAction:ua,workspaceSyncError:zp,coordinatorRecoveryObligations:Zo,pushBlockedReason:Yo.pushBlockedReason||null,pullBlockedReason:Yo.pullBlockedReason||null,retryBlockedReason:Yo.retryBlockedReason||null}),[nr,ir,Na,Ga,ta,ua,zp,Zo,Yo.pushBlockedReason,Yo.pullBlockedReason,Yo.retryBlockedReason]),Hn=o.useMemo(()=>Fq(yr),[yr]),Hi=Hn?.header||Km,Ty=Hn?Hn.pendingLocalChanges:br,P_=Hn?Hn.lastPullAt:Sr,E_=Hn?Hn.lastPushAt:va,N_=Hn?Hn.lastSyncedAt:Zt,mw=gn(P_),hw=gn(E_),gw=gn(N_),yw=Hn?Hn.busy:Qr,xy=yr?.snapshot?.state.ownershipMode||null,Hp=xy==="server"||xy==="browser-gateway"?xy:null,[Ry,kw]=o.useState(!1),M_=yr?.phase!=="ready"||!yr.snapshot||yr.snapshot.state.transitionState!=="idle"||yr.snapshot.permits.active>0||Zo>0,D_=o.useCallback(async()=>{if(!(!Hp||Ry)){kw(!0);try{const m=Hp==="server"?"browser-gateway":"server";await Gr(m),dt(m==="server"?"The local Taskforce server now owns background synchronization.":"This browser now owns background synchronization.","success")}catch(m){dt(m instanceof Error&&m.message.trim()?m.message:"Sync ownership could not be transferred.","error")}finally{kw(!1)}}},[Hp,Ry,dt,Gr]),vw=Hi.lastError,[Gp,ww]=o.useState(Hi.status),L_=o.useMemo(()=>Hn?.diagnostics||wY({...Yo,coordinatorRecoveryObligations:Zo}),[Hn,Yo,Zo]),{syncRecentEvents:ad,syncRecentEventsLoading:bw,syncRecentEventsError:Sw,syncEventsListRef:O_,loadRecentSyncEvents:B_}=oee({isOpen:Op,workspaceId:ht,refreshKeys:[va,Sr,Ya,Na]}),Aw=Hi.actionable&&Na==="syncing"&&Hr==="active"&&Ty===0;o.useEffect(()=>{if(!Aw){ww(Hi.status);return}const m=window.setTimeout(()=>{ww(Hi.status)},1200);return()=>window.clearTimeout(m)},[Hi.status,Aw]);const W_=o.useMemo(()=>bY({syncRecentEvents:ad,syncRecentEventsError:Sw,syncRecentEventsLoading:bw}),[ad,Sw,bw]),Cw=o.useMemo(()=>SY(ad),[ad]),$_=o.useMemo(()=>AY(ad),[ad]),Iw=o.useMemo(()=>n_(Gp),[Gp]),Vp=o.useMemo(()=>vY(Gp,Zl),[Zl,Gp]),{workspaceSyncRepairBusy:jy,workspaceSyncRepairQueued:F_,workspaceSyncCopied:U_,handleCopySyncDetails:z_,handleQueueOrRunRepairSync:H_}=lee({currentWorkspaceId:ht,syncStatusLabel:Iw.label,workspaceSyncSummary:Hi.summary,workspaceSyncRecommendedAction:Hi.recommendedAction,formattedLastSyncTime:gw,formattedLastPullTime:mw,formattedLastPushTime:hw,workspaceSyncDiagnostics:Yo,workspaceSyncPendingChanges:Ty,syncLastError:vw,workspaceSyncPhase:Hr,referenceMismatchCount:Cw,syncRecentEvents:ad,loadRecentSyncEvents:B_,pushNotice:dt,resetWorkspaceSyncCursorAndPull:it,workspaceSyncBusy:yw,durableRepairQueueAvailable:Hp==="server"}),G_=Hn?Hn.repairBusy:jy,V_=o.useMemo(()=>Hn?.stage||s_(Hr,jy,Qr),[Hn,Qr,Hr,jy]),_w=o.useMemo(()=>bf(ts)||new Date,[ts]),nd=o.useMemo(()=>mv(_w,tr),[_w,tr]),Ic=o.useMemo(()=>{const m={mon:"",tue:"",wed:"",thu:"",fri:"",sat:"",sun:""};return JS.forEach(A=>{const B=eee(A,tr);m[A]=bd(x_(nd,B))}),m},[nd,tr]),Tw=o.useCallback(m=>{const A=bf(m);if(!A)return Ic.mon;const B=A.getDay();return Ic[B===1?"mon":B===2?"tue":B===3?"wed":B===4?"thu":B===5?"fri":B===6?Sa?"sat":"fri":Sa?"sun":"fri"]||Ic.mon},[Ic,Sa]),K_=o.useCallback(async()=>{if(!(Di||Mi.length===0)){Vl(!0);try{for(const m of Mi){const A=m.scheduledDate||m.dueDate||en,B=Tw(A);await F(m.id,{scheduledDate:B,scheduledWeekKey:tee(B),orderInDay:null})}await je(!0)}finally{Vl(!1)}}},[Di,Mi,en,Tw,F,je]),q_=o.useCallback(async()=>{if(!(Di||gc.length===0)){Vl(!0);try{for(const m of gc)await F(m.id,{scheduledDate:null,scheduledWeekKey:null,orderInDay:null});await je(!0)}finally{Vl(!1)}}},[Di,gc,F,je]),Y_=o.useMemo(()=>ug(nd,{month:"short",day:"numeric",year:"numeric"},bs),[nd,bs]),xw=o.useMemo(()=>{const B=(Sa?tr==="sunday"?["sun","mon","tue","wed","thu","fri","sat"]:JS:["mon","tue","wed","thu","fri"]).map(De=>{const Ot=bf(Ic[De])||nd,xr=Ic[De],Lr=De==="sat"||De==="sun";return{value:De,label:`${XX[De]} ${ug(Ot,{month:"short",day:"numeric"},bs)}`,color:Lr?"#1e3a8a":"#3b82f6",icon:"Calendar",date:xr,isPast:xr<en,isSelected:xr===ts,isWeekend:Lr}}),be=yc.length>0;return[...aa?[{value:"backlog",label:"Backlog",color:"#64748b",icon:"Inbox"}]:[],...be?[{value:"expired",label:"Expired",color:"#ef4444",icon:"AlertTriangle"}]:[],...B]},[Sa,aa,Ic,nd,yc.length,en,ts,tr,bs]),Rw=o.useMemo(()=>{switch(h){case"category":return g;case"type":return(kt||[]).map(m=>({...m,icon:m.icon||rg[m.value]?.icon,color:m.color||rg[m.value]?.color}));case"priority":return xe;case"complexity":return[{value:1,label:"Tiny",icon:"Gauge",color:"#10b981"},{value:2,label:"Low",icon:"Gauge",color:"#14b8a6"},{value:3,label:"Medium",icon:"Gauge",color:"#3b82f6"},{value:4,label:"High",icon:"Gauge",color:"#8b5cf6"},{value:5,label:"Epic",icon:"Gauge",color:"#d946ef"}];case"assignee":return Dt.map(m=>({value:m.value,label:m.label,icon:m.icon==="HelpCircle"?"Circle":m.icon,color:m.color}));case"status":return[...rc.filter(m=>m.value!=="done"&&m.value!=="cancelled"),{value:"completed",label:"Completed",icon:Po("done").icon,color:Po("done").color}];case"schedule":return xw;default:return g}},[h,g,kt,xe,Dt,xw]),Z_=a.jsxs("div",{className:lr.accountMenuWrap,ref:Mp,children:[a.jsx("button",{className:`tf-control-icon ${lr.avatarBtn}`,onClick:()=>{$s(m=>{const A=!m;return A?Um("account_menu"):(al.current=null,iu.current={billing:!1,teamManagement:!1}),A})},title:ir?"Account":"Account (Not signed in)","aria-label":ir?"Account":"Account (Not signed in)","aria-haspopup":"menu","aria-expanded":Li,children:a.jsx("span",{className:lr.avatarBadge,"aria-hidden":"true",children:ky?a.jsx("img",{src:Fm,alt:"",className:lr.avatarImage}):cu||a.jsx(Du,{size:14,className:lr.avatarIcon})})}),Li&&a.jsxs("div",{className:lr.accountMenu,role:"menu","aria-label":"Account menu",children:[a.jsxs("div",{className:lr.accountMenuSection,children:[a.jsx("div",{className:lr.accountMenuSectionLabel,children:"Account"}),a.jsx("div",{className:lr.accountMenuHint,children:du?"Checking sign-in status...":ir?a.jsx(a.Fragment,{children:gy?a.jsx(a.Fragment,{children:a.jsxs("span",{className:lr.accountIdentityBlock,children:[a.jsx("span",{className:lr.accountIdentityEmail,children:Ql}),Bm&&il&&a.jsxs("span",{className:lr.accountIdentityMetaLine,children:[a.jsx("span",{className:lr.accountIdentityMetaLabel,children:"Email"}),a.jsx("span",{className:lr.accountIdentityMetaValue,children:Sc})]}),Rp?a.jsxs("span",{className:lr.accountIdentityMetaLine,children:[a.jsx("span",{className:lr.accountIdentityMetaLabel,children:"Subscription"}),a.jsx("span",{className:lr.accountIdentityMetaValue,children:"Loading…"})]}):vy?a.jsxs("button",{"aria-label":`Subscription ${Ac}`,className:`${lr.accountIdentityMetaLine} ${lr.accountIdentityMetaAction}`,onClick:()=>{$s(!1),c()},type:"button",children:[a.jsx("span",{className:lr.accountIdentityMetaLabel,children:"Subscription"}),a.jsx("span",{className:lr.accountIdentityMetaValue,children:Ac})]}):vc?a.jsxs("span",{className:lr.accountIdentityMetaLine,children:[a.jsx("span",{className:lr.accountIdentityMetaLabel,children:"Subscription"}),a.jsx("span",{className:lr.accountIdentityMetaValue,children:"Unavailable"})]}):null,a.jsxs("span",{className:lr.accountIdentityMetaLine,children:[a.jsx("span",{className:lr.accountIdentityMetaLabel,children:"Runtime"}),a.jsx("span",{className:lr.accountIdentityMetaValue,children:Bp})]}),a.jsxs("span",{className:lr.accountIdentityMetaLine,children:[a.jsx("span",{className:lr.accountIdentityMetaLabel,children:"Environment"}),a.jsx("span",{className:lr.accountIdentityMetaValue,children:Wp})]})]})}):"Signed in"}):"Not signed in"})]}),uy&&a.jsxs("div",{className:lr.accountMenuSection,children:[a.jsx("div",{className:lr.accountMenuSectionLabel,children:"Workspaces (Owned + Invited)"}),sr.length===0&&a.jsx("div",{className:lr.accountMenuHint,children:"No workspaces found for this account yet."}),sr.map(m=>a.jsxs("button",{className:`${lr.accountMenuItem} ${m.id===ht?lr.accountMenuItemActive:""}`,onClick:()=>Vm(m.id),role:"menuitem",disabled:cs||m.id===ht,title:m.description||m.name,children:[a.jsx(Qi,{size:15}),a.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:"2px"},children:[a.jsx("span",{children:m.name}),a.jsx("span",{className:lr.accountMenuMeta,children:m.role})]})]},m.id)),a.jsxs("button",{className:lr.accountMenuItem,onClick:()=>{Fs(""),Sp(!0),$s(!1)},role:"menuitem",disabled:cs,children:[a.jsx(ri,{size:15}),"Create Workspace"]}),eu&&a.jsx("div",{className:lr.accountMenuError,children:eu})]}),_m?a.jsx("div",{className:lr.accountMenuHint,children:"Resolving team management access..."}):To?a.jsxs("button",{className:lr.accountMenuItem,onClick:()=>{fw()},role:"menuitem",children:[a.jsx(Mh,{size:15}),"Team Management"]}):Zg?a.jsx("div",{className:lr.accountMenuHint,children:"Team Management unavailable right now."}):null,ir&&a.jsxs("button",{className:lr.accountMenuItem,onClick:()=>{$s(!1),Um("account_settings"),Bi(!0)},role:"menuitem",children:[a.jsx(Nf,{size:15}),"Account Settings"]}),a.jsxs("button",{className:lr.accountMenuItem,onClick:()=>{$s(!1),bp(!0)},role:"menuitem",children:[a.jsx(Td,{size:15}),"Help & Support"]}),nr==="local"&&!ir&&!du&&a.jsxs("button",{className:lr.accountMenuItem,onClick:()=>{Up("login")},role:"menuitem",children:[a.jsx(Du,{size:15}),"Sign In / Register"]}),ir&&a.jsxs("button",{className:lr.accountMenuItem,onClick:async()=>{$s(!1),await Tr(),nr==="cloud"&&n("/login",{replace:!0})},role:"menuitem",children:[a.jsx(y0,{size:15}),"Sign Out"]})]})]}),jw=o.useCallback(()=>{S(m=>m==="show"?"collapse":m==="collapse"?"hide":"show")},[S]),Pw=o.useCallback(()=>{_(),b("tasks"),p("add")},[_,p,b]),J_=o.useCallback(m=>{const A=e.workstreams.find(B=>B.id===m);_(),Me(Eo(A)||m),b("tasks"),p("add")},[e.workstreams,_,p,b,Me]),Ew=o.useCallback(m=>{Xs.current=!1,xi(!1),di(m),ci(!1),Fo(null),vo(!1),oc(""),ic(""),cc(""),Al(null),Cl(null);const A=m.entityType==="workstream"&&D&&Ut.initiativeById.get(D)||null;ui(A?fs(A):""),xn(null)},[Ut.initiativeById,D]),Nw=o.useCallback((m,A)=>{Xs.current=!1,xi(!1),Fo(m),vo(!1),oc(""),ic(""),cc(""),Al(null),Cl(null);const B=m.entityType==="workstream"&&((A?Ut.initiativeById.get(A):null)||D&&Ut.initiativeById.get(D))||null;ui(B?fs(B):""),xn(null)},[Ut.initiativeById,D]),Py=o.useCallback(()=>{Xs.current=!1,xi(!1),di(null),oc(""),ic(""),cc(""),Al(null),Cl(null),ui("")},[]),Ey=o.useCallback(()=>{Xs.current=!1,xi(!1),Fo(null),oc(""),ic(""),cc(""),Al(null),Cl(null),ui("")},[]),Q_=o.useCallback(async()=>{const m=Ti||ja;if(!m||Xs.current)return;const A=Ld.trim();if(!A)return;Xs.current=!0,xi(!0);const B=!!Ti,be=Yu.trim()||null;try{if(m.entityType==="initiative")if(m.mode==="edit")await e.updateInitiative(m.targetId,{title:A,description:Sl.trim()||null}),Jt({type:"initiative",id:m.targetId}),dt("Initiative updated","success");else{const De=await e.createInitiative({title:A,description:Sl.trim()||null,ownerId:be,...Lc||Oc?{icon:Lc,color:Oc}:{}});Jt({type:"initiative",id:De.id}),xn(null),dt("Initiative created","success")}else{const De=jX(Ut.allInitiatives,m.mode==="create"?m.initiativeId:null,Rn);if(De.invalid){dt("Initiative not found by that reference.","error");return}const Ot={title:A,description:Sl.trim()||null,initiativeId:De.initiativeId,...m.mode==="create"?{ownerId:be}:{}};if(m.mode==="edit")await e.updateWorkstream(m.targetId,Ot),B?xn(m.targetId):(Jt({type:"workstream",id:m.targetId}),xn(null)),dt("Workstream updated","success");else{const xr=await e.createWorkstream({...Ot,...Lc||Oc?{icon:Lc,color:Oc}:{}});B?xn(xr.id):(Jt({type:"workstream",id:xr.id}),xn(null)),dt("Workstream created","success")}}B?Ey():Py()}catch(De){dt(De instanceof Error?De.message:"Failed to save planning item.","error")}finally{Xs.current=!1,xi(!1)}},[Py,Ey,Sl,Rn,Lc,Oc,Yu,Ld,ja,Ti,Ut.allInitiatives,e,dt]),X_=o.useCallback(m=>{Oe(A=>{const B=new Set(A);return B.has(m)?B.delete(m):B.add(m),B})},[]),eT=o.useCallback(m=>{L(A=>A===m?"":m),zt("")},[]),tT=o.useCallback((m,A)=>{zt(B=>{const be=B===m?"":m;return L(be&&A||""),be})},[]),Kp=o.useCallback(m=>{di(null),Fo(null),ci(!1),vo(!1),Jt(m?{type:"initiative",id:m}:null),xn(null)},[]),qp=o.useCallback(m=>{di(null),Fo(null),ci(!1),vo(!1),Jt(m?{type:"workstream",id:m}:null),xn(null)},[]),rT=o.useCallback(m=>{Fo(null),vo(!1),xn(m)},[]),Mw=o.useCallback(m=>{if(m.kind==="initiative"||m.kind==="workstream"){const be=m.kind==="initiative"?e.initiatives.find(De=>De.referenceNumber===m.referenceNumber):e.workstreams.find(De=>De.referenceNumber===m.referenceNumber);if(!be){dt(`${m.token} could not be found.`,"error");return}So(()=>{b("planning"),In(!0),m.kind==="initiative"?Kp(be.id):qp(be.id)});return}const A=String(ht||"default").trim()||"default",B=be=>{Ff(be,{ownerType:"task",ownerId:M,ownerReferenceLabel:hs(ra),workspaceId:A})};cI(m,{workspaceId:A,headers:dc}).then(B).catch(()=>{dt(`${m.token} could not be opened.`,"error")})},[ra,ht,M,So,Kp,qp,e.initiatives,e.workstreams,dt,b,dc]),Dw=o.useMemo(()=>({...Nn,entityReferences:{resolve:_A,activate:Mw}}),[Mw,Nn]);o.useEffect(()=>{const m=String(i.get(wi.initiative)||"").trim(),A=String(i.get(wi.workstream)||"").trim(),B=String(i.get(wi.document)||"").trim(),be=String(i.get(wi.image)||"").trim(),De=m?`initiative:${m}`:A?`workstream:${A}`:B?`document:${B}`:be?`image:${be}`:"";if(!De||El.current===De)return;if(m||A){const Lr=m?e.initiatives.find(Ln=>Ln.id===m):e.workstreams.find(Ln=>Ln.id===A);if(!Lr)return;El.current=De,So(()=>{b("planning"),In(!0),m?Kp(Lr.id):qp(Lr.id)});return}if(B){if(!Ei)return;El.current=De,So(()=>{Rl(null),Wc(B),b("docs")});return}if(!$c)return;El.current=De;const Ot=String(ht||"default").trim()||"default",xr=new URLSearchParams({workspaceId:Ot});fetch(`/api/taskforce/annotated-attachments/images/${encodeURIComponent(be)}?${xr.toString()}`,{credentials:"include",headers:dc}).then(async Lr=>{if(!Lr.ok)throw new Error("Image not found");const Ln=await Lr.json();if(!Ln.target?.assetId||!Ln.target.path)throw new Error("Image target is unavailable");So(()=>{const fa=Ln.target;eo.current=fa,fi.current=null,pi(fa),lc(null),ji(cl=>cl+1),b("annotate")})}).catch(()=>{dt(`Image ${be} could not be opened.`,"error")})},[$c,ht,Ei,So,Kp,qp,e.initiatives,e.workstreams,dt,i,b,dc]);const fu=o.useCallback(async m=>{const A=`${m.type}:${m.id}`;xs(B=>({...B,[A]:{status:"loading",error:null}}));try{await e.fetchPlanningEntityDetail(m.type,m.id),xs(B=>({...B,[A]:{status:"ready",error:null}}))}catch(B){xs(be=>({...be,[A]:{status:"error",error:B instanceof Error?B.message:"Failed to load the latest planning details."}}))}},[e.fetchPlanningEntityDetail]);o.useEffect(()=>{const m=new Map;if(ya?.id&&m.set(`${ya.type}:${ya.id}`,ya),Aa&&m.set(`workstream:${Aa}`,{type:"workstream",id:Aa}),m.size!==0)for(const A of m.values())fu(A)},[fu,ya?.id,ya?.type,Aa]);const Ny=o.useCallback((m,A)=>{if(m==="workstream"&&A){Nw({mode:"create",entityType:"workstream",initiativeId:A},A);return}if(Ew({mode:"create",entityType:m}),m==="workstream"){const B=(A?Ut.initiativeById.get(A):null)||(D?Ut.initiativeById.get(D):null)||null;ui(B?fs(B):"")}},[Ew,Nw,Ut.initiativeById,D]),Lw=o.useCallback((m,A)=>{if(Xs.current=!1,xi(!1),m==="initiative"){const B=Ut.allInitiativeById.get(A);if(!B)return;Fo(null),di({mode:"edit",entityType:"initiative",targetId:A}),oc(B.title),ic(B.description||""),cc(B.ownerId?String(B.ownerId):""),ui("");return}else{const B=Ut.allWorkstreamById.get(A);if(!B)return;const be=Aa===A;be?(di(null),Fo({mode:"edit",entityType:"workstream",targetId:A})):(Fo(null),di({mode:"edit",entityType:"workstream",targetId:A})),oc(B.title),ic(B.description||""),cc(B.ownerId?String(B.ownerId):"");const De=B.initiativeId&&Ut.allInitiativeById.get(B.initiativeId)||null;if(ui(De?fs(De):""),be)return}xn(null)},[Aa,Ut.allInitiativeById,Ut.allWorkstreamById]),My=o.useCallback(async(m,A,B)=>{const be=B.trim()||null;try{m==="initiative"?await e.updateInitiative(A,{ownerId:be}):await e.updateWorkstream(A,{ownerId:be}),dt(`${m==="initiative"?"Initiative":"Workstream"} owner updated`,"success")}catch(De){throw dt(De instanceof Error?De.message:"Failed to update owner.","error"),De}},[e,dt]),Dy=o.useCallback(async(m,A,B)=>{try{await e.updatePlanningIdentity(m,A,B)}catch(be){throw dt(be instanceof Error?be.message:"Failed to update visual identity.","error"),be}},[e.updatePlanningIdentity,dt]),mu=o.useCallback(async(m,A)=>{const B=e.workstreams.find(xr=>xr.id===m);if(!B)return dt("Workstream not found.","error"),!1;const be=typeof A=="string"?A.trim():A===null?"":Rn.trim(),De=be.length===0?null:Zk(Ut.allInitiatives,be);if(be.length>0&&!De)return dt("Initiative not found by that reference.","error"),!1;const Ot=De?.id||null;if((B.initiativeId||null)===Ot)return dt(Ot?"Workstream already belongs to that initiative.":"Workstream is already standalone.","info"),!1;try{return await e.updateWorkstream(m,{initiativeId:Ot}),ui(De?fs(De):""),dt(Ot?"Initiative set":"Initiative removed","success"),!0}catch{return dt("Failed to set initiative.","error"),!1}},[Rn,Ut.allInitiatives,e,dt]),hu=o.useCallback(async(m,A)=>{const B=zc.get(m);if(!B)return dt("Task not found.","error"),!1;const be=A||null;if(Ut.initiativeById.has(m)||Ut.workstreamById.has(m))return dt("Only execution tasks can be moved into workstreams.","error"),!1;if(be&&!Ut.workstreamById.has(be))return dt("Workstream not found.","error"),!1;if((B.workstreamId||null)===be)return dt(be?"Task already belongs to that workstream.":"Task is already standalone.","info"),!1;try{return await e.handleUpdateTask(m,{workstreamId:be})===!1?!1:(await e.fetchPlanningEntities(),dt(be?"Workstream set":"Workstream removed","success"),!0)}catch{return dt("Failed to set workstream.","error"),!1}},[zc,Ut.initiativeById,Ut.workstreamById,e,dt]),Ly=o.useCallback(async(m,A)=>{const B=A.trim();if(!B)return dt("Enter a task reference.","error"),!1;const be=Ig(B),De=mc.find(Ot=>Ot.id===B||hs(Ot)===B||be!==null&&Ot.referenceNumber===be);return De?hu(De.id,m):(dt("Task not found by that reference.","error"),!1)},[hu,mc,dt]),Oy=o.useCallback(async(m,A)=>{const B=A.trim();if(!B)return dt("Enter a workstream reference.","error"),!1;const be=Ut.allInitiativeById.get(m);if(!be)return dt("Initiative not found.","error"),!1;const De=VC(B),Ot=e.workstreams.find(xr=>xr.id===B||Eo(xr)===B||De!==null&&xr.referenceNumber===De);return Ot?mu(Ot.id,fs(be)):(dt("Workstream not found by that reference.","error"),!1)},[mu,Ut.allInitiativeById,e.workstreams,dt]),gu=o.useCallback((m,A)=>{const B=`${m}:${A}`,be=em.current.get(B);if(be)return be;const De=m==="initiative"?e.initiatives.find(Ot=>Ot.id===A):e.workstreams.find(Ot=>Ot.id===A);return Array.isArray(De?.attachments)?De.attachments:[]},[e.initiatives,e.workstreams]),yu=o.useCallback((m,A,B)=>{const be=`${m}:${A}`;em.current.set(be,B);const Ot=(Bd.current.get(be)||Promise.resolve()).catch(()=>{}).then(()=>m==="initiative"?e.updateInitiative(A,{attachments:B}):e.updateWorkstream(A,{attachments:B}));Bd.current.set(be,Ot),Ot.catch(xr=>{dt(xr instanceof Error?xr.message:"Failed to update planning context.","error")}).finally(()=>{Bd.current.get(be)===Ot&&Bd.current.delete(be)})},[e,dt]),By=o.useCallback((m,A,B)=>{const be=gu(m,A);yu(m,A,[...be,B])},[gu,yu]),Wy=o.useCallback((m,A,B)=>{const be=gu(m,A);yu(m,A,be.filter((De,Ot)=>Ot!==B))},[gu,yu]),$y=o.useCallback((m,A,B,be)=>{const Ot=gu(m,A).map((xr,Lr)=>Lr!==B?xr:typeof xr=="string"?{path:xr,caption:be,timestamp:new Date().toISOString()}:{...xr,caption:be});yu(m,A,Ot)},[gu,yu]),Ow=o.useCallback(m=>{L(m),zt("")},[]),Bw=o.useCallback(m=>{zt(m),L(m&&Ut.workstreamInitiativeIds.get(m)||"")},[Ut.workstreamInitiativeIds]),qm=o.useCallback(m=>{const A=ZS(m,Ho);if(A!==m){const B=Ho.find(be=>be.id===m)?.label||"That module";dt(`${B} is not available in this build yet.`,"error");return}if(Cr==="workflowManager"&&A!=="workflowManager"&&Is&&!_i.current){Tn(()=>()=>qm(m));return}hi(),b(A)},[hi,dt,Cr,b,Is,Ho]),Ww=o.useCallback(()=>{if(Cr==="tasks"&&Ka){In(!1),Jt(null),xn(null),di(null);return}if(Cr!=="tasks"){b("tasks"),In(!0);return}In(m=>!m)},[Ka,Cr,b]),$w=o.useCallback(()=>{if(Cr!=="docs"){b("docs"),Ii(!0);return}Ii(m=>!m)},[Cr,b]),Fw=o.useCallback(()=>{if(Cr!=="annotate"){b("annotate"),Wo(!0);return}Wo(m=>!m)},[Cr,b]),Uw=o.useCallback(()=>{if(Cr!=="aiProfiles"){b("aiProfiles"),Cs(!0);return}Cs(m=>!m)},[Cr,b]),zw=o.useCallback(()=>{if(Cr!=="taskforceAgents"){b("taskforceAgents"),nc(!0);return}nc(m=>!m)},[Cr,b]),Hw=o.useCallback(()=>{if(Cr!=="workflowManager"){b("workflowManager"),dn(!0);return}dn(m=>!m)},[Cr,b]),Yp=o.useCallback(()=>{uc(!1),Bl(null),Vd(null)},[]),Fy=o.useCallback(m=>{if(!gi[gd]?.allowed){dt("Taskforce Agents are unavailable for this workspace.","error");return}const A=hs(m)||m.id;Bl({taskId:m.id,taskReference:A,taskTitle:m.title}),pc(!1),uc(!0),as(!1)},[dt,gi]),Gw=o.useCallback(()=>{if(ra&&M){Fy(ra);return}if(!gi[gd]?.allowed){dt("Taskforce Agents are unavailable for this workspace.","error");return}Bl(null),pc(!1),uc(!0)},[ra,M,Fy,dt,gi]),aT=o.useCallback(m=>{const A=String(m||"").trim();A&&(Wl({agentId:A,conversationId:Ja[A]||null}),Bl(null),pc(!1),uc(!0))},[Wl,Ja]),nT=o.useCallback(m=>{$e(m),as(!1)},[$e]),sT=o.useCallback(m=>{hi(),b("tasks"),$e(m)},[hi,$e,b]),oT=o.useCallback(m=>{hi(),b("tasks"),$e(m)},[hi,$e,b]),iT=o.useCallback((m,A)=>{const B=A?.sessionId??null;eo.current=m,fi.current=B,pi(m),lc(B),ji(be=>be+1),b("annotate")},[b]),cT=o.useCallback(({target:m,sessionId:A})=>{eo.current=m,fi.current=A,pi(B=>!B&&!m||B&&m&&B.taskId===m.taskId&&B.taskReferenceLabel===m.taskReferenceLabel&&B.assetId===m.assetId&&B.imageReferenceLabel===m.imageReferenceLabel&&B.path===m.path&&B.displayName===m.displayName?B:m),lc(B=>B===A?B:A)},[]),lT=o.useCallback((m,A)=>{const B=m.trim(),be=Math.max(0,Math.round(A));B&&Xu(De=>De[B]===be?De:eA(De,B,be))},[]),dT=o.useCallback(m=>{const A=Math.max(0,Math.round(m));ep(B=>B===A?B:A)},[]),uT=o.useCallback((m,A)=>{const B=m.trim();if(!B)return;const be={zoomLevel:Math.min(4,Math.max(.25,A.zoomLevel)),scrollLeft:Math.max(0,Math.round(A.scrollLeft)),scrollTop:Math.max(0,Math.round(A.scrollTop))};Pl(De=>{const Ot=De[B];return Ot&&Ot.zoomLevel===be.zoomLevel&&Ot.scrollLeft===be.scrollLeft&&Ot.scrollTop===be.scrollTop?De:eA(De,B,be)})},[]),Vw=o.useMemo(()=>[{value:"created",label:bt("standalone.sortCreated")},{value:"updated",label:bt("standalone.sortUpdated")},{value:"priority",label:bt("standalone.sortPriority")},{value:"complexity",label:bt("standalone.sortComplexity")},...ZC(rt,[...e.searchAgnosticTasks,...is])],[is,e.searchAgnosticTasks,rt]),Kw=o.useMemo(()=>[{value:"status",label:bt("standalone.groupStatus")},{value:"category",label:bt("standalone.groupCategory")},{value:"type",label:bt("standalone.groupType")},{value:"priority",label:bt("standalone.groupPriority")},{value:"complexity",label:bt("standalone.groupComplexity")},{value:"assignee",label:bt("standalone.groupAssignee")},{value:"schedule",label:bt("standalone.groupSchedule")}],[]),qw=o.useMemo(()=>Ho.filter(m=>m.enabled),[Ho]),Yw=o.useMemo(()=>[{key:"empty-columns",icon:C==="show"?a.jsx(rb,{size:16}):C==="collapse"?a.jsx(ab,{size:16}):a.jsx(fA,{size:16}),title:bt(C==="show"?"standalone.showEmptyColumns":C==="collapse"?"standalone.compressEmptyColumns":"standalone.hideEmptyColumns"),onClick:jw,active:C!=="show"},{key:"compressed-cards",icon:Rr?a.jsx(k0,{size:16}):a.jsx(v0,{size:16}),title:bt(Rr?"standalone.expandCards":"standalone.compressCards"),onClick:()=>la(!Rr),active:Rr}],[Rr,jw,C]),pT=o.useMemo(()=>tt.moduleId!=="tasks"?[]:[{key:"filter-toggle",icon:a.jsx(mA,{size:16}),title:bt("standalone.toggleFilters"),onClick:()=>oi(!Bo),active:Bo,ariaExpanded:Bo,ariaControls:"task-workspace-filters",className:Gt?R.filterGlow:""}],[Gt,oi,Bo,tt.moduleId]),fT=o.useMemo(()=>{const m=[];return $l&&m.push({key:"ask-agent",icon:a.jsx(yd,{size:16}),title:to?"Close Taskforce Agent":"Ask Taskforce Agent",onClick:to?Yp:Gw,active:to}),m},[Yp,Gw,to,$l]),mT=o.useMemo(()=>a.jsx(dZ,{id:"task-workspace-filters",categoryFilterOptions:lp,typeFilterOptions:dp,priorities:xe,taxonomyDisplayLabels:St,filterCategories:Ve,setFilterCategories:lt,filterTypes:It,setFilterTypes:wt,filterPriorities:$t,setFilterPriorities:Yt,filterStatus:E,setFilterStatus:x,filterAssignees:qt,setFilterAssignees:er,assigneeOptions:Dt,initiativeFilterOptions:gm,selectedInitiativeId:D,setSelectedInitiativeId:Ow,workstreamFilterOptions:qd,selectedWorkstreamId:Ct,setSelectedWorkstreamId:Bw,taskScope:Tt,setTaskScope:Xr,showArchive:fc,setShowArchive:Fl,clearFiltersDisabled:!re&&!Fe&&sa==="created"&&e.sortOrder==="desc",clearFilters:()=>{Ur(),Xf(),L(""),zt("")}}),[Dt,lp,Ur,qt,Ve,$t,E,It,Fe,re,Ow,Bw,gm,xe,e.sortOrder,D,Ct,er,lt,Yt,x,wt,L,zt,Fl,Xr,sa,Xf,fc,Tt,St,dp,qd]),hT=o.useMemo(()=>[{key:"zen-toggle",icon:a.jsx(w0,{size:16,fill:w?"currentColor":"none"}),title:bt(w?"standalone.exitZenMode":"standalone.enterZenMode"),onClick:()=>T(),active:w}],[T,w]),gT=o.useMemo(()=>({search:a.jsx(oZ,{value:ot,placeholder:bt("standalone.searchPlaceholder"),active:re,onChange:pt,onClear:()=>pt(""),clearTitle:bt("standalone.clearSearchTitle")}),sort:a.jsx(US,{label:a.jsxs(a.Fragment,{children:[a.jsx(kv,{size:12})," ",bt("standalone.sortLabel")]}),value:sa,options:Vw,onChange:m=>ea(m),trailingAction:a.jsx("button",{className:`tf-control-icon ${R.sortDirectionBtn}`,onClick:()=>e.toggleSortOrder(),title:e.sortOrder==="desc"?bt("standalone.sortDirectionDescTitle"):bt("standalone.sortDirectionAscTitle"),children:e.sortOrder==="desc"?a.jsx(gv,{size:14}):a.jsx(sA,{size:14})})}),"divider-primary":a.jsx(zS,{}),grouping:a.jsx(US,{label:a.jsxs(a.Fragment,{children:[a.jsx(Vh,{size:12})," ",bt("standalone.groupLabel")]}),value:h,options:Kw,onChange:m=>y(m)}),"divider-secondary":a.jsx(zS,{}),"task-display-actions":a.jsx(Rh,{actions:Yw})}),[h,Kw,qm,re,e,ot,y,pt,ea,sa,Vw,Yw,tt.moduleId]),yT=o.useMemo(()=>({"add-task":a.jsx(iZ,{icon:a.jsx(ri,{size:16}),label:bt("standalone.addTask"),onClick:Pw}),"add-document":null}),[Pw]),sd=o.useMemo(()=>{const m=`${Fr.workspaceToolButton} tf-control-icon tf-control-icon-quiet`,A=`${m} tf-control-icon-active`,B={tasks:a.jsx(I0,{size:18}),planning:a.jsx(Vh,{size:18}),docs:a.jsx(Ef,{size:18}),annotate:a.jsx(cA,{size:18}),workflowManager:a.jsx(nb,{size:18}),taskforceAgents:a.jsx(yd,{size:18}),aiProfiles:a.jsx(Mh,{size:18})},be=Cr==="planning"?a.jsx("span",{className:Fr.workspaceToolButton,"aria-hidden":"true"}):Cr==="docs"?a.jsx("button",{type:"button",className:As?A:m,onClick:$w,title:As?"Collapse document tray":"Document tray","aria-label":As?"Collapse document tray":"Document tray",children:As?a.jsx(po,{size:18}):a.jsx(Qi,{size:18})}):Cr==="annotate"?a.jsx("button",{type:"button",className:_n?A:m,onClick:Fw,title:_n?"Collapse image tray":"Image tray","aria-label":_n?"Collapse image tray":"Image tray",children:_n?a.jsx(po,{size:18}):a.jsx(Qi,{size:18})}):Cr==="aiProfiles"?a.jsx("button",{type:"button",className:_a?A:m,onClick:Uw,title:_a?"Collapse AI Profile tray":"MCP settings tray","aria-label":_a?"Collapse AI Profile tray":"MCP settings tray",children:_a?a.jsx(po,{size:18}):a.jsx(A0,{size:18})}):Cr==="taskforceAgents"?a.jsx("button",{type:"button",className:jr?A:m,onClick:zw,title:jr?"Collapse builder library":"Builder library","aria-label":jr?"Collapse builder library":"Builder library",children:jr?a.jsx(po,{size:18}):a.jsx(Mh,{size:18})}):Cr==="workflowManager"?a.jsx("button",{type:"button",className:Xa?A:m,onClick:Hw,title:Xa?"Collapse workflow library":"Workflow library","aria-label":Xa?"Collapse workflow library":"Workflow library",children:Xa?a.jsx(po,{size:18}):a.jsx(nb,{size:18})}):a.jsx("button",{ref:Ci,type:"button",className:Cr==="tasks"&&Ka?A:m,onClick:Ww,title:Cr==="tasks"&&Ka?"Collapse planning trays":"Planning","aria-label":Cr==="tasks"&&Ka?"Collapse planning trays":"Planning",children:Cr==="tasks"&&Ka?a.jsx(po,{size:18}):a.jsx(C0,{size:18})});return a.jsxs("aside",{className:`${Fr.workspaceToolRail} ${Fr.workspaceToolRailLeft}`,"aria-label":"Workspace tools",children:[a.jsxs("div",{className:Fr.workspaceToolRailMain,children:[be&&a.jsxs(a.Fragment,{children:[be,a.jsx("div",{className:Fr.workspaceToolRailDivider})]}),qw.map(De=>a.jsx("button",{type:"button",className:Cr===De.id?A:m,onClick:()=>qm(De.id),title:De.label,"aria-label":De.label,children:B[De.id]},De.id))]}),a.jsxs("div",{className:Fr.workspaceToolRailBottom,children:[a.jsx("div",{className:Fr.workspaceToolRailDivider}),a.jsx("button",{type:"button",className:f==="settings"?A:m,onClick:()=>{if(Cr==="workflowManager"&&Is&&!_i.current){Tn(()=>()=>{Br("general"),p("settings")});return}Br("general"),p("settings")},title:"Workspace Settings","aria-label":"Workspace Settings",children:a.jsx(Nf,{size:18})})]})]})},[f,_a,As,Uw,$w,Fw,qm,Ww,zw,Hw,_n,Ka,Cr,Br,p,jr,Xa,Is,qw]),[Zw,kT]=o.useState(null),vT=o.useCallback(m=>{kT(m)},[]),Jw=o.useCallback((m,A)=>fu({type:m,id:A}),[fu]),Qw=o.useCallback(async(m,A)=>{const B=A.title.trim();if(!B)throw new Error(`${m==="initiative"?"Initiative":"Workstream"} title is required.`);try{if(m==="initiative"){const De=await e.createInitiative({title:B,description:A.description?.trim()||null,ownerId:A.ownerId?.trim()||null,...A.icon||A.color?{icon:A.icon??null,color:A.color??null}:{}});return dt("Initiative created","success"),{id:De.id}}const be=await e.createWorkstream({title:B,description:A.description?.trim()||null,ownerId:A.ownerId?.trim()||null,initiativeId:A.initiativeId?.trim()||null,...A.icon||A.color?{icon:A.icon??null,color:A.color??null}:{}});return dt("Workstream created","success"),{id:be.id}}catch(be){throw dt(be instanceof Error?be.message:"Failed to create planning item.","error"),be}},[e.createInitiative,e.createWorkstream,dt]),Xw=o.useCallback(async(m,A,B)=>{const be=B.title.trim();if(!be)throw new Error(`${m==="initiative"?"Initiative":"Workstream"} title is required.`);try{const De={title:be,description:B.description?.trim()||null};if(m==="initiative"){await e.updateInitiative(A,De),dt("Initiative updated","success");return}await e.updateWorkstream(A,De),dt("Workstream updated","success")}catch(De){throw dt(De instanceof Error?De.message:"Failed to update planning item.","error"),De}},[e.updateInitiative,e.updateWorkstream,dt]),Uy=o.useCallback(async(m,A)=>{try{await e.reorderWorkstreamTasks(m,A)}catch(B){throw dt(B instanceof Error?B.message:"Failed to reorder workstream tasks.","error"),B}},[e.reorderWorkstreamTasks,dt]),ku=o.useMemo(()=>({initiatives:Ut.allInitiatives,standaloneWorkstreams:Ut.allStandaloneWorkstreams,assigneeOptions:Dt,currentOwnerId:Ba==="anonymous"?null:Ba,currentWorkspaceId:ht,theme:Rt,taskReferences:Nn,loadState:e.planningLoadState,hydrationStateByEntity:Bs,hydrateEntity:Jw,retry:()=>{e.fetchPlanningEntities()},openTask:$e,setTaskStatus:kp,setTaskAssignee:vp,linkOptions:fp,assignWorkstreamToInitiative:mu,assignTaskToWorkstream:hu,attachWorkstreamToInitiative:Oy,attachTaskToWorkstream:Ly,archiveEntity:Sm,unarchiveEntity:Am,changeOwner:My,changeIdentity:Dy,createEntity:Qw,updateEntity:Xw,addContextFile:By,removeContextFile:Wy,updateContextCaption:$y,showTaskCardStatusLabel:Ce,taskArrangeMode:Ts,setTaskArrangeMode:wo,reorderWorkstreamTasks:Uy}),[ht,Rt,My,Dy,mu,hu,Ly,Oy,Sm,Am,Qw,By,$e,Wy,kp,vp,$y,Jw,Dt,Ba,Ut.allInitiatives,Ut.allStandaloneWorkstreams,fp,Bs,e.fetchPlanningEntities,e.planningLoadState,Ce,Ts,Uy,Nn,Xw]),wT=a.jsx(RX,{open:Ka,leftOffset:56,returnFocusRef:Ci,theme:Rt,initiatives:ku.initiatives,standaloneWorkstreams:ku.standaloneWorkstreams,planningLoadState:ku.loadState,onRetryPlanning:ku.retry,taskScope:Tt,activeInitiativeId:D,activeWorkstreamId:Ct,navigatorSort:Dn,navigatorSortReady:cp,onNavigatorSortChange:Os,taskArrangeMode:Ts,onTaskArrangeModeChange:wo,onReorderWorkstreamTasks:Uy,planningFavorites:cp?wl:[],onTogglePlanningFavorite:m=>{bl(A=>VY(A,m))},favoritesSectionCollapsed:sc,initiativesSectionCollapsed:Dc,workstreamsSectionCollapsed:Vr,onToggleFavoritesSection:()=>vl(m=>!m),onToggleInitiativesSection:()=>ss(m=>!m),onToggleWorkstreamsSection:()=>Dd(m=>!m),expandedInitiativeIds:xt,detail:ym,editor:ja,secondaryEditor:Ti,secondaryPane:km,primaryHydrationState:Gc,secondaryHydrationState:Ug,onRetryPrimaryHydration:ya?()=>{fu(ya)}:void 0,onRetrySecondaryHydration:Aa?()=>{fu({type:"workstream",id:Aa})}:void 0,onWidthChange:Zd,currentWorkspaceId:ht,currentOwnerId:Ba==="anonymous"?"":Ba,linkOptions:fp,showTaskCardStatusLabel:Ce,assigneeOptions:Dt.map(m=>({value:String(m.value),label:m.label,icon:m.icon,color:m.color,kind:m.kind,avatarUrl:m.avatarUrl??null,avatarRevision:m.avatarRevision??null,avatarUpdatedAt:m.avatarUpdatedAt??null,username:m.username??null,surfaceType:m.surfaceType??null,providerMetadata:m.providerMetadata??null,archivedAt:m.archivedAt??null})),draftInitiativeSummary:zg,draftTitle:Ld,draftDescription:Sl,draftOwner:Yu,draftInitiativeId:Rn,draftIcon:Lc,draftColor:Oc,onChangeDraftTitle:oc,onChangeDraftDescription:ic,onChangeDraftOwner:cc,onChangeDraftInitiativeId:ui,onChangeDraftIcon:Al,onChangeDraftColor:Cl,onCollapseTreePane:()=>$o(!0),onExpandTreePane:()=>$o(!1),onCollapsePrimaryPane:()=>ci(!0),onExpandPrimaryPane:()=>ci(!1),onCollapseSecondaryPane:()=>vo(!0),onExpandSecondaryPane:()=>vo(!1),onBackFromSecondary:()=>{Xs.current=!1,xi(!1),Fo(null),xn(null)},treeCollapsed:ko,primaryCollapsed:ns,secondaryCollapsed:li,onCancelEditor:Py,onCancelSecondaryEditor:Ey,onSubmitEditor:Q_,isSubmittingEditor:Bg,onCreateInitiative:()=>Ny("initiative"),onCreateWorkstream:()=>Ny("workstream"),onCreateTaskInWorkstream:J_,onCreateWorkstreamInInitiative:m=>Ny("workstream",m),onAssignInitiativeToWorkstream:mu,onOpenTaskById:ku.openTask,onSetTaskStatus:kp,onChangeTaskAssignee:vp,onArchivePlanningTask:Gg,onArchiveResolvedWorkstream:wp,onArchiveResolvedInitiative:Xd,taskReferences:Nn,onAssignTaskToWorkstream:hu,onAttachTaskToWorkstreamByReference:Ly,onAttachWorkstreamToInitiativeByReference:Oy,onAddPlanningContextFile:By,onRemovePlanningContextFile:Wy,onUpdatePlanningContextCaption:$y,onToggleInitiative:X_,onSelectInitiative:eT,onSelectWorkstream:tT,onOpenInitiativeDetails:Kp,onOpenWorkstreamDetails:qp,onOpenNestedWorkstreamDetails:rT,onEditInitiative:m=>Lw("initiative",m),onEditWorkstream:m=>Lw("workstream",m),onChangePlanningOwner:My,onChangePlanningIdentity:Dy,onArchiveInitiative:m=>{e.archiveInitiative(m).then(()=>{dt("Initiative archived","success")}).catch(A=>{dt(A instanceof Error?A.message:"Failed to archive initiative.","error")})},onUnarchiveInitiative:m=>{e.unarchiveInitiative(m).then(()=>{dt("Initiative unarchived","success")}).catch(A=>{dt(A instanceof Error?A.message:"Failed to unarchive initiative.","error")})},onArchiveWorkstream:m=>{e.archiveWorkstream(m).then(()=>{dt("Workstream archived","success")}).catch(A=>{dt(A instanceof Error?A.message:"Failed to archive workstream.","error")})},onUnarchiveWorkstream:m=>{e.unarchiveWorkstream(m).then(()=>{dt("Workstream unarchived","success")}).catch(A=>{dt(A instanceof Error?A.message:"Failed to unarchive workstream.","error")})}}),bT=tt.headerSections.map(m=>{const A=gT[m];return A?a.jsx(Y.Fragment,{children:A},m):null}).filter(Boolean),ST=tt.primaryAction?yT[tt.primaryAction]:null,zy=to?a.jsx("div",{className:`${R.taskforceAgentDrawerOverlay} ${Pi?R.taskforceAgentDrawerOverlayCollapsed:""}`.trim(),style:{top:`${_s}px`},"data-theme":Rt,"aria-label":"Taskforce Agent chat",children:a.jsx("aside",{className:Pi?`${Fr.workspaceToolRail} ${Fr.workspaceToolRailRight}`:R.taskforceAgentDrawerPanel,children:Pi?a.jsxs("div",{className:Fr.workspaceToolRailMain,children:[a.jsx("button",{type:"button",className:`${Fr.workspaceToolButton} tf-control-icon tf-control-icon-quiet tf-control-icon-active`,onClick:()=>pc(!1),title:"Expand agent chat","aria-label":"Expand agent chat",children:a.jsx(yd,{size:16})}),a.jsx("button",{type:"button",className:`${Fr.workspaceToolButton} tf-control-icon tf-control-icon-quiet`,onClick:Yp,title:"Close agent chat","aria-label":"Close agent chat",children:a.jsx(Mo,{size:16})})]}):a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:R.taskforceAgentDrawerHeader,children:[lm||a.jsxs("div",{className:R.taskforceAgentDrawerHeaderFallback,children:[a.jsx("span",{className:R.taskforceAgentDrawerFallbackAvatar,"aria-hidden":"true",children:a.jsx(yd,{size:16})}),a.jsx("strong",{children:"Loading agent..."})]}),a.jsxs("div",{className:R.taskforceAgentDrawerHeaderActions,children:[a.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>pc(!0),title:"Collapse agent chat","aria-label":"Collapse agent chat",children:a.jsx(xd,{size:16})}),a.jsx("button",{type:"button",className:"tf-control-icon",onClick:Yp,title:"Close agent chat","aria-label":"Close agent chat",children:a.jsx(Mo,{size:16})})]})]}),a.jsx(o.Suspense,{fallback:a.jsx("div",{className:R.taskforceAgentDrawerLoading,children:a.jsx(za,{size:18,className:R.spinner})}),children:a.jsx(XS,{workspaceId:ht,launchContext:cm,onClearLaunchContext:Yp,onOpenTaskContext:nT,taskReferences:Nn,surface:"taskDrawer",runtimeMode:nr,cloudAuthConfigured:He,authSessionResolved:Mr,isAuthenticated:ir,resolveCloudAuthUrl:or,theme:Rt,rememberedAgentId:Fa,rememberedConversationId:La,rememberedConversationByAgentId:Ja,rememberedSelectionReady:cn,onRememberSelection:Wl,onRenderDrawerHeader:sp})})]})})}):null;return a.jsxs("div",{className:`${Fr.standaloneWrapper} ${w?R.zenModeEnabled:""}`,"data-theme":Rt,children:[a.jsx("div",{ref:zn,style:{flexShrink:0},children:a.jsx(HY,{projectName:Ta,currentWorkspaceId:ht,runtimeMode:nr,theme:Rt,onBrandClick:_y,meta:a.jsxs(a.Fragment,{children:[a.jsx("span",{className:R.taskCountBadge,title:Ua,children:Er}),Ba&&Ba!=="anonymous"&&a.jsxs(a.Fragment,{children:[a.jsxs("button",{type:"button",className:`${R.taskCountBadge} ${R.taskCountBadgeButton} ${os==="assigned-to-me"?R.taskCountBadgeActive:""}`.trim(),onClick:()=>Gm("assigned-to-me"),title:os==="assigned-to-me"?"Clear assigned-to-me quick filter":"Filter to my open tasks","aria-label":`${os==="assigned-to-me"?"Clear":"Apply"} assigned to me quick filter (${Gl} task${Gl===1?"":"s"})`,"aria-pressed":os==="assigned-to-me",children:[a.jsx(Du,{size:13,className:R.taskCountBadgeIcon,"aria-hidden":"true"}),Gl]}),a.jsxs("button",{type:"button",className:`${R.taskCountBadge} ${R.taskCountBadgeButton} ${Kc>0?R.taskCountBadgeAlert:""} ${os==="overdue"?R.taskCountBadgeActive:""}`.trim(),onClick:()=>Gm("overdue"),title:os==="overdue"?"Clear my-overdue-tasks quick filter":"Filter to my overdue tasks","aria-label":`${os==="overdue"?"Clear":"Apply"} my overdue tasks quick filter (${Kc} task${Kc===1?"":"s"})`,"aria-pressed":os==="overdue",children:[a.jsx(b0,{size:13,className:R.taskCountBadgeIcon,"aria-hidden":"true"}),Kc]})]}),Rs&&a.jsx("button",{className:"tf-control-icon",onClick:Lm,title:`Sync manager: ${Vp.label} | Last success: ${zs}`,style:{marginLeft:"6px",height:"24px",width:"24px",padding:0,borderRadius:"999px",border:`1px solid ${Vp.border}`,background:Vp.background,color:Vp.color,display:"inline-flex",alignItems:"center",justifyContent:"center"},children:Vp.icon==="off"?a.jsx(S0,{size:16}):a.jsx(hA,{size:16})})]}),actions:a.jsxs(a.Fragment,{children:[l&&a.jsxs(a.Fragment,{children:[ir&&jn?.stripeCustomerId&&a.jsx("button",{className:"tf-control-icon",onClick:()=>{Hm()},title:"Manage billing",disabled:Io,children:"Manage billing"}),a.jsx("button",{className:"tf-control-icon",onClick:()=>{if($p){pu();return}d()},title:$p?"Continue to Taskforce":"Back",disabled:el,children:$p?"Take Me to Taskforce":"Back"})]}),!l&&a.jsxs(a.Fragment,{children:[bT,a.jsx(Rh,{actions:pT}),ST]}),a.jsx(Rh,{actions:hT}),!l&&a.jsx(Rh,{actions:fT}),Z_]})})}),a.jsx(pg,{notice:f==="add"?null:Xn,onDismiss:es}),a.jsx(KI,{theme:Rt}),da&&a.jsx("div",{className:Je.authBlockedBanner,children:"Authentication required for this environment. Use the Account menu to sign in."}),a.jsx("div",{className:`${R.taskforceAssistantWorkspace} ${to?R.taskforceAssistantWorkspaceOpen:""} ${Pi?R.taskforceAssistantWorkspaceCollapsed:""}`.trim(),children:a.jsx("div",{className:R.taskforceAssistantWorkspaceContent,children:l?a.jsx("div",{className:`${Fr.standalonePage} ${Fr.standaloneContent} ${R.appScrollbar} tf-scrollbar`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflowY:"auto",overflowX:"hidden",scrollbarGutter:"stable",background:"var(--surface-page)"},children:a.jsx(o.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(za,{size:20,className:R.spinner})}),children:a.jsx(gee,{...e,currentTheme:Rt,projectName:Ta,currentWorkspaceId:ht,authUserId:ut,apiBaseUrl:lu,connectedEnvironmentSource:e.config?.cloudAuthBaseUrl||e.config?.apiBaseUrl||"",resolveCloudAuthUrl:or,embedded:!0,shellOwnsScroll:!0,onAccountProfileSummaryChange:zm,onContinueToTaskforce:pu,continueBusy:el})})}):Cr==="planning"?a.jsxs("div",{className:`${Fr.standalonePage} ${Fr.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[sd,a.jsx(o.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(za,{size:20,className:R.spinner})}),children:a.jsx(hee,{model:ku})})]}):Cr==="docs"&&Ei?a.jsxs("div",{className:`${Fr.standalonePage} ${Fr.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[sd,a.jsx(o.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(za,{size:20,className:R.spinner})}),children:a.jsx(pee,{taskReferences:Nn,tasks:N,runtimeMode:nr,workspaceId:ht,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",typeFilters:Zu,attachmentFilters:Wd,onTypeFiltersChange:tm,onAttachmentFiltersChange:rm,sortField:Ju,sortOrder:Qu,onSortFieldChange:am,onSortOrderChange:$d,pinnedDocIds:Il,onPinnedDocIdsChange:Fd,searchQuery:_l,onSearchQueryChange:Bc,selectedDocId:Ri,onSelectedDocIdChange:Tl,selectionReady:cp,documentScrollByDocId:xl,onDocumentScrollChange:lT,documentListScrollTop:Ud,onDocumentListScrollChange:dT,documentTrayOpen:As,onCloseDocumentTray:()=>Ii(!1),requestedDocPath:nm,requestedDocAssetId:sm,onRequestedDocHandled:()=>{Rl(null),Wc(null)},onBackToTask:oT,enableTaskGeneration:!0})})]}):Cr==="annotate"&&$c?a.jsxs("div",{className:`${Fr.standalonePage} ${Fr.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[sd,a.jsx(o.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(za,{size:20,className:R.spinner})}),children:a.jsx(uee,{runtimeMode:nr,apiBaseUrl:e.config?.apiBaseUrl||"",cloudAuthBaseUrl:e.config?.cloudAuthBaseUrl||"",workspaceId:ht,sessionLoadReady:Ml,requestedTarget:Ws,requestedSessionId:Nl,requestedOpenVersion:om,imageTrayOpen:_n,onCloseImageTray:()=>Wo(!1),resolveTaskReferenceLabel:pm,resolveImageReferenceLabel:Fg,onOpenTarget:iT,onContextChange:cT,viewportByContextKey:Hd,onViewportChange:uT,onBackToTask:sT})})]}):Cr==="workflowManager"?a.jsxs("div",{className:`${Fr.standalonePage} ${Fr.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[sd,a.jsx(o.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(za,{size:20,className:R.spinner})}),children:a.jsx(fee,{workspaceId:ht,libraryTrayOpen:Xa,onCloseLibraryTray:()=>dn(!1),assigneeOptions:Dt,theme:Rt,onUnsavedChangesChange:Md})})]}):Cr==="taskforceAgents"?a.jsxs("div",{className:`${Fr.standalonePage} ${Fr.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[sd,a.jsx(o.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(za,{size:20,className:R.spinner})}),children:a.jsx(XS,{workspaceId:ht,taskReferences:Nn,agentRosterTrayOpen:jr,onCloseAgentRosterTray:()=>nc(!1),runtimeMode:nr,cloudAuthConfigured:He,authSessionResolved:Mr,isAuthenticated:ir,resolveCloudAuthUrl:or,theme:Rt,rememberedAgentId:Fa,rememberedConversationId:La,rememberedConversationByAgentId:Ja,rememberedSelectionReady:cn,onRememberSelection:Wl,onOpenConversation:aT})})]}):Cr==="aiProfiles"?a.jsxs("div",{className:`${Fr.standalonePage} ${Fr.standaloneContent}`,style:{position:"relative",display:"flex",flex:1,minHeight:0,overflow:"hidden",paddingLeft:"56px"},children:[sd,a.jsx(o.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",flex:1},children:a.jsx(za,{size:20,className:R.spinner})}),children:a.jsx(mee,{workspaceId:ht,runtimeMode:nr,cloudAuthConfigured:He,authSessionResolved:Mr,isAuthenticated:ir,cloudAiProfileSeatUsage:jn?.aiProfileSeatUsage??null,agentTrayOpen:_a,onCloseAgentTray:()=>Cs(!1),resolveCloudAuthUrl:or,theme:Rt,onNotice:dt,mcpSettingsNode:a.jsx(QS,{settingsModel:{...Ft,initialSection:"mcp",onOpenCloudAuth:Up},renderMode:"mcp-only"})})})]}):a.jsxs("div",{className:`${Fr.standalonePage} ${Fr.standaloneContent} `,style:{position:"relative",opacity:e.loadingTasks?.7:1,transition:"opacity 0.2s ease, padding 220ms cubic-bezier(0.4, 0, 0.2, 1)",display:"flex",flex:1,minHeight:0,paddingLeft:"56px"},children:[sd,a.jsxs("div",{style:{position:"relative",width:"100%",minWidth:0,flex:1,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:[Bo&&mT,a.jsxs("div",{style:{position:"relative",width:"100%",minWidth:0,flex:1,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden",transition:"padding 220ms cubic-bezier(0.4, 0, 0.2, 1)",paddingLeft:Ka?`${hp+6}px`:"6px",paddingRight:h==="schedule"&&Ss?`${hv}px`:0},children:[a.jsx("div",{ref:vT,style:{position:"absolute",top:0,right:0,bottom:0,left:"-56px",zIndex:35,pointerEvents:"none"}}),e.loadingTasks&&Vc.length>0&&a.jsx("div",{className:R.boardRefreshIndicator,"aria-live":"polite","aria-label":"Refreshing tasks",children:a.jsx(za,{size:14,className:R.spinner})}),Tt==="deleted"&&a.jsx(VI,{theme:Rt,selectedRecords:Vo.selectedRecords,matchingCount:Vo.matchingRecords.length,allMatchingSelected:Vo.allMatchingSelected,someMatchingSelected:Vo.someMatchingSelected,fullTrashCount:e.deletedTasks.length,onSelectAllMatching:Vo.selectAllMatching,onClearSelection:Vo.clear,onRestore:nt,onEmptyEntireTrash:()=>{const m=e.deletedTasks.length;m>0&&window.confirm(`Permanently delete all ${m} tasks in Trash? Filters and selection do not limit this action. This cannot be undone.`)&&ur()}}),a.jsx(nY,{tasks:vm,allTasks:wm,columns:Rw,groupBy:h,scheduleDates:Ic,searchQuery:ot,filterCategories:Ve,filterTypes:It,filterPriorities:$t,filterStatus:E,filterAssignees:qt,filtersReady:_t,assigneeOptions:Dt,scheduleFilteredTaskIds:gp,copiedId:jt,taxonomies:rt,types:kt,priorities:xe,workspaceId:ht,deletedTaskRecordByTaskId:Ni,selectedDeletedRecordIds:Vo.selectedIds,onDeletedSelectionChange:Vo.toggle,onUpdateTask:F,onTaskClick:v,taskReferences:Dw,onCopyId:$,onToggleInProgress:Ke,onToggleReview:Ge,onToggleComplete:Qe,onToggleCancel:At,onSetStatus:qc,onArchiveTask:Nt,onAddTaskToColumn:Vg,showTaskCardStatusLabel:Ce,onScheduleDaySelected:Hg,persistedScrollLeft:h==="schedule"?Js:void 0,onScrollLeftChange:hc,emptyColumnMode:C,categories:g,compressed:Rr,readOnlyMode:Tt==="deleted"?"deleted":Tt==="archived"?"archived":null,recentlyChangedTaskIds:e.recentlyChangedTaskIds,sortBy:sa,sortOrder:e.sortOrder,planningDropTargets:Zw?tc.createPortal(wT,Zw):null,onAssignTaskToWorkstream:hu,onAssignWorkstreamToInitiative:mu,workstreams:e.workstreams,initiatives:e.initiatives,onUnarchive:bm,onDelete:Jd},`${h}-${Rw.map(m=>String(m.value)).join("|")}-${Ic.mon}`),h==="schedule"&&!Ss&&a.jsx("button",{type:"button",className:"tf-control-icon",onClick:()=>{Jt(null),go(!0)},title:"Show Schedule Sidebar",style:{position:"absolute",top:"10px",right:"10px",zIndex:20},children:a.jsx(po,{size:16})}),h==="schedule"&&a.jsx(ree,{open:Ss,onClose:()=>go(!1),scheduleSelectedDate:ts,setScheduleSelectedDate:rs,scheduleCalendarMonth:Un,setScheduleCalendarMonth:na,scheduleShowWeekends:Sa,setScheduleShowWeekends:hn,scheduleShowBacklog:aa,setScheduleShowBacklog:Ds,scheduleOnlyExpired:Mn,setScheduleOnlyExpired:Ls,expiredScheduledCount:Qd,overdueDueCount:Hl,expiredLeafCandidates:Mi,expiredRecoveryCandidates:gc,onMoveExpiredToSelectedWeek:K_,onMoveExpiredToBacklog:q_,scheduleBulkBusy:Di,globalWeekStartsOn:tr,resolvedLocale:bs,todayDateOnly:en,scheduleBaseTasks:up,scheduleWeekStart:nd,scheduleWeekLabel:Y_})]})]})]})})}),zy&&typeof document<"u"?tc.createPortal(zy,document.body):zy,a.jsxs(Do,{isOpen:f==="add",onClose:yp,title:M?ra?.isDeleted?"Deleted Task":"Edit Task":"New Task",size:ii?"full":"xl",theme:Rt,className:`${R.taskforceTaskModalOverlay} ${to?R.taskforceModalWithAssistantPanel:""} ${Pi?R.taskforceModalWithAssistantPanelCollapsed:""}`.trim(),overlayStyle:{"--taskforce-task-modal-backdrop-top":`${_s}px`,"--taskforce-task-modal-backdrop-left":"56px"},headerActions:a.jsxs(a.Fragment,{children:[M?null:a.jsxs("button",{type:"button",onClick:m=>V(m),disabled:O||!U.trim(),className:R.primaryUpdateBtn,title:bt("actionHeader.addTaskTitle"),children:[O?a.jsx(za,{size:16,className:R.spinner}):a.jsx(ri,{size:16}),bt("actionHeader.addTask")]}),a.jsx("button",{className:"tf-control-icon",onClick:()=>as(m=>!m),title:ii?"Exit full screen":"Enter full screen","aria-label":ii?"Exit full screen":"Enter full screen",children:ii?a.jsx(ab,{size:18}):a.jsx(rb,{size:18})})]}),draggable:!ii,closeOnOverlayClick:!1,children:[a.jsxs("div",{className:R.taskNoticeAnchor,children:[a.jsx(GI,{editingTaskId:M,loading:O,submitDisabled:We,autoSaveState:de,title:U,status:Re,onStatusChange:we,showCreateSubmit:!1,currentTask:ra,currentTaskWorkstream:Fn,currentTaskInitiative:Qa,workstreams:e.workstreams,onWorkstreamInputChange:Me,onSetWorkstreamForCurrentTask:Ee,handleSubmit:V,handleCopyId:$,copiedId:jt,tasks:N,handleToggleInProgress:Ke,handleToggleReview:Ge,handleToggleComplete:Qe,handleToggleCancel:At,handleSetStatus:qc,handleArchiveTask:Nt,handleUnarchiveTask:m=>{if(ra?.isDeleted){const A=Ni.get(m);if(!A)return;Xt(A.id,A.taskId);return}Qt(m)},handleRestoreDeletedTask:ra?.deletedRecordId?m=>{const A=e.deletedTasks.find(B=>B.id===m);Xt(m,A?.taskId)}:void 0,handlePermanentlyDeleteDeletedTask:ra?.deletedRecordId?m=>{window.confirm("Permanently delete this task? This cannot be undone.")&&(Mt(m),_(),p("tasks"))}:void 0,onAskAgent:Fy}),a.jsx(pg,{notice:Z?{message:Z,tone:"error"}:Xn,onDismiss:()=>{pa(),es()},placement:"task"})]}),a.jsx(HI,{editingTaskId:M,initialActivityEntryId:e.initialActivityEntryId,title:U,description:ce,checklistItems:Ye,category:he,type:ye,priority:ae,complexity:W,manualComplexityEnabled:pe,assignee:ie,scheduledDate:H,dueDate:Pe,formTaxonomies:P,onTaxonomyChange:(m,A)=>ee(B=>({...B,[m]:A})),taxonomies:rt,comments:Se,newCommentText:_e,contextFiles:Ze,currentWorkspaceId:ht,descriptionImageDraftId:G,currentActorId:ut,apiBaseUrl:lu,runtimeMode:nr,showImageReviews:!0,descriptionFocused:Xe,showMarkdownHelp:qe,checklistEnabled:le,categories:g,types:kt,priorities:xe,taxonomyDisplayLabels:St,assigneeOptions:Dt,workstreams:e.workstreams,initiatives:e.initiatives,copiedId:jt,onTitleChange:ve,onTitleDraftChange:te,onDescriptionChange:Le,onDescriptionDraftChange:Ie,onChecklistItemsChange:ge,onCategoryChange:Ae,onTypeChange:Ne,onPriorityChange:q,onComplexityChange:K,onAssigneeChange:Q,onScheduledDateChange:se,onDueDateChange:ue,onNewCommentTextChange:ke,onDescriptionFocusedChange:ze,onShowMarkdownHelpChange:Te,onOpenSettings:m=>{Br(m),p("settings")},onSubmit:V,onDescriptionImageUploadStart:Be,commentsEndRef:Va,onAddComment:()=>fe(_e),taskReferences:Dw,onAddContextFile:m=>{Uo(A=>[...A,m])},onRemoveContextFile:async m=>{Uo(A=>A.filter((B,be)=>be!==m))},onUpdateContextCaption:(m,A)=>{Uo(B=>B.map((be,De)=>De!==m?be:typeof be=="string"?{path:be,caption:A,timestamp:new Date().toISOString()}:{...be,caption:A}))},onSetCardCover:async m=>{if(!M)return;if(await F(M,{cardCoverAssetId:m})===!1)throw new Error("Unable to update the task card image.")},cardCoverDisabled:at,onOpenContextImage:m=>{Ff(m,{ownerType:"task",ownerId:M,ownerReferenceLabel:hs(ra),workspaceId:ht})},onCopyId:$,onToggleInProgress:Ke,onToggleReview:Ge,onToggleComplete:Qe,onToggleCancel:At,onSetStatus:qc,onArchiveTask:Nt,onUnarchive:m=>{if(ra?.isDeleted){const A=Ni.get(m);if(!A)return;Xt(A.id,A.taskId);return}Qt(m)},currentTask:ra})]}),a.jsx(Do,{isOpen:f==="settings",onClose:yp,title:"Settings",size:"xl",theme:Rt,draggable:!0,isSettings:!0,closeOnOverlayClick:!1,children:a.jsx(o.Suspense,{fallback:a.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",padding:"2rem"},children:a.jsx(za,{size:20,className:R.spinner})}),children:a.jsx(QS,{settingsModel:{...Ft,onOpenCloudAuth:Up},onSectionChange:Br})})}),a.jsx(VK,{prompt:Ai,theme:Rt,onClose:si,onConfirm:Cn}),a.jsx(KK,{isOpen:Dm,theme:Rt,onClose:my,onConfirm:hy}),a.jsx(GK,{isOpen:Kg,theme:Rt,onClose:()=>bp(!1),supportMailtoHref:yy,onOpenSettings:()=>{bp(!1),p("settings"),Br("general")}}),a.jsx(bK,{isOpen:Oi,theme:Rt,displayName:$i,email:Sc,avatarDisplayUrl:Xl,accountBadgeInitial:cu,profileSaveBusy:Fi,profileAvatarBusy:Em,profileSaveError:Ep,profileSaveNotice:Mm,cloudAuthEnabled:He,availableAuthProviders:Bn,billingLoading:Rp,billingError:vc,billingActionError:Xc,billingNotice:rl,billingActionBusy:Io,billingIntervalChoice:Us,accountProfileSummary:jn,onClose:wy,onSaveProfile:()=>{Cy()},onDisplayNameChange:jp,onOpenAvatarManager:()=>{so(null),oo(null),Kl(!0)},onFetchLoginMethods:ha,onUnlinkLoginMethod:ba,onAddPassword:nn,onChangePassword:kr,onLinkProvider:m=>wn(m),onBillingIntervalChange:dy,onRefreshBilling:()=>{ki()},onUpdateInterval:()=>{Iy()},onManageBilling:()=>{Hm()},onOpenPlans:()=>{Bi(!1),Fp()}}),a.jsx(zK,{isOpen:qg,theme:Rt,title:"Edit Profile Photo",currentImageUrl:Xl,fallbackInitial:cu,accept:yee,busy:Em,hasPendingImage:!!ls,canRemove:!!Xl,error:Ep,notice:Mm,onClose:()=>Kl(!1),onApplyImage:by,onRemoveImage:Ay,onDiscardPendingImage:Sy}),a.jsx(Gq,{isOpen:tu,theme:Rt,teamPlanMode:Ap,teamMgmtError:Jg,teamManagementTab:Yg,teamUsersLoading:Qg,teamUsers:Ip,teamActionBusyUserId:ey,teamInviteFeedback:ao,teamInviteEmail:_p,teamInviteRole:su,teamInvitePermissionMode:Tp,teamInviteBusy:ry,pendingInvites:J,teamAuditLoading:ny,teamAuditEvents:ou,teamAuditPage:kc,teamAuditPages:cy,teamAuditHasMore:oy,onClose:()=>Jc(!1),onOpenMembersTab:()=>{ru("members"),td()},onOpenInvitesTab:()=>ru("invites"),onOpenAuditTab:()=>{ru("audit"),Cc(kc)},onMemberRoleChange:(m,A)=>{I(m,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(m)}/role`,{method:"PATCH",headers:{"Content-Type":"application/json",...xo()},credentials:"include",body:JSON.stringify({workspaceId:qo,role:A})}))},onMemberPermissionChange:(m,A)=>{I(m,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(m)}/permission-mode`,{method:"PATCH",headers:{"Content-Type":"application/json",...xo()},credentials:"include",body:JSON.stringify({workspaceId:qo,mode:A})}))},onToggleMemberDisabled:(m,A)=>{I(m,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(m)}/disable`,{method:"PATCH",headers:{"Content-Type":"application/json",...xo()},credentials:"include",body:JSON.stringify({workspaceId:qo,disabled:A})}))},onRevokeInvite:m=>{I(m,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(m)}/invite/revoke`,{method:"POST",headers:{"Content-Type":"application/json",...xo()},credentials:"include",body:JSON.stringify({workspaceId:qo})}))},onRemoveMember:m=>{I(m,async()=>fetch(`/api/taskforce/admin/users/${encodeURIComponent(m)}?workspaceId=${encodeURIComponent(qo)}`,{method:"DELETE",headers:xo(),credentials:"include"}))},onInviteEmailChange:Rm,onInviteRoleChange:ty,onInvitePermissionModeChange:jm,onSubmitInvite:()=>{X()},onLoadAuditPrevious:()=>{Cc(kc-1)},onLoadAuditNext:()=>{Cc(kc+1)}}),a.jsx(LV,{isOpen:Im,theme:Rt,onClose:()=>Sp(!1),onConfirm:()=>rd({intent:"create-workspace"})}),a.jsx(Hq,{isOpen:Op,theme:Rt,currentWorkspaceLabel:Jl,syncStatus:Gp,syncStatusMeta:Iw,workspaceCloudSyncEnabled:Zl,syncControlBusy:fy,canManageWorkspaceSync:Dp,workspaceSyncSummary:Hi.summary,workspaceSyncRecommendedAction:Hi.recommendedAction,workspaceSyncRepairBusy:G_,referenceMismatchCount:Cw,syncStageLabel:V_,workspaceSyncPendingChanges:Ty,incomingCloudChanges:Hn?.incomingCloudChanges||"Unknown",formattedLastSyncTime:gw,formattedLastPullTime:mw,formattedLastPushTime:hw,syncLastError:vw,activeReferenceMismatchSummaries:$_,syncDiagnosticsSummary:L_,syncEventRows:W_,syncEventsListRef:O_,workspaceSyncRepairQueued:F_,workspaceSyncBusy:yw,workspaceSyncCopied:U_,coordinatorOwnershipMode:Hp,coordinatorOwnershipTransferBusy:Ry,coordinatorOwnershipTransferDisabled:M_,onClose:sl,onToggleWorkspaceSync:m=>{Om(m)},onRepairSync:H_,onCopyReport:()=>{z_()},onRetrySync:()=>{me().catch(()=>{})},onTransferCoordinatorOwnership:()=>{D_()}}),a.jsx(Yq,{isOpen:!!kl,onKeepEditing:()=>Tn(null),onDiscard:()=>{const m=kl;Tn(null),_i.current=!0,m?.(),window.setTimeout(()=>{_i.current=!1},0)},theme:Rt}),yt&&tc.createPortal(a.jsx("div",{className:`${dr.overlay} ${dr.unsavedOverlay}`,style:{zIndex:2e3},children:a.jsxs("div",{className:`tf-surface-modal tf-modal-shell ${dr.modal} ${dr.unsavedModal}`,"data-theme":Rt,children:[a.jsx("div",{className:`tf-modal-header ${dr.unsavedHeader}`,children:a.jsxs("div",{className:`tf-modal-title ${dr.unsavedTitle}`,children:[a.jsx(Rd,{size:20}),"Unsaved Changes"]})}),a.jsx("div",{className:`${dr.form} ${dr.unsavedContent}`,children:a.jsx("p",{className:dr.unsavedText,children:"You have unsaved changes. Would you like to save them?"})}),a.jsxs("div",{className:`${dr.formActions} ${dr.unsavedActions}`,children:[a.jsx("button",{className:R.cancelBtn,onClick:()=>ar(!1),title:"Close dialog and continue editing",children:"Keep Editing"}),a.jsx("button",{className:R.destructiveBtn,onClick:Oo,title:"Discard unsaved changes and leave",children:"Discard"}),a.jsxs("button",{className:R.submitBtn,onClick:Vt,disabled:O,title:"Save changes and leave",children:[O?a.jsx(za,{size:16,className:R.spinner}):a.jsx(lA,{size:16}),"Save"]})]})]})}),document.body),Ks&&tc.createPortal(a.jsx("div",{className:Ea.overlay,children:a.jsxs("div",{className:Ea.browser,children:[a.jsxs("div",{className:Ea.header,children:[a.jsxs("div",{className:Ea.pathInfo,children:[a.jsx(Qi,{size:14}),a.jsx("span",{children:fn||"Project Root"})]}),a.jsxs("div",{className:Ea.actions,children:[fn&&a.jsx("button",{className:R.helpLink,onClick:()=>{const m=fn.split("/").filter(Boolean);m.pop(),xa(m.length?m.join("/")+"/":"")},children:"Back"}),a.jsx("button",{className:R.helpLink,onClick:()=>ys(!1),children:"Close"})]})]}),a.jsxs("div",{className:Ea.list,children:[ks&&typeof ks=="object"&&a.jsxs("div",{className:`${Ea.item} ${Ea.itemFile} ${Ea.itemCurrent}`,onClick:()=>mn(fn),children:[a.jsx(Si,{size:14})," Select Current: ./",fn||"(root)"]}),$n.map(m=>a.jsxs("div",{className:Ea.item,onClick:()=>xa(fn+m+"/"),children:[a.jsx(Qi,{size:14})," ",m,"/"]},m)),Ia.map(m=>a.jsxs("div",{className:`${Ea.item} ${Ea.itemFile}`,onClick:()=>mn(fn+m),children:[a.jsx(Ef,{size:14})," ",m]},m)),$n.length===0&&Ia.length===0&&a.jsx("div",{className:`${Ea.item} ${Ea.empty}`,children:"No items found"})]})]})}),document.body)]})}function See(e){const t=e.setupState,r=e.runtimeMode,n=e.isAuthenticated,s=!!(t&&r==="cloud"&&n&&t.globalSetupState==="missing"),i=!!(t&&r==="local"&&t.globalSetupState==="missing"),l=!!(t&&r==="cloud"&&n&&t.workspaceSetupState==="missing"),c=!!(t&&r==="local"&&t.workspaceSetupState==="missing"),d=!!(t&&(t.forceSetup||t.forceGlobalSetup||t.forceWorkspaceSetup||s||l||i||c));if(!d)return{setupGateActive:!1,needsGlobalSetup:!1,needsWorkspaceSetup:!1,hasSetupReadError:!1,phase:"ready"};const f=!!(t&&(t.forceSetup||t.forceGlobalSetup||s||i)),p=!!(t&&(t.forceSetup||t.forceWorkspaceSetup||l||c)),g=!!(f&&t?.globalSetupState==="missing"),h=!!(p&&t?.workspaceSetupState==="missing"),y=!!(f&&t?.globalSetupState==="unreadable"),k=!!(p&&t?.workspaceSetupState==="unreadable"),b=y||k;return{setupGateActive:d,needsGlobalSetup:g,needsWorkspaceSetup:h,hasSetupReadError:b,phase:b?"setup-read-error":g?"needs-global-setup":h?"needs-workspace-setup":"ready"}}const _k="/taskforce/assets/taskforce-BxLPokNB.png";function tA(e){return{categories:!!e?.categories?.length,types:!!e?.types?.length,priorities:!!e?.priorities?.length}}function Tk(e){return(Array.isArray(e)?e:[]).map(t=>String(t.label||t.value||"").trim()).filter(Boolean).join(", ")}function xk(e={}){const t=new URLSearchParams;t.set("screen","plans");for(const[r,n]of Object.entries(e)){const s=String(n||"").trim();s&&t.set(r,s)}return`/?${t.toString()}`}function fd(e,t){const r=String(t||"").trim();if(!r.startsWith("/")||r==="/")return e;try{const n=new URL(e,"https://taskforce.local");return n.searchParams.set("next",r),`${n.pathname}${n.search}${n.hash}`}catch{return e}}function rA({config:e={},initialTaskId:t,initialActivityEntryId:r,onTaskCountChange:n,onHeaderMouseDown:s,isDragging:i,onClose:l,mode:c="standalone"}){const d=SA(),f=o.useMemo(()=>new URLSearchParams(d.search),[d.search]),p=String(f.get(wi.workspaceId)||"").trim()||void 0,g=String(t||f.get(wi.task)||"").trim()||void 0,h=String(r||f.get(wi.activity)||f.get(wi.comment)||"").trim()||void 0,y=String(f.get("planId")||"").trim(),k=String(f.get("planVersionId")||"").trim(),b=String(f.get("interval")||"").trim(),C=d.pathname==="/pricing",S=d.pathname==="/plans",w=d.pathname==="/"&&String(f.get("screen")||"").trim().toLowerCase()==="plans",T=xk(),E=xk({gate:"plan_selection_required"}),x=bA(),[N,v]=o.useState(""),[V,_]=o.useState(""),[j,F]=o.useState(""),[z,M]=o.useState(""),[O,Z]=o.useState("login"),[U,ve]=o.useState(""),[te,ce]=o.useState(!1),[Le,Ie]=o.useState(null),[Ye,ge]=o.useState(null),[he,Ae]=o.useState(null),[ye,Ne]=o.useState(!1),[ae,q]=o.useState(""),[W,K]=o.useState(""),[Re,we]=o.useState(null),[ie,Q]=o.useState(null),[H,se]=o.useState("unknown"),[Pe,ue]=o.useState(!1),[ne,Me]=o.useState([]),[pe,le]=o.useState(null),[Ce,P]=o.useState(null),[ee,Se]=o.useState(null),[_e,ke]=o.useState(!1),[Ze,st]=o.useState(0),[at,oe]=o.useState(0),[We,G]=o.useState(()=>Date.now()),[Be,Xe]=o.useState("core"),[ze,qe]=o.useState(!1),[Te,fe]=o.useState(null),[Ee,$e]=o.useState(null),[rt,kt]=o.useState(""),[xe,St]=o.useState(""),[jt,$]=o.useState("local"),[Ke,Qe]=o.useState("details"),[Ge,At]=o.useState([]),[Nt,Bt]=o.useState(""),[Qt,Xt]=o.useState(!1),[nt,Mt]=o.useState(null),[ur,je]=o.useState(!1),[ot,pt]=o.useState(null),[Ve,lt]=o.useState(!1),It=o.useRef(!1),wt=o.useMemo(()=>qC(),[]),[$t,Yt]=o.useState(wt),[qt,er]=o.useState(()=>wt.find(de=>de.isDefaultStarter)?.id||wt[0]?.id||""),[_t,Dt]=o.useState(()=>tA(wt.find(de=>de.isDefaultStarter)||wt[0]||null)),[Tt,Xr]=o.useState(!1),[Rr,la]=o.useState(null),[sa,ea]=o.useState(!1),[Ur,Ft]=o.useState(null),[ft,Rt]=o.useState(!1),_r=RN({config:e,initialTaskId:g,initialActivityEntryId:h,requestedWorkspaceId:p,onTaskCountChange:n,onClose:l}),{runtimeMode:u,workspaceSwitchingEnabled:Pt,currentWorkspaceId:pr,cloudAuthConfigured:Yr,authRequiredForApi:tr,authBlocked:$r,isAuthenticated:Lt,hasBetaAccess:zr,authSessionResolved:Ir,setupState:Kt,runtimeCapabilities:Jr,refreshSetupContext:Br,retryBootstrapChecks:nr,createWorkspace:Zr,saveWorkspaceProfile:He,fetchWorkspaces:Ca,applyWorkspaceSyncStateSnapshot:da,workspaceCloudSyncEnabled:ir,workspaceSyncPhase:ut,workspaceSyncSetupIntent:ka,workspaceSyncSummary:Wt,workspaceSyncRecommendedAction:rr,workspaceSyncBusy:oa,workspaceLastErrorMessage:Mr,retryWorkspaceCloudSync:vn,settingsModel:En,fetchTasks:Ga,bootstrapState:Hr,loginWithCredentials:Na,beginOAuthLogin:ta,availableAuthProviders:ua,registerWithCredentials:Qr,requestEmailVerification:br,confirmEmailVerification:yr,requestPasswordReset:Gr,confirmPasswordReset:Kr,inspectInviteAcceptance:dt,acceptInviteWithToken:Ma,joinInviteWithToken:Zt,authUserEmail:Sr,currentTheme:va,logout:Ya}=_r,Ar=o.useCallback(async(de,yt)=>{const ar=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:de,stateKey:"workspace-sync",patch:yt})}),gr=await ar.json().catch(()=>({}));if(!ar.ok||gr?.success===!1)throw new Error(gr?.error||`Failed to configure workspace sync (${ar.status})`);return gr},[]),ma=o.useMemo(()=>$t.find(de=>de.id===qt)||$t.find(de=>de.isDefaultStarter)||$t[0]||null,[qt,$t]);IA(va);const me=dv,it=o.useMemo(()=>{const de=String(e.cloudAuthBaseUrl||e.apiBaseUrl||"").trim();return de?de.replace(/\/+$/,""):""},[e.apiBaseUrl,e.cloudAuthBaseUrl]),mt=u==="cloud"||Jr?.runtimeMode==="cloud",ht=!mt&&Yr&&!!it,Ht=typeof window<"u"&&/^app\./i.test(window.location.hostname),sr=u==="cloud"&&tr,wa=u==="cloud"&&$r,fr=d.pathname==="/login",or=d.pathname==="/setup",Tr=d.pathname==="/coming-soon",ha="/setup?step=workspace&source=cloud&postAuth=select-cloud-workspace",ba=!mt&&jt==="cloud",nn=ba&&ht,kr=o.useMemo(()=>{if(ot)return ot;if(ka!=="attach-cloud-import")return null;const de=String(pr||"").trim();if(!de||de.toLowerCase()==="default")return null;const yt=Ge.find(ar=>ar.id===de);return{workspaceId:de,name:yt?.name||de}},[Ge,pr,ot,ka]),ho=!!(kr&&pr===kr.workspaceId),wn=!!(kr&&ho&&ut==="error"),Bn=!!(kr&&ho&&ir&&ut==="active"&&!oa),Wn=o.useMemo(()=>{if(!kr)return[];const de=ze?"In progress":"Complete",yt=wn?"Needs attention":oa||ut==="attach-cloud"?"In progress":ut==="active"?"Complete":"Waiting",ar=Ve?"In progress":Bn?"Ready":"Waiting";return[`Connect workspace: ${de}`,`Import cloud data: ${yt}`,`Open local workspace: ${ar}`]},[kr,ze,wn,oa,ut,Ve,Bn]),Ta=Ht?(!Lt||$r)&&!C&&!S&&!w:(sr&&!Lt||wa)&&!C&&!S&&!w,Ms=u==="cloud"&&Lt&&!zr&&!C&&!S&&!w,Vs=u==="cloud"&&Lt&&Ir&&Ur?.canAccessApp===!1&&Ur?.canAccessPlans!==!1&&!C&&!S&&!w,Ks=u==="cloud"&&Lt&&(!Ir||!ft),ys=Yr,$n=o.useMemo(()=>{switch(O){case"register":return"Create Account | Taskforce";case"verify":return"Verify Email | Taskforce";case"forgot":return"Reset Password | Taskforce";case"reset":return"Set New Password | Taskforce";case"invite":return"Accept Invite | Taskforce";default:return"Sign In | Taskforce"}},[O]),Ia=o.useMemo(()=>String(new URLSearchParams(d.search).get("step")||"").trim().toLowerCase(),[d.search]),fn=o.useMemo(()=>String(new URLSearchParams(d.search).get("intent")||"").trim().toLowerCase(),[d.search]),xa=or&&Ia==="workspace"&&fn==="create-workspace",ks=c!=="widget"&&Hr.authPending&&!fr&&!or&&!C&&!S&&!w&&(u==="cloud"||Ht),sn=o.useMemo(()=>See({setupState:Kt?{globalSetupState:Kt.globalSetupState,workspaceSetupState:Kt.workspaceSetupState,runtimeMode:Kt.runtimeMode,workspaceId:Kt.workspaceId,mode:Kt.mode,forceSetup:Kt.forceSetup,forceGlobalSetup:Kt.forceGlobalSetup,forceWorkspaceSetup:Kt.forceWorkspaceSetup}:null,runtimeMode:u,isAuthenticated:Lt}),[Kt,u,Lt]),mn=sn.setupGateActive,on=sn.needsGlobalSetup,Zn=sn.needsWorkspaceSetup,Da=sn.hasSetupReadError,qs=c!=="widget"&&Hr.auth.resolved&&!Ta&&!Ms&&!C&&!S&&!w&&!fr&&Hr.appPending&&(or||u==="cloud"||Ht),vt=u==="cloud"&&ye&&!w,hr=Hr.subtitle,ga=xa||or&&!!kr||or&&mn&&(Da||on||Zn),ia=o.useMemo(()=>ks?"auth-bootstrap":vt||qs?"app-bootstrap":fr?"login":Ta&&!fr?"login-redirect":Tr&&Ms?"coming-soon":ga?"guided-setup":"app",[Tr,fr,Ms,Ta,vt,ks,qs,ga]),Za=o.useCallback((de,yt,ar)=>{const gr=String(de||"").trim().toLowerCase(),Pr=String(yt||"").trim().toLowerCase();return!!(!gr||gr==="system default workspace"||Pr&&gr===Pr)},[]);o.useEffect(()=>{const de=Kt?.mode==="operations"?"operations":"core";Xe(de)},[Kt?.mode]),o.useEffect(()=>{if(u!=="cloud"||!Lt){Ft(null),Rt(!1);return}if(!Ir){Ft(null),Rt(!1);return}Ft(null),Rt(!1);let de=!1;return(async()=>{try{const yt=await fetch("/api/taskforce/account/access-status",{method:"GET",credentials:"include"}),ar=await yt.json().catch(()=>({}));if(de)return;if(!yt.ok){Ft(null),Rt(!0);return}const gr=String(ar?.gate||"").trim().toLowerCase();if(gr!=="ok"&&gr!=="plan_selection_required"&&gr!=="checkout_pending"&&gr!=="misconfigured"&&gr!=="missing_entitlement"){Ft(null),Rt(!0);return}Ft({gate:gr,canAccessApp:ar?.canAccessApp===!0,canAccessPlans:ar?.canAccessPlans!==!1,message:typeof ar?.message=="string"?ar.message:null}),Rt(!0)}catch{de||(Ft(null),Rt(!0))}})(),()=>{de=!0}},[Ir,Lt,u,d.pathname,d.search]),o.useEffect(()=>{if(xa){kt(""),St("");return}if(!Kt)return;const de=String(Kt.workspace?.name||"").trim(),yt=String(Kt.suggestedWorkspaceName||"").trim(),ar=Za(de,Kt.workspaceId,Kt.workspace?.description)?yt:de;kt(ar||yt||de),St(String(Kt.workspace?.description||""))},[Kt?.workspace?.name,Kt?.workspace?.description,Kt?.suggestedWorkspaceName,Kt?.workspaceId,xa,Za]),o.useEffect(()=>{if(!or||Ia!=="workspace")return;if(Qe("details"),kr&&ht){$("cloud"),je(!1);return}if(String(new URLSearchParams(d.search).get("source")||"").trim().toLowerCase()==="cloud"&&ht){$("cloud"),je(!1);return}$("local")},[kr,ht,or,d.search,Ia]);const Ys=o.useCallback(async()=>{if(!ht||!Lt){At([]),Bt("");return}Xt(!0),Mt(null);try{const de=await fetch(`${it}/api/taskforce/workspaces`,{method:"GET",credentials:"include"}),yt=await de.json().catch(()=>({}));if(!de.ok||yt?.success===!1){At([]),Bt(""),Mt(yt?.error||`Failed to load cloud projects (${de.status})`);return}const ar=Array.isArray(yt?.workspaces)?yt.workspaces.map(gr=>({id:String(gr?.id||"").trim(),name:String(gr?.name||gr?.id||"").trim(),description:typeof gr?.description=="string"?gr.description:null})).filter(gr=>gr.id.length>0):[];At(ar),Bt(gr=>gr&&ar.some(Pr=>Pr.id===gr)?gr:ar[0]?.id||"")}catch{At([]),Bt(""),Mt("Failed to load cloud projects.")}finally{Xt(!1)}},[ht,Lt,it]);o.useEffect(()=>{jt==="cloud"&&Ys()},[Ys,jt]),o.useEffect(()=>{if(!or||Ia!=="workspace"||jt==="cloud")return;let de=!1;return Xr(!0),la(null),fetch("/api/taskforce/taxonomy-library",{method:"GET",credentials:"include"}).then(async yt=>{if(!yt.ok)throw new Error(`Failed to load setup libraries (${yt.status})`);const ar=await yt.json().catch(()=>({})),gr=Array.isArray(ar?.packs)?ar.packs:[];de||gr.length===0||(Yt(gr),er(Pr=>gr.some(ra=>ra.id===Pr)?Pr:gr.find(ra=>ra.isDefaultStarter)?.id||gr[0]?.id||""))}).catch(yt=>{de||(Yt(wt),la(yt instanceof Error?yt.message:"Failed to load setup libraries."))}).finally(()=>{de||Xr(!1)}),()=>{de=!0}},[wt,or,Ia,jt]),o.useEffect(()=>{Dt(tA(ma))},[qt,ma]),o.useEffect(()=>{jt==="cloud"&&Qe("details")},[jt]),o.useEffect(()=>{nn||(pt(null),lt(!1),It.current=!1)},[nn]),o.useEffect(()=>{!wn||!kr||($e(null),fe(Mr||`Failed to import "${kr.name}" from cloud. Retry import to continue.`))},[kr,wn,Mr]),o.useEffect(()=>{if(!Bn||!kr||It.current)return;let de=!1;return It.current=!0,lt(!0),fe(null),$e(`Workspace import complete. Opening ${kr.name}...`),(async()=>{try{if(await Br(),await Promise.all([Ca(),Ga(!0)]),de)return;await Ar(kr.workspaceId,{setupIntent:null}),da({enabled:ir,phase:ut,setupIntent:null}),pt(null),x("/",{replace:!0})}catch{if(de)return;$e(null),fe(`Imported "${kr.name}" but failed to finish opening it.`),lt(!1),It.current=!1}})(),()=>{de=!0}},[kr,da,Ga,Ca,Bn,x,Ar,Br]);const ca=o.useMemo(()=>{const de=new URLSearchParams(d.search).get("next")||"/";if(de.startsWith("/"))return de==="/login"?"/":de;try{const yt=new URL(de),ar=yt.hostname.toLowerCase(),gr=ar==="localhost"||ar==="127.0.0.1"||ar==="::1",Pr=ar==="taskforcehq.ai"||ar.endsWith(".taskforcehq.ai");if((yt.protocol==="http:"||yt.protocol==="https:")&&(gr||Pr))return yt.toString()}catch{return"/"}return"/"},[d.search]),vs=o.useMemo(()=>ca.startsWith("/")?ca:"/",[ca]),Fa=o.useCallback((de,yt)=>{if(de){if(de.startsWith("/")){x(de,{replace:yt?.replace===!0});return}typeof window<"u"&&(yt?.replace===!0?window.location.replace(de):window.location.assign(de))}},[x]),Jn=o.useMemo(()=>{try{const de=new URL(vs,"https://taskforce.local");return de.pathname==="/setup"&&de.searchParams.get("step")==="workspace"&&de.searchParams.get("source")==="cloud"&&de.searchParams.get("postAuth")==="select-cloud-workspace"}catch{return!1}},[vs]),La=o.useCallback((de=ca)=>{const yt=Jn?ha:"/setup?step=workspace";return Jn?yt:fd(yt,de)},[ca,Jn]),vr=b==="year"?"year":"month",Ja=o.useCallback(de=>!!(de?.planSelectionRequired||de?.checkoutPending||de?.commercialState==="pending_plan_selection"||de?.commercialState==="checkout_pending"),[]),Qn=o.useCallback(de=>de?.planSelectionRequired||de?.commercialState==="pending_plan_selection"?fd(E,ca):de?.checkoutPending||de?.commercialState==="checkout_pending"?fd(xk({gate:"checkout_pending",checkout:k?"start":null,planId:y||null,planVersionId:k||null,interval:k?vr:null}),ca):ca,[ca,E,vr,y,k]),cn=o.useMemo(()=>{const de=String(new URLSearchParams(d.search).get("mode")||"").trim().toLowerCase();return de==="register"?ys?"register":"login":de==="verify"||de==="forgot"||de==="reset"||de==="invite"?de:"login"},[ys,d.search]),bn=o.useMemo(()=>String(new URLSearchParams(d.search).get("token")||"").trim(),[d.search]),Ra=o.useCallback(de=>{const yt=new URLSearchParams(d.search),ar=de==="register"&&!ys?"login":de;ar==="login"?yt.delete("mode"):yt.set("mode",ar);const gr=yt.toString();x(`/login${gr?`?${gr}`:""}`,{replace:!0})},[ys,d.search,x]);o.useEffect(()=>{fr&&(Z(cn),cn==="verify"&&bn&&ve(bn),cn==="reset"&&bn&&q(bn),cn==="invite"&&bn&&K(bn))},[fr,cn,bn]),o.useEffect(()=>{O!=="verify"&&(fr&&cn==="verify"||(ce(!1),Ie(null),ge(null)))},[O,fr,cn]),o.useEffect(()=>{O!=="register"&&M("")},[O]),o.useEffect(()=>{if(!he||!Lt||!he.commercialOnboardingGate&&(!Ir||Ks))return;const de=!he.commercialOnboardingGate&&he.workspaceSetupRequired?La():he.path,yt=`${d.pathname}${d.search}${d.hash||""}`;if(de.startsWith("/")){yt!==de&&x(de,{replace:!0});return}Fa(de,{replace:!0})},[Ir,Ks,Lt,d.hash,d.pathname,d.search,x,Fa,he,La]),o.useEffect(()=>{if(!ye||!Ir)return;if(!Lt){Ne(!1),Ae(null);return}if(ft&&Ur?.canAccessApp===!0){v(""),_(""),F(""),M(""),Ae(null),Ne(!1);return}const de=he?.commercialOnboardingGate?he.path:E,yt=`${d.pathname}${d.search}${d.hash||""}`;if(de.startsWith("/")){yt!==de&&x(de,{replace:!0});return}Fa(de,{replace:!0})},[Ur?.canAccessApp,ft,Ir,ye,Lt,d.hash,d.pathname,d.search,x,Fa,he,E]),o.useEffect(()=>{if(!he||!Lt)return;const de=!he.commercialOnboardingGate&&he.workspaceSetupRequired?La():he.path;`${d.pathname}${d.search}${d.hash||""}`===de&&(he.commercialOnboardingGate||(v(""),_(""),F(""),M(""),Ae(null)))},[d.hash,d.pathname,d.search,Lt,he,La,u]),o.useEffect(()=>{fr&&(document.title=$n)},[$n,fr]),o.useEffect(()=>{if(!fr||O!=="invite"||!W.trim())return;let de=!0;return(async()=>{const yt=await dt(W);if(de)if(yt.success){we(yt.email||null),Q(yt.workspaceId||null),ue(yt.passwordRequired===!0);const ar=(yt.availableMethods||[]).filter(ra=>ra==="google"||ra==="github"||ra==="apple");Me(yt.inviteeState==="pending_setup"?ar:[]);const gr=!!(Lt&&Sr&&yt.email&&Sr.trim().toLowerCase()===yt.email.trim().toLowerCase()),Pr=yt.passwordRequired===!0?"new_user":gr?"existing_user_ready":"existing_user_signed_out";se(Pr),le(Pr==="new_user"?"Create your account password to join this workspace.":Pr==="existing_user_ready"?"Invite ready. Confirm to join this workspace.":"Sign in with the invited account to join this workspace."),P(null),Se(null)}else we(null),Q(null),se("invalid"),ue(!1),Me([]),P(ln(yt)),Se(yt.code||yt.state||null)})(),()=>{de=!1}},[fr,O,W,dt,Lt,Sr]),o.useEffect(()=>{O==="invite"&&H==="existing_user_signed_out"&&Re&&v(de=>de.trim()?de:Re)},[O,H,Re]),o.useEffect(()=>{if(!(Ze>Date.now()||at>Date.now()))return;const yt=window.setInterval(()=>G(Date.now()),1e3);return()=>window.clearInterval(yt)},[Ze,at]);const Zs=Math.max(0,Math.ceil((Ze-We)/1e3)),Xn=Math.max(0,Math.ceil((at-We)/1e3)),es=Zs>0,pa=Xn>0,Sn=o.useMemo(()=>YI(),[]),ln=de=>{const yt=de.error||"Request failed.",ar=de.code||de.state;return ar?`[${ar}] ${yt}`:yt},An=de=>de?.deliveryAttempted===!1?de?.intro||"If that account exists and still needs verification, we sent an email.":de?.emailSent===!1?`Verification email failed to send. ${de?.emailError||"Try Resend Verification again."}`:"Verification email resent.",ws=de=>de?.deliveryAttempted===!1?"If that account exists, we sent password reset instructions.":de?.emailSent===!1?`Password reset email failed to send. ${de?.emailError||"Try again in a minute."}`:"Password reset instructions sent.";o.useEffect(()=>{if(c==="widget"||fr&&_e)return;const de=`${d.pathname}${d.search}${d.hash||""}`,yt=or?ca:de,ar=u==="cloud"&&Lt&&ft&&Ur?.canAccessApp===!1&&Ur?.canAccessPlans!==!1;if(Hr.workspace.pending&&!ar)return;if(Ms){Tr||x("/coming-soon",{replace:!0});return}if(Tr&&!Ms){x("/",{replace:!0});return}if(Ta){if(!fr){const Pr=`${d.pathname}${d.search}${d.hash}`;x(`/login?next=${encodeURIComponent(Pr||"/")}`,{replace:!0});return}return}else{const Pr=fr&&O==="invite"&&W.trim().length>0;if(fr&&Lt&&!Pr&&(!!he||Hr.workspace.pending||O==="register"||O==="verify"||!Hr.config.loaded||Ks))return;fr&&Lt&&!Pr&&Fa(ca,{replace:!0})}if(!(fr&&!Lt||he&&Lt||fr&&Lt&&(O==="register"||O==="verify"||O==="invite"&&W.trim().length>0))&&!ye&&!w){if(Vs){if(!w){const Pr=encodeURIComponent(String(Ur?.gate||"plan_selection_required"));x(fd(`/?screen=plans&gate=${Pr}`,de),{replace:!0})}return}if(kr){or&&Ia==="workspace"&&new URLSearchParams(d.search).get("source")==="cloud"||x(ha,{replace:!0});return}if(!(w&&Ks)&&!(w&&u==="cloud"&&ft&&Ur?.canAccessApp===!1&&Ur?.canAccessPlans!==!1)){if(mn){if(Da){(!or||Ia!=="error")&&x(fd("/setup?step=error",yt),{replace:!0});return}if(on){(!or||Ia!=="global")&&x(fd("/setup?step=global",yt),{replace:!0});return}if(Zn){(!or||Ia!=="workspace")&&x(La(yt),{replace:!0});return}or&&Fa(ca,{replace:!0});return}or&&Kt&&!xa&&Fa(ca,{replace:!0})}}},[c,Ta,Ms,Vs,fr,or,Tr,S,w,Ur,Ur?.gate,ft,O,ye,Ks,mn,Kt,Da,xa,kr,on,Zn,Ia,Hr,u,_e,Lt,ft,W,d.pathname,d.search,d.hash,x,Fa,vs,ca,he,ha]),o.useEffect(()=>{if(c==="widget"||u!=="local"||!Hr.config.loaded||fr||or)return;const de=String(pr||"").trim().toLowerCase();if(!de||de==="default"){const yt=`${d.pathname}${d.search}${d.hash||""}`;x(fd("/setup?step=workspace",yt),{replace:!0})}},[c,u,Hr.config.loaded,fr,or,pr,d.hash,d.pathname,d.search,x]);const Oa=o.useCallback(async()=>{ea(!0);try{await nr()}finally{ea(!1)}},[nr]),Va=o.useCallback(async()=>{await Ya(),x("/login",{replace:!0})},[Ya,x]);if(c==="widget")return a.jsx(iG,{..._r,initialActivityEntryId:h,onHeaderMouseDown:s,isDragging:i,onClose:l});if(C){const de=new URLSearchParams(d.search);return de.set("screen","plans"),a.jsx(ib,{to:`/?${de.toString()}${d.hash||""}`,replace:!0})}if(S){const de=new URLSearchParams(d.search);return de.set("screen","plans"),a.jsx(ib,{to:`/?${de.toString()}${d.hash||""}`,replace:!0})}if(ia==="auth-bootstrap")return a.jsx("div",{className:Fr.standaloneWrapper,"data-theme":va,children:a.jsx("div",{className:Je.loginView,children:a.jsxs("div",{className:Je.loginCard,children:[a.jsxs("div",{className:Je.authBrandRow,children:[a.jsx("img",{src:me,alt:"Taskforce",className:Je.loginLogo}),a.jsx("h1",{className:Je.loginTitle,children:"Loading Taskforce"})]}),a.jsx("p",{className:Je.loginSubtitle,children:"Checking your session..."})]})})});if(ia==="app-bootstrap")return a.jsx("div",{className:Fr.standaloneWrapper,"data-theme":va,children:a.jsx("div",{className:Je.loginView,children:a.jsxs("div",{className:Je.loginCard,children:[a.jsxs("div",{className:Je.authBrandRow,children:[a.jsx("img",{src:me,alt:"Taskforce",className:Je.loginLogo}),a.jsx("h1",{className:Je.loginTitle,children:"Loading Taskforce"})]}),a.jsx("p",{className:Je.loginSubtitle,children:hr}),Hr.stalled&&a.jsxs(a.Fragment,{children:[a.jsx("p",{className:Je.loginError,children:Hr.error||"Startup checks timed out."}),a.jsx("button",{className:R.submitBtn,disabled:sa,onClick:Oa,children:sa?"Retrying...":"Retry checks"}),mt&&a.jsx("button",{className:R.cancelBtn,disabled:sa,onClick:Va,children:"Go to sign-in"})]})]})})});if(ia==="login")return a.jsx("div",{className:Fr.standaloneWrapper,"data-theme":va,children:a.jsx("div",{className:Je.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${_k})`},children:a.jsxs("div",{className:Je.loginCard,children:[!mt&&!Ta&&a.jsx("button",{className:Je.loginCloseBtn,"aria-label":"Close sign in","data-testid":"auth-close-button",onClick:()=>x(vs,{replace:!0}),children:"×"}),a.jsxs("div",{className:Je.authBrandRow,children:[a.jsx("img",{src:me,alt:"Taskforce",className:Je.loginLogo}),a.jsxs("h1",{className:Je.loginTitle,children:["TASKFORCE ",a.jsx("span",{className:Je.loginTitleAccent,children:"HQ"})]})]}),a.jsxs("p",{className:Je.loginSubtitle,children:[O==="login"&&"Sign in with your account credentials.",O==="register"&&"Create your Taskforce account.",O==="verify"&&"Enter your verification token.",O==="forgot"&&"Request a password reset link.",O==="reset"&&"Set a new password using your reset token.",O==="invite"&&(H==="existing_user_ready"?`You've been invited to join ${ie||"this workspace"}.`:H==="existing_user_signed_out"?"Sign in to join this workspace.":"Create your account to join this workspace.")]}),(O==="login"||O==="register"||O==="verify"||O==="forgot"||O==="invite"&&H==="existing_user_signed_out")&&a.jsxs("label",{className:Je.loginField,children:[a.jsx("span",{className:Je.loginFieldLabel,children:"Email"}),a.jsx("input",{className:`${R.input} ${Je.loginInput}`,type:"email",value:N,placeholder:"Email",autoComplete:"email","data-testid":"auth-email-input",onChange:de=>v(de.target.value)})]}),O==="register"&&a.jsxs("label",{className:Je.loginField,children:[a.jsx("span",{className:Je.loginFieldLabel,children:"Display name"}),a.jsx("input",{className:`${R.input} ${Je.loginInput}`,type:"text",value:V,placeholder:"Display name",autoComplete:"nickname","data-testid":"auth-display-name-input",onChange:de=>_(de.target.value)})]}),(O==="login"||O==="register"||O==="reset"||O==="invite"&&(Pe||H==="existing_user_signed_out"))&&a.jsxs("label",{className:Je.loginField,children:[a.jsx("span",{className:Je.loginFieldLabel,children:O==="reset"?"New password":O==="invite"&&Pe?"Create password":"Password"}),a.jsx("input",{className:`${R.input} ${Je.loginInput}`,type:"password",value:j,placeholder:O==="reset"?"New password":O==="invite"&&Pe?"Create password":"Password",autoComplete:O==="register"||O==="reset"||O==="invite"&&Pe?"new-password":"current-password","data-testid":"auth-password-input",onChange:de=>F(de.target.value)})]}),(O==="register"||O==="invite"&&Pe)&&a.jsx(a.Fragment,{children:a.jsxs("label",{className:Je.loginField,children:[a.jsx("span",{className:Je.loginFieldLabel,children:"Confirm password"}),a.jsx("input",{className:`${R.input} ${Je.loginInput}`,type:"password",value:z,placeholder:"Confirm password",autoComplete:"new-password","data-testid":"auth-confirm-password-input",onChange:de=>M(de.target.value)})]})}),(O==="register"||O==="invite"&&Pe)&&a.jsx("p",{className:Je.loginSubtitle,children:Sn.join(" ")}),O==="verify"&&a.jsxs("label",{className:Je.loginField,children:[a.jsx("span",{className:Je.loginFieldLabel,children:"Verification token"}),a.jsx("input",{className:`${R.input} ${Je.loginInput}`,type:"text",value:U,placeholder:"Verification token",autoComplete:"one-time-code","data-testid":"auth-verification-token-input",onChange:de=>ve(de.target.value)})]}),O==="reset"&&a.jsxs("label",{className:Je.loginField,children:[a.jsx("span",{className:Je.loginFieldLabel,children:"Reset token"}),a.jsx("input",{className:`${R.input} ${Je.loginInput}`,type:"text",value:ae,placeholder:"Reset token",autoComplete:"one-time-code","data-testid":"auth-reset-token-input",onChange:de=>q(de.target.value)})]}),O==="invite"&&a.jsxs(a.Fragment,{children:[a.jsxs("label",{className:Je.loginField,children:[a.jsx("span",{className:Je.loginFieldLabel,children:"Invite token"}),a.jsx("input",{className:`${R.input} ${Je.loginInput}`,type:"text",value:W,placeholder:"Invite token","data-testid":"auth-invite-token-input",onChange:de=>K(de.target.value)})]}),Re&&a.jsxs("p",{className:Je.loginSubtitle,children:["Invite for: ",a.jsx("strong",{children:Re}),ie?` · Workspace: ${ie}`:""]})]}),pe&&a.jsx("p",{className:Je.loginSubtitle,children:pe}),Ce&&a.jsx("p",{className:Je.loginError,children:Ce}),O==="login"&&ee==="EMAIL_NOT_VERIFIED"&&N.trim()&&a.jsx("button",{className:Je.authModeLink,disabled:_e||es,onClick:async()=>{ke(!0),le(null);const de=await br(N);de.success?(st(Date.now()+3e4),Ra("verify"),de.verificationToken&&ve(de.verificationToken),le(An(de)),P(null),Se(null)):P(ln(de)),ke(!1)},children:es?`Resend in ${Zs}s`:"Resend Verification Email"}),a.jsx("div",{className:Je.authPrimaryActions,role:"group","aria-label":"Primary authentication action",children:a.jsx("button",{className:`${R.submitBtn} ${Je.loginPrimaryBtn}`,disabled:_e||O==="forgot"&&pa,"data-testid":"auth-submit-button",onClick:async()=>{if(ke(!0),le(null),P(null),Se(null),O==="register"&&!V.trim()){P("Display name is required."),ke(!1);return}if(O==="register"){const yt=cv(j,{email:N,displayName:V});if(!yt.ok){P(yt.message||"Password does not meet the password policy."),Se(yt.code||null),ke(!1);return}if(j!==z){P("Passwords do not match."),Se("PASSWORD_CONFIRMATION_MISMATCH"),ke(!1);return}}let de={success:!1};if(O==="login"?de=await Na(N,j):O==="register"?de=await Qr(N,j,{displayName:V,planId:y||void 0,planVersionId:k||void 0,interval:b||void 0}):O==="verify"?de=await yr(U):O==="forgot"?de=await Gr(N):O==="reset"?de=await Kr(ae,j):O==="invite"&&(H==="existing_user_signed_out"?de=await Na(N,j):de=Pe?await Ma(W,j):await Zt(W)),de.success)if(O==="register"){const yt=Qn(de),ar=Ja(de);de.verificationRequired?(ce(!!de.workspaceSetupRequired),Ie(ar?String(de.commercialState||"").trim()||(de.planSelectionRequired?"pending_plan_selection":"checkout_pending"):null),ge(yt),de.verificationToken&&ve(de.verificationToken),st(Date.now()+3e4),Ra("verify"),le(de.emailSent===!1?`Account created, but verification email failed to send. ${de.emailError||"Try Resend Verification again."}`:"Account created. Check your email for verification instructions.")):(Ne(ar),Ae({path:yt,workspaceSetupRequired:!!de.workspaceSetupRequired,commercialOnboardingGate:ar}))}else if(O==="verify"){await nr();const yt=Le==="pending_plan_selection"||Le==="checkout_pending";Ne(yt),Ae({path:Ye||ca,workspaceSetupRequired:te,commercialOnboardingGate:yt})}else if(O==="forgot"){const yt=de.deliveryAttempted===!0&&de.emailSent===!1;de.resetToken&&q(de.resetToken),le(ws(de)),yt||(oe(Date.now()+3e4),Ra("reset"))}else if(O==="reset")Ra("login"),le("Password updated. Sign in with your new password.");else if(O==="invite"){if(H==="existing_user_signed_out"){const yt=String(Re||"").trim().toLowerCase(),ar=N.trim().toLowerCase();if(yt&&ar===yt){Z("invite"),se("existing_user_ready"),F(""),M(""),le("Signed in. Review the invite details to continue."),P(null),Se(null),ke(!1);return}yt&&v(Re||""),se("existing_user_signed_out"),F(""),M(""),le(yt?`Signed in, but this invite is for ${Re}. Sign in with that account to continue.`:"Signed in, but this invite requires the invited account. Sign in with that account to continue."),P("Sign in with the invited account to join this workspace."),Se("INVITE_ACCOUNT_MISMATCH"),ke(!1);return}if(de.workspaceSetupRequired){x(La(),{replace:!0}),ke(!1);return}Fa(ca,{replace:!0})}else if(O==="login"){if(W.trim()){Z("invite"),F(""),M(""),le("Signed in. Review the invite details to continue."),ke(!1);return}if(de.workspaceSetupRequired){x(La(),{replace:!0}),ke(!1);return}v(""),_(""),F(""),M(""),Fa(ca,{replace:!0})}else v(""),_(""),F(""),M(""),Fa(ca,{replace:!0});else{if(O==="register"&&(de.code==="SIGNUP_PLAN_NOT_ENABLED"||de.code==="SIGNUP_PLAN_VERSION_NOT_FOUND"||de.code==="SIGNUP_PLAN_VERSION_REQUIRED")){x(E,{replace:!0}),ke(!1);return}if(P(ln(de)),Se(de.code||null),O==="login"&&(de.code==="WORKSPACE_NOT_FOUND"||de.code==="WORKSPACE_ID_REQUIRED")){x("/setup?step=workspace",{replace:!0}),ke(!1);return}if(O==="login"&&de.code==="EMAIL_NOT_VERIFIED"&&N.trim()){const yt=await br(N);yt.success&&(st(Date.now()+3e4),Ra("verify"),yt.verificationToken&&ve(yt.verificationToken),le(An({...yt,intro:"If that account exists and still needs verification, we sent an email."})),P(null),Se(null))}O==="register"&&de.code==="EMAIL_ALREADY_EXISTS_UNVERIFIED"&&N.trim()&&(st(Date.now()+3e4),Ra("verify"),de.verificationToken&&ve(de.verificationToken),le(de.emailSent===!1?`This email already has an unverified account, but verification email delivery failed. ${de.emailError||"Try Resend Verification again."}`:"This email already has an unverified account. Check your email for verification instructions."),P(null),Se(null))}ke(!1)},children:_e?"Working...":O==="login"?"Sign In":O==="register"?"Create Account":O==="verify"?"Verify Email":O==="forgot"?pa?`Retry in ${Xn}s`:"Send Reset Link":O==="reset"?"Reset Password":H==="existing_user_signed_out"?"Sign In to Continue":Pe?"Create Account and Join":"Join Workspace"})}),(O==="login"||O==="register")&&ua.length>0&&a.jsxs("div",{className:Je.oauthProviders,children:[a.jsx("div",{className:Je.oauthDivider,children:a.jsx("span",{children:"or continue with"})}),a.jsxs("div",{className:Je.oauthButtons,children:[ua.includes("google")&&a.jsx("button",{type:"button",className:Je.oauthButton,disabled:_e,onClick:()=>ta("google",ca),"aria-label":"Continue with Google",children:"Google"}),ua.includes("github")&&a.jsx("button",{type:"button",className:Je.oauthButton,disabled:_e,onClick:()=>ta("github",ca),"aria-label":"Continue with GitHub",children:"GitHub"}),ua.includes("apple")&&a.jsx("button",{type:"button",className:Je.oauthButton,disabled:_e,onClick:()=>ta("apple",ca),"aria-label":"Continue with Apple",children:"Apple"})]})]}),O==="invite"&&H==="new_user"&&ne.length>0&&a.jsxs("div",{className:Je.oauthProviders,children:[a.jsx("div",{className:Je.oauthDivider,children:a.jsx("span",{children:"or join with"})}),a.jsxs("div",{className:Je.oauthButtons,children:[ne.includes("google")&&a.jsx("button",{type:"button",className:Je.oauthButton,disabled:_e,onClick:()=>ta("google","/",W),"aria-label":"Join with Google",children:"Google"}),ne.includes("github")&&a.jsx("button",{type:"button",className:Je.oauthButton,disabled:_e,onClick:()=>ta("github","/",W),"aria-label":"Join with GitHub",children:"GitHub"}),ne.includes("apple")&&a.jsx("button",{type:"button",className:Je.oauthButton,disabled:_e,onClick:()=>ta("apple","/",W),"aria-label":"Join with Apple",children:"Apple"})]})]}),O==="register"&&a.jsxs("p",{className:Je.registerConsent,children:["By creating an account, you agree to the"," ",a.jsx("a",{className:Je.registerConsentLink,href:"https://taskforcehq.ai/legal/terms/",target:"_blank",rel:"noopener noreferrer",children:"Terms of Service"})," ","and acknowledge the"," ",a.jsx("a",{className:Je.registerConsentLink,href:"https://taskforcehq.ai/legal/privacy/",target:"_blank",rel:"noopener noreferrer",children:"Privacy Policy"}),"."]}),a.jsxs("div",{className:Je.authSecondaryActions,role:"group","aria-label":"Authentication navigation",children:[ys&&(O==="login"||O==="register")&&a.jsxs("p",{className:Je.authModeSwitch,children:[O==="login"?"Need an account?":"Already have an account?"," ",a.jsx("button",{className:Je.authModeSwitchLink,disabled:_e,"data-testid":"auth-switch-mode-button",onClick:()=>{P(null),Se(null),le(null),Ra(O==="login"?"register":"login")},children:O==="login"?"Register":"Sign In"})]}),a.jsxs("div",{className:Je.authModeLinks,children:[(O==="login"||O==="register")&&a.jsxs(a.Fragment,{children:[a.jsx("button",{className:Je.authModeLink,disabled:_e||pa,"data-testid":"auth-forgot-password-button",onClick:()=>{P(null),Se(null),le(null),Ra("forgot")},children:pa?`Forgot Password (${Xn}s)`:"Forgot Password"}),a.jsx("button",{className:Je.authModeLink,disabled:_e||es,"data-testid":"auth-resend-verification-button",onClick:()=>{P(null),Se(null),le(null),Ra("verify")},children:es?`Resend Verification (${Zs}s)`:"Resend Verification"}),a.jsx("button",{className:Je.authModeLink,disabled:_e,"data-testid":"auth-accept-invite-button",onClick:()=>{P(null),Se(null),le(null),Ra("invite")},children:"Accept Invite"})]}),O!=="login"&&O!=="register"&&a.jsxs(a.Fragment,{children:[O==="verify"&&a.jsx("button",{className:Je.authModeLink,disabled:_e||es||!N.trim(),"data-testid":"auth-resend-verification-button",onClick:async()=>{ke(!0),le(null),P(null),Se(null);const de=await br(N);de.success?(st(Date.now()+3e4),de.verificationToken&&ve(de.verificationToken),le(An(de))):P(ln(de)),ke(!1)},children:es?`Resend Verification (${Zs}s)`:"Resend Verification"}),a.jsx("button",{className:Je.authModeLink,disabled:_e,"data-testid":"auth-return-sign-in-button",onClick:()=>{P(null),Se(null),le(null),Ra("login")},children:O==="verify"?"Back to Sign In":"Sign In"}),ys&&O!=="verify"&&a.jsx("button",{className:Je.authModeLink,disabled:_e,"data-testid":"auth-return-register-button",onClick:()=>{P(null),Se(null),le(null),Ra("register")},children:"Register"}),O==="reset"&&a.jsx("button",{className:Je.authModeLink,disabled:_e||pa,"data-testid":"auth-return-forgot-password-button",onClick:()=>{P(null),Se(null),le(null),Ra("forgot")},children:pa?`Forgot Password (${Xn}s)`:"Forgot Password"})]})]})]})]})})});if(ia==="login-redirect")return a.jsx("div",{className:Fr.standaloneWrapper,"data-theme":va,children:a.jsx("div",{className:Je.loginView,children:a.jsxs("div",{className:Je.loginCard,children:[a.jsxs("div",{className:Je.authBrandRow,children:[a.jsx("img",{src:me,alt:"Taskforce",className:Je.loginLogo}),a.jsx("h1",{className:Je.loginTitle,children:"Loading Taskforce"})]}),a.jsx("p",{className:Je.loginSubtitle,children:"Redirecting to sign in..."})]})})});if(ia==="coming-soon")return a.jsx("div",{className:Fr.standaloneWrapper,"data-theme":va,children:a.jsx("div",{className:Je.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${_k})`},children:a.jsxs("div",{className:Je.loginCard,children:[a.jsxs("div",{className:Je.authBrandRow,children:[a.jsx("img",{src:me,alt:"Taskforce",className:Je.loginLogo}),a.jsx("h1",{className:Je.loginTitle,children:"Beta Access"})]}),a.jsx("p",{className:Je.loginSubtitle,children:"You are signed in, but your account does not have beta access yet."}),a.jsx("p",{className:Je.loginSubtitle,children:"You will see the full app as soon as beta access is enabled."}),a.jsx("button",{className:R.cancelBtn,onClick:async()=>{await _r.logout(),x("/login",{replace:!0})},children:"Sign Out"})]})})});if(ia==="guided-setup"){const de=!xa&&(Da||Ia==="error"),yt=!xa&&!de&&(on||Ia==="global"),ar=bt(de?"setup.headingCheckFailed":yt?"setup.headingGlobalRequired":"setup.headingWorkspaceRequired"),gr=de?bt("setup.subtitleUnreadable"):yt?bt("setup.subtitleGlobalRequired"):null,Pr="Workspace",ra=mt||jt!=="cloud",Fn=ra&&Ke==="details",Qa=ra&&Ke==="library",Ai=!mt&&ht&&Fn&&!kr,Cn=Jr?.runtimeMode==="cloud"?hA:_0,si=ma?Tk(ma.categories):"",Nn=ma?Tk(ma.types):"",bs=ma?Tk(ma.priorities):"",Oo=ze?bt("setup.saving"):ba?kr?wn?"Retry Import":"Importing Workspace...":"Connect Workspace":Fn?"Continue":Qa?"Create Workspace":"Connect Workspace";return a.jsx("div",{className:Fr.standaloneWrapper,"data-theme":va,children:a.jsx("div",{className:Je.loginView,style:{backgroundImage:`linear-gradient(rgba(15, 15, 26, 0.88), rgba(15, 15, 26, 0.9)), url(${_k})`},children:a.jsxs("div",{className:Je.loginCard,children:[a.jsxs("div",{className:Je.setupHeaderRow,children:[a.jsxs("div",{className:Je.authBrandRow,children:[a.jsx("img",{src:me,alt:"Taskforce",className:Je.loginLogo}),a.jsxs("h1",{className:Je.loginTitle,children:["TASKFORCE ",a.jsx("span",{className:Je.loginTitleAccent,children:"HQ"})]})]}),Jr&&a.jsx("span",{className:Je.runtimeIconBadge,title:Jr.runtimeMode==="cloud"?"Cloud runtime":"Local runtime","aria-label":Jr.runtimeMode==="cloud"?"Cloud runtime":"Local runtime",children:Y.createElement(Cn,{size:16,"aria-hidden":!0})})]}),a.jsx("p",{className:Je.loginSubtitle,children:a.jsx("strong",{children:ar})}),gr?a.jsx("p",{className:Je.loginSubtitle,children:gr}):null,Ee&&a.jsx("p",{className:Je.loginSubtitle,children:Ee}),Te&&a.jsx("p",{className:Je.loginError,children:Te}),yt&&a.jsxs("div",{className:Je.optionGrid,children:[a.jsxs("label",{className:`${Je.authModeLink} ${Je.optionRow}`,children:[a.jsx("input",{type:"radio",name:"setup-mode",value:"core",checked:Be==="core",onChange:()=>Xe("core"),disabled:ze}),a.jsx("span",{children:bt("setup.coreModeOption",{workspaceLabel:Pr})})]}),a.jsxs("label",{className:`${Je.authModeLink} ${Je.optionRow}`,children:[a.jsx("input",{type:"radio",name:"setup-mode",value:"operations",checked:Be==="operations",onChange:()=>Xe("operations"),disabled:ze}),a.jsx("span",{children:bt("setup.operationsModeOption")})]})]}),!de&&!yt&&a.jsxs("div",{className:Je.optionGrid,children:[Ai&&a.jsxs("div",{className:Je.optionGroup,children:[a.jsxs("label",{className:`${Je.authModeLink} ${Je.optionRow}`,children:[a.jsx("input",{type:"radio",name:"workspace-setup-source",value:"local",checked:jt==="local",onChange:()=>$("local"),disabled:ze}),a.jsxs("span",{children:["Create new local ",Pr.toLowerCase()]})]}),a.jsxs("label",{className:`${Je.authModeLink} ${Je.optionRow}`,children:[a.jsx("input",{type:"radio",name:"workspace-setup-source",value:"cloud",checked:jt==="cloud",onChange:()=>$("cloud"),disabled:ze}),a.jsxs("span",{children:["Sync existing cloud ",Pr.toLowerCase()]})]})]}),ba?a.jsxs("div",{className:Je.optionGroup,children:[!kr&&!ht&&a.jsx("p",{className:Je.loginError,children:"Cloud workspace sync is unavailable right now. Switch back to local setup or refresh runtime configuration."}),!kr&&ht&&!Lt&&a.jsxs(a.Fragment,{children:[a.jsx("p",{className:Je.inlineHint,children:"Sign in to choose one of your cloud projects."}),a.jsxs("div",{className:Je.actionRowEnd,children:[a.jsx("button",{className:R.cancelBtn,disabled:ze,onClick:()=>{x(`/login?mode=login&next=${encodeURIComponent(ha)}`,{replace:!0})},children:"Sign In"}),ys&&a.jsx("button",{className:R.submitBtn,disabled:ze,onClick:()=>{x(`/login?mode=register&next=${encodeURIComponent(ha)}`,{replace:!0})},children:"Register"})]})]}),!kr&&ht&&Lt&&a.jsxs(a.Fragment,{children:[a.jsxs("select",{className:R.input,value:Nt,onChange:Vt=>Bt(Vt.target.value),disabled:ze||Qt||Ge.length===0,children:[Ge.length===0&&a.jsx("option",{value:"",children:Qt?"Loading cloud projects...":"No cloud projects found"}),Ge.map(Vt=>a.jsxs("option",{value:Vt.id,children:[Vt.name," (",Vt.id,")"]},Vt.id))]}),a.jsx("div",{className:Je.actionRowEnd,children:a.jsx("button",{className:R.cancelBtn,disabled:ze||Qt,onClick:()=>{Ys()},children:"Refresh Cloud Projects"})}),nt&&a.jsx("p",{className:Je.loginError,children:nt})]}),kr&&a.jsxs(a.Fragment,{children:[a.jsxs("p",{className:Je.inlineHint,children:['Importing "',kr.name,'" from cloud into local.']}),a.jsx("div",{className:Je.optionGroup,children:Wn.map(Vt=>a.jsx("p",{className:Je.inlineHint,children:Vt},Vt))}),a.jsx("p",{className:Je.inlineHint,children:Ve?"Finishing setup and opening your workspace.":Wt||"Pulling tasks, taxonomies, and settings into local."}),!Ve&&rr&&a.jsx("p",{className:Je.inlineHint,children:rr})]})]}):a.jsxs(a.Fragment,{children:[Fn&&a.jsxs(a.Fragment,{children:[a.jsx("p",{className:Je.loginSubtitle,children:"Workspace name"}),a.jsx("input",{className:R.input,type:"text",value:rt,placeholder:"Workspace name",onChange:Vt=>kt(Vt.target.value),disabled:ze}),a.jsx("p",{className:Je.loginSubtitle,children:"Workspace description"}),a.jsx("textarea",{className:R.textarea,value:xe,placeholder:"Workspace description (optional)",onChange:Vt=>St(Vt.target.value),disabled:ze,rows:4})]}),Qa&&a.jsxs("div",{className:Je.optionGroup,children:[a.jsx("p",{className:Je.loginSubtitle,children:"What are you working on?"}),a.jsxs("select",{className:R.input,value:qt,onChange:Vt=>er(Vt.target.value),disabled:ze||Tt||$t.length===0,children:[$t.length===0&&a.jsx("option",{value:"",children:Tt?"Loading setup options...":"No setup options available"}),$t.map(Vt=>a.jsx("option",{value:Vt.id,children:Vt.label},Vt.id))]}),ma?a.jsx(a.Fragment,{children:ma.description?a.jsx("p",{className:Je.inlineHint,children:ma.description}):null}):null,a.jsxs("div",{className:Je.optionGroup,children:[a.jsx("p",{className:Je.loginSubtitle,children:"Apply Setup Sections"}),a.jsxs("label",{className:`${Je.authModeLink} ${Je.optionRow}`,children:[a.jsx("input",{type:"checkbox",checked:_t.categories,onChange:()=>Dt(Vt=>({...Vt,categories:!Vt.categories})),disabled:ze||!ma?.categories.length}),a.jsx("span",{children:"Categories"})]}),si?a.jsx("p",{className:Je.inlineHint,children:si}):null,a.jsxs("label",{className:`${Je.authModeLink} ${Je.optionRow}`,children:[a.jsx("input",{type:"checkbox",checked:_t.types,onChange:()=>Dt(Vt=>({...Vt,types:!Vt.types})),disabled:ze||!ma?.types.length}),a.jsx("span",{children:"Task Types"})]}),Nn?a.jsx("p",{className:Je.inlineHint,children:Nn}):null,a.jsxs("label",{className:`${Je.authModeLink} ${Je.optionRow}`,children:[a.jsx("input",{type:"checkbox",checked:_t.priorities,onChange:()=>Dt(Vt=>({...Vt,priorities:!Vt.priorities})),disabled:ze||!ma?.priorities.length}),a.jsx("span",{children:"Priorities"})]}),bs?a.jsx("p",{className:Je.inlineHint,children:bs}):null]}),Tt?a.jsx("p",{className:Je.inlineHint,children:"Loading setup options…"}):null,Rr?a.jsx("p",{className:Je.loginError,children:Rr}):null]}),!mt&&ht&&Lt&&Fn&&a.jsxs("div",{className:Je.optionGroup,children:[a.jsxs("label",{className:`${Je.authModeLink} ${Je.optionRow}`,children:[a.jsx("input",{type:"checkbox",checked:ur,onChange:Vt=>je(Vt.target.checked),disabled:ze}),a.jsx("span",{children:"Sync to cloud after setup"})]}),a.jsx("p",{className:Je.inlineHint,children:"When enabled, this project will connect to cloud sync as soon as setup finishes."})]})]})]}),a.jsxs("div",{className:Je.authModeLinks,children:[Qa?a.jsx("button",{className:R.cancelBtn,onClick:()=>{fe(null),$e(null),Qe("details")},children:"Back"}):xa?a.jsx("button",{className:R.cancelBtn,onClick:()=>{fe(null),$e(null),x("/",{replace:!0})},children:"Cancel"}):u==="cloud"?a.jsx("button",{className:R.cancelBtn,onClick:async()=>{await _r.logout(),x("/login",{replace:!0})},children:bt("setup.signOut")}):null,yt?a.jsx("button",{className:R.submitBtn,disabled:ze||nn&&!!kr&&!wn,onClick:async()=>{qe(!0),$e(null),fe(null);try{const Vt=await fetch("/api/taskforce/global-settings",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({setup:{mode:Be}})}),Sa=await Vt.json().catch(()=>({}));!Vt.ok||Sa?.success===!1?fe(Sa?.error||bt("setup.saveFailedWithStatus",{status:Vt.status})):($e(bt("setup.globalSetupSaved")),await Br())}catch{fe(bt("setup.saveFailed"))}finally{qe(!1)}},children:bt(ze?"setup.saving":"setup.saveGlobalSetup")}):de?a.jsx("button",{className:R.submitBtn,disabled:ze,onClick:Br,children:bt("setup.retrySetupCheck")}):a.jsx("button",{className:R.submitBtn,disabled:ze||nn&&!kr&&!Lt,onClick:async()=>{if(nn&&kr){if(!wn)return;qe(!0),$e(`Retrying import for ${kr.name}...`),fe(null);try{await vn()}catch{$e(null),fe(`Failed to retry import for "${kr.name}".`)}finally{qe(!1)}return}if(ba){if(!ht){fe("Cloud workspace sync is unavailable right now."),qe(!1);return}if(!Lt){fe("Sign in is required before syncing a cloud project."),qe(!1);return}const Vt=Ge.find(aa=>aa.id===Nt);if(!Vt){fe("Select a cloud project to sync."),qe(!1);return}const Sa=await He({workspaceId:Vt.id,name:Vt.name||Vt.id,description:Vt.description||void 0});if(!Sa.success){fe(Sa.error||bt("setup.saveWorkspaceFailed")),qe(!1);return}const hn=String(Sa.workspaceId||Vt.id||"").trim();if(!hn){fe("Failed to resolve workspace id for sync setup."),qe(!1);return}try{await Ar(hn,{version:2,enabled:!0,phase:"attach-cloud",setupIntent:"attach-cloud-import",pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null,lastErrorMessage:null})}catch(aa){fe(aa instanceof Error?aa.message:"Failed to configure workspace sync."),qe(!1);return}da({enabled:!0,phase:"attach-cloud",setupIntent:"attach-cloud-import",pullCursor:null}),await Br(),pt({workspaceId:hn,name:Vt.name||Vt.id}),lt(!1),$e(`Importing ${Vt.name||Vt.id} from cloud...`),qe(!1);return}if(Fn){if(!rt.trim()){fe("Workspace name is required before continuing.");return}fe(null),$e(null),Qe("library");return}qe(!0),$e(null),fe(null);{const Vt=xa||Kt?.workspaceSetupState==="missing",Sa=xa||Pt&&Vt,hn=Sa?await Zr(rt,xe||void 0):null,aa=Sa?null:await He({workspaceId:Vt?void 0:Kt?.workspaceId,name:rt,description:xe}),Ds=hn||aa;if(Ds?.success){const Mn=String(hn?.workspace?.id||aa?.workspaceId||Kt?.workspaceId||"").trim();if(!Mn){fe("Failed to resolve workspace id for setup."),qe(!1);return}if(!!ma&&(_t.categories||_t.types||_t.priorities)&&ma){const Un=await En.onApplySystemTaxonomyPack({pack:ma,sections:_t,remapExistingValuesToDefault:!0,workspaceIdOverride:Mn});if(!Un?.success){fe(Un?.error||"Failed to apply setup library."),qe(!1);return}}const Ss=!!(!mt&&ur&&ht&&Lt),ts=await fetch("/api/taskforce/ui-state",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({workspaceId:Mn,stateKey:"workspace-sync",patch:{version:2,enabled:Ss,phase:Ss?"provision-local":"idle",setupIntent:null,pullCursor:null,lastPullAt:null,lastPushAt:null,lastSyncedAt:null}})}),rs=await ts.json().catch(()=>({}));if(!ts.ok||rs?.success===!1){fe(rs?.error||`Failed to configure workspace sync (${ts.status})`),qe(!1);return}da({enabled:Ss,phase:Ss?"provision-local":"idle",setupIntent:null,pullCursor:null}),$e(Ss?`${Pr} setup saved. Cloud sync enabled.`:bt("setup.workspaceSetupSaved",{workspaceLabel:Pr})),xa&&(await Br(),await Ga(!0),Fa(ca,{replace:!0}))}else{if(Ds?.code==="WORKSPACE_LIMIT_REACHED"){qe(!1),x(T,{replace:!0});return}fe(Ds?.error||bt("setup.saveWorkspaceFailed"))}}qe(!1)},children:Oo})]})]})})})}return a.jsx(bee,{..._r,initialActivityEntryId:h,onHeaderMouseDown:s,isDragging:i,onClose:l})}function Aee(e){return M0()?a.jsx(rA,{...e}):a.jsx(D0,{children:a.jsx(rA,{...e})})}const j_={},aA="STAGING_MARKER_2026_02_24";typeof window<"u"&&(window.__TASKFORCE_BUILD_MARKER=aA,console.info(`[Taskforce] Build marker: ${aA}`));function Cee(){if(typeof window<"u"){const t=window.location.hostname.toLowerCase();if(t==="localhost"||t==="127.0.0.1"||t==="::1")return}return Ev(j_).apiBaseUrl||void 0}function Iee(e){const t=Ev(j_),r=t.cloudAuthBaseUrl;if(r)if(typeof window<"u"){const n=window.location.hostname.toLowerCase(),s=n==="localhost"||n==="127.0.0.1"||n==="::1",i="".trim().toLowerCase()==="true";if(!s&&!i)try{const l=new URL(r,window.location.origin);if(l.origin!==window.location.origin)console.warn(`[Taskforce] Ignoring cross-origin cloud auth base in hosted runtime: ${l.origin}`);else return r}catch{}else return r}else return r;if(t.baseUrl)return t.baseUrl;if(e)return e}function _ee(){const e=Cee(),t=Iee(e);return a.jsx(L0,{children:a.jsx(Aee,{mode:"standalone",config:{apiEndpoint:"/api/taskforce/task",apiBaseUrl:e,cloudAuthBaseUrl:t}})})}RT.createRoot(document.getElementById("root")).render(a.jsx(Y.StrictMode,{children:a.jsx(_ee,{})}));export{IC as $,Uee as A,Uk as B,_C as C,Lu as D,Bee as E,TC as F,RC as G,zj as H,Hu as I,jC as J,Gj as K,Hv as L,Do as M,Vj as N,$k as O,Fee as P,Wee as Q,nw as R,$ee as S,ai as T,zV as U,eE as V,zK as W,u8 as X,DI as Y,q7 as Z,yE as _,Ag as a,Ff as a$,WY as a0,K7 as a1,qee as a2,Yee as a3,Zee as a4,Jee as a5,Qee as a6,WA as a7,Of as a8,BA as a9,C_ as aA,ZQ as aB,mX as aC,Jf as aD,uw as aE,_d as aF,A_ as aG,d_ as aH,pv as aI,kQ as aJ,vQ as aK,wQ as aL,hK as aM,Pv as aN,sv as aO,DS as aP,LS as aQ,_Y as aR,HY as aS,vI as aT,ug as aU,Gee as aV,Hee as aW,cg as aX,av as aY,_f as aZ,gI as a_,qu as aa,Yq as ab,yC as ac,gC as ad,Oee as ae,d8 as af,YR as ag,Mee as ah,Kee as ai,c8 as aj,Dee as ak,Lee as al,I_ as am,xg as an,qf as ao,SX as ap,uv as aq,pw as ar,VS as as,yg as at,vf as au,Eo as av,fs as aw,tX as ax,iX as ay,hs as az,fo as b,fI as b0,pI as b1,kz as b2,vz as b3,G8 as b4,V7 as b5,Fj as b6,Ax as c,G0 as d,wr as e,Yx as f,Vee as g,Ou as h,_z as i,aee as j,nee as k,qC as l,md as m,JU as n,rE as o,zee as p,yf as q,rn as r,Tz as s,R as t,NH as u,Mg as v,qx as w,Wk as x,EE as y,Fk as z};