@a-company/paradigm 7.2.0 → 7.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/dist/{accept-orchestration-XW44LF5Y.js → accept-orchestration-NFNY5A4Q.js} +1 -1
  2. package/dist/{aggregate-H7SB2UYT.js → aggregate-647KIGV6.js} +1 -1
  3. package/dist/ambient-5TA5CD7Z.js +2 -0
  4. package/dist/{ambient-TFLZFV5Y.js → ambient-N24SR3BC.js} +1 -1
  5. package/dist/ambient-W3SPKLKC.js +2 -0
  6. package/dist/{arch-loader-YVOS3QRY.js → arch-loader-6TDQOSUE.js} +1 -1
  7. package/dist/arch-loader-NAGXLWUQ.js +2 -0
  8. package/dist/{beacon-WVN264OT.js → beacon-4XQSMTNN.js} +1 -1
  9. package/dist/calibrate-SH6PRZFD.js +2 -0
  10. package/dist/calibration-aggregate-5IVXSBDP.js +2 -0
  11. package/dist/calibration-aggregate-DUEE3LL2.js +4 -0
  12. package/dist/captain-2MEKZKJS.js +2 -0
  13. package/dist/captain-V5XPN4UP.js +2 -0
  14. package/dist/chunk-43H6PB2A.js +142 -0
  15. package/dist/chunk-54C2PETP.js +12 -0
  16. package/dist/{chunk-RGSFU2YW.js → chunk-5LIE2QMS.js} +1 -1
  17. package/dist/{chunk-ACJWUOMA.js → chunk-74NGU6YN.js} +1 -1
  18. package/dist/chunk-ABHILQLA.js +42 -0
  19. package/dist/{chunk-2KK4JQ55.js → chunk-AMZ3ESAK.js} +2 -2
  20. package/dist/chunk-BTMT4K73.js +93 -0
  21. package/dist/chunk-BXKFSYIN.js +2 -0
  22. package/dist/{chunk-RZRFYGND.js → chunk-CHFY3JSF.js} +15 -15
  23. package/dist/chunk-D2T5AV5N.js +504 -0
  24. package/dist/{chunk-ASBK55FU.js → chunk-DLMDHS2X.js} +1 -1
  25. package/dist/{chunk-6VZSOQ7Y.js → chunk-DQ4MMMTP.js} +1 -1
  26. package/dist/chunk-F3OBFUOE.js +2 -0
  27. package/dist/chunk-GADXREYG.js +18 -0
  28. package/dist/{chunk-A5EEY6NO.js → chunk-HGT7RNOL.js} +1 -1
  29. package/dist/chunk-HLPYCWE5.js +6 -0
  30. package/dist/chunk-IGB2CIMK.js +93 -0
  31. package/dist/{chunk-27EK3OQZ.js → chunk-JJ3AUHQU.js} +1 -1
  32. package/dist/chunk-JOHPASZG.js +4 -0
  33. package/dist/chunk-JOWT6J4C.js +25 -0
  34. package/dist/chunk-L4MKNG56.js +42 -0
  35. package/dist/chunk-PRZZL57E.js +7 -0
  36. package/dist/chunk-QBIME67A.js +2 -0
  37. package/dist/{chunk-USYV5QYU.js → chunk-QTMJVEEW.js} +1 -1
  38. package/dist/chunk-RPGSQQTS.js +2 -0
  39. package/dist/chunk-RQHZUPLO.js +4 -0
  40. package/dist/chunk-SGLIPRIC.js +3 -0
  41. package/dist/chunk-SOVBBLFK.js +6 -0
  42. package/dist/chunk-SPU3R5GW.js +25 -0
  43. package/dist/{chunk-NRP2KJ6I.js → chunk-T577TTVG.js} +3 -3
  44. package/dist/{chunk-W3VWORQZ.js → chunk-VHVUJGZ2.js} +2 -2
  45. package/dist/chunk-WUSTIEYA.js +4 -0
  46. package/dist/{commands-4ENQMHFO.js → commands-RSHKXKXN.js} +1 -1
  47. package/dist/{compliance-3M6COUCO.js → compliance-EFNXWHDL.js} +1 -1
  48. package/dist/{constellation-TIKNCZWR.js → constellation-26225R5K.js} +1 -1
  49. package/dist/{diff-Z2YSIRC4.js → diff-G52RYZNF.js} +1 -1
  50. package/dist/dist-6TDAY6TQ-HMSTBL57.js +39 -0
  51. package/dist/dist-N4NYCS3D.js +2 -0
  52. package/dist/dist-O7KGTIYK.js +4 -0
  53. package/dist/{docs-OWJ7EPD7.js → docs-2O7HUSBX.js} +1 -1
  54. package/dist/doctor-KGQXLGOQ.js +2 -0
  55. package/dist/github-GI3HX3N5.js +4 -0
  56. package/dist/graph-slice-2WECDOEN.js +2 -0
  57. package/dist/index.js +6 -6
  58. package/dist/{init-QPMLEQWQ.js → init-JGYCABZZ.js} +1 -1
  59. package/dist/{integrity-FRGF5BFS.js → integrity-YUCXTQX3.js} +1 -1
  60. package/dist/mcp.js +2 -2
  61. package/dist/nomination-engine-3EYXJOZZ.js +2 -0
  62. package/dist/nomination-engine-BUPERVPR.js +2 -0
  63. package/dist/notebook-loader-QM4KUT4R.js +2 -0
  64. package/dist/{orchestrate-C5NM5MFN.js → orchestrate-RIKQB2DV.js} +1 -1
  65. package/dist/orchestration-GFNPCEUU.js +2 -0
  66. package/dist/orchestration-I62QXOWV.js +2 -0
  67. package/dist/platform-server-AAEDDBS3.js +25 -0
  68. package/dist/{probe-G3TKOJYW.js → probe-GD3VDWGT.js} +1 -1
  69. package/dist/reindex-FNL4QRUZ.js +2 -0
  70. package/dist/reindex-N4NTDLJY.js +2 -0
  71. package/dist/{review-WHRNLW2W.js → review-YG4LWV22.js} +1 -1
  72. package/dist/{ripple-B6U7263T.js → ripple-S6VBP5C6.js} +1 -1
  73. package/dist/{sentinel-EFPEX246.js → sentinel-RIEQWALQ.js} +1 -1
  74. package/dist/{sentinel-bridge-UR2MKARY.js → sentinel-bridge-D4LFDFCH.js} +1 -1
  75. package/dist/sentinel.js +1 -1
  76. package/dist/serve-NPRYOGQX.js +9 -0
  77. package/dist/{server-4D77LCST.js → server-K7G3IHR3.js} +1 -1
  78. package/dist/session-tracker-HYN6ZYPH.js +2 -0
  79. package/dist/{session-work-log-T2IE4Y4T.js → session-work-log-KZX4PGUL.js} +1 -1
  80. package/dist/{setup-L5OP24US.js → setup-GPOTHS3N.js} +1 -1
  81. package/dist/{shift-UDKXCIW7.js → shift-ZIJTQ5SW.js} +2 -2
  82. package/dist/{snapshot-MT5L6XE4.js → snapshot-2ARNF3U2.js} +1 -1
  83. package/dist/{spawn-I6XG57S2.js → spawn-PHA2SVQ3.js} +1 -1
  84. package/dist/{status-4QGKLOP6.js → status-NTWWESOR.js} +1 -1
  85. package/dist/{summary-6QNVQZJV.js → summary-4QXYLXAB.js} +1 -1
  86. package/dist/sync-layer-Z266WBWF.js +2 -0
  87. package/dist/task-6F527BNU.js +3 -0
  88. package/dist/task-loader-75NBBLRQ.js +2 -0
  89. package/dist/task-loader-INPLZRG5.js +2 -0
  90. package/dist/task-settlement-3ROAHAND.js +3 -0
  91. package/dist/task-settlement-F7CIKUG3.js +3 -0
  92. package/dist/team-PFJTOCPM.js +2 -0
  93. package/dist/tools-MAH6K5UL.js +142 -0
  94. package/dist/tools-Z354SXGS.js +2 -0
  95. package/dist/{workspace-4D4TQ637.js → workspace-HADUT5XT.js} +1 -1
  96. package/package.json +3 -6
  97. package/platform-ui/dist/assets/{AmbientSection-CwatqcBD.js → AmbientSection-xoxr3DQg.js} +1 -1
  98. package/platform-ui/dist/assets/{DocsSection-BZ2SFJBZ.js → DocsSection-Us2qksna.js} +1 -1
  99. package/platform-ui/dist/assets/{GitSection-MNNYU1tO.js → GitSection-DIHZyadf.js} +1 -1
  100. package/platform-ui/dist/assets/{GraphSection-COYjb4Pt.js → GraphSection-9TO0L1IO.js} +1 -1
  101. package/platform-ui/dist/assets/{LoreSection-B0hUbfsJ.js → LoreSection-DVDit8Aw.js} +1 -1
  102. package/platform-ui/dist/assets/{SentinelSection-BCxW1DCp.js → SentinelSection-a5_VNYcx.js} +1 -1
  103. package/platform-ui/dist/assets/{SymphonySection-BsucZRqy.js → SymphonySection-cRHEoJ9t.js} +1 -1
  104. package/platform-ui/dist/assets/TasksSection-44_gDO3L.css +1 -0
  105. package/platform-ui/dist/assets/TasksSection-h8x3qRIj.js +1 -0
  106. package/platform-ui/dist/assets/{TeamSection-C0QNTudW.js → TeamSection-mFoDyNic.js} +1 -1
  107. package/platform-ui/dist/assets/{UniversitySection-DN1-g9pw.js → UniversitySection-D99YRjmC.js} +1 -1
  108. package/platform-ui/dist/assets/{index-DwUT8pju.js → index-D_wB2S_2.js} +11 -11
  109. package/platform-ui/dist/index.html +1 -1
  110. package/dist/ambient-OW5M5LVN.js +0 -2
  111. package/dist/ambient-VCTUHHIG.js +0 -2
  112. package/dist/arch-loader-G3AAM4E2.js +0 -2
  113. package/dist/calibrate-PHVP7RPH.js +0 -4
  114. package/dist/captain-CAXGHC2V.js +0 -2
  115. package/dist/captain-CWCLFOXV.js +0 -2
  116. package/dist/chunk-33ERV2MW.js +0 -18
  117. package/dist/chunk-3I3TITBA.js +0 -25
  118. package/dist/chunk-3YM5ABNX.js +0 -2
  119. package/dist/chunk-6HYRS3PH.js +0 -142
  120. package/dist/chunk-727PXENG.js +0 -2
  121. package/dist/chunk-D6BSCELB.js +0 -2
  122. package/dist/chunk-FG3M6VVO.js +0 -30
  123. package/dist/chunk-HSY75GRR.js +0 -6
  124. package/dist/chunk-K7KT6FL3.js +0 -25
  125. package/dist/chunk-KAUGQMXU.js +0 -4
  126. package/dist/chunk-QPQBXRXX.js +0 -93
  127. package/dist/chunk-RVXQNS6K.js +0 -30
  128. package/dist/chunk-TMDPDIWA.js +0 -3
  129. package/dist/chunk-UNSI6DVD.js +0 -93
  130. package/dist/chunk-XBK244QR.js +0 -6
  131. package/dist/chunk-XMAV5AG6.js +0 -2
  132. package/dist/chunk-XSKIXXFW.js +0 -504
  133. package/dist/chunk-Y76OIMDO.js +0 -7
  134. package/dist/chunk-ZSWXLFN7.js +0 -12
  135. package/dist/dist-GQ42YS5N-4HIJZVBB.js +0 -39
  136. package/dist/dist-PW5YPGFF.js +0 -2
  137. package/dist/dist-RXYJK7AZ.js +0 -2
  138. package/dist/doctor-CBZYYQQH.js +0 -2
  139. package/dist/github-4X4MYINS.js +0 -4
  140. package/dist/lore-server-FC2GMDLT.js +0 -14
  141. package/dist/nomination-engine-EFXDEPZN.js +0 -2
  142. package/dist/nomination-engine-YRHZZZUN.js +0 -2
  143. package/dist/notebook-loader-TZVIMNDJ.js +0 -2
  144. package/dist/orchestration-EVWQWTOV.js +0 -2
  145. package/dist/orchestration-UP3KFUJT.js +0 -2
  146. package/dist/platform-server-FXF3XFHM.js +0 -25
  147. package/dist/reindex-QZYOD5K4.js +0 -2
  148. package/dist/reindex-W67B2LQP.js +0 -2
  149. package/dist/serve-L52ZUTU6.js +0 -10
  150. package/dist/serve-ZT2Z54NK.js +0 -8
  151. package/dist/session-tracker-BZ7FU4AT.js +0 -2
  152. package/dist/task-KFND4HLF.js +0 -3
  153. package/dist/task-loader-HBZ3KRH2.js +0 -2
  154. package/dist/task-loader-IO4UVFUD.js +0 -2
  155. package/dist/task-settlement-NF7PFSNE.js +0 -3
  156. package/dist/task-settlement-TATNPY6L.js +0 -3
  157. package/dist/team-6WNNLBAO.js +0 -2
  158. package/dist/tools-GDWT74O6.js +0 -2
  159. package/dist/tools-SDWAFQMQ.js +0 -142
  160. package/graph-ui/dist/assets/index-BlgXTl53.css +0 -1
  161. package/graph-ui/dist/assets/index-Bq5nXK8p.js +0 -63
  162. package/graph-ui/dist/index.html +0 -13
  163. package/lore-ui/dist/assets/index-C3EixkjW.css +0 -1
  164. package/lore-ui/dist/assets/index-DKhNxgtW.js +0 -56
  165. package/lore-ui/dist/index.html +0 -13
  166. package/platform-ui/dist/assets/CanvasSection-dFAthehN.js +0 -9
  167. package/platform-ui/dist/assets/CanvasSection-flMXU19z.css +0 -1
@@ -1,93 +0,0 @@
1
- #!/usr/bin/env node
2
- import {a,O,j as j$2,M as M$1,B}from'./chunk-W3VWORQZ.js';import {a as a$1,b as b$3,c as c$1}from'./chunk-M4UMM6DC.js';import {r,i,a as a$2,f}from'./chunk-TMDPDIWA.js';import {j as j$1,b as b$2,a as a$4}from'./chunk-GRZQIKST.js';import {b as b$1,a as a$3}from'./chunk-EK4ZRIFJ.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as S from'fs';import*as T from'path';import*as j from'crypto';import {execSync}from'child_process';import*as C from'js-yaml';import*as Y from'os';import ht from'sql.js';var ve={};c(ve,{contentSearch:()=>gt,detectFileRename:()=>Ae,generateFingerprint:()=>xe,levenshteinDistance:()=>Ie,levenshteinSimilarity:()=>se,searchSiblingFiles:()=>Ce,slidingWindowSearch:()=>V});function xe(e){let t=e.split(`
3
- `).filter(n=>n.trim()!=="");return {firstLine:q(t[0]||""),lastLine:q(t[t.length-1]||""),lineCount:t.length,structuralHash:Le(t)}}function Le(e){let t=e.map(n=>n.trim()).filter(n=>Re.test(n)).map(n=>{let s=n.match(Re);return s?s[1].trim():""}).join("|");return j.createHash("sha256").update(t).digest("hex").slice(0,16)}function q(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function Ie(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;e.length>t.length&&([e,t]=[t,e]);let n=e.length,s=t.length;if(n>5e3||s>5e3)return Math.abs(n-s);let r=new Array(n+1),i=new Array(n+1);for(let a=0;a<=n;a++)r[a]=a;for(let a=1;a<=s;a++){i[0]=a;for(let c=1;c<=n;c++){let o=e[c-1]===t[a-1]?0:1;i[c]=Math.min(r[c]+1,i[c-1]+1,r[c-1]+o);}[r,i]=[i,r];}return r[n]}function se(e,t){if(e.length===0&&t.length===0)return 1;let n=Math.max(e.length,t.length);return 1-Ie(e,t)/n}function V(e,t,n,s=3){let{lineCount:r}=t,i=Math.max(1,Math.floor(r*.8)),a=Math.ceil(r*1.2),c=[],o=ne(n);for(let l of [r,i,a])if(!(l>e.length))for(let d=0;d<=e.length-l;d++){let p=e.slice(d,d+l),y=ft(p,t,o);if(y>=.5){let m=p.join(`
4
- `);c.push({windowStart:d+1,windowEnd:d+l,similarity:se(ne(m),o),score:y});}}let u=new Map;for(let l of c){let d=u.get(l.windowStart);(!d||l.score>d.score)&&u.set(l.windowStart,l);}return Array.from(u.values()).sort((l,d)=>d.score-l.score).slice(0,s)}function ft(e,t,n){let s=e.filter(p=>p.trim()!=="");if(s.length===0)return 0;let r=0,i=q(s[0]),a=q(s[s.length-1]),c=0;i===t.firstLine&&(c+=.5),a===t.lastLine&&(c+=.5),r+=c*lt,Le(s)===t.structuralHash&&(r+=ut);let u=s.join(`
5
- `),l=se(ne(u),n);l>=.8&&(r+=(l-.8)/.2*dt);let d=s.length/t.lineCount;if(d>=.8&&d<=1.2){let p=1-Math.abs(1-d)/.2;r+=p*pt;}return r}function ne(e){return e.split(`
6
- `).map(t=>t.trim()).filter(t=>t!=="").join(`
7
- `)}function Ae(e,t){try{let n=execSync(`git log --follow --diff-filter=R --name-status --format="" -- "${t}"`,{cwd:e,encoding:"utf8",timeout:5e3}).trim();if(!n)return null;let s=n.split(`
8
- `);for(let r of s){let i=r.split(" ");if(i.length>=3&&i[0].startsWith("R"))return i[2]}return null}catch{return null}}function Ce(e,t,n,s,r=10){let i=T.isAbsolute(t)?t:T.join(e,t);if(!S.existsSync(i))return [];let a=[];try{let c=S.readdirSync(i).filter(o=>!o.startsWith(".")&&S.statSync(T.join(i,o)).isFile()).slice(0,r);for(let o of c)try{let l=S.readFileSync(T.join(i,o),"utf8").split(`
9
- `),d=V(l,n,s,1);if(d.length>0&&d[0].score>=.7){let p=T.relative(e,T.join(i,o));a.push({file:p,score:d[0].score,start:d[0].windowStart,end:d[0].windowEnd});}}catch{}}catch{return []}return a.sort((c,o)=>o.score-c.score)}function gt(e,t,n,s=true){let r=xe(n),i=T.isAbsolute(t)?t:T.join(e,t);if(S.existsSync(i)){let l=S.readFileSync(i,"utf8").split(`
10
- `),d=V(l,r,n);if(d.length>0){let p=d[0];return {found:p.score>=.7,score:p.score,suggestedStart:p.windowStart,suggestedEnd:p.windowEnd,similarity:p.similarity}}}let a=Ae(e,t);if(a){let u=T.join(e,a);if(S.existsSync(u)){let d=S.readFileSync(u,"utf8").split(`
11
- `),p=V(d,r,n);if(p.length>0&&p[0].score>=.7)return {found:true,score:p[0].score,suggestedStart:p[0].windowStart,suggestedEnd:p[0].windowEnd,suggestedPath:a,similarity:p[0].similarity}}}let c=T.dirname(t),o=Ce(e,c,r,n);if(o.length>0&&o[0].score>=.7){let u=o[0];return {found:true,score:u.score,suggestedStart:u.start,suggestedEnd:u.end,suggestedPath:u.file!==t?u.file:void 0,similarity:u.score}}return {found:false,score:0}}var Re,lt,ut,dt,pt,Ne=b(()=>{Re=/^\s*(function |class |if |else |for |while |switch |case |return |export |import |const |let |var |async |await |try |catch |throw |struct |enum |protocol |guard |def |fn )/;lt=.4,ut=.3,dt=.2,pt=.1;});var Ye="0.1.0",qe="1.0.0";function ee(e,t){let n={$meta:Ve(t.projectName,e),components:{},features:{},flows:{},state:{},gates:{},signals:{},aspects:{},screens:{},symbolMap:{}};for(let r of e.symbols)Ke(r,n,t);if(t.screenDefinitions)for(let[r,i]of Object.entries(t.screenDefinitions))n.screens[r]||(n.screens[r]={id:r,name:M(r),route:i.route,path:"",components:i.components,features:i.features});let s={};for(let r of Object.values(n.components))r.componentType&&(s[r.componentType]=(s[r.componentType]||0)+1);for(let r of Object.values(n.features))r.componentType&&(s[r.componentType]=(s[r.componentType]||0)+1);return Object.keys(s).length>0&&(n.$meta.componentTypes=s),rt(n),n}function Ve(e,t){return {version:qe,project:e,generatedAt:new Date().toISOString(),paradigmVersion:Ye,sources:{purposeFiles:t.purposeFiles.length,portalFiles:t.portalFiles.length,premiseFiles:t.symbols.filter(n=>n.source==="premise").length>0?1:0}}}function Ke(e,t,n){let{type:s}=e;switch(s){case "component":Je(e,t,n);break;case "feature":Qe(e,t,n);break;case "flow":Ze(e,t);break;case "state":et(e,t);break;case "gate":tt(e,t);break;case "signal":nt(e,t);break;case "aspect":st(e,t);break;}}function Je(e,t,n){let s=W(e.symbol),r=Se(s,e.data,n.visualTagMappings),i={id:s,name:M(s),symbol:e.symbol,category:"components",path:e.filePath,description:e.description,visualTags:r,related:e.references,componentType:e.componentType,parent:e.parentSymbol};t.components[s]=i,t.symbolMap[e.symbol]={category:"components",id:s};}function Qe(e,t,n){let s=W(e.symbol),r=Se(s,e.data,n.visualTagMappings),i={id:s,name:M(s),symbol:e.symbol,category:"features",path:e.filePath,description:e.description,visualTags:r,related:e.references,componentType:e.componentType,parent:e.parentSymbol};t.features[s]=i,t.symbolMap[e.symbol]={category:"features",id:s};}function Ze(e,t){let n=W(e.symbol),s=e.data,r=[];if(s?.steps)for(let a=0;a<s.steps.length;a++){let c=s.steps[a];r.push({id:`${n}-step-${a}`,name:c.action||`Step ${a+1}`,target:c.component,description:c.description,order:a});}let i={id:n,name:M(n),symbol:e.symbol,path:e.filePath,description:e.description,steps:r};t.flows[n]=i,t.symbolMap[e.symbol]={category:"flows",id:n};}function et(e,t){let n=W(e.symbol),s={id:n,name:M(n),symbol:e.symbol,path:e.filePath,description:e.description,consumers:e.referencedBy};t.state[n]=s,t.symbolMap[e.symbol]={category:"state",id:n};}function tt(e,t){let n=W(e.symbol),s={id:n,name:M(n),symbol:e.symbol,category:"gates",path:e.filePath,description:e.description,related:e.references};t.gates[n]=s,t.symbolMap[e.symbol]={category:"gates",id:n};}function nt(e,t){let n=W(e.symbol),s={id:n,name:M(n),symbol:e.symbol,category:"signals",path:e.filePath,description:e.description,related:e.references};t.signals[n]=s,t.symbolMap[e.symbol]={category:"signals",id:n};}function st(e,t){let n=W(e.symbol),s={id:n,name:M(n),symbol:e.symbol,category:"aspects",path:e.filePath,description:e.description,related:e.references};t.aspects[n]=s,t.symbolMap[e.symbol]={category:"aspects",id:n};}function rt(e){for(let t of Object.values(e.screens))if(t.components)for(let n of t.components){let s=e.components[n];s&&(s.screens=s.screens||[],s.screens.includes(t.id)||s.screens.push(t.id));}}function W(e){return e.slice(1)}function M(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}function Se(e,t,n){let s=[];if(n?.[e])return n[e];let r=[[/button/i,"button"],[/btn/i,"button"],[/form/i,"form"],[/input/i,"input"],[/field/i,"input"],[/select/i,"input"],[/card/i,"card"],[/list/i,"list"],[/table/i,"list"],[/modal/i,"modal"],[/dialog/i,"modal"],[/drawer/i,"modal"],[/nav/i,"nav"],[/menu/i,"menu"],[/dropdown/i,"menu"],[/header/i,"header"],[/footer/i,"footer"],[/sidebar/i,"sidebar"],[/hero/i,"hero"],[/grid/i,"grid"],[/chart/i,"chart"],[/graph/i,"chart"],[/icon/i,"icon"],[/image/i,"image"],[/avatar/i,"avatar"],[/badge/i,"badge"],[/tag/i,"badge"],[/tab/i,"tab"],[/accordion/i,"accordion"],[/toast/i,"toast"],[/notification/i,"toast"],[/alert/i,"toast"],[/spinner/i,"spinner"],[/loader/i,"spinner"],[/loading/i,"spinner"],[/skeleton/i,"skeleton"]];for(let[i,a]of r)i.test(e)&&s.push(a);return s}function te(e){return JSON.stringify(e,null,2)}var ot=300*1e3,$=null;function be(){$=null;}function N(e,t){return S.existsSync(T.join(e,t))}function P(e,t){return S.existsSync(T.join(e,t))}function it(e,t,n){let s=e;try{if(!S.existsSync(s))return !1;let r=S.readdirSync(s,{withFileTypes:!0});for(let i of r){if(i.isFile()&&i.name.endsWith(t))return !0;if(i.isDirectory())try{if(S.readdirSync(T.join(s,i.name)).some(c=>c.endsWith(t)))return !0}catch{}}}catch{}return false}var at={wisdom:e=>N(e,".paradigm/wisdom"),history:e=>N(e,".paradigm/history"),lore:e=>N(e,".paradigm/lore"),habits:e=>P(e,".paradigm/habits.yaml"),sentinel:e=>{try{let t=T.join(e,".paradigm","config.yaml");return S.existsSync(t)?S.readFileSync(t,"utf-8").includes("sentinel"):!1}catch{return false}},flows:e=>P(e,".paradigm/flow-index.json")||P(e,".paradigm/flows.yaml"),fixtures:e=>P(e,".paradigm/fixtures.yaml"),orchestration:e=>P(e,".paradigm/agents.yaml"),tasks:e=>N(e,".paradigm/tasks"),assessment:e=>N(e,".paradigm/lore"),personas:e=>it(e,".persona"),protocols:e=>N(e,".paradigm/protocols"),symphony:()=>{let e=T.join(Y.homedir(),".paradigm","score");return S.existsSync(e)},university:e=>N(e,".paradigm/university"),agents:e=>{let t=T.join(Y.homedir(),".paradigm","agents");return N(e,".paradigm/agents")||S.existsSync(t)},"aspect-graph":e=>P(e,".paradigm/aspect-graph.db"),pan:e=>P(e,".pan")||P(e,"nevr.yaml"),notebooks:e=>{let t=T.join(Y.homedir(),".paradigm","notebooks");return N(e,".paradigm/notebooks")||S.existsSync(t)}},we=class{modules=new Map;activatedAdvanced=new Set;rootDir;constructor(t){this.rootDir=t;}register(t){this.modules.set(t.key,t);}registerAll(t){for(let n of t)this.register(n);}detectActiveFeatures(){if($&&Date.now()-$.timestamp<ot)return $.features;let t=new Set;for(let[n,s]of this.modules){if(s.tier==="core"){t.add(n);continue}if(s.tier==="advanced"){this.activatedAdvanced.has(n)&&t.add(n);continue}let r=s.detect||at[n];if(r)try{r(this.rootDir)&&t.add(n);}catch{}else t.add(n);}return $={features:t,timestamp:Date.now()},t}getActiveTools(){let t=this.detectActiveFeatures(),n=[];for(let[s,r]of this.modules)t.has(s)&&n.push(...r.getToolsList());return n}activateAdvanced(t){let n=this.modules.get(t);return !n||n.tier!=="advanced"?null:(this.activatedAdvanced.add(t),n.getToolsList())}getAvailableAdvanced(){let t=[];for(let[n,s]of this.modules)s.tier==="advanced"&&!this.activatedAdvanced.has(n)&&t.push({key:n,toolCount:s.getToolsList().length});return t}async dispatch(t,n,s,r){let i=this.detectActiveFeatures();for(let[a,c]of this.modules)if(i.has(a))try{let o=await c.handleTool(t,n,s,r);if(o.handled)return o}catch(o){return {handled:true,text:JSON.stringify({error:`Tool handler error in module "${a}"`,message:o.message},null,2)}}return null}get size(){return this.modules.size}getRegistryInfo(){let t=this.detectActiveFeatures(),n={core:0,feature:0,advanced:0};for(let s of this.modules.values())n[s.tier]++;return {total:this.modules.size,byTier:n,activeFeatures:[...t],availableAdvanced:[...this.modules.entries()].filter(([s,r])=>r.tier==="advanced"&&!this.activatedAdvanced.has(s)).map(([s])=>s)}}};var re=null;async function mt(){return re||(re=await ht()),re}var yt=[`CREATE TABLE IF NOT EXISTS aspects (
12
- id TEXT PRIMARY KEY,
13
- description TEXT NOT NULL,
14
- category TEXT DEFAULT 'rule',
15
- severity TEXT DEFAULT 'medium',
16
- value TEXT,
17
- enforcement TEXT,
18
- defined_in TEXT NOT NULL,
19
- tags TEXT,
20
- created_at TEXT NOT NULL,
21
- updated_at TEXT NOT NULL
22
- )`,`CREATE TABLE IF NOT EXISTS anchors (
23
- id INTEGER PRIMARY KEY AUTOINCREMENT,
24
- aspect_id TEXT NOT NULL REFERENCES aspects(id) ON DELETE CASCADE,
25
- file_path TEXT NOT NULL,
26
- start_line INTEGER NOT NULL,
27
- end_line INTEGER NOT NULL,
28
- content_hash TEXT,
29
- normalized_hash TEXT,
30
- materialized_at_commit TEXT,
31
- last_verified TEXT,
32
- drifted INTEGER DEFAULT 0
33
- )`,"CREATE INDEX IF NOT EXISTS idx_anchors_file ON anchors(file_path)","CREATE INDEX IF NOT EXISTS idx_anchors_aspect ON anchors(aspect_id)",`CREATE TABLE IF NOT EXISTS edges (
34
- id INTEGER PRIMARY KEY AUTOINCREMENT,
35
- source TEXT NOT NULL,
36
- target TEXT NOT NULL,
37
- relation TEXT NOT NULL,
38
- weight REAL DEFAULT 1.0,
39
- origin TEXT DEFAULT 'explicit',
40
- created_at TEXT NOT NULL
41
- )`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)",`CREATE TABLE IF NOT EXISTS lore_links (
42
- aspect_id TEXT NOT NULL,
43
- lore_id TEXT NOT NULL,
44
- PRIMARY KEY (aspect_id, lore_id)
45
- )`,`CREATE TABLE IF NOT EXISTS search_log (
46
- id INTEGER PRIMARY KEY AUTOINCREMENT,
47
- query TEXT NOT NULL,
48
- results_returned TEXT NOT NULL,
49
- selected_result TEXT,
50
- timestamp TEXT NOT NULL
51
- )`,"CREATE INDEX IF NOT EXISTS idx_search_query ON search_log(query)",`CREATE TABLE IF NOT EXISTS search_weights (
52
- query_normalized TEXT NOT NULL,
53
- aspect_id TEXT NOT NULL,
54
- weight REAL DEFAULT 1.0,
55
- hit_count INTEGER DEFAULT 1,
56
- last_hit TEXT NOT NULL,
57
- PRIMARY KEY (query_normalized, aspect_id)
58
- )`,`CREATE TABLE IF NOT EXISTS heatmap (
59
- aspect_id TEXT NOT NULL,
60
- access_type TEXT NOT NULL,
61
- count INTEGER DEFAULT 0,
62
- last_accessed TEXT NOT NULL,
63
- PRIMARY KEY (aspect_id, access_type)
64
- )`],Et=["ALTER TABLE anchors ADD COLUMN original_content TEXT",`CREATE TABLE IF NOT EXISTS anchor_history (
65
- id INTEGER PRIMARY KEY AUTOINCREMENT,
66
- anchor_id INTEGER NOT NULL,
67
- action TEXT NOT NULL,
68
- old_start INTEGER,
69
- old_end INTEGER,
70
- new_start INTEGER,
71
- new_end INTEGER,
72
- old_path TEXT,
73
- new_path TEXT,
74
- confidence REAL,
75
- commit_hash TEXT,
76
- healed_at TEXT NOT NULL
77
- )`],Tt="CREATE VIRTUAL TABLE IF NOT EXISTS aspects_fts USING fts5(id, description, enforcement, tags)";function A(e,t,n){let s=e.prepare(t);n&&n.length>0&&s.bind(n);let r=[];for(;s.step();)r.push(s.getAsObject());return s.free(),r}function St(e,t,n){let s=e.prepare(t);n&&n.length>0&&s.bind(n);let r=null;return s.step()&&(r=s.getAsObject()),s.free(),r}async function Fe(e){let t=await mt(),n=T.join(e,".paradigm"),s=T.join(n,"aspect-graph.db"),r;if(S.existsSync(s)){let i=S.readFileSync(s);r=new t.Database(i);}else S.existsSync(n)||S.mkdirSync(n,{recursive:true}),r=new t.Database;for(let i of yt)r.run(i);try{r.run(Tt);}catch{}for(let i of Et)try{r.run(i);}catch{}return r}function ke(e,t){if(t){let n=T.join(t,".paradigm");S.existsSync(n)||S.mkdirSync(n,{recursive:true});let s=T.join(n,"aspect-graph.db"),r=e.export();S.writeFileSync(s,Buffer.from(r));}e.close();}function Me(e,t,n){let s=t.filter(a=>a.type==="aspect"),r=new Date().toISOString(),i=null;try{i=execSync("git rev-parse HEAD",{cwd:n,encoding:"utf8"}).trim();}catch{}e.run("DELETE FROM anchors"),e.run("DELETE FROM edges"),e.run("DELETE FROM aspects");try{e.run("DELETE FROM aspects_fts");}catch{}for(let a of s){let c=a.data??{},o=_t(c,a),u=xt(c,a),l=c.value!=null?String(c.value):null,d=a.enforcement??(c.enforcement!=null?String(c.enforcement):null),p=a.tags?JSON.stringify(a.tags):null;if(e.run(`INSERT INTO aspects (id, description, category, severity, value, enforcement, defined_in, tags, created_at, updated_at)
78
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a.symbol,a.description??"",o,u,l,d,a.filePath,p,a.created??r,a.modified??r]),a.anchors)for(let m of a.anchors){let{startLine:R,endLine:v}=Pe(m),L=Rt();e.run(`INSERT INTO anchors (aspect_id, file_path, start_line, end_line, content_hash, normalized_hash, materialized_at_commit, last_verified, original_content)
79
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a.symbol,m.path,R,v,L.exact,L.normalized,i,r,L.normalizedContent]);}let y=c.edges;if(Array.isArray(y))for(let m of y)e.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
80
- VALUES (?, ?, ?, ?, ?, ?)`,[m.source??a.symbol,m.target??"",m.relation??"related-to",m.weight??1,m.origin??"explicit",r]);if(a.appliesTo)for(let m of a.appliesTo)e.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
81
- VALUES (?, ?, ?, ?, ?, ?)`,[a.symbol,m,"related-to",.5,"inferred",r]);try{e.run(`INSERT INTO aspects_fts (id, description, enforcement, tags)
82
- VALUES (?, ?, ?, ?)`,[a.symbol,a.description??"",d??"",p??""]);}catch{}}}function cn(e,t){return St(e,"SELECT * FROM aspects WHERE id = ?",[t])}function ln(e,t){return A(e,"SELECT * FROM anchors WHERE aspect_id = ?",[t])}function un(e,t){return A(e,"SELECT * FROM edges WHERE source = ?",[t])}function dn(e,t){return A(e,"SELECT * FROM edges WHERE target = ?",[t])}function pn(e,t){return A(e,"SELECT * FROM edges WHERE source = ? OR target = ?",[t,t])}function fn(e,t,n){let s=new Date().toISOString();e.run(`INSERT INTO heatmap (aspect_id, access_type, count, last_accessed)
83
- VALUES (?, ?, 1, ?)
84
- ON CONFLICT(aspect_id, access_type)
85
- DO UPDATE SET count = count + 1, last_accessed = ?`,[t,n,s,s]);}function gn(e,t=20,n){return n?A(e,"SELECT * FROM heatmap WHERE access_type = ? ORDER BY count DESC LIMIT ?",[n,t]):A(e,"SELECT * FROM heatmap ORDER BY count DESC LIMIT ?",[t])}function hn(e,t,n,s=true,r$1=.7,i=.85){let a=n?A(e,"SELECT * FROM anchors WHERE aspect_id = ?",[n]):A(e,"SELECT * FROM anchors"),c=[];for(let o of a){let l=A(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id])[0]?.defined_in,d$1=l?T.dirname(T.isAbsolute(l)?l:T.resolve(t,l)):t,p=r(o.file_path,d$1,t),y=p.resolvedPath;if(!p.exists){c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"missing",resolvedBy:"none",exists:false,drifted:true});continue}try{let R=S.readFileSync(y,"utf8").split(`
86
- `),v=Math.max(0,o.start_line-1),L=Math.min(R.length,o.end_line),D=R.slice(v,L).join(`
87
- `),U=j.createHash("sha256").update(D).digest("hex");if(o.content_hash!=null&&U===o.content_hash){c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1}),o.drifted===1&&e.run("UPDATE anchors SET drifted = 0 WHERE id = ?",[o.id]);continue}let X=j.createHash("sha256").update(ie(D)).digest("hex");if(o.normalized_hash!=null&&X===o.normalized_hash){e.run("UPDATE anchors SET content_hash = ?, drifted = 0 WHERE id = ?",[U,o.id]),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"cosmetic",resolvedBy:"normalized-hash",exists:!0,drifted:!1});continue}if(o.content_hash==null&&o.normalized_hash==null){e.run("UPDATE anchors SET content_hash = ?, normalized_hash = ?, drifted = 0 WHERE id = ?",[U,X,o.id]),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1});continue}let H=!1;if(o.materialized_at_commit){let h=bt(t,o.file_path,o.materialized_at_commit,o.start_line,o.end_line);if(h){let g=Math.max(0,h.currentStart-1),f=Math.min(R.length,h.currentEnd),E=R.slice(g,f).join(`
88
- `),F=j.createHash("sha256").update(E).digest("hex");if(o.content_hash!=null&&F===o.content_hash){let k=s;if(k){e.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[h.currentStart,h.currentEnd,o.id]);let z=A(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id]);z.length>0&&oe(t,z[0].defined_in,o.file_path,o.start_line,o.end_line,h.currentStart,h.currentEnd);}c.push({aspectId:o.aspect_id,path:o.file_path,startLine:k?h.currentStart:o.start_line,endLine:k?h.currentEnd:o.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:h.currentStart,suggestedEnd:h.currentEnd,autoHealed:k}),H=!0;}else {let k=j.createHash("sha256").update(ie(E)).digest("hex");if(o.normalized_hash!=null&&k===o.normalized_hash){if(s){let z=j.createHash("sha256").update(E).digest("hex");e.run("UPDATE anchors SET start_line = ?, end_line = ?, content_hash = ?, drifted = 0 WHERE id = ?",[h.currentStart,h.currentEnd,z,o.id]);let B=A(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id]);B.length>0&&oe(t,B[0].defined_in,o.file_path,o.start_line,o.end_line,h.currentStart,h.currentEnd);}c.push({aspectId:o.aspect_id,path:o.file_path,startLine:s?h.currentStart:o.start_line,endLine:s?h.currentEnd:o.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:h.currentStart,suggestedEnd:h.currentEnd,autoHealed:s}),H=!0;}}}}if(H)continue;if(o.original_content){let{contentSearch:h}=(Ne(),d(ve)),g=h(t,o.file_path,o.original_content,s);if(g.found&&g.score>=r$1){if(s&&g.score>=i&&!g.suggestedPath&&g.suggestedStart&&g.suggestedEnd){e.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[g.suggestedStart,g.suggestedEnd,o.id]);try{e.run(`INSERT INTO anchor_history (anchor_id, action, old_start, old_end, new_start, new_end, confidence, healed_at)
89
- VALUES (?, 'relocated', ?, ?, ?, ?, ?, ?)`,[o.id,o.start_line,o.end_line,g.suggestedStart,g.suggestedEnd,g.score,new Date().toISOString()]);}catch{}let E=A(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id]);E.length>0&&oe(t,E[0].defined_in,o.file_path,o.start_line,o.end_line,g.suggestedStart,g.suggestedEnd),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:g.suggestedStart,endLine:g.suggestedEnd,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:g.similarity,suggestedStart:g.suggestedStart,suggestedEnd:g.suggestedEnd,autoHealed:!0,drifted:!1});continue}c.push({aspectId:o.aspect_id,path:g.suggestedPath||o.file_path,startLine:o.start_line,endLine:o.end_line,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:g.similarity,suggestedStart:g.suggestedStart,suggestedEnd:g.suggestedEnd,autoHealed:!1,drifted:!0});continue}}e.run("UPDATE anchors SET drifted = 1 WHERE id = ?",[o.id]),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"modified",resolvedBy:"none",exists:!0,currentContent:D,drifted:!0});}catch{c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"modified",resolvedBy:"none",exists:true,drifted:true});}}return c}function Pe(e){let{lines:t}=e;return typeof t=="number"?{startLine:t,endLine:t}:Array.isArray(t)?t.length===2?{startLine:t[0],endLine:t[1]}:{startLine:Math.min(...t),endLine:Math.max(...t)}:{startLine:1,endLine:1}}function wt(e){let t=[],n=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm,s;for(;(s=n.exec(e))!==null;)t.push({oldStart:parseInt(s[1],10),oldCount:s[2]!==void 0?parseInt(s[2],10):1,newStart:parseInt(s[3],10),newCount:s[4]!==void 0?parseInt(s[4],10):1});return t}function bt(e,t,n,s,r){let i;try{i=execSync(`git diff ${n}..HEAD --unified=0 -- "${t}"`,{cwd:e,encoding:"utf8",timeout:5e3});}catch{return null}if(!i.trim())return {originalStart:s,originalEnd:r,currentStart:s,currentEnd:r};let a=wt(i),c=0;for(let o of a){if(o.oldStart+o.oldCount<=s){c+=o.newCount-o.oldCount;continue}if(o.oldStart<r)return null;break}return c===0?null:{originalStart:s,originalEnd:r,currentStart:s+c,currentEnd:r+c}}function oe(e,t,n,s,r,i,a){let c=T.isAbsolute(t)?t:T.join(e,t);if(!S.existsSync(c))return false;try{let o=S.readFileSync(c,"utf8"),u=s===r?`${n}:${s}`:`${n}:${s}-${r}`,l=i===a?`${n}:${i}`:`${n}:${i}-${a}`;if(!o.includes(u))return !1;let d=o.replace(u,l);return S.writeFileSync(c,d,"utf8"),!0}catch{return false}}function ie(e){return e.split(`
90
- `).map(t=>t.trimEnd()).filter(t=>t.trim()!=="").map(t=>t.replace(/\s+/g," ")).join(`
91
- `)}function Rt(e,t,n){return {exact:null,normalized:null,normalizedContent:null};}function _t(e,t){if(typeof e.category=="string")return e.category;let n=(t.description??"").toLowerCase();return /\b(must|require|always)\b/.test(n)?"rule":/\b(decided|chose)\b/.test(n)?"decision":/\b(limit|cannot)\b/.test(n)?"constraint":/\b(set to|configured|value)\b/.test(n)?"configuration":"rule"}function xt(e,t){if(typeof e.severity=="string")return e.severity;let n=t.tags??[];return n.includes("critical")?"critical":n.includes("security")||n.includes("compliance")?"high":"medium"}j$1();var Lt=/L-\d{4}-\d{2}-\d{2}-\d{3}/g;async function je(e,t){e.run("DELETE FROM lore_links");let n=await a$4(t);if(n.length===0)return 0;let s=It(n),r=new Map;for(let u of n)r.set(u.id,u);let i=new Set,a=e.exec("SELECT id, enforcement FROM aspects");if(a.length>0){let{columns:u,values:l}=a[0],d=u.indexOf("id"),p=u.indexOf("enforcement");for(let y of l){let m=String(y[d]),R=y[p];if(R&&typeof R=="string"){let v=R.match(Lt);if(v)for(let L of v)r.has(L)&&i.add(`${m}\0${L}`);}}}let c=e.exec("SELECT source, target FROM edges");if(c.length>0&&a.length>0){let u=At(e,c);for(let[l,d]of u)for(let p of d){let y=s.get(p);if(y)for(let m of y)i.add(`${l}\0${m}`);}}if(i.size===0)return 0;let o=e.prepare("INSERT OR IGNORE INTO lore_links (aspect_id, lore_id) VALUES (?, ?)");try{for(let u of i){let[l,d]=u.split("\0");o.bind([l,d]),o.step(),o.reset();}}finally{o.free();}return i.size}async function En(e,t,n){let s=e.exec("SELECT lore_id FROM lore_links WHERE aspect_id = ?",[n]);if(s.length===0||s[0].values.length===0)return [];let r=s[0].values.map(i=>String(i[0]));return Ct(t,r)}async function De(e,t){let n=await a$4(t);if(n.length===0)return 0;let s=e.exec("SELECT id FROM aspects"),r=new Set;if(s.length>0)for(let o of s[0].values)r.add(String(o[0]));if(r.size<2)return 0;let i=new Date().toISOString(),a=0,c=e.prepare(`INSERT OR IGNORE INTO edges (source, target, relation, weight, origin, created_at)
92
- VALUES (?, ?, 'related-to', 0.3, 'learned', ?)`);try{for(let o of n){if(!o.symbols_touched||o.symbols_touched.length<2)continue;let u=[];for(let l of o.symbols_touched){let d=l.startsWith("~")?l.slice(1):l;r.has(d)&&u.push(d);}for(let l=0;l<u.length;l++)for(let d=l+1;d<u.length;d++){let[p,y]=u[l]<u[d]?[u[l],u[d]]:[u[d],u[l]];c.bind([p,y,i]),c.step(),c.reset(),a++;}}}finally{c.free();}return a}function It(e){let t=new Map;for(let n of e)if(n.symbols_touched)for(let s of n.symbols_touched){let r=t.get(s);r||(r=new Set,t.set(s,r)),r.add(n.id);}return t}function At(e,t){let n=e.exec("SELECT id FROM aspects"),s=new Set;if(n.length>0)for(let u of n[0].values)s.add(String(u[0]));let r=new Map;if(t.length===0)return r;let{columns:i,values:a}=t[0],c=i.indexOf("source"),o=i.indexOf("target");for(let u of a){let l=String(u[c]),d=String(u[o]);if(s.has(l)){let p=r.get(l);p||(p=new Set,r.set(l,p)),p.add(d),p.add(`~${l}`);}if(s.has(d)){let p=r.get(d);p||(p=new Set,r.set(d,p)),p.add(l),p.add(`~${d}`);}}return r}async function Ct(e,t){let n=new Set,s=[];for(let r of t){if(n.has(r))continue;n.add(r);let i=await b$2(e,r);i&&s.push(vt(i));}return s}function vt(e){return {id:e.id,title:e.title,summary:e.summary,timestamp:e.timestamp,symbolsTouched:e.symbols_touched}}var Nt="PARADIGM_STRICT";function K(){let e=process.env[Nt];if(e===void 0||e==="")return false;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}var Ue=new Set(["duplicate-key-detected"]);function Ot(e){let t=e.trim();if(t.includes("/")||t.includes("\\")){let n=t.split(/[/\\]/);t=n[n.length-1]||"unknown";}return t.length>40&&(t=t.slice(0,40)),t||"unknown"}var J=class{transforms=new Map;record(t,n,s=1){let r=Ot(n),i=`${t}::${r}`,a=this.transforms.get(i);a?a.count+=s:this.transforms.set(i,{kind:t,surface:r,count:s});}report(){let t=Array.from(this.transforms.values()).sort((s,r)=>s.kind!==r.kind?s.kind.localeCompare(r.kind):s.surface.localeCompare(r.surface)),n=t.filter(s=>Ue.has(s.kind)).reduce((s,r)=>s+r.count,0);return {reindex_ts:new Date().toISOString(),transformations:t,lossy_count:n,strict_mode:K()}}hasLossy(){for(let t of this.transforms.values())if(Ue.has(t.kind))return true;return false}totalCount(){let t=0;for(let n of this.transforms.values())t+=n.count;return t}};b$1();var Ft={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},kt={features:["src/features/","features/","app/","src/app/","src/modules/","modules/"],components:["src/components/","components/","src/lib/","lib/","src/ui/","ui/"],gates:["middleware/","src/middleware/","auth/","src/auth/","guards/","src/guards/"],flows:["flows/","src/flows/","workflows/","src/workflows/","sagas/","src/sagas/"],integrations:["integrations/","src/integrations/","external/","src/external/","vendors/"],signals:["events/","src/events/","handlers/","src/handlers/"],state:["stores/","src/stores/","state/","src/state/","reducers/","src/reducers/"]},Mt={config:[".paradigm/config.yaml","package.json","tsconfig.json",".env.example"],entry:["src/index.ts","src/index.tsx","src/main.ts","src/main.tsx","index.ts","main.ts","src/app.ts","src/app.tsx"],types:["src/types/","types/","src/types.ts","types.ts"]},ae={always:["node_modules/","dist/","build/",".git/",".next/",".nuxt/",".cache/","*.lock","*.log"],unless_testing:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","__tests__/","test/","tests/"],unless_docs:["docs/","*.md","README*","CHANGELOG*"]};function Dn(){return [{name:"paradigm_reindex",description:"Rebuild scan-index.json, navigator.yaml, and flow-index.json from .purpose files. Call after modifying paradigm files or at the end of a work session to ensure static index files are fresh. Returns counts of indexed symbols, files processed, and any errors. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true},aliases:["rebuild","refresh","rescan","regenerate index","update index"]}]}async function Un(e,t,n,s){if(e!=="paradigm_reindex")return {handled:false,text:""};try{let r=await Pt(n.rootDir,n);await s(),a.clear(),be();let i=(r.integrityReport?.brokenReferences?.length||0)+(r.integrityReport?.duplicateSymbols?.length||0)+(r.componentAnchorIssues||0)+(r.crossFileIssues||0),a$1={success:!0,symbolCount:r.symbolCount,breakdown:r.breakdown,flowCount:r.flowCount,filesWritten:r.filesWritten.length,...r.aspectGraphStats?{aspects:r.aspectGraphStats.aspects,loreLinks:r.aspectGraphStats.loreLinks}:{},...r.protocolHealth?{protocols:r.protocolHealth.total,staleProtocols:r.protocolHealth.stale}:{},...i>0?{issues:i}:{}};r.consistency&&(a$1.consistency=r.consistency);let c=JSON.stringify(a$1,null,2);return O(c.length,e),{handled:!0,text:c}}catch(r){let i=JSON.stringify({error:r.message},null,2);return O(i.length,e),{handled:true,text:i}}}async function Pt(e,t){let n=[],s=new J,r;t?r=t.aggregation:r=await i(e);let i$1=t?.projectName||T.basename(e),a=T.join(e,".paradigm");S.existsSync(a)||S.mkdirSync(a,{recursive:true}),jt(e,s),Dt(r.purposeFiles,s);let c=ee({symbols:r.symbols,purposeFiles:r.purposeFiles,portalFiles:r.portalFiles},{projectName:i$1}),o=T.join(a,"scan-index.json");S.writeFileSync(o,te(c),"utf8"),n.push(".paradigm/scan-index.json");let u=Ut(e,r),l=T.join(a,"navigator.yaml");S.writeFileSync(l,C.dump(u,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),n.push(".paradigm/navigator.yaml");let d=Bt(e,r.purposeFiles),p=0;if(d&&Object.keys(d.flows).length>0){let f=T.join(a,"flow-index.json");S.writeFileSync(f,JSON.stringify(d,null,2),"utf8"),n.push(".paradigm/flow-index.json"),p=Object.keys(d.flows).length;}let y;try{let f=await Fe(e);Me(f,r.symbols,e);let E=await je(f,e),F=await De(f,e),k=f.exec("SELECT COUNT(*) FROM aspects")[0]?.values[0]?.[0]??0,z=f.exec("SELECT COUNT(*) FROM anchors")[0]?.values[0]?.[0]??0,B=f.exec("SELECT COUNT(*) FROM edges")[0]?.values[0]?.[0]??0;ke(f,e),n.push(".paradigm/aspect-graph.db"),y={aspects:k,anchors:z,edges:B,loreLinks:E};}catch{}let m=0;try{let f=await j$2(e);m=Object.keys(f.personas).length,m>0&&n.push(".paradigm/personas/index.yaml");}catch{}let R;try{let f=await M$1(e);f.health.total>0&&(R=f.health,n.push(".paradigm/protocols/index.yaml"));}catch{}let v;try{let f=T.join(e,".paradigm","university");if(S.existsSync(f)){let E=B(e);(E.totalContent>0||E.diplomaCount>0)&&(v={totalContent:E.totalContent,diplomaCount:E.diplomaCount},n.push(".paradigm/university/index.yaml"));}}catch{}let L;try{L=a$1(r,e);}catch{}let D;try{let f=b$3(r.symbols,e),E=f.missing+f.outOfBounds;E>0&&(D=E);}catch{}let U;try{U=c$1(r.purposeFiles,e);}catch{}let X;try{let f$1=[];for(let E of r.purposeFiles){let F=a$2(E);F.data&&f$1.push({filePath:E,data:F.data});}if(f$1.length>0){let F=f(f$1).issues.length;F>0&&(X=F);}}catch{}let H={};for(let f of r.symbols)H[f.type]=(H[f.type]||0)+1;let h={};for(let f of r.symbols)f.type==="component"&&f.componentType&&(h[f.componentType]=(h[f.componentType]||0)+1);let g=s.report();try{let f=T.join(a,"manifest.consistency.json");S.writeFileSync(f,JSON.stringify(g,null,2),"utf-8"),n.push(".paradigm/manifest.consistency.json");}catch{a$3.component("#reindex").warn("failed to write consistency manifest",{stage:"manifest-write"});}if(K()&&s.hasLossy())throw new Error(`reindex aborted: ${g.lossy_count} lossy transformation(s) detected under PARADIGM_STRICT=1. See .paradigm/manifest.consistency.json.`);return {action:"reindex",filesWritten:n,symbolCount:r.symbols.length,breakdown:H,flowCount:p,aspectGraphStats:y,personaCount:m,protocolHealth:R,consistency:g,...Object.keys(h).length>0?{componentTypeBreakdown:h}:{},...v?{universityStats:v}:{},...L?{integrityReport:L}:{},...D!==void 0?{componentAnchorIssues:D}:{},...U?{purposeHealth:U}:{},...X!==void 0?{crossFileIssues:X}:{}}}function jt(e,t){let n=T.join(e,"portal.yaml");if(!S.existsSync(n))return;let s;try{s=S.readFileSync(n,"utf-8");}catch{return}try{C.load(s);}catch(o){(o?.reason?.toLowerCase()||"").includes("duplicate")&&t.record("duplicate-key-detected","portal.yaml");return}let r;try{r=C.load(s,{schema:C.FAILSAFE_SCHEMA});}catch{return}if(!r||typeof r!="object")return;let i=r,a=i.gates;if(a&&typeof a=="object"&&!Array.isArray(a)){let o=0;for(let u of Object.keys(a))u.startsWith("^")&&o++;o>0&&t.record("prefix-stripped","portal.yaml",o);}else Array.isArray(a)&&a.length>0&&t.record("array-coerced","portal.yaml");let c=i.routes;Array.isArray(c)&&c.length>0&&t.record("array-coerced","portal.yaml"),i.version||t.record("default-applied","portal.yaml");}function Dt(e,t){for(let n of e){let s;try{s=S.readFileSync(n,"utf-8");}catch{continue}try{C.load(s);}catch(l){(l?.reason?.toLowerCase()||"").includes("duplicate")&&t.record("duplicate-key-detected","purpose.yaml");continue}let r;try{r=C.load(s,{schema:C.FAILSAFE_SCHEMA});}catch{continue}if(!r||typeof r!="object")continue;let i=r,a=["components","features","gates","signals","aspects","states"],c=0;for(let l of a)Array.isArray(i[l])&&c++;c>0&&t.record("array-coerced","purpose.yaml",c);let o=(l,d)=>{if(!l||typeof l!="object"||Array.isArray(l))return 0;let p=0;for(let y of Object.keys(l))y.startsWith(d)&&p++;return p},u=o(i.gates,"^")+o(i.signals,"!")+o(i.aspects,"~")+o(i.components,"#")+o(i.features,"#");u>0&&t.record("prefix-stripped","purpose.yaml",u);}}function Ut(e,t){let n={};for(let s of t.symbols)if(s.type==="component"&&s.componentType){let r=s.componentType;n[r]||(n[r]=[]),n[r].push(s.symbol);}return {version:"1.0",generated:new Date().toISOString(),structure:Ht(e),key_files:Wt(e),skip_patterns:Xt(e),symbols:$t(t.symbols,t.purposeFiles),...Object.keys(n).length>0?{symbolsByComponentType:n}:{}}}function Ht(e){let t={};for(let[n,s]of Object.entries(kt)){let r=s.filter(i=>S.existsSync(T.join(e,i)));if(r.length>0){let i=Object.values(Ft).find(a=>a.category===n);t[n]={paths:r,symbol:i?.prefix||"@"};}}return t}function Wt(e){let t={};for(let[n,s]of Object.entries(Mt)){let r=s.filter(i=>S.existsSync(T.join(e,i)));r.length>0&&(t[n]=r);}return t.config||(t.config=[]),t.entry||(t.entry=[]),t.types||(t.types=[]),t}function Xt(e){let t={always:[...ae.always],unless_testing:[...ae.unless_testing],unless_docs:[...ae.unless_docs]},n=T.join(e,".gitignore");if(S.existsSync(n))try{let r=S.readFileSync(n,"utf8").split(`
93
- `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#")).filter(i=>i.endsWith("/")||i.includes("*")||["node_modules","dist","build",".cache"].some(a=>i.includes(a))).slice(0,20);for(let i of r)t.always.includes(i)||t.always.push(i);}catch{}return t}function zt(e){switch(e){case "feature":return "@";case "component":return "#";case "gate":return "^";case "flow":return "$";case "integration":return "&";case "signal":return "!";case "state":return "%";case "idea":return "?";case "deprecated":return "~";case "aspect":return "~";default:return "@"}}function $t(e,t,n){let s={};for(let r of e){let a=`${zt(r.type)}${r.id}`;if(r.filePath)s[a]=r.filePath;else {let c=t.find(o=>T.dirname(o).toLowerCase().includes(r.id.toLowerCase()));c&&(s[a]=T.dirname(c)+"/");}}return s}function Bt(e,t){let n={},s={};for(let r of t)try{let i=S.readFileSync(r,"utf8"),a=C.load(i);if(!a?.flows)continue;if(Array.isArray(a.flows))for(let c of a.flows){let o=c;if(!o.name)continue;let u=`$${o.name}`,l=He(o.steps);l.length>0&&(n[u]={id:u,description:o.description||"",steps:l,definedIn:T.relative(e,r)},We(u,l,s));}else for(let[c,o]of Object.entries(a.flows)){let u=c.startsWith("$")?c:`$${c}`,l=He(o.steps);l.length>0&&(n[u]={id:u,description:o.description||"",trigger:o.trigger,steps:l,validation:o.validation,definedIn:T.relative(e,r)},We(u,l,s));}}catch{}return Object.keys(n).length===0?null:{version:"1.0",generatedAt:new Date().toISOString(),flows:n,symbolToFlows:s}}function He(e){if(!e||!Array.isArray(e))return [];let t=[];for(let n=0;n<e.length;n++){let s=e[n];if(typeof s=="object"&&s!==null){let r=s,i=r.action||r.description||r.component||"";i&&t.push({id:r.id||`step-${n+1}`,action:i,symbol:r.symbol||r.component,expect:r.expect});}}return t}function We(e,t,n){for(let s of t)s.symbol&&(n[s.symbol]||(n[s.symbol]=[]),n[s.symbol].includes(e)||n[s.symbol].push(e));}export{we as a,K as b,Fe as c,ke as d,cn as e,ln as f,un as g,dn as h,pn as i,fn as j,gn as k,hn as l,En as m,Dn as n,Un as o,Pt as p};
@@ -1,30 +0,0 @@
1
- #!/usr/bin/env node
2
- import {c,b as b$2}from'./chunk-3KVVC4WV.js';import {j,a as a$1,d,g as g$1}from'./chunk-KAUGQMXU.js';import {z,i,c as c$1,f as f$1,j as j$1}from'./chunk-KAFQA7HV.js';import {b as b$1,a as a$2}from'./chunk-EK4ZRIFJ.js';import {f,b as b$3}from'./chunk-ECO3LHCE.js';import {b,a}from'./chunk-5TAVYPOV.js';import*as l from'fs';import*as g from'path';import*as nt from'js-yaml';import*as T from'os';function Q(e){return g.join(e,K,ut)}function gt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `ev-${e}-${t}`}function E(e,t){let n={id:gt(),timestamp:new Date().toISOString(),...t};_.push(n),_.length>k&&(_=_.slice(-k));try{let o=g.join(e,K);l.mkdirSync(o,{recursive:!0});let r=Q(e);l.appendFileSync(r,JSON.stringify(n)+`
3
- `,"utf8"),pt(r);}catch{}return n}function pt(e){try{if(l.statSync(e).size>512*1024){let o=l.readFileSync(e,"utf8").trim().split(`
4
- `);if(o.length>k){let r=o.slice(-k);l.writeFileSync(e,r.join(`
5
- `)+`
6
- `,"utf8");}}}catch{}}function Lt(e,t){let n=ht(e);return t?.type&&(n=n.filter(o=>o.type===t.type)),t?.source&&(n=n.filter(o=>o.source===t.source)),t?.symbol&&(n=n.filter(o=>o.symbols?.includes(t.symbol))),t?.agent&&(n=n.filter(o=>o.agent===t.agent)),t?.since&&(n=n.filter(o=>o.timestamp>=t.since)),n.sort((o,r)=>r.timestamp.localeCompare(o.timestamp)),t?.limit&&(n=n.slice(0,t.limit)),n}function ht(e){let t=Q(e);if(!l.existsSync(t))return [..._];try{return l.readFileSync(t,"utf8").trim().split(`
7
- `).filter(r=>r.trim()).map(r=>{try{return JSON.parse(r)}catch{return null}}).filter(r=>r!==null)}catch{return [..._]}}function Z(e,t,n){let o=0,r=0,i=0,s=0;if(n.symbols?.length&&e.symbols?.length)for(let c of n.symbols)for(let a of e.symbols)X(c,a)&&(o=Math.max(o,1));if(n.paths?.length&&e.path){for(let c of n.paths)if(X(c,e.path)){r=1;break}}if(n.concepts?.length){let c=[e.context||"",...e.keywords||[],e.type||""].join(" ").toLowerCase(),a=0;for(let u of n.concepts)u&&c.includes(u.toLowerCase())&&a++;n.concepts.length>0&&(i=a/n.concepts.length);}if(n.signals?.length){for(let c of n.signals)if(c.type===e.type){s=1;break}}let f=[o,r,i,s].sort((c,a)=>a-c),d=f[0]*.5+f[1]*.2+f[2]*.15+f[3]*.15,m=n.threshold??.6;return {agentId:t,score:d,breakdown:{symbolMatch:o,pathMatch:r,conceptMatch:i,signalMatch:s},shouldNominate:d>=m,quietReason:d<m?"below-threshold":void 0}}function X(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var K,ut,k,_,tt=b(()=>{K=".paradigm/events",ut="stream.jsonl",k=1e3,_=[];});function C(e){let t=g.join(e,yt);if(!l.existsSync(t))return {...b$2};try{let n=l.readFileSync(t,"utf8"),o=nt.load(n);return bt(b$2,o)}catch{return {...b$2}}}function bt(e,t){let n={...e};if(t.version&&(n.version=t.version),t.default_ring&&(n.default_ring=t.default_ring),t.observation&&(n.observation={allow:t.observation.allow||e.observation?.allow,deny:[...e.observation?.deny||[],...t.observation.deny||[]].filter((o,r,i)=>i.indexOf(o)===r)}),t.streams){n.streams={...e.streams};for(let o of ["work_log","learning_journal","team_decisions"])t.streams[o]&&(n.streams[o]={...e.streams?.[o],...t.streams[o],deny_content:[...e.streams?.[o]?.deny_content||[],...t.streams[o]?.deny_content||[]].filter((r,i,s)=>s.indexOf(r)===i)});}return t.upstream&&(n.upstream={...e.upstream,...t.upstream}),t.network&&(n.network={...e.network,...t.network}),t.agent_overrides&&(n.agent_overrides={...e.agent_overrides,...t.agent_overrides}),t.deployment&&(n.deployment={...e.deployment,...t.deployment}),n}function M(e,t,n){return n&&e.agent_overrides?.[n]?.observation&&e.agent_overrides[n].observation.deny?.some(r=>R(r,t))||e.observation?.deny?.some(o=>R(o,t))?false:e.observation?.allow?.length?e.observation.allow.some(o=>R(o,t)):true}function Gt(e,t,n){let o=t.streams?.[n];if(!o)return {filtered:e,redacted:[]};let r=[],i=e;if(o.redaction)for(let s of o.redaction)try{let f=new RegExp(s.pattern,"gi"),d=i.match(f);d&&(r.push(...d),i=i.replace(f,s.replacement||"[REDACTED]"));}catch{}return {filtered:i,redacted:r}}function R(e,t){if(e===t)return true;let n=e.replace(/\*\*/g,"\xA7\xA7").replace(/\*/g,"[^/]*").replace(/§§/g,".*");try{return new RegExp(`^${n}$`).test(t)}catch{return false}}var yt,ot=b(()=>{c();yt=".paradigm/data-policy.yaml";});function kt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `nom-${e}-${t}`}function jt(){let e=Date.now(),t=Math.floor(Math.random()*9999).toString().padStart(4,"0");return `dbt-${e}-${t}`}function st(e,t){let n=i(e),o=C(e),r=[];for(let m of n){if(!m.attention||!c$1(m.id,e)||t.path&&!M(o,t.path,m.id))continue;let c=Z(t,m.id,m.attention);c.shouldNominate&&r.push({profile:m,score:c});}if(r.length===0)return {nominations:[],debates:[]};let i$1=A(e,{since:new Date(Date.now()-3e4).toISOString()}),s=r.filter(({profile:m})=>!i$1.find(a=>a.agent===m.id&&a.brief===rt(m,t,{...r.find(u=>u.profile.id===m.id).score})));if(s.length===0)return {nominations:[],debates:[]};let f=s.map(({profile:m,score:c})=>{let a=Tt(t,c),u=Pt(m,t);return {id:kt(),agent:m.id,relevance:c.score,urgency:a,type:u,brief:rt(m,t,c),triggered_by:[t.id],timestamp:new Date().toISOString(),surfaced:false}});Dt(e,f);let d=At(e,f);return d.length>0&&Ft(e,d),{nominations:f,debates:d}}function Tt(e,t){return e.severity==="critical"?"critical":e.severity==="error"||e.type==="compliance-violation"||e.type==="error-encountered"?"high":e.type==="gate-added"||e.type==="route-created"||t.score>=.9?"medium":"low"}function Pt(e,t){let n=e.collaboration?.stance;return t.type==="compliance-violation"||t.type==="error-encountered"?"warning":t.type==="gate-added"||t.type==="route-created"?"observation":n==="advisory"||n==="lead"?"suggestion":"observation"}function rt(e,t,n){let o=e.role||e.id;switch(t.type){case "gate-checked":return `${o}: Gate check on ${t.symbols?.join(", ")||"route"} \u2014 verify gate coverage is complete`;case "file-modified":return `${o}: ${t.path||"File"} modified \u2014 review for ${e.id==="security"?"security implications":e.id==="tester"?"test coverage":e.id==="reviewer"?"code quality":"consistency"}`;case "compliance-violation":return `${o}: Compliance violation detected \u2014 ${t.context||"check .purpose and portal.yaml coverage"}`;case "route-created":return `${o}: New route ${t.symbols?.join(", ")||""} \u2014 ${e.id==="security"?"needs gate assignment in portal.yaml":"review route structure"}`;case "gate-added":return `${o}: Gate ${t.symbols?.join(", ")||""} added \u2014 ${e.id==="security"?"verify enforcement points":"check downstream impact"}`;case "decision-made":return `${o}: Decision recorded \u2014 ${t.context?.slice(0,80)||"review for alignment with project patterns"}`;case "work-completed":return `${o}: Work completed on ${t.symbols?.join(", ")||t.context?.slice(0,40)||"task"} \u2014 review outcome`;case "error-encountered":return `${o}: Error detected \u2014 ${t.context?.slice(0,80)||"investigate root cause"}`;default:{let r=n.breakdown.symbolMatch>0?`symbol match on ${t.symbols?.join(", ")||"unknown"}`:n.breakdown.pathMatch>0?`path ${t.path||"unknown"}`:t.context?.slice(0,60)||t.type;return `${o}: ${r}`}}}function At(e,t){if(t.length<2)return [];let n=[],o=new Map;for(let r of t)for(let i of r.triggered_by){let s=o.get(i)||[];s.push(r),o.set(i,s);}for(let[r,i]of o){if(i.length<2||new Set(i.map(m=>m.agent)).size<2)continue;let f=new Set(i.map(m=>m.type)),d=f.size>1&&f.has("warning")&&f.has("suggestion");n.push({id:jt(),topic:`Multiple agents responded to event ${r}`,nominations:i.map(m=>m.id),type:d?"conflicting":"complementary",overlap_events:[r]});}return n}function I(e){return g.join(e,S,St)}function L(e){return g.join(e,S,_t)}function Dt(e,t){try{let n=g.join(e,S);l.mkdirSync(n,{recursive:!0});let o=I(e),r=t.map(s=>JSON.stringify(s)).join(`
8
- `)+`
9
- `;l.appendFileSync(o,r,"utf8"),J(o,it);let{nominationTtlDays:i}=P(e);at(o,i*24*60*60*1e3);}catch{}}function Ft(e,t){try{let n=g.join(e,S);l.mkdirSync(n,{recursive:!0});let o=L(e),r=t.map(s=>JSON.stringify(s)).join(`
10
- `)+`
11
- `;l.appendFileSync(o,r,"utf8"),J(o,Et);let{debateTtlDays:i}=P(e);at(o,i*24*60*60*1e3);}catch{}}function $t(e,t){try{let n=g.join(e,S);l.mkdirSync(n,{recursive:!0});let o=g.join(n,wt);l.appendFileSync(o,JSON.stringify(t)+`
12
- `,"utf8"),J(o,it);}catch(n){a$2.component("#promotion-decisions").warn("failed to record promotion decision",{agent:t.agent,error:n instanceof Error?n.message:String(n)});}}function J(e,t){try{let o=l.readFileSync(e,"utf8").trim().split(`
13
- `).filter(r=>r.trim());if(o.length>t){let r=o.slice(-t);l.writeFileSync(e,r.join(`
14
- `)+`
15
- `,"utf8");}}catch{}}function P(e){let t={nominationTtlDays:Nt,debateTtlDays:vt};try{let n=g.join(e,".paradigm","config.yaml");if(!l.existsSync(n))return t;let o=a("js-yaml"),r=l.readFileSync(n,"utf8"),s=o.load(r)?.ambient;return s?{nominationTtlDays:typeof s["nomination-ttl-days"]=="number"?s["nomination-ttl-days"]:t.nominationTtlDays,debateTtlDays:typeof s["debate-ttl-days"]=="number"?s["debate-ttl-days"]:t.debateTtlDays}:t}catch{return t}}function at(e,t){try{if(!l.existsSync(e))return;let o=l.readFileSync(e,"utf8").trim().split(`
16
- `).filter(s=>s.trim());if(o.length<=xt)return;let r=Date.now()-t,i=o.filter(s=>{try{let f=JSON.parse(s);return (f.timestamp?new Date(f.timestamp).getTime():Date.now())>=r}catch{return !0}});i.length<o.length&&l.writeFileSync(e,i.join(`
17
- `)+`
18
- `,"utf8");}catch{}}function A(e,t){let n=I(e);if(!l.existsSync(n))return [];try{let r=l.readFileSync(n,"utf8").trim().split(`
19
- `).filter(i=>i.trim()).map(i=>{try{return JSON.parse(i)}catch{return null}}).filter(i=>i!==null);return t?.agent&&(r=r.filter(i=>i.agent===t.agent)),t?.urgency&&(r=r.filter(i=>i.urgency===t.urgency)),t?.surfaced!==void 0&&(r=r.filter(i=>i.surfaced===t.surfaced)),t?.pending_only&&(r=r.filter(i=>!i.engaged)),t?.since&&(r=r.filter(i=>i.timestamp>=t.since)),r.sort((i,s)=>s.timestamp.localeCompare(i.timestamp)),t?.limit&&(r=r.slice(0,t.limit)),r}catch{return []}}function Kt(e){let t=L(e);if(!l.existsSync(t))return [];try{return l.readFileSync(t,"utf8").trim().split(`
20
- `).filter(o=>o.trim()).map(o=>{try{return JSON.parse(o)}catch{return null}}).filter(o=>o!==null)}catch{return []}}function Qt(e,t,n,o){let r=I(e);if(!l.existsSync(r))return false;try{let s=l.readFileSync(r,"utf8").trim().split(`
21
- `),f=!1,d=s.map(m=>{try{let c=JSON.parse(m);return c.id===t?(c.engaged=!0,c.response=n,o&&(c.reason=o),f=!0,JSON.stringify(c)):m}catch{return m}});if(f&&(l.writeFileSync(r,d.join(`
22
- `)+`
23
- `,"utf8"),n==="accepted"||n==="dismissed")){let m=JSON.parse(s.find(a=>{try{return JSON.parse(a).id===t}catch{return !1}}));i(e).find(a=>a.id===m.agent)?.learning?.intrinsic?.feedback?.after_recommendation&&E(e,{type:"work-completed",source:"agent-action",agent:m.agent,context:`Nomination ${t} ${n} \u2014 feedback for learning`,data:{nomination_id:t,response:n}});}return f}catch{return false}}function Zt(e,t,n,o){let r=L(e);if(!l.existsSync(r))return false;try{let s=l.readFileSync(r,"utf8").trim().split(`
24
- `),f=!1,d=s.map(m=>{try{let c=JSON.parse(m);if(c.id===t){c.resolution={chosen:n,reason:o,resolved_by:"human",resolved_at:new Date().toISOString()},f=!0;let a=c.nominations.filter(u=>u!==n);for(let u of a){let p=A(e).find(b=>b.id===u);p&&E(e,{type:"work-completed",source:"agent-action",agent:p.agent,context:`Debate ${t} resolved \u2014 nomination ${u} not chosen`,data:{debate_id:t,chosen:n,reason:o}});}return JSON.stringify(c)}return m}catch{return m}});return f&&l.writeFileSync(r,d.join(`
25
- `)+`
26
- `,"utf8"),f}catch{return false}}function te(e){let t=g.join(e,S,".last-processed"),n="";try{l.existsSync(t)&&(n=l.readFileSync(t,"utf8").trim());}catch{}let o=g.join(e,S,"stream.jsonl");if(!l.existsSync(o))return {processed:0,nominations:[]};let r=[];try{r=l.readFileSync(o,"utf8").trim().split(`
27
- `).filter(a=>a.trim()).map(a=>{try{return JSON.parse(a)}catch{return null}}).filter(a=>a!==null);}catch{return {processed:0,nominations:[]}}let i=0;if(n){let c=r.findIndex(a=>a.id===n);c>=0&&(i=c+1);}let s=r.slice(i);if(s.length===0)return {processed:0,nominations:[]};let f=[],d=s.slice(0,50);for(let c of d){let{nominations:a}=st(e,c);f.push(...a);}let m=d[d.length-1];try{l.mkdirSync(g.join(e,S),{recursive:!0}),l.writeFileSync(t,m.id,"utf8");}catch{}return {processed:d.length,nominations:f}}function ee(e,t,n){let o=C(e);if(t.path&&!M(o,t.path))return {event:E(e,t),nominations:[],debates:[]};let r=E(e,t);if(n?.skipNominations)return {event:r,nominations:[],debates:[]};let{nominations:i,debates:s}=st(e,r);return i.length>0&&Rt(e,i),{event:r,nominations:i,debates:s}}function ne(e,t){let n=f$1(e,t);if(!n?.attention)return {adjusted:false,oldThreshold:.6,newThreshold:.6,reason:"No attention config"};let o=n.attention.threshold??.6,{nominationTtlDays:r}=P(e),i=r*24*60*60*1e3,d=A(e,{agent:t}).filter(h=>h.engaged||Date.now()-new Date(h.timestamp).getTime()<i).filter(h=>h.engaged);if(d.length<5)return {adjusted:false,oldThreshold:o,newThreshold:o,reason:`Insufficient data (${d.length}/5 engaged nominations)`};let m=d.filter(h=>h.response==="accepted").length,c=d.filter(h=>h.response==="dismissed").length,a=m/d.length,u=c/d.length,p=o,b="No adjustment needed";if(u>.6?(p=Math.min(.95,o+.05),b=`High dismiss rate (${(u*100).toFixed(0)}%) \u2014 raising threshold to reduce noise`):a>.8&&(p=Math.max(.2,o-.05),b=`High accept rate (${(a*100).toFixed(0)}%) \u2014 lowering threshold to contribute more`),p===o)return {adjusted:false,oldThreshold:o,newThreshold:p,reason:b};n.attention.threshold=p;let w=g.join(e,".paradigm/agents",`${t}.agent`),N=l.existsSync(w)?"project":"global";return j$1(t,n,N,e),E(e,{type:"work-completed",source:"agent-action",agent:t,context:`Attention threshold adjusted: ${o.toFixed(2)} \u2192 ${p.toFixed(2)} (${b})`,data:{old_threshold:o,new_threshold:p,accept_rate:a,dismiss_rate:u}}),{adjusted:true,oldThreshold:o,newThreshold:p,reason:b}}function Ot(e,t){let{nominationTtlDays:n}=P(e),o=n*24*60*60*1e3,i=A(e,{agent:t}).filter(a=>a.engaged||Date.now()-new Date(a.timestamp).getTime()<o),s=i.filter(a=>a.response==="accepted").length,f=i.filter(a=>a.response==="dismissed").length,d=i.filter(a=>a.response==="deferred").length,m=i.filter(a=>!a.engaged).length,c=s+f+d;return {total:i.length,accepted:s,dismissed:f,deferred:d,pending:m,acceptRate:c>0?s/c:0}}function oe(e){let n=i(e).filter(a=>c$1(a.id,e)).map(a=>{let u=Ot(e,a.id),p=0;try{let b=g.join(T.homedir(),".paradigm","notebooks",a.id);l.existsSync(b)&&(p=l.readdirSync(b).filter(w=>w.endsWith(".yaml")).length);}catch{}return {id:a.id,acceptRate:u.acceptRate,threshold:a.attention?.threshold??.5,expertiseCount:(a.expertise||[]).length,notebookCount:p,transferableCount:(a.transferable||[]).length,totalNominations:u.total}}),o=n.length||1,r=n.reduce((a,u)=>a+u.acceptRate,0)/o,i$1=n.reduce((a,u)=>a+u.threshold,0)/o,s=n.reduce((a,u)=>a+u.expertiseCount,0),f=n.reduce((a,u)=>a+u.notebookCount,0),d=n.reduce((a,u)=>a+u.transferableCount,0),m=n.reduce((a,u)=>a+u.totalNominations,0),c;return m<10?c="cold-start":r<.5?c="accumulating":r<.7?c="calibrating":c="mature",{agents:n,aggregate:{avgAcceptRate:r,avgThreshold:i$1,totalExpertise:s,totalNotebooks:f,totalTransferable:d},healthStatus:c}}function Rt(e,t){if(t.length===0)return;let n=g.join(T.homedir(),".paradigm","score","outbox");if(l.existsSync(n))try{let o=g.join(n,`nom-${Date.now()}.json`),r={type:"nomination_forward",nominations:t.map(i=>({...i})),origin:Ct(e),timestamp:new Date().toISOString()};l.writeFileSync(o,JSON.stringify(r),"utf8");}catch{}}function Ct(e){try{let t=g.join(e,".paradigm","config.yaml");if(l.existsSync(t)){let o=l.readFileSync(t,"utf8").match(/project:\s*(.+)/);if(o)return o[1].trim()}}catch{}return g.basename(e)}function re(e,t){let n=b$3(t,{trigger:"pattern_discovered",limit:100}),o=b$3(t,{trigger:"human_feedback",limit:100}),r=[...n,...o],i=[];for(let s of r){if(s.promoted_to_notebook)continue;let f=(s.tags||[s.pattern?.id||"learned-pattern"]).map(a$1).filter(Boolean),d$1=s.confidence_after??0,m=d$1>=.8,c=.5,a=false;try{let u=d(t,f,e);c=u.value,a=u.found;}catch{}if($t(e,{ts:new Date().toISOString(),agent:t,concepts:f,before:c,after:d$1,delta:d$1-c,promoted:m,priorFound:a,gate:"absolute-0.8"}),!((s.confidence_after??0)<.8))try{let{entry:u}=g$1(t,{context:s.pattern?.applies_when||s.insight.slice(0,80),snippet:s.pattern?.correct_approach||s.insight,confidence:s.confidence_after??.5,concepts:f,tags:s.tags??[],provenance:{source:"lore",loreEntryId:s.id,createdBy:t}},"global",e);i.push({journalId:s.id,notebookId:u.id});try{let p=g.join(T.homedir(),".paradigm","agents",t,"journal");if(l.existsSync(p)){let b=l.readdirSync(p).filter(w=>w.endsWith(".yaml"));for(let w of b){let N=g.join(p,w),h=l.readFileSync(N,"utf8");if(h.includes(s.id)){let U=h.replace(/promoted_to_notebook:.*$/m,`promoted_to_notebook: "${u.id}"`);if(U===h){let B=h.trimEnd().split(`
28
- `);B.push(`promoted_to_notebook: "${u.id}"`),l.writeFileSync(N,B.join(`
29
- `)+`
30
- `,"utf8");}else l.writeFileSync(N,U,"utf8");break}}}}catch{}}catch(u){console.error("PROMOTE_THREW",u.message);}}return {promoted:i.length,entries:i}}function ie(e){let t=g.join(e,Mt),n={default_min_urgency:"low",enable_debates:true};if(!l.existsSync(t))return n;try{let o=a("js-yaml"),r=l.readFileSync(t,"utf8"),i=o.load(r);return {...n,...i}}catch{return n}}function se(e,t){let n={critical:0,high:1,medium:2,low:3},o=n[t.default_min_urgency||"low"]??3;return e.filter(r=>{let i=n[r.urgency]??3;if(t.preferences){let s=t.preferences.find(f=>f.agent===r.agent);if(s){if(s.always_show)return true;if(s.mute_unless?.length&&!s.mute_unless.some(d=>r.urgency===d||r.type===d))return false;if(s.min_urgency){let f=n[s.min_urgency]??3;return i<=f}}}return i<=o})}var S,St,wt,_t,it,Et,Nt,vt,xt,Mt,It=b(()=>{tt();ot();z();f();j();b$1();S=".paradigm/events",St="nominations.jsonl",wt="promotion-decisions.jsonl",_t="debates.jsonl",it=500,Et=200,Nt=7,vt=14,xt=100;Mt=".paradigm/surfacing.yaml";});export{Lt as a,tt as b,C as c,Gt as d,ot as e,st as f,At as g,Dt as h,A as i,Kt as j,Qt as k,Zt as l,te as m,ee as n,ne as o,Ot as p,oe as q,Rt as r,re as s,ie as t,se as u,It as v};
@@ -1,3 +0,0 @@
1
- #!/usr/bin/env node
2
- import*as P from'fs';import*as z from'js-yaml';import {z as z$1}from'zod';import*as b from'path';import {glob}from'glob';var T=z$1.object({description:z$1.string(),type:z$1.string().optional(),parent:z$1.string().optional(),anchors:z$1.array(z$1.string()).optional(),tags:z$1.array(z$1.string()).optional(),endpoints:z$1.array(z$1.string()).optional(),tests:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),aspects:z$1.array(z$1.string()).optional(),flows:z$1.array(z$1.string()).optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),states:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),location:z$1.string().optional(),locations:z$1.array(z$1.string()).optional(),uses:z$1.array(z$1.string()).optional(),"used-by":z$1.array(z$1.string()).optional(),"used-for":z$1.array(z$1.string()).optional(),exports:z$1.array(z$1.string()).optional(),status:z$1.string().optional(),properties:z$1.record(z$1.unknown()).optional(),handles:z$1.array(z$1.string()).optional()}).passthrough(),Y=T.extend({id:z$1.string()}),de=z$1.object({description:z$1.string().optional(),category:z$1.string().optional(),severity:z$1.enum(["info","warn","error"]).optional(),emitters:z$1.array(z$1.string()).optional(),related:z$1.array(z$1.string()).optional(),data:z$1.record(z$1.unknown()).optional()}),me=z$1.union([de,z$1.string().transform(t=>({description:t}))]),he=z$1.object({from:z$1.string(),to:z$1.string(),type:z$1.string(),description:z$1.string().optional()}),ge=z$1.union([he,z$1.string()]),ye=z$1.object({component:z$1.string(),action:z$1.string(),description:z$1.string().optional()}),N=z$1.union([ye,z$1.string()]),$e=z$1.object({name:z$1.string(),description:z$1.string().optional(),steps:z$1.array(N)}),we=z$1.object({description:z$1.string().optional(),gates:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional(),components:z$1.array(z$1.string()).optional(),steps:z$1.array(N).optional()}),be=z$1.object({description:z$1.string().optional(),requires:z$1.array(z$1.string()).optional(),keys:z$1.array(z$1.string()).optional(),signals:z$1.array(z$1.string()).optional()}),Se=z$1.object({description:z$1.string().optional(),default:z$1.unknown().optional(),type:z$1.string().optional()}),ve=z$1.object({description:z$1.string().optional(),tags:z$1.array(z$1.string()).optional(),anchors:z$1.array(z$1.string()).optional(),"applies-to":z$1.array(z$1.string()).optional(),enforcement:z$1.string().optional()}),xe=z$1.object({target:z$1.string(),type:z$1.string(),path:z$1.string()}),Pe=z$1.object({version:z$1.string().optional(),description:z$1.string().optional(),apiSpec:z$1.string().optional(),context:z$1.array(z$1.string()).optional(),rules:z$1.record(z$1.unknown()).optional(),features:z$1.union([z$1.array(Y),z$1.record(T)]).optional(),components:z$1.union([z$1.array(Y),z$1.record(T)]).optional(),gates:z$1.record(be).optional(),states:z$1.record(Se).optional(),signals:z$1.record(me).optional(),aspects:z$1.record(ve).optional(),relationships:z$1.array(ge).optional(),flows:z$1.union([z$1.array($e),z$1.record(we)]).optional(),references:z$1.array(xe).optional()});function ke(t){let s=je(t);return {data:s.data,errors:s.errors}}function je(t){let s=[],e=[],o;try{o=P.readFileSync(t,"utf8");}catch(c){let p=`Cannot read file: ${c.message}`;return s.push(p),e.push({message:p,type:"file"}),{data:null,errors:s,detailedErrors:e,rawContent:void 0,isYamlValid:false}}let a=o.replace(/^([#~!$^][\w-]+):/gm,'"$1":').replace(/^(\s*-\s+)([!#][\w-]+)$/gm,'$1"$2"'),i=null;try{i=z.load(a);}catch(c){let p=c,f=p.mark?.line?p.mark.line+1:void 0,u=`YAML syntax error: ${p.reason||c.message}`;return s.push(`${u}${f?` (line ${f})`:""}`),e.push({message:u,line:f,type:"yaml"}),{data:null,errors:s,detailedErrors:e,rawContent:o,isYamlValid:false}}if(i==null)return {data:{},errors:[],detailedErrors:[],rawContent:o,isYamlValid:true};if(typeof i=="object"&&i!==null){let c=i,p={"#":"components",$:"flows","^":"gates","!":"signals","~":"aspects"};for(let f of Object.keys(c)){let u=f[0],d=p[u];if(!d||f.length<2)continue;let g=f.slice(1),y=c[f];if(typeof y!="object"||y===null)continue;let S=c[d]||{};d in c||(c[d]=S),g in S||(S[g]=y),delete c[f];}}let r=Pe.safeParse(i);if(!r.success){for(let c of r.error.issues){let p=c.path.join("."),f=c.message;s.push(`Schema error at ${p||"/"}: ${f}`),e.push({message:f,path:p||"/",type:"schema"});}return {data:i,errors:s,detailedErrors:e,rawContent:o,isYamlValid:true}}return {data:r.data,errors:[],detailedErrors:[],rawContent:o,isYamlValid:true}}function He(t){return z.dump(t,{indent:2,lineWidth:-1,noRefs:true,sortKeys:false})}function D(t){return t?Array.isArray(t)?t.map(s=>[s.id,s]):Object.entries(t):[]}async function Ae(t){let s=b.resolve(t);return (await glob("**/.purpose",{cwd:s,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})).sort((o,a)=>{let i=o.split(b.sep).length,r=a.split(b.sep).length;return i-r})}async function K(t){let s=await Ae(t),e=[];for(let o of s){let{data:a,errors:i}=ke(o);a&&(e.push({filePath:o,data:a}),i.length>0&&console.warn(`Warnings parsing ${o}:`,i));}return e}function U(t){let s=new Map;for(let{filePath:e,data:o}of t){let a=D(o.features);for(let[i,r]of a)s.set(i,{item:r,filePath:e});}return s}function q(t){let s=new Map;for(let{filePath:e,data:o}of t){let a=D(o.components);for(let[i,r]of a)s.set(i,{item:r,filePath:e});}return s}function Z(t){let s=new Map;for(let{filePath:e,data:o}of t)if(o.gates)for(let[a,i]of Object.entries(o.gates))s.set(a,{item:i,filePath:e});return s}function X(t){let s=new Map;for(let{filePath:e,data:o}of t)if(o.states)for(let[a,i]of Object.entries(o.states))s.set(a,{item:i,filePath:e});return s}function H(t){let s=new Map;for(let{filePath:e,data:o}of t)if(o.flows)if(Array.isArray(o.flows))for(let a of o.flows)s.set(a.name,{item:{id:a.name,description:a.description,steps:a.steps},filePath:e});else for(let[a,i]of Object.entries(o.flows))s.set(a,{item:{id:a,description:i.description,gates:i.gates,signals:i.signals,components:i.components,steps:i.steps},filePath:e});return s}function J(t){let s=new Map;for(let{filePath:e,data:o}of t)if(o.signals)for(let[a,i]of Object.entries(o.signals))s.set(a,{item:i,filePath:e});return s}function Q(t){let s=new Map;for(let{filePath:e,data:o}of t)if(o.aspects)for(let[a,i]of Object.entries(o.aspects))s.set(a,{item:i,filePath:e});return s}function ee(t){let s=[],e=new Set;for(let{filePath:o,data:a}of t){let i=D(a.features);for(let[c,p]of i)B(`#${c}`,p,o,s,e);let r=D(a.components);for(let[c,p]of r)B(`#${c}`,p,o,s,e);}return s}function B(t,s,e,o,a){if(s.flows)for(let i of s.flows){let r=i.startsWith("$")?i:`$${i}`;a.has(r)||(a.add(r),o.push({symbol:r,type:"flow",sourceSymbol:t,filePath:e}));}if(s.gates)for(let i of s.gates){let r=i.startsWith("^")?i:`^${i}`;a.has(r)||(a.add(r),o.push({symbol:r,type:"gate",sourceSymbol:t,filePath:e}));}if(s.signals)for(let i of s.signals){let r=i.startsWith("!")?i:`!${i}`;a.has(r)||(a.add(r),o.push({symbol:r,type:"signal",sourceSymbol:t,filePath:e}));}if(s.states)for(let i of s.states){let r=i.startsWith("#")?i:i.startsWith("%")?`#${i.slice(1)}`:`#${i}`;a.has(r)||(a.add(r),o.push({symbol:r,type:"component",sourceSymbol:t,filePath:e}));}if(s.components)for(let i of s.components){let r=i.startsWith("#")?i:`#${i}`;a.has(r)||(a.add(r),o.push({symbol:r,type:"component",sourceSymbol:t,filePath:e}));}if(s.aspects)for(let i of s.aspects){let r=i.startsWith("~")?i:`~${i}`;a.has(r)||(a.add(r),o.push({symbol:r,type:"aspect",sourceSymbol:t,filePath:e}));}if(s.description){let i=De(s.description);for(let{symbol:r,type:c}of i)a.has(r)||(a.add(r),o.push({symbol:r,type:c,sourceSymbol:t,filePath:e}));}}var Ie=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function De(t){let s=[],e=/([$^!#~%])([a-zA-Z][a-zA-Z0-9._-]*)/g,o;for(;(o=e.exec(t))!==null;){let a=o[1],i=o[2],r,c;switch(a){case "#":c="component",r=`#${i}`;break;case "$":c="flow",r=`$${i}`;break;case "^":c="gate",r=`^${i}`;break;case "!":c="signal",r=`!${i}`;break;case "~":c="aspect",r=`~${i}`;break;case "%":c="component",r=`#${i}`;break;default:continue}Ie.has(r)||s.push({symbol:r,type:c});}return s}function k(t){return t?Array.isArray(t)?t.map(s=>[s.id,s]):Object.entries(t):[]}function F(t){return t?Array.isArray(t)?t.map(s=>s.id):Object.keys(t):[]}function Qe(t,s){let e=[],o=s?`${s}: `:"",a=k(t.features);for(let[r,c]of a)V(r,c,"feature",o,e);let i=k(t.components);for(let[r,c]of i)V(r,c,"component",o,e);if(t.relationships){let r=new Set([...F(t.features),...F(t.components)]);for(let c of t.relationships){if(typeof c=="string"||!c||!c.from||!c.to)continue;let p=c.from.replace(/^[@#$%~^!?]/,"");!r.has(p)&&!c.from.includes(".")&&e.push({type:"warning",message:`${o}Relationship references unknown source: "${c.from}"`,path:"relationships"});let f=c.to.replace(/^[@#$%~^!?]/,"");!r.has(f)&&!c.to.includes(".")&&e.push({type:"warning",message:`${o}Relationship references unknown target: "${c.to}"`,path:"relationships"});}}if(t.flows){let r=new Set(F(t.components));if(Array.isArray(t.flows)){for(let c of t.flows)if(!(!c||typeof c!="object")&&(c.name||e.push({type:"error",message:`${o}Flow missing required "name" field`,path:"flows"}),c.steps&&Array.isArray(c.steps)))for(let p of c.steps){if(typeof p=="string"||!p||!p.component)continue;let f=p.component.replace(/^#/,"");r.has(f)||e.push({type:"warning",message:`${o}Flow "${c.name}" references unknown component: "${p.component}"`,path:`flows.${c.name}`});}}else for(let[c,p]of Object.entries(t.flows))if(!(!p||typeof p!="object")&&p.steps&&Array.isArray(p.steps))for(let f of p.steps){if(typeof f=="string"||!f||!f.component)continue;let u=f.component.replace(/^#/,"");r.has(u)||e.push({type:"warning",message:`${o}Flow "${c}" references unknown component: "${f.component}"`,path:`flows.${c}`});}}return {valid:e.filter(r=>r.type==="error").length===0,issues:e}}function V(t,s,e,o,a){let i=`${e}s.${t}`;if(/^[a-zA-Z][a-zA-Z0-9-]*$/.test(t)||a.push({type:"warning",message:`${o}${e} ID "${t}" should use alphanumeric characters and hyphens`,path:i}),(!s.description||s.description.trim()==="")&&a.push({type:"warning",message:`${o}${e} "${t}" has no description`,path:i}),s.endpoints)for(let r of s.endpoints)/^(GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS)\s+\//.test(r)||a.push({type:"warning",message:`${o}Endpoint "${r}" in ${e} "${t}" may not be in standard format (e.g., "GET /api/users")`,path:`${i}.endpoints`});}function et(t){let s=[],e=new Set;for(let{data:o}of t){let a=k(o.components);for(let[r]of a)e.add(`#${r}`),e.add(r);let i=k(o.features);for(let[r]of i)e.add(`#${r}`),e.add(r);if(o.gates)for(let r of Object.keys(o.gates))e.add(`^${r}`),e.add(r);if(o.signals)for(let r of Object.keys(o.signals))e.add(`!${r}`),e.add(r);if(o.flows)if(Array.isArray(o.flows))for(let r of o.flows)r?.name&&(e.add(`$${r.name}`),e.add(r.name));else for(let r of Object.keys(o.flows))e.add(`$${r}`),e.add(r);if(o.aspects)for(let r of Object.keys(o.aspects))e.add(`~${r}`),e.add(r);if(o.states)for(let r of Object.keys(o.states))e.add(`#${r}`),e.add(r);}for(let{filePath:o,data:a}of t){let i=o?`${o}: `:"",r=[...k(a.components),...k(a.features)];for(let[c,p]of r){if(p.parent){let u=p.parent.replace(/^["']|["']$/g,""),d=u.replace(/^[#$^!~@%?&]/,"");!e.has(u)&&!e.has(d)&&s.push({type:"warning",message:`${i}Component "${c}" references parent "${u}" which is not defined in any .purpose file`,path:`components.${c}.parent`});}let f=[{field:"gates",refs:p.gates},{field:"signals",refs:p.signals},{field:"flows",refs:p.flows},{field:"components",refs:p.components},{field:"aspects",refs:p.aspects}];for(let{field:u,refs:d}of f)if(d)for(let g of d){let y=g.replace(/^[#$^!~@%?&]/,"");!e.has(g)&&!e.has(y)&&s.push({type:"warning",message:`${i}Symbol "${c}" references ${u} "${g}" which is not defined`,path:`components.${c}.${u}`});}}if(a.flows){if(Array.isArray(a.flows)){for(let c of a.flows)if(c?.steps)for(let p of c.steps){if(typeof p=="string"||!p?.component)continue;let f=p.component.replace(/^#/,"");!e.has(p.component)&&!e.has(f)&&s.push({type:"warning",message:`${i}Flow "${c.name}" step references "${p.component}" which is not defined`,path:`flows.${c.name}.steps`});}}else for(let[c,p]of Object.entries(a.flows))if(p?.steps)for(let f of p.steps){if(typeof f=="string"||!f?.component)continue;let u=f.component.replace(/^#/,"");!e.has(f.component)&&!e.has(u)&&s.push({type:"warning",message:`${i}Flow "${c}" step references "${f.component}" which is not defined`,path:`flows.${c}.steps`});}}}return {valid:s.filter(o=>o.type==="error").length===0,issues:s}}var ze={visualizerPort:42195,watcherPort:42196,autoConnect:true};async function R(t){let s=b.resolve(t),e=b.dirname(s);if(!P.existsSync(s))throw new Error(`Gate config not found: ${s}`);let o=P.readFileSync(s,"utf8"),a=z.load(o);if(!a.version)throw new Error('Gate config missing required "version" field');let i=[],r=a,c=a.gates||r.portals;if(c)for(let[f,u]of Object.entries(c)){let d=f.startsWith("^")?f.slice(1):f;i.push(L(d,u));}if(a.include)for(let f of a.include){let u=b.join(e,f),d=await glob(u.replace(/\\/g,"/"));for(let g of d){let y=await Oe(g);i.push(...y);}}let p=[];if(a.flows)for(let[f,u]of Object.entries(a.flows))p.push(Fe(f,u));return {version:a.version,gates:i,flows:p,settings:{dev:{...ze,...a.settings?.dev}}}}async function Oe(t){let s=P.readFileSync(t,"utf8"),e=z.load(s);if(e.id){let o=e.id,a=o.startsWith("^")?o.slice(1):o;return [L(a,e)]}if(e.gates){let o=[];for(let[a,i]of Object.entries(e.gates)){let r=a.startsWith("^")?a.slice(1):a;o.push(L(r,i));}return o}return []}function L(t,s){let e=[];if(s.locks)for(let a of s.locks)e.push(Re(a));let o=[];if(s.prizes)for(let a of s.prizes)o.push(Ee(a));return {id:t,description:s.description,locks:e,prizes:o,position:s.position}}function Re(t){let s=t,e=[];if(s.keys){for(let o of s.keys)if(typeof o=="string")e.push({expression:o});else if(o.expression){let a=o;e.push({expression:a.expression,description:a.description});}}return {id:s.id,description:s.description,keys:e,mode:s.mode||"all"}}function Ee(t){let s=t;return {id:s.id,oneTime:s.oneTime??false,metadata:s.metadata}}function Fe(t,s){return {id:t,description:s.description,gates:s.gates||[],forkable:s.forkable}}async function se(t){let s=b.resolve(t);return await glob("**/portal.yaml",{cwd:s,absolute:true,ignore:["**/node_modules/**","**/dist/**","**/.git/**"]})}function ot(t){if(t instanceof z.YAMLException){let s=(t.reason||"").toLowerCase();return s.includes("duplicated mapping key")||s.includes("duplicate mapping key")?{errorClass:"duplicate-key",detail:"duplicate mapping key"}:["unexpected","expected","bad indentation","mapping values","cannot read a block mapping entry","end of the stream","while scanning","while parsing"].some(o=>s.includes(o))?{errorClass:"syntax",detail:"yaml syntax error"}:{errorClass:"other",detail:"yaml parse error"}}return {errorClass:"other",detail:"yaml parse error"}}var Te=z$1.object({x:z$1.number(),y:z$1.number()}),Le=z$1.object({x:z$1.number(),y:z$1.number(),zoom:z$1.number()}),ne=z$1.object({path:z$1.string(),include:z$1.array(z$1.string()).optional(),exclude:z$1.array(z$1.string()).optional()}),ae=z$1.object({id:z$1.string(),symbol:z$1.string(),type:z$1.enum(["feature","component","flow","state","aspect","gate","signal","idea"]),content:z$1.string().optional(),position:Te,tags:z$1.array(z$1.string()).optional(),created:z$1.string(),modified:z$1.string().optional()}),ie=z$1.object({from:z$1.string(),to:z$1.string(),label:z$1.string().optional(),type:z$1.string().optional()}),Me=z$1.object({id:z$1.string(),name:z$1.string(),nodes:z$1.array(z$1.string()),color:z$1.string().optional()}),ce=z$1.object({viewport:Le,groups:z$1.array(Me).optional()}),Ge=z$1.object({nodes:z$1.array(ae),connections:z$1.array(ie),layout:ce}),We=z$1.object({id:z$1.string(),name:z$1.string(),timestamp:z$1.string(),description:z$1.string().optional(),state:Ge});z$1.object({version:z$1.string(),metadata:z$1.object({name:z$1.string(),created:z$1.string(),modified:z$1.string()}),sources:z$1.object({purpose:z$1.array(ne).optional(),portal:z$1.array(ne).optional()}),nodes:z$1.array(ae),connections:z$1.array(ie),layout:ce,snapshots:z$1.array(We).optional()});async function Ye(t,s){let e=[],o=[],a=[],i=[];if(t.sources.purpose)for(let p of t.sources.purpose){let f=b.resolve(s,p.path);try{let u=await K(f);a.push(...u.map(m=>m.filePath));let d=U(u);for(let[m,{item:h,filePath:$}]of d){let C=["feature",...h.tags||[]];e.push(w({id:`purpose-feature-${m}`,symbol:`#${m}`,type:"component",source:"purpose",filePath:$,data:h,description:h.description,tags:C,componentType:h.type,parentSymbol:h.parent,anchors:h.anchors?.map(ue=>M(ue))}));}let g=q(u);for(let[m,{item:h,filePath:$}]of g)e.push(w({id:`purpose-component-${m}`,symbol:`#${m}`,type:"component",source:"purpose",filePath:$,data:h,description:h.description,tags:h.tags,componentType:h.type,parentSymbol:h.parent,anchors:h.anchors?.map(C=>M(C))}));let y=Z(u);for(let[m,{item:h,filePath:$}]of y)e.push(w({id:`purpose-gate-${m}`,symbol:`^${m}`,type:"gate",source:"purpose",filePath:$,data:h,description:h.description}));let S=X(u);for(let[m,{item:h,filePath:$}]of S)e.push(w({id:`purpose-state-${m}`,symbol:`#${m}`,type:"component",source:"purpose",filePath:$,data:h,description:h.description,tags:["state"]}));let G=H(u);for(let[m,{item:h,filePath:$}]of G)e.push(w({id:`purpose-flow-${m}`,symbol:`$${m}`,type:"flow",source:"purpose",filePath:$,data:h,description:h.description}));let pe=J(u);for(let[m,{item:h,filePath:$}]of pe)e.push(w({id:`purpose-signal-${m}`,symbol:`!${m}`,type:"signal",source:"purpose",filePath:$,data:h,description:h.description}));let fe=Q(u);for(let[m,{item:h,filePath:$}]of fe)e.push(w({id:`purpose-aspect-${m}`,symbol:`~${m}`,type:"aspect",source:"purpose",filePath:$,data:h,description:h.description,anchors:h.anchors?.map(C=>M(C)),appliesTo:h["applies-to"],tags:h.tags,enforcement:h.enforcement}));let le=ee(u),W=new Set(e.map(m=>m.symbol));for(let m of le)W.has(m.symbol)||(W.add(m.symbol),e.push(w({id:`purpose-ref-${m.type}-${m.symbol.slice(1)}`,symbol:m.symbol,type:m.type,source:"purpose",filePath:m.filePath,data:{referencedFrom:m.sourceSymbol},description:`Referenced from ${m.sourceSymbol}`})));}catch(u){o.push({source:"purpose",filePath:f,message:u.message});}}if(t.sources.portal)for(let p of t.sources.portal){let f=b.resolve(s,p.path);try{let u;if(f.endsWith(".yaml")||f.endsWith(".yml"))u=await R(f),i.push(f);else {let d=await se(f);if(i.push(...d),d.length>0){u=await R(d[0]);for(let g=1;g<d.length;g++){let y=await R(d[g]);u.gates.push(...y.gates),u.flows.push(...y.flows);}}else continue}for(let d of u.gates){e.push(Be(d,f));for(let g of d.prizes)e.push(w({id:`gate-signal-${d.id}-${g.id}`,symbol:`!${g.id}`,type:"signal",source:"portal",filePath:f,data:g,description:`Signal from gate ${d.id}`}));}for(let d of u.flows)e.push(Ve(d,f));}catch(u){o.push({source:"portal",filePath:f,message:u.message});}}for(let p of t.nodes){let f=p.tags?.includes("idea");if(!p.content&&!f){let u=e.find(d=>d.symbol===p.symbol);if(u){u.position=p.position,u.tags=p.tags;continue}}e.push(w({id:p.id,symbol:p.symbol,type:p.type,source:"premise",filePath:".premise",data:p,description:p.content,position:p.position,tags:p.tags,created:p.created,modified:p.modified}));}Ne(e);let r=new Map;for(let p of e){let f=r.get(p.symbol)||[];f.includes(p.filePath)||f.push(p.filePath),r.set(p.symbol,f);}let c=[];for(let[p,f]of r)f.length>1&&c.push({symbol:p,files:f});return {symbols:e,purposeFiles:a,portalFiles:i,errors:o,timestamp:Date.now(),...c.length>0?{duplicateSymbols:c}:{}}}function w(t){return {...t,data:t.data??null,references:t.references??[],referencedBy:t.referencedBy??[]}}function Be(t,s){let e=t.id.startsWith("^")?t.id.slice(1):t.id;return w({id:`gate-${e}`,symbol:`^${e}`,type:"gate",source:"portal",filePath:s,data:t,description:t.description,position:t.position})}function Ve(t,s){return w({id:`gate-flow-${t.id}`,symbol:`$${t.id}`,type:"flow",source:"portal",filePath:s,data:t,description:t.description})}function M(t){let s=t.lastIndexOf(":");if(s===-1||s===t.length-1)return {path:t,lines:0,raw:t};let e=t.slice(s+1),o=t.slice(0,s);if(!/^[\d,\- ]+$/.test(e))return {path:t,lines:0,raw:t};if(e.includes("-")){let[a,i]=e.split("-").map(Number);return {path:o,lines:[a,i],raw:t}}else if(e.includes(",")){let a=e.split(",").map(Number);return {path:o,lines:a,raw:t}}else return {path:o,lines:Number(e),raw:t}}var _e=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);function Ne(t){let s=new Map(t.map(e=>[e.symbol,e]));for(let e of t){let o=JSON.stringify(e.data),a=/(?:\?[@#$%~^!]|[@#$%~^!?])[a-zA-Z][\w-]*/g,i=(o.match(a)||[]).filter(r=>!_e.has(r));for(let r of i)if(r!==e.symbol&&s.has(r)){e.references.includes(r)||e.references.push(r);let c=s.get(r);c&&!c.referencedBy.includes(e.symbol)&&c.referencedBy.push(e.symbol);}}}async function pt(t){let s={metadata:{name:b.basename(t),created:new Date().toISOString(),modified:new Date().toISOString()},sources:{purpose:[{path:"./"}],portal:[{path:"./"}]},nodes:[]};return Ye(s,t)}function Ke(){return {entries:new Map,byType:new Map,bySource:new Map,timestamp:0}}function ft(t){let s=Ke();s.timestamp=t.timestamp;for(let e of t.symbols)s.entries.set(e.id,e),s.byType.has(e.type)||s.byType.set(e.type,[]),s.byType.get(e.type).push(e),s.bySource.has(e.source)||s.bySource.set(e.source,[]),s.bySource.get(e.source).push(e);return s}function E(t,s){for(let e of t.entries.values())if(e.symbol===s)return e}function Ue(t,s){return t.byType.get(s)||[]}function lt(t,s){let e=s.toLowerCase(),o=[];for(let a of t.entries.values()){if(a.symbol.toLowerCase().includes(e)){o.push(a);continue}if(a.description?.toLowerCase().includes(e)){o.push(a);continue}if(a.tags?.some(i=>i.toLowerCase().includes(e))){o.push(a);continue}if(a.componentType?.toLowerCase().includes(e)){o.push(a);continue}}return o}function ut(t,s){let e=E(t,s);return e?e.referencedBy.map(o=>E(t,o)).filter(o=>o!==void 0):[]}function dt(t,s){let e=E(t,s);return e?e.references.map(o=>E(t,o)).filter(o=>o!==void 0):[]}function mt(t){let s={component:0,flow:0,gate:0,signal:0,aspect:0};for(let[e,o]of t.byType)e in s&&(s[e]=o.length);return s}function ht(t){return Array.from(t.entries.values())}function qe(t,s,e){if(b.isAbsolute(t))return {resolvedPath:t,baseUsed:"absolute",exists:P.existsSync(t)};let o=b.join(e,t);if(P.existsSync(o))return {resolvedPath:o,baseUsed:"project-root",exists:true};let a=b.resolve(s,t);return P.existsSync(a)?{resolvedPath:a,baseUsed:"purpose-dir",exists:true}:{resolvedPath:o,baseUsed:"project-root",exists:false}}function gt(t,s,e){if(b.isAbsolute(t)){let i=P.existsSync(t);return {rootResolves:i,purposeResolves:i,mismatch:false}}let o=P.existsSync(b.join(e,t)),a=P.existsSync(b.resolve(s,t));return {rootResolves:o,purposeResolves:a,mismatch:o!==a}}function Ze(t,s){return t.includes("*")?new RegExp("^"+t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")+"$").test(s):t===s}function yt(t,s,e){let o=[],a=Ue(t,"aspect"),i=new Set;for(let r of a){let c=r.appliesTo||[];if(c.length!==0)for(let p of c)for(let f of s){if(!Ze(p,f))continue;let u=r.anchors||[];if(u.length===0){let d=`${r.symbol}::__no-anchors__`;i.has(d)||(i.add(d),o.push({aspectSymbol:r.symbol,anchorRaw:null,kind:"no-anchors"}));}else {let d=r.filePath?b.isAbsolute(r.filePath)?r.filePath:b.resolve(e,r.filePath):e,g=r.filePath?b.dirname(d):e;for(let y of u){let S=`${r.symbol}::${y.raw}`;if(i.has(S))continue;qe(y.path,g,e).exists||(i.add(S),o.push({aspectSymbol:r.symbol,anchorRaw:y.raw,kind:"missing-file"}));}}}}return o}
3
- export{ke as a,je as b,He as c,Ae as d,Qe as e,et as f,R as g,ot as h,pt as i,ft as j,E as k,Ue as l,lt as m,ut as n,dt as o,mt as p,ht as q,qe as r,gt as s,yt as t};
@@ -1,93 +0,0 @@
1
- #!/usr/bin/env node
2
- import {f,a,o,z}from'./chunk-2KK4JQ55.js';import {t}from'./chunk-M7JHVVDW.js';import {a as a$2,b as b$4,c as c$1}from'./chunk-M4UMM6DC.js';import {j,b as b$2,a as a$5}from'./chunk-GRZQIKST.js';import {b as b$1,a as a$4}from'./chunk-EK4ZRIFJ.js';import {a as a$1,b as b$3}from'./chunk-4TXOVRWD.js';import {H,m}from'./chunk-D6BSCELB.js';import {a as a$3,q as q$1}from'./chunk-K6TLYNRQ.js';import {c,b,d}from'./chunk-5TAVYPOV.js';import*as S from'fs';import*as T from'path';import*as D from'crypto';import {execSync}from'child_process';import*as C from'js-yaml';import*as B from'os';import te from'sql.js';var At={};c(At,{contentSearch:()=>Zt,detectFileRename:()=>xt,generateFingerprint:()=>Rt,levenshteinDistance:()=>bt,levenshteinSimilarity:()=>Z,searchSiblingFiles:()=>Lt,slidingWindowSearch:()=>Y});function Rt(e){let t=e.split(`
3
- `).filter(n=>n.trim()!=="");return {firstLine:G(t[0]||""),lastLine:G(t[t.length-1]||""),lineCount:t.length,structuralHash:_t(t)}}function _t(e){let t=e.map(n=>n.trim()).filter(n=>St.test(n)).map(n=>{let r=n.match(St);return r?r[1].trim():""}).join("|");return D.createHash("sha256").update(t).digest("hex").slice(0,16)}function G(e){return e.trim().replace(/\s+/g," ").toLowerCase()}function bt(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;e.length>t.length&&([e,t]=[t,e]);let n=e.length,r=t.length;if(n>5e3||r>5e3)return Math.abs(n-r);let s=new Array(n+1),i=new Array(n+1);for(let a=0;a<=n;a++)s[a]=a;for(let a=1;a<=r;a++){i[0]=a;for(let c=1;c<=n;c++){let o=e[c-1]===t[a-1]?0:1;i[c]=Math.min(s[c]+1,i[c-1]+1,s[c-1]+o);}[s,i]=[i,s];}return s[n]}function Z(e,t){if(e.length===0&&t.length===0)return 1;let n=Math.max(e.length,t.length);return 1-bt(e,t)/n}function Y(e,t,n,r=3){let{lineCount:s}=t,i=Math.max(1,Math.floor(s*.8)),a=Math.ceil(s*1.2),c=[],o=Q(n);for(let l of [s,i,a])if(!(l>e.length))for(let u=0;u<=e.length-l;u++){let f=e.slice(u,u+l),y=Qt(f,t,o);if(y>=.5){let h=f.join(`
4
- `);c.push({windowStart:u+1,windowEnd:u+l,similarity:Z(Q(h),o),score:y});}}let d=new Map;for(let l of c){let u=d.get(l.windowStart);(!u||l.score>u.score)&&d.set(l.windowStart,l);}return Array.from(d.values()).sort((l,u)=>u.score-l.score).slice(0,r)}function Qt(e,t,n){let r=e.filter(f=>f.trim()!=="");if(r.length===0)return 0;let s=0,i=G(r[0]),a=G(r[r.length-1]),c=0;i===t.firstLine&&(c+=.5),a===t.lastLine&&(c+=.5),s+=c*qt,_t(r)===t.structuralHash&&(s+=Kt);let d=r.join(`
5
- `),l=Z(Q(d),n);l>=.8&&(s+=(l-.8)/.2*Vt);let u=r.length/t.lineCount;if(u>=.8&&u<=1.2){let f=1-Math.abs(1-u)/.2;s+=f*Jt;}return s}function Q(e){return e.split(`
6
- `).map(t=>t.trim()).filter(t=>t!=="").join(`
7
- `)}function xt(e,t){try{let n=execSync(`git log --follow --diff-filter=R --name-status --format="" -- "${t}"`,{cwd:e,encoding:"utf8",timeout:5e3}).trim();if(!n)return null;let r=n.split(`
8
- `);for(let s of r){let i=s.split(" ");if(i.length>=3&&i[0].startsWith("R"))return i[2]}return null}catch{return null}}function Lt(e,t,n,r,s=10){let i=T.isAbsolute(t)?t:T.join(e,t);if(!S.existsSync(i))return [];let a=[];try{let c=S.readdirSync(i).filter(o=>!o.startsWith(".")&&S.statSync(T.join(i,o)).isFile()).slice(0,s);for(let o of c)try{let l=S.readFileSync(T.join(i,o),"utf8").split(`
9
- `),u=Y(l,n,r,1);if(u.length>0&&u[0].score>=.7){let f=T.relative(e,T.join(i,o));a.push({file:f,score:u[0].score,start:u[0].windowStart,end:u[0].windowEnd});}}catch{}}catch{return []}return a.sort((c,o)=>o.score-c.score)}function Zt(e,t,n,r=true){let s=Rt(n),i=T.isAbsolute(t)?t:T.join(e,t);if(S.existsSync(i)){let l=S.readFileSync(i,"utf8").split(`
10
- `),u=Y(l,s,n);if(u.length>0){let f=u[0];return {found:f.score>=.7,score:f.score,suggestedStart:f.windowStart,suggestedEnd:f.windowEnd,similarity:f.similarity}}}let a=xt(e,t);if(a){let d=T.join(e,a);if(S.existsSync(d)){let u=S.readFileSync(d,"utf8").split(`
11
- `),f=Y(u,s,n);if(f.length>0&&f[0].score>=.7)return {found:true,score:f[0].score,suggestedStart:f[0].windowStart,suggestedEnd:f[0].windowEnd,suggestedPath:a,similarity:f[0].similarity}}}let c=T.dirname(t),o=Lt(e,c,s,n);if(o.length>0&&o[0].score>=.7){let d=o[0];return {found:true,score:d.score,suggestedStart:d.start,suggestedEnd:d.end,suggestedPath:d.file!==t?d.file:void 0,similarity:d.score}}return {found:false,score:0}}var St,qt,Kt,Vt,Jt,It=b(()=>{St=/^\s*(function |class |if |else |for |while |switch |case |return |export |import |const |let |var |async |await |try |catch |throw |struct |enum |protocol |guard |def |fn )/;qt=.4,Kt=.3,Vt=.2,Jt=.1;});var $t=300*1e3,W=null;function Tt(){W=null;}function O(e,t){return S.existsSync(T.join(e,t))}function M(e,t){return S.existsSync(T.join(e,t))}function Bt(e,t,n){let r=e;try{if(!S.existsSync(r))return !1;let s=S.readdirSync(r,{withFileTypes:!0});for(let i of s){if(i.isFile()&&i.name.endsWith(t))return !0;if(i.isDirectory())try{if(S.readdirSync(T.join(r,i.name)).some(c=>c.endsWith(t)))return !0}catch{}}}catch{}return false}var Gt={wisdom:e=>O(e,".paradigm/wisdom"),history:e=>O(e,".paradigm/history"),lore:e=>O(e,".paradigm/lore"),habits:e=>M(e,".paradigm/habits.yaml"),sentinel:e=>{try{let t=T.join(e,".paradigm","config.yaml");return S.existsSync(t)?S.readFileSync(t,"utf-8").includes("sentinel"):!1}catch{return false}},flows:e=>M(e,".paradigm/flow-index.json")||M(e,".paradigm/flows.yaml"),fixtures:e=>M(e,".paradigm/fixtures.yaml"),orchestration:e=>M(e,".paradigm/agents.yaml"),tasks:e=>O(e,".paradigm/tasks"),assessment:e=>O(e,".paradigm/lore"),personas:e=>Bt(e,".persona"),protocols:e=>O(e,".paradigm/protocols"),symphony:()=>{let e=T.join(B.homedir(),".paradigm","score");return S.existsSync(e)},university:e=>O(e,".paradigm/university"),agents:e=>{let t=T.join(B.homedir(),".paradigm","agents");return O(e,".paradigm/agents")||S.existsSync(t)},"aspect-graph":e=>M(e,".paradigm/aspect-graph.db"),pan:e=>M(e,".pan")||M(e,"nevr.yaml"),notebooks:e=>{let t=T.join(B.homedir(),".paradigm","notebooks");return O(e,".paradigm/notebooks")||S.existsSync(t)}},Et=class{modules=new Map;activatedAdvanced=new Set;rootDir;constructor(t){this.rootDir=t;}register(t){this.modules.set(t.key,t);}registerAll(t){for(let n of t)this.register(n);}detectActiveFeatures(){if(W&&Date.now()-W.timestamp<$t)return W.features;let t=new Set;for(let[n,r]of this.modules){if(r.tier==="core"){t.add(n);continue}if(r.tier==="advanced"){this.activatedAdvanced.has(n)&&t.add(n);continue}let s=r.detect||Gt[n];if(s)try{s(this.rootDir)&&t.add(n);}catch{}else t.add(n);}return W={features:t,timestamp:Date.now()},t}getActiveTools(){let t=this.detectActiveFeatures(),n=[];for(let[r,s]of this.modules)t.has(r)&&n.push(...s.getToolsList());return n}activateAdvanced(t){let n=this.modules.get(t);return !n||n.tier!=="advanced"?null:(this.activatedAdvanced.add(t),n.getToolsList())}getAvailableAdvanced(){let t=[];for(let[n,r]of this.modules)r.tier==="advanced"&&!this.activatedAdvanced.has(n)&&t.push({key:n,toolCount:r.getToolsList().length});return t}async dispatch(t,n,r,s){let i=this.detectActiveFeatures();for(let[a,c]of this.modules)if(i.has(a))try{let o=await c.handleTool(t,n,r,s);if(o.handled)return o}catch(o){return {handled:true,text:JSON.stringify({error:`Tool handler error in module "${a}"`,message:o.message},null,2)}}return null}get size(){return this.modules.size}getRegistryInfo(){let t=this.detectActiveFeatures(),n={core:0,feature:0,advanced:0};for(let r of this.modules.values())n[r.tier]++;return {total:this.modules.size,byTier:n,activeFeatures:[...t],availableAdvanced:[...this.modules.entries()].filter(([r,s])=>s.tier==="advanced"&&!this.activatedAdvanced.has(r)).map(([r])=>r)}}};var tt=null;async function ee(){return tt||(tt=await te()),tt}var ne=[`CREATE TABLE IF NOT EXISTS aspects (
12
- id TEXT PRIMARY KEY,
13
- description TEXT NOT NULL,
14
- category TEXT DEFAULT 'rule',
15
- severity TEXT DEFAULT 'medium',
16
- value TEXT,
17
- enforcement TEXT,
18
- defined_in TEXT NOT NULL,
19
- tags TEXT,
20
- created_at TEXT NOT NULL,
21
- updated_at TEXT NOT NULL
22
- )`,`CREATE TABLE IF NOT EXISTS anchors (
23
- id INTEGER PRIMARY KEY AUTOINCREMENT,
24
- aspect_id TEXT NOT NULL REFERENCES aspects(id) ON DELETE CASCADE,
25
- file_path TEXT NOT NULL,
26
- start_line INTEGER NOT NULL,
27
- end_line INTEGER NOT NULL,
28
- content_hash TEXT,
29
- normalized_hash TEXT,
30
- materialized_at_commit TEXT,
31
- last_verified TEXT,
32
- drifted INTEGER DEFAULT 0
33
- )`,"CREATE INDEX IF NOT EXISTS idx_anchors_file ON anchors(file_path)","CREATE INDEX IF NOT EXISTS idx_anchors_aspect ON anchors(aspect_id)",`CREATE TABLE IF NOT EXISTS edges (
34
- id INTEGER PRIMARY KEY AUTOINCREMENT,
35
- source TEXT NOT NULL,
36
- target TEXT NOT NULL,
37
- relation TEXT NOT NULL,
38
- weight REAL DEFAULT 1.0,
39
- origin TEXT DEFAULT 'explicit',
40
- created_at TEXT NOT NULL
41
- )`,"CREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source)","CREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target)",`CREATE TABLE IF NOT EXISTS lore_links (
42
- aspect_id TEXT NOT NULL,
43
- lore_id TEXT NOT NULL,
44
- PRIMARY KEY (aspect_id, lore_id)
45
- )`,`CREATE TABLE IF NOT EXISTS search_log (
46
- id INTEGER PRIMARY KEY AUTOINCREMENT,
47
- query TEXT NOT NULL,
48
- results_returned TEXT NOT NULL,
49
- selected_result TEXT,
50
- timestamp TEXT NOT NULL
51
- )`,"CREATE INDEX IF NOT EXISTS idx_search_query ON search_log(query)",`CREATE TABLE IF NOT EXISTS search_weights (
52
- query_normalized TEXT NOT NULL,
53
- aspect_id TEXT NOT NULL,
54
- weight REAL DEFAULT 1.0,
55
- hit_count INTEGER DEFAULT 1,
56
- last_hit TEXT NOT NULL,
57
- PRIMARY KEY (query_normalized, aspect_id)
58
- )`,`CREATE TABLE IF NOT EXISTS heatmap (
59
- aspect_id TEXT NOT NULL,
60
- access_type TEXT NOT NULL,
61
- count INTEGER DEFAULT 0,
62
- last_accessed TEXT NOT NULL,
63
- PRIMARY KEY (aspect_id, access_type)
64
- )`],se=["ALTER TABLE anchors ADD COLUMN original_content TEXT",`CREATE TABLE IF NOT EXISTS anchor_history (
65
- id INTEGER PRIMARY KEY AUTOINCREMENT,
66
- anchor_id INTEGER NOT NULL,
67
- action TEXT NOT NULL,
68
- old_start INTEGER,
69
- old_end INTEGER,
70
- new_start INTEGER,
71
- new_end INTEGER,
72
- old_path TEXT,
73
- new_path TEXT,
74
- confidence REAL,
75
- commit_hash TEXT,
76
- healed_at TEXT NOT NULL
77
- )`],re="CREATE VIRTUAL TABLE IF NOT EXISTS aspects_fts USING fts5(id, description, enforcement, tags)";function I(e,t,n){let r=e.prepare(t);n&&n.length>0&&r.bind(n);let s=[];for(;r.step();)s.push(r.getAsObject());return r.free(),s}function oe(e,t,n){let r=e.prepare(t);n&&n.length>0&&r.bind(n);let s=null;return r.step()&&(s=r.getAsObject()),r.free(),s}async function Nt(e){let t=await ee(),n=T.join(e,".paradigm"),r=T.join(n,"aspect-graph.db"),s;if(S.existsSync(r)){let i=S.readFileSync(r);s=new t.Database(i);}else S.existsSync(n)||S.mkdirSync(n,{recursive:true}),s=new t.Database;for(let i of ne)s.run(i);try{s.run(re);}catch{}for(let i of se)try{s.run(i);}catch{}return s}function Ot(e,t){if(t){let n=T.join(t,".paradigm");S.existsSync(n)||S.mkdirSync(n,{recursive:true});let r=T.join(n,"aspect-graph.db"),s=e.export();S.writeFileSync(r,Buffer.from(s));}e.close();}function vt(e,t,n){let r=t.filter(a=>a.type==="aspect"),s=new Date().toISOString(),i=null;try{i=execSync("git rev-parse HEAD",{cwd:n,encoding:"utf8"}).trim();}catch{}e.run("DELETE FROM anchors"),e.run("DELETE FROM edges"),e.run("DELETE FROM aspects");try{e.run("DELETE FROM aspects_fts");}catch{}for(let a of r){let c=a.data??{},o=le(c,a),d=de(c,a),l=c.value!=null?String(c.value):null,u=a.enforcement??(c.enforcement!=null?String(c.enforcement):null),f=a.tags?JSON.stringify(a.tags):null;if(e.run(`INSERT INTO aspects (id, description, category, severity, value, enforcement, defined_in, tags, created_at, updated_at)
78
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a.symbol,a.description??"",o,d,l,u,a.filePath,f,a.created??s,a.modified??s]),a.anchors)for(let h of a.anchors){let{startLine:_,endLine:N}=Ft(h),L=ce();e.run(`INSERT INTO anchors (aspect_id, file_path, start_line, end_line, content_hash, normalized_hash, materialized_at_commit, last_verified, original_content)
79
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[a.symbol,h.path,_,N,L.exact,L.normalized,i,s,L.normalizedContent]);}let y=c.edges;if(Array.isArray(y))for(let h of y)e.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
80
- VALUES (?, ?, ?, ?, ?, ?)`,[h.source??a.symbol,h.target??"",h.relation??"related-to",h.weight??1,h.origin??"explicit",s]);if(a.appliesTo)for(let h of a.appliesTo)e.run(`INSERT INTO edges (source, target, relation, weight, origin, created_at)
81
- VALUES (?, ?, ?, ?, ?, ?)`,[a.symbol,h,"related-to",.5,"inferred",s]);try{e.run(`INSERT INTO aspects_fts (id, description, enforcement, tags)
82
- VALUES (?, ?, ?, ?)`,[a.symbol,a.description??"",u??"",f??""]);}catch{}}}function He(e,t){return oe(e,"SELECT * FROM aspects WHERE id = ?",[t])}function Ue(e,t){return I(e,"SELECT * FROM anchors WHERE aspect_id = ?",[t])}function Xe(e,t){return I(e,"SELECT * FROM edges WHERE source = ?",[t])}function We(e,t){return I(e,"SELECT * FROM edges WHERE target = ?",[t])}function ze(e,t){return I(e,"SELECT * FROM edges WHERE source = ? OR target = ?",[t,t])}function $e(e,t,n){let r=new Date().toISOString();e.run(`INSERT INTO heatmap (aspect_id, access_type, count, last_accessed)
83
- VALUES (?, ?, 1, ?)
84
- ON CONFLICT(aspect_id, access_type)
85
- DO UPDATE SET count = count + 1, last_accessed = ?`,[t,n,r,r]);}function Be(e,t=20,n){return n?I(e,"SELECT * FROM heatmap WHERE access_type = ? ORDER BY count DESC LIMIT ?",[n,t]):I(e,"SELECT * FROM heatmap ORDER BY count DESC LIMIT ?",[t])}function Ge(e,t,n,r=true,s=.7,i=.85){let a=n?I(e,"SELECT * FROM anchors WHERE aspect_id = ?",[n]):I(e,"SELECT * FROM anchors"),c=[];for(let o of a){let l=I(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id])[0]?.defined_in,u=l?T.dirname(T.isAbsolute(l)?l:T.resolve(t,l)):t,f=H(o.file_path,u,t),y=f.resolvedPath;if(!f.exists){c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"missing",resolvedBy:"none",exists:false,drifted:true});continue}try{let _=S.readFileSync(y,"utf8").split(`
86
- `),N=Math.max(0,o.start_line-1),L=Math.min(_.length,o.end_line),P=_.slice(N,L).join(`
87
- `),j=D.createHash("sha256").update(P).digest("hex");if(o.content_hash!=null&&j===o.content_hash){c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1}),o.drifted===1&&e.run("UPDATE anchors SET drifted = 0 WHERE id = ?",[o.id]);continue}let U=D.createHash("sha256").update(nt(P)).digest("hex");if(o.normalized_hash!=null&&U===o.normalized_hash){e.run("UPDATE anchors SET content_hash = ?, drifted = 0 WHERE id = ?",[j,o.id]),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"cosmetic",resolvedBy:"normalized-hash",exists:!0,drifted:!1});continue}if(o.content_hash==null&&o.normalized_hash==null){e.run("UPDATE anchors SET content_hash = ?, normalized_hash = ?, drifted = 0 WHERE id = ?",[j,U,o.id]),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"clean",resolvedBy:"exact-hash",exists:!0,drifted:!1});continue}let H=!1;if(o.materialized_at_commit){let m=ae(t,o.file_path,o.materialized_at_commit,o.start_line,o.end_line);if(m){let g=Math.max(0,m.currentStart-1),p=Math.min(_.length,m.currentEnd),E=_.slice(g,p).join(`
88
- `),F=D.createHash("sha256").update(E).digest("hex");if(o.content_hash!=null&&F===o.content_hash){let k=r;if(k){e.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[m.currentStart,m.currentEnd,o.id]);let X=I(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id]);X.length>0&&et(t,X[0].defined_in,o.file_path,o.start_line,o.end_line,m.currentStart,m.currentEnd);}c.push({aspectId:o.aspect_id,path:o.file_path,startLine:k?m.currentStart:o.start_line,endLine:k?m.currentEnd:o.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:m.currentStart,suggestedEnd:m.currentEnd,autoHealed:k}),H=!0;}else {let k=D.createHash("sha256").update(nt(E)).digest("hex");if(o.normalized_hash!=null&&k===o.normalized_hash){if(r){let X=D.createHash("sha256").update(E).digest("hex");e.run("UPDATE anchors SET start_line = ?, end_line = ?, content_hash = ?, drifted = 0 WHERE id = ?",[m.currentStart,m.currentEnd,X,o.id]);let z=I(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id]);z.length>0&&et(t,z[0].defined_in,o.file_path,o.start_line,o.end_line,m.currentStart,m.currentEnd);}c.push({aspectId:o.aspect_id,path:o.file_path,startLine:r?m.currentStart:o.start_line,endLine:r?m.currentEnd:o.end_line,status:"shifted",resolvedBy:"git-line-mapping",exists:!0,drifted:!1,suggestedStart:m.currentStart,suggestedEnd:m.currentEnd,autoHealed:r}),H=!0;}}}}if(H)continue;if(o.original_content){let{contentSearch:m}=(It(),d(At)),g=m(t,o.file_path,o.original_content,r);if(g.found&&g.score>=s){if(r&&g.score>=i&&!g.suggestedPath&&g.suggestedStart&&g.suggestedEnd){e.run("UPDATE anchors SET start_line = ?, end_line = ?, drifted = 0 WHERE id = ?",[g.suggestedStart,g.suggestedEnd,o.id]);try{e.run(`INSERT INTO anchor_history (anchor_id, action, old_start, old_end, new_start, new_end, confidence, healed_at)
89
- VALUES (?, 'relocated', ?, ?, ?, ?, ?, ?)`,[o.id,o.start_line,o.end_line,g.suggestedStart,g.suggestedEnd,g.score,new Date().toISOString()]);}catch{}let E=I(e,"SELECT defined_in FROM aspects WHERE id = ?",[o.aspect_id]);E.length>0&&et(t,E[0].defined_in,o.file_path,o.start_line,o.end_line,g.suggestedStart,g.suggestedEnd),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:g.suggestedStart,endLine:g.suggestedEnd,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:g.similarity,suggestedStart:g.suggestedStart,suggestedEnd:g.suggestedEnd,autoHealed:!0,drifted:!1});continue}c.push({aspectId:o.aspect_id,path:g.suggestedPath||o.file_path,startLine:o.start_line,endLine:o.end_line,status:"relocated",resolvedBy:"content-search",exists:!0,similarity:g.similarity,suggestedStart:g.suggestedStart,suggestedEnd:g.suggestedEnd,autoHealed:!1,drifted:!0});continue}}e.run("UPDATE anchors SET drifted = 1 WHERE id = ?",[o.id]),c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"modified",resolvedBy:"none",exists:!0,currentContent:P,drifted:!0});}catch{c.push({aspectId:o.aspect_id,path:o.file_path,startLine:o.start_line,endLine:o.end_line,status:"modified",resolvedBy:"none",exists:true,drifted:true});}}return c}function Ft(e){let{lines:t}=e;return typeof t=="number"?{startLine:t,endLine:t}:Array.isArray(t)?t.length===2?{startLine:t[0],endLine:t[1]}:{startLine:Math.min(...t),endLine:Math.max(...t)}:{startLine:1,endLine:1}}function ie(e){let t=[],n=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm,r;for(;(r=n.exec(e))!==null;)t.push({oldStart:parseInt(r[1],10),oldCount:r[2]!==void 0?parseInt(r[2],10):1,newStart:parseInt(r[3],10),newCount:r[4]!==void 0?parseInt(r[4],10):1});return t}function ae(e,t,n,r,s){let i;try{i=execSync(`git diff ${n}..HEAD --unified=0 -- "${t}"`,{cwd:e,encoding:"utf8",timeout:5e3});}catch{return null}if(!i.trim())return {originalStart:r,originalEnd:s,currentStart:r,currentEnd:s};let a=ie(i),c=0;for(let o of a){if(o.oldStart+o.oldCount<=r){c+=o.newCount-o.oldCount;continue}if(o.oldStart<s)return null;break}return c===0?null:{originalStart:r,originalEnd:s,currentStart:r+c,currentEnd:s+c}}function et(e,t,n,r,s,i,a){let c=T.isAbsolute(t)?t:T.join(e,t);if(!S.existsSync(c))return false;try{let o=S.readFileSync(c,"utf8"),d=r===s?`${n}:${r}`:`${n}:${r}-${s}`,l=i===a?`${n}:${i}`:`${n}:${i}-${a}`;if(!o.includes(d))return !1;let u=o.replace(d,l);return S.writeFileSync(c,u,"utf8"),!0}catch{return false}}function nt(e){return e.split(`
90
- `).map(t=>t.trimEnd()).filter(t=>t.trim()!=="").map(t=>t.replace(/\s+/g," ")).join(`
91
- `)}function ce(e,t,n){return {exact:null,normalized:null,normalizedContent:null};}function le(e,t){if(typeof e.category=="string")return e.category;let n=(t.description??"").toLowerCase();return /\b(must|require|always)\b/.test(n)?"rule":/\b(decided|chose)\b/.test(n)?"decision":/\b(limit|cannot)\b/.test(n)?"constraint":/\b(set to|configured|value)\b/.test(n)?"configuration":"rule"}function de(e,t){if(typeof e.severity=="string")return e.severity;let n=t.tags??[];return n.includes("critical")?"critical":n.includes("security")||n.includes("compliance")?"high":"medium"}j();var ue=/L-\d{4}-\d{2}-\d{2}-\d{3}/g;async function kt(e,t){e.run("DELETE FROM lore_links");let n=await a$5(t);if(n.length===0)return 0;let r=fe(n),s=new Map;for(let d of n)s.set(d.id,d);let i=new Set,a=e.exec("SELECT id, enforcement FROM aspects");if(a.length>0){let{columns:d,values:l}=a[0],u=d.indexOf("id"),f=d.indexOf("enforcement");for(let y of l){let h=String(y[u]),_=y[f];if(_&&typeof _=="string"){let N=_.match(ue);if(N)for(let L of N)s.has(L)&&i.add(`${h}\0${L}`);}}}let c=e.exec("SELECT source, target FROM edges");if(c.length>0&&a.length>0){let d=pe(e,c);for(let[l,u]of d)for(let f of u){let y=r.get(f);if(y)for(let h of y)i.add(`${l}\0${h}`);}}if(i.size===0)return 0;let o=e.prepare("INSERT OR IGNORE INTO lore_links (aspect_id, lore_id) VALUES (?, ?)");try{for(let d of i){let[l,u]=d.split("\0");o.bind([l,u]),o.step(),o.reset();}}finally{o.free();}return i.size}async function Ke(e,t,n){let r=e.exec("SELECT lore_id FROM lore_links WHERE aspect_id = ?",[n]);if(r.length===0||r[0].values.length===0)return [];let s=r[0].values.map(i=>String(i[0]));return ge(t,s)}async function Mt(e,t){let n=await a$5(t);if(n.length===0)return 0;let r=e.exec("SELECT id FROM aspects"),s=new Set;if(r.length>0)for(let o of r[0].values)s.add(String(o[0]));if(s.size<2)return 0;let i=new Date().toISOString(),a=0,c=e.prepare(`INSERT OR IGNORE INTO edges (source, target, relation, weight, origin, created_at)
92
- VALUES (?, ?, 'related-to', 0.3, 'learned', ?)`);try{for(let o of n){if(!o.symbols_touched||o.symbols_touched.length<2)continue;let d=[];for(let l of o.symbols_touched){let u=l.startsWith("~")?l.slice(1):l;s.has(u)&&d.push(u);}for(let l=0;l<d.length;l++)for(let u=l+1;u<d.length;u++){let[f,y]=d[l]<d[u]?[d[l],d[u]]:[d[u],d[l]];c.bind([f,y,i]),c.step(),c.reset(),a++;}}}finally{c.free();}return a}function fe(e){let t=new Map;for(let n of e)if(n.symbols_touched)for(let r of n.symbols_touched){let s=t.get(r);s||(s=new Set,t.set(r,s)),s.add(n.id);}return t}function pe(e,t){let n=e.exec("SELECT id FROM aspects"),r=new Set;if(n.length>0)for(let d of n[0].values)r.add(String(d[0]));let s=new Map;if(t.length===0)return s;let{columns:i,values:a}=t[0],c=i.indexOf("source"),o=i.indexOf("target");for(let d of a){let l=String(d[c]),u=String(d[o]);if(r.has(l)){let f=s.get(l);f||(f=new Set,s.set(l,f)),f.add(u),f.add(`~${l}`);}if(r.has(u)){let f=s.get(u);f||(f=new Set,s.set(u,f)),f.add(l),f.add(`~${u}`);}}return s}async function ge(e,t){let n=new Set,r=[];for(let s of t){if(n.has(s))continue;n.add(s);let i=await b$2(e,s);i&&r.push(me(i));}return r}function me(e){return {id:e.id,title:e.title,summary:e.summary,timestamp:e.timestamp,symbolsTouched:e.symbols_touched}}var he="PARADIGM_STRICT";function q(){let e=process.env[he];if(e===void 0||e==="")return false;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}var Dt=new Set(["duplicate-key-detected"]);function ye(e){let t=e.trim();if(t.includes("/")||t.includes("\\")){let n=t.split(/[/\\]/);t=n[n.length-1]||"unknown";}return t.length>40&&(t=t.slice(0,40)),t||"unknown"}var K=class{transforms=new Map;record(t,n,r=1){let s=ye(n),i=`${t}::${s}`,a=this.transforms.get(i);a?a.count+=r:this.transforms.set(i,{kind:t,surface:s,count:r});}report(){let t=Array.from(this.transforms.values()).sort((r,s)=>r.kind!==s.kind?r.kind.localeCompare(s.kind):r.surface.localeCompare(s.surface)),n=t.filter(r=>Dt.has(r.kind)).reduce((r,s)=>r+s.count,0);return {reindex_ts:new Date().toISOString(),transformations:t,lossy_count:n,strict_mode:q()}}hasLossy(){for(let t of this.transforms.values())if(Dt.has(t.kind))return true;return false}totalCount(){let t=0;for(let n of this.transforms.values())t+=n.count;return t}};b$1();var Ee={"@":{category:"features",prefix:"@"},"#":{category:"components",prefix:"#"},"^":{category:"gates",prefix:"^"},$:{category:"flows",prefix:"$"},"&":{category:"integrations",prefix:"&"},"!":{category:"signals",prefix:"!"},"%":{category:"state",prefix:"%"}},Te={features:["src/features/","features/","app/","src/app/","src/modules/","modules/"],components:["src/components/","components/","src/lib/","lib/","src/ui/","ui/"],gates:["middleware/","src/middleware/","auth/","src/auth/","guards/","src/guards/"],flows:["flows/","src/flows/","workflows/","src/workflows/","sagas/","src/sagas/"],integrations:["integrations/","src/integrations/","external/","src/external/","vendors/"],signals:["events/","src/events/","handlers/","src/handlers/"],state:["stores/","src/stores/","state/","src/state/","reducers/","src/reducers/"]},Se={config:[".paradigm/config.yaml","package.json","tsconfig.json",".env.example"],entry:["src/index.ts","src/index.tsx","src/main.ts","src/main.tsx","index.ts","main.ts","src/app.ts","src/app.tsx"],types:["src/types/","types/","src/types.ts","types.ts"]},st={always:["node_modules/","dist/","build/",".git/",".next/",".nuxt/",".cache/","*.lock","*.log"],unless_testing:["**/*.test.ts","**/*.test.tsx","**/*.spec.ts","**/*.spec.tsx","__tests__/","test/","tests/"],unless_docs:["docs/","*.md","README*","CHANGELOG*"]};function hn(){return [{name:"paradigm_reindex",description:"Rebuild scan-index.json, navigator.yaml, and flow-index.json from .purpose files. Call after modifying paradigm files or at the end of a work session to ensure static index files are fresh. Returns counts of indexed symbols, files processed, and any errors. ~150 tokens.",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:false,destructiveHint:true},aliases:["rebuild","refresh","rescan","regenerate index","update index"]}]}async function yn(e,t,n,r){if(e!=="paradigm_reindex")return {handled:false,text:""};try{let s=await we(n.rootDir,n);await r(),f.clear(),Tt();let i=(s.integrityReport?.brokenReferences?.length||0)+(s.integrityReport?.duplicateSymbols?.length||0)+(s.componentAnchorIssues||0)+(s.crossFileIssues||0),a$1={success:!0,symbolCount:s.symbolCount,breakdown:s.breakdown,flowCount:s.flowCount,filesWritten:s.filesWritten.length,...s.aspectGraphStats?{aspects:s.aspectGraphStats.aspects,loreLinks:s.aspectGraphStats.loreLinks}:{},...s.protocolHealth?{protocols:s.protocolHealth.total,staleProtocols:s.protocolHealth.stale}:{},...i>0?{issues:i}:{}};s.consistency&&(a$1.consistency=s.consistency);let c=JSON.stringify(a$1,null,2);return a(c.length,e),{handled:!0,text:c}}catch(s){let i=JSON.stringify({error:s.message},null,2);return a(i.length,e),{handled:true,text:i}}}async function we(e,t$1){let n=[],r=new K,s;t$1?s=t$1.aggregation:s=await m(e);let i=t$1?.projectName||T.basename(e),a=T.join(e,".paradigm");S.existsSync(a)||S.mkdirSync(a,{recursive:true}),Re(e,r),_e(s.purposeFiles,r);let c=a$1({symbols:s.symbols,purposeFiles:s.purposeFiles,portalFiles:s.portalFiles},{projectName:i}),o$1=T.join(a,"scan-index.json");S.writeFileSync(o$1,b$3(c),"utf8"),n.push(".paradigm/scan-index.json");let d=be(e,s),l=T.join(a,"navigator.yaml");S.writeFileSync(l,C.dump(d,{indent:2,lineWidth:120,noRefs:true,sortKeys:false}),"utf8"),n.push(".paradigm/navigator.yaml");let u=Ne(e,s.purposeFiles),f=0;if(u&&Object.keys(u.flows).length>0){let p=T.join(a,"flow-index.json");S.writeFileSync(p,JSON.stringify(u,null,2),"utf8"),n.push(".paradigm/flow-index.json"),f=Object.keys(u.flows).length;}let y;try{let p=await Nt(e);vt(p,s.symbols,e);let E=await kt(p,e),F=await Mt(p,e),k=p.exec("SELECT COUNT(*) FROM aspects")[0]?.values[0]?.[0]??0,X=p.exec("SELECT COUNT(*) FROM anchors")[0]?.values[0]?.[0]??0,z=p.exec("SELECT COUNT(*) FROM edges")[0]?.values[0]?.[0]??0;Ot(p,e),n.push(".paradigm/aspect-graph.db"),y={aspects:k,anchors:X,edges:z,loreLinks:E};}catch{}let h=0;try{let p=await o(e);h=Object.keys(p.personas).length,h>0&&n.push(".paradigm/personas/index.yaml");}catch{}let _;try{let p=await z(e);p.health.total>0&&(_=p.health,n.push(".paradigm/protocols/index.yaml"));}catch{}let N;try{let p=T.join(e,".paradigm","university");if(S.existsSync(p)){let E=t(e);(E.totalContent>0||E.diplomaCount>0)&&(N={totalContent:E.totalContent,diplomaCount:E.diplomaCount},n.push(".paradigm/university/index.yaml"));}}catch{}let L;try{L=a$2(s,e);}catch{}let P;try{let p=b$4(s.symbols,e),E=p.missing+p.outOfBounds;E>0&&(P=E);}catch{}let j;try{j=c$1(s.purposeFiles,e);}catch{}let U;try{let p=[];for(let E of s.purposeFiles){let F=a$3(E);F.data&&p.push({filePath:E,data:F.data});}if(p.length>0){let F=q$1(p).issues.length;F>0&&(U=F);}}catch{}let H={};for(let p of s.symbols)H[p.type]=(H[p.type]||0)+1;let m$1={};for(let p of s.symbols)p.type==="component"&&p.componentType&&(m$1[p.componentType]=(m$1[p.componentType]||0)+1);let g=r.report();try{let p=T.join(a,"manifest.consistency.json");S.writeFileSync(p,JSON.stringify(g,null,2),"utf-8"),n.push(".paradigm/manifest.consistency.json");}catch{a$4.component("#reindex").warn("failed to write consistency manifest",{stage:"manifest-write"});}if(q()&&r.hasLossy())throw new Error(`reindex aborted: ${g.lossy_count} lossy transformation(s) detected under PARADIGM_STRICT=1. See .paradigm/manifest.consistency.json.`);return {action:"reindex",filesWritten:n,symbolCount:s.symbols.length,breakdown:H,flowCount:f,aspectGraphStats:y,personaCount:h,protocolHealth:_,consistency:g,...Object.keys(m$1).length>0?{componentTypeBreakdown:m$1}:{},...N?{universityStats:N}:{},...L?{integrityReport:L}:{},...P!==void 0?{componentAnchorIssues:P}:{},...j?{purposeHealth:j}:{},...U!==void 0?{crossFileIssues:U}:{}}}function Re(e,t){let n=T.join(e,"portal.yaml");if(!S.existsSync(n))return;let r;try{r=S.readFileSync(n,"utf-8");}catch{return}try{C.load(r);}catch(o){(o?.reason?.toLowerCase()||"").includes("duplicate")&&t.record("duplicate-key-detected","portal.yaml");return}let s;try{s=C.load(r,{schema:C.FAILSAFE_SCHEMA});}catch{return}if(!s||typeof s!="object")return;let i=s,a=i.gates;if(a&&typeof a=="object"&&!Array.isArray(a)){let o=0;for(let d of Object.keys(a))d.startsWith("^")&&o++;o>0&&t.record("prefix-stripped","portal.yaml",o);}else Array.isArray(a)&&a.length>0&&t.record("array-coerced","portal.yaml");let c=i.routes;Array.isArray(c)&&c.length>0&&t.record("array-coerced","portal.yaml"),i.version||t.record("default-applied","portal.yaml");}function _e(e,t){for(let n of e){let r;try{r=S.readFileSync(n,"utf-8");}catch{continue}try{C.load(r);}catch(l){(l?.reason?.toLowerCase()||"").includes("duplicate")&&t.record("duplicate-key-detected","purpose.yaml");continue}let s;try{s=C.load(r,{schema:C.FAILSAFE_SCHEMA});}catch{continue}if(!s||typeof s!="object")continue;let i=s,a=["components","features","gates","signals","aspects","states"],c=0;for(let l of a)Array.isArray(i[l])&&c++;c>0&&t.record("array-coerced","purpose.yaml",c);let o=(l,u)=>{if(!l||typeof l!="object"||Array.isArray(l))return 0;let f=0;for(let y of Object.keys(l))y.startsWith(u)&&f++;return f},d=o(i.gates,"^")+o(i.signals,"!")+o(i.aspects,"~")+o(i.components,"#")+o(i.features,"#");d>0&&t.record("prefix-stripped","purpose.yaml",d);}}function be(e,t){let n={};for(let r of t.symbols)if(r.type==="component"&&r.componentType){let s=r.componentType;n[s]||(n[s]=[]),n[s].push(r.symbol);}return {version:"1.0",generated:new Date().toISOString(),structure:xe(e),key_files:Le(e),skip_patterns:Ae(e),symbols:Ce(t.symbols,t.purposeFiles),...Object.keys(n).length>0?{symbolsByComponentType:n}:{}}}function xe(e){let t={};for(let[n,r]of Object.entries(Te)){let s=r.filter(i=>S.existsSync(T.join(e,i)));if(s.length>0){let i=Object.values(Ee).find(a=>a.category===n);t[n]={paths:s,symbol:i?.prefix||"@"};}}return t}function Le(e){let t={};for(let[n,r]of Object.entries(Se)){let s=r.filter(i=>S.existsSync(T.join(e,i)));s.length>0&&(t[n]=s);}return t.config||(t.config=[]),t.entry||(t.entry=[]),t.types||(t.types=[]),t}function Ae(e){let t={always:[...st.always],unless_testing:[...st.unless_testing],unless_docs:[...st.unless_docs]},n=T.join(e,".gitignore");if(S.existsSync(n))try{let s=S.readFileSync(n,"utf8").split(`
93
- `).map(i=>i.trim()).filter(i=>i&&!i.startsWith("#")).filter(i=>i.endsWith("/")||i.includes("*")||["node_modules","dist","build",".cache"].some(a=>i.includes(a))).slice(0,20);for(let i of s)t.always.includes(i)||t.always.push(i);}catch{}return t}function Ie(e){switch(e){case "feature":return "@";case "component":return "#";case "gate":return "^";case "flow":return "$";case "integration":return "&";case "signal":return "!";case "state":return "%";case "idea":return "?";case "deprecated":return "~";case "aspect":return "~";default:return "@"}}function Ce(e,t,n){let r={};for(let s of e){let a=`${Ie(s.type)}${s.id}`;if(s.filePath)r[a]=s.filePath;else {let c=t.find(o=>T.dirname(o).toLowerCase().includes(s.id.toLowerCase()));c&&(r[a]=T.dirname(c)+"/");}}return r}function Ne(e,t){let n={},r={};for(let s of t)try{let i=S.readFileSync(s,"utf8"),a=C.load(i);if(!a?.flows)continue;if(Array.isArray(a.flows))for(let c of a.flows){let o=c;if(!o.name)continue;let d=`$${o.name}`,l=Pt(o.steps);l.length>0&&(n[d]={id:d,description:o.description||"",steps:l,definedIn:T.relative(e,s)},jt(d,l,r));}else for(let[c,o]of Object.entries(a.flows)){let d=c.startsWith("$")?c:`$${c}`,l=Pt(o.steps);l.length>0&&(n[d]={id:d,description:o.description||"",trigger:o.trigger,steps:l,validation:o.validation,definedIn:T.relative(e,s)},jt(d,l,r));}}catch{}return Object.keys(n).length===0?null:{version:"1.0",generatedAt:new Date().toISOString(),flows:n,symbolToFlows:r}}function Pt(e){if(!e||!Array.isArray(e))return [];let t=[];for(let n=0;n<e.length;n++){let r=e[n];if(typeof r=="object"&&r!==null){let s=r,i=s.action||s.description||s.component||"";i&&t.push({id:s.id||`step-${n+1}`,action:i,symbol:s.symbol||s.component,expect:s.expect});}}return t}function jt(e,t,n){for(let r of t)r.symbol&&(n[r.symbol]||(n[r.symbol]=[]),n[r.symbol].includes(e)||n[r.symbol].push(e));}export{Et as a,q as b,Nt as c,Ot as d,He as e,Ue as f,Xe as g,We as h,ze as i,$e as j,Be as k,Ge as l,Ke as m,hn as n,yn as o,we as p};
@@ -1,6 +0,0 @@
1
- #!/usr/bin/env node
2
- import {v as v$1,b,q,p,o,s as s$1,i,k,l,a,m,t,u,j as j$1}from'./chunk-FG3M6VVO.js';import {e}from'./chunk-Q527BPUF.js';import {s,e as e$1,g,b as b$2,f as f$2,h}from'./chunk-33ERV2MW.js';import {z,f as f$1,p as p$1}from'./chunk-KAFQA7HV.js';import {f,b as b$1,a as a$1}from'./chunk-ECO3LHCE.js';import*as v from'fs';import*as j from'path';v$1();b();z();f();s();function be(){return [{name:"paradigm_ambient_nominations",description:"Get pending agent nominations \u2014 agents that self-nominated contributions based on recent events. Filters by urgency, agent, pending status. Marks returned nominations as surfaced. ~200 tokens.",inputSchema:{type:"object",properties:{urgency:{type:"string",enum:["critical","high","medium","low"],description:"Filter by urgency level"},agent:{type:"string",description:"Filter by agent ID"},pending_only:{type:"boolean",description:"Only show un-engaged nominations (default: true)"},include_debates:{type:"boolean",description:"Include debate groupings (default: false)"},limit:{type:"number",description:"Max nominations to return (default: 20)"}}},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_events",description:"Query the ambient event stream \u2014 recent tool calls, file edits, gate checks, and other project activity. Filters by type, source, symbol, agent, time window. ~200 tokens.",inputSchema:{type:"object",properties:{type:{type:"string",description:'Event type filter (e.g., "file-modified", "gate-checked", "decision-made")'},source:{type:"string",description:'Event source filter (e.g., "mcp-tool-call", "post-write-hook")'},symbol:{type:"string",description:"Filter events referencing this symbol"},agent:{type:"string",description:"Filter events from this agent"},since:{type:"string",description:'Relative time filter (e.g., "1h", "30m", "2d") or ISO timestamp'},limit:{type:"number",description:"Max events to return (default: 50)"}}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_engage",description:"Accept, dismiss, or defer a nomination. Optionally resolves a debate by choosing this nomination over others. ~50 tokens.",inputSchema:{type:"object",properties:{nomination_id:{type:"string",description:"Nomination ID to engage with"},response:{type:"string",enum:["accepted","dismissed","deferred"],description:"How to respond"},resolve_debate:{type:"string",description:"Optional debate ID to resolve by choosing this nomination"},reason:{type:"string",description:"Reason for response \u2014 stored on nomination for learning feedback. Especially valuable for dismissals."}},required:["nomination_id","response"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_context_compose",description:"Compose full agent session context: profile enrichment + recent decisions + transferable journal entries + pending nominations. Returns a markdown context block for prompt injection. ~300 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to compose context for"},symbols:{type:"array",items:{type:"string"},description:"Relevant symbols for expertise filtering"},include_nominations:{type:"boolean",description:"Include pending nominations (default: true)"},include_decisions:{type:"boolean",description:"Include recent team decisions (default: true)"},include_journal:{type:"boolean",description:"Include transferable journal entries (default: true)"},max_decisions:{type:"number",description:"Max decisions to include (default: 5)"},max_journal:{type:"number",description:"Max journal entries to include (default: 5)"}},required:["agent"]},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_promote",description:"Auto-promote high-confidence pattern discoveries from an agent's learning journal to its notebook. Promotes entries with trigger=pattern_discovered and confidence_after >= 0.8. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID whose journal to scan"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_learn",description:"Analyze an agent's nomination acceptance/dismissal history and adjust its attention threshold. If >60% dismissed \u2192 raise threshold (less noise). If >80% accepted \u2192 lower threshold (contribute more). Also returns engagement stats. ~100 tokens.",inputSchema:{type:"object",properties:{agent:{type:"string",description:"Agent ID to analyze and adjust"},dry_run:{type:"boolean",description:"If true, return stats without adjusting (default: false)"}},required:["agent"]},annotations:{readOnlyHint:false,destructiveHint:false}},{name:"paradigm_ambient_health",description:"Agent learning health metrics \u2014 aggregate learning quality across all agents: nomination acceptance rates, threshold drift, notebook counts, expertise growth, and overall health status (cold-start \u2192 accumulating \u2192 calibrating \u2192 mature).",inputSchema:{type:"object",properties:{}},annotations:{readOnlyHint:true,destructiveHint:false}},{name:"paradigm_ambient_learn_postflight",description:"Postflight learning pass \u2014 converts session work log verdicts into agent journal entries. Reads accepted/dismissed/revised verdicts from the session log, creates journal entries for each agent, then auto-promotes high-confidence entries to notebooks. Typically called at session end by the stop hook. ~200 tokens.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID (default: current session)"},dry_run:{type:"boolean",description:"If true, show what would be written without writing (default: false)"}}},annotations:{readOnlyHint:false,destructiveHint:false}}]}function re(s){let e=Date.now(),t=s.match(/^(\d+)(m|h|d)$/);if(t){let r=parseInt(t[1],10),i=t[2],l=i==="m"?r*6e4:i==="h"?r*36e5:r*864e5;return new Date(e-l).toISOString()}return s}async function ve(s,e$1,t$1){let r=i=>JSON.stringify(i,null,2);switch(s){case "paradigm_ambient_nominations":{m(t$1.rootDir);let l=e$1.pending_only!==false,d=e$1.limit||20,o=i(t$1.rootDir,{agent:e$1.agent,urgency:e$1.urgency,pending_only:l,limit:d+20}),b=t(t$1.rootDir);o=u(o,b).slice(0,d);let y=j.join(t$1.rootDir,".paradigm/events/nominations.jsonl");if(v.existsSync(y))try{let a=v.readFileSync(y,"utf8"),c=new Set(o.map(m=>m.id)),g=a.trim().split(`
3
- `).map(m=>{try{let f=JSON.parse(m);return c.has(f.id)?(f.surfaced=!0,JSON.stringify(f)):m}catch{return m}});v.writeFileSync(y,g.join(`
4
- `)+`
5
- `,"utf8");}catch{}let h={count:o.length,nominations:o.map(a=>({id:a.id,agent:a.agent,urgency:a.urgency,type:a.type,brief:a.brief,relevance:a.relevance,timestamp:a.timestamp,engaged:a.engaged,response:a.response}))};if(e$1.include_debates){let c=j$1(t$1.rootDir).filter(g=>!g.resolution);h.debates=c.map(g=>({id:g.id,topic:g.topic,type:g.type,nominations:g.nominations})),h.debate_count=c.length;}return {text:r(h),handled:true}}case "paradigm_ambient_events":{let i=e$1.since?re(e$1.since):void 0,l=e$1.limit||50,d=a(t$1.rootDir,{type:e$1.type,source:e$1.source,symbol:e$1.symbol,agent:e$1.agent,since:i,limit:l});return {text:r({count:d.length,events:d.map(o=>({id:o.id,type:o.type,source:o.source,timestamp:o.timestamp,path:o.path,symbols:o.symbols,context:o.context,agent:o.agent,tool:o.tool,severity:o.severity}))}),handled:true}}case "paradigm_ambient_engage":{let i$1=e$1.nomination_id,l$1=e$1.response,d=e$1.reason,o=k(t$1.rootDir,i$1,l$1,d);if(o)try{let{appendSessionWorkEntry:y,appendVerdictEntry:h}=await import('./session-work-log-T2IE4Y4T.js'),c=i(t$1.rootDir,{limit:500}).find(m=>m.id===i$1),g={timestamp:new Date().toISOString(),type:"user-verdict",agent:c?.agent,nominationId:i$1,verdict:l$1,reason:d};y(t$1.rootDir,g),h(t$1.rootDir,g);}catch{}let b=false;return e$1.resolve_debate&&o&&(b=l(t$1.rootDir,e$1.resolve_debate,i$1,e$1.reason)),{text:r({engaged:o,nomination_id:i$1,response:l$1,debate_resolved:b||void 0}),handled:true}}case "paradigm_context_compose":{let i$1=e$1.agent,l=e$1.symbols||[],d=e$1.include_nominations!==false,o=e$1.include_decisions!==false,b=e$1.include_journal!==false,y=e$1.max_decisions||5,h=e$1.max_journal||5,a=f$1(t$1.rootDir,i$1);if(!a)return {text:r({error:`Agent profile not found: ${i$1}`}),handled:true};let c=[],g=p$1(a,l);if(g.trim()&&c.push(g),o){let m=e(t$1.rootDir,{status:"active",limit:y});if(m.length>0){c.push("## Recent Team Decisions");for(let f of m)c.push(`- **${f.title}**: ${f.decision.slice(0,150)}${f.decision.length>150?"...":""}`);c.push("");}}if(b){let m=b$1(i$1,{transferable:true,limit:h});if(m.length>0){c.push("## Transferable Insights");for(let f of m)c.push(`- [${f.trigger}] ${f.insight.slice(0,150)}${f.insight.length>150?"...":""}`);c.push("");}}if(d){let m=i(t$1.rootDir,{pending_only:true,limit:10});if(m.length>0){c.push("## Pending Nominations");for(let f of m)c.push(`- [${f.urgency}] ${f.brief}`);c.push("");}}return {text:r({agent:i$1,context:c.join(`
6
- `),sections_included:{profile:true,decisions:o,journal:b,nominations:d}}),handled:true}}case "paradigm_ambient_promote":{let i=e$1.agent,l=s$1(t$1.rootDir,i);return {text:r({agent:i,promoted:l.promoted,entries:l.entries}),handled:true}}case "paradigm_ambient_learn":{let i=e$1.agent,l=e$1.dry_run===true,d=p(t$1.rootDir,i);if(l)return {text:r({agent:i,dry_run:true,stats:d,note:d.total<5?"Insufficient data for threshold adjustment (need 5+ engaged nominations)":`Accept rate: ${(d.acceptRate*100).toFixed(0)}% \u2014 ${d.acceptRate>.8?"would lower threshold":d.acceptRate<.4?"would raise threshold":"no adjustment needed"}`}),handled:true};let o$1=o(t$1.rootDir,i);return {text:r({agent:i,...o$1,stats:d}),handled:true}}case "paradigm_ambient_health":case "paradigm_ambient_neverland":{let i=q(t$1.rootDir);return {text:r(i),handled:true}}case "paradigm_ambient_learn_postflight":return {text:r(await de(t$1.rootDir,e$1)),handled:true};default:return {text:`Unknown ambient tool: ${s}`,handled:false}}}var ae={accepted:"human_feedback",dismissed:"confidence_miss",revised:"correction_received"};function ce(s){try{let e=j.join(s,".paradigm","config.yaml");if(v.existsSync(e)){let r=v.readFileSync(e,"utf8").match(/project:\s*["']?([^"'\n]+)["']?/);if(r)return r[1].trim()}}catch{}return j.basename(s)}async function de(s,e={}){let t=e.dry_run===true,r=ce(s),i=e$1(s).filter(n=>n.verdict&&n.agent),l=g(s).filter(n=>n.agent&&n.corrections.length>0),d=b$2(s);if(i.length===0&&l.length===0)return {sessionEntries:d.length,agentsProcessed:[],journalsWritten:0,journalsByAgent:{},promoted:0,promotedByAgent:{},dryRun:t,details:[]};let o=new Map;for(let n of i){let u=n.agent;o.has(u)||o.set(u,[]),o.get(u).push(n);}let b=d.filter(n=>n.type==="agent-contribution"),y=new Map;for(let n of b)n.agent&&(y.has(n.agent)||y.set(n.agent,[]),y.get(n.agent).push(n));let h$1=[],a={},c=0;for(let[n,u]of o){a[n]=0;let _=u.filter(p=>p.verdict==="accepted").length;u.filter(p=>p.verdict==="dismissed").length;u.filter(p=>p.verdict==="revised").length;let R=u.length,K=R>0?_/R:0;for(let p of u){let I=ae[p.verdict];if(!I)continue;let X=y.get(n)?.shift(),A=le(p,X,{acceptRate:K,total:R,accepted:_}),Y=typeof p.confidence=="number"?p.confidence:p.verdict==="accepted"?.85:p.verdict==="revised"?.6:.4,Z={agent:n,verdict:p.verdict,trigger:I,insight:A,symbols:p.symbols};if(h$1.push(Z),t)a[n]++,c++;else try{a$1(n,{trigger:I,insight:A,confidence_before:p.verdict==="accepted"?.7:.8,confidence_after:Y,project:r,transferable:p.verdict==="dismissed",tags:["postflight",`verdict:${p.verdict}`,...(p.symbols||[]).map(ee=>`symbol:${ee}`)]}),a[n]++,c++;}catch{}}}let g$1=new Set;for(let n of l){let u=n.agent;g$1.add(u),a[u]===void 0&&(a[u]=0);let _=`Self-revision during iteration round ${n.round}: ${n.corrections.join("; ")}`;if(h$1.push({agent:u,verdict:"iteration-revision",trigger:"self_reflection",insight:_,symbols:n.symbols}),t)a[u]++,c++;else try{a$1(u,{trigger:"self_reflection",insight:_,confidence_before:.6,confidence_after:typeof n.confidence=="number"?n.confidence:.75,project:r,transferable:!1,tags:["postflight","iteration-revision",`round:${n.round}`,...(n.symbols||[]).map($=>`symbol:${$}`)]}),a[u]++,c++;}catch{}}let m={},f=0,k=new Set([...o.keys(),...g$1]);if(!t)for(let n of k)try{let u=s$1(s,n);u.promoted>0&&(m[n]=u.promoted,f+=u.promoted);}catch{}return !t&&i.length>0&&f$2(s,i.map(n=>n.nominationId).filter(Boolean)),!t&&l.length>0&&h(s,l.map(n=>n.id)),{sessionEntries:d.length,agentsProcessed:Array.from(k),journalsWritten:c,journalsByAgent:a,promoted:f,promotedByAgent:m,dryRun:t,details:h$1}}function le(s,e,t){let r=s.symbols?.length?` (symbols: ${s.symbols.join(", ")})`:"",i=s.reason?` Reason: ${s.reason}.`:"";switch(s.verdict){case "accepted":return `Contribution accepted by user${r}.${i}`+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "dismissed":return `Contribution dismissed by user${r}.${i}`+(e?.contribution?` Rejected contribution: "${e.contribution.slice(0,120)}".`:"")+` Learn from this dismissal to improve future nominations. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;case "revised":return `Contribution revised by user${r}.${i}`+(s.revisionDelta?` Delta: "${s.revisionDelta.slice(0,120)}".`:"")+(e?.contribution?` Original: "${e.contribution.slice(0,120)}".`:"")+` Partial credit \u2014 close but not accurate enough. Session accept rate: ${(t.acceptRate*100).toFixed(0)}% (${t.accepted}/${t.total}).`;default:return `Unknown verdict "${s.verdict}"${r}.${i}`}}export{be as a,ve as b,de as c};
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- import {Router}from'express';import*as d from'fs';import*as h from'path';import*as S from'js-yaml';import*as M from'os';var q=".paradigm/lore",D="entries";function J(e){return e.endsWith(".yaml")||e.endsWith(".lore")}function V(e){let a=e.author;if(typeof a=="object"&&a&&!Array.isArray(a)){let o=a;if(o.type==="agent"){e.author=o.id||"unknown";let n=o.model||o.id||"unknown",t=n.toLowerCase(),s="unknown";t.includes("claude")||t.includes("anthropic")?s="anthropic":(t.includes("gpt")||t.includes("openai"))&&(s="openai"),e.agent={provider:s,model:n};}else e.author=o.id||"unknown";delete e.assistedBy;}else typeof a!="string"&&(e.author="unknown");return e.symbols_touched&&!Array.isArray(e.symbols_touched)&&(e.symbols_touched=[String(e.symbols_touched)]),e.symbols_created&&!Array.isArray(e.symbols_created)&&(e.symbols_created=[String(e.symbols_created)]),e}function x(e,a,o){let n=h.join(e,q,D,a),t=h.join(n,`${o}.lore`);if(d.existsSync(t))return t;let s=h.join(n,`${o}.yaml`);return d.existsSync(s)?s:null}function p(e){let a=h.join(e,q,D);if(!d.existsSync(a))return [];let o=[],n=d.readdirSync(a).filter(t=>/^\d{4}-\d{2}-\d{2}$/.test(t)).sort().reverse();for(let t of n){let s=h.join(a,t),i=d.readdirSync(s).filter(J).sort();for(let r of i)try{let c=d.readFileSync(h.join(s,r),"utf8"),u=S.load(c);o.push(V(u));}catch{}}return o}function et(e){let a=Router();return a.get("/",(o,n)=>{let t=p(e),{author:s,authorType:i,hasAgent:r,symbol:c,type:u,tag:y,from:_,to:T,tags:v,hasReview:j,hasBody:m,hasConfidence:R,hasAssessment:E,limit:$,offset:N}=o.query;if(s&&(t=t.filter(l=>l.author===s)),r!==void 0?t=t.filter(l=>r==="true"?l.agent!=null:l.agent==null):i&&(t=t.filter(l=>i==="agent"?l.agent!=null:l.agent==null)),c&&(t=t.filter(l=>l.symbols_touched?.includes(c)||l.symbols_created?.includes(c))),u&&(t=t.filter(l=>l.type===u)),y){let l=y;t=t.filter(g=>g.tags?.some(A=>A===l||A.startsWith(l+":")||l.includes(":")&&A===l));}if(m==="true"?t=t.filter(l=>l.body!=null&&l.body.length>0):m==="false"&&(t=t.filter(l=>!l.body||l.body.length===0)),_){let l=new Date(_).getTime();t=t.filter(g=>new Date(g.timestamp).getTime()>=l);}if(T){let l=new Date(T).getTime();t=t.filter(g=>new Date(g.timestamp).getTime()<=l);}if(v){let l=v.split(",");t=t.filter(g=>l.some(A=>g.tags?.includes(A)));}j==="true"?t=t.filter(l=>l.review!=null):j==="false"&&(t=t.filter(l=>l.review==null)),R==="true"?t=t.filter(l=>l.confidence!=null):R==="false"&&(t=t.filter(l=>l.confidence==null)),E==="true"?t=t.filter(l=>l.assessment!=null):E==="false"&&(t=t.filter(l=>l.assessment==null)),t.sort((l,g)=>new Date(g.timestamp).getTime()-new Date(l.timestamp).getTime());let k=parseInt(N||"0",10),I=parseInt($||"100",10),z=t.length;t=t.slice(k,k+I),n.json({total:z,offset:k,limit:I,entries:t});}),a.get("/timeline",(o,n)=>{let t=h.join(e,q,"timeline.yaml");if(!d.existsSync(t)){n.json({version:"1.0",project:"unknown",entries:0,last_updated:"",authors:[]});return}try{let s=d.readFileSync(t,"utf8");n.json(S.load(s));}catch{n.status(500).json({error:"Failed to load timeline"});}}),a.get("/symbols",(o,n)=>{let t=p(e),s={};for(let r of t){if(r.symbols_touched)for(let c of r.symbols_touched)s[c]=(s[c]||0)+1;if(r.symbols_created)for(let c of r.symbols_created)s[c]=(s[c]||0)+1;}let i=Object.entries(s).map(([r,c])=>({symbol:r,count:c})).sort((r,c)=>c.count-r.count);n.json({symbols:i});}),a.get("/tags",(o,n)=>{let t=p(e),s={};for(let r of t)if(r.tags)for(let c of r.tags)s[c]=(s[c]||0)+1;let i=Object.entries(s).map(([r,c])=>({tag:r,count:c})).sort((r,c)=>c.count-r.count);n.json({tags:i});}),a.get("/authors",(o,n)=>{let t=p(e),s={};for(let r of t){let c=r.author;s[c]||(s[c]={hasAgent:r.agent!=null,count:0,lastActive:r.timestamp}),s[c].count++,r.agent!=null&&(s[c].hasAgent=true),r.timestamp>s[c].lastActive&&(s[c].lastActive=r.timestamp);}let i=Object.entries(s).map(([r,c])=>({id:r,...c})).sort((r,c)=>c.count-r.count);n.json({authors:i});}),a.get("/calibration",(o,n)=>{let t=p(e).filter(m=>m.assessment!=null),s=t.filter(m=>m.confidence!=null),i=t.length,r=s.length,c={correct:0,partial:0,incorrect:0},u=0,y=0,_=0;for(let m of t){let R=m.assessment.verdict;c[R]++;let E=R==="correct"?1:R==="partial"?.5:0;u+=E,m.confidence!=null&&(y+=m.confidence,_+=Math.abs(E-m.confidence));}let T=i>0?u/i:0,v=r>0?y/r:null,j=r>0?1-_/r:null;n.json({totalAssessed:i,totalWithConfidence:r,accuracyRate:Math.round(T*1e3)/1e3,avgConfidence:v!=null?Math.round(v*1e3)/1e3:null,calibrationScore:j!=null?Math.round(j*1e3)/1e3:null,verdictBreakdown:c});}),a.get("/:id",(o,n)=>{let s=p(e).find(i=>i.id===o.params.id);if(!s){n.status(404).json({error:"Entry not found"});return}n.json(s);}),a.put("/:id/assess",(o,n)=>{let t=o.params.id,i=p(e).find(y=>y.id===t);if(!i){n.status(404).json({error:"Entry not found"});return}let r=i.timestamp.slice(0,10),c=x(e,r,t);if(!c){n.status(404).json({error:"Entry file not found"});return}let u=o.body.verdict;if(!["correct","partial","incorrect"].includes(u)){n.status(400).json({error:"Invalid verdict. Must be: correct, partial, incorrect"});return}if(i.assessment={verdict:u,assessed_by:o.body.assessed_by||"anonymous",assessed_at:new Date().toISOString(),notes:o.body.notes},i.confidence!=null){let y=u==="correct"?1:u==="partial"?.5:0;i.assessment_delta=y-i.confidence;}d.writeFileSync(c,S.dump(i,{lineWidth:-1,noRefs:true})),n.json({success:true,entry:i});}),a.put("/:id/review",(o,n)=>{let t=o.params.id,i=p(e).find(u=>u.id===t);if(!i){n.status(404).json({error:"Entry not found"});return}let r=i.timestamp.slice(0,10),c=x(e,r,t);if(!c){n.status(404).json({error:"Entry file not found"});return}i.review={reviewer:o.body.reviewer||"anonymous",completeness:o.body.completeness||3,quality:o.body.quality||3,notes:o.body.notes,reviewed_at:new Date().toISOString()},d.writeFileSync(c,S.dump(i,{lineWidth:-1,noRefs:true})),n.json({success:true,entry:i});}),a}function ot(e){let a=Router();return a.get("/",(o,n)=>{let t=h.join(e,".paradigm","config.yaml"),s=h.basename(e);if(d.existsSync(t))try{let i=S.load(d.readFileSync(t,"utf8"));s=i.project||i.name||s;}catch{}n.json({project:s,projectDir:e,paradigmVersion:"2.0"});}),a}var Q=".paradigm/lore",U="entries",X=14400*1e3;function Y(e){return e.endsWith(".yaml")||e.endsWith(".lore")}function Z(e){let a=e.author;if(typeof a=="object"&&a&&!Array.isArray(a)){let o=a;if(o.type==="agent"){e.author=o.id||"unknown";let n=o.model||o.id||"unknown",t=n.toLowerCase(),s="unknown";t.includes("claude")||t.includes("anthropic")?s="anthropic":(t.includes("gpt")||t.includes("openai"))&&(s="openai"),e.agent={provider:s,model:n};}else e.author=o.id||"unknown";delete e.assistedBy;}else typeof a!="string"&&(e.author="unknown");return e.symbols_touched&&!Array.isArray(e.symbols_touched)&&(e.symbols_touched=[String(e.symbols_touched)]),e.symbols_created&&!Array.isArray(e.symbols_created)&&(e.symbols_created=[String(e.symbols_created)]),e}function F(e){let a=h.join(e,Q,U);if(!d.existsSync(a))return [];let o=[],n=d.readdirSync(a).filter(t=>/^\d{4}-\d{2}-\d{2}$/.test(t)).sort().reverse();for(let t of n){let s=h.join(a,t),i=d.readdirSync(s).filter(Y).sort();for(let r of i)try{let c=d.readFileSync(h.join(s,r),"utf8"),u=S.load(c);o.push(Z(u));}catch{}}return o}function C(e){let a=h.join(e,".paradigm","session-breadcrumbs.json");if(d.existsSync(a))try{return JSON.parse(d.readFileSync(a,"utf8"))}catch{}let o=h.join(M.homedir(),".paradigm","sessions");if(d.existsSync(o))try{let n=d.readdirSync(o).sort().reverse();for(let t of n.slice(0,5)){let s=h.join(o,t,"breadcrumbs.json");if(d.existsSync(s))return JSON.parse(d.readFileSync(s,"utf8"))}}catch{}return []}function O(e,a){if(e.length===0)return [];let o=[...e].sort((s,i)=>new Date(s.timestamp).getTime()-new Date(i.timestamp).getTime()),n=[],t=[o[0]];for(let s=1;s<o.length;s++){let i=o[s-1],r=o[s],c=new Date(r.timestamp).getTime()-new Date(i.timestamp).getTime(),u=r.author===i.author;c<=X&&u?t.push(r):(n.push(B(t)),t=[r]);}return n.push(B(t)),a.length>0&&n.length>0&&(n[n.length-1].breadcrumbs=a),n.sort((s,i)=>new Date(i.startTime).getTime()-new Date(s.startTime).getTime()),n}function B(e){let a=new Set,o=false;for(let i of e){if(i.symbols_touched)for(let r of i.symbols_touched)a.add(r);if(i.symbols_created)for(let r of i.symbols_created)a.add(r);i.agent&&(o=true);}let n=e[0].timestamp,t=e[e.length-1].timestamp,s=n.slice(0,10);return {id:`session-${s}-${e[0].author}-${e[0].id.slice(0,8)}`,date:s,author:{name:e[0].author,hasAgent:o},startTime:n,endTime:t,entryCount:e.length,symbolsTouched:Array.from(a),entryIds:e.map(i=>i.id)}}function at(e){let a=Router();return a.get("/",(o,n)=>{let t=F(e),s=C(e),i=O(t,s);n.json({sessions:i});}),a.get("/:id",(o,n)=>{let t=F(e),s=C(e),r=O(t,s).find(u=>u.id===o.params.id);if(!r){n.status(404).json({error:"Session not found"});return}let c=t.filter(u=>r.entryIds.includes(u.id));n.json({...r,entries:c});}),a}export{et as a,ot as b,at as c};