@unbrained/pm-cli 2026.10.22 → 2026.10.23

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 (149) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +17 -0
  3. package/dist/cli/error-guidance.d.ts +12 -0
  4. package/dist/cli/error-guidance.js +2 -2
  5. package/dist/cli/register-setup.js +1 -1
  6. package/dist/cli-bundle/bundle-manifest.json +1 -1
  7. package/dist/cli-bundle/chunks/{chunk-5LSN7K4N.js → chunk-2LTGJ5DL.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-E3JC3WQL.js → chunk-2UX2TAN2.js} +15 -15
  9. package/dist/cli-bundle/chunks/{chunk-2B5HAZFK.js → chunk-3S5FLCG7.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-J444ZX23.js → chunk-5DKCD4KV.js} +39 -39
  11. package/dist/cli-bundle/chunks/{chunk-LIC5EUQS.js → chunk-5V4HU6GK.js} +48 -48
  12. package/dist/cli-bundle/chunks/{chunk-UYYTV2TX.js → chunk-AAX7CNL7.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-AOAQDCXX.js → chunk-AXGFNNI3.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-F76ZUP73.js +113 -0
  15. package/dist/cli-bundle/chunks/chunk-HDKY2YX3.js +3 -0
  16. package/dist/cli-bundle/chunks/{chunk-7OTYULIJ.js → chunk-KY34HTT2.js} +29 -29
  17. package/dist/cli-bundle/chunks/{chunk-TNU3XVPC.js → chunk-MMVX5L32.js} +3 -3
  18. package/dist/cli-bundle/chunks/{chunk-PCPOTFJP.js → chunk-MTRYEVZR.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-O67N62DT.js → chunk-QSY55FTA.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-GWIGZDRS.js → chunk-R7KWBFM2.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-HC2DCGFA.js → chunk-REXCO5AG.js} +2 -2
  22. package/dist/cli-bundle/chunks/chunk-ZDVTXLA6.js +9 -0
  23. package/dist/cli-bundle/chunks/{chunk-MV3KYY2A.js → chunk-ZEI3DC5E.js} +3 -3
  24. package/dist/cli-bundle/chunks/{chunk-URV4VHQ4.js → chunk-ZMJF5HQW.js} +2 -2
  25. package/dist/cli-bundle/chunks/chunk-ZNDYAZZ6.js +6 -0
  26. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-L3BOTMZN.js → indexed-receipt-blobs-XANVELIV.js} +2 -2
  27. package/dist/cli-bundle/chunks/{mutation-admission-TATOFEXF.js → mutation-admission-P6LOBNLO.js} +2 -2
  28. package/dist/cli-bundle/chunks/{register-list-query-GULR2IYO.js → register-list-query-JOB65KDN.js} +2 -2
  29. package/dist/cli-bundle/chunks/{register-mutation-HLSQ4WVW.js → register-mutation-QMNIN3RJ.js} +2 -2
  30. package/dist/cli-bundle/chunks/{register-operations-FE3GGA7O.js → register-operations-Z4VET3I7.js} +2 -2
  31. package/dist/cli-bundle/chunks/register-setup-GNKWL3VL.js +2 -0
  32. package/dist/cli-bundle/chunks/{settlement-hook-UVFYSBMU.js → settlement-hook-YUVCO65H.js} +2 -2
  33. package/dist/cli-bundle/chunks/{stage-QCPZBZRC.js → stage-FW5OXCCR.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-EHPRSWJE.js → chunk-4MNUQCGR.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/{chunk-CB7TSZ7P.js → chunk-6GTZ24YV.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-2GFTVXKZ.js → chunk-BM652VCB.js} +3 -3
  37. package/dist/cli-bundle/focused-chunks/{chunk-3LWH2RJC.js → chunk-BUZ2Z4P3.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-QGDKWULS.js → chunk-CGL36F6I.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-TMN3RAXZ.js → chunk-DWQMYLFM.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-SXVJRLLP.js → chunk-EDXTOAXP.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-FO4U3FIP.js +91 -0
  42. package/dist/cli-bundle/focused-chunks/chunk-GXKP56W7.js +2 -0
  43. package/dist/cli-bundle/focused-chunks/{chunk-46HBJC6J.js → chunk-I2USTQNQ.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-XX5JQCLF.js → chunk-JDN34LEZ.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-GVKYTDOH.js → chunk-KI5YFKNN.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-UQ5JPBY2.js → chunk-LEHGCPZ6.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-KM77WU5U.js → chunk-MLET6I3I.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-25NQRZ7J.js → chunk-NSMZY6IK.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-OMXMYTEX.js +26 -0
  50. package/dist/cli-bundle/focused-chunks/{chunk-VYAZND5Q.js → chunk-P7DPS5M4.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/chunk-R536272H.js +9 -0
  52. package/dist/cli-bundle/focused-chunks/{chunk-CX5FNEFC.js → chunk-UNTCCJPL.js} +3 -3
  53. package/dist/cli-bundle/focused-chunks/{chunk-A52W6GLA.js → chunk-XIZYJDYW.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-25L3L2PF.js → chunk-Z5LDTMZ3.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/chunk-ZHMF34DT.js +65 -0
  56. package/dist/cli-bundle/focused-chunks/{chunk-GC4VMLXL.js → chunk-ZR6ZKQUK.js} +3 -3
  57. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-AAQOKO5B.js → indexed-receipt-blobs-FVOA3XMI.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{mutation-admission-TBKR4KRM.js → mutation-admission-HTFAIHJL.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{settlement-hook-MNCHFCAX.js → settlement-hook-2VXEB6PP.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{stage-RM6MJIMT.js → stage-X3BUGEJT.js} +2 -2
  61. package/dist/cli-bundle/main.js +21 -21
  62. package/dist/cli-bundle/sdk-authoring.js +1 -1
  63. package/dist/cli-bundle/sdk-contracts.js +5 -2
  64. package/dist/cli-bundle/sdk-core.js +33 -33
  65. package/dist/cli-bundle/sdk-governance.js +1 -1
  66. package/dist/cli-bundle/sdk-graph.js +1 -1
  67. package/dist/cli-bundle/sdk-merge.js +58 -58
  68. package/dist/cli-bundle/sdk-query.js +1 -1
  69. package/dist/cli-bundle/sdk-runtime.js +1 -1
  70. package/dist/cli-bundle/sdk-testing.js +1 -1
  71. package/dist/cli-bundle/sdk.js +12 -9
  72. package/dist/core/config/nested-settings.js +1 -1
  73. package/dist/core/extensions/loader.js +1 -1
  74. package/dist/core/extensions/version-diagnostics.d.ts +2 -0
  75. package/dist/core/extensions/version-diagnostics.js +2 -0
  76. package/dist/core/lock/lock.d.ts +40 -6
  77. package/dist/core/lock/lock.js +3 -3
  78. package/dist/core/shared/errors.d.ts +28 -0
  79. package/dist/core/shared/errors.js +1 -1
  80. package/dist/core/store/item-store.js +1 -1
  81. package/dist/mcp/http-server.js +2 -2
  82. package/dist/mcp/server.js +2 -2
  83. package/dist/sdk/cli-contracts/agent-output-contracts.js +1 -1
  84. package/dist/sdk/contracts.d.ts +1 -0
  85. package/dist/sdk/contracts.js +1 -1
  86. package/dist/sdk/extension/doctor.js +1 -1
  87. package/dist/sdk/extension/install-receipts.js +1 -1
  88. package/dist/sdk/extension/install-snapshot.d.ts +11 -0
  89. package/dist/sdk/extension/install-snapshot.js +1 -1
  90. package/dist/sdk/extension.d.ts +12 -0
  91. package/dist/sdk/extension.js +1 -1
  92. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  93. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  94. package/dist/sdk/governance/health.d.ts +1 -0
  95. package/dist/sdk/governance/health.js +2 -2
  96. package/dist/sdk/index.d.ts +3 -2
  97. package/dist/sdk/index.js +1 -1
  98. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  99. package/dist/sdk/lifecycle/restore.js +1 -1
  100. package/dist/sdk/mcp/executable.d.ts +13 -0
  101. package/dist/sdk/mcp/executable.js +5 -0
  102. package/dist/sdk/public-surface.json +1 -1
  103. package/dist/sdk/runtime-primitives.d.ts +1 -1
  104. package/dist/sdk/runtime-primitives.js +1 -1
  105. package/dist/sdk/runtime.d.ts +1 -1
  106. package/dist/sdk/runtime.js +1 -1
  107. package/dist/sdk/workspace-snapshot.d.ts +5 -1
  108. package/dist/sdk/workspace-snapshot.js +3 -3
  109. package/dist/sdk/workspace.js +2 -2
  110. package/docs/CONFIGURATION.md +19 -3
  111. package/docs/EXTENSION_AUTHOR_CONTRACTS.md +2 -1
  112. package/docs/EXTENSION_LIFECYCLE.md +47 -0
  113. package/docs/MCP_REMOTE_TRANSPORT_SECURITY.md +16 -1
  114. package/docs/RELEASING.md +9 -0
  115. package/docs/SDK.md +39 -5
  116. package/docs/SDK_STORAGE_LIFECYCLE.md +2 -1
  117. package/docs/TESTING.md +11 -7
  118. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +6 -3
  119. package/marketplace.json +1 -1
  120. package/package.json +1 -1
  121. package/packages/pm-beads/package.json +1 -1
  122. package/packages/pm-calendar/package.json +1 -1
  123. package/packages/pm-command-kit/package.json +1 -1
  124. package/packages/pm-digital-twin/package.json +1 -1
  125. package/packages/pm-governance-audit/package.json +1 -1
  126. package/packages/pm-guide-shell/package.json +1 -1
  127. package/packages/pm-kanban/package.json +1 -1
  128. package/packages/pm-lifecycle-hooks/package.json +1 -1
  129. package/packages/pm-linked-test-adapters/package.json +1 -1
  130. package/packages/pm-search-advanced/package.json +1 -1
  131. package/packages/pm-templates/package.json +1 -1
  132. package/packages/pm-todos/package.json +1 -1
  133. package/packages/pm-vcs/package.json +1 -1
  134. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  135. package/plugins/pm-claude/package.json +1 -1
  136. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  137. package/plugins/pm-codex/package.json +1 -1
  138. package/plugins/pm-codex/plugin.json +1 -1
  139. package/runtime-dependencies.json +1 -1
  140. package/dist/cli-bundle/chunks/chunk-35ISFIPC.js +0 -113
  141. package/dist/cli-bundle/chunks/chunk-BAIVTLJM.js +0 -6
  142. package/dist/cli-bundle/chunks/chunk-C37RDYZI.js +0 -3
  143. package/dist/cli-bundle/chunks/chunk-VO3KDIU7.js +0 -9
  144. package/dist/cli-bundle/chunks/register-setup-XUIKAIZA.js +0 -2
  145. package/dist/cli-bundle/focused-chunks/chunk-DVNUHTVK.js +0 -9
  146. package/dist/cli-bundle/focused-chunks/chunk-QWKCQ5PW.js +0 -91
  147. package/dist/cli-bundle/focused-chunks/chunk-SOVXHW6Z.js +0 -2
  148. package/dist/cli-bundle/focused-chunks/chunk-UUPJ6OZL.js +0 -26
  149. package/dist/cli-bundle/focused-chunks/chunk-W2CND3BD.js +0 -65
@@ -1,2 +1,2 @@
1
- import{E as $e,G as qe,K as $,L as Ue,M as Be,N as ze,m as Fe,x as G,y as Ge}from"./chunk-QGDKWULS.js";import{G as Le,a as Oe}from"./chunk-QWKCQ5PW.js";import{_a as Me,db as Pe,t as je}from"./chunk-VYAZND5Q.js";import{j as Se}from"./chunk-TMN3RAXZ.js";import{a as I}from"./chunk-AK2CI2GI.js";import{Jd as Re,R as we,W as ke,ic as Ce,lb as ie,nd as Te,od as oe,qa as xe,rd as Ne,wa as Ee,wd as Ae,xc as De}from"./chunk-UUPJ6OZL.js";import{E as j,H as re,J as Ie,y as w,z as k}from"./chunk-3LWH2RJC.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="403706c5-987d-5db1-95d2-b0eaded98e92")}catch{}})();function Ut(e,t,n,r,i,o){if(e.seen.has(t))return"skip";if(e.cursorFound&&e.affected.length>=o)return"truncate";e.seen.add(t),e.parents.set(t,n.id);let s=n.depth+1;return e.queue.push({id:t,depth:s}),e.cursorFound?(e.affected.push({id:t,distance:s,path:Yt(r,t,e.parents)}),"continue"):(e.cursorFound=t===i,"skip")}function Ke(e,t,n,r){let i=Te("graph impact",{root:e,direction:n,kinds:[...t.kinds??[]].sort(),max_depth:Number.isFinite(r)?r:"unbounded"});return{fingerprint:i,after:t.after===void 0?void 0:Ne(t.after,i)}}function C(e,t,n){e.get(t).add(n)}function M(e){return new Map(e.map(t=>[t,new Set]))}function Ve(e){for(let t of e)t.sort();return e.sort((t,n)=>n.length-t.length||t[0].localeCompare(n[0]))}function q(e){if(Array.isArray(e))return e.map(n=>q(n));if(e===null||typeof e!="object")return e;let t=e.toJSON;return typeof t=="function"?q(t.call(e)):Object.fromEntries(Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,q(r)]))}function He(e){return JSON.stringify(q(e))}function Bt(e,t,n,r){let i=[{id:e,expanded:!1}];for(;i.length>0;){let o=i.pop();if(o.expanded){r.push(o.id);continue}if(n.has(o.id))continue;n.add(o.id),i.push({id:o.id,expanded:!0});let s=[...t.get(o.id)].sort().reverse();for(let a of s)n.has(a)||i.push({id:a,expanded:!1})}}function zt(e,t){let n=new Set,r=[];for(let i of e)n.has(i)||Bt(i,t,n,r);return r}function Ht(e,t){let n=new Set,r=[];for(let i of[...e].reverse()){if(n.has(i))continue;let o=[],s=[i];for(n.add(i);s.length>0;){let a=s.pop();o.push(a);for(let c of t.get(a))n.has(c)||(n.add(c),s.push(c))}r.push(o)}return Ve(r)}function We(e,t){let n=M(e);for(let[r,i]of t)for(let o of i)C(n,o,r);return Ht(zt(e,t),n)}function Kt(e,t){let n=M(e.nodes());for(let r of e.edges()){let i=t.require(r.kind);if(!i.ordering)continue;let o=(i.precedence??"source_before_target")==="source_before_target";C(n,o?r.source:r.target,o?r.target:r.source)}return n}function Vt(e,t){let n=new Map(e.map(o=>[o,0]));for(let o of t.values())for(let s of o)n.set(s,n.get(s)+1);let r=e.filter(o=>n.get(o)===0).sort(),i=[];for(;r.length>0;){i.push(r);let o=[];for(let s of r)for(let a of t.get(s)){let c=n.get(a)-1;n.set(a,c),c===0&&o.push(a)}r=o.sort()}return i}function Wt(e,t){let n=new Map(e.map(s=>[s,0])),r=new Map;for(let s of e)for(let a of t.get(s)){if(!n.has(a))continue;let c=n.get(s)+1,d=r.get(a);(c>n.get(a)||c===n.get(a)&&(d===void 0||s.localeCompare(d)<0))&&(n.set(a,c),r.set(a,s))}let i=[...e].sort((s,a)=>n.get(a)-n.get(s)||s.localeCompare(a))[0],o=i===void 0?[]:[i];for(;o[0]!==void 0&&r.has(o[0]);)o.unshift(r.get(o[0]));return{depth:Object.fromEntries(n),path:o}}function Yt(e,t,n){let r=[t],i=t;for(;i!==e;)i=n.get(i),r.push(i);return r.reverse()}function B(e,t={}){let n=t.registry??we(),r=[...e.nodes()],i=Kt(e,n),o=Vt(r,i),s=o.flat(),a=s.length===r.length,c=a?[]:We(r,i).filter(l=>l.length>1||i.get(l[0]).has(l[0])),d=Wt(s,i);return{exact:!0,acyclic:a,order:s,layers:o,frontier:o[0]??[],depth:d.depth,criticalPath:d.path,criticalPathLength:Math.max(0,d.path.length-1),cycles:c,provenance:{algorithm:"kahn-longest-path",edgeFamily:"ordering"}}}function Xt(e,t,n){let r=M(e.nodes()),i=n===void 0?void 0:new Set(n.map(s=>e.registry().require(s).kind)),o=e.edges();for(let s of o){let a=e.registry().require(s.kind);i!==void 0&&!i.has(s.kind)&&(a.inverse===void 0||!i.has(a.inverse))||C(r,t==="incoming"?s.target:s.source,t==="incoming"?s.source:s.target)}return{adjacency:r,inspectedEdges:o.length}}function Jt(e,t,n,r,i,o){let s=U(e,t,{...n,after:void 0,direction:"incoming",limit:void 0}),a=U(e,t,{...n,after:void 0,direction:"outgoing",limit:void 0}),c=new Map,d=[...s.affected,...a.affected].sort((p,m)=>p.distance-m.distance||p.id.localeCompare(m.id)||p.path.join("\0").localeCompare(m.path.join("\0")));for(let p of d)c.has(p.id)||c.set(p.id,p);let l=[...c.values()].sort((p,m)=>p.distance-m.distance||p.id.localeCompare(m.id)),g=r===void 0||r===t?-1:l.findIndex(p=>p.id===r);if(r!==void 0&&r!==t&&g<0)throw new TypeError(`Unknown impact cursor item: ${r}`);let u=l.slice(g+1,g+1+i),f=g+1+u.length<l.length;return{root:t,affected:u,exact:!0,truncated:s.truncated||a.truncated||f,...f?{nextCursor:oe(o,u.at(-1)?.id??t)}:{},cost:{visitedNodes:s.cost.visitedNodes+a.cost.visitedNodes,inspectedEdges:s.cost.inspectedEdges+a.cost.inspectedEdges}}}function Qt(e,t,n){let r=n.direction,i=n.maxDepth??Number.POSITIVE_INFINITY,o=n.limit??Number.POSITIVE_INFINITY,{fingerprint:s,after:a}=Ke(t,n,r,i),{adjacency:c,inspectedEdges:d}=Xt(e,r,n.kinds),l={queue:[{id:t,depth:0}],seen:new Set([t]),parents:new Map,affected:[],cursorFound:a===void 0||a===t},g=0,u=!1,f=!1;e:for(let p=0;p<l.queue.length;p+=1){n.signal?.throwIfAborted();let m=l.queue[p];g+=1;let b=[...c.get(m.id)].sort();if(m.depth>=i){b.some(v=>!l.seen.has(v))&&(u=!0);continue}for(let v of b)if(Ut(l,v,m,t,a,o)==="truncate"){u=!0,f=!0;break e}}if(!l.cursorFound)throw new TypeError(`Unknown impact cursor item: ${a}`);return{root:t,affected:l.affected,exact:!0,truncated:u,...f?{nextCursor:oe(s,l.affected.at(-1)?.id??t)}:{},cost:{visitedNodes:g,inspectedEdges:d}}}function U(e,t,n={}){let r=n.direction??"outgoing";if(r!=="both")return Qt(e,t,{...n,direction:r});let i=n.maxDepth??Number.POSITIVE_INFINITY,o=n.limit??Number.POSITIVE_INFINITY,{fingerprint:s,after:a}=Ke(t,n,r,i);return Jt(e,t,n,a,o,s)}function Ye(e){let t=[...e.nodes()],n=M(t),r=M(t);for(let c of e.edges())C(n,c.source,c.target),C(n,c.target,c.source),C(r,c.source,c.target);let i=[],o=new Set;for(let c of t){if(o.has(c))continue;let d=[],l=[c];for(o.add(c);l.length>0;){let g=l.pop();d.push(g);for(let u of n.get(g))o.has(u)||(o.add(u),l.push(u))}i.push(d)}let s=t.map(c=>({id:c,degree:n.get(c).size})),a=Math.max(0,...s.map(({degree:c})=>c));return{components:Ve(i),stronglyConnected:We(t,r),orphans:s.filter(({degree:c})=>c===0).map(({id:c})=>c),hubs:s.filter(({degree:c})=>c>0&&c===a),exact:!0,provenance:{algorithm:"component-degree",edgeFamily:"all"}}}function Xr(e,t){let n=new Map(e.edges.map(i=>[He(i),i])),r=new Map(t.edges.map(i=>[He(i),i]));return{fromVersion:e.version,toVersion:t.version,added:[...r].filter(([i])=>!n.has(i)).map(([,i])=>i),removed:[...n].filter(([i])=>!r.has(i)).map(([,i])=>i),unchangedCount:[...n.keys()].filter(i=>r.has(i)).length,exact:!0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f60c628a-2e42-5770-a001-39cce5f92595")}catch{}})();var Zt=I.paths,en=I.visited_paths,tn=I.path_depth;function se(e,t){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new TypeError(`Invalid path ${e} bound: ${String(t)}`)}function z(e,t){return t.hierarchyDirection==="target_parent"?e.target:e.source}function P(e,t){return(t.precedence??"source_before_target")==="target_before_source"?e.target:e.source}function D(e,t){let n=P(e,t);return{predecessor:n,successor:n===e.source?e.target:e.source}}function nn(e,t,n){if(t===void 0)return;let r=e.registry(),i=new Set;for(let o of t){let s=r.require(o),a=s.traversal;if(a==="association")throw new TypeError(`Relationship kind ${s.kind} uses association traversal; use graph impact --direction both`);if(a!==n&&a!=="semantic"){let c=a==="hierarchy"?"graph ancestors or graph descendants":"graph predecessors or graph successors";throw new TypeError(`Relationship kind ${s.kind} uses ${a} traversal; use ${c}`)}i.add(s.kind)}return i}function rn(e,t,n,r,i){let o=e.registry(),s=e.neighborEdges(t,{direction:"both",...n===void 0?{}:{kinds:[...n]}}),a=[],c=new Set;for(let d of s.value){let l=o.require(d.edge.kind);n===void 0&&!l[r]||i(d,l,t)&&(c.has(d.id)||(c.add(d.id),a.push(d.id)))}return{neighbors:a,inspectedEdges:s.meta.inspectedEdges}}function on(e,t,n,r,i,o){if(t>=n)return e.neighbors.some(s=>!o.seen.has(s))&&(o.truncated=!0),!1;for(let s of e.neighbors)if(!o.seen.has(s)){if(o.seen.add(s),o.queue.push({id:s,depth:t+1}),!o.resumed){s===i&&(o.resumed=!0);continue}if(o.value.length>=r)return o.truncated=!0,!0;o.value.push(s)}return!1}function H(e,t,n,r,i){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`);let o=nn(e,n.kinds,r),s=n.limit??Number.POSITIVE_INFINITY,a=n.maxDepth??Number.POSITIVE_INFINITY,c=n.after,d={seen:new Set([t]),value:[],queue:[{id:t,depth:0}],resumed:c===void 0,truncated:!1},l=0,g=0;for(let u=0;u<d.queue.length;u+=1){n.signal?.throwIfAborted();let f=d.queue[u];l+=1;let p=rn(e,f.id,o,r,i);if(g+=p.inspectedEdges,on(p,f.depth,a,s,c,d))break}if(!d.resumed)throw new TypeError(`Traversal cursor not found in sequence: ${c}`);return{value:d.value,meta:{visitedNodes:l,inspectedEdges:g,truncated:d.truncated,nextCursor:d.value.at(-1)}}}function Xe(e,t){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`)}function Je(e,t,n,r,i){let o=e.neighborEdges(t.nodes.at(-1),{direction:r,...n.kinds===void 0?{}:{kinds:n.kinds}});return i.inspectedEdges+=o.meta.inspectedEdges,o.value.filter(s=>!t.nodeSet.has(s.id))}function sn(e,t,n,r,i,o,s){for(let a of Je(e,t,r,i,s)){let c=[...t.nodes,a.id],d=new Set(t.nodeSet).add(a.id),l=[...t.edges,a.edge];if(a.id===n){if(s.value.push({nodes:c,edges:l,length:l.length}),s.value.length>=o)return!0}else s.queue.push({nodes:c,nodeSet:d,edges:l})}return!1}function Qe(e,t,n={}){return H(e,t,n,"hierarchy",(r,i)=>z(r.edge,i)===r.id)}function Ze(e,t,n={}){return H(e,t,n,"hierarchy",(r,i,o)=>z(r.edge,i)===o)}function et(e,t,n={}){return H(e,t,n,"ordering",(r,i)=>P(r.edge,i)===r.id)}function tt(e,t,n={}){return H(e,t,n,"ordering",(r,i,o)=>P(r.edge,i)===o)}function an(e,t,n,r,i,o,s,a){let c={value:[],queue:[{nodes:[t],nodeSet:new Set([t]),edges:[]}],inspectedEdges:0},d=0,l=!1,g=i+1;for(let u=0;u<c.queue.length;u+=1){if(r.signal?.throwIfAborted(),c.value.length>=g||d>=o){l=!0;break}let f=c.queue[u];if(d+=1,f.edges.length>=s){Je(e,f,r,a,c).length>0&&(l=!0);continue}if(sn(e,f,n,r,a,g,c)){l=!0;break}}return{value:c.value.slice(0,i),meta:{visitedNodes:d,inspectedEdges:c.inspectedEdges,truncated:l}}}function nt(e,t,n,r={}){Xe(e,t),Xe(e,n);let i=r.maxPaths??Zt,o=r.maxVisitedPaths??en,s=r.maxDepth??tn;se("maxPaths",i),se("maxVisitedPaths",o),se("maxDepth",s);let a=r.direction??"outgoing";r.signal?.throwIfAborted();for(let c of r.kinds??[])e.registry().require(c);return t===n?i===0?{value:[],meta:{visitedNodes:1,inspectedEdges:0,truncated:!0}}:{value:[{nodes:[t],edges:[],length:0}],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}}:an(e,t,n,r,i,o,s,a)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="789f7451-ceb1-5e5c-b2b6-45eec49580ce")}catch{}})();var cn=16,dn=2,ln=8;function K(e,t){if(!Number.isInteger(t)||t<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`)}function V(e,t,n){let r=e.registry(),i=t===void 0?void 0:new Set(t.map(o=>r.require(o).kind));for(let o of e.edges()){if(o.source===o.target)continue;let s=r.require(o.kind);i!==void 0&&!(i.has(s.kind)||s.inverse!==void 0&&i.has(s.inverse))||n(o,s)}}function un(e,t){let n=new Map;V(e,t,r=>{rt(n,r.source,r.target),rt(n,r.target,r.source)});for(let r of n.values())r.sort();return n}function rt(e,t,n){let r=e.get(t);r===void 0?e.set(t,[n]):r.push(n)}function gn(e,t){let n=new Map;for(let o of e){let s=t.get(o);n.set(s,(n.get(s)??0)+1)}let r,i=0;for(let[o,s]of n)(s>i||s===i&&o<r)&&(r=o,i=s);return r}function fn(e,t){let n=new Map;for(let[i,o]of e){let s=n.get(o);s===void 0?n.set(o,[i]):s.push(i)}let r=[];for(let i of n.values())i.length<t||(i.sort(),r.push({representative:i[0],size:i.length,members:i}));return r.sort((i,o)=>o.size-i.size||i.representative.localeCompare(o.representative))}function it(e,t={}){let n=t.maxIterations??cn,r=t.minSize??dn;K("maxIterations",n),K("minSize",r);let i=un(e,t.kinds),o=e.nodes(),s=new Map(o.map(g=>[g,g])),a=0,c=!1,d=0,l=0;for(;a<n&&!c;){t.signal?.throwIfAborted(),a+=1,c=!0;for(let g of o){d+=1;let u=i.get(g);if(u===void 0)continue;l+=u.length;let f=gn(u,s);f!==s.get(g)&&(s.set(g,f),c=!1)}}return{value:{communities:fn(s,r),iterations:a,converged:c},meta:{visitedNodes:d,inspectedEdges:l,truncated:!c}}}function W(e){return e.direction==="directed"&&(e.ordering||e.hierarchy)}function Y(e){return e.inverse!==void 0&&e.inverse<e.kind?e.inverse:e.kind}function ae(e,t){return(t.hierarchy?z(e,t):e.source===P(e,t)?e.target:e.source)===e.target?{from:e.source,to:e.target}:{from:e.target,to:e.source}}function pn(e,t){if(t===void 0)return;let n=e.registry(),r=new Set;for(let i of t){let o=n.require(i);if(!W(o))throw new TypeError(`Relationship kind ${o.kind} is not a directed ordering or hierarchy kind`);r.add(Y(o))}return r}function hn(e,t){let n=e.registry(),r=new Map;for(let i of e.edges()){let o=n.require(i.kind);if(!W(o))continue;let s=Y(o);if(t!==void 0&&!t.has(s))continue;let a=ae(i,o);if(a.from===a.to)continue;let c=r.get(s);c===void 0&&(c={adjacency:new Map,records:[]},r.set(s,c));let d=c.adjacency.get(a.from);d===void 0?c.adjacency.set(a.from,new Set([a.to])):d.add(a.to),c.records.push({...a,edge:i})}return r}function mn(e){let t=new Map;for(let[n,r]of e.adjacency)t.set(n,[...r].sort());return t}function _n(e,t,n,r){let i=[r];for(let o=n;o!==t;o=e.get(o))i.push(o);return i.push(t),i.reverse()}function yn(e,t,n,r,i,o){for(let s of e.get(n.id)??[])if(o.inspectedEdges+=1,!(n.depth===0&&s===t.to)&&!r.has(s)){if(r.set(s,n.id),s===t.to)return _n(r,t.from,n.id,s);i.push({id:s,depth:n.depth+1})}}function bn(e,t,n,r){let i=new Map([[t.from,t.from]]),o=[{id:t.from,depth:0}];for(let s=0;s<o.length;s+=1){let a=o[s];if(r.visitedNodes+=1,a.depth>=n)continue;let c=yn(e,t,a,i,o,r);if(c!==void 0)return c}}function T(e,t={}){let n=t.maxDepth??ln;K("maxDepth",n),t.limit!==void 0&&K("limit",t.limit);let r=t.limit??Number.POSITIVE_INFINITY,i=pn(e,t.kinds),o=hn(e,i),s=[],a={visitedNodes:0,inspectedEdges:0},c=!1;e:for(let d of[...o.keys()].sort()){let l=o.get(d),g=mn(l);for(let u of l.records){t.signal?.throwIfAborted();let f=bn(g,u,n,a);if(f!==void 0){if(s.length>=r){c=!0;break e}s.push({edge:u.edge,witness:f})}}}return{value:s,meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:c}}}function vn(e,t,n,r,i){let o=new Set,s=[];for(let a of n){if(a.id===e||o.has(a.id))continue;if(!i.seen.has(a.id)){if(t>=r){i.truncated=!0;continue}i.seen.add(a.id),i.queue.push({id:a.id,depth:t+1})}o.add(a.id),s.push(a.id);let c=i.predecessors.get(a.id);c===void 0&&(c=new Set,i.predecessors.set(a.id,c)),c.add(e)}return s}function wn(e,t,n){let r=n.direction??"outgoing",i=n.maxDepth??Number.POSITIVE_INFINITY,o=[],s=new Map,a={seen:new Set([t]),queue:[{id:t,depth:0}],predecessors:new Map,truncated:!1},c=0;for(let d=0;d<a.queue.length;d+=1){n.signal?.throwIfAborted();let{id:l,depth:g}=a.queue[d];o.push(l);let u=e.neighborEdges(l,{direction:r,...n.kinds===void 0?{}:{kinds:n.kinds}});c+=u.meta.inspectedEdges,s.set(l,vn(l,g,u.value,i,a))}return{order:o,successors:s,predecessors:a.predecessors,inspectedEdges:c,truncated:a.truncated}}function kn(e,t){let n=[],r=new Set([t]),i=[{id:t,index:0}];for(;i.length>0;){let o=i.at(-1),s=e.successors.get(o.id);if(o.index<s.length){let a=s[o.index];o.index+=1,r.has(a)||(r.add(a),i.push({id:a,index:0}))}else n.push(o.id),i.pop()}return n.reverse()}function In(e,t,n,r){let i=e,o=t;for(;i!==o;){for(;r.get(i)>r.get(o);)i=n.get(i);for(;r.get(o)>r.get(i);)o=n.get(o)}return i}function xn(e,t,n){let r;for(let i of[...e].sort())t.has(i)&&(r=r===void 0?i:In(r,i,t,n));return r}function En(e,t,n,r,i){let o=new Map([[t,t]]),s=!0;for(;s;){s=!1;for(let a of n){if(i?.throwIfAborted(),a===t)continue;let c=xn(e.predecessors.get(a),o,r);c!==void 0&&o.get(a)!==c&&(o.set(a,c),s=!0)}}return o}function ot(e,t,n={}){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`);if(n.maxDepth!==void 0&&(!Number.isInteger(n.maxDepth)||n.maxDepth<0))throw new TypeError(`Invalid maxDepth bound: ${String(n.maxDepth)}`);let r=wn(e,t,n),i=kn(r,t),o=new Map(i.map((d,l)=>[d,l])),s=En(r,t,i,o,n.signal),a=new Map(i.map(d=>[d,1]));for(let d=i.length-1;d>=0;d-=1){let l=i[d];if(l===t)continue;let g=s.get(l);a.set(g,a.get(g)+a.get(l))}let c=i.filter(d=>d!==t).map(d=>({id:d,idom:s.get(d),dominatedCount:a.get(d)-1})).sort((d,l)=>l.dominatedCount-d.dominatedCount||d.id.localeCompare(l.id));return{value:{root:t,reachableCount:r.order.length,rows:c},meta:{visitedNodes:r.order.length,inspectedEdges:r.inspectedEdges,truncated:r.truncated}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3cef3a97-fda4-5811-9e69-04ff722e40a1")}catch{}})();function st(e){return Math.round(e*1e6)/1e6}function at(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function ct(e,t){let n=new Map(e.nodes().map(i=>[i,new Set]));V(e,t,i=>{n.get(i.source).add(i.target),n.get(i.target).add(i.source)});let r=new Map;for(let[i,o]of n)r.set(i,[...o].sort());return r}function Sn(e,t){let n=new Map,r=new Map;return V(e,t,(i,o)=>{if(!o.ordering)return;let{predecessor:s,successor:a}=D(i,o);at(r,s,a),at(n,a,s)}),{incoming:n,outgoing:r}}function Cn(e,t,n){let r=new Map([[e,0]]),i=new Map([[e,1]]),o=new Map,s=[],a=[e],c=0,d=0;for(let l=0;l<a.length;l+=1){let g=a[l];n.visitedNodes+=1,s.push(g);let u=r.get(g);g!==e&&(c+=1,d+=u);for(let f of t.get(g))if(n.inspectedEdges+=1,r.has(f)||(r.set(f,u+1),a.push(f)),r.get(f)===u+1){i.set(f,(i.get(f)??0)+i.get(g));let p=o.get(f);p===void 0?o.set(f,[g]):p.push(g)}}return{stack:s,sigma:i,predecessors:o,reachableCount:c,distanceSum:d}}function Dn(e,t,n){let r=new Map;for(let i=e.stack.length-1;i>=0;i-=1){let o=e.stack[i],s=(1+(r.get(o)??0))/e.sigma.get(o);for(let a of e.predecessors.get(o)??[])r.set(a,(r.get(a)??0)+e.sigma.get(a)*s);o!==t&&n.set(o,(n.get(o)??0)+(r.get(o)??0))}}function Tn(e,t){return t<=1||e.reachableCount===0?0:e.reachableCount/(t-1)*(e.reachableCount/e.distanceSum)}function Nn(e,t,n,r,i){return{id:e,degree:t.get(e).length,inDegree:n.incoming.get(e)?.size??0,outDegree:n.outgoing.get(e)?.size??0,betweenness:st((r.get(e)??0)/2),closeness:st(i.get(e))}}function dt(e,t={}){let n=ct(e,t.kinds),r=Sn(e,t.kinds),i=e.nodes(),o=new Map,s=new Map,a={visitedNodes:0,inspectedEdges:0};for(let l of i){t.signal?.throwIfAborted();let g=Cn(l,n,a);s.set(l,Tn(g,i.length)),Dn(g,l,o)}let c=0;for(let l of n.values())c+=l.length;let d=i.map(l=>Nn(l,n,r,o,s)).sort((l,g)=>g.betweenness-l.betweenness||g.degree-l.degree||l.id.localeCompare(g.id));return{value:{nodeCount:i.length,edgeCount:c/2,rows:d},meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:!1}}}function An(e,t){return e<=t?{source:e,target:t}:{source:t,target:e}}function Rn(e,t,n){let r=t.get(e.node)[e.neighborIndex];if(e.neighborIndex+=1,n.inspectedEdges+=1,r!==e.parent){if(n.discovery.has(r)){n.low.set(e.node,Math.min(n.low.get(e.node),n.discovery.get(r)));return}return e.children+=1,n.discovery.set(r,n.timer),n.low.set(r,n.timer),n.timer+=1,{node:r,parent:e.node,neighborIndex:0,children:0}}}function On(e,t,n){if(e.parent===null){e.children>1&&n.articulation.add(e.node);return}let r=e.parent,i=n.low.get(e.node);n.low.set(r,Math.min(n.low.get(r),i)),r!==t&&i>=n.discovery.get(r)&&n.articulation.add(r),i>n.discovery.get(r)&&n.bridges.push(An(r,e.node))}function jn(e,t,n,r){n.discovery.set(e,n.timer),n.low.set(e,n.timer),n.timer+=1;let i=[{node:e,parent:null,neighborIndex:0,children:0}];for(;i.length>0;){r?.throwIfAborted();let o=i.at(-1);if(o.neighborIndex<t.get(o.node).length){let s=Rn(o,t,n);s!==void 0&&i.push(s)}else On(o,e,n),i.pop()}}function X(e,t={}){let n=ct(e,t.kinds),r={discovery:new Map,low:new Map,timer:0,articulation:new Set,bridges:[],inspectedEdges:0};for(let i of e.nodes())r.discovery.has(i)||jn(i,n,r,t.signal);return{value:{articulationPoints:[...r.articulation].sort(),bridges:r.bridges.sort((i,o)=>i.source.localeCompare(o.source)||i.target.localeCompare(o.target))},meta:{visitedNodes:r.discovery.size,inspectedEdges:r.inspectedEdges,truncated:!1}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32f3ce0d-64ac-5ad4-b27a-2a279718de22")}catch{}})();function Mn(e){let t=e.registry(),n=new Map,r=new Set;for(let i of e.edges()){let o=t.require(i.kind);if(!o.ordering)continue;let{predecessor:s,successor:a}=D(i,o);if(r.add(s),r.add(a),s===a)continue;let c=n.get(s);c===void 0?n.set(s,new Set([a])):c.add(a)}return{forward:n,participants:r}}function Pn(e,t,n,r){if(e===void 0)return r;let i=r;for(let o of e)t.has(o)&&(i=Math.min(i,n.get(o)));return i}function Ln(e,t,n){let r=n-t;return{id:e,earliestStart:t,earliestFinish:t+1,latestStart:n,latestFinish:n+1,slack:r,critical:r===0}}function Fn(e,t,n,r,i){let o=new Map;for(let s=e.length-1;s>=0;s-=1){let a=e[s],c=Pn(t.forward.get(a),r,o,i);o.set(a,c-1)}return e.map(s=>Ln(s,n[s],o.get(s))).sort((s,a)=>s.slack-a.slack||s.earliestStart-a.earliestStart||s.id.localeCompare(a.id))}function lt(e,t={}){t.signal?.throwIfAborted();let n=B(e,{registry:e.registry()}),r=Mn(e),i=new Set(n.order),o=n.order.filter(d=>r.participants.has(d)),s=o.reduce((d,l)=>Math.max(d,n.depth[l]+1),0),a=Fn(o,r,n.depth,i,s),c=a.length>0;return{exact:!0,acyclic:n.acyclic,makespan:s,scheduledCount:a.length,criticalPath:c?n.criticalPath:[],criticalPathLength:c?n.criticalPathLength:0,cycles:n.cycles,rows:a,provenance:{algorithm:"critical-path-method",edgeFamily:"ordering",weighting:"unit"}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fa17672a-97a2-5f94-bdfe-9df970cc038b")}catch{}})();function Gn(e,t,n){for(let r=e.length-1;r>=0;r-=1){n?.throwIfAborted();let i=t.get(e[r]);for(let o of i.successors){n?.throwIfAborted();let s=t.get(o);if(s.latest===void 0||s.duration===void 0)continue;let a=s.latest-s.duration;(i.latest===void 0||a<i.latest)&&(i.latest=a,i.anchor=s.anchor)}}}function $n(e,t,n,r){let i=[],o=e;for(;o!==void 0&&i.length<n;)r?.throwIfAborted(),i.push(o),o=t.get(o).predecessor;return i.reverse(),{path:i,path_truncated:o!==void 0}}function qn(e,t,n,r,i){let o=new Map(t.map(a=>[a.id,a])),s=new Map;for(let a of e){i?.throwIfAborted();let c=o.get(a),d=c?.estimated_minutes,l=typeof d=="number"&&Number.isFinite(d)&&d>=0?d:void 0,g={item:c,duration:l,pending:0,successors:new Set,earliest:0};if(c?.deadline!==void 0){let u=Date.parse(c.deadline);Number.isFinite(u)?(g.deadline=(u-n)/6e4,g.latest=g.deadline,g.anchor=a):r(a,"invalid_deadline")}s.set(a,g)}return s}function Un(e,t,n){for(let r of e.edges()){n?.throwIfAborted();let i=e.registry().require(r.kind);if(!i.ordering)continue;let{predecessor:o,successor:s}=D(r,i),a=t.get(o);a.successors.has(s)||(a.successors.add(s),t.get(s).pending+=1)}}function Bn(e,t,n){let r=e.filter(i=>t.get(i).pending===0);for(let i=0;i<r.length;i+=1){n?.throwIfAborted();let o=r[i],s=t.get(o),a=s.earliest===null||s.duration===void 0?null:s.earliest+s.duration;for(let c of s.successors){n?.throwIfAborted();let d=t.get(c);a===null?d.earliest=null:d.earliest!==null&&(a>d.earliest||a===d.earliest&&(d.predecessor===void 0||o<d.predecessor))&&(d.earliest=a,d.predecessor=o),d.pending-=1,d.pending===0&&r.push(c)}}return r}function zn(e,t,n,r,i,o,s,a){let c=t.duration;if(t.latest!==void 0){r.scheduled_count+=1;let d=t.latest-c;r.rows.length<o?r.rows.push({id:e,deadline_id:t.anchor,latest_start:new Date(i+d*6e4).toISOString(),slack_minutes:t.earliest===null?null:d-t.earliest}):r.truncated=!0}if(t.deadline!==void 0&&t.earliest!==null&&t.earliest+c>t.deadline)if(r.overcommitted_count+=1,r.overcommitted.length<o){let d=$n(e,n,Math.min(o,s.remaining),a);s.remaining-=d.path.length,d.path_truncated&&(r.truncated=!0),r.overcommitted.push({deadline_id:e,deadline:t.item.deadline,shortfall_minutes:t.earliest+c-t.deadline,...d})}else r.truncated=!0}function Hn(e,t,n,r,i,o,s,a){let c={remaining:o};for(let d of e){a?.throwIfAborted();let l=t.get(d);if(l.pending>0){s(d,"cycle_or_gated_by_cycle");continue}if(l.duration===void 0){s(d,"unknown_estimate");continue}if(l.latest!==void 0&&!Number.isFinite(new Date(r+(l.latest-l.duration)*6e4).getTime())){s(d,"date_range_exceeded");continue}l.earliest===null&&s(d,"unknown_predecessor_estimate"),zn(d,l,t,n,r,i,c,a)}}function ut(e,t,n={}){n.signal?.throwIfAborted();let r=Date.parse(n.now??new Date().toISOString());if(!Number.isFinite(r))throw new TypeError("Invalid scheduling clock");let i=n.maxWork??1e5,o=n.limit??10;for(let[u,f]of[["maxWork",i],["limit",o]])if(!Number.isSafeInteger(f)||f<1)throw new TypeError(`Invalid scheduling ${u}`);let s={as_of:new Date(r).toISOString(),basis:"derived_elapsed_minutes",complete:!0,truncated:!1,work_limit_exceeded:!1,scheduled_count:0,residual_count:0,overcommitted_count:0,rows:[],residuals:[],overcommitted:[]},a=e.nodes(),c=e.edges();if(a.length+c.length+t.length>i)return{...s,complete:!1,work_limit_exceeded:!0};let d=(u,f)=>{s.complete=!1,s.residual_count+=1,s.residuals.length<o?s.residuals.push({id:u,reason:f}):s.truncated=!0},l=qn(a,t,r,d,n.signal);Un(e,l,n.signal);let g=Bn(a,l,n.signal);return Gn(g,l,n.signal),Hn(a,l,s,r,o,i,d,n.signal),s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ccb7d865-8baa-5379-a810-7be494eadcb1")}catch{}})();function N(){return{nodes:0,isolated:0,degree_leq_one:0,semantic_nodes:0,without_semantic_edges:0,degree_histogram:{}}}function pt(e,t,n,r){let i={all:N(),active:N(),terminal:N()},o=new Map;for(let s of e.details){if(r?.throwIfAborted(),e.missingIdSet.has(s.id.toLowerCase())||s.status==="external")continue;let a=o.get(s.status)??N();o.set(s.status,a);let c=e.graph.incidentEdges(s.id),d=c.some(l=>n(l.kind));for(let l of[i.all,i[t(s.status)?"terminal":"active"],a]){l.nodes+=1,l.isolated+=+(c.length===0),c.length<=1&&(l.degree_leq_one+=1),d?l.semantic_nodes+=1:l.without_semantic_edges+=1;let g=String(c.length);l.degree_histogram[g]=(l.degree_histogram[g]??0)+1}}return{coverage_by_lifecycle:i,coverage_by_status:Object.fromEntries([...o].sort(([s],[a])=>s.localeCompare(a)))}}function gt(e){if(!J(e))return!1;let t=e;if(!["nodes","isolated","degree_leq_one","semantic_nodes","without_semantic_edges"].every(r=>Number.isSafeInteger(t[r])&&Number(t[r])>=0)||!J(t.degree_histogram))return!1;let n=Object.entries(t.degree_histogram);return n.every(([r,i])=>/^(0|[1-9]\d*)$/.test(r)&&Number.isSafeInteger(i)&&Number(i)>=0)&&n.reduce((r,[,i])=>r+Number(i),0)===t.nodes&&Number(t.isolated)<=Number(t.degree_leq_one)&&Number(t.degree_leq_one)<=Number(t.nodes)&&Number(t.semantic_nodes)+Number(t.without_semantic_edges)===t.nodes}function J(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ht(e){for(let r of["ordering_acyclic","active_ordering_acyclic"])if(e[r]!==void 0&&typeof e[r]!="boolean")return!1;let t=e.coverage_by_lifecycle,n=e.coverage_by_status;return t===void 0&&n===void 0?!0:!J(t)||!J(n)?!1:["all","active","terminal"].every(r=>gt(t[r]))&&Object.values(n).every(gt)}function ft(e,t){return Object.fromEntries([...new Set([...Object.keys(e),...Object.keys(t)])].sort().map(n=>{let r=Object.hasOwn(e,n)?e[n]:N(),i=Object.hasOwn(t,n)?t[n]:N(),o=Object.fromEntries([...new Set([...Object.keys(r.degree_histogram),...Object.keys(i.degree_histogram)])].sort().map(s=>[s,(i.degree_histogram[s]??0)-(r.degree_histogram[s]??0)]));return[n,{nodes:i.nodes-r.nodes,isolated:i.isolated-r.isolated,degree_leq_one:i.degree_leq_one-r.degree_leq_one,semantic_nodes:i.semantic_nodes-r.semantic_nodes,without_semantic_edges:i.without_semantic_edges-r.without_semantic_edges,degree_histogram:o}]}))}function mt(e,t){return!e.coverage_by_lifecycle||!t.coverage_by_lifecycle||!e.coverage_by_status||!t.coverage_by_status?{lifecycle_comparable:!1}:{lifecycle_comparable:!0,coverage_by_lifecycle:ft(e.coverage_by_lifecycle,t.coverage_by_lifecycle),coverage_by_status:ft(e.coverage_by_status,t.coverage_by_status)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="896e1553-b127-532f-ac39-e0d47f29eebc")}catch{}})();var A=["missing_reference_active","missing_reference_terminal","legacy_no_blocker_sentinel","ordering_cycle","legacy_ordering_cycle","ordering_storage_contradiction","legacy_ordering_storage_contradiction","hierarchy_cycle","legacy_hierarchy_cycle","hierarchy_cardinality_violation","legacy_hierarchy_cardinality_violation","hierarchy_direction_violation","legacy_hierarchy_direction_violation","duplicate_edge","legacy_duplicate_edge","duplicate_dependency_row","legacy_duplicate_dependency_row","stale_lifecycle_block","isolated_active_node","sparse_active_node"];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34b2e83e-f6a1-57e7-84ee-4ad83acb2e19")}catch{}})();var Kn=25,Vn="milestone",Wn="outcome milestone:",Yn=new Set(["discovered_from","incident_from","recurs_from","supersedes","verifies"]);function Q(e){return Yn.has(e)}var _t={error:0,warning:1,info:2};function yt(e){return new Set((e??[]).filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()))}function R(e,t,n,r,i,o,s,a){let c=[...i].sort((d,l)=>d.localeCompare(l));return{code:e,severity:t,policy:n,message:r(c.length),count:c.length,sample:c.slice(0,o),sample_truncated:c.length>o,remediation:s,...a===void 0?{}:{evidence:[...a].sort((d,l)=>d.localeCompare(l)).slice(0,o)}}}function Xn(e,t){return e.cycles.map(n=>R(n.legacy_terminal?"legacy_hierarchy_cycle":"hierarchy_cycle",n.legacy_terminal?"info":"error","Structural hierarchy must be acyclic across scalar and registered dependency relationships.",r=>`${r} items participate in one hierarchy cycle.`,n.item_ids,t,n.legacy_terminal?"Preserve historical rows unless an explicit legacy repair is approved.":"Remove or retype one exact hierarchy relation before continuing mutation."))}function bt(e,t,n){let r=e.cardinality_violations.filter(i=>i.legacy_terminal===n);return r.length===0?[]:[R(n?"legacy_hierarchy_cardinality_violation":"hierarchy_cardinality_violation",n?"info":"error","Every structural child must resolve to at most one logical parent across all hierarchy spellings.",i=>`${i} child item${i===1?"":"s"} resolve to multiple hierarchy parents.`,r.map(i=>i.child_id),t,n?"Preserve historical rows unless an explicit legacy repair is approved.":"Remove the exact surplus hierarchy rows so each child has one parent.",r.map(i=>`${i.child_id} <- ${i.parent_ids.join(", ")}`))]}function vt(e,t,n){let r=e.divergences.filter(i=>i.legacy_terminal===n);return r.length===0?[]:[R(n?"legacy_hierarchy_direction_violation":"hierarchy_direction_violation",n?"info":"error","Scalar parent metadata and dependency-backed hierarchy rows must resolve to the same logical parent.",i=>`${i} child item${i===1?"":"s"} have divergent hierarchy storage surfaces.`,r.map(i=>i.child_id),t,n?"Preserve historical rows unless an explicit legacy repair is approved.":"Align the scalar parent and exact dependency rows to one canonical parent.",r.map(i=>`${i.child_id}: scalar=${i.scalar_parent_id} dependencies=${i.dependency_parent_ids.join(",")}`))]}function Jn(e,t){let n=G(e);return n?[...Xn(n,t),...bt(n,t,!1),...bt(n,t,!0),...vt(n,t,!1),...vt(n,t,!0)]:[]}function Qn(e){let t=e.graph.registry(),n=new Map;for(let r of e.graph.edges()){let i=t.require(r.kind);if(!i.ordering)continue;let[o,s]=(i.precedence??"source_before_target")==="target_before_source"?[r.target,r.source]:[r.source,r.target],a=n.get(o);a?a.push(s):n.set(o,[s])}for(let r of n.values())r.sort((i,o)=>i.localeCompare(o));return n}function kt(e,t){t.indexes.set(e,t.nextIndex),t.lowLinks.set(e,t.nextIndex),t.nextIndex+=1,t.stack.push(e),t.onStack.add(e)}function Zn(e,t,n,r){let i=n.get(e.node)??[];if(e.neighborIndex>=i.length)return!1;let o=i[e.neighborIndex];return e.neighborIndex+=1,r.indexes.has(o)?r.onStack.has(o)&&r.lowLinks.set(e.node,Math.min(r.lowLinks.get(e.node),r.indexes.get(o))):(kt(o,r),t.push({node:o,neighborIndex:0})),!0}function er(e,t,n,r){t.pop();let i=t.at(-1);if(i&&r.lowLinks.set(i.node,Math.min(r.lowLinks.get(i.node),r.lowLinks.get(e.node))),r.lowLinks.get(e.node)!==r.indexes.get(e.node))return;let o=[];for(;;){let s=r.stack.pop();if(r.onStack.delete(s),o.push(s),s===e.node)break}(o.length>1||o.length===1&&n.get(o[0])?.includes(o[0]))&&r.components.push(o.sort((s,a)=>s.localeCompare(a)))}function tr(e){let t={indexes:new Map,lowLinks:new Map,onStack:new Set,stack:[],components:[],nextIndex:0},n=[...e.keys()].sort((r,i)=>r.localeCompare(i));for(let r of n){if(t.indexes.has(r))continue;let i=[{node:r,neighborIndex:0}];for(kt(r,t);i.length>0;){let o=i.at(-1);Zn(o,i,e,t)||er(o,i,e,t)}}return t.components.sort((r,i)=>r[0].localeCompare(i[0]))}function ce(e){return`${e.holder_id} -> ${e.target_id} (${e.kind})`}function y(e,t,n,r,i,o,s,a){t.length!==0&&e.push(R(r,i,o,s,t,n,a))}function nr(e,t,n){let r=[],i=[...e.dangling.active,...e.dangling.legacy_terminal].filter(o=>!o.no_active_blocker_sentinel);return y(r,i.filter(o=>!t(o.holder_status)).map(ce),n,"missing_reference_active","error","Active items must not reference absent targets; missing prerequisites distort scheduling.",o=>`${o} active dangling reference(s) to absent items`,"Restore or re-create the referenced item, or remove/retype the reference on the holder."),y(r,i.filter(o=>t(o.holder_status)).map(ce),n,"missing_reference_terminal","info","Terminal items may retain historical references, but absent targets remain unexplainable context.",o=>`${o} terminal dangling reference(s) to absent items`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),y(r,e.dangling.no_active_blocker_sentinels.map(ce),n,"legacy_no_blocker_sentinel","info","The pre-structured-dependency no-active-blocker sentinel is retired; real edges carry blocker state.",o=>`${o} legacy no-active-blocker sentinel reference(s)`,"Delete the sentinel reference; blocker state is derived from blocked_by edges."),r}function le(e,t){let n=t.get(e);return n?!n.terminal:!0}function It(e){return`${e.holder_id} -> ${e.target_id} (blocked_by scalar + ${e.dependency_kind} dependency)`}function rr(e,t){let n=[],r=[];for(let o of e.orderingContradictions??[])(o.legacy_terminal?r:n).push(It(o));let i=[];return y(i,n,t,"ordering_storage_contradiction","error","A scalar blocker and same-target structured ordering row must not assert opposite precedence.",o=>`${o} active scalar-versus-structured ordering contradiction(s)`,"Remove the structured dependency row that points the holder before its scalar blocker, or replace both representations with one unambiguous ordering edge."),y(i,r,t,"legacy_ordering_storage_contradiction","info","Terminal scalar-versus-structured ordering contradictions are exact historical storage defects with no live scheduling effect.",o=>`${o} terminal scalar-versus-structured ordering contradiction(s)`,"Remove the contradictory blocks dependency row in a dedicated changelog-safe closed-item batch; preserve the scalar blocker as the historical precedence record."),i}function ir(e,t,n,r){let i=[],o=Qn(e);for(let c of tr(o)){let d=c.some(u=>le(u,t)),l=new Set(c.map(u=>u.toLowerCase())),g=(e.orderingContradictions??[]).filter(u=>l.has(u.holder_id.toLowerCase())&&l.has(u.target_id.toLowerCase())).map(It);i.push(d?R("ordering_cycle","error","Order-bearing relationship kinds must stay acyclic; a cycle makes every member unschedulable.",u=>`execution-order cycle across ${u} item(s)`,c,r,"Remove or retype one ordering edge inside the cycle, or split the work so precedence is linear.",g.length===0?void 0:g):R("legacy_ordering_cycle","info","Ordering cycles between exclusively terminal items are historical contradictions with no scheduling effect.",u=>`terminal-only execution-order cycle across ${u} item(s)`,c,r,"Leave as history debt, or clean up in a dedicated changelog-safe closed-item batch; never repair closed items ad hoc.",g.length===0?void 0:g))}let s=new Map;for(let[c,d]of o)for(let l of d){let g=s.get(l);g?g.push(c):s.set(l,[c])}let a=[...t.values()].filter(c=>!c.missing&&!c.terminal&&n(c.status)&&!(s.get(c.id)??[]).some(d=>{let l=t.get(d);return l===void 0||!l.terminal})).map(c=>c.id);return y(i,a,r,"stale_lifecycle_block","warning","A blocked lifecycle status must be backed by at least one open ordering predecessor.",c=>`${c} status-blocked item(s) with no open blocker edge`,'Add a local blocker edge, declare an external blocker with --dep "id=<external-ref>,kind=blocked_by,source_kind=external", or move the item back to an active status.'),i}function Z(e){let t=e.edges.map(n=>n.kind).sort((n,r)=>n.localeCompare(r));return`${e.from} -> ${e.to} (${t.join(" + ")})`}function ue(e){let t=e.graph.registry(),n=new Map;for(let i of e.graph.edges()){let o=t.require(i.kind);if(!W(o))continue;let s=ae(i,o);if(s.from===s.to)continue;let a=`${Y(o)}::${s.from}::${s.to}`,c=n.get(a);c?c.edges.push(i):n.set(a,{...s,edges:[i]})}let r=[...n.values()].filter(i=>i.edges.length>=2);for(let i of r)i.edges.sort((o,s)=>o.kind.localeCompare(s.kind));return r.sort((i,o)=>i.from.localeCompare(o.from)||i.to.localeCompare(o.to))}function or(e,t,n){let r=[],i=[];for(let s of ue(e))(le(s.from,t)||le(s.to,t)?r:i).push(Z(s));let o=[];return y(o,r,n,"duplicate_edge","info","One semantic relationship should be stored once; parallel same-family spellings (reciprocal inverse pairs included) add no information and skew degree metrics.",s=>`${s} duplicated relationship(s) between active endpoints`,"Remove all but one stored spelling of the relationship; keep the canonical direction the holder declared first."),y(o,i,n,"legacy_duplicate_edge","info","Duplicated spellings between exclusively terminal items are historical noise with no scheduling effect.",s=>`${s} duplicated relationship(s) between terminal endpoints`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),o}function sr(e,t){let n=[],r=[];for(let o of e.duplicateRows??[])(o.legacy_terminal?r:n).push(`${o.holder_id} -> ${o.target_id} (${o.kind} x${o.occurrences})`);let i=[];return y(i,n,t,"duplicate_dependency_row","warning","One dependency row must be stored once per holder; identical repeated rows are a storage-layer defect invisible to the assembled graph.",o=>`${o} exactly duplicated stored dependency row(s) on active holder(s)`,"Remove the repeated rows so the dependency is stored exactly once; graph semantics are unchanged."),y(i,r,t,"legacy_duplicate_dependency_row","info","Identical repeated dependency rows on terminal holders are historical storage noise with no scheduling effect.",o=>`${o} exactly duplicated stored dependency row(s) on terminal holder(s)`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),i}function ar(e,t){let n=new Map,r={source_to_target:[],target_to_source:[],both:[]};for(let s of e.graph.registry().list())s.outcomeTraversal!==void 0&&r[s.outcomeTraversal].push(s.kind);let i={source_to_target:r.source_to_target.join(","),target_to_source:r.target_to_source.join(","),both:r.both.join(",")},o=(s,a)=>{let c=n.get(a)??new Set;c.add(s),n.set(a,c)};for(let s of e.graph.edges()){t?.throwIfAborted();let a=e.graph.registry().require(s.kind);(a.outcomeTraversal==="source_to_target"||a.outcomeTraversal==="both")&&o(s.source,s.target),(a.outcomeTraversal==="target_to_source"||a.outcomeTraversal==="both")&&o(s.target,s.source)}return{basis:i,reverse:n}}function cr(e,t,n){let r=new Set(e),i=[...e].sort();for(let o=0;o<i.length;o+=1){n?.throwIfAborted();for(let s of[...t.get(i[o])??[]].sort())r.has(s)||(r.add(s),i.push(s))}return r}function dr(e,t,n,r){let i=0,o=0,s=0,a=0;for(let f of e.values())if(r?.throwIfAborted(),!t.has(f.id)&&!(f.missing||f.status==="external")){if(f.terminal){s+=1,n.has(f.id)&&(a+=1);continue}n.has(f.id)?i+=1:o+=1}let c=i+o,d=s-a,l=i+a,g=o+d,u=l+g;return{active_outcome_reachable_nodes:i,active_outcome_unreachable_nodes:o,active_outcome_reachability_basis_points:c===0?0:Math.floor(i*1e4/c),terminal_nodes:s,terminal_outcome_reachable_nodes:a,terminal_outcome_unreachable_nodes:d,terminal_outcome_reachability_basis_points:s===0?0:Math.floor(a*1e4/s),outcome_reachable_nodes:l,outcome_unreachable_nodes:g,outcome_reachability_basis_points:u===0?0:Math.floor(l*1e4/u)}}function lr(e,t,n){let r=new Set(e.details.filter(a=>a.type?.toLowerCase()===Vn&&a.title.trim().toLowerCase().startsWith(Wn)).map(a=>a.id)),{basis:i,reverse:o}=ar(e,n),s=cr(r,o,n);return{outcome_nodes:r.size,outcome_reachability_basis:i,...dr(t,r,s,n)}}function ur(e,t,n,r,i){e.active+=1;let o=t.type??"(untyped)",s=e.byType.get(o);s||(s={active:0,isolated:0,degree_leq_one:0},e.byType.set(o,s)),s.active+=1,!(n>1)&&(e.degreeLeqOne+=1,s.degree_leq_one+=1,n===0&&(e.isolated+=1,s.isolated+=1),!(r.has(t.id.toLowerCase())||i.has(o.toLowerCase()))&&(n===0?e.isolates.push(t.id):e.sparse.push(t.id)))}function gr(e,t,n,r,i,o,s){let a={active:0,missing:0,isolated:0,degreeLeqOne:0,isolates:[],sparse:[],byType:new Map};for(let h of e.graph.nodes()){s?.throwIfAborted();let _=t.get(h);if(_){if(_.missing){a.missing+=1;continue}_.terminal||ur(a,_,e.graph.incidentEdges(h).length,n,r)}}let{isolates:c,sparse:d}=a,l=[];y(l,c,i,"isolated_active_node","warning","Active work should be reachable from the graph unless explicitly declared a valid isolate.",h=>`${h} active item(s) with no relationships`,"Link the item to its parent, prerequisite, or origin \u2014 or register it as an exempt isolate."),y(l,d,i,"sparse_active_node","info","Active items with a single edge often miss an honest semantic partner; sparse is not automatically defective.",h=>`${h} active item(s) with exactly one relationship`,"Investigate for an honest second edge (story->task, defect family, cross-epic complement); do not fabricate one.");let g=e.graph.edges().length,u=T(e.graph,{signal:s}).value,f=new Set(u.map(({edge:h})=>`${h.source.toLowerCase()}\0${h.target.toLowerCase()}\0${h.kind}`));for(let h of e.orderingContradictions??[])f.add(`${h.holder_id.toLowerCase()}\0${h.target_id.toLowerCase()}\0${h.dependency_kind}`);let p=Object.fromEntries(Object.entries(o).sort(([h],[_])=>h.localeCompare(_))),m=Object.entries(p).reduce((h,[_,E])=>h+(Q(_)?E:0),0),b=X(e.graph,{signal:s}).value,v=lr(e,t,s);return{findings:l,profile:{nodes:e.graph.nodes().length,recorded_nodes:e.details.filter(h=>h.status!=="missing"&&h.status!=="external").length,edges:g,informative_edges:g-f.size,redundant_edges:u.length,ordering_contradiction_edges:e.orderingContradictions?.length??0,edge_basis:"deduplicated_directed",edges_by_kind:p,edge_share_by_kind:Object.fromEntries(Object.entries(p).map(([h,_])=>[h,_/g])),semantic_edges:m,semantic_edge_share:g===0?0:m/g,active_nodes:a.active,missing_nodes:a.missing,isolated_active_nodes:a.isolated,degree_leq_one_active_nodes:a.degreeLeqOne,coverage_by_type:Object.fromEntries([...a.byType.entries()].sort(([h],[_])=>h<_?-1:1)),articulation_points:b.articulationPoints.length,bridge_edges:b.bridges.length,...v,finding_subjects_by_code:Object.fromEntries(A.map(h=>[h,0]))}}}function ee(e,t={}){let n=t.isTerminal??(u=>u==="closed"||u==="canceled"),r=t.isBlocked??(u=>u==="blocked"),i=t.maxSampleSize??Kn;if(!Number.isInteger(i)||i<1)throw new TypeError(`Invalid audit sample bound: ${String(t.maxSampleSize)}`);let o=yt(t.exemptIsolates),s=yt(t.isolateExemptTypes),a=new Map(e.details.map(u=>[u.id,{id:u.id,status:u.status,missing:e.missingIdSet.has(u.id.toLowerCase()),terminal:n(u.status),...u.type===void 0?{}:{type:u.type}}]));t.signal?.throwIfAborted();let c={};for(let u of e.graph.edges())c[u.kind]=(c[u.kind]??0)+1;let d=nr(e,n,i);d.push(...Jn(e,i)),t.signal?.throwIfAborted(),d.push(...rr(e,i)),t.signal?.throwIfAborted(),d.push(...ir(e,a,r,i)),t.signal?.throwIfAborted(),d.push(...or(e,a,i),...sr(e,i)),t.signal?.throwIfAborted();let l=gr(e,a,o,s,i,c,t.signal);d.push(...l.findings),d.sort((u,f)=>_t[u.severity]-_t[f.severity]||u.code.localeCompare(f.code)||u.sample[0].localeCompare(f.sample[0]));let g=l.profile.finding_subjects_by_code;for(let u of d)g[u.code]+=u.count;return{findings:d,profile:{...l.profile,...pt(e,n,Q,t.signal),ordering_acyclic:!d.some(u=>u.code==="ordering_cycle"||u.code==="legacy_ordering_cycle"),active_ordering_acyclic:!d.some(u=>u.code==="ordering_cycle"),finding_subjects_by_code:g}}}function de(e,t){let n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort(),r={};for(let i of n){let o=(t[i]??0)-(e[i]??0);o!==0&&(r[i]=o)}return r}function wt(e){return e.profile.coverage_by_type??{}}function fr(e,t){let n={},r=wt(e),i=wt(t),o=[...new Set([...Object.keys(r),...Object.keys(i)])].sort();for(let s of o){let a=Object.assign({active:0,isolated:0,degree_leq_one:0},r[s]),c=Object.assign({active:0,isolated:0,degree_leq_one:0},i[s]),d={active:c.active-a.active,isolated:c.isolated-a.isolated,degree_leq_one:c.degree_leq_one-a.degree_leq_one};Object.values(d).some(l=>l!==0)&&(n[s]=d)}return n}function xt(e,t){let n=fr(e,t),{edge_share_by_kind:r={},semantic_edges:i=0,semantic_edge_share:o=0}=e.profile,{edge_share_by_kind:s={},semantic_edges:a=0,semantic_edge_share:c=0}=t.profile,d=e.profile.recorded_nodes??e.profile.nodes,l=t.profile.recorded_nodes??t.profile.nodes,g=e.profile.informative_edges??e.profile.edges,u=t.profile.informative_edges??t.profile.edges,f=e.profile.redundant_edges??0,p=t.profile.redundant_edges??0,m=e.profile.ordering_contradiction_edges??0,b=t.profile.ordering_contradiction_edges??0;return{baseline_saved_at:e.saved_at,same_snapshot:e.fingerprint===t.fingerprint,affected_subjects_by_code:de(e.affected_subjects_by_code,t.affected_subjects_by_code),profile:{nodes:t.profile.nodes-e.profile.nodes,recorded_nodes:l-d,edges:t.profile.edges-e.profile.edges,informative_edges:u-g,redundant_edges:p-f,ordering_contradiction_edges:b-m,active_nodes:t.profile.active_nodes-e.profile.active_nodes,missing_nodes:t.profile.missing_nodes-e.profile.missing_nodes,isolated_active_nodes:t.profile.isolated_active_nodes-e.profile.isolated_active_nodes,degree_leq_one_active_nodes:t.profile.degree_leq_one_active_nodes-e.profile.degree_leq_one_active_nodes,edges_by_kind:de(e.profile.edges_by_kind,t.profile.edges_by_kind),edge_share_by_kind:de(r,s),semantic_edges:a-i,semantic_edge_share:c-o,coverage_by_type:n,...mt(e.profile,t.profile)}}}import Et from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5089f2d-3fc5-5843-95ab-ba3dd2ab9582")}catch{}})();var St=2,ge=500,pr=64,hr="graph-durable-cache";function Ct(e){return Re(e,hr,30,`graph-cache:${process.pid}`,!1,!1,3e3)}function F(e){return Et.join(e,"runtime","graph-cache.json")}function Dt(e){return Et.join(e,"runtime","graph-audit-baseline.json")}function fe(e){if(e!==null)try{let t=JSON.parse(e);return typeof t!="object"||t===null||t.version!==St||typeof t.fingerprint!="string"||typeof t.saved_at!="string"||typeof t.results!="object"||t.results===null||Array.isArray(t.results)?void 0:t}catch{return}}async function pe(e,t){let n=await j(F(e)),r=fe(n),i=r?.fingerprint===t;return{exists:n!==null,fresh:i,results:i?r.results:{}}}async function he(e,t,n,r,i){let o=await Ct(e);try{let s=fe(await j(F(e))),a=s?.fingerprint===t?s.results:{};delete a[r],a[r]=i;let c=Object.keys(a);for(let d of c.slice(0,Math.max(0,c.length-pr)))delete a[d];await re(F(e),JSON.stringify({version:St,fingerprint:t,saved_at:new Date().toISOString(),results:a})),n.results=a}finally{await o()}}async function me(e){let t=await Ct(e);try{await Ie(F(e))}finally{await t()}}async function Tt(e,t){let n=F(e),r=await j(n),i=fe(r);return i===void 0?{exists:r!==null,fresh:!1,entry_count:0}:{exists:!0,fresh:i.fingerprint===t,entry_count:Object.keys(i.results).length,fingerprint:i.fingerprint.slice(0,12),saved_at:i.saved_at,bytes:Buffer.byteLength(r,"utf8")}}function _e(e,t){return t||e>=ge}function te(e){return O(e)&&Object.values(e).every(x)}function O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function x(e){return Number.isInteger(e)&&Number(e)>=0}function Nt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function L(e,t){return e===void 0||t(e)}function mr(e){return O(e)&&Object.values(e).every(Nt)}function _r(e){return O(e)?Object.values(e).every(t=>O(t)&&[t.active,t.isolated,t.degree_leq_one].every(x)):!1}function yr(e,t,n){let r=["recorded_nodes","informative_edges","redundant_edges","ordering_contradiction_edges"],i=r.filter(s=>e[s]!==void 0).length;if(i!==0&&i!==r.length||!r.every(s=>L(e[s],x)))return;let o={recorded_nodes:e.recorded_nodes??t,informative_edges:e.informative_edges??n,redundant_edges:e.redundant_edges??0,ordering_contradiction_edges:e.ordering_contradiction_edges??0};return o.recorded_nodes<=t&&o.informative_edges<=n&&o.redundant_edges<=n&&o.ordering_contradiction_edges<=n?o:void 0}function br(e,t,n){let r=[...t,...n,"finding_subjects_by_code"],i=r.filter(o=>e[o]!==void 0).length;return i!==0&&i!==r.length?!1:t.every(o=>L(e[o],x))&&n.every(o=>L(e[o],x)&&(e[o]===void 0||Number(e[o])<=1e4))&&L(e.finding_subjects_by_code,te)}function vr(e,t,n,r){let i=yr(e,n,r);if(i===void 0)return;let o=["articulation_points","bridge_edges","outcome_nodes","active_outcome_reachable_nodes","active_outcome_unreachable_nodes","terminal_nodes","terminal_outcome_reachable_nodes","terminal_outcome_unreachable_nodes","outcome_reachable_nodes","outcome_unreachable_nodes"],s=["active_outcome_reachability_basis_points","terminal_outcome_reachability_basis_points","outcome_reachability_basis_points"];if(!br(e,o,s)||e.edge_basis!==void 0&&e.edge_basis!=="deduplicated_directed")return;let a=te(e.finding_subjects_by_code)?e.finding_subjects_by_code:{};return{edge_basis:"deduplicated_directed",...i,...Object.fromEntries(o.map(c=>[c,e[c]??0])),...Object.fromEntries(s.map(c=>[c,e[c]??0])),finding_subjects_by_code:Object.fromEntries(A.map(c=>[c,a[c]??t[c]??0]))}}function wr(e,t,n,r,i){let o=[n,r,i],s=o.filter(d=>d!==void 0).length;if(s===0)return{edge_share_by_kind:{},semantic_edges:0,semantic_edge_share:0};if(s!==o.length||!mr(n)||!x(r)||!Nt(i))return;let a=Object.entries(t);if(a.reduce((d,[,l])=>d+l,0)!==e||Object.keys(n).length!==a.length||a.some(([d,l])=>n[d]!==(e===0?0:l/e)))return;let c=a.reduce((d,[l,g])=>d+(Q(l)?g:0),0);if(!(r!==c||i!==(e===0?0:c/e)))return{edge_share_by_kind:n,semantic_edges:r,semantic_edge_share:i}}function kr(e){if(e!==null)try{let t=JSON.parse(e);if(!O(t))return;let n=t,r=n.profile;if(typeof n.saved_at!="string"||typeof n.fingerprint!="string")return;let i=n.affected_subjects_by_code;if(!te(i)||!O(r)||!ht(r)||![r.nodes,r.edges,r.active_nodes,r.missing_nodes,r.isolated_active_nodes,r.degree_leq_one_active_nodes].every(x)||!te(r.edges_by_kind)||!L(r.coverage_by_type,_r))return;let o=wr(r.edges,r.edges_by_kind,r.edge_share_by_kind,r.semantic_edges,r.semantic_edge_share);if(o===void 0)return;let s=vr(r,i,r.nodes,r.edges);if(s===void 0)return;let{coverage_by_type:a={}}=r;return{...n,profile:{...r,...o,...s,coverage_by_type:a}}}catch{return}}async function At(e){return kr(await j(Dt(e)))}async function Rt(e,t){await re(Dt(e),JSON.stringify(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="253f392d-4e91-57ec-b656-6134583d57e5")}catch{}})();var Ir={missing_reference_active:{op:"investigate",confidence:"medium",rationale:"Restore or re-create the referenced item, or remove/retype the reference on the active holder; the correct fix depends on why the target is absent."},missing_reference_terminal:{op:"waive",confidence:"high",rationale:"Terminal-holder reference to an absent item is historical debt; waive it or clean it up only in a dedicated changelog-safe closed-item batch."},legacy_no_blocker_sentinel:{op:"remove",confidence:"high",rationale:"The pre-structured-dependency no-active-blocker sentinel is retired and carries no information; blocker state derives from blocked_by edges."},ordering_cycle:{op:"investigate",confidence:"low",rationale:"Every cycle member is unschedulable until one ordering edge is removed or retyped; the planner never chooses which edge to cut."},legacy_ordering_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only ordering cycles have no scheduling effect; repairing them would mutate closed history (changelog drag)."},ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The structured ordering row asserts the opposite precedence from the same-target scalar blocker; remove that exact dependency row or replace both representations with one unambiguous edge."},legacy_ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The terminal holder contains a proven contradictory structured ordering row; remove it in a dedicated changelog-safe batch while preserving the scalar blocker as history."},hierarchy_cycle:{op:"investigate",confidence:"low",rationale:"Cut or retype one exact structural relation in the cycle; the planner preserves every evidence row because intent determines the correct parent."},legacy_hierarchy_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only hierarchy cycles are historical debt; waive them unless an explicit closed-history repair is approved."},hierarchy_cardinality_violation:{op:"investigate",confidence:"medium",rationale:"Choose the canonical parent and remove or retype the exact surplus hierarchy rows; the planner cannot infer ownership intent."},legacy_hierarchy_cardinality_violation:{op:"waive",confidence:"high",rationale:"Multiple parents confined to terminal items are historical debt; waive them unless a dedicated history repair is approved."},hierarchy_direction_violation:{op:"investigate",confidence:"medium",rationale:"Align the scalar parent and dependency-backed hierarchy rows to the intended canonical parent."},legacy_hierarchy_direction_violation:{op:"waive",confidence:"high",rationale:"Divergent hierarchy storage confined to terminal items is historical debt; waive it unless a dedicated history repair is approved."},duplicate_edge:{op:"remove",confidence:"high",rationale:"Parallel same-family spellings state one relationship twice; remove all but one stored spelling, keeping the holder's canonical direction."},legacy_duplicate_edge:{op:"waive",confidence:"high",rationale:"Duplicated spellings between terminal items are historical noise; waive or batch changelog-safe cleanup."},duplicate_dependency_row:{op:"remove",confidence:"high",rationale:"The identical dependency row is stored more than once on the holder; drop the repeats so the row exists exactly once \u2014 graph semantics are unchanged."},legacy_duplicate_dependency_row:{op:"waive",confidence:"high",rationale:"Repeated identical rows on terminal holders are storage noise; waive or clean up only in a changelog-safe closed-item batch."},stale_lifecycle_block:{op:"investigate",confidence:"medium",rationale:`Add a local ordering edge, declare an external blocker with --dep "id=<external-ref>,kind=blocked_by,source_kind=external", or move the item back to an active status; only the holder's owner knows which is true.`},isolated_active_node:{op:"investigate",confidence:"medium",rationale:"Link the item to its parent, prerequisite, or origin \u2014 or register it as an explicitly exempt isolate; the audit never fabricates an edge."},sparse_active_node:{op:"investigate",confidence:"low",rationale:"Investigate for an honest second edge (story-to-task, defect family, cross-epic complement); sparse is not automatically defective."}};function Ot(e){return`${e.source} -${e.kind}-> ${e.target}`}function xr(e){let[t,...n]=e.edges;return n.map(r=>({op:"remove",code:"duplicate_edge",subject:Ot(r),rationale:"This stored spelling restates the kept canonical edge of the same semantic family; removing it leaves the relationship stated exactly once.",evidence:[`keep: ${Ot(t)}`,`group: ${Z(e)}`],confidence:"high"}))}function Er(e,t){if(e.code==="duplicate_edge")return e.sample.flatMap(r=>xr(t.get(r)));let n=Ir[e.code];return e.sample.map(r=>({op:n.op,code:e.code,subject:r,rationale:n.rationale,evidence:[e.policy],confidence:n.confidence}))}function jt(e,t={}){let{redundancyLimit:n,...r}=t,i=ee(e,r),o=new Map(ue(e).map(d=>[Z(d),d])),s=i.findings.flatMap(d=>Er(d,o)),a=i.findings.some(d=>d.sample_truncated);t.signal?.throwIfAborted();let c=T(e.graph,{limit:n??t.maxSampleSize??25,...t.signal===void 0?{}:{signal:t.signal}});for(let d of c.value)s.push({op:"remove",code:"redundant_edge",subject:`${d.edge.source} -> ${d.edge.target} (${d.edge.kind})`,rationale:"The stored edge is implied by a longer same-family witness path; shortcut edges are sometimes deliberate emphasis, so confirm intent before removing.",evidence:[`witness: ${d.witness.join(" -> ")}`],confidence:"medium"});return a=a||c.meta.truncated,{steps:s,report:i,truncated:a,cost:{visitedNodes:c.meta.visitedNodes,inspectedEdges:c.meta.inspectedEdges}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="66df3949-0caf-5f01-8cec-3bba3d1e6111")}catch{}})();var Ft=new Set(["ancestors","descendants","predecessors","successors","paths","impact","dominators"]);function Mt(e,t,n){let r=e;if(t&&e.subcommand==="audit"){let{nodes:i,recorded_nodes:o,edges:s,active_nodes:a,terminal_nodes:c,missing_nodes:d,ordering_acyclic:l,active_ordering_acyclic:g,coverage_by_lifecycle:u}=e.profile,f=Object.fromEntries(Object.entries(u).map(([p,m])=>{let{degree_histogram:b,...v}=m;return[p,v]}));r={...e,profile:{nodes:i,recorded_nodes:o,edges:s,active_nodes:a,terminal_nodes:c,missing_nodes:d,ordering_acyclic:l,active_ordering_acyclic:g,coverage_by_lifecycle:f}}}return{...r,projection:{mode:t?"summary":"full",declared_field_groups:n===void 0?[]:[{name:n,restore_with:"--full"}],included_field_groups:n===void 0||t?[]:[n]}}}function Sr(e,t,n,r){return{assembly:t,...n===void 0?{}:{kinds:n},maxDepth:Ue(r.maxDepth),limit:e==="impact"&&Number(r.limit)===0?0:$(r.limit,"limit")??(r.full===!0?Number.MAX_SAFE_INTEGER:I.rows),after:r.after?.trim()||void 0,direction:Be(r.direction),maxPaths:$(r.maxPaths,"max-paths"),sample:$(r.sample,"sample")??I.samples,exemptIsolates:Pt(r.exemptIsolate),exemptIsolateTypes:Pt(r.exemptIsolateType),saveBaseline:r.saveBaseline===!0,summary:r.summary===!0,unbounded:r.full===!0}}function Pt(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function Cr(e,t,n){let r=e.trim().toLowerCase();if(!ie.includes(r))throw Oe({command_path:"graph",token:r||"<empty>",allowed:ie});let i=r;if(Ft.has(i)&&!t?.trim())throw new k(`graph ${i} requires an item id.`,w.USAGE);if(i==="paths"&&!n?.trim())throw new k("graph paths requires a source and a target item id.",w.USAGE);return i}function ye(e){throw e instanceof TypeError?new k(e.message,w.USAGE):e}function be(e){return{truncated:e.truncated,cost:{visited_nodes:e.visitedNodes,inspected_edges:e.inspectedEdges}}}function Lt(e,t){let n=t.trim().toLowerCase();for(let r of e.details)if(r.id.trim().toLowerCase()===n&&!e.missingIdSet.has(r.id.toLowerCase()))return r.id;throw new k(`Item ${t} not found`,w.NOT_FOUND)}function Dr(e,t,n){let r={ancestors:Qe,descendants:Ze,predecessors:et,successors:tt}[e],i;try{i=r(n.assembly.graph,t,{...n.kinds===void 0?{}:{kinds:n.kinds},...n.maxDepth===void 0?{}:{maxDepth:n.maxDepth},limit:n.limit,...n.after===void 0?{}:{after:n.after}})}catch(s){ye(s)}let o=be(i.meta);return{subcommand:e,root:t,count:i.value.length,...o,...i.meta.nextCursor===void 0?{}:{next_cursor:i.meta.nextCursor},...n.summary?{}:{ids:i.value}}}function Tr(e,t,n){let r=nt(n.assembly.graph,e,t,{direction:n.direction,...n.kinds===void 0?{}:{kinds:n.kinds},...n.maxDepth===void 0?{}:{maxDepth:n.maxDepth},...n.maxPaths===void 0?{}:{maxPaths:n.maxPaths}});return{subcommand:"paths",root:e,target:t,direction:n.direction,count:r.value.length,...be(r.meta),...n.summary?{}:{paths:r.value.map(i=>({nodes:i.nodes,kinds:i.edges.map(o=>o.kind),length:i.length}))}}}function Nr(e,t){let n;try{n=U(t.assembly.graph,e,{direction:t.direction,...t.kinds===void 0?{}:{kinds:t.kinds},...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth},...t.unbounded?{}:{limit:t.limit},...t.after===void 0?{}:{after:t.after}})}catch(r){ye(r)}return{subcommand:"impact",root:e,direction:t.direction,count:n.affected.length,truncated:n.truncated,...n.nextCursor===void 0?{}:{next_cursor:n.nextCursor},cost:{visited_nodes:n.cost.visitedNodes,inspected_edges:n.cost.inspectedEdges},...t.summary?{}:{affected:n.affected}}}function Ar(e,t,n){return{acyclic:e.acyclic,ordered_node_count:e.order.length,layer_count:e.layers.length,frontier_count:e.frontier.length,critical_path_length:e.criticalPathLength,cycle_count:e.cycles.length,...t?{}:{frontier:e.frontier.slice(0,n),critical_path:e.criticalPath.slice(0,n),cycles:e.cycles.slice(0,n)}}}function Rr(e,t,n){return{component_count:e.components.length,largest_component_size:e.components[0]?.length??0,orphan_count:e.orphans.length,...t?{}:{orphans:e.orphans.slice(0,n),hubs:e.hubs.slice(0,n)}}}function Or(e,t,n){let r=0,i=0,o=0;for(let s of e.cycles)r+=Number(s.legacy_terminal);for(let s of e.cardinality_violations)i+=Number(s.legacy_terminal);for(let s of e.divergences)o+=Number(s.legacy_terminal);return{acyclic:e.cycles.length===0,relation_count:e.relations.length,cycle_count:e.cycles.length,active_cycle_count:e.cycles.length-r,legacy_cycle_count:r,cardinality_violation_count:e.cardinality_violations.length,active_cardinality_violation_count:e.cardinality_violations.length-i,legacy_cardinality_violation_count:i,parent_divergence_count:e.divergences.length,active_parent_divergence_count:e.divergences.length-o,legacy_parent_divergence_count:o,...t?{}:{cycles:e.cycles.slice(0,n).map(s=>s.item_ids)}}}function jr(e){let t=e.assembly.graph,n=e.limit,r=B(t,{registry:t.registry()}),i=Ye(t);return{subcommand:"analyze",node_count:t.nodes().length,edge_count:t.edges().length,edge_basis:"deduplicated_directed",sample_limit:n,execution:Ar(r,e.summary,n),knowledge:Rr(i,e.summary,n),hierarchy:Or(G(e.assembly),e.summary,n)}}function Mr(e,t){let n=ee(e.assembly,{isTerminal:t,maxSampleSize:e.sample,...e.exemptIsolates.length===0?{}:{exemptIsolates:e.exemptIsolates},...e.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:e.exemptIsolateTypes}}),r={},i={},o={},s={};for(let d of n.findings)r[d.severity]=(r[d.severity]??0)+1,i[d.code]=(i[d.code]??0)+1,o[d.severity]=(o[d.severity]??0)+d.count,s[d.code]=(s[d.code]??0)+d.count;let{finding_subjects_by_code:a,...c}=n.profile;return{subcommand:"audit",truncated:n.findings.length>e.limit,finding_count:n.findings.length,findings_by_severity:r,findings_by_code:i,affected_subjects_by_severity:o,affected_subjects_by_code:s,profile:e.summary?c:n.profile,legacy_alias_counts:e.assembly.legacyAliasCounts,...e.summary?{}:{findings:n.findings.slice(0,e.limit)}}}function Pr(e){let t=e.limit,n={};e.kinds!==void 0&&(n.kinds=e.kinds);let r=it(e.assembly.graph,n),i=r.value;return{subcommand:"communities",community_count:i.communities.length,largest_community_size:i.communities[0]?.size??0,iterations:i.iterations,converged:i.converged,truncated:!i.converged||i.communities.length>t,cost:{visited_nodes:r.meta.visitedNodes,inspected_edges:r.meta.inspectedEdges},...e.summary?{}:{communities:i.communities.slice(0,t).map(o=>({representative:o.representative,size:o.size,members:o.members.slice(0,t)}))}}}function Lr(e){let t;try{t=T(e.assembly.graph,{...e.kinds===void 0?{}:{kinds:e.kinds},...e.maxDepth===void 0?{}:{maxDepth:e.maxDepth},limit:e.limit})}catch(n){ye(n)}return{subcommand:"redundancy",redundant_count:t.value.length,...be(t.meta),...e.summary?{}:{redundant:t.value.map(n=>({source:n.edge.source,target:n.edge.target,kind:n.edge.kind,witness:n.witness}))}}}function Fr(e,t){let n=t.limit,r=ot(t.assembly.graph,e,{direction:t.direction,...t.kinds===void 0?{}:{kinds:t.kinds},...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth}}),i=r.value.rows.filter(o=>o.dominatedCount>0);return{subcommand:"dominators",root:e,direction:t.direction,reachable_count:r.value.reachableCount,bottleneck_count:i.length,truncated:r.meta.truncated||i.length>n,cost:{visited_nodes:r.meta.visitedNodes,inspected_edges:r.meta.inspectedEdges},...t.summary?{}:{bottlenecks:i.slice(0,n).map(o=>({id:o.id,idom:o.idom,dominated_count:o.dominatedCount}))}}}function Gr(e){let t=e.limit,n=lt(e.assembly.graph),r=n.rows.filter(i=>i.critical).length;return{subcommand:"slack",acyclic:n.acyclic,makespan:n.makespan,scheduled_count:n.scheduledCount,critical_count:r,critical_path_length:n.criticalPathLength,cycle_count:n.cycles.length,truncated:n.rows.length>t,...e.summary?{}:{critical_path:n.criticalPath.slice(0,t),rows:n.rows.slice(0,t).map(i=>({id:i.id,earliest_start:i.earliestStart,latest_start:i.latestStart,slack:i.slack,critical:i.critical}))}}}function $r(e){let t=e.limit,n=dt(e.assembly.graph,e.kinds===void 0?{}:{kinds:e.kinds}),r=n.value;return{subcommand:"centrality",node_count:r.nodeCount,edge_count:r.edgeCount,edge_basis:"simple_undirected",truncated:r.rows.length>t,cost:{visited_nodes:n.meta.visitedNodes,inspected_edges:n.meta.inspectedEdges},...e.summary?{}:{rows:r.rows.slice(0,t).map(i=>({id:i.id,degree:i.degree,in_degree:i.inDegree,out_degree:i.outDegree,betweenness:i.betweenness,closeness:i.closeness}))}}}function qr(e){let t=e.limit,n=X(e.assembly.graph,e.kinds===void 0?{}:{kinds:e.kinds}),{articulationPoints:r,bridges:i}=n.value;return{subcommand:"articulation",articulation_count:r.length,bridge_count:i.length,truncated:r.length>t||i.length>t,cost:{visited_nodes:n.meta.visitedNodes,inspected_edges:n.meta.inspectedEdges},...e.summary?{}:{articulation_points:r.slice(0,t),bridges:i.slice(0,t)}}}function Ur(e,t){let n=e.limit,r=jt(e.assembly,{isTerminal:t,redundancyLimit:n,maxSampleSize:e.sample,...e.exemptIsolates.length===0?{}:{exemptIsolates:e.exemptIsolates},...e.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:e.exemptIsolateTypes}}),i={},o={};for(let s of r.steps)i[s.op]=(i[s.op]??0)+1,o[s.code]=(o[s.code]??0)+1;return{subcommand:"plan",step_count:r.steps.length,steps_by_op:i,steps_by_code:o,finding_count:r.report.findings.length,truncated:r.truncated||r.steps.length>n,cost:{visited_nodes:r.cost.visitedNodes,inspected_edges:r.cost.inspectedEdges},...e.summary?{}:{steps:r.steps.slice(0,n)}}}function Gt(e,t,n,r){return JSON.stringify({projection_version:2,subcommand:e,root:t??null,target:n??null,kinds:r.kinds??null,maxDepth:r.maxDepth??null,limit:r.limit,after:r.after??null,direction:r.direction,maxPaths:r.maxPaths??null,sample:r.sample,exemptIsolates:[...new Set(r.exemptIsolates.map(i=>i.toLowerCase()))].sort(),exemptIsolateTypes:[...new Set(r.exemptIsolateTypes.map(i=>i.toLowerCase()))].sort(),summary:r.summary,unbounded:r.unbounded})}function $t(e,t,n,r,i){return e==="analyze"?jr(r):e==="audit"?Mr(r,i):e==="plan"?Ur(r,i):e==="communities"?Pr(r):e==="redundancy"?Lr(r):e==="dominators"?Fr(t,r):e==="slack"?Gr(r):e==="centrality"?$r(r):e==="articulation"?qr(r):e==="paths"?Tr(t,n,r):e==="impact"?Nr(t,r):Dr(e,t,r)}function Br(e,t){if(e!=="index"&&(t.rebuild===!0||t.clear===!0))throw new k("--rebuild and --clear apply only to graph index.",w.USAGE);if(e!=="audit"&&t.saveBaseline===!0)throw new k("--save-baseline applies only to graph audit.",w.USAGE);if(e==="slack"&&t.kind!==void 0)throw new k("graph slack analyzes every ordering kind; --kind is not supported.",w.USAGE);if(t.rebuild===!0&&t.clear===!0)throw new k("graph index accepts either --rebuild or --clear, not both.",w.USAGE);if(t.full===!0&&t.limit!==void 0)throw new k(`graph ${e} accepts either --full or --limit, not both.`,w.USAGE)}async function zr(e,t,n,r,i,o){let s="status";if(o.clear===!0&&(await me(e),s="cleared"),o.rebuild===!0){await me(e);let c=await pe(e,t),d={assembly:n.assembly,direction:"both",exemptIsolates:[],exemptIsolateTypes:[],saveBaseline:!1,summary:!0,limit:I.rows,sample:I.samples,unbounded:!1};for(let l of["analyze","audit"])await he(e,t,c,Gt(l,void 0,void 0,d),$t(l,void 0,void 0,d,i));s="rebuilt"}let a=await Tt(e,t);return{subcommand:"index",action:s,state:a.exists?a.fresh?"fresh":"stale":"absent",entry_count:a.entry_count,item_count:r,min_items_threshold:ge,persist_enabled:_e(r,a.exists),current_fingerprint:t.slice(0,12),...a.saved_at===void 0?{}:{saved_at:a.saved_at},...a.bytes===void 0?{}:{bytes:a.bytes}}}async function Hr(e,t,n,r){let i={saved_at:new Date().toISOString(),fingerprint:t,affected_subjects_by_code:n.affected_subjects_by_code,profile:{...n.profile,finding_subjects_by_code:Object.fromEntries(A.map(s=>[s,n.affected_subjects_by_code[s]??0]))}},o=await At(e);return r&&await Rt(e,i),o===void 0?n:{...n,baseline:xt(o,i)}}async function Kr(e,t,n,r,i){try{await he(e,t,n,r,i)}catch{}}function Vr(e,t,n,r){if(e.subcommand!=="slack")return;let i=new Set(t.assembly.details.filter(u=>r(u.status)).map(u=>u.id)),o=t.assembly.graph,s=new ke(o.nodes().filter(u=>!i.has(u)),o.edges().filter(u=>!i.has(u.source)&&!i.has(u.target)),o.registry()),a=ut(s,n.filter(u=>!i.has(u.id)),{now:Ae(),limit:t.limit}),{rows:c,residuals:d,overcommitted:l,...g}=a;e.deadline_schedule={population:"active",...g,...t.summary?{}:{rows:c,residuals:d,overcommitted:l}}}async function ro(e,t,n,r,i){let o=Cr(e,t,n);De(r.summary===!0,r.full===!0,"--summary");let s=Ee(process.cwd(),i.path);await Pe(s);let a=await Me(s),c=xe(a,Ce()),d=await Le(s,a.item_format,c.type_to_folder,void 0,a.schema),l=Se(a.schema),g=qt=>je(qt,l);Br(o,r);let u=Fe(),f=ze(r.kind,u),p=qe().lookup(s,$e(d,g,u),()=>Ge(d,g,u)),m=Sr(o,p.assembly,f,r);if(o==="index")return Mt(await zr(s,p.fingerprint,m,d.length,g,r),!1);let b=Ft.has(o)?Lt(m.assembly,t):void 0,v=o==="paths"?Lt(m.assembly,n):void 0,h=Gt(o,b,v,m),_=await pe(s,p.fingerprint),E=_.results[h],S=p.memoize(h,()=>E!==void 0?structuredClone(E):$t(o,b,v,m,g)),ve=_e(d.length,_.exists);!S.reused&&E===void 0&&ve&&await Kr(s,p.fingerprint,_,h,S.value);let ne=S.value.subcommand==="audit"?await Hr(s,p.fingerprint,S.value,m.saveBaseline):S.value;return ne.cache={fingerprint:p.fingerprint.slice(0,12),assembly:p.assemblyReused?"hit":"miss",result:S.reused?"hit":"miss",durable:E!==void 0?"hit":ve?"miss":"off"},Vr(ne,m,d,g),Mt(ne,m.summary,"result_rows")}export{B as a,U as b,Ye as c,Xr as d,Qe as e,Ze as f,et as g,tt as h,nt as i,V as j,it as k,T as l,ot as m,dt as n,X as o,lt as p,ut as q,tr as r,It as s,Z as t,ue as u,ee as v,xt as w,St as x,ge as y,F as z,Dt as A,pe as B,he as C,me as D,Tt as E,_e as F,At as G,Rt as H,jt as I,Cr as J,ro as K};
2
- //# sourceMappingURL=chunk-SXVJRLLP.js.map
1
+ import{E as $e,G as qe,K as $,L as Ue,M as Be,N as ze,m as Fe,x as G,y as Ge}from"./chunk-CGL36F6I.js";import{G as Le,a as Oe}from"./chunk-FO4U3FIP.js";import{_a as Me,db as Pe,t as je}from"./chunk-P7DPS5M4.js";import{j as Se}from"./chunk-DWQMYLFM.js";import{a as I}from"./chunk-AK2CI2GI.js";import{Kd as Re,R as we,W as ke,ic as Ce,lb as ie,nd as Te,od as oe,qa as xe,rd as Ne,wa as Ee,wd as Ae,xc as De}from"./chunk-OMXMYTEX.js";import{E as j,H as re,J as Ie,y as w,z as k}from"./chunk-BUZ2Z4P3.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="403706c5-987d-5db1-95d2-b0eaded98e92")}catch{}})();function Ut(e,t,n,r,i,o){if(e.seen.has(t))return"skip";if(e.cursorFound&&e.affected.length>=o)return"truncate";e.seen.add(t),e.parents.set(t,n.id);let s=n.depth+1;return e.queue.push({id:t,depth:s}),e.cursorFound?(e.affected.push({id:t,distance:s,path:Yt(r,t,e.parents)}),"continue"):(e.cursorFound=t===i,"skip")}function Ke(e,t,n,r){let i=Te("graph impact",{root:e,direction:n,kinds:[...t.kinds??[]].sort(),max_depth:Number.isFinite(r)?r:"unbounded"});return{fingerprint:i,after:t.after===void 0?void 0:Ne(t.after,i)}}function C(e,t,n){e.get(t).add(n)}function M(e){return new Map(e.map(t=>[t,new Set]))}function Ve(e){for(let t of e)t.sort();return e.sort((t,n)=>n.length-t.length||t[0].localeCompare(n[0]))}function q(e){if(Array.isArray(e))return e.map(n=>q(n));if(e===null||typeof e!="object")return e;let t=e.toJSON;return typeof t=="function"?q(t.call(e)):Object.fromEntries(Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,q(r)]))}function He(e){return JSON.stringify(q(e))}function Bt(e,t,n,r){let i=[{id:e,expanded:!1}];for(;i.length>0;){let o=i.pop();if(o.expanded){r.push(o.id);continue}if(n.has(o.id))continue;n.add(o.id),i.push({id:o.id,expanded:!0});let s=[...t.get(o.id)].sort().reverse();for(let a of s)n.has(a)||i.push({id:a,expanded:!1})}}function zt(e,t){let n=new Set,r=[];for(let i of e)n.has(i)||Bt(i,t,n,r);return r}function Ht(e,t){let n=new Set,r=[];for(let i of[...e].reverse()){if(n.has(i))continue;let o=[],s=[i];for(n.add(i);s.length>0;){let a=s.pop();o.push(a);for(let c of t.get(a))n.has(c)||(n.add(c),s.push(c))}r.push(o)}return Ve(r)}function We(e,t){let n=M(e);for(let[r,i]of t)for(let o of i)C(n,o,r);return Ht(zt(e,t),n)}function Kt(e,t){let n=M(e.nodes());for(let r of e.edges()){let i=t.require(r.kind);if(!i.ordering)continue;let o=(i.precedence??"source_before_target")==="source_before_target";C(n,o?r.source:r.target,o?r.target:r.source)}return n}function Vt(e,t){let n=new Map(e.map(o=>[o,0]));for(let o of t.values())for(let s of o)n.set(s,n.get(s)+1);let r=e.filter(o=>n.get(o)===0).sort(),i=[];for(;r.length>0;){i.push(r);let o=[];for(let s of r)for(let a of t.get(s)){let c=n.get(a)-1;n.set(a,c),c===0&&o.push(a)}r=o.sort()}return i}function Wt(e,t){let n=new Map(e.map(s=>[s,0])),r=new Map;for(let s of e)for(let a of t.get(s)){if(!n.has(a))continue;let c=n.get(s)+1,d=r.get(a);(c>n.get(a)||c===n.get(a)&&(d===void 0||s.localeCompare(d)<0))&&(n.set(a,c),r.set(a,s))}let i=[...e].sort((s,a)=>n.get(a)-n.get(s)||s.localeCompare(a))[0],o=i===void 0?[]:[i];for(;o[0]!==void 0&&r.has(o[0]);)o.unshift(r.get(o[0]));return{depth:Object.fromEntries(n),path:o}}function Yt(e,t,n){let r=[t],i=t;for(;i!==e;)i=n.get(i),r.push(i);return r.reverse()}function B(e,t={}){let n=t.registry??we(),r=[...e.nodes()],i=Kt(e,n),o=Vt(r,i),s=o.flat(),a=s.length===r.length,c=a?[]:We(r,i).filter(l=>l.length>1||i.get(l[0]).has(l[0])),d=Wt(s,i);return{exact:!0,acyclic:a,order:s,layers:o,frontier:o[0]??[],depth:d.depth,criticalPath:d.path,criticalPathLength:Math.max(0,d.path.length-1),cycles:c,provenance:{algorithm:"kahn-longest-path",edgeFamily:"ordering"}}}function Xt(e,t,n){let r=M(e.nodes()),i=n===void 0?void 0:new Set(n.map(s=>e.registry().require(s).kind)),o=e.edges();for(let s of o){let a=e.registry().require(s.kind);i!==void 0&&!i.has(s.kind)&&(a.inverse===void 0||!i.has(a.inverse))||C(r,t==="incoming"?s.target:s.source,t==="incoming"?s.source:s.target)}return{adjacency:r,inspectedEdges:o.length}}function Jt(e,t,n,r,i,o){let s=U(e,t,{...n,after:void 0,direction:"incoming",limit:void 0}),a=U(e,t,{...n,after:void 0,direction:"outgoing",limit:void 0}),c=new Map,d=[...s.affected,...a.affected].sort((p,m)=>p.distance-m.distance||p.id.localeCompare(m.id)||p.path.join("\0").localeCompare(m.path.join("\0")));for(let p of d)c.has(p.id)||c.set(p.id,p);let l=[...c.values()].sort((p,m)=>p.distance-m.distance||p.id.localeCompare(m.id)),g=r===void 0||r===t?-1:l.findIndex(p=>p.id===r);if(r!==void 0&&r!==t&&g<0)throw new TypeError(`Unknown impact cursor item: ${r}`);let u=l.slice(g+1,g+1+i),f=g+1+u.length<l.length;return{root:t,affected:u,exact:!0,truncated:s.truncated||a.truncated||f,...f?{nextCursor:oe(o,u.at(-1)?.id??t)}:{},cost:{visitedNodes:s.cost.visitedNodes+a.cost.visitedNodes,inspectedEdges:s.cost.inspectedEdges+a.cost.inspectedEdges}}}function Qt(e,t,n){let r=n.direction,i=n.maxDepth??Number.POSITIVE_INFINITY,o=n.limit??Number.POSITIVE_INFINITY,{fingerprint:s,after:a}=Ke(t,n,r,i),{adjacency:c,inspectedEdges:d}=Xt(e,r,n.kinds),l={queue:[{id:t,depth:0}],seen:new Set([t]),parents:new Map,affected:[],cursorFound:a===void 0||a===t},g=0,u=!1,f=!1;e:for(let p=0;p<l.queue.length;p+=1){n.signal?.throwIfAborted();let m=l.queue[p];g+=1;let b=[...c.get(m.id)].sort();if(m.depth>=i){b.some(v=>!l.seen.has(v))&&(u=!0);continue}for(let v of b)if(Ut(l,v,m,t,a,o)==="truncate"){u=!0,f=!0;break e}}if(!l.cursorFound)throw new TypeError(`Unknown impact cursor item: ${a}`);return{root:t,affected:l.affected,exact:!0,truncated:u,...f?{nextCursor:oe(s,l.affected.at(-1)?.id??t)}:{},cost:{visitedNodes:g,inspectedEdges:d}}}function U(e,t,n={}){let r=n.direction??"outgoing";if(r!=="both")return Qt(e,t,{...n,direction:r});let i=n.maxDepth??Number.POSITIVE_INFINITY,o=n.limit??Number.POSITIVE_INFINITY,{fingerprint:s,after:a}=Ke(t,n,r,i);return Jt(e,t,n,a,o,s)}function Ye(e){let t=[...e.nodes()],n=M(t),r=M(t);for(let c of e.edges())C(n,c.source,c.target),C(n,c.target,c.source),C(r,c.source,c.target);let i=[],o=new Set;for(let c of t){if(o.has(c))continue;let d=[],l=[c];for(o.add(c);l.length>0;){let g=l.pop();d.push(g);for(let u of n.get(g))o.has(u)||(o.add(u),l.push(u))}i.push(d)}let s=t.map(c=>({id:c,degree:n.get(c).size})),a=Math.max(0,...s.map(({degree:c})=>c));return{components:Ve(i),stronglyConnected:We(t,r),orphans:s.filter(({degree:c})=>c===0).map(({id:c})=>c),hubs:s.filter(({degree:c})=>c>0&&c===a),exact:!0,provenance:{algorithm:"component-degree",edgeFamily:"all"}}}function Xr(e,t){let n=new Map(e.edges.map(i=>[He(i),i])),r=new Map(t.edges.map(i=>[He(i),i]));return{fromVersion:e.version,toVersion:t.version,added:[...r].filter(([i])=>!n.has(i)).map(([,i])=>i),removed:[...n].filter(([i])=>!r.has(i)).map(([,i])=>i),unchangedCount:[...n.keys()].filter(i=>r.has(i)).length,exact:!0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f60c628a-2e42-5770-a001-39cce5f92595")}catch{}})();var Zt=I.paths,en=I.visited_paths,tn=I.path_depth;function se(e,t){if(!Number.isFinite(t)||!Number.isInteger(t)||t<0)throw new TypeError(`Invalid path ${e} bound: ${String(t)}`)}function z(e,t){return t.hierarchyDirection==="target_parent"?e.target:e.source}function P(e,t){return(t.precedence??"source_before_target")==="target_before_source"?e.target:e.source}function D(e,t){let n=P(e,t);return{predecessor:n,successor:n===e.source?e.target:e.source}}function nn(e,t,n){if(t===void 0)return;let r=e.registry(),i=new Set;for(let o of t){let s=r.require(o),a=s.traversal;if(a==="association")throw new TypeError(`Relationship kind ${s.kind} uses association traversal; use graph impact --direction both`);if(a!==n&&a!=="semantic"){let c=a==="hierarchy"?"graph ancestors or graph descendants":"graph predecessors or graph successors";throw new TypeError(`Relationship kind ${s.kind} uses ${a} traversal; use ${c}`)}i.add(s.kind)}return i}function rn(e,t,n,r,i){let o=e.registry(),s=e.neighborEdges(t,{direction:"both",...n===void 0?{}:{kinds:[...n]}}),a=[],c=new Set;for(let d of s.value){let l=o.require(d.edge.kind);n===void 0&&!l[r]||i(d,l,t)&&(c.has(d.id)||(c.add(d.id),a.push(d.id)))}return{neighbors:a,inspectedEdges:s.meta.inspectedEdges}}function on(e,t,n,r,i,o){if(t>=n)return e.neighbors.some(s=>!o.seen.has(s))&&(o.truncated=!0),!1;for(let s of e.neighbors)if(!o.seen.has(s)){if(o.seen.add(s),o.queue.push({id:s,depth:t+1}),!o.resumed){s===i&&(o.resumed=!0);continue}if(o.value.length>=r)return o.truncated=!0,!0;o.value.push(s)}return!1}function H(e,t,n,r,i){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`);let o=nn(e,n.kinds,r),s=n.limit??Number.POSITIVE_INFINITY,a=n.maxDepth??Number.POSITIVE_INFINITY,c=n.after,d={seen:new Set([t]),value:[],queue:[{id:t,depth:0}],resumed:c===void 0,truncated:!1},l=0,g=0;for(let u=0;u<d.queue.length;u+=1){n.signal?.throwIfAborted();let f=d.queue[u];l+=1;let p=rn(e,f.id,o,r,i);if(g+=p.inspectedEdges,on(p,f.depth,a,s,c,d))break}if(!d.resumed)throw new TypeError(`Traversal cursor not found in sequence: ${c}`);return{value:d.value,meta:{visitedNodes:l,inspectedEdges:g,truncated:d.truncated,nextCursor:d.value.at(-1)}}}function Xe(e,t){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`)}function Je(e,t,n,r,i){let o=e.neighborEdges(t.nodes.at(-1),{direction:r,...n.kinds===void 0?{}:{kinds:n.kinds}});return i.inspectedEdges+=o.meta.inspectedEdges,o.value.filter(s=>!t.nodeSet.has(s.id))}function sn(e,t,n,r,i,o,s){for(let a of Je(e,t,r,i,s)){let c=[...t.nodes,a.id],d=new Set(t.nodeSet).add(a.id),l=[...t.edges,a.edge];if(a.id===n){if(s.value.push({nodes:c,edges:l,length:l.length}),s.value.length>=o)return!0}else s.queue.push({nodes:c,nodeSet:d,edges:l})}return!1}function Qe(e,t,n={}){return H(e,t,n,"hierarchy",(r,i)=>z(r.edge,i)===r.id)}function Ze(e,t,n={}){return H(e,t,n,"hierarchy",(r,i,o)=>z(r.edge,i)===o)}function et(e,t,n={}){return H(e,t,n,"ordering",(r,i)=>P(r.edge,i)===r.id)}function tt(e,t,n={}){return H(e,t,n,"ordering",(r,i,o)=>P(r.edge,i)===o)}function an(e,t,n,r,i,o,s,a){let c={value:[],queue:[{nodes:[t],nodeSet:new Set([t]),edges:[]}],inspectedEdges:0},d=0,l=!1,g=i+1;for(let u=0;u<c.queue.length;u+=1){if(r.signal?.throwIfAborted(),c.value.length>=g||d>=o){l=!0;break}let f=c.queue[u];if(d+=1,f.edges.length>=s){Je(e,f,r,a,c).length>0&&(l=!0);continue}if(sn(e,f,n,r,a,g,c)){l=!0;break}}return{value:c.value.slice(0,i),meta:{visitedNodes:d,inspectedEdges:c.inspectedEdges,truncated:l}}}function nt(e,t,n,r={}){Xe(e,t),Xe(e,n);let i=r.maxPaths??Zt,o=r.maxVisitedPaths??en,s=r.maxDepth??tn;se("maxPaths",i),se("maxVisitedPaths",o),se("maxDepth",s);let a=r.direction??"outgoing";r.signal?.throwIfAborted();for(let c of r.kinds??[])e.registry().require(c);return t===n?i===0?{value:[],meta:{visitedNodes:1,inspectedEdges:0,truncated:!0}}:{value:[{nodes:[t],edges:[],length:0}],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}}:an(e,t,n,r,i,o,s,a)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="789f7451-ceb1-5e5c-b2b6-45eec49580ce")}catch{}})();var cn=16,dn=2,ln=8;function K(e,t){if(!Number.isInteger(t)||t<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`)}function V(e,t,n){let r=e.registry(),i=t===void 0?void 0:new Set(t.map(o=>r.require(o).kind));for(let o of e.edges()){if(o.source===o.target)continue;let s=r.require(o.kind);i!==void 0&&!(i.has(s.kind)||s.inverse!==void 0&&i.has(s.inverse))||n(o,s)}}function un(e,t){let n=new Map;V(e,t,r=>{rt(n,r.source,r.target),rt(n,r.target,r.source)});for(let r of n.values())r.sort();return n}function rt(e,t,n){let r=e.get(t);r===void 0?e.set(t,[n]):r.push(n)}function gn(e,t){let n=new Map;for(let o of e){let s=t.get(o);n.set(s,(n.get(s)??0)+1)}let r,i=0;for(let[o,s]of n)(s>i||s===i&&o<r)&&(r=o,i=s);return r}function fn(e,t){let n=new Map;for(let[i,o]of e){let s=n.get(o);s===void 0?n.set(o,[i]):s.push(i)}let r=[];for(let i of n.values())i.length<t||(i.sort(),r.push({representative:i[0],size:i.length,members:i}));return r.sort((i,o)=>o.size-i.size||i.representative.localeCompare(o.representative))}function it(e,t={}){let n=t.maxIterations??cn,r=t.minSize??dn;K("maxIterations",n),K("minSize",r);let i=un(e,t.kinds),o=e.nodes(),s=new Map(o.map(g=>[g,g])),a=0,c=!1,d=0,l=0;for(;a<n&&!c;){t.signal?.throwIfAborted(),a+=1,c=!0;for(let g of o){d+=1;let u=i.get(g);if(u===void 0)continue;l+=u.length;let f=gn(u,s);f!==s.get(g)&&(s.set(g,f),c=!1)}}return{value:{communities:fn(s,r),iterations:a,converged:c},meta:{visitedNodes:d,inspectedEdges:l,truncated:!c}}}function W(e){return e.direction==="directed"&&(e.ordering||e.hierarchy)}function Y(e){return e.inverse!==void 0&&e.inverse<e.kind?e.inverse:e.kind}function ae(e,t){return(t.hierarchy?z(e,t):e.source===P(e,t)?e.target:e.source)===e.target?{from:e.source,to:e.target}:{from:e.target,to:e.source}}function pn(e,t){if(t===void 0)return;let n=e.registry(),r=new Set;for(let i of t){let o=n.require(i);if(!W(o))throw new TypeError(`Relationship kind ${o.kind} is not a directed ordering or hierarchy kind`);r.add(Y(o))}return r}function hn(e,t){let n=e.registry(),r=new Map;for(let i of e.edges()){let o=n.require(i.kind);if(!W(o))continue;let s=Y(o);if(t!==void 0&&!t.has(s))continue;let a=ae(i,o);if(a.from===a.to)continue;let c=r.get(s);c===void 0&&(c={adjacency:new Map,records:[]},r.set(s,c));let d=c.adjacency.get(a.from);d===void 0?c.adjacency.set(a.from,new Set([a.to])):d.add(a.to),c.records.push({...a,edge:i})}return r}function mn(e){let t=new Map;for(let[n,r]of e.adjacency)t.set(n,[...r].sort());return t}function _n(e,t,n,r){let i=[r];for(let o=n;o!==t;o=e.get(o))i.push(o);return i.push(t),i.reverse()}function yn(e,t,n,r,i,o){for(let s of e.get(n.id)??[])if(o.inspectedEdges+=1,!(n.depth===0&&s===t.to)&&!r.has(s)){if(r.set(s,n.id),s===t.to)return _n(r,t.from,n.id,s);i.push({id:s,depth:n.depth+1})}}function bn(e,t,n,r){let i=new Map([[t.from,t.from]]),o=[{id:t.from,depth:0}];for(let s=0;s<o.length;s+=1){let a=o[s];if(r.visitedNodes+=1,a.depth>=n)continue;let c=yn(e,t,a,i,o,r);if(c!==void 0)return c}}function T(e,t={}){let n=t.maxDepth??ln;K("maxDepth",n),t.limit!==void 0&&K("limit",t.limit);let r=t.limit??Number.POSITIVE_INFINITY,i=pn(e,t.kinds),o=hn(e,i),s=[],a={visitedNodes:0,inspectedEdges:0},c=!1;e:for(let d of[...o.keys()].sort()){let l=o.get(d),g=mn(l);for(let u of l.records){t.signal?.throwIfAborted();let f=bn(g,u,n,a);if(f!==void 0){if(s.length>=r){c=!0;break e}s.push({edge:u.edge,witness:f})}}}return{value:s,meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:c}}}function vn(e,t,n,r,i){let o=new Set,s=[];for(let a of n){if(a.id===e||o.has(a.id))continue;if(!i.seen.has(a.id)){if(t>=r){i.truncated=!0;continue}i.seen.add(a.id),i.queue.push({id:a.id,depth:t+1})}o.add(a.id),s.push(a.id);let c=i.predecessors.get(a.id);c===void 0&&(c=new Set,i.predecessors.set(a.id,c)),c.add(e)}return s}function wn(e,t,n){let r=n.direction??"outgoing",i=n.maxDepth??Number.POSITIVE_INFINITY,o=[],s=new Map,a={seen:new Set([t]),queue:[{id:t,depth:0}],predecessors:new Map,truncated:!1},c=0;for(let d=0;d<a.queue.length;d+=1){n.signal?.throwIfAborted();let{id:l,depth:g}=a.queue[d];o.push(l);let u=e.neighborEdges(l,{direction:r,...n.kinds===void 0?{}:{kinds:n.kinds}});c+=u.meta.inspectedEdges,s.set(l,vn(l,g,u.value,i,a))}return{order:o,successors:s,predecessors:a.predecessors,inspectedEdges:c,truncated:a.truncated}}function kn(e,t){let n=[],r=new Set([t]),i=[{id:t,index:0}];for(;i.length>0;){let o=i.at(-1),s=e.successors.get(o.id);if(o.index<s.length){let a=s[o.index];o.index+=1,r.has(a)||(r.add(a),i.push({id:a,index:0}))}else n.push(o.id),i.pop()}return n.reverse()}function In(e,t,n,r){let i=e,o=t;for(;i!==o;){for(;r.get(i)>r.get(o);)i=n.get(i);for(;r.get(o)>r.get(i);)o=n.get(o)}return i}function xn(e,t,n){let r;for(let i of[...e].sort())t.has(i)&&(r=r===void 0?i:In(r,i,t,n));return r}function En(e,t,n,r,i){let o=new Map([[t,t]]),s=!0;for(;s;){s=!1;for(let a of n){if(i?.throwIfAborted(),a===t)continue;let c=xn(e.predecessors.get(a),o,r);c!==void 0&&o.get(a)!==c&&(o.set(a,c),s=!0)}}return o}function ot(e,t,n={}){if(!e.hasNode(t))throw new TypeError(`Relationship node not found: ${t}`);if(n.maxDepth!==void 0&&(!Number.isInteger(n.maxDepth)||n.maxDepth<0))throw new TypeError(`Invalid maxDepth bound: ${String(n.maxDepth)}`);let r=wn(e,t,n),i=kn(r,t),o=new Map(i.map((d,l)=>[d,l])),s=En(r,t,i,o,n.signal),a=new Map(i.map(d=>[d,1]));for(let d=i.length-1;d>=0;d-=1){let l=i[d];if(l===t)continue;let g=s.get(l);a.set(g,a.get(g)+a.get(l))}let c=i.filter(d=>d!==t).map(d=>({id:d,idom:s.get(d),dominatedCount:a.get(d)-1})).sort((d,l)=>l.dominatedCount-d.dominatedCount||d.id.localeCompare(l.id));return{value:{root:t,reachableCount:r.order.length,rows:c},meta:{visitedNodes:r.order.length,inspectedEdges:r.inspectedEdges,truncated:r.truncated}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3cef3a97-fda4-5811-9e69-04ff722e40a1")}catch{}})();function st(e){return Math.round(e*1e6)/1e6}function at(e,t,n){let r=e.get(t);r===void 0?e.set(t,new Set([n])):r.add(n)}function ct(e,t){let n=new Map(e.nodes().map(i=>[i,new Set]));V(e,t,i=>{n.get(i.source).add(i.target),n.get(i.target).add(i.source)});let r=new Map;for(let[i,o]of n)r.set(i,[...o].sort());return r}function Sn(e,t){let n=new Map,r=new Map;return V(e,t,(i,o)=>{if(!o.ordering)return;let{predecessor:s,successor:a}=D(i,o);at(r,s,a),at(n,a,s)}),{incoming:n,outgoing:r}}function Cn(e,t,n){let r=new Map([[e,0]]),i=new Map([[e,1]]),o=new Map,s=[],a=[e],c=0,d=0;for(let l=0;l<a.length;l+=1){let g=a[l];n.visitedNodes+=1,s.push(g);let u=r.get(g);g!==e&&(c+=1,d+=u);for(let f of t.get(g))if(n.inspectedEdges+=1,r.has(f)||(r.set(f,u+1),a.push(f)),r.get(f)===u+1){i.set(f,(i.get(f)??0)+i.get(g));let p=o.get(f);p===void 0?o.set(f,[g]):p.push(g)}}return{stack:s,sigma:i,predecessors:o,reachableCount:c,distanceSum:d}}function Dn(e,t,n){let r=new Map;for(let i=e.stack.length-1;i>=0;i-=1){let o=e.stack[i],s=(1+(r.get(o)??0))/e.sigma.get(o);for(let a of e.predecessors.get(o)??[])r.set(a,(r.get(a)??0)+e.sigma.get(a)*s);o!==t&&n.set(o,(n.get(o)??0)+(r.get(o)??0))}}function Tn(e,t){return t<=1||e.reachableCount===0?0:e.reachableCount/(t-1)*(e.reachableCount/e.distanceSum)}function Nn(e,t,n,r,i){return{id:e,degree:t.get(e).length,inDegree:n.incoming.get(e)?.size??0,outDegree:n.outgoing.get(e)?.size??0,betweenness:st((r.get(e)??0)/2),closeness:st(i.get(e))}}function dt(e,t={}){let n=ct(e,t.kinds),r=Sn(e,t.kinds),i=e.nodes(),o=new Map,s=new Map,a={visitedNodes:0,inspectedEdges:0};for(let l of i){t.signal?.throwIfAborted();let g=Cn(l,n,a);s.set(l,Tn(g,i.length)),Dn(g,l,o)}let c=0;for(let l of n.values())c+=l.length;let d=i.map(l=>Nn(l,n,r,o,s)).sort((l,g)=>g.betweenness-l.betweenness||g.degree-l.degree||l.id.localeCompare(g.id));return{value:{nodeCount:i.length,edgeCount:c/2,rows:d},meta:{visitedNodes:a.visitedNodes,inspectedEdges:a.inspectedEdges,truncated:!1}}}function An(e,t){return e<=t?{source:e,target:t}:{source:t,target:e}}function Rn(e,t,n){let r=t.get(e.node)[e.neighborIndex];if(e.neighborIndex+=1,n.inspectedEdges+=1,r!==e.parent){if(n.discovery.has(r)){n.low.set(e.node,Math.min(n.low.get(e.node),n.discovery.get(r)));return}return e.children+=1,n.discovery.set(r,n.timer),n.low.set(r,n.timer),n.timer+=1,{node:r,parent:e.node,neighborIndex:0,children:0}}}function On(e,t,n){if(e.parent===null){e.children>1&&n.articulation.add(e.node);return}let r=e.parent,i=n.low.get(e.node);n.low.set(r,Math.min(n.low.get(r),i)),r!==t&&i>=n.discovery.get(r)&&n.articulation.add(r),i>n.discovery.get(r)&&n.bridges.push(An(r,e.node))}function jn(e,t,n,r){n.discovery.set(e,n.timer),n.low.set(e,n.timer),n.timer+=1;let i=[{node:e,parent:null,neighborIndex:0,children:0}];for(;i.length>0;){r?.throwIfAborted();let o=i.at(-1);if(o.neighborIndex<t.get(o.node).length){let s=Rn(o,t,n);s!==void 0&&i.push(s)}else On(o,e,n),i.pop()}}function X(e,t={}){let n=ct(e,t.kinds),r={discovery:new Map,low:new Map,timer:0,articulation:new Set,bridges:[],inspectedEdges:0};for(let i of e.nodes())r.discovery.has(i)||jn(i,n,r,t.signal);return{value:{articulationPoints:[...r.articulation].sort(),bridges:r.bridges.sort((i,o)=>i.source.localeCompare(o.source)||i.target.localeCompare(o.target))},meta:{visitedNodes:r.discovery.size,inspectedEdges:r.inspectedEdges,truncated:!1}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="32f3ce0d-64ac-5ad4-b27a-2a279718de22")}catch{}})();function Mn(e){let t=e.registry(),n=new Map,r=new Set;for(let i of e.edges()){let o=t.require(i.kind);if(!o.ordering)continue;let{predecessor:s,successor:a}=D(i,o);if(r.add(s),r.add(a),s===a)continue;let c=n.get(s);c===void 0?n.set(s,new Set([a])):c.add(a)}return{forward:n,participants:r}}function Pn(e,t,n,r){if(e===void 0)return r;let i=r;for(let o of e)t.has(o)&&(i=Math.min(i,n.get(o)));return i}function Ln(e,t,n){let r=n-t;return{id:e,earliestStart:t,earliestFinish:t+1,latestStart:n,latestFinish:n+1,slack:r,critical:r===0}}function Fn(e,t,n,r,i){let o=new Map;for(let s=e.length-1;s>=0;s-=1){let a=e[s],c=Pn(t.forward.get(a),r,o,i);o.set(a,c-1)}return e.map(s=>Ln(s,n[s],o.get(s))).sort((s,a)=>s.slack-a.slack||s.earliestStart-a.earliestStart||s.id.localeCompare(a.id))}function lt(e,t={}){t.signal?.throwIfAborted();let n=B(e,{registry:e.registry()}),r=Mn(e),i=new Set(n.order),o=n.order.filter(d=>r.participants.has(d)),s=o.reduce((d,l)=>Math.max(d,n.depth[l]+1),0),a=Fn(o,r,n.depth,i,s),c=a.length>0;return{exact:!0,acyclic:n.acyclic,makespan:s,scheduledCount:a.length,criticalPath:c?n.criticalPath:[],criticalPathLength:c?n.criticalPathLength:0,cycles:n.cycles,rows:a,provenance:{algorithm:"critical-path-method",edgeFamily:"ordering",weighting:"unit"}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fa17672a-97a2-5f94-bdfe-9df970cc038b")}catch{}})();function Gn(e,t,n){for(let r=e.length-1;r>=0;r-=1){n?.throwIfAborted();let i=t.get(e[r]);for(let o of i.successors){n?.throwIfAborted();let s=t.get(o);if(s.latest===void 0||s.duration===void 0)continue;let a=s.latest-s.duration;(i.latest===void 0||a<i.latest)&&(i.latest=a,i.anchor=s.anchor)}}}function $n(e,t,n,r){let i=[],o=e;for(;o!==void 0&&i.length<n;)r?.throwIfAborted(),i.push(o),o=t.get(o).predecessor;return i.reverse(),{path:i,path_truncated:o!==void 0}}function qn(e,t,n,r,i){let o=new Map(t.map(a=>[a.id,a])),s=new Map;for(let a of e){i?.throwIfAborted();let c=o.get(a),d=c?.estimated_minutes,l=typeof d=="number"&&Number.isFinite(d)&&d>=0?d:void 0,g={item:c,duration:l,pending:0,successors:new Set,earliest:0};if(c?.deadline!==void 0){let u=Date.parse(c.deadline);Number.isFinite(u)?(g.deadline=(u-n)/6e4,g.latest=g.deadline,g.anchor=a):r(a,"invalid_deadline")}s.set(a,g)}return s}function Un(e,t,n){for(let r of e.edges()){n?.throwIfAborted();let i=e.registry().require(r.kind);if(!i.ordering)continue;let{predecessor:o,successor:s}=D(r,i),a=t.get(o);a.successors.has(s)||(a.successors.add(s),t.get(s).pending+=1)}}function Bn(e,t,n){let r=e.filter(i=>t.get(i).pending===0);for(let i=0;i<r.length;i+=1){n?.throwIfAborted();let o=r[i],s=t.get(o),a=s.earliest===null||s.duration===void 0?null:s.earliest+s.duration;for(let c of s.successors){n?.throwIfAborted();let d=t.get(c);a===null?d.earliest=null:d.earliest!==null&&(a>d.earliest||a===d.earliest&&(d.predecessor===void 0||o<d.predecessor))&&(d.earliest=a,d.predecessor=o),d.pending-=1,d.pending===0&&r.push(c)}}return r}function zn(e,t,n,r,i,o,s,a){let c=t.duration;if(t.latest!==void 0){r.scheduled_count+=1;let d=t.latest-c;r.rows.length<o?r.rows.push({id:e,deadline_id:t.anchor,latest_start:new Date(i+d*6e4).toISOString(),slack_minutes:t.earliest===null?null:d-t.earliest}):r.truncated=!0}if(t.deadline!==void 0&&t.earliest!==null&&t.earliest+c>t.deadline)if(r.overcommitted_count+=1,r.overcommitted.length<o){let d=$n(e,n,Math.min(o,s.remaining),a);s.remaining-=d.path.length,d.path_truncated&&(r.truncated=!0),r.overcommitted.push({deadline_id:e,deadline:t.item.deadline,shortfall_minutes:t.earliest+c-t.deadline,...d})}else r.truncated=!0}function Hn(e,t,n,r,i,o,s,a){let c={remaining:o};for(let d of e){a?.throwIfAborted();let l=t.get(d);if(l.pending>0){s(d,"cycle_or_gated_by_cycle");continue}if(l.duration===void 0){s(d,"unknown_estimate");continue}if(l.latest!==void 0&&!Number.isFinite(new Date(r+(l.latest-l.duration)*6e4).getTime())){s(d,"date_range_exceeded");continue}l.earliest===null&&s(d,"unknown_predecessor_estimate"),zn(d,l,t,n,r,i,c,a)}}function ut(e,t,n={}){n.signal?.throwIfAborted();let r=Date.parse(n.now??new Date().toISOString());if(!Number.isFinite(r))throw new TypeError("Invalid scheduling clock");let i=n.maxWork??1e5,o=n.limit??10;for(let[u,f]of[["maxWork",i],["limit",o]])if(!Number.isSafeInteger(f)||f<1)throw new TypeError(`Invalid scheduling ${u}`);let s={as_of:new Date(r).toISOString(),basis:"derived_elapsed_minutes",complete:!0,truncated:!1,work_limit_exceeded:!1,scheduled_count:0,residual_count:0,overcommitted_count:0,rows:[],residuals:[],overcommitted:[]},a=e.nodes(),c=e.edges();if(a.length+c.length+t.length>i)return{...s,complete:!1,work_limit_exceeded:!0};let d=(u,f)=>{s.complete=!1,s.residual_count+=1,s.residuals.length<o?s.residuals.push({id:u,reason:f}):s.truncated=!0},l=qn(a,t,r,d,n.signal);Un(e,l,n.signal);let g=Bn(a,l,n.signal);return Gn(g,l,n.signal),Hn(a,l,s,r,o,i,d,n.signal),s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ccb7d865-8baa-5379-a810-7be494eadcb1")}catch{}})();function N(){return{nodes:0,isolated:0,degree_leq_one:0,semantic_nodes:0,without_semantic_edges:0,degree_histogram:{}}}function pt(e,t,n,r){let i={all:N(),active:N(),terminal:N()},o=new Map;for(let s of e.details){if(r?.throwIfAborted(),e.missingIdSet.has(s.id.toLowerCase())||s.status==="external")continue;let a=o.get(s.status)??N();o.set(s.status,a);let c=e.graph.incidentEdges(s.id),d=c.some(l=>n(l.kind));for(let l of[i.all,i[t(s.status)?"terminal":"active"],a]){l.nodes+=1,l.isolated+=+(c.length===0),c.length<=1&&(l.degree_leq_one+=1),d?l.semantic_nodes+=1:l.without_semantic_edges+=1;let g=String(c.length);l.degree_histogram[g]=(l.degree_histogram[g]??0)+1}}return{coverage_by_lifecycle:i,coverage_by_status:Object.fromEntries([...o].sort(([s],[a])=>s.localeCompare(a)))}}function gt(e){if(!J(e))return!1;let t=e;if(!["nodes","isolated","degree_leq_one","semantic_nodes","without_semantic_edges"].every(r=>Number.isSafeInteger(t[r])&&Number(t[r])>=0)||!J(t.degree_histogram))return!1;let n=Object.entries(t.degree_histogram);return n.every(([r,i])=>/^(0|[1-9]\d*)$/.test(r)&&Number.isSafeInteger(i)&&Number(i)>=0)&&n.reduce((r,[,i])=>r+Number(i),0)===t.nodes&&Number(t.isolated)<=Number(t.degree_leq_one)&&Number(t.degree_leq_one)<=Number(t.nodes)&&Number(t.semantic_nodes)+Number(t.without_semantic_edges)===t.nodes}function J(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ht(e){for(let r of["ordering_acyclic","active_ordering_acyclic"])if(e[r]!==void 0&&typeof e[r]!="boolean")return!1;let t=e.coverage_by_lifecycle,n=e.coverage_by_status;return t===void 0&&n===void 0?!0:!J(t)||!J(n)?!1:["all","active","terminal"].every(r=>gt(t[r]))&&Object.values(n).every(gt)}function ft(e,t){return Object.fromEntries([...new Set([...Object.keys(e),...Object.keys(t)])].sort().map(n=>{let r=Object.hasOwn(e,n)?e[n]:N(),i=Object.hasOwn(t,n)?t[n]:N(),o=Object.fromEntries([...new Set([...Object.keys(r.degree_histogram),...Object.keys(i.degree_histogram)])].sort().map(s=>[s,(i.degree_histogram[s]??0)-(r.degree_histogram[s]??0)]));return[n,{nodes:i.nodes-r.nodes,isolated:i.isolated-r.isolated,degree_leq_one:i.degree_leq_one-r.degree_leq_one,semantic_nodes:i.semantic_nodes-r.semantic_nodes,without_semantic_edges:i.without_semantic_edges-r.without_semantic_edges,degree_histogram:o}]}))}function mt(e,t){return!e.coverage_by_lifecycle||!t.coverage_by_lifecycle||!e.coverage_by_status||!t.coverage_by_status?{lifecycle_comparable:!1}:{lifecycle_comparable:!0,coverage_by_lifecycle:ft(e.coverage_by_lifecycle,t.coverage_by_lifecycle),coverage_by_status:ft(e.coverage_by_status,t.coverage_by_status)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="896e1553-b127-532f-ac39-e0d47f29eebc")}catch{}})();var A=["missing_reference_active","missing_reference_terminal","legacy_no_blocker_sentinel","ordering_cycle","legacy_ordering_cycle","ordering_storage_contradiction","legacy_ordering_storage_contradiction","hierarchy_cycle","legacy_hierarchy_cycle","hierarchy_cardinality_violation","legacy_hierarchy_cardinality_violation","hierarchy_direction_violation","legacy_hierarchy_direction_violation","duplicate_edge","legacy_duplicate_edge","duplicate_dependency_row","legacy_duplicate_dependency_row","stale_lifecycle_block","isolated_active_node","sparse_active_node"];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34b2e83e-f6a1-57e7-84ee-4ad83acb2e19")}catch{}})();var Kn=25,Vn="milestone",Wn="outcome milestone:",Yn=new Set(["discovered_from","incident_from","recurs_from","supersedes","verifies"]);function Q(e){return Yn.has(e)}var _t={error:0,warning:1,info:2};function yt(e){return new Set((e??[]).filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()))}function R(e,t,n,r,i,o,s,a){let c=[...i].sort((d,l)=>d.localeCompare(l));return{code:e,severity:t,policy:n,message:r(c.length),count:c.length,sample:c.slice(0,o),sample_truncated:c.length>o,remediation:s,...a===void 0?{}:{evidence:[...a].sort((d,l)=>d.localeCompare(l)).slice(0,o)}}}function Xn(e,t){return e.cycles.map(n=>R(n.legacy_terminal?"legacy_hierarchy_cycle":"hierarchy_cycle",n.legacy_terminal?"info":"error","Structural hierarchy must be acyclic across scalar and registered dependency relationships.",r=>`${r} items participate in one hierarchy cycle.`,n.item_ids,t,n.legacy_terminal?"Preserve historical rows unless an explicit legacy repair is approved.":"Remove or retype one exact hierarchy relation before continuing mutation."))}function bt(e,t,n){let r=e.cardinality_violations.filter(i=>i.legacy_terminal===n);return r.length===0?[]:[R(n?"legacy_hierarchy_cardinality_violation":"hierarchy_cardinality_violation",n?"info":"error","Every structural child must resolve to at most one logical parent across all hierarchy spellings.",i=>`${i} child item${i===1?"":"s"} resolve to multiple hierarchy parents.`,r.map(i=>i.child_id),t,n?"Preserve historical rows unless an explicit legacy repair is approved.":"Remove the exact surplus hierarchy rows so each child has one parent.",r.map(i=>`${i.child_id} <- ${i.parent_ids.join(", ")}`))]}function vt(e,t,n){let r=e.divergences.filter(i=>i.legacy_terminal===n);return r.length===0?[]:[R(n?"legacy_hierarchy_direction_violation":"hierarchy_direction_violation",n?"info":"error","Scalar parent metadata and dependency-backed hierarchy rows must resolve to the same logical parent.",i=>`${i} child item${i===1?"":"s"} have divergent hierarchy storage surfaces.`,r.map(i=>i.child_id),t,n?"Preserve historical rows unless an explicit legacy repair is approved.":"Align the scalar parent and exact dependency rows to one canonical parent.",r.map(i=>`${i.child_id}: scalar=${i.scalar_parent_id} dependencies=${i.dependency_parent_ids.join(",")}`))]}function Jn(e,t){let n=G(e);return n?[...Xn(n,t),...bt(n,t,!1),...bt(n,t,!0),...vt(n,t,!1),...vt(n,t,!0)]:[]}function Qn(e){let t=e.graph.registry(),n=new Map;for(let r of e.graph.edges()){let i=t.require(r.kind);if(!i.ordering)continue;let[o,s]=(i.precedence??"source_before_target")==="target_before_source"?[r.target,r.source]:[r.source,r.target],a=n.get(o);a?a.push(s):n.set(o,[s])}for(let r of n.values())r.sort((i,o)=>i.localeCompare(o));return n}function kt(e,t){t.indexes.set(e,t.nextIndex),t.lowLinks.set(e,t.nextIndex),t.nextIndex+=1,t.stack.push(e),t.onStack.add(e)}function Zn(e,t,n,r){let i=n.get(e.node)??[];if(e.neighborIndex>=i.length)return!1;let o=i[e.neighborIndex];return e.neighborIndex+=1,r.indexes.has(o)?r.onStack.has(o)&&r.lowLinks.set(e.node,Math.min(r.lowLinks.get(e.node),r.indexes.get(o))):(kt(o,r),t.push({node:o,neighborIndex:0})),!0}function er(e,t,n,r){t.pop();let i=t.at(-1);if(i&&r.lowLinks.set(i.node,Math.min(r.lowLinks.get(i.node),r.lowLinks.get(e.node))),r.lowLinks.get(e.node)!==r.indexes.get(e.node))return;let o=[];for(;;){let s=r.stack.pop();if(r.onStack.delete(s),o.push(s),s===e.node)break}(o.length>1||o.length===1&&n.get(o[0])?.includes(o[0]))&&r.components.push(o.sort((s,a)=>s.localeCompare(a)))}function tr(e){let t={indexes:new Map,lowLinks:new Map,onStack:new Set,stack:[],components:[],nextIndex:0},n=[...e.keys()].sort((r,i)=>r.localeCompare(i));for(let r of n){if(t.indexes.has(r))continue;let i=[{node:r,neighborIndex:0}];for(kt(r,t);i.length>0;){let o=i.at(-1);Zn(o,i,e,t)||er(o,i,e,t)}}return t.components.sort((r,i)=>r[0].localeCompare(i[0]))}function ce(e){return`${e.holder_id} -> ${e.target_id} (${e.kind})`}function y(e,t,n,r,i,o,s,a){t.length!==0&&e.push(R(r,i,o,s,t,n,a))}function nr(e,t,n){let r=[],i=[...e.dangling.active,...e.dangling.legacy_terminal].filter(o=>!o.no_active_blocker_sentinel);return y(r,i.filter(o=>!t(o.holder_status)).map(ce),n,"missing_reference_active","error","Active items must not reference absent targets; missing prerequisites distort scheduling.",o=>`${o} active dangling reference(s) to absent items`,"Restore or re-create the referenced item, or remove/retype the reference on the holder."),y(r,i.filter(o=>t(o.holder_status)).map(ce),n,"missing_reference_terminal","info","Terminal items may retain historical references, but absent targets remain unexplainable context.",o=>`${o} terminal dangling reference(s) to absent items`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),y(r,e.dangling.no_active_blocker_sentinels.map(ce),n,"legacy_no_blocker_sentinel","info","The pre-structured-dependency no-active-blocker sentinel is retired; real edges carry blocker state.",o=>`${o} legacy no-active-blocker sentinel reference(s)`,"Delete the sentinel reference; blocker state is derived from blocked_by edges."),r}function le(e,t){let n=t.get(e);return n?!n.terminal:!0}function It(e){return`${e.holder_id} -> ${e.target_id} (blocked_by scalar + ${e.dependency_kind} dependency)`}function rr(e,t){let n=[],r=[];for(let o of e.orderingContradictions??[])(o.legacy_terminal?r:n).push(It(o));let i=[];return y(i,n,t,"ordering_storage_contradiction","error","A scalar blocker and same-target structured ordering row must not assert opposite precedence.",o=>`${o} active scalar-versus-structured ordering contradiction(s)`,"Remove the structured dependency row that points the holder before its scalar blocker, or replace both representations with one unambiguous ordering edge."),y(i,r,t,"legacy_ordering_storage_contradiction","info","Terminal scalar-versus-structured ordering contradictions are exact historical storage defects with no live scheduling effect.",o=>`${o} terminal scalar-versus-structured ordering contradiction(s)`,"Remove the contradictory blocks dependency row in a dedicated changelog-safe closed-item batch; preserve the scalar blocker as the historical precedence record."),i}function ir(e,t,n,r){let i=[],o=Qn(e);for(let c of tr(o)){let d=c.some(u=>le(u,t)),l=new Set(c.map(u=>u.toLowerCase())),g=(e.orderingContradictions??[]).filter(u=>l.has(u.holder_id.toLowerCase())&&l.has(u.target_id.toLowerCase())).map(It);i.push(d?R("ordering_cycle","error","Order-bearing relationship kinds must stay acyclic; a cycle makes every member unschedulable.",u=>`execution-order cycle across ${u} item(s)`,c,r,"Remove or retype one ordering edge inside the cycle, or split the work so precedence is linear.",g.length===0?void 0:g):R("legacy_ordering_cycle","info","Ordering cycles between exclusively terminal items are historical contradictions with no scheduling effect.",u=>`terminal-only execution-order cycle across ${u} item(s)`,c,r,"Leave as history debt, or clean up in a dedicated changelog-safe closed-item batch; never repair closed items ad hoc.",g.length===0?void 0:g))}let s=new Map;for(let[c,d]of o)for(let l of d){let g=s.get(l);g?g.push(c):s.set(l,[c])}let a=[...t.values()].filter(c=>!c.missing&&!c.terminal&&n(c.status)&&!(s.get(c.id)??[]).some(d=>{let l=t.get(d);return l===void 0||!l.terminal})).map(c=>c.id);return y(i,a,r,"stale_lifecycle_block","warning","A blocked lifecycle status must be backed by at least one open ordering predecessor.",c=>`${c} status-blocked item(s) with no open blocker edge`,'Add a local blocker edge, declare an external blocker with --dep "id=<external-ref>,kind=blocked_by,source_kind=external", or move the item back to an active status.'),i}function Z(e){let t=e.edges.map(n=>n.kind).sort((n,r)=>n.localeCompare(r));return`${e.from} -> ${e.to} (${t.join(" + ")})`}function ue(e){let t=e.graph.registry(),n=new Map;for(let i of e.graph.edges()){let o=t.require(i.kind);if(!W(o))continue;let s=ae(i,o);if(s.from===s.to)continue;let a=`${Y(o)}::${s.from}::${s.to}`,c=n.get(a);c?c.edges.push(i):n.set(a,{...s,edges:[i]})}let r=[...n.values()].filter(i=>i.edges.length>=2);for(let i of r)i.edges.sort((o,s)=>o.kind.localeCompare(s.kind));return r.sort((i,o)=>i.from.localeCompare(o.from)||i.to.localeCompare(o.to))}function or(e,t,n){let r=[],i=[];for(let s of ue(e))(le(s.from,t)||le(s.to,t)?r:i).push(Z(s));let o=[];return y(o,r,n,"duplicate_edge","info","One semantic relationship should be stored once; parallel same-family spellings (reciprocal inverse pairs included) add no information and skew degree metrics.",s=>`${s} duplicated relationship(s) between active endpoints`,"Remove all but one stored spelling of the relationship; keep the canonical direction the holder declared first."),y(o,i,n,"legacy_duplicate_edge","info","Duplicated spellings between exclusively terminal items are historical noise with no scheduling effect.",s=>`${s} duplicated relationship(s) between terminal endpoints`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),o}function sr(e,t){let n=[],r=[];for(let o of e.duplicateRows??[])(o.legacy_terminal?r:n).push(`${o.holder_id} -> ${o.target_id} (${o.kind} x${o.occurrences})`);let i=[];return y(i,n,t,"duplicate_dependency_row","warning","One dependency row must be stored once per holder; identical repeated rows are a storage-layer defect invisible to the assembled graph.",o=>`${o} exactly duplicated stored dependency row(s) on active holder(s)`,"Remove the repeated rows so the dependency is stored exactly once; graph semantics are unchanged."),y(i,r,t,"legacy_duplicate_dependency_row","info","Identical repeated dependency rows on terminal holders are historical storage noise with no scheduling effect.",o=>`${o} exactly duplicated stored dependency row(s) on terminal holder(s)`,"Leave as history debt or clean up in a dedicated changelog-safe closed-item batch."),i}function ar(e,t){let n=new Map,r={source_to_target:[],target_to_source:[],both:[]};for(let s of e.graph.registry().list())s.outcomeTraversal!==void 0&&r[s.outcomeTraversal].push(s.kind);let i={source_to_target:r.source_to_target.join(","),target_to_source:r.target_to_source.join(","),both:r.both.join(",")},o=(s,a)=>{let c=n.get(a)??new Set;c.add(s),n.set(a,c)};for(let s of e.graph.edges()){t?.throwIfAborted();let a=e.graph.registry().require(s.kind);(a.outcomeTraversal==="source_to_target"||a.outcomeTraversal==="both")&&o(s.source,s.target),(a.outcomeTraversal==="target_to_source"||a.outcomeTraversal==="both")&&o(s.target,s.source)}return{basis:i,reverse:n}}function cr(e,t,n){let r=new Set(e),i=[...e].sort();for(let o=0;o<i.length;o+=1){n?.throwIfAborted();for(let s of[...t.get(i[o])??[]].sort())r.has(s)||(r.add(s),i.push(s))}return r}function dr(e,t,n,r){let i=0,o=0,s=0,a=0;for(let f of e.values())if(r?.throwIfAborted(),!t.has(f.id)&&!(f.missing||f.status==="external")){if(f.terminal){s+=1,n.has(f.id)&&(a+=1);continue}n.has(f.id)?i+=1:o+=1}let c=i+o,d=s-a,l=i+a,g=o+d,u=l+g;return{active_outcome_reachable_nodes:i,active_outcome_unreachable_nodes:o,active_outcome_reachability_basis_points:c===0?0:Math.floor(i*1e4/c),terminal_nodes:s,terminal_outcome_reachable_nodes:a,terminal_outcome_unreachable_nodes:d,terminal_outcome_reachability_basis_points:s===0?0:Math.floor(a*1e4/s),outcome_reachable_nodes:l,outcome_unreachable_nodes:g,outcome_reachability_basis_points:u===0?0:Math.floor(l*1e4/u)}}function lr(e,t,n){let r=new Set(e.details.filter(a=>a.type?.toLowerCase()===Vn&&a.title.trim().toLowerCase().startsWith(Wn)).map(a=>a.id)),{basis:i,reverse:o}=ar(e,n),s=cr(r,o,n);return{outcome_nodes:r.size,outcome_reachability_basis:i,...dr(t,r,s,n)}}function ur(e,t,n,r,i){e.active+=1;let o=t.type??"(untyped)",s=e.byType.get(o);s||(s={active:0,isolated:0,degree_leq_one:0},e.byType.set(o,s)),s.active+=1,!(n>1)&&(e.degreeLeqOne+=1,s.degree_leq_one+=1,n===0&&(e.isolated+=1,s.isolated+=1),!(r.has(t.id.toLowerCase())||i.has(o.toLowerCase()))&&(n===0?e.isolates.push(t.id):e.sparse.push(t.id)))}function gr(e,t,n,r,i,o,s){let a={active:0,missing:0,isolated:0,degreeLeqOne:0,isolates:[],sparse:[],byType:new Map};for(let h of e.graph.nodes()){s?.throwIfAborted();let _=t.get(h);if(_){if(_.missing){a.missing+=1;continue}_.terminal||ur(a,_,e.graph.incidentEdges(h).length,n,r)}}let{isolates:c,sparse:d}=a,l=[];y(l,c,i,"isolated_active_node","warning","Active work should be reachable from the graph unless explicitly declared a valid isolate.",h=>`${h} active item(s) with no relationships`,"Link the item to its parent, prerequisite, or origin \u2014 or register it as an exempt isolate."),y(l,d,i,"sparse_active_node","info","Active items with a single edge often miss an honest semantic partner; sparse is not automatically defective.",h=>`${h} active item(s) with exactly one relationship`,"Investigate for an honest second edge (story->task, defect family, cross-epic complement); do not fabricate one.");let g=e.graph.edges().length,u=T(e.graph,{signal:s}).value,f=new Set(u.map(({edge:h})=>`${h.source.toLowerCase()}\0${h.target.toLowerCase()}\0${h.kind}`));for(let h of e.orderingContradictions??[])f.add(`${h.holder_id.toLowerCase()}\0${h.target_id.toLowerCase()}\0${h.dependency_kind}`);let p=Object.fromEntries(Object.entries(o).sort(([h],[_])=>h.localeCompare(_))),m=Object.entries(p).reduce((h,[_,E])=>h+(Q(_)?E:0),0),b=X(e.graph,{signal:s}).value,v=lr(e,t,s);return{findings:l,profile:{nodes:e.graph.nodes().length,recorded_nodes:e.details.filter(h=>h.status!=="missing"&&h.status!=="external").length,edges:g,informative_edges:g-f.size,redundant_edges:u.length,ordering_contradiction_edges:e.orderingContradictions?.length??0,edge_basis:"deduplicated_directed",edges_by_kind:p,edge_share_by_kind:Object.fromEntries(Object.entries(p).map(([h,_])=>[h,_/g])),semantic_edges:m,semantic_edge_share:g===0?0:m/g,active_nodes:a.active,missing_nodes:a.missing,isolated_active_nodes:a.isolated,degree_leq_one_active_nodes:a.degreeLeqOne,coverage_by_type:Object.fromEntries([...a.byType.entries()].sort(([h],[_])=>h<_?-1:1)),articulation_points:b.articulationPoints.length,bridge_edges:b.bridges.length,...v,finding_subjects_by_code:Object.fromEntries(A.map(h=>[h,0]))}}}function ee(e,t={}){let n=t.isTerminal??(u=>u==="closed"||u==="canceled"),r=t.isBlocked??(u=>u==="blocked"),i=t.maxSampleSize??Kn;if(!Number.isInteger(i)||i<1)throw new TypeError(`Invalid audit sample bound: ${String(t.maxSampleSize)}`);let o=yt(t.exemptIsolates),s=yt(t.isolateExemptTypes),a=new Map(e.details.map(u=>[u.id,{id:u.id,status:u.status,missing:e.missingIdSet.has(u.id.toLowerCase()),terminal:n(u.status),...u.type===void 0?{}:{type:u.type}}]));t.signal?.throwIfAborted();let c={};for(let u of e.graph.edges())c[u.kind]=(c[u.kind]??0)+1;let d=nr(e,n,i);d.push(...Jn(e,i)),t.signal?.throwIfAborted(),d.push(...rr(e,i)),t.signal?.throwIfAborted(),d.push(...ir(e,a,r,i)),t.signal?.throwIfAborted(),d.push(...or(e,a,i),...sr(e,i)),t.signal?.throwIfAborted();let l=gr(e,a,o,s,i,c,t.signal);d.push(...l.findings),d.sort((u,f)=>_t[u.severity]-_t[f.severity]||u.code.localeCompare(f.code)||u.sample[0].localeCompare(f.sample[0]));let g=l.profile.finding_subjects_by_code;for(let u of d)g[u.code]+=u.count;return{findings:d,profile:{...l.profile,...pt(e,n,Q,t.signal),ordering_acyclic:!d.some(u=>u.code==="ordering_cycle"||u.code==="legacy_ordering_cycle"),active_ordering_acyclic:!d.some(u=>u.code==="ordering_cycle"),finding_subjects_by_code:g}}}function de(e,t){let n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort(),r={};for(let i of n){let o=(t[i]??0)-(e[i]??0);o!==0&&(r[i]=o)}return r}function wt(e){return e.profile.coverage_by_type??{}}function fr(e,t){let n={},r=wt(e),i=wt(t),o=[...new Set([...Object.keys(r),...Object.keys(i)])].sort();for(let s of o){let a=Object.assign({active:0,isolated:0,degree_leq_one:0},r[s]),c=Object.assign({active:0,isolated:0,degree_leq_one:0},i[s]),d={active:c.active-a.active,isolated:c.isolated-a.isolated,degree_leq_one:c.degree_leq_one-a.degree_leq_one};Object.values(d).some(l=>l!==0)&&(n[s]=d)}return n}function xt(e,t){let n=fr(e,t),{edge_share_by_kind:r={},semantic_edges:i=0,semantic_edge_share:o=0}=e.profile,{edge_share_by_kind:s={},semantic_edges:a=0,semantic_edge_share:c=0}=t.profile,d=e.profile.recorded_nodes??e.profile.nodes,l=t.profile.recorded_nodes??t.profile.nodes,g=e.profile.informative_edges??e.profile.edges,u=t.profile.informative_edges??t.profile.edges,f=e.profile.redundant_edges??0,p=t.profile.redundant_edges??0,m=e.profile.ordering_contradiction_edges??0,b=t.profile.ordering_contradiction_edges??0;return{baseline_saved_at:e.saved_at,same_snapshot:e.fingerprint===t.fingerprint,affected_subjects_by_code:de(e.affected_subjects_by_code,t.affected_subjects_by_code),profile:{nodes:t.profile.nodes-e.profile.nodes,recorded_nodes:l-d,edges:t.profile.edges-e.profile.edges,informative_edges:u-g,redundant_edges:p-f,ordering_contradiction_edges:b-m,active_nodes:t.profile.active_nodes-e.profile.active_nodes,missing_nodes:t.profile.missing_nodes-e.profile.missing_nodes,isolated_active_nodes:t.profile.isolated_active_nodes-e.profile.isolated_active_nodes,degree_leq_one_active_nodes:t.profile.degree_leq_one_active_nodes-e.profile.degree_leq_one_active_nodes,edges_by_kind:de(e.profile.edges_by_kind,t.profile.edges_by_kind),edge_share_by_kind:de(r,s),semantic_edges:a-i,semantic_edge_share:c-o,coverage_by_type:n,...mt(e.profile,t.profile)}}}import Et from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e5089f2d-3fc5-5843-95ab-ba3dd2ab9582")}catch{}})();var St=2,ge=500,pr=64,hr="graph-durable-cache";function Ct(e){return Re(e,hr,30,`graph-cache:${process.pid}`,!1,!1,3e3)}function F(e){return Et.join(e,"runtime","graph-cache.json")}function Dt(e){return Et.join(e,"runtime","graph-audit-baseline.json")}function fe(e){if(e!==null)try{let t=JSON.parse(e);return typeof t!="object"||t===null||t.version!==St||typeof t.fingerprint!="string"||typeof t.saved_at!="string"||typeof t.results!="object"||t.results===null||Array.isArray(t.results)?void 0:t}catch{return}}async function pe(e,t){let n=await j(F(e)),r=fe(n),i=r?.fingerprint===t;return{exists:n!==null,fresh:i,results:i?r.results:{}}}async function he(e,t,n,r,i){let o=await Ct(e);try{let s=fe(await j(F(e))),a=s?.fingerprint===t?s.results:{};delete a[r],a[r]=i;let c=Object.keys(a);for(let d of c.slice(0,Math.max(0,c.length-pr)))delete a[d];await re(F(e),JSON.stringify({version:St,fingerprint:t,saved_at:new Date().toISOString(),results:a})),n.results=a}finally{await o()}}async function me(e){let t=await Ct(e);try{await Ie(F(e))}finally{await t()}}async function Tt(e,t){let n=F(e),r=await j(n),i=fe(r);return i===void 0?{exists:r!==null,fresh:!1,entry_count:0}:{exists:!0,fresh:i.fingerprint===t,entry_count:Object.keys(i.results).length,fingerprint:i.fingerprint.slice(0,12),saved_at:i.saved_at,bytes:Buffer.byteLength(r,"utf8")}}function _e(e,t){return t||e>=ge}function te(e){return O(e)&&Object.values(e).every(x)}function O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function x(e){return Number.isInteger(e)&&Number(e)>=0}function Nt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function L(e,t){return e===void 0||t(e)}function mr(e){return O(e)&&Object.values(e).every(Nt)}function _r(e){return O(e)?Object.values(e).every(t=>O(t)&&[t.active,t.isolated,t.degree_leq_one].every(x)):!1}function yr(e,t,n){let r=["recorded_nodes","informative_edges","redundant_edges","ordering_contradiction_edges"],i=r.filter(s=>e[s]!==void 0).length;if(i!==0&&i!==r.length||!r.every(s=>L(e[s],x)))return;let o={recorded_nodes:e.recorded_nodes??t,informative_edges:e.informative_edges??n,redundant_edges:e.redundant_edges??0,ordering_contradiction_edges:e.ordering_contradiction_edges??0};return o.recorded_nodes<=t&&o.informative_edges<=n&&o.redundant_edges<=n&&o.ordering_contradiction_edges<=n?o:void 0}function br(e,t,n){let r=[...t,...n,"finding_subjects_by_code"],i=r.filter(o=>e[o]!==void 0).length;return i!==0&&i!==r.length?!1:t.every(o=>L(e[o],x))&&n.every(o=>L(e[o],x)&&(e[o]===void 0||Number(e[o])<=1e4))&&L(e.finding_subjects_by_code,te)}function vr(e,t,n,r){let i=yr(e,n,r);if(i===void 0)return;let o=["articulation_points","bridge_edges","outcome_nodes","active_outcome_reachable_nodes","active_outcome_unreachable_nodes","terminal_nodes","terminal_outcome_reachable_nodes","terminal_outcome_unreachable_nodes","outcome_reachable_nodes","outcome_unreachable_nodes"],s=["active_outcome_reachability_basis_points","terminal_outcome_reachability_basis_points","outcome_reachability_basis_points"];if(!br(e,o,s)||e.edge_basis!==void 0&&e.edge_basis!=="deduplicated_directed")return;let a=te(e.finding_subjects_by_code)?e.finding_subjects_by_code:{};return{edge_basis:"deduplicated_directed",...i,...Object.fromEntries(o.map(c=>[c,e[c]??0])),...Object.fromEntries(s.map(c=>[c,e[c]??0])),finding_subjects_by_code:Object.fromEntries(A.map(c=>[c,a[c]??t[c]??0]))}}function wr(e,t,n,r,i){let o=[n,r,i],s=o.filter(d=>d!==void 0).length;if(s===0)return{edge_share_by_kind:{},semantic_edges:0,semantic_edge_share:0};if(s!==o.length||!mr(n)||!x(r)||!Nt(i))return;let a=Object.entries(t);if(a.reduce((d,[,l])=>d+l,0)!==e||Object.keys(n).length!==a.length||a.some(([d,l])=>n[d]!==(e===0?0:l/e)))return;let c=a.reduce((d,[l,g])=>d+(Q(l)?g:0),0);if(!(r!==c||i!==(e===0?0:c/e)))return{edge_share_by_kind:n,semantic_edges:r,semantic_edge_share:i}}function kr(e){if(e!==null)try{let t=JSON.parse(e);if(!O(t))return;let n=t,r=n.profile;if(typeof n.saved_at!="string"||typeof n.fingerprint!="string")return;let i=n.affected_subjects_by_code;if(!te(i)||!O(r)||!ht(r)||![r.nodes,r.edges,r.active_nodes,r.missing_nodes,r.isolated_active_nodes,r.degree_leq_one_active_nodes].every(x)||!te(r.edges_by_kind)||!L(r.coverage_by_type,_r))return;let o=wr(r.edges,r.edges_by_kind,r.edge_share_by_kind,r.semantic_edges,r.semantic_edge_share);if(o===void 0)return;let s=vr(r,i,r.nodes,r.edges);if(s===void 0)return;let{coverage_by_type:a={}}=r;return{...n,profile:{...r,...o,...s,coverage_by_type:a}}}catch{return}}async function At(e){return kr(await j(Dt(e)))}async function Rt(e,t){await re(Dt(e),JSON.stringify(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="253f392d-4e91-57ec-b656-6134583d57e5")}catch{}})();var Ir={missing_reference_active:{op:"investigate",confidence:"medium",rationale:"Restore or re-create the referenced item, or remove/retype the reference on the active holder; the correct fix depends on why the target is absent."},missing_reference_terminal:{op:"waive",confidence:"high",rationale:"Terminal-holder reference to an absent item is historical debt; waive it or clean it up only in a dedicated changelog-safe closed-item batch."},legacy_no_blocker_sentinel:{op:"remove",confidence:"high",rationale:"The pre-structured-dependency no-active-blocker sentinel is retired and carries no information; blocker state derives from blocked_by edges."},ordering_cycle:{op:"investigate",confidence:"low",rationale:"Every cycle member is unschedulable until one ordering edge is removed or retyped; the planner never chooses which edge to cut."},legacy_ordering_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only ordering cycles have no scheduling effect; repairing them would mutate closed history (changelog drag)."},ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The structured ordering row asserts the opposite precedence from the same-target scalar blocker; remove that exact dependency row or replace both representations with one unambiguous edge."},legacy_ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The terminal holder contains a proven contradictory structured ordering row; remove it in a dedicated changelog-safe batch while preserving the scalar blocker as history."},hierarchy_cycle:{op:"investigate",confidence:"low",rationale:"Cut or retype one exact structural relation in the cycle; the planner preserves every evidence row because intent determines the correct parent."},legacy_hierarchy_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only hierarchy cycles are historical debt; waive them unless an explicit closed-history repair is approved."},hierarchy_cardinality_violation:{op:"investigate",confidence:"medium",rationale:"Choose the canonical parent and remove or retype the exact surplus hierarchy rows; the planner cannot infer ownership intent."},legacy_hierarchy_cardinality_violation:{op:"waive",confidence:"high",rationale:"Multiple parents confined to terminal items are historical debt; waive them unless a dedicated history repair is approved."},hierarchy_direction_violation:{op:"investigate",confidence:"medium",rationale:"Align the scalar parent and dependency-backed hierarchy rows to the intended canonical parent."},legacy_hierarchy_direction_violation:{op:"waive",confidence:"high",rationale:"Divergent hierarchy storage confined to terminal items is historical debt; waive it unless a dedicated history repair is approved."},duplicate_edge:{op:"remove",confidence:"high",rationale:"Parallel same-family spellings state one relationship twice; remove all but one stored spelling, keeping the holder's canonical direction."},legacy_duplicate_edge:{op:"waive",confidence:"high",rationale:"Duplicated spellings between terminal items are historical noise; waive or batch changelog-safe cleanup."},duplicate_dependency_row:{op:"remove",confidence:"high",rationale:"The identical dependency row is stored more than once on the holder; drop the repeats so the row exists exactly once \u2014 graph semantics are unchanged."},legacy_duplicate_dependency_row:{op:"waive",confidence:"high",rationale:"Repeated identical rows on terminal holders are storage noise; waive or clean up only in a changelog-safe closed-item batch."},stale_lifecycle_block:{op:"investigate",confidence:"medium",rationale:`Add a local ordering edge, declare an external blocker with --dep "id=<external-ref>,kind=blocked_by,source_kind=external", or move the item back to an active status; only the holder's owner knows which is true.`},isolated_active_node:{op:"investigate",confidence:"medium",rationale:"Link the item to its parent, prerequisite, or origin \u2014 or register it as an explicitly exempt isolate; the audit never fabricates an edge."},sparse_active_node:{op:"investigate",confidence:"low",rationale:"Investigate for an honest second edge (story-to-task, defect family, cross-epic complement); sparse is not automatically defective."}};function Ot(e){return`${e.source} -${e.kind}-> ${e.target}`}function xr(e){let[t,...n]=e.edges;return n.map(r=>({op:"remove",code:"duplicate_edge",subject:Ot(r),rationale:"This stored spelling restates the kept canonical edge of the same semantic family; removing it leaves the relationship stated exactly once.",evidence:[`keep: ${Ot(t)}`,`group: ${Z(e)}`],confidence:"high"}))}function Er(e,t){if(e.code==="duplicate_edge")return e.sample.flatMap(r=>xr(t.get(r)));let n=Ir[e.code];return e.sample.map(r=>({op:n.op,code:e.code,subject:r,rationale:n.rationale,evidence:[e.policy],confidence:n.confidence}))}function jt(e,t={}){let{redundancyLimit:n,...r}=t,i=ee(e,r),o=new Map(ue(e).map(d=>[Z(d),d])),s=i.findings.flatMap(d=>Er(d,o)),a=i.findings.some(d=>d.sample_truncated);t.signal?.throwIfAborted();let c=T(e.graph,{limit:n??t.maxSampleSize??25,...t.signal===void 0?{}:{signal:t.signal}});for(let d of c.value)s.push({op:"remove",code:"redundant_edge",subject:`${d.edge.source} -> ${d.edge.target} (${d.edge.kind})`,rationale:"The stored edge is implied by a longer same-family witness path; shortcut edges are sometimes deliberate emphasis, so confirm intent before removing.",evidence:[`witness: ${d.witness.join(" -> ")}`],confidence:"medium"});return a=a||c.meta.truncated,{steps:s,report:i,truncated:a,cost:{visitedNodes:c.meta.visitedNodes,inspectedEdges:c.meta.inspectedEdges}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="66df3949-0caf-5f01-8cec-3bba3d1e6111")}catch{}})();var Ft=new Set(["ancestors","descendants","predecessors","successors","paths","impact","dominators"]);function Mt(e,t,n){let r=e;if(t&&e.subcommand==="audit"){let{nodes:i,recorded_nodes:o,edges:s,active_nodes:a,terminal_nodes:c,missing_nodes:d,ordering_acyclic:l,active_ordering_acyclic:g,coverage_by_lifecycle:u}=e.profile,f=Object.fromEntries(Object.entries(u).map(([p,m])=>{let{degree_histogram:b,...v}=m;return[p,v]}));r={...e,profile:{nodes:i,recorded_nodes:o,edges:s,active_nodes:a,terminal_nodes:c,missing_nodes:d,ordering_acyclic:l,active_ordering_acyclic:g,coverage_by_lifecycle:f}}}return{...r,projection:{mode:t?"summary":"full",declared_field_groups:n===void 0?[]:[{name:n,restore_with:"--full"}],included_field_groups:n===void 0||t?[]:[n]}}}function Sr(e,t,n,r){return{assembly:t,...n===void 0?{}:{kinds:n},maxDepth:Ue(r.maxDepth),limit:e==="impact"&&Number(r.limit)===0?0:$(r.limit,"limit")??(r.full===!0?Number.MAX_SAFE_INTEGER:I.rows),after:r.after?.trim()||void 0,direction:Be(r.direction),maxPaths:$(r.maxPaths,"max-paths"),sample:$(r.sample,"sample")??I.samples,exemptIsolates:Pt(r.exemptIsolate),exemptIsolateTypes:Pt(r.exemptIsolateType),saveBaseline:r.saveBaseline===!0,summary:r.summary===!0,unbounded:r.full===!0}}function Pt(e){return e===void 0?[]:(Array.isArray(e)?e:[e]).flatMap(t=>t.split(",")).map(t=>t.trim()).filter(t=>t.length>0)}function Cr(e,t,n){let r=e.trim().toLowerCase();if(!ie.includes(r))throw Oe({command_path:"graph",token:r||"<empty>",allowed:ie});let i=r;if(Ft.has(i)&&!t?.trim())throw new k(`graph ${i} requires an item id.`,w.USAGE);if(i==="paths"&&!n?.trim())throw new k("graph paths requires a source and a target item id.",w.USAGE);return i}function ye(e){throw e instanceof TypeError?new k(e.message,w.USAGE):e}function be(e){return{truncated:e.truncated,cost:{visited_nodes:e.visitedNodes,inspected_edges:e.inspectedEdges}}}function Lt(e,t){let n=t.trim().toLowerCase();for(let r of e.details)if(r.id.trim().toLowerCase()===n&&!e.missingIdSet.has(r.id.toLowerCase()))return r.id;throw new k(`Item ${t} not found`,w.NOT_FOUND)}function Dr(e,t,n){let r={ancestors:Qe,descendants:Ze,predecessors:et,successors:tt}[e],i;try{i=r(n.assembly.graph,t,{...n.kinds===void 0?{}:{kinds:n.kinds},...n.maxDepth===void 0?{}:{maxDepth:n.maxDepth},limit:n.limit,...n.after===void 0?{}:{after:n.after}})}catch(s){ye(s)}let o=be(i.meta);return{subcommand:e,root:t,count:i.value.length,...o,...i.meta.nextCursor===void 0?{}:{next_cursor:i.meta.nextCursor},...n.summary?{}:{ids:i.value}}}function Tr(e,t,n){let r=nt(n.assembly.graph,e,t,{direction:n.direction,...n.kinds===void 0?{}:{kinds:n.kinds},...n.maxDepth===void 0?{}:{maxDepth:n.maxDepth},...n.maxPaths===void 0?{}:{maxPaths:n.maxPaths}});return{subcommand:"paths",root:e,target:t,direction:n.direction,count:r.value.length,...be(r.meta),...n.summary?{}:{paths:r.value.map(i=>({nodes:i.nodes,kinds:i.edges.map(o=>o.kind),length:i.length}))}}}function Nr(e,t){let n;try{n=U(t.assembly.graph,e,{direction:t.direction,...t.kinds===void 0?{}:{kinds:t.kinds},...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth},...t.unbounded?{}:{limit:t.limit},...t.after===void 0?{}:{after:t.after}})}catch(r){ye(r)}return{subcommand:"impact",root:e,direction:t.direction,count:n.affected.length,truncated:n.truncated,...n.nextCursor===void 0?{}:{next_cursor:n.nextCursor},cost:{visited_nodes:n.cost.visitedNodes,inspected_edges:n.cost.inspectedEdges},...t.summary?{}:{affected:n.affected}}}function Ar(e,t,n){return{acyclic:e.acyclic,ordered_node_count:e.order.length,layer_count:e.layers.length,frontier_count:e.frontier.length,critical_path_length:e.criticalPathLength,cycle_count:e.cycles.length,...t?{}:{frontier:e.frontier.slice(0,n),critical_path:e.criticalPath.slice(0,n),cycles:e.cycles.slice(0,n)}}}function Rr(e,t,n){return{component_count:e.components.length,largest_component_size:e.components[0]?.length??0,orphan_count:e.orphans.length,...t?{}:{orphans:e.orphans.slice(0,n),hubs:e.hubs.slice(0,n)}}}function Or(e,t,n){let r=0,i=0,o=0;for(let s of e.cycles)r+=Number(s.legacy_terminal);for(let s of e.cardinality_violations)i+=Number(s.legacy_terminal);for(let s of e.divergences)o+=Number(s.legacy_terminal);return{acyclic:e.cycles.length===0,relation_count:e.relations.length,cycle_count:e.cycles.length,active_cycle_count:e.cycles.length-r,legacy_cycle_count:r,cardinality_violation_count:e.cardinality_violations.length,active_cardinality_violation_count:e.cardinality_violations.length-i,legacy_cardinality_violation_count:i,parent_divergence_count:e.divergences.length,active_parent_divergence_count:e.divergences.length-o,legacy_parent_divergence_count:o,...t?{}:{cycles:e.cycles.slice(0,n).map(s=>s.item_ids)}}}function jr(e){let t=e.assembly.graph,n=e.limit,r=B(t,{registry:t.registry()}),i=Ye(t);return{subcommand:"analyze",node_count:t.nodes().length,edge_count:t.edges().length,edge_basis:"deduplicated_directed",sample_limit:n,execution:Ar(r,e.summary,n),knowledge:Rr(i,e.summary,n),hierarchy:Or(G(e.assembly),e.summary,n)}}function Mr(e,t){let n=ee(e.assembly,{isTerminal:t,maxSampleSize:e.sample,...e.exemptIsolates.length===0?{}:{exemptIsolates:e.exemptIsolates},...e.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:e.exemptIsolateTypes}}),r={},i={},o={},s={};for(let d of n.findings)r[d.severity]=(r[d.severity]??0)+1,i[d.code]=(i[d.code]??0)+1,o[d.severity]=(o[d.severity]??0)+d.count,s[d.code]=(s[d.code]??0)+d.count;let{finding_subjects_by_code:a,...c}=n.profile;return{subcommand:"audit",truncated:n.findings.length>e.limit,finding_count:n.findings.length,findings_by_severity:r,findings_by_code:i,affected_subjects_by_severity:o,affected_subjects_by_code:s,profile:e.summary?c:n.profile,legacy_alias_counts:e.assembly.legacyAliasCounts,...e.summary?{}:{findings:n.findings.slice(0,e.limit)}}}function Pr(e){let t=e.limit,n={};e.kinds!==void 0&&(n.kinds=e.kinds);let r=it(e.assembly.graph,n),i=r.value;return{subcommand:"communities",community_count:i.communities.length,largest_community_size:i.communities[0]?.size??0,iterations:i.iterations,converged:i.converged,truncated:!i.converged||i.communities.length>t,cost:{visited_nodes:r.meta.visitedNodes,inspected_edges:r.meta.inspectedEdges},...e.summary?{}:{communities:i.communities.slice(0,t).map(o=>({representative:o.representative,size:o.size,members:o.members.slice(0,t)}))}}}function Lr(e){let t;try{t=T(e.assembly.graph,{...e.kinds===void 0?{}:{kinds:e.kinds},...e.maxDepth===void 0?{}:{maxDepth:e.maxDepth},limit:e.limit})}catch(n){ye(n)}return{subcommand:"redundancy",redundant_count:t.value.length,...be(t.meta),...e.summary?{}:{redundant:t.value.map(n=>({source:n.edge.source,target:n.edge.target,kind:n.edge.kind,witness:n.witness}))}}}function Fr(e,t){let n=t.limit,r=ot(t.assembly.graph,e,{direction:t.direction,...t.kinds===void 0?{}:{kinds:t.kinds},...t.maxDepth===void 0?{}:{maxDepth:t.maxDepth}}),i=r.value.rows.filter(o=>o.dominatedCount>0);return{subcommand:"dominators",root:e,direction:t.direction,reachable_count:r.value.reachableCount,bottleneck_count:i.length,truncated:r.meta.truncated||i.length>n,cost:{visited_nodes:r.meta.visitedNodes,inspected_edges:r.meta.inspectedEdges},...t.summary?{}:{bottlenecks:i.slice(0,n).map(o=>({id:o.id,idom:o.idom,dominated_count:o.dominatedCount}))}}}function Gr(e){let t=e.limit,n=lt(e.assembly.graph),r=n.rows.filter(i=>i.critical).length;return{subcommand:"slack",acyclic:n.acyclic,makespan:n.makespan,scheduled_count:n.scheduledCount,critical_count:r,critical_path_length:n.criticalPathLength,cycle_count:n.cycles.length,truncated:n.rows.length>t,...e.summary?{}:{critical_path:n.criticalPath.slice(0,t),rows:n.rows.slice(0,t).map(i=>({id:i.id,earliest_start:i.earliestStart,latest_start:i.latestStart,slack:i.slack,critical:i.critical}))}}}function $r(e){let t=e.limit,n=dt(e.assembly.graph,e.kinds===void 0?{}:{kinds:e.kinds}),r=n.value;return{subcommand:"centrality",node_count:r.nodeCount,edge_count:r.edgeCount,edge_basis:"simple_undirected",truncated:r.rows.length>t,cost:{visited_nodes:n.meta.visitedNodes,inspected_edges:n.meta.inspectedEdges},...e.summary?{}:{rows:r.rows.slice(0,t).map(i=>({id:i.id,degree:i.degree,in_degree:i.inDegree,out_degree:i.outDegree,betweenness:i.betweenness,closeness:i.closeness}))}}}function qr(e){let t=e.limit,n=X(e.assembly.graph,e.kinds===void 0?{}:{kinds:e.kinds}),{articulationPoints:r,bridges:i}=n.value;return{subcommand:"articulation",articulation_count:r.length,bridge_count:i.length,truncated:r.length>t||i.length>t,cost:{visited_nodes:n.meta.visitedNodes,inspected_edges:n.meta.inspectedEdges},...e.summary?{}:{articulation_points:r.slice(0,t),bridges:i.slice(0,t)}}}function Ur(e,t){let n=e.limit,r=jt(e.assembly,{isTerminal:t,redundancyLimit:n,maxSampleSize:e.sample,...e.exemptIsolates.length===0?{}:{exemptIsolates:e.exemptIsolates},...e.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:e.exemptIsolateTypes}}),i={},o={};for(let s of r.steps)i[s.op]=(i[s.op]??0)+1,o[s.code]=(o[s.code]??0)+1;return{subcommand:"plan",step_count:r.steps.length,steps_by_op:i,steps_by_code:o,finding_count:r.report.findings.length,truncated:r.truncated||r.steps.length>n,cost:{visited_nodes:r.cost.visitedNodes,inspected_edges:r.cost.inspectedEdges},...e.summary?{}:{steps:r.steps.slice(0,n)}}}function Gt(e,t,n,r){return JSON.stringify({projection_version:2,subcommand:e,root:t??null,target:n??null,kinds:r.kinds??null,maxDepth:r.maxDepth??null,limit:r.limit,after:r.after??null,direction:r.direction,maxPaths:r.maxPaths??null,sample:r.sample,exemptIsolates:[...new Set(r.exemptIsolates.map(i=>i.toLowerCase()))].sort(),exemptIsolateTypes:[...new Set(r.exemptIsolateTypes.map(i=>i.toLowerCase()))].sort(),summary:r.summary,unbounded:r.unbounded})}function $t(e,t,n,r,i){return e==="analyze"?jr(r):e==="audit"?Mr(r,i):e==="plan"?Ur(r,i):e==="communities"?Pr(r):e==="redundancy"?Lr(r):e==="dominators"?Fr(t,r):e==="slack"?Gr(r):e==="centrality"?$r(r):e==="articulation"?qr(r):e==="paths"?Tr(t,n,r):e==="impact"?Nr(t,r):Dr(e,t,r)}function Br(e,t){if(e!=="index"&&(t.rebuild===!0||t.clear===!0))throw new k("--rebuild and --clear apply only to graph index.",w.USAGE);if(e!=="audit"&&t.saveBaseline===!0)throw new k("--save-baseline applies only to graph audit.",w.USAGE);if(e==="slack"&&t.kind!==void 0)throw new k("graph slack analyzes every ordering kind; --kind is not supported.",w.USAGE);if(t.rebuild===!0&&t.clear===!0)throw new k("graph index accepts either --rebuild or --clear, not both.",w.USAGE);if(t.full===!0&&t.limit!==void 0)throw new k(`graph ${e} accepts either --full or --limit, not both.`,w.USAGE)}async function zr(e,t,n,r,i,o){let s="status";if(o.clear===!0&&(await me(e),s="cleared"),o.rebuild===!0){await me(e);let c=await pe(e,t),d={assembly:n.assembly,direction:"both",exemptIsolates:[],exemptIsolateTypes:[],saveBaseline:!1,summary:!0,limit:I.rows,sample:I.samples,unbounded:!1};for(let l of["analyze","audit"])await he(e,t,c,Gt(l,void 0,void 0,d),$t(l,void 0,void 0,d,i));s="rebuilt"}let a=await Tt(e,t);return{subcommand:"index",action:s,state:a.exists?a.fresh?"fresh":"stale":"absent",entry_count:a.entry_count,item_count:r,min_items_threshold:ge,persist_enabled:_e(r,a.exists),current_fingerprint:t.slice(0,12),...a.saved_at===void 0?{}:{saved_at:a.saved_at},...a.bytes===void 0?{}:{bytes:a.bytes}}}async function Hr(e,t,n,r){let i={saved_at:new Date().toISOString(),fingerprint:t,affected_subjects_by_code:n.affected_subjects_by_code,profile:{...n.profile,finding_subjects_by_code:Object.fromEntries(A.map(s=>[s,n.affected_subjects_by_code[s]??0]))}},o=await At(e);return r&&await Rt(e,i),o===void 0?n:{...n,baseline:xt(o,i)}}async function Kr(e,t,n,r,i){try{await he(e,t,n,r,i)}catch{}}function Vr(e,t,n,r){if(e.subcommand!=="slack")return;let i=new Set(t.assembly.details.filter(u=>r(u.status)).map(u=>u.id)),o=t.assembly.graph,s=new ke(o.nodes().filter(u=>!i.has(u)),o.edges().filter(u=>!i.has(u.source)&&!i.has(u.target)),o.registry()),a=ut(s,n.filter(u=>!i.has(u.id)),{now:Ae(),limit:t.limit}),{rows:c,residuals:d,overcommitted:l,...g}=a;e.deadline_schedule={population:"active",...g,...t.summary?{}:{rows:c,residuals:d,overcommitted:l}}}async function ro(e,t,n,r,i){let o=Cr(e,t,n);De(r.summary===!0,r.full===!0,"--summary");let s=Ee(process.cwd(),i.path);await Pe(s);let a=await Me(s),c=xe(a,Ce()),d=await Le(s,a.item_format,c.type_to_folder,void 0,a.schema),l=Se(a.schema),g=qt=>je(qt,l);Br(o,r);let u=Fe(),f=ze(r.kind,u),p=qe().lookup(s,$e(d,g,u),()=>Ge(d,g,u)),m=Sr(o,p.assembly,f,r);if(o==="index")return Mt(await zr(s,p.fingerprint,m,d.length,g,r),!1);let b=Ft.has(o)?Lt(m.assembly,t):void 0,v=o==="paths"?Lt(m.assembly,n):void 0,h=Gt(o,b,v,m),_=await pe(s,p.fingerprint),E=_.results[h],S=p.memoize(h,()=>E!==void 0?structuredClone(E):$t(o,b,v,m,g)),ve=_e(d.length,_.exists);!S.reused&&E===void 0&&ve&&await Kr(s,p.fingerprint,_,h,S.value);let ne=S.value.subcommand==="audit"?await Hr(s,p.fingerprint,S.value,m.saveBaseline):S.value;return ne.cache={fingerprint:p.fingerprint.slice(0,12),assembly:p.assemblyReused?"hit":"miss",result:S.reused?"hit":"miss",durable:E!==void 0?"hit":ve?"miss":"off"},Vr(ne,m,d,g),Mt(ne,m.summary,"result_rows")}export{B as a,U as b,Ye as c,Xr as d,Qe as e,Ze as f,et as g,tt as h,nt as i,V as j,it as k,T as l,ot as m,dt as n,X as o,lt as p,ut as q,tr as r,It as s,Z as t,ue as u,ee as v,xt as w,St as x,ge as y,F as z,Dt as A,pe as B,he as C,me as D,Tt as E,_e as F,At as G,Rt as H,jt as I,Cr as J,ro as K};
2
+ //# sourceMappingURL=chunk-EDXTOAXP.js.map
@@ -0,0 +1,91 @@
1
+ import{$ as _t,Ea as je,Ga as me,Oa as bt,Wa as Et,bb as It,ca as gt,cb as fe,ea as wt,m as Ae,n as yt,ua as Le,va as Pe,wa as K,x as ue,y as ht,z as q}from"./chunk-P7DPS5M4.js";import{b as se}from"./chunk-4MNUQCGR.js";import{h as pt}from"./chunk-YLVHHWHN.js";import{Aa as Re,Ba as Ne,Ca as R,Dc as G,Kd as mt,Ld as ft,Na as st,Ra as ct,Sa as dt,Ub as lt,a as ae,ic as Y,kc as ke,lc as de,ma as ot,mc as L,na as nt,nc as Oe,oc as le,pc as De,qa as rt,sc as Me,va as ce,vd as ut,wd as Fe,xa as at}from"./chunk-OMXMYTEX.js";import{A as it,B as X,D as A,H as O,s as F,x as tt,y as p,z as f}from"./chunk-BUZ2Z4P3.js";import ai from"node:crypto";import pe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();function Ct(e){let i=[],t=!1;for(let o of(e??"").toLowerCase()){let n=o.charCodeAt(0),r=n>=48&&n<=57,a=n>=97&&n<=122;if(!r&&!a){t=i.length>0;continue}t&&(i.push("-"),t=!1),i.push(o)}return i.length===0?"pm-":`${i.join("")}-`}function V(e){let i=e.trim().toLowerCase();return i.startsWith("#")&&(i=i.slice(1)),i}function J(e,i){let t=Ct(i),o=V(e);return o.startsWith(t)?o:`${t}${o}`}function si(e){let i=ut(e);if(i!==void 0)return i;let t="";for(let o=0;o<e;o+=1)t+=ai.randomInt(0,36).toString(36);return t}async function ci(e,i,t){let o=[...new Set(Object.values(t))].flatMap(n=>[pe.join(e,n,`${i}.md`),pe.join(e,n,`${i}.toon`)]);return o.push(pe.join(e,"history",`${i}.jsonl`)),(await Promise.all(o.map(n=>X(n)))).some(Boolean)}var vt=4,Tt=12;function di(e){return typeof e!="number"||!Number.isFinite(e)?vt:Math.min(Tt,Math.max(vt,Math.trunc(e)))}async function Bo(e,i,t={}){let o=di(t.tokenLength),n=Math.min(o+6,Tt),r=0;for(;o<=n;){for(let a=0;a<32;a+=1){let s=`${Ct(i)}${si(o)}`;if(!await(t.probeExisting===!1?X(pe.join(e,"history",`${s}.jsonl`)):ci(e,s,t.typeToFolder??F)))return s;r+=1}o+=1}throw new Error(`Unable to generate unique id after ${r} attempts`)}import St from"node:fs/promises";import Q from"node:path";import{isUtf8 as li}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="7db1d069-0038-57f8-8c3e-0b0ba66579ca")}catch{}})();var ui=1048576,mi=4194304;async function xt(e,i){let t=Q.dirname(e);for(;t!==Q.parse(e).root;){let n=await St.stat(t).catch(r=>{if(A(r))return null;throw r});if(n!==null){if(!n.isDirectory())throw new f("Workflow policy storage ancestor must be a directory.",p.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Restore the policy or approval history directory before retrying."]});break}t=Q.dirname(t)}let o=await St.open(e,"r").catch(n=>{if(A(n))return null;throw n});if(o===null)return null;try{let n=(await o.stat()).size,r=Buffer.alloc(Math.min(i,n)+1),a=0;for(;a<r.length;){let s=await o.read(r,a,r.length-a,a);if(s.bytesRead===0)break;a+=s.bytesRead}if(a===r.length||!li(r.subarray(0,a)))throw new f("Workflow policy input exceeds its byte bound or is not valid UTF-8.",p.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Inspect the policy and approval history; reduce the declaration or use verified history compaction before retrying."]});return r.toString("utf8",0,a)}finally{await o.close()}}function fi(e){if(e===null)return{version:1,enforcement:"advise",policies:[]};let i;try{i=JSON.parse(e)}catch{throw new f("schema/policies.json must contain valid JSON.",p.CONFLICT,{code:"workflow_policy_registry_invalid",nextSteps:["Restore valid policy JSON before retrying the mutation."]})}return st(i)}async function pi(e){return fi(await xt(Q.join(e,"schema","policies.json"),ui))}async function yi(e,i){let t=await xt(R(e,i),mi);if(t===null)return[];let o;try{if(o=t.split(/\r?\n/).filter(n=>n.trim()).map(n=>JSON.parse(n)),!me(o).ok)throw new Error("invalid chain")}catch{throw new f("Approval evidence requires a valid item history chain.",p.CONFLICT,{code:"workflow_policy_approval_history_invalid",nextSteps:[`Run pm history ${i} --verify before recording or using an approval.`]})}return o.flatMap(n=>{let r=n.context?.workflow_approval;if(n.op!=="policy_approve"||n.record_hash_version!==1||typeof n.record_hash!="string"||typeof r!="object"||r===null)return[];let a=r;return typeof a.policy_fingerprint!="string"||typeof a.content_fingerprint!="string"?[]:[{policy_fingerprint:a.policy_fingerprint,content_fingerprint:a.content_fingerprint,author:n.author}]})}async function hi(e,i,t){let o=t.before?.status!==t.after?.status&&i.policies.some(a=>a.rule.kind==="approval"&&ct(a,t)),n=t.before?.id??t.after?.id,r=o&&typeof n=="string"?await yi(e,n):[];return dt(i,{...t,approvals:r})}async function $e(e){let i=await pi(e.pmRoot),t=await hi(e.pmRoot,i,{operation:e.operation,author:e.author,before:e.before?{...e.before.metadata,body:e.before.body}:null,after:e.after?{...e.after.metadata,body:e.after.body}:null});if(t.allowed)return t;let o=t.decisions.filter(d=>!d.satisfied&&d.effect==="refuse");if(!e.dryRun)try{await bt({pmRoot:e.pmRoot,op:"policy_refused",author:e.author,context:{item_id:e.after?.metadata.id??e.before?.metadata.id,operation:e.operation,workflow_policies:t.decisions},message:"Workflow policy refused a proposed item mutation.",lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}catch(d){let u=new f("Workflow policy refusal could not be recorded in workspace history.",p.CONFLICT,{code:"workflow_policy_audit_failed",nextSteps:["Resolve workspace-history lock or storage failures, then retry the refused mutation; no item changes were written."]});throw u.cause=d,u}let n=o.slice(0,3).map(d=>({policy_id:d.policy_id,rule:d.rule,description:i.policies.find(u=>u.id===d.policy_id).description,missing_fields:d.missing_fields})),r=[...new Set(n.flatMap(d=>d.missing_fields))],a=n.map(d=>`${d.policy_id} (${d.rule})`).join(", "),s=o.length>3?` and ${o.length-3} more`:"",l=e.after?.metadata.id??e.before.metadata.id,c=r.map(d=>{if(e.before===null)return`Supply ${d} in the original ${e.operation} request, then retry; the item was not created.`;let u=ot("update",d);return u===void 0?`Supply ${d} using its declared SDK or package mutation contract, then retry.`:G(["update",l,nt("update",u),`<${d}>`,"--pm-path",Q.resolve(e.pmRoot)])});throw new f(`Workflow policy refused ${e.operation}: ${a}${s}.${r.length?` Missing: ${r.join(", ")}.`:""}`,p.CONFLICT,{code:"workflow_policy_refused",reason:n.map(d=>d.policy_id).join(","),policy_violations:n,policy_violation_count:o.length,required:r.length?`Supply missing fields: ${r.join(", ")}, then retry the refused mutation.`:"Satisfy the declared workflow policy before retrying.",why:n.map(d=>d.description).filter(Boolean).join(" ")||void 0,recovery:{missing_required_fields:r},nextSteps:[...c,...new Set(o.slice(0,3).filter(d=>d.missing_fields.length===0).map(d=>d.remediation)),...o.length>3?[`Inspect all policies with pm schema policies before retrying ${e.operation}.`]:[]]})}import{AsyncLocalStorage as _i}from"node:async_hooks";import{channel as gi}from"node:diagnostics_channel";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="b2b2d49a-bb8c-54d7-89d2-1dbe76879129")}catch{}})();var We=new _i,He=gi("@unbrained/pm-cli/item-metadata-enumeration/v1");function ye(e){He.publish(e)}async function sn(e){let i={enumeration_calls:0,metadata_rows:0},t=o=>{We.getStore()?.includes(i)&&(i.enumeration_calls+=1,i.metadata_rows+=o)};He.subscribe(t);try{return{result:await We.run([...We.getStore()??[],i],e),work:{...i}}}finally{He.unsubscribe(t)}}import P from"node:fs/promises";import Nt from"node:path";import{randomUUID as wi}from"node:crypto";import{createRequire as bi}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="84a3dae8-69b6-589d-a8ec-11f77c1d103a")}catch{}})();var Ei="metadata-query-index.sqlite",Z="5",Ue;function ee(){return Ue!==void 0||(Ue=wt(process.versions.node,bi(import.meta.url))),Ue}function Rt(e,i){return Math.max(0,Math.floor(e===void 0?i:e))}function H(e){return Nt.join(e,"runtime",Ei)}function Ii(e){e.exec(`
2
+ PRAGMA foreign_keys = ON;
3
+ PRAGMA journal_mode = OFF;
4
+ PRAGMA synchronous = OFF;
5
+ CREATE TABLE metadata (
6
+ key TEXT PRIMARY KEY,
7
+ value TEXT NOT NULL
8
+ ) STRICT;
9
+ CREATE TABLE items (
10
+ id TEXT PRIMARY KEY,
11
+ relative_path TEXT NOT NULL UNIQUE,
12
+ metadata_json TEXT NOT NULL,
13
+ status TEXT NOT NULL,
14
+ type TEXT NOT NULL,
15
+ priority INTEGER NOT NULL,
16
+ updated_at TEXT NOT NULL,
17
+ created_at TEXT NOT NULL,
18
+ parent TEXT,
19
+ assignee TEXT,
20
+ sprint TEXT,
21
+ release TEXT
22
+ ) STRICT;
23
+ CREATE INDEX items_default_order
24
+ ON items(priority, updated_at DESC, id);
25
+ CREATE INDEX items_status_default_order
26
+ ON items(status, priority, updated_at DESC, id);
27
+ CREATE INDEX items_type_default_order
28
+ ON items(type, priority, updated_at DESC, id);
29
+ CREATE INDEX items_parent_default_order
30
+ ON items(parent, priority, updated_at DESC, id);
31
+ CREATE TABLE item_metadata_keys (
32
+ item_id TEXT NOT NULL,
33
+ key TEXT NOT NULL,
34
+ PRIMARY KEY(item_id, key),
35
+ FOREIGN KEY(item_id) REFERENCES items(id) ON DELETE CASCADE
36
+ ) STRICT;
37
+ CREATE INDEX item_metadata_keys_key_item
38
+ ON item_metadata_keys(key, item_id);
39
+ CREATE TABLE item_linked_files (
40
+ item_id TEXT NOT NULL,
41
+ path TEXT NOT NULL,
42
+ scope TEXT NOT NULL,
43
+ note TEXT,
44
+ PRIMARY KEY(item_id, path, scope),
45
+ FOREIGN KEY(item_id) REFERENCES items(id) ON DELETE CASCADE
46
+ ) STRICT;
47
+ CREATE INDEX item_linked_files_path_scope_item
48
+ ON item_linked_files(path, scope, item_id);
49
+ CREATE VIRTUAL TABLE item_search USING fts5(
50
+ id UNINDEXED,
51
+ title,
52
+ description,
53
+ tags,
54
+ tokenize = 'unicode61'
55
+ );
56
+ `)}function _e(e,i,t){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(i,t)}function kt(e,i){let t=i.metadata;e.prepare(`INSERT INTO items(
57
+ id, relative_path, metadata_json, status, type, priority,
58
+ updated_at, created_at, parent, assignee, sprint, release
59
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
60
+ ON CONFLICT(id) DO UPDATE SET
61
+ relative_path = excluded.relative_path,
62
+ metadata_json = excluded.metadata_json,
63
+ status = excluded.status,
64
+ type = excluded.type,
65
+ priority = excluded.priority,
66
+ updated_at = excluded.updated_at,
67
+ created_at = excluded.created_at,
68
+ parent = excluded.parent,
69
+ assignee = excluded.assignee,
70
+ sprint = excluded.sprint,
71
+ release = excluded.release`).run(t.id,i.relativePath,JSON.stringify(t),t.status,t.type,t.priority,t.updated_at,t.created_at,t.parent??null,t.assignee??null,t.sprint??null,t.release??null),e.prepare("DELETE FROM item_metadata_keys WHERE item_id = ?").run(t.id),e.prepare("DELETE FROM item_linked_files WHERE item_id = ?").run(t.id),e.prepare("DELETE FROM item_search WHERE rowid = (SELECT rowid FROM items WHERE id = ?)").run(t.id),e.prepare("INSERT INTO item_search(rowid, id, title, description, tags) SELECT rowid, ?, ?, ?, ? FROM items WHERE id = ?").run(t.id,t.title,t.description,t.tags.join(" "),t.id);let o=e.prepare("INSERT INTO item_metadata_keys(item_id, key) VALUES (?, ?)");for(let r of Object.keys(t))o.run(t.id,r);let n=e.prepare("INSERT INTO item_linked_files(item_id, path, scope, note) VALUES (?, ?, ?, ?)");for(let r of i.linkedFiles??[])n.run(t.id,r.path,r.scope,r.note??null)}async function Ot(e){let i=H(e.pmRoot),t=ee();if(!t){await P.rm(i,{force:!0});return}await P.mkdir(Nt.dirname(i),{recursive:!0});let o=`${i}.${wi()}.tmp`,n;try{n=new t(o),Ii(n),n.exec("BEGIN IMMEDIATE"),_e(n,"version",Z),_e(n,"context_fingerprint",e.contextFingerprint),_e(n,"source_cursor",e.sourceCursor);for(let r of e.rows)kt(n,r);n.exec("COMMIT"),n.close(),n=void 0,await P.rm(i,{force:!0}),await P.rename(o,i)}catch(r){throw n?.close(),await Promise.allSettled([P.rm(o,{force:!0})]),r}}function ge(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(i=>[String(i.key),String(i.value)]))}async function Dt(e){let i=ee();if(!i)return!1;let t=H(e.pmRoot),o;try{await P.access(t),o=new i(t),o.exec("PRAGMA foreign_keys = ON");let n=ge(o);if(n.version!==Z||n.context_fingerprint!==e.contextFingerprint||n.source_cursor!==e.expectedSourceCursor)return o.close(),!1;o.exec("BEGIN IMMEDIATE");let r=o.prepare("DELETE FROM items WHERE relative_path = ?"),a=o.prepare("SELECT rowid FROM items WHERE relative_path = ?"),s=o.prepare("DELETE FROM item_search WHERE rowid = ?");for(let l of e.deletedRelativePaths??[]){let c=a.get(l);r.run(l),c&&s.run(c.rowid)}return e.row&&kt(o,e.row),_e(o,"source_cursor",e.sourceCursor),o.exec("COMMIT"),o.close(),!0}catch{try{o?.exec("ROLLBACK")}catch{}return o?.close(),!1}}function he(e,i,t,o,n){!o||o.length===0||(e.push(`${t} ${n} (${o.map(()=>"?").join(", ")})`),i.push(...o))}function vi(e){let i=[],t=[];he(i,t,"status",e.statuses,"IN"),he(i,t,"status",e.excludeStatuses,"NOT IN"),he(i,t,"type",e.types,"IN"),he(i,t,"id",e.ids,"IN");for(let o of e.metadataKeys??[])i.push("EXISTS (SELECT 1 FROM item_metadata_keys AS indexed_key WHERE indexed_key.item_id = items.id AND indexed_key.key = ?)"),t.push(o);for(let[o,n]of[["parent",e.parent],["assignee",e.assignee],["sprint",e.sprint],["release",e.release]])n!==void 0&&(i.push(`${o} = ?`),t.push(n));return e.priority!==void 0&&(i.push("priority = ?"),t.push(e.priority)),{where:i.length===0?"":` WHERE ${i.join(" AND ")}`,parameters:t}}async function yn(e){let i=ee();if(!i)return null;let t=e.query??{},{where:o,parameters:n}=vi(t),r;try{r=new i(H(e.pmRoot),{readOnly:!0});let a=ge(r);if(a.version!==Z||a.source_cursor!==e.expectedSourceCursor)return r.close(),null;let s=r.prepare(`SELECT COUNT(*) AS count FROM items${o}`).get(...n),l=[],c="";t.limit!==void 0?(c+=" LIMIT ?",l.push(Math.max(0,Math.floor(t.limit))),t.offset!==void 0&&(c+=" OFFSET ?",l.push(Math.max(0,Math.floor(t.offset))))):t.offset!==void 0&&(c+=" LIMIT -1 OFFSET ?",l.push(Math.max(0,Math.floor(t.offset))));let d=r.prepare(`SELECT metadata_json FROM items${o}
72
+ ORDER BY ${t.terminalStatuses&&t.terminalStatuses.length>0?`CASE WHEN status IN (${t.terminalStatuses.map(()=>"?").join(", ")}) THEN 1 ELSE 0 END ASC, `:""}priority ASC, updated_at DESC, id ASC${c}`).all(...n,...t.terminalStatuses??[],...l).map(u=>{let y=JSON.parse(String(u.metadata_json));if(!y.id)throw new TypeError("Indexed metadata row has no id");return y});return r.close(),{source_cursor:a.source_cursor,total:Number(s.count),items:d}}catch{return r?.close(),null}}async function hn(e){let i=ee();if(!i||e.paths.length===0)return null;let t;try{t=new i(H(e.pmRoot),{readOnly:!0});let o=ge(t);if(o.version!==Z||o.source_cursor!==e.expectedSourceCursor)return t.close(),null;let n=e.paths.map(()=>"?").join(", "),r=e.scope===void 0?"":" AND scope = ?",a=[...e.paths,...e.scope===void 0?[]:[e.scope]],s=`path IN (${n})${r}`,l=t.prepare(`SELECT COUNT(DISTINCT item_id) AS count
73
+ FROM item_linked_files
74
+ WHERE ${s}`).get(...a),c=Rt(e.limit,50),d=Rt(e.offset,0),u=t.prepare(`SELECT items.id, items.metadata_json
75
+ FROM items
76
+ WHERE EXISTS (
77
+ SELECT 1 FROM item_linked_files
78
+ WHERE item_linked_files.item_id = items.id AND ${s}
79
+ )
80
+ ORDER BY items.priority ASC, items.updated_at DESC, items.id ASC
81
+ LIMIT ? OFFSET ?`).all(...a,c,d),y=[];if(u.length>0){let h=u.map(_=>String(_.id)),m=t.prepare(`SELECT item_id, path, scope, note
82
+ FROM item_linked_files
83
+ WHERE item_id IN (${h.map(()=>"?").join(", ")})
84
+ AND ${s}
85
+ ORDER BY path ASC, scope ASC`).all(...h,...a),g=new Map(h.map(_=>[_,[]]));for(let _ of m){let b=String(_.item_id),T=g.get(b);T.push({path:String(_.path),scope:String(_.scope),..._.note===null?{}:{note:String(_.note)}}),g.set(b,T)}for(let _ of u){let b=JSON.parse(String(_.metadata_json));y.push({item:b,files:g.get(String(_.id))})}}return t.close(),{source_cursor:o.source_cursor,total:Number(l.count),matches:y}}catch{return t?.close(),null}}async function _n(e){let i=ee();if(!i)return null;let t;try{t=new i(H(e.pmRoot),{readOnly:!0});let o=ge(t);if(o.version!==Z||o.source_cursor!==e.expectedSourceCursor)return t.close(),null;let n=t.prepare(`SELECT items.metadata_json
86
+ FROM item_search
87
+ JOIN items ON items.id = item_search.id
88
+ WHERE item_search MATCH ?
89
+ ORDER BY bm25(item_search), items.priority, items.updated_at DESC, items.id
90
+ LIMIT ?`).all(e.query,Math.max(0,Math.floor(e.limit))).map(r=>JSON.parse(String(r.metadata_json)));return t.close(),{source_cursor:o.source_cursor,items:n}}catch{return t?.close(),null}}async function we(e){await P.rm(H(e),{force:!0})}import E from"node:fs/promises";import w from"node:path";import{createHash as Ci,randomUUID as Pt}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="846c1c5d-8a5c-56ee-832a-bfc780283e70")}catch{}})();var x=8,jt=500,Ti="metadata-derived-index",Si="metadata-cache.json",xi="metadata-cache-bodies.json",Ri="metadata-cache-collections.json",Ni="metadata-cache-delta.json",ki="metadata-cache-manifest.json",Mt=4,Oi=["comments","notes","learnings","files","tests","test_runs","docs"];function $t(){return se(Y())}function Ee(e){let i={...e},t={};for(let o of Oi)o in i&&(t[o]=i[o],delete i[o]);return{light:i,heavy:t}}function Wt(e,i){return!i||Object.keys(i).length===0?e:{...e,...i}}function Ht(e,i,t,o){let n=Ci("sha256");n.update(`format:${e??"default"}`);let r=Object.entries(i).sort(([a],[s])=>a.localeCompare(s)).map(([a,s])=>`${a}=${s}`).join(",");return n.update(`|types:${r}`),t&&n.update(`|schema:${JSON.stringify(t)}`),o.length>0&&n.update(`|extension_fields:${o.join(",")}`),n.digest("hex").slice(0,16)}function Ie(e){return w.join(e,"runtime",Si)}function ve(e){return w.join(e,"runtime",xi)}function Ce(e){return w.join(e,"runtime",Ri)}function ze(e){return w.join(e,"runtime",Ni)}function Xe(e){return w.join(e,"runtime",ki)}function Te(e,i){let t=w.extname(e);return`${e.slice(0,-t.length)}.${i}${t}`}var Di=24,v=new Map,Se=new WeakMap;function Ye(e){return Se.get(e)??e.source_cursor}function Mi(e,i){let t=Ye(e);if(!(i.base_source_cursor!==t||e.source_cursor===i.source_cursor)){Se.set(e,t);for(let[o,n]of Object.entries(i.changes))n.entry?e.entries[o]=n.entry:delete e.entries[o];e.directory_signatures=i.directory_signatures,e.source_cursor=i.source_cursor}}function Fi(e,i){if(!e)return;let t=Ye(e);if(!(i.base_source_cursor!==t||e.source_cursor===i.source_cursor)){Se.set(e,t);for(let[o,n]of Object.entries(i.changes))n.body?e.bodies[o]=n.body:delete e.bodies[o];e.source_cursor=i.source_cursor}}function Ai(e,i){if(!e)return;let t=Ye(e);if(!(i.base_source_cursor!==t||e.source_cursor===i.source_cursor)){Se.set(e,t);for(let[o,n]of Object.entries(i.changes))n.collections?e.collections[o]=n.collections:delete e.collections[o];e.source_cursor=i.source_cursor}}function Li(e,i,t,o){!e||!o||e.context_fingerprint!==o.context_fingerprint||(Mi(e,o),Fi(i,o),Ai(t,o))}function Be(e,i){v.size>=Di&&!v.has(e)&&lt(v),v.set(e,i)}async function D(e,i){let t;try{t=await E.stat(e)}catch{return v.delete(e),null}let o=v.get(e);if(o&&te(o.signature,t.mtimeMs,t.ctimeMs,t.size))return v.delete(e),v.set(e,o),o.envelope;let n;try{n=i(await E.readFile(e,"utf8"))}catch{n=null}return Be(e,{signature:{mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size},envelope:n}),n}async function Pi(e,i,t){let o=s=>{let l=JSON.parse(s);return l.version!==x||typeof l.source_cursor!="string"||typeof l.entries!="object"||l.entries===null?null:l},n=Ie(e),r=await D(n,o);if(!i||r===null||r.context_fingerprint===i)return r;let a=await D(Te(n,i),o);return a===null&&ne(t,`metadata_cache_context_changed:${r.context_fingerprint}->${i}`),a}async function ji(e,i){let t=r=>{let a=JSON.parse(r);return a.version!==x||typeof a.source_cursor!="string"||typeof a.bodies!="object"||a.bodies===null?null:a},o=ve(e),n=await D(o,t);return i&&n?.context_fingerprint!==i?await D(Te(o,i),t):n}async function $i(e,i){let t=r=>{let a=JSON.parse(r);return a.version!==x||typeof a.source_cursor!="string"||typeof a.collections!="object"||a.collections===null?null:a},o=Ce(e),n=await D(o,t);return i&&n?.context_fingerprint!==i?await D(Te(o,i),t):n}async function Ge(e){let i=ze(e),t=await D(i,o=>{let n=JSON.parse(o);return n.version!==x||typeof n.base_source_cursor!="string"||typeof n.source_cursor!="string"||typeof n.changes!="object"||n.changes===null?null:n});if(t)return{envelope:t,invalid:!1};try{return await E.stat(i),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function qe(e){let i=Xe(e),t=await D(i,o=>{let n=JSON.parse(o);return n.version!==x||typeof n.context_fingerprint!="string"||typeof n.source_cursor!="string"||!Number.isInteger(n.entry_count)||n.entry_count<0||typeof n.directory_signatures!="object"||n.directory_signatures===null?null:n});if(t)return t;try{await E.stat(i),await U(e)}catch{}return null}async function ie(e,i){await E.mkdir(w.dirname(e),{recursive:!0}),await O(e,JSON.stringify(i));try{let o=await E.stat(e);Be(e,{signature:{mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size},envelope:i})}catch{v.delete(e)}let t=w.dirname(w.dirname(e));if(e===Ie(t)||e===ve(t)||e===Ce(t)){let o=Te(e,i.context_fingerprint);await O(o,JSON.stringify(i));try{let l=await E.stat(o);Be(o,{signature:{mtime_ms:l.mtimeMs,ctime_ms:l.ctimeMs,size:l.size},envelope:i})}catch{v.delete(o)}let n=w.dirname(e),r=w.extname(e),a=w.basename(e,r),s=(await E.readdir(n,{withFileTypes:!0}).catch(()=>[])).filter(l=>l.isFile()&&l.name!==w.basename(e)&&l.name.startsWith(`${a}.`)&&l.name.endsWith(r)).map(l=>w.join(n,l.name));if(s.length>Mt){let l=(await Promise.all(s.map(async c=>{try{return{path:c,mtime:(await E.stat(c)).mtimeMs}}catch{return null}}))).filter(c=>c!==null);for(let c of l.sort((d,u)=>d.mtime-u.mtime).slice(0,Math.max(0,l.length-Mt)))await E.rm(c.path,{force:!0}),v.delete(c.path)}}}function Wi(e,i,t){return t?i===t&&e!==t:i==="toon"&&e!=="toon"}function Ut(e,i,t){return e===void 0||Wi(e,i,t)}function ne(e,i){e&&!e.includes(i)&&e.push(i)}function te(e,i,t,o){return e.mtime_ms===i&&e.ctime_ms===t&&e.size===o}async function Hi(e,i,t){let o=w.join(e,i);try{let n=await E.readdir(o);return{folder:i,dirPath:o,files:n}}catch(n){return typeof n=="object"&&n!==null&&"code"in n&&!A(n)&&ne(t,`item_list_directory_read_failed:${i}`),{folder:i,dirPath:o,files:[]}}}async function Ui(e,i){try{let t=await E.stat(w.join(e,i));return[i,{exists:!0,mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size}]}catch{return[i,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function be(e,i){return Object.fromEntries(await Promise.all(i.map(async t=>await Ui(e,t))))}function oe(e,i){return!e||Object.keys(e).length!==Object.keys(i).length?!1:Object.entries(i).every(([t,o])=>{let n=e[t];return n!==void 0&&n.exists===o.exists&&te(n,o.mtime_ms,o.ctime_ms,o.size)})}function Bi(e){return ce.some(i=>e.toLowerCase().endsWith(i))}function zi(e,i,t,o,n,r){o||(e.metadata=!0),i&&!n&&(e.body=!0),t&&!r&&(e.collections=!0)}async function Xi(e,i,t){if(t)for(let o of await le({path:e,scope:"project"}))ne(i,o)}function Ft(e,i,t,o){if(e)return i&&t?t.collections:o}async function Yi(e,i,t){let o=await E.stat(e),n=o.mtimeMs,r=o.ctimeMs,{size:a}=o,s=Ne(e);await Xi(e,t.warnings,t.dispatchReadHooks);let l=t.previousEntries[i],c=!t.forceSourceRead&&l!==void 0&&te(l,n,r,a),d=t.previousBodies[i],u=!t.forceSourceRead&&d!==void 0&&te(d,n,r,a),y=t.previousCollections[i],h=!t.forceSourceRead&&y!==void 0&&te(y,n,r,a);if(!(!c||t.includeBody&&!u||t.includeCollections&&!h))return{mtimeMs:n,ctimeMs:r,size:a,itemFormat:s,lightMetadata:l.metadata,heavyMetadata:Ft(t.includeCollections,h,y,void 0),bodyLength:l.body_length,body:t.includeBody?d.body:void 0};let m=await E.readFile(e,"utf8"),g=ue(m,{format:s,schema:t.schema,extensionFieldNames:t.extensionFieldNames,onWarning:b=>ne(t.warnings,b)}),_=Ee(g.metadata);return zi(t.state.misses,t.includeBody,t.includeCollections,c,u,h),{mtimeMs:n,ctimeMs:r,size:a,itemFormat:s,lightMetadata:c?l.metadata:_.light,heavyMetadata:Ft(t.includeCollections,h,y,_.heavy),bodyLength:c?l.body_length:g.body.length,body:t.includeBody?g.body:void 0}}function Gi(e,i,t,o){t.state.newEntries[i]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,metadata:o.lightMetadata,body_length:o.bodyLength},t.includeBody&&o.body!==void 0&&(t.state.newBodies[i]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,body:o.body}),t.includeCollections&&o.heavyMetadata!==void 0&&(t.state.newCollections[i]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,collections:o.heavyMetadata});let n=t.includeCollections?Wt(o.lightMetadata,o.heavyMetadata):o.lightMetadata,r=t.state.documentsById.get(n.id),a={metadata:n,body:o.body,item_format:o.itemFormat,item_path:e};Ut(r?.itemFormat,o.itemFormat,t.preferredFormat)&&t.state.documentsById.set(n.id,{candidate:a,itemFormat:o.itemFormat})}async function qi(e,i,t,o){try{let n=await Yi(i,t,o);Gi(i,t,o,n)}catch{ne(o.warnings,`item_list_item_read_failed:${e}/${w.basename(i)}`)}}function Ki(e,i){return e&&e.context_fingerprint===i?e.entries:{}}function Vi(e,i){return e&&e.context_fingerprint===i?e.bodies:{}}function Ji(e,i){return e&&e.context_fingerprint===i?e.collections:{}}function Qi(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function Zi(e,i){let t=[];for(let{folder:o,dirPath:n,files:r}of e)for(let a of r){if(!Bi(a))continue;let s=w.join(n,a),l=w.relative(i.pmRoot,s);t.push(qi(o,s,l,i)),t.length===32&&(await Promise.all(t),t.length=0)}await Promise.all(t)}async function eo(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!oe(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await ie(Ie(e.pmRoot),{version:x,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await ie(Xe(e.pmRoot),{version:x,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});let i=[...e.state.documentsById.values()].map(({candidate:t})=>({relativePath:w.relative(e.pmRoot,t.item_path),metadata:Ee(t.metadata).light,linkedFiles:t.metadata.files??[]}));i.length>=e.minimumIndexedItems?await Ot({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:i}):await we(e.pmRoot)}catch{}}async function to(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await ie(ve(e.pmRoot),{version:x,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function io(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await ie(Ce(e.pmRoot),{version:x,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function Ke(e,i,t={}){let o=await qe(e);return t.required!==!0&&(o===null||o.entry_count<jt)?async()=>{}:mt(e,Ti,30,i,!1,!1,3e3)}async function kn(e,i){let t=await qe(e);if(t===null)return null;let o=await Ge(e);if(o.invalid)return await U(e),null;let n=o.envelope?.context_fingerprint===t.context_fingerprint&&o.envelope.base_source_cursor===t.source_cursor?o.envelope.source_cursor:t.source_cursor,r=o.envelope?.context_fingerprint===t.context_fingerprint&&o.envelope.base_source_cursor===t.source_cursor?o.envelope.directory_signatures:t.directory_signatures;return i&&!oe(r,await be(e,i))?null:{source_cursor:n,entry_count:t.entry_count}}function At(e,i){let t=w.relative(e,i);return t===""||t===".."||t.startsWith(`..${w.sep}`)||w.isAbsolute(t)?null:t}async function U(e){await Promise.all([Ie(e),ve(e),Ce(e),ze(e),Xe(e)].map(async i=>{await E.rm(i,{force:!0}),v.delete(i)})),await we(e)}async function oo(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let i=await E.stat(e.mutation.itemPath),t=Ee(e.mutation.document.metadata),o={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size};return{entry:{...o,metadata:t.light,body_length:e.mutation.document.body.length},body:{...o,body:e.mutation.document.body},collections:{...o,collections:t.heavy}}}function no(e,i,t){return e?.context_fingerprint===i&&e.base_source_cursor===t?structuredClone(e.changes):{}}async function Ve(e){let i=At(e.pmRoot,e.itemPath),t=e.previousItemPath?At(e.pmRoot,e.previousItemPath):void 0;if(i===null||t===null)return await U(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let o=Ht(e.preferredFormat,e.typeToFolder,e.schema,$t()),n=await qe(e.pmRoot);if(n===null||n.context_fingerprint!==o)return[];let r=n.source_cursor,a=await Ge(e.pmRoot);if(a.invalid)return await U(e.pmRoot),["metadata_derived_index_refresh_failed"];let s=no(a.envelope,o,r),l=a.envelope?.context_fingerprint===o&&a.envelope.base_source_cursor===r?a.envelope.source_cursor:r;t!==void 0&&(s[t]={entry:null,body:null,collections:null}),s[i]=await oo({mutation:e});let c=Pt();return await ie(ze(e.pmRoot),{version:x,context_fingerprint:o,base_source_cursor:r,source_cursor:c,directory_signatures:await be(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:s}),await Dt({pmRoot:e.pmRoot,contextFingerprint:o,expectedSourceCursor:l,sourceCursor:c,row:e.document===null?null:{relativePath:i,metadata:Ee(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...t===void 0?[]:[t],...e.document===null?[i]:[]]})||await we(e.pmRoot),[]}catch{return await U(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function ro(e){return[...e.documentsById.values()].sort((i,t)=>i.candidate.metadata.id.localeCompare(t.candidate.metadata.id)).map(i=>i.candidate)}function Lt(e,i,t){return e?.context_fingerprint===i&&e.source_cursor===t}function ao(e,i,t,o,n){return e.every(r=>(!i||o[r]!==void 0)&&(!t||n[r]!==void 0))}function so(e){let i=new Map;for(let[t,o]of Object.entries(e.previousEntries)){let n=Ne(t);if(!n)continue;let r=e.includeCollections?Wt(o.metadata,e.previousCollections[t]?.collections):o.metadata,a=i.get(r.id);Ut(a?.itemFormat,n,e.preferredFormat)&&i.set(r.id,{itemFormat:n,candidate:{metadata:r,body:e.includeBody?e.previousBodies[t]?.body:void 0,item_format:n,item_path:w.join(e.pmRoot,t)}})}return[...i.values()].sort((t,o)=>t.candidate.metadata.id.localeCompare(o.candidate.metadata.id)).map(t=>t.candidate)}function co(e){return e.forceSourceScan||De()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!oe(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||Lt(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||Lt(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&ao(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function xe(e,i,t,o,n,r={}){let a=r.includeBody!==!1,s=r.includeCollections!==!1,l=$t(),c=Ht(i,t,n,l),d=await Ge(e);d.invalid&&await U(e);let u=await Pi(e,c,r.cacheDiagnostics),y=a?await ji(e,c):null,h=s?await $i(e,c):null;Li(u,y,h,d.envelope);let m=Ki(u,c),g=Vi(y,c),_=Ji(h,c),b=[...new Set(Object.values(t))],T=await be(e,b),$=Object.keys(m),N=Math.max(1,Math.floor(r.derivedIndexMinimumItems??jt));if(co({forceSourceScan:r.forceSourceScan===!0,contextFingerprint:c,existingCache:u,existingBodyCache:y,existingCollectionsCache:h,directorySignatures:T,entryKeys:$,minimumIndexedItems:N,includeBody:a,includeCollections:s,previousBodies:g,previousCollections:_}))return so({pmRoot:e,preferredFormat:i,includeBody:a,includeCollections:s,previousEntries:m,previousBodies:g,previousCollections:_});let I=await Promise.all(b.map(W=>Hi(e,W,o))),M=De(),C=Qi(),B={pmRoot:e,preferredFormat:i,warnings:o,schema:n,extensionFieldNames:l,includeBody:a,includeCollections:s,forceSourceRead:r.forceSourceScan===!0,dispatchReadHooks:M,previousEntries:m,previousBodies:g,previousCollections:_,state:C};await Zi(I,B);let k=await be(e,b),S=oe(T,k)?k:{},z=C.misses.metadata||Object.keys(m).length!==Object.keys(C.newEntries).length||!oe(u?.directory_signatures,S)||u===null?Pt():u.source_cursor;return await eo({pmRoot:e,contextFingerprint:c,sourceCursor:z,existingCache:u,previousEntries:m,directorySignatures:S,state:C,minimumIndexedItems:N}),a&&await to({pmRoot:e,contextFingerprint:c,sourceCursor:z,existingBodyCache:y,previousBodies:g,state:C}),s&&await io({pmRoot:e,contextFingerprint:c,sourceCursor:z,existingCollectionsCache:h,previousCollections:_,state:C}),ro(C)}async function Bt(e,i,t,o,n){return(await xe(e,i,t,o,n,{includeBody:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}async function zt(e,i,t,o,n){return(await xe(e,i,t,o,n,{includeBody:!1,includeCollections:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="e23f9ca6-9fa6-566b-9bfb-7cbe6d449a59")}catch{}})();function lo(e,i){let t=e.trim().toLowerCase();if(t.length===0)return;let o=Math.floor(t.length/3);return i.map(n=>({candidate:n,distance:ae(t,n.toLowerCase(),o)??Number.POSITIVE_INFINITY})).filter(({distance:n})=>Number.isFinite(n)).sort((n,r)=>n.distance!==r.distance?n.distance-r.distance:n.candidate.localeCompare(r.candidate))[0]?.candidate}function Xt(e){return["pm",...e].map(i=>/^[A-Za-z0-9_./:@=-]+$/u.test(i)?i:JSON.stringify(i)).join(" ")}function An(e){let i=e.command_path.trim().replaceAll(/\s+/gu," "),t=e.token.trim(),o=t.length===0?"<empty>":t,n=[...new Set(e.allowed.map(y=>y.trim()))].filter(Boolean).sort((y,h)=>y.localeCompare(h));if(i.length===0||o.length===0||n.length===0)throw new TypeError("Unknown-subcommand contracts require a path, token, and allowed set");let r=i.split(" "),a=e.trailing_args??[],s=e.display_name??`pm ${i}`,l=e.token_kind??"subcommand",c=e.retry_command?void 0:lo(o,n),d=Xt([...r,o,...a]),u=e.retry_command??(c?Xt([...r,c,...a]):void 0);return new f(`Unknown ${s} ${l} "${o}". Allowed: ${n.join(", ")}${e.message_suffix??""}`,e.exit_code??p.USAGE,{code:"unknown_subcommand",reason:"unknown_positional_token",value:o,examples:[...u?[u]:[],...e.examples??[],`pm ${i} --help`],nextSteps:u?[`Retry with the suggested command: ${u}`]:["Choose one value from recovery.allowed_values."],recovery:{attempted_command:d,allowed_values:n,suggested_retry:u,fallback_candidates:e.fallback_candidates}})}import uo from"node:fs/promises";import mo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="1d746e4d-ff6c-54ec-a94f-4ec4cb8f77b5")}catch{}})();function fo(e){return[...new Set(e.filter(i=>i.trim().length>0))].sort((i,t)=>i.localeCompare(t))}function po(e,i){return new f(`Missing history stream for ${e}. ${i} requires history streams when settings.history.missing_stream is strict_error.`,p.NOT_FOUND)}async function yo(e,i){return await it(mo.dirname(e)),await(await uo.open(e,"a")).close(),L({path:e,scope:"project",op:`${i}:history:auto_create`})}async function Je(e){return ho({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function ho(e){let i=fo(e.itemIds),t=[],o=[];for(let n of i){let r=R(e.pmRoot,n);if(!await X(r)){if(e.settings.history.missing_stream==="strict_error")throw po(n,e.commandLabel);o.push(...await yo(r,e.commandLabel)),o.push(`history_stream_auto_created:${n}`),t.push(n)}}return{auto_created_ids:t,warnings:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="5db05e2f-4742-526b-b1c8-b97ff302b40e")}catch{}})();function re(e,i=!1){let t=e[0];if(t?.op!=="history_compact_baseline")return 0;let o=t.context?.history_compaction,n=typeof o=="object"&&o!==null&&"version_offset"in o?o.version_offset:void 0;if(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0&&Number.isSafeInteger(n+e.length))return n;if(i)return null;throw new f("This compacted stream has no trustworthy version offset; numeric history addresses are unavailable.",p.USAGE,{code:"history_version_mapping_unavailable",required:"Use a retained timestamp or recover the pre-compaction stream from version control.",nextSteps:["Run pm history <id> --full to inspect the retained timestamps and checkpoint evidence."]})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="ddc5bb8f-83bc-5121-a628-a501e7ed5a73")}catch{}})();function _o(e,i){let t=-1;return e.forEach((o,n)=>{let r=Date.parse(o.ts);if(!Number.isFinite(r))throw new f(`History for this item contains invalid timestamp at entry ${n+1}.`,p.GENERIC_FAILURE);r<=i&&(t=n)}),t}function go(e,i){let t=e[0]?.ts??null,o=e.at(-1)?.ts??null,n={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:t,last_timestamp:o}};return o!==null&&(n.examples=[o],i!==null&&(n.examples.unshift(String(i+1),String(i+e.length)),n.valid_range.first_version=i+1,n.valid_range.last_version=i+e.length)),{guidance:n,lastTimestamp:o}}function wo(e,i){let t={};if(i instanceof Error&&i.message.trim().length>0&&(t.reason=i.message.trim()),typeof i!="object"||i===null)return t;let o=i;if(typeof o.index=="number"&&Number.isInteger(o.index)&&o.index>=0&&(t.patchIndex=o.index),typeof o.operation=="object"&&o.operation!==null){let n=o.operation;Object.assign(t,Object.fromEntries(["op","path","from"].flatMap(r=>{let a=n[r];return typeof a=="string"?[[r,a]]:[]})))}if(t.patchIndex!==void 0){let n=e[t.patchIndex];n&&(t.op??=n.op,t.path??=n.path,t.from??=n.from)}return t}function Yt(e,i,t={}){let o=e.trim(),n=t.errorSubject??"history",r=n==="restore"?"Restore":"History",{guidance:a,lastTimestamp:s}=go(i,re(i,!0));if(!o)throw new f(`Missing ${n} target. Use a timestamp or version number.`,p.USAGE,a);if(/^\d+$/.test(o)){let d=re(i),u=Number(o);if(u>=1&&u<=d)throw new f(`History version ${u} was pruned by compaction.`,p.USAGE,{...a,code:"history_version_pruned"});if(!Number.isSafeInteger(u)||u<1||u>d+i.length)throw new f(`${r} version must be between ${d+1} and ${d+i.length} for this item.`,p.USAGE,a);return{kind:"version",raw:o,historyIndex:u-d-1}}let l=Date.parse(o);if(!Number.isFinite(l))throw new f(`Invalid ${n} target "${e}". Use a positive version number or ISO timestamp.`,p.USAGE,a);let c=_o(i,l);if(c<0||t.allowFutureTimestamp!==!0&&l>Date.parse(s))throw new f(n==="restore"?`No history entries exist at or before timestamp ${o}.`:`No history entry exists at timestamp ${o}.`,p.USAGE,a);return{kind:"timestamp",raw:o,historyIndex:c}}function Qe(e,i,t,o){let n=je(e,i);if(n.ok)return n.document;let r=wo(i,n.error),a=[`history_op=${o}`,r.patchIndex===void 0?null:`patch_index=${r.patchIndex}`,r.op?`op=${r.op}`:null,r.path?`path=${r.path}`:null,r.from?`from=${r.from}`:null].filter(s=>s!==null);throw new f(`Failed to apply history patch at entry ${t} (${a.join(", ")}). ${r.reason??String(n.error)}`,p.GENERIC_FAILURE)}function Gt(e,i){let t=e[0];if(t&&t.op!=="create"&&t.op!=="history_compact_baseline"){let a=je(K,t.patch);if(!a.ok||typeof a.document.metadata.id!="string")throw new f("History starts without a reconstructable item baseline.",p.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}let o=e.slice(0,i+1),n=me([...o]),r=structuredClone(K);for(let a=0;a<=i;a+=1){let s=e[a];if(!s)throw new f(`History target entry ${a+1} does not exist.`,p.USAGE);r=Qe(r,s.patch,a+1,s.op)}if(!n.ok)throw new f(`History cannot be replayed: ${n.errors.join(", ")}.`,p.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:n.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]});return r}function Qn(e,i){if(Object.keys(e.metadata).length>0){if(typeof e.metadata.id!="string"||!Array.isArray(e.metadata.tags))throw new f("History has no complete item baseline for this target.",p.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return e}throw new f(`History target ${i.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,p.USAGE)}import j from"node:fs/promises";import{statSync as bo}from"node:fs";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="be69f1e8-4543-5cf5-abb0-9d38ca1d0cc6")}catch{}})();function Eo(e,i){let t=-1,o=structuredClone(K);for(let[s,l]of e.entries()){if(o=Qe(o,l.patch,s+1,l.op),o.metadata.id!==void 0&&o.metadata.id!==i)throw new f(`History belongs to item ${String(o.metadata.id)}, expected ${i}.`,p.GENERIC_FAILURE,{code:"history_replay_invalid",required:"Recover the correct history stream for this item before attempting restoration."});o.metadata.id===i&&Array.isArray(o.metadata.tags)&&(t=s)}let n=re(e,!0),r=t<0||n===null?null:n+t+1,a=r===null?void 0:String(r);if(t>=0&&a===void 0){let s=e[t].ts;Yt(s,e).historyIndex===t&&(a=s)}return{version:r,target:a}}async function qt(e,i,t){let o=new Set([J(i,t),V(i)]);for(let n of o){let r=R(e,n);if(!bo(r,{throwIfNoEntry:!1})?.isFile())continue;let a=await gt(r,n),s=-1;if(a.forEach((h,m)=>{h.op==="delete"&&(s=m)}),s<0)continue;let l=Gt(a,a.length-1);if(Object.keys(l.metadata).length!==0)continue;let{version:c,target:d}=Eo(a,n),u=d===void 0?["history",n,"--verify"]:["get",n,"--at",d],y=G(u);return new f(`Item ${n} was deleted at ${a[s].ts}; its history is retained.`,p.NOT_FOUND,{code:"item_deleted",required:"Read a retained materialized version, then restore it if the item should exist again.",item_id:n,tombstone:{deleted:!0,deleted_at:a[s].ts,recoverable:d!==void 0,last_materialized_version:c},nextSteps:[y,...d===void 0?["Recover the pre-compaction history from version control."]:[G(["restore",n,d])]],recovery:{suggested_retry:y,suggested_retry_args:u}})}}import{AsyncLocalStorage as Io}from"node:async_hooks";import vo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="53df109f-bd64-5879-96a6-39f70334910e")}catch{}})();var Co=new Io;function Kt(e,i){for(let t of Co.getStore()??[])t.pmRoot===vo.resolve(e)&&t.id===i.metadata.id&&t.validate(i)}import Ze from"node:path";import{isUtf8 as To}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="3ecac03b-7dfe-5ce3-a93d-6b9f948c68fe")}catch{}})();async function So(e){try{return await j.access(e),!0}catch{return!1}}function xo(e,i){e&&(e.includes(i)||e.push(i))}function Vt(e){return e??se(Y())}function Ro(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function Jt(e,i,t="pm-",o,n=F){let r=i.trim(),a=r.startsWith("#")?r.slice(1):r;if(a.length===0)return null;let s=J(i,t),l=V(i),c=[...new Set([a,s,l])].filter(y=>y.length>0),d=Object.entries(n),u=Ro(o);for(let y of c){let h=new Map;for(let[m]of d)for(let g of u){let _=Re(e,m,y,g,n);await So(_)&&h.set(_,h.get(_)??{id:y,type:m,itemPath:_,item_format:g})}if(h.size>1){let m=[...h.keys()].map(g=>Ze.relative(e,g).split(Ze.sep).join("/")).sort();throw new f(`Item ${y} has ambiguous identity across ${m.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,p.CONFLICT,{code:"item_identity_ambiguous",item_id:y,paths:m})}for(let m of h.values())return m}return null}async function Qt(e,i={}){let t=await No(e,i);if(t.error!==null)throw t.error;return{raw:t.raw,document:t.document}}async function No(e,i={}){let t=await j.readFile(e.itemPath);if(!To(t))throw new f("Item contains invalid UTF-8; preserve a binary backup before recovering it.",p.CONFLICT,{code:"item_document_encoding_invalid",item_id:e.id,item_path:e.itemPath,byte_length:t.length,empty:!1});let o=t.toString("utf8");await le({path:e.itemPath,scope:"project"});let n;try{n=ue(o,{format:e.item_format,requireSupportedFormat:!0,schema:i.schema,extensionFieldNames:Vt(i.extensionFieldNames),onWarning:r=>xo(i.warnings,r)})}catch(r){if(r instanceof f&&r.code==="item_format_version_unsupported")throw new f(`Item ${e.id}: ${r.message}`,r.exitCode,{...r.context,item_id:e.id,item_path:e.itemPath});if(r instanceof f&&r.code==="item_document_invalid")return{raw:o,document:null,error:new f(`Cannot read ${e.id} at ${e.itemPath}${t.length===0?" (zero-length file)":""}: ${r.message}`,r.exitCode,{...r.context,item_id:e.id,item_path:e.itemPath,byte_length:t.length,empty:t.length===0,nextSteps:[`Run pm history ${e.id} --full, then pm restore ${e.id} <version> to recover a recorded state.`]})};throw r}return{raw:o,document:n,error:null}}async function ko(e,i,t=F,o,n){await fe(e);let r=await Bt(e,i,t,o,n);return ye(r.length),r.map(a=>a.metadata)}async function Ur(e,i,t=F,o,n){await fe(e);let r=await zt(e,i,t,o,n);return ye(r.length),r.map(a=>a.metadata)}async function Br(e,i,t=F,o,n,r={}){await fe(e);let a=await xe(e,i,t,o,n,{includeBody:!0,forceSourceScan:r.forceSourceScan});return ye(a.length),a.map(s=>({...s.metadata,body:s.body}))}function Zt(e){return{async get(i){let t=await Jt(e.pmRoot,i,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)return null;let{document:o}=await Qt(t,{schema:e.settings.schema});return{item:o.metadata,body:o.body}},list:()=>ko(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function Oo(e,i){let t=new Set(Object.values(i)),o=[];return await Promise.all([...t].map(async n=>{try{let r=await j.readdir(Ze.join(e,n));for(let a of r)for(let s of ce)if(a.toLowerCase().endsWith(s)){o.push(a.slice(0,-s.length));break}}catch{}})),o}async function Do(e,i,t,o){let n=J(i,t),r=await Oo(e,o);if(r.length===0)return[];let a=Math.max(3,Math.floor(n.length/2));return r.map(s=>({id:s,distance:ae(s,n,a)})).filter(s=>s.distance!==null).sort((s,l)=>s.distance-l.distance).slice(0,3).map(s=>s.id)}async function Mo(e,i,t,o){let n=await qt(e,i,t);if(n)return n;let r=await Do(e,i,t,o),a=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return r.length>0&&a.unshift(`Did you mean one of: ${r.join(", ")}?`),new f(`Item ${i} not found`,p.NOT_FOUND,{nextSteps:a})}function Fo(e,i){return e==="claim"||i===!0&&(e==="comment_add"||e==="comment_edit"||e==="comment_delete"||e==="note_add"||e==="learning_add"||e==="release"||e==="update"||e==="update_ownership_bypass"||e==="update_audit")}async function ei(e){let i=e.typeToFolder??rt(e.settings,Y()).type_to_folder,t=await Jt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,i);if(!t)throw await Mo(e.pmRoot,e.id,e.settings.id_prefix,i);let o=await ft(e.pmRoot,t.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms,{waitPolicy:"progress"}),n=o.release;try{let r=[],{raw:a,document:s}=await Qt(t,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:r}),l=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||l,d=_t(e.author),u=Et(e.settings);if(l&&c!==d&&!e.force&&!Fo(e.op,e.bypassAssigneeConflict)){if(u.ownership_enforcement==="strict")throw new f(`Item ${t.id} is assigned to ${l}. Use --force to override.`,p.CONFLICT);u.ownership_enforcement==="warn"&&r.push(`ownership_warning:assignee_conflict:${t.id}:${l}`)}return{typeToFolder:i,located:t,originalRaw:a,document:s,warnings:r,releaseLock:n,lease:o}}catch(r){throw await n(),r}}async function ti(e,i,t,o){return e.fence(async()=>{let n;try{n=await j.readFile(i.itemPath,"utf8")}catch(r){if(!A(r))throw r;n=null}if(n!==t)throw new f(`Item ${i.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,p.CONFLICT,{code:"stale_revision",item_id:i.id,reason:n===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return o()})}function Ao(e,i,t){if(!e.handled||typeof e.result!="object"||e.result===null)return{effectiveTargetItemPath:i,effectiveSerializedAfter:t,skipItemWrite:!1};let o=e.result;return{effectiveTargetItemPath:typeof o.target_item_path=="string"&&o.target_item_path.trim().length>0?o.target_item_path:i,effectiveSerializedAfter:typeof o.contents=="string"?o.contents:t,skipItemWrite:o.skip_write===!0}}async function Lo(e){let i=await Me("item_store_delete",e),t=i.handled&&typeof i.result=="object"&&i.result!==null?i.result:{};return{effectiveItemPath:typeof t.item_path=="string"&&t.item_path.trim().length>0?t.item_path:e.item_path,skipDelete:t.skip_delete===!0,warnings:i.warnings}}async function Po(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await O(e.originalItemPath,e.originalRaw),await j.rm(e.effectiveTargetItemPath,{force:!0});return}await O(e.originalItemPath,e.originalRaw)}}async function ii(e){pt(e.op);let i=await ei({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:e.op,author:e.author,force:e.force,bypassAssigneeConflict:e.bypassAssigneeConflict,extensionFieldNames:e.extensionFieldNames,typeToFolder:e.typeToFolder}),{typeToFolder:t,located:o,originalRaw:n,document:r,warnings:a,releaseLock:s,lease:l}=i;try{Kt(e.pmRoot,r);let c=q(r,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),d=q(structuredClone(r),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),u=await e.mutate(d);if(e.skipNoop===!0&&u.changedFields.length===0)return{item:c.metadata,body:c.body,changedFields:[],warnings:[...a,...u.warnings??[]]};let y=e.resolveHistoryContext?.(),h=Math.max(Ae(c.metadata),Ae(d.metadata));It(at(e.pmRoot),h),h>yt(d.metadata)&&(d.metadata.pm_format_version=h,u.changedFields.push("pm_format_version")),d.metadata.updated_at=Fe();let m=q(d,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),g=await $e({pmRoot:e.pmRoot,settings:e.settings,operation:e.op,author:e.author,before:c,after:m});await Oe({pm_root:e.pmRoot,operation:e.op,before:c,after:m,changed_fields:u.changedFields,sdk:Zt({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t})});let _=await Je({pmRoot:e.pmRoot,settings:e.settings,itemId:o.id,commandLabel:e.op}),b="toon",T=ht(m,{format:b,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),$=Re(e.pmRoot,m.metadata.type,o.id,b,t),N=R(e.pmRoot,o.id),I=await ti(l,o,n,async()=>{let k=await Me("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:o.id,source_item_path:o.itemPath,target_item_path:$,history_path:N,item_format:b,before:c,after:m,contents:T}),{effectiveTargetItemPath:S,effectiveSerializedAfter:z,skipItemWrite:W}=Ao(k,$,T),oi=await Ke(e.pmRoot,e.author),et=[];try{W||await O(S,z),!W&&S!==o.itemPath&&await j.rm(o.itemPath);let ni=Le({nowIso:m.metadata.updated_at,author:e.author,op:e.op,before:c,after:m,message:e.message,context:g.decisions.length===0?y:{...y,workflow_policies:g.decisions}});try{await Pe(N,ni)}catch(ri){throw await Po({skipItemWrite:W,effectiveTargetItemPath:S,originalItemPath:o.itemPath,originalRaw:n}),ri}W||(et=await Ve({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t,schema:e.settings.schema,itemPath:S,previousItemPath:o.itemPath,document:m}))}finally{await oi()}return{derivedIndexWarnings:et,effectiveTargetItemPath:S,overrideWarnings:k.warnings}}),{derivedIndexWarnings:M,effectiveTargetItemPath:C}=I,B=[...await L({path:C,scope:"project",op:e.op,item_id:m.metadata.id,item_type:m.metadata.type,before:c,after:m,changed_fields:u.changedFields}),...await L({path:N,scope:"project",op:`${e.op}:history`,item_id:m.metadata.id,item_type:m.metadata.type,before:c,after:m,changed_fields:u.changedFields})];return ke({id:m.metadata.id,op:e.op,item_type:m.metadata.type,previous_status:c.metadata.status,status:m.metadata.status,previous:de(c.metadata,u.changedFields),current:de(m.metadata,u.changedFields),changed_fields:u.changedFields}),{item:m.metadata,body:m.body,changedFields:u.changedFields,warnings:[...a,...u.warnings??[],...g.warnings,..._.warnings,...I.overrideWarnings,...M,...B]}}finally{await s()}}async function zr(e){return ii(e)}async function Xr(e){return ii(e)}async function Yr(e){let i=await ei({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:"delete",author:e.author,force:e.force}),{located:t,originalRaw:o,document:n,warnings:r,releaseLock:a,lease:s}=i;try{let l=Vt(void 0),c=q(n,{schema:e.settings.schema,extensionFieldNames:l}),d=await $e({pmRoot:e.pmRoot,settings:e.settings,operation:"delete",author:e.author,before:c,after:null,dryRun:e.dryRun});await Oe({pm_root:e.pmRoot,operation:"delete",before:c,after:null,changed_fields:["deleted"],sdk:Zt({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:i.typeToFolder})});let u=await Je({pmRoot:e.pmRoot,settings:e.settings,itemId:t.id,commandLabel:"delete"}),y=Fe(),h=tt,m=Le({nowIso:y,author:e.author,op:"delete",before:c,after:h,message:e.message,context:d.decisions.length===0?void 0:{workflow_policies:d.decisions}}),g=R(e.pmRoot,t.id),_=()=>Lo({op:"delete",pm_root:e.pmRoot,item_id:t.id,item_path:t.itemPath,history_path:g,before:c});if(e.dryRun===!0){let I=await _();return{item:c.metadata,changedFields:["deleted"],targetPath:I.effectiveItemPath,warnings:[...r,...d.warnings,...u.warnings,...I.warnings]}}let b=await ti(s,t,o,async()=>{let{effectiveItemPath:I,skipDelete:M,warnings:C}=await _(),B=await Ke(e.pmRoot,e.author),k=[];try{M||await j.rm(I);try{await Pe(g,m)}catch(S){throw M||await O(I,o),S}M||(k=await Ve({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:i.typeToFolder,schema:e.settings.schema,itemPath:I,document:null}))}finally{await B()}return{derivedIndexWarnings:k,effectiveItemPath:I,overrideWarnings:C}}),{derivedIndexWarnings:T,effectiveItemPath:$}=b,N=[...await L({path:$,scope:"project",op:"delete",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:h,changed_fields:["deleted"]}),...await L({path:g,scope:"project",op:"delete:history",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:h,changed_fields:["deleted"]})];return ke({id:c.metadata.id,op:"delete",item_type:c.metadata.type,previous_status:c.metadata.status,previous:de(c.metadata,Object.keys(c.metadata)),changed_fields:["deleted"]}),{item:c.metadata,changedFields:["deleted"],warnings:[...r,...d.warnings,...u.warnings,...b.overrideWarnings,...T,...N]}}finally{await a()}}export{An as a,Je as b,ho as c,Ct as d,V as e,J as f,Bo as g,re as h,Yt as i,Qe as j,Gt as k,Qn as l,ui as m,fi as n,pi as o,yi as p,hi as q,$e as r,sn as s,yn as t,hn as u,_n as v,jt as w,Oi as x,Ke as y,kn as z,Ve as A,xe as B,Jt as C,Qt as D,No as E,ko as F,Ur as G,Br as H,Zt as I,Mo as J,zr as K,Xr as L,Yr as M};
91
+ //# sourceMappingURL=chunk-FO4U3FIP.js.map