@a-company/paradigm 5.10.0 → 5.21.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 (409) hide show
  1. package/dist/accept-orchestration-IUAWQZUN.js +18 -0
  2. package/dist/add-P76GEMGF.js +8 -0
  3. package/dist/agent-UUTYOFTH.js +33 -0
  4. package/dist/agent-loader-EPXURMO7.js +2 -0
  5. package/dist/agent-loader-PYGPX6D2.js +2 -0
  6. package/dist/agent-state-KSQ3S7OB.js +2 -0
  7. package/dist/agents-suggest-HYTFMQD3.js +10 -0
  8. package/dist/aggregate-W66DM3GA.js +10 -0
  9. package/dist/ambient-HYZR42NX.js +35 -0
  10. package/dist/assess-UFPYEJKP.js +9 -0
  11. package/dist/auto-RHJXOZFL.js +14 -0
  12. package/dist/beacon-5QVYV5DF.js +13 -0
  13. package/dist/calibration-OLJYB5HN.js +7 -0
  14. package/dist/check-THVGY4R5.js +14 -0
  15. package/dist/chunk-22ISTMKI.js +31 -0
  16. package/dist/chunk-2QO33NYK.js +3 -0
  17. package/dist/chunk-33LKBMVK.js +134 -0
  18. package/dist/chunk-4QADCWPU.js +7 -0
  19. package/dist/chunk-4TXOVRWD.js +3 -0
  20. package/dist/chunk-4UJ4NIEQ.js +4 -0
  21. package/dist/chunk-4ZGGWZ32.js +3 -0
  22. package/dist/chunk-5TAVYPOV.js +2 -0
  23. package/dist/chunk-6EX37L4Q.js +8 -0
  24. package/dist/chunk-AD5TAD2A.js +5 -0
  25. package/dist/chunk-AGVAHVUA.js +2 -0
  26. package/dist/chunk-AO7ZSRME.js +13 -0
  27. package/dist/chunk-BFD3GFRK.js +2 -0
  28. package/dist/chunk-D34YFK4M.js +6 -0
  29. package/dist/chunk-DVZWCXB6.js +2 -0
  30. package/dist/chunk-EKZDFEJW.js +2 -0
  31. package/dist/chunk-ET5XJTSX.js +2 -0
  32. package/dist/chunk-FYDRENK7.js +3 -0
  33. package/dist/chunk-HMQ5BHP2.js +743 -0
  34. package/dist/chunk-HXKWL3VK.js +29 -0
  35. package/dist/chunk-IZSBGW6E.js +2 -0
  36. package/dist/chunk-J32OPJEX.js +2 -0
  37. package/dist/chunk-JBDMCRPP.js +7 -0
  38. package/dist/chunk-JIXHEBGK.js +7 -0
  39. package/dist/chunk-JNSJVCTU.js +2 -0
  40. package/dist/chunk-JQKKVAAN.js +2 -0
  41. package/dist/chunk-KLBH26PA.js +429 -0
  42. package/dist/chunk-L6K5HNDL.js +24 -0
  43. package/dist/chunk-LKAT7IAK.js +2 -0
  44. package/dist/chunk-M4UMM6DC.js +5 -0
  45. package/dist/chunk-NKYNHSA5.js +424 -0
  46. package/dist/chunk-NW6OKHE6.js +5 -0
  47. package/dist/chunk-NXRVR37G.js +60 -0
  48. package/dist/chunk-ODVKPZZ4.js +2 -0
  49. package/dist/chunk-PUBB7LIT.js +5 -0
  50. package/dist/chunk-Q2J542ST.js +2 -0
  51. package/dist/chunk-QGZRM6ZB.js +2 -0
  52. package/dist/chunk-QNZEG7IT.js +13 -0
  53. package/dist/chunk-QT2LKB3P.js +7 -0
  54. package/dist/chunk-RVRARWSY.js +9 -0
  55. package/dist/chunk-T6IDXUUA.js +2 -0
  56. package/dist/chunk-TYWB5IQJ.js +3 -0
  57. package/dist/chunk-UIKLE3WD.js +2 -0
  58. package/dist/chunk-V7K6CQVX.js +111 -0
  59. package/dist/chunk-VCKKJDLP.js +8 -0
  60. package/dist/chunk-VG7FN2TU.js +4 -0
  61. package/dist/chunk-W5IWDW4Y.js +16 -0
  62. package/dist/chunk-W7C6FFMO.js +8 -0
  63. package/dist/chunk-WESTEMIM.js +10 -0
  64. package/dist/chunk-WR6D3SC6.js +5 -0
  65. package/dist/chunk-WS2N27RX.js +3 -0
  66. package/dist/chunk-XMAV5AG6.js +2 -0
  67. package/dist/chunk-XROULIQN.js +2 -0
  68. package/dist/chunk-XUFYOXOU.js +3 -0
  69. package/dist/chunk-Y4XFVDZC.js +3 -0
  70. package/dist/chunk-Y6KXTQBG.js +2 -0
  71. package/dist/{chunk-GTR2TBIJ.js → chunk-Z2UZUCY6.js} +237 -1047
  72. package/dist/chunk-Z34K6GY2.js +8 -0
  73. package/dist/claude-4LR3LJQZ.js +13 -0
  74. package/dist/claude-cli-UP6HGH7C.js +6 -0
  75. package/dist/claude-code-RLJ4GX77.js +11 -0
  76. package/dist/claude-code-teams-R37HJY3Y.js +29 -0
  77. package/dist/commands-LMUD5L6R.js +455 -0
  78. package/dist/compliance-GZ7UAOG3.js +6 -0
  79. package/dist/conductor-Y5IXELTL.js +4 -0
  80. package/dist/config-schema-HR7LDEQ6.js +2 -0
  81. package/dist/constellation-CG7C4WFE.js +13 -0
  82. package/dist/context-audit-RSSRX6XC.js +6 -0
  83. package/dist/cost-IDNVMAEV.js +10 -0
  84. package/dist/cost-PK4KIF7R.js +2 -0
  85. package/dist/cursor-cli-QKF7Z6M2.js +4 -0
  86. package/dist/cursorrules-U5O4G5T4.js +14 -0
  87. package/dist/decision-loader-2XPZE4EZ.js +2 -0
  88. package/dist/delete-P5VULXR4.js +14 -0
  89. package/dist/diff-RTFUKJHF.js +9 -0
  90. package/dist/discipline-H7LDI6NT.js +2 -0
  91. package/dist/dist-3ZCH25SG.js +2 -0
  92. package/dist/dist-KGRCLBJP-2QAPFYNF.js +39 -0
  93. package/dist/dist-R3RWD35F.js +2 -0
  94. package/dist/dist-VGFSP3XM.js +2 -0
  95. package/dist/dist-VXCZWVVJ.js +2 -0
  96. package/dist/dist-W3XCATBJ.js +2 -0
  97. package/dist/docs-EDQ2STFK.js +2 -0
  98. package/dist/docs-RXPN6CK7.js +12 -0
  99. package/dist/doctor-2T2QL6VM.js +2 -0
  100. package/dist/drift-ILZE5BFJ.js +13 -0
  101. package/dist/echo-UPTQUEDU.js +46 -0
  102. package/dist/edit-GUU3HBVW.js +9 -0
  103. package/dist/event-Y3VXC2RV.js +3 -0
  104. package/dist/explain-files-3GPZUETV.js +4 -0
  105. package/dist/export-CV5KCTPS.js +2 -0
  106. package/dist/flow-S3RQ4YPY.js +11 -0
  107. package/dist/global-C44FW4G2.js +13 -0
  108. package/dist/graduate-3BBSC27A.js +5 -0
  109. package/dist/graph-CNDE5TAT.js +2 -0
  110. package/dist/graph-server-COZR5C3Z.js +14 -0
  111. package/dist/habits-4J2KRYUL.js +42 -0
  112. package/dist/history-UW454SDP.js +12 -0
  113. package/dist/hooks-XH52VGOU.js +2 -0
  114. package/dist/index.js +15 -1039
  115. package/dist/init-24MAQJFM.js +2 -0
  116. package/dist/integrity-UYDOOJDP.js +7 -0
  117. package/dist/integrity-checker-DHGMZQDG.js +2 -0
  118. package/dist/journal-loader-GLH7XFTK.js +2 -0
  119. package/dist/lint-IGKE6UPS.js +26 -0
  120. package/dist/list-5IUGP3ZB.js +7 -0
  121. package/dist/list-YKIQNKGB.js +6 -0
  122. package/dist/lore-loader-RVQI5GXL.js +2 -0
  123. package/dist/lore-loader-XY5MZRR2.js +2 -0
  124. package/dist/lore-server-FC2GMDLT.js +14 -0
  125. package/dist/manual-RXSPSFLL.js +20 -0
  126. package/dist/mcp.js +93 -20484
  127. package/dist/migrate-X5OMAFAQ.js +59 -0
  128. package/dist/migrate-assessments-GEI5WMI2.js +4 -0
  129. package/dist/model-discovery-HMB3YI4L.js +2 -0
  130. package/dist/nomination-engine-XF7TWPAP.js +2 -0
  131. package/dist/notebook-PE3JSYZI.js +11 -0
  132. package/dist/notebook-loader-CENTDDUJ.js +2 -0
  133. package/dist/orchestrate-35HBQ3O3.js +8 -0
  134. package/dist/peers-P2KXU7ZK.js +5 -0
  135. package/dist/persona-STQWZH5P.js +29 -0
  136. package/dist/pipeline-MZUITRVN.js +4 -0
  137. package/dist/platform-server-2KXHGHFV.js +25 -0
  138. package/dist/plugin-update-checker-M7PW434O.js +2 -0
  139. package/dist/portal-check-3JVNLOEP.js +8 -0
  140. package/dist/portal-compliance-2UG4VKWH.js +2 -0
  141. package/dist/probe-5L5BQDGE.js +6 -0
  142. package/dist/project-type-SURTOIG7.js +2 -0
  143. package/dist/promote-NJQDZBZA.js +8 -0
  144. package/dist/providers-4PXMWA7V.js +8 -0
  145. package/dist/quiz-FE5UGAY2.js +10 -0
  146. package/dist/record-YXPB34MY.js +6 -0
  147. package/dist/reindex-PGDQSM42.js +2 -0
  148. package/dist/remember-MJRNTXYS.js +14 -0
  149. package/dist/retag-N5XF3KXP.js +6 -0
  150. package/dist/review-6UAH6V3R.js +11 -0
  151. package/dist/review-77QI6VOC.js +6 -0
  152. package/dist/ripple-ZGDITCGB.js +10 -0
  153. package/dist/roster-FLRZ5J42.js +2 -0
  154. package/dist/sentinel-HYAZ3CO5.js +19 -0
  155. package/dist/sentinel-bridge-VR357PKL.js +2 -0
  156. package/dist/sentinel-mcp.js +38 -3808
  157. package/dist/sentinel.js +1 -34
  158. package/dist/serve-JE6UF5P2.js +8 -0
  159. package/dist/serve-L52ZUTU6.js +10 -0
  160. package/dist/serve-OY6XYL7F.js +12 -0
  161. package/dist/server-2MNROHF6.js +7 -0
  162. package/dist/server-4YNUIK4W.js +8 -0
  163. package/dist/session-tracker-SKOMBDOW.js +2 -0
  164. package/dist/session-work-log-3MNUDEZ6.js +2 -0
  165. package/dist/session-work-log-J2H5OZBR.js +2 -0
  166. package/dist/setup-3F5IK7MO.js +31 -0
  167. package/dist/setup-KPIMRZ4Q.js +2 -0
  168. package/dist/shift-6GCNH666.js +11 -0
  169. package/dist/show-BOAVWZPZ.js +7 -0
  170. package/dist/show-PJ5LFLIL.js +5 -0
  171. package/dist/snapshot-L2G56RPL.js +8 -0
  172. package/dist/spawn-UH5RENSE.js +12 -0
  173. package/dist/status-77M3SDIF.js +8 -0
  174. package/dist/status-A37ECYNJ.js +6 -0
  175. package/dist/summary-ZJLQ6KHB.js +7 -0
  176. package/dist/sweep-HU74OPVW.js +17 -0
  177. package/dist/switch-CTW4PDGI.js +17 -0
  178. package/dist/symphony-3QMBGCZY.js +2 -0
  179. package/dist/symphony-QI63XL62.js +53 -0
  180. package/dist/symphony-loader-XACVV2E3.js +2 -0
  181. package/dist/symphony-peers-U4KHMKGI.js +2 -0
  182. package/dist/symphony-peers-X5NGWXFP.js +2 -0
  183. package/dist/symphony-relay-5GY5JIPT.js +3 -0
  184. package/dist/sync-QRDSFETO.js +2 -0
  185. package/dist/sync-llms-HL5PPW3M.js +15 -0
  186. package/dist/task-loader-NZFDTUQ5.js +2 -0
  187. package/dist/team-WGERKGNP.js +2 -0
  188. package/dist/test-BQJMS4Y2.js +111 -0
  189. package/dist/thread-HFXK65D4.js +41 -0
  190. package/dist/timeline-K3ZFKJ3R.js +6 -0
  191. package/dist/triage-FCWOZASE.js +18 -0
  192. package/dist/tutorial-UC6YQMNN.js +305 -0
  193. package/dist/university-content/courses/.purpose +74 -5
  194. package/dist/university-content/courses/para-701.json +807 -0
  195. package/dist/university-content/plsat/.purpose +3 -2
  196. package/dist/university-ui/assets/{index-BjewBB6s.js → index-CGFJczb1.js} +2 -2
  197. package/dist/university-ui/assets/{index-BjewBB6s.js.map → index-CGFJczb1.js.map} +1 -1
  198. package/dist/university-ui/index.html +1 -1
  199. package/dist/upgrade-B4IOLZYK.js +53 -0
  200. package/dist/validate-C6SMKGYD.js +9 -0
  201. package/dist/validate-LSCDOLBO.js +13 -0
  202. package/dist/validate-VZXTJHGO.js +6 -0
  203. package/dist/watch-LRM5XD46.js +8 -0
  204. package/dist/watch-PZCCUP6K.js +9 -0
  205. package/dist/wisdom-XZ3QKPNP.js +7 -0
  206. package/dist/work-log-loader-DL5GZ2BQ.js +2 -0
  207. package/dist/workspace-2ODL5WLY.js +2 -0
  208. package/package.json +1 -1
  209. package/platform-ui/dist/assets/AmbientSection-DqQ2mfCO.js +1 -0
  210. package/platform-ui/dist/assets/{CanvasSection-DwPTRdIN.js → CanvasSection-DLW0s-Bu.js} +1 -1
  211. package/platform-ui/dist/assets/{DocsSection-BJc_ws4I.js → DocsSection-BQ9Hi51g.js} +1 -1
  212. package/platform-ui/dist/assets/{GitSection-DhqBo1xc.js → GitSection-QQeUX6o3.js} +1 -1
  213. package/platform-ui/dist/assets/{GraphSection-D9fhVnZ0.js → GraphSection-0c9C-w7K.js} +2 -2
  214. package/platform-ui/dist/assets/{GraphSection-BlgXTl53.css → GraphSection-Bbs2a8sC.css} +1 -1
  215. package/platform-ui/dist/assets/LoreSection--t56kCj2.js +1 -0
  216. package/platform-ui/dist/assets/LoreSection-qnmm3o4y.css +1 -0
  217. package/platform-ui/dist/assets/SentinelSection-C4OoME9U.js +1 -0
  218. package/platform-ui/dist/assets/{SymphonySection-BRoBaUSS.js → SymphonySection-B-rvsLxq.js} +1 -1
  219. package/platform-ui/dist/assets/TeamSection-CBFmNEEo.js +1 -0
  220. package/platform-ui/dist/assets/index-Bxp0TVaf.css +1 -0
  221. package/platform-ui/dist/assets/index-DPpOdAtC.js +57 -0
  222. package/platform-ui/dist/index.html +2 -2
  223. package/dist/accept-orchestration-UQLM7PTQ.js +0 -189
  224. package/dist/add-FZRKEGH4.js +0 -81
  225. package/dist/agent-WERIO2XV.js +0 -523
  226. package/dist/agent-loader-TFIANSF4.js +0 -44
  227. package/dist/agent-state-S5DAWPTF.js +0 -24
  228. package/dist/agents-suggest-DNSYJ6IA.js +0 -83
  229. package/dist/aggregate-H57K7PNV.js +0 -88
  230. package/dist/assess-4WVXZLZQ.js +0 -68
  231. package/dist/auto-QFS5NHQU.js +0 -504
  232. package/dist/beacon-KXZXYQHX.js +0 -251
  233. package/dist/calibration-V46G7JTY.js +0 -135
  234. package/dist/check-OWAIWV23.js +0 -175
  235. package/dist/chunk-2IO7JAG2.js +0 -148
  236. package/dist/chunk-2T6BTYBN.js +0 -712
  237. package/dist/chunk-36TKPM5Z.js +0 -400
  238. package/dist/chunk-45MUDW6E.js +0 -804
  239. package/dist/chunk-4BLYIB7J.js +0 -5701
  240. package/dist/chunk-4L3UTYQX.js +0 -677
  241. package/dist/chunk-4NCFWYGG.js +0 -110
  242. package/dist/chunk-54LTTQBH.js +0 -138
  243. package/dist/chunk-5EWAQHFY.js +0 -269
  244. package/dist/chunk-5JGJACDU.js +0 -37
  245. package/dist/chunk-5OUOLN6M.js +0 -659
  246. package/dist/chunk-5VKJBNJL.js +0 -444
  247. package/dist/chunk-6N3JTACN.js +0 -2260
  248. package/dist/chunk-6QC3YGB6.js +0 -114
  249. package/dist/chunk-7N7GSU6K.js +0 -34
  250. package/dist/chunk-ABVQGRF7.js +0 -268
  251. package/dist/chunk-CL7JSK52.js +0 -129
  252. package/dist/chunk-CSD7IHSN.js +0 -152
  253. package/dist/chunk-EDOAWN7J.js +0 -717
  254. package/dist/chunk-EKGMAM62.js +0 -525
  255. package/dist/chunk-EZ3GOCYC.js +0 -132
  256. package/dist/chunk-F3BCHPYT.js +0 -143
  257. package/dist/chunk-FKJUBQU3.js +0 -3081
  258. package/dist/chunk-GT5QGC2H.js +0 -253
  259. package/dist/chunk-GZDFVP2N.js +0 -540
  260. package/dist/chunk-IRKUEJVW.js +0 -405
  261. package/dist/chunk-J2JEQRT3.js +0 -164
  262. package/dist/chunk-JASGXLK3.js +0 -679
  263. package/dist/chunk-KVDYJLTC.js +0 -121
  264. package/dist/chunk-L27I3CPZ.js +0 -357
  265. package/dist/chunk-LHLIAYQ3.js +0 -185
  266. package/dist/chunk-MCMOGQMU.js +0 -145
  267. package/dist/chunk-NQKQG45G.js +0 -688
  268. package/dist/chunk-PBHIFAL4.js +0 -259
  269. package/dist/chunk-PDX44BCA.js +0 -11
  270. package/dist/chunk-PMXRGPRQ.js +0 -305
  271. package/dist/chunk-RAB5IKPR.js +0 -487
  272. package/dist/chunk-RJE5G7WO.js +0 -590
  273. package/dist/chunk-RTHA3XRE.js +0 -880
  274. package/dist/chunk-S2HO5MLR.js +0 -621
  275. package/dist/chunk-S3ORKP3V.js +0 -716
  276. package/dist/chunk-TAIJOFOE.js +0 -124
  277. package/dist/chunk-TXESEO7Y.js +0 -245
  278. package/dist/chunk-UPLDI7CN.js +0 -1334
  279. package/dist/chunk-VL67H5IC.js +0 -506
  280. package/dist/chunk-VPPK3SY4.js +0 -1136
  281. package/dist/chunk-YMDLDELF.js +0 -314
  282. package/dist/chunk-YO6DVTL7.js +0 -99
  283. package/dist/chunk-YRZ5RPEB.js +0 -1561
  284. package/dist/chunk-ZDHLG5VP.js +0 -5676
  285. package/dist/chunk-ZGUAAVMA.js +0 -756
  286. package/dist/chunk-ZSYVKSY6.js +0 -2602
  287. package/dist/claude-FRRWJSTJ.js +0 -362
  288. package/dist/claude-cli-XJLK2X4L.js +0 -276
  289. package/dist/claude-code-HTBA4XRB.js +0 -126
  290. package/dist/claude-code-teams-T4SP24MD.js +0 -199
  291. package/dist/commands-5N4ILTPH.js +0 -5859
  292. package/dist/conductor-CQVGTEQN.js +0 -161
  293. package/dist/config-schema-EA4XALGG.js +0 -154
  294. package/dist/constellation-A26CCGQS.js +0 -225
  295. package/dist/context-audit-RLO3ETRP.js +0 -682
  296. package/dist/cost-BGM32XJU.js +0 -93
  297. package/dist/cost-VI46A4XL.js +0 -174
  298. package/dist/cursor-cli-JVEZGHWQ.js +0 -269
  299. package/dist/cursorrules-HLIKJJZT.js +0 -84
  300. package/dist/decision-loader-WWCLIQPJ.js +0 -20
  301. package/dist/delete-KBRPQLPC.js +0 -56
  302. package/dist/diff-D4X53HAC.js +0 -126
  303. package/dist/discipline-FA4OZXIS.js +0 -24
  304. package/dist/dist-34NA5RS5.js +0 -74
  305. package/dist/dist-5QE2BB2B-5S3T6Y3T.js +0 -6919
  306. package/dist/dist-77JDTVAY.js +0 -62
  307. package/dist/dist-OGTSAZ55.js +0 -1358
  308. package/dist/dist-QK4SQAK7.js +0 -64
  309. package/dist/dist-TA6LSC2Q.js +0 -20
  310. package/dist/docs-PBZB7LYP.js +0 -89
  311. package/dist/docs-QIYKO3BR.js +0 -155
  312. package/dist/doctor-ULBOHEIC.js +0 -11
  313. package/dist/drift-R5NRKFHI.js +0 -251
  314. package/dist/echo-O2LY7CC2.js +0 -248
  315. package/dist/edit-R2HNLMOG.js +0 -63
  316. package/dist/event-25OJKDCE.js +0 -31
  317. package/dist/export-IWVL7XLF.js +0 -38
  318. package/dist/flow-CRRVV3O3.js +0 -185
  319. package/dist/global-3NG5JXUB.js +0 -136
  320. package/dist/graduate-USAWGBJM.js +0 -160
  321. package/dist/graph-VHUMAAS6.js +0 -12
  322. package/dist/graph-server-YL22VBBN.js +0 -116
  323. package/dist/habits-OL5NGPXO.js +0 -1405
  324. package/dist/history-WOWC573W.js +0 -277
  325. package/dist/hooks-HFWSCGPV.js +0 -12
  326. package/dist/integrity-IHO4FZTS.js +0 -194
  327. package/dist/integrity-checker-PSKJA5SB.js +0 -12
  328. package/dist/journal-loader-5EYSBFFY.js +0 -18
  329. package/dist/lint-K6CJGGPH.js +0 -456
  330. package/dist/list-4YK7QKFF.js +0 -57
  331. package/dist/list-ENR7Q4CR.js +0 -56
  332. package/dist/lore-loader-7NO6N6FT.js +0 -26
  333. package/dist/lore-server-UNJY5KC3.js +0 -118
  334. package/dist/manual-G6FISID5.js +0 -204
  335. package/dist/migrate-LS45DNEV.js +0 -889
  336. package/dist/migrate-assessments-RGH4O6IX.js +0 -97
  337. package/dist/model-discovery-D2H3VBGC.js +0 -8
  338. package/dist/nomination-engine-RV5CNO5B.js +0 -42
  339. package/dist/notebook-YWIYGEHV.js +0 -155
  340. package/dist/orchestrate-JLILBBJE.js +0 -324
  341. package/dist/peers-DEOUIZM6.js +0 -82
  342. package/dist/persona-UHAHIVST.js +0 -390
  343. package/dist/pipeline-L4HCSBGN.js +0 -263
  344. package/dist/platform-server-H5YO3DQD.js +0 -1475
  345. package/dist/plugin-update-checker-KRRSGXMV.js +0 -12
  346. package/dist/portal-check-NPYGII2D.js +0 -42
  347. package/dist/portal-compliance-J7DGAPFX.js +0 -18
  348. package/dist/probe-MHL5HQZ2.js +0 -167
  349. package/dist/promote-F6ZYZZAL.js +0 -182
  350. package/dist/providers-GK7PB2OL.js +0 -104
  351. package/dist/quiz-M66SC7F7.js +0 -99
  352. package/dist/record-RA4WR2BO.js +0 -49
  353. package/dist/reindex-5LTD53ZC.js +0 -16
  354. package/dist/remember-HBWJ655S.js +0 -77
  355. package/dist/retag-3OLCVDEQ.js +0 -62
  356. package/dist/review-27ATYTD2.js +0 -33
  357. package/dist/review-57QMURZV.js +0 -334
  358. package/dist/ripple-JPBXP5I3.js +0 -215
  359. package/dist/sentinel-4XIG4STA.js +0 -63
  360. package/dist/sentinel-bridge-MDUXTQRL.js +0 -109
  361. package/dist/serve-CAH3PHE7.js +0 -33
  362. package/dist/serve-INL7SNBK.js +0 -36
  363. package/dist/serve-KBSE36PL.js +0 -49
  364. package/dist/server-54SKYFFY.js +0 -1647
  365. package/dist/server-XUOIO7E6.js +0 -338
  366. package/dist/session-tracker-C4BMD5WG.js +0 -13
  367. package/dist/session-work-log-MZ47OAPB.js +0 -20
  368. package/dist/setup-EDS27WUR.js +0 -25
  369. package/dist/setup-KO5AFC4K.js +0 -296
  370. package/dist/shift-D2JOHHBF.js +0 -668
  371. package/dist/show-5PV5KFJE.js +0 -176
  372. package/dist/show-NQKYX6WQ.js +0 -82
  373. package/dist/snapshot-BK4RBPCG.js +0 -62
  374. package/dist/spawn-RCHNXDHE.js +0 -196
  375. package/dist/status-WGIAQODY.js +0 -71
  376. package/dist/summary-NIRABMF5.js +0 -140
  377. package/dist/sweep-QMHNSIY5.js +0 -934
  378. package/dist/switch-6EJPZDIA.js +0 -232
  379. package/dist/symphony-4OCY36AI.js +0 -791
  380. package/dist/symphony-B75X2MME.js +0 -326
  381. package/dist/symphony-loader-UZGON56V.js +0 -90
  382. package/dist/symphony-peers-2ZQYLRNI.js +0 -34
  383. package/dist/symphony-peers-OL7F6M5S.js +0 -121
  384. package/dist/symphony-relay-UJYUXN65.js +0 -710
  385. package/dist/sync-VEHUH4OA.js +0 -11
  386. package/dist/sync-llms-YHCFIE6X.js +0 -166
  387. package/dist/task-loader-LDYWQSLM.js +0 -20
  388. package/dist/team-O5MIIFMA.js +0 -34
  389. package/dist/test-566CP5KC.js +0 -1017
  390. package/dist/thread-N754I4D5.js +0 -274
  391. package/dist/timeline-M3CICQFE.js +0 -112
  392. package/dist/triage-HHYGT3HY.js +0 -671
  393. package/dist/tutorial-KD22SUNO.js +0 -666
  394. package/dist/upgrade-H5PF32BW.js +0 -551
  395. package/dist/validate-CNKEKO6A.js +0 -134
  396. package/dist/validate-MB5ULIHS.js +0 -39
  397. package/dist/validate-QH3LADM6.js +0 -64
  398. package/dist/watch-2TKP5PVL.js +0 -199
  399. package/dist/watch-ZF4ML6CD.js +0 -111
  400. package/dist/wisdom-AATMGNFA.js +0 -319
  401. package/dist/work-log-loader-5L45XNYZ.js +0 -14
  402. package/dist/workspace-6E6OSRNU.js +0 -21
  403. package/platform-ui/dist/assets/AmbientSection-WtHfNedO.js +0 -1
  404. package/platform-ui/dist/assets/LoreSection-C3EixkjW.css +0 -1
  405. package/platform-ui/dist/assets/LoreSection-CwDDHrz9.js +0 -1
  406. package/platform-ui/dist/assets/SentinelSection-Cl7e5oZ6.js +0 -1
  407. package/platform-ui/dist/assets/TeamSection-CqSIMrKz.js +0 -1
  408. package/platform-ui/dist/assets/index-CfpZFjea.css +0 -1
  409. package/platform-ui/dist/assets/index-F0KL9xrN.js +0 -57
@@ -0,0 +1,455 @@
1
+ #!/usr/bin/env node
2
+ import m from'chalk';import Ze from'sql.js';import {v4}from'uuid';import*as S from'path';import*as E from'fs';import {fileURLToPath}from'url';import Se,{Router}from'express';import*as Xe from'http';import {WebSocketServer,WebSocket}from'ws';import ht from'simple-git';var et=5,tt={score:50,timesMatched:0,timesResolved:0,timesRecurred:0},U=null,_=class{db=null;dbPath;incidentCounter=0;initialized=false;constructor(e){this.dbPath=e||this.getDefaultDbPath();}getDefaultDbPath(){let e=process.env.SENTINEL_DATA_DIR||process.env.PARADIGM_DATA_DIR||S.join(process.cwd(),".paradigm","sentinel");return S.join(e,"sentinel.db")}createSchema(){this.db&&(this.db.run(`
3
+ -- Metadata table for schema versioning
4
+ CREATE TABLE IF NOT EXISTS metadata (
5
+ key TEXT PRIMARY KEY,
6
+ value TEXT NOT NULL
7
+ );
8
+
9
+ -- Incidents table
10
+ CREATE TABLE IF NOT EXISTS incidents (
11
+ id TEXT PRIMARY KEY,
12
+ timestamp TEXT NOT NULL,
13
+ status TEXT NOT NULL DEFAULT 'open',
14
+ error_message TEXT NOT NULL,
15
+ error_stack TEXT,
16
+ error_code TEXT,
17
+ error_type TEXT,
18
+ symbols TEXT NOT NULL,
19
+ flow_position TEXT,
20
+ environment TEXT NOT NULL,
21
+ service TEXT,
22
+ version TEXT,
23
+ user_id TEXT,
24
+ request_id TEXT,
25
+ group_id TEXT,
26
+ notes TEXT DEFAULT '[]',
27
+ related_incidents TEXT DEFAULT '[]',
28
+ resolved_at TEXT,
29
+ resolved_by TEXT,
30
+ resolution TEXT,
31
+ created_at TEXT NOT NULL,
32
+ updated_at TEXT NOT NULL
33
+ );
34
+
35
+ -- Patterns table
36
+ CREATE TABLE IF NOT EXISTS patterns (
37
+ id TEXT PRIMARY KEY,
38
+ name TEXT NOT NULL,
39
+ description TEXT,
40
+ pattern TEXT NOT NULL,
41
+ resolution TEXT NOT NULL,
42
+ confidence TEXT NOT NULL,
43
+ source TEXT NOT NULL DEFAULT 'manual',
44
+ private INTEGER NOT NULL DEFAULT 0,
45
+ tags TEXT DEFAULT '[]',
46
+ created_at TEXT NOT NULL,
47
+ updated_at TEXT NOT NULL
48
+ );
49
+
50
+ -- Incident groups
51
+ CREATE TABLE IF NOT EXISTS groups (
52
+ id TEXT PRIMARY KEY,
53
+ name TEXT,
54
+ common_symbols TEXT,
55
+ common_error_patterns TEXT,
56
+ suggested_pattern_id TEXT,
57
+ first_seen TEXT NOT NULL,
58
+ last_seen TEXT NOT NULL,
59
+ created_at TEXT NOT NULL,
60
+ updated_at TEXT NOT NULL
61
+ );
62
+
63
+ -- Group members
64
+ CREATE TABLE IF NOT EXISTS group_members (
65
+ group_id TEXT NOT NULL,
66
+ incident_id TEXT NOT NULL,
67
+ added_at TEXT NOT NULL,
68
+ PRIMARY KEY (group_id, incident_id)
69
+ );
70
+
71
+ -- Resolutions history
72
+ CREATE TABLE IF NOT EXISTS resolutions (
73
+ id TEXT PRIMARY KEY,
74
+ incident_id TEXT NOT NULL,
75
+ pattern_id TEXT,
76
+ commit_hash TEXT,
77
+ pr_url TEXT,
78
+ notes TEXT,
79
+ resolved_at TEXT NOT NULL,
80
+ recurred INTEGER DEFAULT 0
81
+ );
82
+
83
+ -- Practice events (habits system)
84
+ CREATE TABLE IF NOT EXISTS practice_events (
85
+ id TEXT PRIMARY KEY,
86
+ timestamp TEXT NOT NULL,
87
+ habit_id TEXT NOT NULL,
88
+ habit_category TEXT NOT NULL,
89
+ result TEXT NOT NULL CHECK (result IN ('followed', 'skipped', 'partial')),
90
+ engineer TEXT NOT NULL,
91
+ session_id TEXT NOT NULL,
92
+ lore_entry_id TEXT,
93
+ task_description TEXT,
94
+ symbols_touched TEXT DEFAULT '[]',
95
+ files_modified TEXT DEFAULT '[]',
96
+ related_incident_id TEXT,
97
+ notes TEXT
98
+ );
99
+
100
+ -- Structured logs table
101
+ CREATE TABLE IF NOT EXISTS logs (
102
+ id TEXT PRIMARY KEY,
103
+ timestamp TEXT NOT NULL,
104
+ level TEXT NOT NULL CHECK (level IN ('debug','info','warn','error')),
105
+ symbol TEXT NOT NULL,
106
+ symbol_type TEXT NOT NULL DEFAULT 'raw',
107
+ message TEXT NOT NULL,
108
+ data_json TEXT,
109
+ service TEXT NOT NULL,
110
+ session_id TEXT,
111
+ correlation_id TEXT,
112
+ duration_ms REAL,
113
+ environment TEXT
114
+ );
115
+
116
+ -- Service registry
117
+ CREATE TABLE IF NOT EXISTS services (
118
+ name TEXT PRIMARY KEY,
119
+ version TEXT,
120
+ pid INTEGER,
121
+ started_at TEXT NOT NULL,
122
+ last_seen_at TEXT NOT NULL,
123
+ environment TEXT,
124
+ metadata_json TEXT
125
+ );
126
+
127
+ -- Live app state snapshots (latest-wins per service+session)
128
+ CREATE TABLE IF NOT EXISTS app_state (
129
+ service TEXT NOT NULL,
130
+ session_id TEXT NOT NULL,
131
+ timestamp TEXT NOT NULL,
132
+ state_json TEXT NOT NULL,
133
+ active_flows_json TEXT,
134
+ active_gates_json TEXT,
135
+ PRIMARY KEY (service, session_id)
136
+ );
137
+
138
+ -- Metrics table
139
+ CREATE TABLE IF NOT EXISTS metrics (
140
+ id TEXT PRIMARY KEY,
141
+ timestamp TEXT NOT NULL,
142
+ name TEXT NOT NULL,
143
+ type TEXT NOT NULL CHECK (type IN ('counter','gauge','histogram')),
144
+ value REAL NOT NULL,
145
+ tags_json TEXT DEFAULT '{}',
146
+ service TEXT NOT NULL,
147
+ environment TEXT
148
+ );
149
+
150
+ -- Traces table
151
+ CREATE TABLE IF NOT EXISTS traces (
152
+ trace_id TEXT NOT NULL,
153
+ span_id TEXT PRIMARY KEY,
154
+ parent_span_id TEXT,
155
+ service TEXT NOT NULL,
156
+ symbol TEXT NOT NULL,
157
+ operation TEXT NOT NULL,
158
+ start_time TEXT NOT NULL,
159
+ end_time TEXT,
160
+ duration_ms REAL,
161
+ status TEXT NOT NULL DEFAULT 'ok',
162
+ tags_json TEXT DEFAULT '{}',
163
+ log_ids_json TEXT DEFAULT '[]'
164
+ );
165
+
166
+ -- Indexes
167
+ CREATE INDEX IF NOT EXISTS idx_incidents_timestamp ON incidents(timestamp);
168
+ CREATE INDEX IF NOT EXISTS idx_incidents_status ON incidents(status);
169
+ CREATE INDEX IF NOT EXISTS idx_incidents_environment ON incidents(environment);
170
+ CREATE INDEX IF NOT EXISTS idx_patterns_source ON patterns(source);
171
+ CREATE INDEX IF NOT EXISTS idx_practice_events_timestamp ON practice_events(timestamp);
172
+ CREATE INDEX IF NOT EXISTS idx_practice_events_habit_id ON practice_events(habit_id);
173
+ CREATE INDEX IF NOT EXISTS idx_practice_events_engineer ON practice_events(engineer);
174
+ CREATE INDEX IF NOT EXISTS idx_practice_events_session_id ON practice_events(session_id);
175
+ CREATE INDEX IF NOT EXISTS idx_logs_timestamp ON logs(timestamp);
176
+ CREATE INDEX IF NOT EXISTS idx_logs_level ON logs(level);
177
+ CREATE INDEX IF NOT EXISTS idx_logs_symbol ON logs(symbol);
178
+ CREATE INDEX IF NOT EXISTS idx_logs_service ON logs(service);
179
+ CREATE INDEX IF NOT EXISTS idx_logs_session_id ON logs(session_id);
180
+ CREATE INDEX IF NOT EXISTS idx_logs_correlation_id ON logs(correlation_id);
181
+ CREATE INDEX IF NOT EXISTS idx_metrics_timestamp ON metrics(timestamp);
182
+ CREATE INDEX IF NOT EXISTS idx_metrics_name ON metrics(name);
183
+ CREATE INDEX IF NOT EXISTS idx_metrics_service ON metrics(service);
184
+ CREATE INDEX IF NOT EXISTS idx_traces_trace_id ON traces(trace_id);
185
+ CREATE INDEX IF NOT EXISTS idx_traces_service ON traces(service);
186
+ CREATE INDEX IF NOT EXISTS idx_traces_start_time ON traces(start_time);
187
+ `),this.db.run("INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', ?)",[String(et)]));}save(){if(!this.db)return;let e=this.db.export(),n=Buffer.from(e);E.writeFileSync(this.dbPath,n);}recordIncident(e){this.db||this.initializeSync(),this.incidentCounter++;let t=`INC-${String(this.incidentCounter).padStart(3,"0")}`,s=new Date().toISOString();return this.db.run(`INSERT INTO incidents (
188
+ id, timestamp, status, error_message, error_stack, error_code, error_type,
189
+ symbols, flow_position, environment, service, version, user_id, request_id,
190
+ group_id, notes, related_incidents, resolved_at, resolved_by, resolution,
191
+ created_at, updated_at
192
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[t,e.timestamp||s,e.status||"open",e.error.message,e.error.stack||null,e.error.code||null,e.error.type||null,JSON.stringify(e.symbols),e.flowPosition?JSON.stringify(e.flowPosition):null,e.environment,e.service||null,e.version||null,e.userId||null,e.requestId||null,e.groupId||null,"[]","[]",e.resolvedAt||null,e.resolvedBy||null,e.resolution?JSON.stringify(e.resolution):null,s,s]),this.save(),t}initializeSync(){if(!(this.initialized&&this.db)&&!this.db&&U){let e=S.dirname(this.dbPath);if(E.existsSync(e)||E.mkdirSync(e,{recursive:true}),E.existsSync(this.dbPath)){let n=E.readFileSync(this.dbPath);this.db=new U.Database(n);}else this.db=new U.Database,this.createSchema();try{let n=this.db.exec("SELECT MAX(CAST(SUBSTR(id, 5) AS INTEGER)) as max FROM incidents");n.length>0&&n[0].values.length>0&&n[0].values[0][0]&&(this.incidentCounter=n[0].values[0][0]);}catch{this.incidentCounter=0;}this.migrateSchema(),this.initialized=true,this.save();}}migrateSchema(){if(!this.db)return;let e=1;try{let n=this.db.exec("SELECT value FROM metadata WHERE key = 'schema_version'");n.length>0&&n[0].values.length>0&&(e=parseInt(n[0].values[0][0],10)||1);}catch{}if(e<2){try{this.db.run(`
193
+ CREATE TABLE IF NOT EXISTS practice_events (
194
+ id TEXT PRIMARY KEY,
195
+ timestamp TEXT NOT NULL,
196
+ habit_id TEXT NOT NULL,
197
+ habit_category TEXT NOT NULL,
198
+ result TEXT NOT NULL CHECK (result IN ('followed', 'skipped', 'partial')),
199
+ engineer TEXT NOT NULL,
200
+ session_id TEXT NOT NULL,
201
+ lore_entry_id TEXT,
202
+ task_description TEXT,
203
+ symbols_touched TEXT DEFAULT '[]',
204
+ files_modified TEXT DEFAULT '[]',
205
+ related_incident_id TEXT,
206
+ notes TEXT
207
+ );
208
+
209
+ CREATE INDEX IF NOT EXISTS idx_practice_events_timestamp ON practice_events(timestamp);
210
+ CREATE INDEX IF NOT EXISTS idx_practice_events_habit_id ON practice_events(habit_id);
211
+ CREATE INDEX IF NOT EXISTS idx_practice_events_engineer ON practice_events(engineer);
212
+ CREATE INDEX IF NOT EXISTS idx_practice_events_session_id ON practice_events(session_id);
213
+ `);}catch{}this.db.run("INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', '2')"),e=2;}if(e<3){try{this.db.run(`
214
+ CREATE TABLE IF NOT EXISTS logs (
215
+ id TEXT PRIMARY KEY,
216
+ timestamp TEXT NOT NULL,
217
+ level TEXT NOT NULL CHECK (level IN ('debug','info','warn','error')),
218
+ symbol TEXT NOT NULL,
219
+ symbol_type TEXT NOT NULL DEFAULT 'raw',
220
+ message TEXT NOT NULL,
221
+ data_json TEXT,
222
+ service TEXT NOT NULL,
223
+ session_id TEXT,
224
+ correlation_id TEXT,
225
+ duration_ms REAL,
226
+ environment TEXT
227
+ );
228
+
229
+ CREATE TABLE IF NOT EXISTS services (
230
+ name TEXT PRIMARY KEY,
231
+ version TEXT,
232
+ pid INTEGER,
233
+ started_at TEXT NOT NULL,
234
+ last_seen_at TEXT NOT NULL,
235
+ environment TEXT,
236
+ metadata_json TEXT
237
+ );
238
+
239
+ CREATE TABLE IF NOT EXISTS app_state (
240
+ service TEXT NOT NULL,
241
+ session_id TEXT NOT NULL,
242
+ timestamp TEXT NOT NULL,
243
+ state_json TEXT NOT NULL,
244
+ active_flows_json TEXT,
245
+ active_gates_json TEXT,
246
+ PRIMARY KEY (service, session_id)
247
+ );
248
+
249
+ CREATE INDEX IF NOT EXISTS idx_logs_timestamp ON logs(timestamp);
250
+ CREATE INDEX IF NOT EXISTS idx_logs_level ON logs(level);
251
+ CREATE INDEX IF NOT EXISTS idx_logs_symbol ON logs(symbol);
252
+ CREATE INDEX IF NOT EXISTS idx_logs_service ON logs(service);
253
+ CREATE INDEX IF NOT EXISTS idx_logs_session_id ON logs(session_id);
254
+ CREATE INDEX IF NOT EXISTS idx_logs_correlation_id ON logs(correlation_id);
255
+ `);}catch{}this.db.run("INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', '3')"),e=3;}if(e<4){try{this.db.run(`
256
+ CREATE TABLE IF NOT EXISTS metrics (
257
+ id TEXT PRIMARY KEY,
258
+ timestamp TEXT NOT NULL,
259
+ name TEXT NOT NULL,
260
+ type TEXT NOT NULL CHECK (type IN ('counter','gauge','histogram')),
261
+ value REAL NOT NULL,
262
+ tags_json TEXT DEFAULT '{}',
263
+ service TEXT NOT NULL,
264
+ environment TEXT
265
+ );
266
+
267
+ CREATE TABLE IF NOT EXISTS traces (
268
+ trace_id TEXT NOT NULL,
269
+ span_id TEXT PRIMARY KEY,
270
+ parent_span_id TEXT,
271
+ service TEXT NOT NULL,
272
+ symbol TEXT NOT NULL,
273
+ operation TEXT NOT NULL,
274
+ start_time TEXT NOT NULL,
275
+ end_time TEXT,
276
+ duration_ms REAL,
277
+ status TEXT NOT NULL DEFAULT 'ok',
278
+ tags_json TEXT DEFAULT '{}',
279
+ log_ids_json TEXT DEFAULT '[]'
280
+ );
281
+
282
+ CREATE INDEX IF NOT EXISTS idx_metrics_timestamp ON metrics(timestamp);
283
+ CREATE INDEX IF NOT EXISTS idx_metrics_name ON metrics(name);
284
+ CREATE INDEX IF NOT EXISTS idx_metrics_service ON metrics(service);
285
+ CREATE INDEX IF NOT EXISTS idx_traces_trace_id ON traces(trace_id);
286
+ CREATE INDEX IF NOT EXISTS idx_traces_service ON traces(service);
287
+ CREATE INDEX IF NOT EXISTS idx_traces_start_time ON traces(start_time);
288
+ `);}catch{}this.db.run("INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', '4')"),e=4;}if(e<5){try{this.db.run(`
289
+ CREATE TABLE IF NOT EXISTS schemas (
290
+ id TEXT PRIMARY KEY,
291
+ version TEXT NOT NULL,
292
+ name TEXT NOT NULL,
293
+ description TEXT,
294
+ scope_json TEXT NOT NULL,
295
+ event_types_json TEXT NOT NULL,
296
+ causality_json TEXT,
297
+ visualization_json TEXT,
298
+ tags_json TEXT DEFAULT '[]',
299
+ registered_at TEXT NOT NULL,
300
+ updated_at TEXT NOT NULL
301
+ );
302
+
303
+ CREATE TABLE IF NOT EXISTS events (
304
+ id TEXT PRIMARY KEY,
305
+ schema_id TEXT NOT NULL,
306
+ event_type TEXT NOT NULL,
307
+ category TEXT NOT NULL,
308
+ timestamp TEXT NOT NULL,
309
+ scope_value TEXT,
310
+ scope_ordinal INTEGER,
311
+ session_id TEXT,
312
+ service TEXT NOT NULL,
313
+ data_json TEXT,
314
+ severity TEXT DEFAULT 'info',
315
+ parent_event_id TEXT,
316
+ depth INTEGER DEFAULT 0
317
+ );
318
+
319
+ CREATE INDEX IF NOT EXISTS idx_events_schema ON events(schema_id);
320
+ CREATE INDEX IF NOT EXISTS idx_events_type ON events(event_type);
321
+ CREATE INDEX IF NOT EXISTS idx_events_scope ON events(schema_id, scope_value);
322
+ CREATE INDEX IF NOT EXISTS idx_events_scope_ord ON events(schema_id, scope_ordinal);
323
+ CREATE INDEX IF NOT EXISTS idx_events_session ON events(session_id);
324
+ CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
325
+ CREATE INDEX IF NOT EXISTS idx_events_service ON events(service);
326
+ `);}catch{}this.db.run("INSERT OR REPLACE INTO metadata (key, value) VALUES ('schema_version', '5')");}}async ensureReady(){U||(U=await Ze()),this.initializeSync();}getIncident(e){this.initializeSync();let n=this.db.exec("SELECT * FROM incidents WHERE id = ?",[e]);return n.length===0||n[0].values.length===0?null:this.rowToIncident(n[0].columns,n[0].values[0])}getRecentIncidents(e={}){this.initializeSync();let{limit:n=50,offset:t=0}=e,s=[],r=[];e.status&&e.status!=="all"&&(s.push("status = ?"),r.push(e.status)),e.environment&&(s.push("environment = ?"),r.push(e.environment)),e.symbol&&(s.push("symbols LIKE ?"),r.push(`%${e.symbol}%`)),e.search&&(s.push("(error_message LIKE ? OR notes LIKE ?)"),r.push(`%${e.search}%`,`%${e.search}%`)),e.dateFrom&&(s.push("timestamp >= ?"),r.push(e.dateFrom)),e.dateTo&&(s.push("timestamp <= ?"),r.push(e.dateTo)),e.groupId&&(s.push("group_id = ?"),r.push(e.groupId));let i=s.length>0?`WHERE ${s.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM incidents ${i} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...r,n,t]);return a.length===0?[]:a[0].values.map(c=>this.rowToIncident(a[0].columns,c))}updateIncident(e,n){this.initializeSync();let t=new Date().toISOString(),s=["updated_at = ?"],r=[t];n.status!==void 0&&(s.push("status = ?"),r.push(n.status)),n.error!==void 0&&(s.push("error_message = ?"),r.push(n.error.message),n.error.stack!==void 0&&(s.push("error_stack = ?"),r.push(n.error.stack||null))),n.symbols!==void 0&&(s.push("symbols = ?"),r.push(JSON.stringify(n.symbols))),n.flowPosition!==void 0&&(s.push("flow_position = ?"),r.push(n.flowPosition?JSON.stringify(n.flowPosition):null)),n.groupId!==void 0&&(s.push("group_id = ?"),r.push(n.groupId||null)),n.resolvedAt!==void 0&&(s.push("resolved_at = ?"),r.push(n.resolvedAt||null)),n.resolvedBy!==void 0&&(s.push("resolved_by = ?"),r.push(n.resolvedBy||null)),n.resolution!==void 0&&(s.push("resolution = ?"),r.push(n.resolution?JSON.stringify(n.resolution):null)),r.push(e),this.db.run(`UPDATE incidents SET ${s.join(", ")} WHERE id = ?`,r),this.save();}resolveIncident(e,n){this.updateIncident(e,{status:"resolved",resolvedAt:new Date().toISOString()}),n?.notes&&this.addIncidentNote(e,{author:"system",content:n.notes,timestamp:new Date().toISOString()});}addIncidentNote(e,n){this.initializeSync();let t=this.getIncident(e);if(!t)return;let s={id:v4(),...n},r=[...t.notes,s];this.db.run("UPDATE incidents SET notes = ?, updated_at = ? WHERE id = ?",[JSON.stringify(r),new Date().toISOString(),e]),this.save();}linkIncidents(e,n){this.initializeSync();let t=this.getIncident(e);if(!t)return;if(!t.relatedIncidents.includes(n)){let r=[...t.relatedIncidents,n];this.db.run("UPDATE incidents SET related_incidents = ?, updated_at = ? WHERE id = ?",[JSON.stringify(r),new Date().toISOString(),e]);}let s=this.getIncident(n);if(s&&!s.relatedIncidents.includes(e)){let r=[...s.relatedIncidents,e];this.db.run("UPDATE incidents SET related_incidents = ?, updated_at = ? WHERE id = ?",[JSON.stringify(r),new Date().toISOString(),n]);}this.save();}getIncidentCount(e={}){this.initializeSync();let n=[],t=[];e.status&&e.status!=="all"&&(n.push("status = ?"),t.push(e.status)),e.environment&&(n.push("environment = ?"),t.push(e.environment)),e.dateFrom&&(n.push("timestamp >= ?"),t.push(e.dateFrom)),e.dateTo&&(n.push("timestamp <= ?"),t.push(e.dateTo));let s=n.length>0?`WHERE ${n.join(" AND ")}`:"",r=this.db.exec(`SELECT COUNT(*) as count FROM incidents ${s}`,t);return r.length===0||r[0].values.length===0?0:r[0].values[0][0]}addPattern(e){this.initializeSync();let n=new Date().toISOString(),t={...tt,...e.confidence};return this.db.run(`INSERT INTO patterns (
327
+ id, name, description, pattern, resolution, confidence,
328
+ source, private, tags, created_at, updated_at
329
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e.id,e.name,e.description||null,JSON.stringify(e.pattern),JSON.stringify(e.resolution),JSON.stringify(t),e.source,e.private?1:0,JSON.stringify(e.tags||[]),n,n]),this.save(),e.id}getPattern(e){this.initializeSync();let n=this.db.exec("SELECT * FROM patterns WHERE id = ?",[e]);return n.length===0||n[0].values.length===0?null:this.rowToPattern(n[0].columns,n[0].values[0])}getAllPatterns(e={}){this.initializeSync();let n=[],t=[];if(e.source&&(n.push("source = ?"),t.push(e.source)),e.minConfidence!==void 0&&(n.push("json_extract(confidence, '$.score') >= ?"),t.push(e.minConfidence)),e.includePrivate||n.push("private = 0"),e.tags&&e.tags.length>0){let i=e.tags.map(()=>"tags LIKE ?");n.push(`(${i.join(" OR ")})`),t.push(...e.tags.map(a=>`%"${a}"%`));}let s=n.length>0?`WHERE ${n.join(" AND ")}`:"",r=this.db.exec(`SELECT * FROM patterns ${s} ORDER BY json_extract(confidence, '$.score') DESC`,t);return r.length===0?[]:r[0].values.map(i=>this.rowToPattern(r[0].columns,i))}updatePattern(e,n){this.initializeSync();let t=new Date().toISOString(),s=["updated_at = ?"],r=[t];n.name!==void 0&&(s.push("name = ?"),r.push(n.name)),n.description!==void 0&&(s.push("description = ?"),r.push(n.description||null)),n.pattern!==void 0&&(s.push("pattern = ?"),r.push(JSON.stringify(n.pattern))),n.resolution!==void 0&&(s.push("resolution = ?"),r.push(JSON.stringify(n.resolution))),n.confidence!==void 0&&(s.push("confidence = ?"),r.push(JSON.stringify(n.confidence))),n.source!==void 0&&(s.push("source = ?"),r.push(n.source)),n.private!==void 0&&(s.push("private = ?"),r.push(n.private?1:0)),n.tags!==void 0&&(s.push("tags = ?"),r.push(JSON.stringify(n.tags))),r.push(e),this.db.run(`UPDATE patterns SET ${s.join(", ")} WHERE id = ?`,r),this.save();}deletePattern(e){this.initializeSync(),this.db.run("DELETE FROM patterns WHERE id = ?",[e]),this.save();}updatePatternConfidence(e,n){let t=this.getPattern(e);if(!t)return;let s=new Date().toISOString(),r={...t.confidence};switch(n){case "matched":r.timesMatched++,r.lastMatched=s;break;case "resolved":r.timesResolved++,r.lastResolved=s,r.score=Math.min(100,r.score+2);break;case "recurred":r.timesRecurred++,r.score=Math.max(10,r.score-5);break}this.updatePattern(e,{confidence:r});}createGroup(e){this.initializeSync();let n=`GRP-${v4().substring(0,8)}`,t=new Date().toISOString();this.db.run(`INSERT INTO groups (
330
+ id, name, common_symbols, common_error_patterns,
331
+ suggested_pattern_id, first_seen, last_seen, created_at, updated_at
332
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,e.name||null,JSON.stringify(e.commonSymbols),JSON.stringify(e.commonErrorPatterns),e.suggestedPattern?.id||null,e.firstSeen,e.lastSeen,t,t]);for(let s of e.incidents)this.addToGroup(n,s);return this.save(),n}getGroup(e){this.initializeSync();let n=this.db.exec("SELECT * FROM groups WHERE id = ?",[e]);return n.length===0||n[0].values.length===0?null:this.rowToGroup(n[0].columns,n[0].values[0])}getGroups(e={}){this.initializeSync();let n=e.limit||100,t=this.db.exec("SELECT * FROM groups ORDER BY last_seen DESC LIMIT ?",[n]);return t.length===0?[]:t[0].values.map(s=>this.rowToGroup(t[0].columns,s))}addToGroup(e,n){this.initializeSync();let t=new Date().toISOString();this.db.run("INSERT OR IGNORE INTO group_members (group_id, incident_id, added_at) VALUES (?, ?, ?)",[e,n,t]),this.db.run("UPDATE incidents SET group_id = ? WHERE id = ?",[e,n]),this.db.run("UPDATE groups SET last_seen = ?, updated_at = ? WHERE id = ?",[t,t,e]),this.save();}recordResolution(e){this.initializeSync();let n=v4(),t=new Date().toISOString();this.db.run(`INSERT INTO resolutions (id, incident_id, pattern_id, commit_hash, pr_url, notes, resolved_at)
333
+ VALUES (?, ?, ?, ?, ?, ?, ?)`,[n,e.incidentId,e.patternId||null,e.commitHash||null,e.prUrl||null,e.notes||null,t]),this.updateIncident(e.incidentId,{status:"resolved",resolvedAt:t,resolvedBy:e.patternId||"manual",resolution:{patternId:e.patternId,commitHash:e.commitHash,prUrl:e.prUrl,notes:e.notes}}),e.patternId&&this.updatePatternConfidence(e.patternId,"resolved"),this.save();}markRecurred(e){this.initializeSync(),this.db.run("UPDATE resolutions SET recurred = 1 WHERE incident_id = ?",[e]);let n=this.db.exec("SELECT pattern_id FROM resolutions WHERE incident_id = ?",[e]);n.length>0&&n[0].values.length>0&&n[0].values[0][0]&&this.updatePatternConfidence(n[0].values[0][0],"recurred"),this.save();}getResolutionHistory(e={}){this.initializeSync();let n=[],t=[];e.patternId&&(n.push("pattern_id = ?"),t.push(e.patternId)),e.symbol&&(n.push(`incident_id IN (
334
+ SELECT id FROM incidents WHERE symbols LIKE ?
335
+ )`),t.push(`%${e.symbol}%`));let s=n.length>0?`WHERE ${n.join(" AND ")}`:"",r=e.limit||100,i=this.db.exec(`SELECT * FROM resolutions ${s} ORDER BY resolved_at DESC LIMIT ?`,[...t,r]);if(i.length===0)return [];let a=i[0].columns;return i[0].values.map(c=>{let l={};return a.forEach((d,u)=>{l[d]=c[u];}),{id:l.id,incidentId:l.incident_id,patternId:l.pattern_id||void 0,commitHash:l.commit_hash||void 0,prUrl:l.pr_url||void 0,notes:l.notes||void 0,resolvedAt:l.resolved_at,recurred:l.recurred===1}})}getStats(e){this.initializeSync();let{start:n,end:t}=e,s=this.getIncidentCount({dateFrom:n,dateTo:t}),r=this.getIncidentCount({dateFrom:n,dateTo:t,status:"open"}),i=this.getIncidentCount({dateFrom:n,dateTo:t,status:"resolved"}),a=this.db.exec(`SELECT environment, COUNT(*) as count
336
+ FROM incidents
337
+ WHERE timestamp >= ? AND timestamp <= ?
338
+ GROUP BY environment`,[n,t]),c={};if(a.length>0)for(let h of a[0].values)c[h[0]]=h[1];let l=this.db.exec(`SELECT DATE(timestamp) as date, COUNT(*) as count
339
+ FROM incidents
340
+ WHERE timestamp >= ? AND timestamp <= ?
341
+ GROUP BY DATE(timestamp)
342
+ ORDER BY date`,[n,t]),d=[];if(l.length>0)for(let h of l[0].values)d.push({date:h[0],count:h[1]});let u=this.getAllPatterns({includePrivate:true}),g=u.length>0?u.reduce((h,R)=>h+R.confidence.score,0)/u.length:0,p=u.sort((h,R)=>R.confidence.timesResolved-h.confidence.timesResolved).slice(0,5).map(h=>({patternId:h.id,resolvedCount:h.confidence.timesResolved})),y=u.filter(h=>h.confidence.timesMatched>0).map(h=>({patternId:h.id,recurrenceRate:h.confidence.timesRecurred/Math.max(1,h.confidence.timesResolved)})).sort((h,R)=>R.recurrenceRate-h.recurrenceRate).slice(0,5),f=new Map,T=this.getRecentIncidents({dateFrom:n,dateTo:t,limit:1e3});for(let h of T)for(let[,R]of Object.entries(h.symbols))R&&f.set(R,(f.get(R)||0)+1);let j=Array.from(f.entries()).sort((h,R)=>R[1]-h[1]).slice(0,10).map(([h,R])=>({symbol:h,count:R})),Re=this.getResolutionHistory({limit:1e3}).filter(h=>h.resolvedAt>=n&&h.resolvedAt<=t),_e=Re.filter(h=>h.patternId).length,Qe=Re.length-_e;return {period:{start:n,end:t},incidents:{total:s,open:r,resolved:i,byEnvironment:c,byDay:d},patterns:{total:u.length,avgConfidence:Math.round(g),mostEffective:p,leastEffective:y},symbols:{mostIncidents:j,mostResolved:[],hotspots:j.slice(0,5).map(h=>({symbol:h.symbol,incidentRate:h.count/Math.max(1,s)}))},resolution:{avgTimeToResolve:0,resolvedWithPattern:_e,resolvedManually:Qe,resolutionRate:s>0?i/s*100:0}}}getSymbolHealth(e){let n=this.getRecentIncidents({symbol:e,limit:1e3}),t=n.length,s=new Map;for(let i of n)if(i.resolution?.patternId){let a=s.get(i.resolution.patternId)||0;s.set(i.resolution.patternId,a+1);}let r=Array.from(s.entries()).sort((i,a)=>a[1]-i[1]).slice(0,5).map(([i,a])=>({patternId:i,count:a}));return {incidentCount:t,avgTimeToResolve:0,topPatterns:r}}exportPatterns(e={}){let n=this.getAllPatterns({includePrivate:e.includePrivate});return {version:"1.0.0",exportedAt:new Date().toISOString(),patterns:n}}importPatterns(e,n={}){let t=0,s=0;for(let r of e.patterns){let i=this.getPattern(r.id);if(i&&!n.overwrite){s++;continue}i?this.updatePattern(r.id,r):this.addPattern({...r,source:"imported"}),t++;}return {imported:t,skipped:s}}exportBackup(){let e=this.getRecentIncidents({limit:1e5}),n=this.getAllPatterns({includePrivate:true}),t=this.getGroups({limit:1e4});return {version:"1.0.0",exportedAt:new Date().toISOString(),incidents:e,patterns:n,groups:t}}importBackup(e){this.initializeSync(),this.db.run("DELETE FROM group_members"),this.db.run("DELETE FROM resolutions"),this.db.run("DELETE FROM groups"),this.db.run("DELETE FROM incidents"),this.db.run("DELETE FROM patterns");for(let s of e.patterns)this.addPattern(s);for(let s of e.incidents){let r=s.timestamp;this.db.run(`INSERT INTO incidents (
343
+ id, timestamp, status, error_message, error_stack, error_code, error_type,
344
+ symbols, flow_position, environment, service, version, user_id, request_id,
345
+ group_id, notes, related_incidents, resolved_at, resolved_by, resolution,
346
+ created_at, updated_at
347
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s.id,s.timestamp,s.status,s.error.message,s.error.stack||null,s.error.code||null,s.error.type||null,JSON.stringify(s.symbols),s.flowPosition?JSON.stringify(s.flowPosition):null,s.environment,s.service||null,s.version||null,s.userId||null,s.requestId||null,s.groupId||null,JSON.stringify(s.notes),JSON.stringify(s.relatedIncidents),s.resolvedAt||null,s.resolvedBy||null,s.resolution?JSON.stringify(s.resolution):null,r,r]);}let n=this.db.exec("SELECT MAX(CAST(SUBSTR(id, 5) AS INTEGER)) as max FROM incidents");n.length>0&&n[0].values.length>0&&n[0].values[0][0]&&(this.incidentCounter=n[0].values[0][0]);let t=new Date().toISOString();for(let s of e.groups){this.db.run(`INSERT INTO groups (
348
+ id, name, common_symbols, common_error_patterns,
349
+ suggested_pattern_id, first_seen, last_seen, created_at, updated_at
350
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,[s.id,s.name||null,JSON.stringify(s.commonSymbols),JSON.stringify(s.commonErrorPatterns),s.suggestedPattern?.id||null,s.firstSeen,s.lastSeen,t,t]);for(let r of s.incidents)this.db.run("INSERT OR IGNORE INTO group_members (group_id, incident_id, added_at) VALUES (?, ?, ?)",[s.id,r,t]);}this.save();}rowToIncident(e,n){let t={};return e.forEach((s,r)=>{t[s]=n[r];}),{id:t.id,timestamp:t.timestamp,status:t.status,error:{message:t.error_message,stack:t.error_stack||void 0,code:t.error_code||void 0,type:t.error_type||void 0},symbols:JSON.parse(t.symbols||"{}"),flowPosition:t.flow_position?JSON.parse(t.flow_position):void 0,environment:t.environment,service:t.service||void 0,version:t.version||void 0,userId:t.user_id||void 0,requestId:t.request_id||void 0,groupId:t.group_id||void 0,notes:JSON.parse(t.notes||"[]"),relatedIncidents:JSON.parse(t.related_incidents||"[]"),resolvedAt:t.resolved_at||void 0,resolvedBy:t.resolved_by||void 0,resolution:t.resolution?JSON.parse(t.resolution):void 0}}rowToPattern(e,n){let t={};return e.forEach((s,r)=>{t[s]=n[r];}),{id:t.id,name:t.name,description:t.description||"",pattern:JSON.parse(t.pattern),resolution:JSON.parse(t.resolution),confidence:JSON.parse(t.confidence),source:t.source,private:t.private===1,tags:JSON.parse(t.tags||"[]"),createdAt:t.created_at,updatedAt:t.updated_at}}rowToGroup(e,n){let t={};e.forEach((c,l)=>{t[c]=n[l];});let s=this.db.exec("SELECT incident_id FROM group_members WHERE group_id = ?",[t.id]),r=[];if(s.length>0)for(let c of s[0].values)r.push(c[0]);let i=this.db.exec(`SELECT DISTINCT environment FROM incidents
351
+ WHERE id IN (SELECT incident_id FROM group_members WHERE group_id = ?)`,[t.id]),a=[];if(i.length>0)for(let c of i[0].values)a.push(c[0]);return {id:t.id,name:t.name||void 0,incidents:r,commonSymbols:JSON.parse(t.common_symbols||"{}"),commonErrorPatterns:JSON.parse(t.common_error_patterns||"[]"),count:r.length,firstSeen:t.first_seen,lastSeen:t.last_seen,environments:a,suggestedPattern:t.suggested_pattern_id&&this.getPattern(t.suggested_pattern_id)||void 0}}recordPracticeEvent(e){this.initializeSync();let n=`PE-${v4().substring(0,8)}`,t=new Date().toISOString();return this.db.run(`INSERT INTO practice_events (
352
+ id, timestamp, habit_id, habit_category, result,
353
+ engineer, session_id, lore_entry_id, task_description,
354
+ symbols_touched, files_modified, related_incident_id, notes
355
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,t,e.habitId,e.habitCategory,e.result,e.engineer,e.sessionId,e.loreEntryId||null,e.taskDescription||null,JSON.stringify(e.symbolsTouched||[]),JSON.stringify(e.filesModified||[]),e.relatedIncidentId||null,e.notes||null]),this.save(),n}getPracticeEvents(e={}){this.initializeSync();let{limit:n=100,offset:t=0}=e,s=[],r=[];e.habitId&&(s.push("habit_id = ?"),r.push(e.habitId)),e.habitCategory&&(s.push("habit_category = ?"),r.push(e.habitCategory)),e.result&&(s.push("result = ?"),r.push(e.result)),e.engineer&&(s.push("engineer = ?"),r.push(e.engineer)),e.sessionId&&(s.push("session_id = ?"),r.push(e.sessionId)),e.dateFrom&&(s.push("timestamp >= ?"),r.push(e.dateFrom)),e.dateTo&&(s.push("timestamp <= ?"),r.push(e.dateTo));let i=s.length>0?`WHERE ${s.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM practice_events ${i} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...r,n,t]);return a.length===0?[]:a[0].values.map(c=>this.rowToPracticeEvent(a[0].columns,c))}getPracticeEventCount(e={}){this.initializeSync();let n=[],t=[];e.habitId&&(n.push("habit_id = ?"),t.push(e.habitId)),e.habitCategory&&(n.push("habit_category = ?"),t.push(e.habitCategory)),e.result&&(n.push("result = ?"),t.push(e.result)),e.engineer&&(n.push("engineer = ?"),t.push(e.engineer)),e.dateFrom&&(n.push("timestamp >= ?"),t.push(e.dateFrom)),e.dateTo&&(n.push("timestamp <= ?"),t.push(e.dateTo));let s=n.length>0?`WHERE ${n.join(" AND ")}`:"",r=this.db.exec(`SELECT COUNT(*) as count FROM practice_events ${s}`,t);return r.length===0||r[0].values.length===0?0:r[0].values[0][0]}getComplianceRate(e={}){this.initializeSync();let n=[],t=[];e.habitId&&(n.push("habit_id = ?"),t.push(e.habitId)),e.habitCategory&&(n.push("habit_category = ?"),t.push(e.habitCategory)),e.engineer&&(n.push("engineer = ?"),t.push(e.engineer)),e.dateFrom&&(n.push("timestamp >= ?"),t.push(e.dateFrom)),e.dateTo&&(n.push("timestamp <= ?"),t.push(e.dateTo));let s=n.length>0?`WHERE ${n.join(" AND ")}`:"",r=this.db.exec(`SELECT result, COUNT(*) as count
356
+ FROM practice_events ${s}
357
+ GROUP BY result`,t),i=0,a=0,c=0;if(r.length>0)for(let u of r[0].values){let g=u[0],p=u[1];g==="followed"?i=p:g==="skipped"?a=p:g==="partial"&&(c=p);}let l=i+a+c,d=l>0?(i+c*.5)/l*100:100;return {total:l,followed:i,skipped:a,partial:c,rate:Math.round(d)}}rowToPracticeEvent(e,n){let t={};return e.forEach((s,r)=>{t[s]=n[r];}),{id:t.id,timestamp:t.timestamp,habitId:t.habit_id,habitCategory:t.habit_category,result:t.result,engineer:t.engineer,sessionId:t.session_id,loreEntryId:t.lore_entry_id||void 0,taskDescription:t.task_description||void 0,symbolsTouched:JSON.parse(t.symbols_touched||"[]"),filesModified:JSON.parse(t.files_modified||"[]"),relatedIncidentId:t.related_incident_id||void 0,notes:t.notes||void 0}}inferSymbolType(e){return e.startsWith("#")?"component":e.startsWith("^")?"gate":e.startsWith("!")?"signal":e.startsWith("$")?"flow":e.startsWith("~")?"aspect":"raw"}insertLog(e){this.initializeSync();let n=e.id||v4(),t=e.timestamp||new Date().toISOString(),s=e.symbolType||this.inferSymbolType(e.symbol);return this.db.run(`INSERT INTO logs (
358
+ id, timestamp, level, symbol, symbol_type, message, data_json,
359
+ service, session_id, correlation_id, duration_ms, environment
360
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[n,t,e.level,e.symbol,s,e.message,e.data?JSON.stringify(e.data):null,e.service,e.sessionId||null,e.correlationId||null,e.durationMs??null,e.environment||null]),this.save(),n}insertLogBatch(e){this.initializeSync();let n=0,t=[];for(let s of e)try{let r=s.id||v4(),i=s.timestamp||new Date().toISOString(),a=s.symbolType||this.inferSymbolType(s.symbol);this.db.run(`INSERT INTO logs (
361
+ id, timestamp, level, symbol, symbol_type, message, data_json,
362
+ service, session_id, correlation_id, duration_ms, environment
363
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[r,i,s.level,s.symbol,a,s.message,s.data?JSON.stringify(s.data):null,s.service,s.sessionId||null,s.correlationId||null,s.durationMs??null,s.environment||null]),n++;}catch(r){t.push(r instanceof Error?r.message:String(r));}return this.save(),{accepted:n,errors:t}}queryLogs(e={}){this.initializeSync();let{limit:n=100,offset:t=0}=e,s=[],r=[];e.level&&(s.push("level = ?"),r.push(e.level)),e.symbol&&(s.push("symbol LIKE ?"),r.push(`%${e.symbol}%`)),e.service&&(s.push("service = ?"),r.push(e.service)),e.sessionId&&(s.push("session_id = ?"),r.push(e.sessionId)),e.correlationId&&(s.push("correlation_id = ?"),r.push(e.correlationId)),e.search&&(s.push("message LIKE ?"),r.push(`%${e.search}%`)),e.since&&(s.push("timestamp >= ?"),r.push(e.since)),e.until&&(s.push("timestamp <= ?"),r.push(e.until));let i=s.length>0?`WHERE ${s.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM logs ${i} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...r,n,t]);return a.length===0?[]:a[0].values.map(c=>this.rowToLogEntry(a[0].columns,c))}getLogCount(e={}){this.initializeSync();let n=[],t=[];e.level&&(n.push("level = ?"),t.push(e.level)),e.symbol&&(n.push("symbol LIKE ?"),t.push(`%${e.symbol}%`)),e.service&&(n.push("service = ?"),t.push(e.service)),e.since&&(n.push("timestamp >= ?"),t.push(e.since)),e.until&&(n.push("timestamp <= ?"),t.push(e.until));let s=n.length>0?`WHERE ${n.join(" AND ")}`:"",r=this.db.exec(`SELECT COUNT(*) as count FROM logs ${s}`,t);return r.length===0||r[0].values.length===0?0:r[0].values[0][0]}pruneLogs(e){if(this.initializeSync(),e<=0)return 0;let n=this.getLogCount();if(n<=e)return 0;let t=n-e;return this.db.run(`DELETE FROM logs WHERE id IN (
364
+ SELECT id FROM logs ORDER BY timestamp ASC LIMIT ?
365
+ )`,[t]),this.save(),t}rowToLogEntry(e,n){let t={};return e.forEach((s,r)=>{t[s]=n[r];}),{id:t.id,timestamp:t.timestamp,level:t.level,symbol:t.symbol,symbolType:t.symbol_type||"raw",message:t.message,data:t.data_json?JSON.parse(t.data_json):void 0,service:t.service,sessionId:t.session_id||void 0,correlationId:t.correlation_id||void 0,durationMs:t.duration_ms||void 0,environment:t.environment||void 0}}registerService(e){this.initializeSync();let n=new Date().toISOString();this.db.run(`INSERT INTO services (name, version, pid, started_at, last_seen_at, environment, metadata_json)
366
+ VALUES (?, ?, ?, ?, ?, ?, ?)
367
+ ON CONFLICT(name) DO UPDATE SET
368
+ version = excluded.version,
369
+ pid = excluded.pid,
370
+ last_seen_at = excluded.last_seen_at,
371
+ environment = excluded.environment,
372
+ metadata_json = excluded.metadata_json`,[e.name,e.version||null,e.pid??null,n,n,e.environment||null,e.metadata?JSON.stringify(e.metadata):null]),this.save();}updateServiceLastSeen(e){this.initializeSync();let n=new Date().toISOString();this.db.run("UPDATE services SET last_seen_at = ? WHERE name = ?",[n,e]),this.save();}getServices(){this.initializeSync();let e=this.db.exec("SELECT * FROM services ORDER BY last_seen_at DESC");return e.length===0?[]:e[0].values.map(n=>{let t={};return e[0].columns.forEach((s,r)=>{t[s]=n[r];}),{name:t.name,version:t.version||void 0,pid:t.pid||void 0,startedAt:t.started_at,lastSeenAt:t.last_seen_at,environment:t.environment||void 0,metadata:t.metadata_json?JSON.parse(t.metadata_json):void 0}})}upsertAppState(e){this.initializeSync(),this.db.run(`INSERT INTO app_state (service, session_id, timestamp, state_json, active_flows_json, active_gates_json)
373
+ VALUES (?, ?, ?, ?, ?, ?)
374
+ ON CONFLICT(service, session_id) DO UPDATE SET
375
+ timestamp = excluded.timestamp,
376
+ state_json = excluded.state_json,
377
+ active_flows_json = excluded.active_flows_json,
378
+ active_gates_json = excluded.active_gates_json`,[e.service,e.sessionId,e.timestamp||new Date().toISOString(),JSON.stringify(e.state),e.activeFlows?JSON.stringify(e.activeFlows):null,e.activeGates?JSON.stringify(e.activeGates):null]),this.save();}getAppState(e,n){this.initializeSync();let t="SELECT * FROM app_state WHERE service = ?",s=[e];n&&(t+=" AND session_id = ?",s.push(n)),t+=" ORDER BY timestamp DESC";let r=this.db.exec(t,s);return r.length===0?[]:r[0].values.map(i=>this.rowToAppState(r[0].columns,i))}getAllAppStates(){this.initializeSync();let e=this.db.exec("SELECT * FROM app_state ORDER BY timestamp DESC");return e.length===0?[]:e[0].values.map(n=>this.rowToAppState(e[0].columns,n))}rowToAppState(e,n){let t={};return e.forEach((s,r)=>{t[s]=n[r];}),{service:t.service,sessionId:t.session_id,timestamp:t.timestamp,state:JSON.parse(t.state_json),activeFlows:t.active_flows_json?JSON.parse(t.active_flows_json):void 0,activeGates:t.active_gates_json?JSON.parse(t.active_gates_json):void 0}}insertMetric(e){this.initializeSync();let n=v4(),t=e.timestamp||new Date().toISOString();return this.db.run(`INSERT INTO metrics (
379
+ id, timestamp, name, type, value, tags_json, service, environment
380
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[n,t,e.name,e.type,e.value,JSON.stringify(e.tags||{}),e.service,e.environment||null]),this.save(),n}insertMetricBatch(e){this.initializeSync();let n=0,t=[];for(let s of e)try{let r=v4(),i=s.timestamp||new Date().toISOString();this.db.run(`INSERT INTO metrics (
381
+ id, timestamp, name, type, value, tags_json, service, environment
382
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,[r,i,s.name,s.type,s.value,JSON.stringify(s.tags||{}),s.service,s.environment||null]),n++;}catch(r){t.push(r instanceof Error?r.message:String(r));}return this.save(),{accepted:n,errors:t}}queryMetrics(e={}){this.initializeSync();let{limit:n=100,offset:t=0}=e,s=[],r=[];if(e.name&&(s.push("name = ?"),r.push(e.name)),e.type&&(s.push("type = ?"),r.push(e.type)),e.service&&(s.push("service = ?"),r.push(e.service)),e.tag){let c=e.tag.indexOf("=");if(c>0){let l=e.tag.substring(0,c),d=e.tag.substring(c+1);s.push("tags_json LIKE ?"),r.push(`%"${l}":"${d}"%`);}}e.since&&(s.push("timestamp >= ?"),r.push(e.since)),e.until&&(s.push("timestamp <= ?"),r.push(e.until));let i=s.length>0?`WHERE ${s.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM metrics ${i} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...r,n,t]);return a.length===0?[]:a[0].values.map(c=>this.rowToMetricEntry(a[0].columns,c))}getMetricCount(e={}){this.initializeSync();let n=[],t=[];if(e.name&&(n.push("name = ?"),t.push(e.name)),e.type&&(n.push("type = ?"),t.push(e.type)),e.service&&(n.push("service = ?"),t.push(e.service)),e.tag){let i=e.tag.indexOf("=");if(i>0){let a=e.tag.substring(0,i),c=e.tag.substring(i+1);n.push("tags_json LIKE ?"),t.push(`%"${a}":"${c}"%`);}}e.since&&(n.push("timestamp >= ?"),t.push(e.since)),e.until&&(n.push("timestamp <= ?"),t.push(e.until));let s=n.length>0?`WHERE ${n.join(" AND ")}`:"",r=this.db.exec(`SELECT COUNT(*) as count FROM metrics ${s}`,t);return r.length===0||r[0].values.length===0?0:r[0].values[0][0]}aggregateMetric(e,n){this.initializeSync();let t=["name = ?"],s=[e];n?.service&&(t.push("service = ?"),s.push(n.service)),n?.since&&(t.push("timestamp >= ?"),s.push(n.since)),n?.until&&(t.push("timestamp <= ?"),s.push(n.until));let r=`WHERE ${t.join(" AND ")}`,i=this.db.exec(`SELECT COUNT(*) as count, SUM(value) as sum, MIN(value) as min, MAX(value) as max, AVG(value) as avg
383
+ FROM metrics ${r}`,s);if(i.length===0||i[0].values.length===0)return {name:e,count:0,sum:0,min:0,max:0,avg:0};let a=i[0].values[0];return {name:e,count:a[0]||0,sum:a[1]||0,min:a[2]||0,max:a[3]||0,avg:a[4]||0}}pruneMetrics(e){if(this.initializeSync(),e<=0)return 0;let n=this.getMetricCount();if(n<=e)return 0;let t=n-e;return this.db.run(`DELETE FROM metrics WHERE id IN (
384
+ SELECT id FROM metrics ORDER BY timestamp ASC LIMIT ?
385
+ )`,[t]),this.save(),t}rowToMetricEntry(e,n){let t={};return e.forEach((s,r)=>{t[s]=n[r];}),{id:t.id,timestamp:t.timestamp,name:t.name,type:t.type,value:t.value,tags:t.tags_json?JSON.parse(t.tags_json):{},service:t.service,environment:t.environment||void 0}}insertSpan(e){this.initializeSync();let n=e.spanId||v4(),t=e.startTime||new Date().toISOString();return this.db.run(`INSERT INTO traces (
386
+ trace_id, span_id, parent_span_id, service, symbol, operation,
387
+ start_time, end_time, duration_ms, status, tags_json, log_ids_json
388
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[e.traceId,n,e.parentSpanId||null,e.service,e.symbol,e.operation,t,e.endTime||null,e.durationMs??null,e.status||"ok",JSON.stringify(e.tags||{}),JSON.stringify(e.logIds||[])]),this.save(),n}getTrace(e){this.initializeSync();let n=this.db.exec("SELECT * FROM traces WHERE trace_id = ? ORDER BY start_time ASC",[e]);if(n.length===0||n[0].values.length===0)return null;let t=n[0].values.map(g=>this.rowToTraceSpan(n[0].columns,g)),s=[...new Set(t.map(g=>g.service))],r=t.map(g=>g.startTime),i=t.filter(g=>g.endTime).map(g=>g.endTime),a=r.sort()[0],c=i.length>0?i.sort().reverse()[0]:a,l=new Date(a).getTime(),u=new Date(c).getTime()-l;return {traceId:e,spans:t,services:s,totalDurationMs:u>0?u:0,startTime:a,endTime:c}}queryTraces(e={}){this.initializeSync();let n=[],t=[];e.service&&(n.push("service = ?"),t.push(e.service)),e.symbol&&(n.push("symbol = ?"),t.push(e.symbol)),e.since&&(n.push("start_time >= ?"),t.push(e.since));let s=n.length>0?`WHERE ${n.join(" AND ")}`:"",r=Math.min(e.limit||20,20),i=this.db.exec(`SELECT DISTINCT trace_id FROM traces ${s} ORDER BY start_time DESC LIMIT ?`,[...t,r]);if(i.length===0)return [];let a=[];for(let c of i[0].values){let l=c[0],d=this.getTrace(l);d&&a.push(d);}return a}rowToTraceSpan(e,n){let t={};return e.forEach((s,r)=>{t[s]=n[r];}),{traceId:t.trace_id,spanId:t.span_id,parentSpanId:t.parent_span_id||void 0,service:t.service,symbol:t.symbol,operation:t.operation,startTime:t.start_time,endTime:t.end_time||void 0,durationMs:t.duration_ms||void 0,status:t.status||"ok",tags:t.tags_json?JSON.parse(t.tags_json):{},logs:t.log_ids_json?JSON.parse(t.log_ids_json):[]}}registerSchema(e){this.initializeSync();let n=new Date().toISOString();return this.db.run(`INSERT INTO schemas (
389
+ id, version, name, description, scope_json, event_types_json,
390
+ causality_json, visualization_json, tags_json, registered_at, updated_at
391
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
392
+ ON CONFLICT(id) DO UPDATE SET
393
+ version = excluded.version,
394
+ name = excluded.name,
395
+ description = excluded.description,
396
+ scope_json = excluded.scope_json,
397
+ event_types_json = excluded.event_types_json,
398
+ causality_json = excluded.causality_json,
399
+ visualization_json = excluded.visualization_json,
400
+ tags_json = excluded.tags_json,
401
+ updated_at = excluded.updated_at`,[e.id,e.version,e.name,e.description||null,JSON.stringify(e.scope),JSON.stringify(e.eventTypes),e.causality?JSON.stringify(e.causality):null,e.visualization?JSON.stringify(e.visualization):null,JSON.stringify(e.tags||[]),n,n]),this.save(),{id:e.id,version:e.version,name:e.name,description:e.description,scope:e.scope,eventTypes:e.eventTypes,causality:e.causality,visualization:e.visualization,tags:e.tags||[],registeredAt:n,updatedAt:n}}getSchema(e){this.initializeSync();let n=this.db.exec("SELECT * FROM schemas WHERE id = ?",[e]);return n.length===0||n[0].values.length===0?null:this.rowToSchema(n[0].columns,n[0].values[0])}listSchemas(){this.initializeSync();let e=this.db.exec("SELECT * FROM schemas ORDER BY name ASC");return e.length===0?[]:e[0].values.map(n=>this.rowToSchema(e[0].columns,n))}rowToSchema(e,n){let t={};return e.forEach((s,r)=>{t[s]=n[r];}),{id:t.id,version:t.version,name:t.name,description:t.description||void 0,scope:JSON.parse(t.scope_json),eventTypes:JSON.parse(t.event_types_json),causality:t.causality_json?JSON.parse(t.causality_json):void 0,visualization:t.visualization_json?JSON.parse(t.visualization_json):void 0,tags:JSON.parse(t.tags_json||"[]"),registeredAt:t.registered_at,updatedAt:t.updated_at}}insertEventBatch(e,n,t){this.initializeSync();let s=this.getSchema(e),r=new Map;if(s)for(let c of s.eventTypes)r.set(c.type,{category:c.category,severity:c.severity||"info"});let i=0,a=[];for(let c of t)try{let l=c.id||v4(),d=c.timestamp||new Date().toISOString(),u=r.get(c.type),g=u?.category||"unknown",p=c.severity||u?.severity||"info",y=c.scopeValue!=null?String(c.scopeValue):null,f=typeof c.scopeValue=="number"?c.scopeValue:null;this.db.run(`INSERT INTO events (
402
+ id, schema_id, event_type, category, timestamp, scope_value,
403
+ scope_ordinal, session_id, service, data_json, severity,
404
+ parent_event_id, depth
405
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[l,e,c.type,g,d,y,f,c.sessionId||null,n,c.data?JSON.stringify(c.data):null,p,c.parentEventId||null,c.depth??0]),i++;}catch(l){a.push(l instanceof Error?l.message:String(l));}return this.save(),{accepted:i,errors:a}}queryEvents(e={}){this.initializeSync();let{limit:n=100,offset:t=0}=e,s=[],r=[];e.schemaId&&(s.push("schema_id = ?"),r.push(e.schemaId)),e.eventType&&(s.push("event_type = ?"),r.push(e.eventType)),e.category&&(s.push("category = ?"),r.push(e.category)),e.service&&(s.push("service = ?"),r.push(e.service)),e.sessionId&&(s.push("session_id = ?"),r.push(e.sessionId)),e.scopeValue&&(s.push("scope_value = ?"),r.push(e.scopeValue)),e.scopeFrom&&(s.push("scope_value >= ?"),r.push(e.scopeFrom)),e.scopeTo&&(s.push("scope_value <= ?"),r.push(e.scopeTo)),e.severity&&(s.push("severity = ?"),r.push(e.severity)),e.since&&(s.push("timestamp >= ?"),r.push(e.since)),e.until&&(s.push("timestamp <= ?"),r.push(e.until)),e.search&&(s.push("data_json LIKE ?"),r.push(`%${e.search}%`));let i=s.length>0?`WHERE ${s.join(" AND ")}`:"",a=this.db.exec(`SELECT * FROM events ${i} ORDER BY timestamp DESC LIMIT ? OFFSET ?`,[...r,n,t]);return a.length===0?[]:a[0].values.map(c=>this.rowToGenericEvent(a[0].columns,c))}queryEventsByScope(e,n){this.initializeSync();let t=this.db.exec(`SELECT * FROM events
406
+ WHERE schema_id = ? AND scope_value = ?
407
+ ORDER BY timestamp ASC`,[e,n]);return t.length===0?[]:t[0].values.map(s=>this.rowToGenericEvent(t[0].columns,s))}getEventScopes(e,n={}){this.initializeSync();let{limit:t=100,offset:s=0}=n,r=["schema_id = ?"],i=[e];n.sessionId&&(r.push("session_id = ?"),i.push(n.sessionId));let a=`WHERE ${r.join(" AND ")}`,c=this.db.exec(`SELECT
408
+ scope_value,
409
+ MIN(scope_ordinal) as scope_ordinal,
410
+ COUNT(*) as event_count,
411
+ MIN(timestamp) as first_timestamp,
412
+ MAX(timestamp) as last_timestamp
413
+ FROM events
414
+ ${a}
415
+ AND scope_value IS NOT NULL
416
+ GROUP BY scope_value
417
+ ORDER BY MIN(COALESCE(scope_ordinal, 0)) DESC, MIN(timestamp) DESC
418
+ LIMIT ? OFFSET ?`,[...i,t,s]);if(c.length===0)return [];let l=[];for(let d of c[0].values){let u=d[0],g=d[1]!=null?d[1]:void 0,p=d[2],y=d[3],f=d[4],T=this.db.exec(`SELECT category, COUNT(*) as count FROM events
419
+ WHERE schema_id = ? AND scope_value = ?
420
+ GROUP BY category`,[e,u]),j={};if(T.length>0)for(let X of T[0].values)j[X[0]]=X[1];l.push({scopeValue:u,scopeOrdinal:g,eventCount:p,categories:j,firstTimestamp:y,lastTimestamp:f});}return l}getEventCount(e={}){this.initializeSync();let n=[],t=[];e.schemaId&&(n.push("schema_id = ?"),t.push(e.schemaId)),e.eventType&&(n.push("event_type = ?"),t.push(e.eventType)),e.service&&(n.push("service = ?"),t.push(e.service)),e.since&&(n.push("timestamp >= ?"),t.push(e.since)),e.until&&(n.push("timestamp <= ?"),t.push(e.until));let s=n.length>0?`WHERE ${n.join(" AND ")}`:"",r=this.db.exec(`SELECT COUNT(*) as count FROM events ${s}`,t);return r.length===0||r[0].values.length===0?0:r[0].values[0][0]}pruneEvents(e){if(this.initializeSync(),e<=0)return 0;let n=this.getEventCount();if(n<=e)return 0;let t=n-e;return this.db.run(`DELETE FROM events WHERE id IN (
421
+ SELECT id FROM events ORDER BY timestamp ASC LIMIT ?
422
+ )`,[t]),this.save(),t}rowToGenericEvent(e,n){let t={};return e.forEach((s,r)=>{t[s]=n[r];}),{id:t.id,schemaId:t.schema_id,eventType:t.event_type,category:t.category,timestamp:t.timestamp,scopeValue:t.scope_value||void 0,scopeOrdinal:t.scope_ordinal!=null?t.scope_ordinal:void 0,sessionId:t.session_id||void 0,service:t.service,data:t.data_json?JSON.parse(t.data_json):void 0,severity:t.severity||"info",parentEventId:t.parent_event_id||void 0,depth:t.depth||0}}close(){this.db&&(this.save(),this.db.close(),this.db=null);}};var nt={minScore:30,maxResults:5,boostConfidence:true},q=class{constructor(e){this.storage=e;}match(e,n={}){let{minScore:t,maxResults:s,boostConfidence:r}={...nt,...n},i=this.storage.getAllPatterns({includePrivate:true}),a=[];for(let c of i){if(!this.matchEnvironment(c,e))continue;let{score:l,matchedCriteria:d}=this.scoreMatch(c,e);if(l>=t){let u=l;if(r){let g=c.confidence.score/100;u=l*(.5+.5*g);}a.push({pattern:c,score:l,matchedCriteria:d,confidence:Math.round(u)}),this.storage.updatePatternConfidence(c.id,"matched");}}return a.sort((c,l)=>l.confidence-c.confidence).slice(0,s)}testPattern(e,n=100){let t=this.storage.getRecentIncidents({limit:n}),s=[],r=0;for(let i of t){if(!this.matchEnvironment(e,i))continue;let{score:a}=this.scoreMatch(e,i);a>=30&&(s.push(i),r+=a);}return {wouldMatch:s,matchCount:s.length,avgScore:s.length>0?Math.round(r/s.length):0}}scoreMatch(e,n){let t=0,s={symbols:[],errorKeywords:[],missingSignals:[]},r=this.matchSymbols(e.pattern.symbols,n.symbols,s.symbols);t+=Math.min(r,50);let i=this.matchErrorText(e,n,s.errorKeywords);t+=Math.min(i,25);let a=this.matchMissingSignals(e,n,s.missingSignals);return t+=Math.min(a,25),t=Math.min(t,100),{score:t,matchedCriteria:s}}matchSymbols(e,n,t){let s=0,r=["feature","component","flow","gate","signal","state","integration"];for(let i of r){let a=e[i],c=n[i];if(!(!a||!c)){if(typeof a=="string")this.matchSingleSymbol(a,c)&&(s+=a.includes("*")?5:10,t.push(i));else if(Array.isArray(a)){for(let l of a)if(this.matchSingleSymbol(l,c)){s+=7,t.push(i);break}}}}return s}matchSingleSymbol(e,n){if(e==="*")return true;if(e.endsWith("*")){let t=e.slice(0,-1);return n.startsWith(t)}if(e.startsWith("*")){let t=e.slice(1);return n.endsWith(t)}return e.includes("*")?new RegExp("^"+e.replace(/\*/g,".*")+"$").test(n):e===n}matchErrorText(e,n,t){let s=0,r=n.error.message.toLowerCase(),i=n.error.type?.toLowerCase();if(e.pattern.errorContains)for(let a of e.pattern.errorContains)r.includes(a.toLowerCase())&&(s+=5,t.push(a));if(e.pattern.errorMatches)try{new RegExp(e.pattern.errorMatches,"i").test(n.error.message)&&(s+=10,t.push(`regex:${e.pattern.errorMatches}`));}catch{}if(e.pattern.errorType&&i)for(let a of e.pattern.errorType)i.includes(a.toLowerCase())&&(s+=5,t.push(`type:${a}`));return s}matchMissingSignals(e,n,t){if(!e.pattern.missingSignals||!n.flowPosition?.missing)return 0;let s=0;for(let r of e.pattern.missingSignals)for(let i of n.flowPosition.missing)if(this.matchSingleSymbol(r,i)){s+=12,t.push(i);break}return s}matchEnvironment(e,n){return !e.pattern.environment||e.pattern.environment.length===0?true:e.pattern.environment.includes(n.environment)}};var G=class{constructor(e){this.storage=e;}getStats(e=7){let n=new Date().toISOString(),t=new Date(Date.now()-e*24*60*60*1e3).toISOString();return this.storage.getStats({start:t,end:n})}getSymbolHealth(e){return this.storage.getSymbolHealth(e)}getTrendingIssues(e=7){let n=Date.now(),t=e*24*60*60*1e3/2,s=new Date(n-e*24*60*60*1e3).toISOString(),r=new Date(n-t).toISOString(),i=new Date(n).toISOString(),a=this.storage.getRecentIncidents({dateFrom:s,dateTo:r,limit:1e3}),c=this.storage.getRecentIncidents({dateFrom:r,dateTo:i,limit:1e3}),l=this.countSymbols(a),d=this.countSymbols(c),u=[],g=new Set([...l.keys(),...d.keys()]);for(let p of g){let y=l.get(p)||0,f=d.get(p)||0;if(y===0&&f>0)u.push({symbol:p,trend:f*100});else if(y>0){let T=(f-y)/y*100;u.push({symbol:p,trend:T});}}return u.filter(p=>p.trend>0).sort((p,y)=>y.trend-p.trend).slice(0,10)}getResolutionMetrics(){let e=this.getStats(30);return {avgTimeToResolve:e.resolution.avgTimeToResolve,resolvedWithPattern:e.resolution.resolvedWithPattern,resolvedManually:e.resolution.resolvedManually,totalResolved:e.incidents.resolved,resolutionRate:e.resolution.resolutionRate}}getPatternEffectiveness(){return this.storage.getAllPatterns({includePrivate:true}).filter(n=>n.confidence.timesMatched>0).map(n=>({patternId:n.id,name:n.name,matches:n.confidence.timesMatched,resolutions:n.confidence.timesResolved,recurrences:n.confidence.timesRecurred,effectiveness:n.confidence.timesMatched>0?Math.round((n.confidence.timesResolved-n.confidence.timesRecurred)/n.confidence.timesMatched*100):0})).sort((n,t)=>t.effectiveness-n.effectiveness)}getIncidentsByHour(e=7){let n=new Date(Date.now()-e*24*60*60*1e3).toISOString(),t=this.storage.getRecentIncidents({dateFrom:n,limit:1e4}),s=new Map;for(let r=0;r<24;r++)s.set(r,0);for(let r of t){let i=new Date(r.timestamp).getHours();s.set(i,(s.get(i)||0)+1);}return Array.from(s.entries()).map(([r,i])=>({hour:r,count:i}))}getIncidentsByEnvironment(){let e=this.getStats(30),n=e.incidents.total;return Object.entries(e.incidents.byEnvironment).map(([t,s])=>({environment:t,count:s,percentage:n>0?Math.round(s/n*100):0})).sort((t,s)=>s.count-t.count)}getSymbolCorrelation(){let e=this.storage.getRecentIncidents({limit:1e3}),n=new Map,t=new Map;for(let r of e){let i=this.getSymbolsFromIncident(r);for(let a of i)t.set(a,(t.get(a)||0)+1);for(let a=0;a<i.length;a++)for(let c=a+1;c<i.length;c++){let l=[i[a],i[c]].sort().join("|");n.set(l,(n.get(l)||0)+1);}}let s=[];for(let[r,i]of n){let[a,c]=r.split("|"),l=t.get(a)||1,d=t.get(c)||1,u=i/Math.max(l,d);u>.3&&s.push({symbol1:a,symbol2:c,correlation:Math.round(u*100)/100});}return s.sort((r,i)=>i.correlation-r.correlation).slice(0,20)}generateDashboard(e=7){let n=this.getStats(e),t=[];t.push("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"),t.push("\u2551 PARADIGM SENTINEL DASHBOARD \u2551"),t.push("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563");let s=n.incidents.byDay[n.incidents.byDay.length-1]?.count||0;t.push(`\u2551 Open: ${String(n.incidents.open).padEnd(4)} \u2502 Investigating: ${String(n.incidents.total-n.incidents.open-n.incidents.resolved).padEnd(3)} \u2502 Resolved: ${String(n.incidents.resolved).padEnd(4)} \u2502 Today: +${s} \u2551`),t.push("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"),t.push(""),t.push("Incidents by Day (last 7 days):"),t.push("\u2500".repeat(50));let r=Math.max(...n.incidents.byDay.map(i=>i.count),1);for(let i of n.incidents.byDay.slice(-7)){let a=Math.round(i.count/r*30),c="\u2588".repeat(a);t.push(`${i.date.substring(5)} ${c} ${i.count}`);}t.push(""),t.push("Most Affected Symbols:"),t.push("\u2500".repeat(50));for(let{symbol:i,count:a}of n.symbols.mostIncidents.slice(0,5))t.push(` ${i.padEnd(25)} ${a} incidents`);t.push(""),t.push("Top Patterns:"),t.push("\u2500".repeat(50));for(let{patternId:i,resolvedCount:a}of n.patterns.mostEffective.slice(0,5))t.push(` ${i.padEnd(25)} ${a} resolved`);return t.push(""),t.push("Resolution Stats:"),t.push("\u2500".repeat(50)),t.push(` Resolution rate: ${Math.round(n.resolution.resolutionRate)}%`),t.push(` With pattern: ${n.resolution.resolvedWithPattern}`),t.push(` Manual: ${n.resolution.resolvedManually}`),t.join(`
423
+ `)}countSymbols(e){let n=new Map;for(let t of e)for(let[,s]of Object.entries(t.symbols))s&&n.set(s,(n.get(s)||0)+1);return n}getSymbolsFromIncident(e){let n=[];for(let[,t]of Object.entries(e.symbols))t&&n.push(t);return n}};var W=class{build(e){if(!e.flowPosition)return null;let n=[],t=new Date(e.timestamp).getTime();n.push({timestamp:new Date(t-5e3).toISOString(),symbol:e.flowPosition.flowId,type:"flow-started"});let s=1e3;for(let i of e.flowPosition.actual){let a=this.inferEventType(i);n.push({timestamp:new Date(t-4e3+s).toISOString(),symbol:i,type:a}),s+=Math.random()*1e3+500;}let r=e.flowPosition.failedAt||e.flowPosition.missing[0]||e.symbols.gate||e.symbols.signal||"unknown";return n.push({timestamp:e.timestamp,symbol:r,type:"error",data:{message:e.error.message,missing:e.flowPosition.missing}}),{incidentId:e.id,flowId:e.flowPosition.flowId,events:n,failure:{at:e.timestamp,symbol:r,reason:e.error.message}}}renderAscii(e){let n=[];n.push(`${e.flowId} Timeline`),n.push("\u2550".repeat(40)),n.push("");for(let s of e.events){let r=this.formatTime(s.timestamp),i=this.getEventIcon(s.type),a=this.getEventStatus(s.type),c=`${r} ${i} ${s.symbol}`;a&&(c+=` (${a})`),n.push(c),s.type==="error"&&s.data&&(n.push(` \u2514\u2500 ${s.data.message}`),s.data.missing&&Array.isArray(s.data.missing)&&s.data.missing.length>0&&n.push(` \u2514\u2500 Expected: ${s.data.missing.join(", ")}`));}let t=e.events.find(s=>s.type==="error")?.data?.missing;return t&&t.length>0&&(n.push(""),n.push(`Missing signals: ${t.join(", ")}`)),n.join(`
424
+ `)}renderStructured(e){return {incidentId:e.incidentId,flow:{id:e.flowId,eventCount:e.events.length},events:e.events.map(n=>({time:this.formatTime(n.timestamp),symbol:n.symbol,type:n.type,status:this.getEventStatus(n.type),data:n.data})),failure:{at:this.formatTime(e.failure.at),symbol:e.failure.symbol,reason:e.failure.reason}}}inferEventType(e){return e.startsWith("^")?"gate-passed":e.startsWith("!")?"signal-emitted":e.startsWith("%")?"state-changed":"signal-emitted"}getEventIcon(e){switch(e){case "flow-started":return "\u25B6";case "flow-ended":return "\u25A0";case "gate-passed":return "\u2713";case "gate-failed":return "\u2717";case "signal-emitted":return "\u26A1";case "state-changed":return "\u25C6";case "error":return "\u2717";default:return "\u2022"}}getEventStatus(e){switch(e){case "gate-passed":return "PASSED";case "gate-failed":return "FAILED";case "signal-emitted":return "EMITTED";case "state-changed":return "CHANGED";case "error":return "ERROR";default:return ""}}formatTime(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),s=String(n.getMinutes()).padStart(2,"0"),r=String(n.getSeconds()).padStart(2,"0"),i=String(n.getMilliseconds()).padStart(3,"0");return `${t}:${s}:${r}.${i}`}};var rt=fileURLToPath(import.meta.url),Ne=S.dirname(rt);function it(){let o=S.join(Ne,"universal-patterns.json"),e=E.readFileSync(o,"utf-8");return JSON.parse(e)}function ot(){let o=S.join(Ne,"paradigm-patterns.json"),e=E.readFileSync(o,"utf-8");return JSON.parse(e)}function Oe(){let o=it(),e=ot();return {version:"1.0.0",exportedAt:new Date().toISOString(),patterns:[...o.patterns,...e.patterns]}}var at=process.env.SENTINEL_LOG_LEVEL||process.env.LOG_LEVEL||"info",xe={debug:0,info:1,warn:2,error:3};function A(o){return xe[o]>=xe[at]}function P(o){if(!o)return "";let e=Object.entries(o).map(([n,t])=>`${n}=${typeof t=="string"?t:JSON.stringify(t)}`).join(" ");return m.gray(` ${e}`)}var v={component(o){let e=m.magenta(`#${o}`);return {debug:(n,t)=>{A("debug")&&console.log(`${m.gray("\u25CB")} ${e} ${n}${P(t)}`);},info:(n,t)=>{A("info")&&console.log(`${m.blue("\u2139")} ${e} ${n}${P(t)}`);},warn:(n,t)=>{A("warn")&&console.log(`${m.yellow("\u26A0")} ${e} ${n}${P(t)}`);},error:(n,t)=>{A("error")&&console.error(`${m.red("\u2716")} ${e} ${n}${P(t)}`);}}},flow(o){let e=m.yellow(`$${o}`);return {debug:(n,t)=>{A("debug")&&console.log(`${m.gray("\u25CB")} ${e} ${n}${P(t)}`);},info:(n,t)=>{A("info")&&console.log(`${m.blue("\u2139")} ${e} ${n}${P(t)}`);},warn:(n,t)=>{A("warn")&&console.log(`${m.yellow("\u26A0")} ${e} ${n}${P(t)}`);},error:(n,t)=>{A("error")&&console.error(`${m.red("\u2716")} ${e} ${n}${P(t)}`);}}}},Le=new Set(["$lib","$env","$app","$service-worker","$virtual","$schema","$ref","$id","$type"]);async function Q(o){let e=S.join(o,".paradigm","config.yaml");if(!E.existsSync(e)){let n=S.join(o,"package.json");if(E.existsSync(n))try{return {name:JSON.parse(E.readFileSync(n,"utf-8")).name}}catch{}return {}}try{let n=E.readFileSync(e,"utf-8"),t={},s=n.match(/^name:\s*(.+)$/m);s&&(t.name=s[1].trim().replace(/^["']|["']$/g,""));let r=n.match(/^discipline:\s*(.+)$/m);r&&(t.discipline=r[1].trim());let i=n.match(/^version:\s*(.+)$/m);return i&&(t.version=i[1].trim()),t}catch(n){return v.component("config-loader").error("Failed to load Paradigm config",{error:String(n)}),{}}}async function ct(o){try{let{aggregateFromDirectory:e}=await import('./dist-R3RWD35F.js');v.flow("load-symbols").info("Using premise-core aggregator",{path:o});let n=await e(o),t={};for(let s of n.symbols)t[s.type]=(t[s.type]||0)+1;if(v.flow("load-symbols").info("Aggregation complete",{total:n.symbols.length,...t,purposeFiles:n.purposeFiles.length,portalFiles:n.portalFiles.length}),n.errors.length>0)for(let s of n.errors)v.component("aggregator").warn("Aggregation error",{source:s.source,file:s.filePath,message:s.message});for(let s of n.purposeFiles)v.component("purpose-loader").info("Loaded .purpose file",{file:S.relative(o,s)});for(let s of n.portalFiles)v.component("gate-loader").info("Loaded portal.yaml",{file:S.relative(o,s)});return n.symbols}catch(e){return v.component("premise-core").warn("premise-core not available, using fallback scanner",{error:e instanceof Error?e.message:String(e)}),null}}async function $(o){v.flow("load-symbols").info("Loading symbols",{projectDir:o});let e=S.join(o,".paradigm","index.json");if(E.existsSync(e))try{v.component("index-loader").info("Found cached index",{path:e});let t=E.readFileSync(e,"utf-8"),s=JSON.parse(t),r=Array.isArray(s.entries)?s.entries:Array.isArray(s)?s:null;if(r)return v.flow("load-symbols").info("Loaded from cached index",{count:r.length}),r}catch(t){v.component("index-loader").error("Failed to load cached index",{error:String(t)});}let n=await ct(o);return n||(v.flow("load-symbols").info("Using fallback scanner"),lt(o))}async function lt(o){let e=[],n=new Set,t=["src","lib","packages","apps","."];for(let r of t){let i=S.join(o,r);E.existsSync(i)&&await we(i,e,n,o);}let s=S.join(o,"portal.yaml");if(E.existsSync(s)){v.component("gate-loader").debug("Found portal.yaml",{path:"portal.yaml"});try{let i=E.readFileSync(s,"utf-8").match(/^gates:\s*\n((?: .+\n)*)/m);if(i){let a=i[1].matchAll(/^ ([a-z][a-z0-9-]*):/gm);for(let c of a){let l=c[1],d=`gate-${l}`;n.has(d)||(n.add(d),e.push({id:d,symbol:`^${l}`,type:"gate",source:"portal",filePath:"portal.yaml",data:{},references:[],referencedBy:[]}),v.component("gate-loader").debug("Extracted gate",{symbol:`^${l}`}));}}}catch(r){v.component("gate-loader").error("Failed to parse portal.yaml",{error:String(r)});}}return v.flow("load-symbols").info("Fallback scan complete",{count:e.length}),e}async function we(o,e,n,t){let s=["node_modules",".git","dist","build",".paradigm","coverage",".next",".svelte-kit"],r;try{r=E.readdirSync(o,{withFileTypes:!0});}catch{return}for(let i of r){let a=S.join(o,i.name);if(i.isDirectory())s.includes(i.name)||await we(a,e,n,t);else if(i.name===".purpose"){let c=S.relative(t,a);v.component("purpose-loader").debug("Scanning .purpose file",{path:c});try{let l=E.readFileSync(a,"utf-8"),d=ut(l,a,t);for(let u of d)n.has(u.id)||(n.add(u.id),e.push(u),v.component("purpose-loader").debug("Extracted symbol",{symbol:u.symbol,type:u.type,file:c}));}catch(l){v.component("purpose-loader").error("Failed to parse .purpose file",{path:c,error:String(l)});}}}}function ut(o,e,n){let t=[],s=S.relative(n,e),r=o.matchAll(/(?:^|\s)#([a-z][a-z0-9-]*)/gm);for(let d of r){let u=d[1];t.push({id:`component-${u}`,symbol:`#${u}`,type:"component",source:"purpose",filePath:s,data:{},description:dt(o,`#${u}`),references:mt(o),referencedBy:[],tags:gt(o)});}let i=o.matchAll(/\$([a-z][a-z0-9-]*)/gm);for(let d of i){let u=d[1],g=`$${u}`;if(Le.has(g)){v.component("purpose-loader").debug("Skipping blocklisted symbol",{symbol:g});continue}t.find(p=>p.symbol===g)||t.push({id:`flow-${u}`,symbol:g,type:"flow",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let a=o.matchAll(/!([a-z][a-z0-9-]*)/gm);for(let d of a){let u=d[1];t.find(g=>g.symbol===`!${u}`)||t.push({id:`signal-${u}`,symbol:`!${u}`,type:"signal",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let c=o.matchAll(/\^([a-z][a-z0-9-]*)/gm);for(let d of c){let u=d[1];t.find(g=>g.symbol===`^${u}`)||t.push({id:`gate-${u}`,symbol:`^${u}`,type:"gate",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}let l=o.matchAll(/~([a-z][a-z0-9-]*)/gm);for(let d of l){let u=d[1];t.find(g=>g.symbol===`~${u}`)||t.push({id:`aspect-${u}`,symbol:`~${u}`,type:"aspect",source:"purpose",filePath:s,data:{},references:[],referencedBy:[]});}return t}function dt(o,e){let n=new RegExp(`${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\s*[-:]?\\s*(.+)`,"m"),t=o.match(n);if(t&&t[1])return t[1].trim()}function mt(o){let e=new Set,n=o.matchAll(/[@#$!^~]([a-z][a-z0-9-]*)/g);for(let t of n){let s=t[0];Le.has(s)||e.add(s);}return Array.from(e)}function gt(o){let e=o.match(/tags:\s*\[([^\]]+)\]/);return e?e[1].split(",").map(n=>n.trim().replace(/^["']|["']$/g,"")):[]}async function Z(o){return (await $(o)).length}async function Ce(o,e,n){let s=(await $(o)).find(i=>i.id===e);if(!s)return {success:false,error:"Symbol not found"};let r=S.join(o,s.filePath);if(!E.existsSync(r))return {success:false,error:"Source file not found"};try{let i=E.readFileSync(r,"utf-8"),a=!1;if(n.description!==void 0){let c=s.symbol.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),l=new RegExp(`(${c})\\s*[-:]?\\s*(.*)`,"m");if(i.match(l)){let u=n.description?`${s.symbol}: ${n.description}`:s.symbol;i=i.replace(l,u),a=!0;}}if(n.tags!==void 0){let c=n.tags.length>0?`tags: [${n.tags.map(d=>`"${d}"`).join(", ")}]`:"",l=/^tags:\s*\[[^\]]*\]\s*$/m;if(l.test(i))c?i=i.replace(l,c):i=i.replace(l,""),a=!0;else if(c){let d=s.symbol.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),u=new RegExp(`(${d}[^\\n]*\\n)`,"m");i.match(u)&&(i=i.replace(u,`$1${c}
425
+ `),a=!0);}}if(a){i=i.replace(/\n{3,}/g,`
426
+
427
+ `),E.writeFileSync(r,i,"utf-8"),v.component("symbol-updater").info("Updated symbol",{symbol:s.symbol,file:s.filePath});let c=S.join(o,".paradigm","index.json");if(E.existsSync(c))try{let l=E.readFileSync(c,"utf-8"),d=JSON.parse(l),u=Array.isArray(d.entries)?d.entries:d,g=u.findIndex(p=>p.id===e);g>=0&&(n.description!==void 0&&(u[g].description=n.description),n.tags!==void 0&&(u[g].tags=n.tags),Array.isArray(d.entries)?(d.entries=u,E.writeFileSync(c,JSON.stringify(d,null,2),"utf-8")):E.writeFileSync(c,JSON.stringify(u,null,2),"utf-8"));}catch{}return {success:!0}}return {success:!0}}catch(i){return v.component("symbol-updater").error("Failed to update symbol",{error:String(i)}),{success:false,error:"Failed to write file"}}}var ft=process.env.SENTINEL_LOG_LEVEL||process.env.LOG_LEVEL||"info",Ae=o=>{let e={debug:0,info:1,warn:2,error:3};return e[o]>=e[ft]},M={gate(o){let e=m.cyan(`^${o}`);return {info:(n,t)=>{if(Ae("info")){let s=t?m.gray(` ${Object.entries(t).map(([r,i])=>`${r}=${i}`).join(" ")}`):"";console.log(`${m.blue("\u2139")} ${e} ${n}${s}`);}},error:(n,t)=>{if(Ae("error")){let s=t?m.gray(` ${Object.entries(t).map(([r,i])=>`${r}=${i}`).join(" ")}`):"";console.error(`${m.red("\u2716")} ${e} ${n}${s}`);}}}}};function ee(o){let e=Router();return e.get("/",async(n,t)=>{try{let s=await $(o);M.gate("api-symbols").info("Symbols loaded",{count:s.length}),t.json({symbols:s});}catch(s){M.gate("api-symbols").error("Failed to load symbols",{error:String(s)}),t.status(500).json({error:"Failed to load symbols"});}}),e.put("/:id",async(n,t)=>{try{let{id:s}=n.params,r=n.body;if(M.gate("api-symbols").info("Update requested",{id:s,updates:JSON.stringify(r)}),r.tags&&!Array.isArray(r.tags)){t.status(400).json({error:"Tags must be an array"});return}let i=await Ce(o,s,r);if(i.success){let c=(await $(o)).find(l=>l.id===s);M.gate("api-symbols").info("Symbol updated",{id:s}),t.json({success:!0,symbol:c});}else M.gate("api-symbols").error("Update failed",{id:s,error:i.error}),t.status(400).json({success:!1,error:i.error});}catch(s){M.gate("api-symbols").error("Failed to update symbol",{error:String(s)}),t.status(500).json({error:"Failed to update symbol"});}}),e}function te(o){let e=Router();return e.get("/",async(n,t)=>{try{let s=await Q(o),r=await Z(o);t.json({projectName:s.name||null,discipline:s.discipline||null,symbolCount:r,projectDir:o});}catch(s){console.error("Failed to load project info:",s),t.status(500).json({error:"Failed to load project info"});}}),e}function vt(o){let e=new Set;for(let n of o){if(n.endsWith(".purpose")){let r=S.dirname(n),i=S.basename(r);r.includes("features/")||r.includes("routes/")||r.includes("api/")?e.add(`@${i}`):r.includes("components/")||r.includes("lib/")||r.includes("utils/")?e.add(`#${i}`):r.includes("middleware/")||r.includes("auth/")||r.includes("guards/")?e.add(`^${i}`):(r.includes("flows/")||r.includes("workflows/"))&&e.add(`$${i}`);}n.includes("portal.yaml")&&e.add("^portal");let t=n.match(/features\/([^/]+)/);t&&e.add(`@${t[1]}`);let s=n.match(/components\/([^/]+)/);s&&e.add(`#${s[1]}`);}return Array.from(e)}async function ne(o,e={}){let n=ht(o);if(!await n.checkIsRepo())return [];try{let s={maxCount:e.limit||100};e.since&&(s["--since"]=e.since);let r=await n.log(s),i=[];for(let a of r.all){let c=[],l=[];try{c=(await n.diffSummary([`${a.hash}^`,a.hash])).files.map(u=>u.file),l=vt(c);}catch{}i.push({hash:a.hash,shortHash:a.hash.slice(0,7),date:a.date,author:a.author_name,message:a.message.split(`
428
+ `)[0],symbolsModified:l,filesChanged:c});}return i}catch(s){return console.error("Failed to load git history:",s),[]}}function se(o){let e=Router();return e.get("/",async(n,t)=>{try{let s=parseInt(n.query.limit)||100,r=n.query.since,i=await ne(o,{limit:s,since:r});t.json({commits:i});}catch(s){console.error("Failed to load commits:",s),t.status(500).json({error:"Failed to load commits"});}}),e}function re(o){let e=Router(),n=new _;return e.get("/",async(t,s)=>{try{let r=parseInt(t.query.limit)||50,i=t.query.status,a=t.query.environment,c=t.query.symbol,l={limit:r};i&&["open","investigating","resolved","wont-fix"].includes(i)&&(l.status=i),a&&(l.environment=a),c&&(l.symbol=c);let u=n.getRecentIncidents(l).map(g=>({id:g.id,timestamp:g.timestamp,status:g.status,error:{message:g.error.message,type:g.error.type},symbols:g.symbols,environment:g.environment,patternMatches:[]}));s.json({incidents:u});}catch(r){console.error("Failed to load incidents:",r),s.status(500).json({error:"Failed to load incidents"});}}),e.get("/:id",async(t,s)=>{try{let r=n.getIncident(t.params.id);if(!r){s.status(404).json({error:"Incident not found"});return}s.json({incident:r});}catch(r){console.error("Failed to load incident:",r),s.status(500).json({error:"Failed to load incident"});}}),e.post("/:id/resolve",async(t,s)=>{try{if(!n.getIncident(t.params.id)){s.status(404).json({error:"Incident not found"});return}n.resolveIncident(t.params.id,{notes:t.body.notes,patternId:t.body.patternId}),s.json({success:!0});}catch(r){console.error("Failed to resolve incident:",r),s.status(500).json({error:"Failed to resolve incident"});}}),e}function ie(o){let e=Router(),n=new _;return e.get("/",async(t,s)=>{try{let r=t.query.source,i=t.query.symbol,a=parseInt(t.query.minConfidence)||void 0,c={};r&&["manual","suggested","imported","community"].includes(r)&&(c.source=r),i&&(c.symbol=i),a&&(c.minConfidence=a);let d=n.getAllPatterns(c).map(u=>({id:u.id,name:u.name,description:u.description,confidence:{score:u.confidence.score,timesMatched:u.confidence.timesMatched,timesResolved:u.confidence.timesResolved},tags:u.tags}));s.json({patterns:d});}catch(r){console.error("Failed to load patterns:",r),s.status(500).json({error:"Failed to load patterns"});}}),e.get("/:id",async(t,s)=>{try{let r=n.getPattern(t.params.id);if(!r){s.status(404).json({error:"Pattern not found"});return}s.json({pattern:r});}catch(r){console.error("Failed to load pattern:",r),s.status(500).json({error:"Failed to load pattern"});}}),e}function Pe(o){return o.startsWith("#")?"component":o.startsWith("^")?"gate":o.startsWith("!")?"signal":o.startsWith("$")?"flow":o.startsWith("~")?"aspect":"raw"}function Rt(o,e){if(e.find(i=>i.symbol===o))return {known:true};let t=o.replace(/^[#^!$~]/,""),s,r=0;for(let i of e){let a=i.symbol.replace(/^[#^!$~]/,""),c=0;for(let d=0;d<Math.min(t.length,a.length)&&t[d]===a[d];d++)c++;let l=c/Math.max(t.length,a.length);l>r&&l>.5&&(r=l,s=i.symbol);}return {known:false,suggestion:s}}function _t(o,e){try{let n=Pe(o.symbol),t={};n==="component"?t.component=o.symbol:n==="gate"?t.gate=o.symbol:n==="signal"?t.signal=o.symbol:n==="flow"?t.flow=o.symbol:t.component=o.symbol,e.recordIncident({error:{message:o.message,type:"LogError"},symbols:t,environment:o.environment||"unknown",service:o.service});}catch{}}var oe=0;function ae(o){let e=Router(),{storage:n,serverConfig:t,onLogReceived:s,symbolIndex:r}=o;return e.post("/",async(i,a)=>{try{let c=i.body,l;if(Array.isArray(c.entries))l=c.entries;else if(c.level&&c.symbol&&c.message&&c.service)l=[c];else {a.status(400).json({error:"Expected {entries: [...]} or a single log entry with level, symbol, message, service"});return}if(l.length>t.maxBatchSize){a.status(413).json({error:`Batch too large: ${l.length} entries, max ${t.maxBatchSize}`});return}for(let u=0;u<l.length;u++){let g=l[u];if(!g.level||!g.symbol||!g.message||!g.service){a.status(400).json({error:`Entry ${u}: missing required fields (level, symbol, message, service)`});return}if(!["debug","info","warn","error"].includes(g.level)){a.status(400).json({error:`Entry ${u}: invalid level "${g.level}", must be debug|info|warn|error`});return}}let d=n.insertLogBatch(l);for(let u of l){let g={id:u.id||v4(),timestamp:u.timestamp||new Date().toISOString(),level:u.level,symbol:u.symbol,symbolType:u.symbolType||Pe(u.symbol),message:u.message,data:u.data,service:u.service,sessionId:u.sessionId,correlationId:u.correlationId,durationMs:u.durationMs,environment:u.environment},p;r&&(p=Rt(g.symbol,r)),g.level==="error"&&_t(g,n),s&&s(g,p);}oe+=d.accepted,t.maxLogs>0&&oe>=t.pruneIntervalInserts&&(oe=0,n.pruneLogs(t.maxLogs)),a.json({accepted:d.accepted,errors:d.errors.length>0?d.errors:void 0});}catch{a.status(500).json({error:"Failed to insert logs"});}}),e.get("/",async(i,a)=>{try{let c={level:i.query.level,symbol:i.query.symbol,service:i.query.service,sessionId:i.query.sessionId,correlationId:i.query.correlationId,search:i.query.search,since:i.query.since,until:i.query.until,limit:i.query.limit?parseInt(i.query.limit):100,offset:i.query.offset?parseInt(i.query.offset):0},l=n.queryLogs(c),d=n.getLogCount(c);a.json({count:l.length,total:d,logs:l});}catch{a.status(500).json({error:"Failed to query logs"});}}),e}function ce(o){let e=Router(),{storage:n}=o;return e.post("/",async(t,s)=>{try{let{name:r,version:i,pid:a,environment:c,metadata:l}=t.body;if(!r){s.status(400).json({error:"Missing required field: name"});return}n.registerService({name:r,version:i,pid:a,environment:c,metadata:l}),s.json({success:!0,service:r});}catch{s.status(500).json({error:"Failed to register service"});}}),e.get("/",async(t,s)=>{try{let r=n.getServices();s.json({count:r.length,services:r});}catch{s.status(500).json({error:"Failed to list services"});}}),e}function le(o){let e=Router(),{storage:n}=o;return e.post("/",async(t,s)=>{try{let{service:r,sessionId:i,state:a,activeFlows:c,activeGates:l}=t.body;if(!r||!i||!a){s.status(400).json({error:"Missing required fields: service, sessionId, state"});return}n.upsertAppState({service:r,sessionId:i,timestamp:new Date().toISOString(),state:a,activeFlows:c,activeGates:l}),n.updateServiceLastSeen(r),s.json({success:!0});}catch{s.status(500).json({error:"Failed to update state"});}}),e.get("/",async(t,s)=>{try{let r=n.getAllAppStates();s.json({count:r.length,states:r});}catch{s.status(500).json({error:"Failed to get states"});}}),e.get("/:service",async(t,s)=>{try{let r=n.getAppState(t.params.service);s.json({count:r.length,states:r});}catch{s.status(500).json({error:"Failed to get service state"});}}),e}var Ot=["counter","gauge","histogram"];function ue(o){let e=Router(),{storage:n,serverConfig:t}=o;return e.post("/",(s,r)=>{try{let i=s.body,a;if(Array.isArray(i.entries))a=i.entries;else if(i.name&&i.type&&i.value!==void 0&&i.service)a=[i];else {r.status(400).json({error:"Expected {entries: [...]} or a single metric with name, type, value, service"});return}if(a.length>t.maxBatchSize){r.status(413).json({error:`Batch too large: ${a.length} entries, max ${t.maxBatchSize}`});return}for(let l=0;l<a.length;l++){let d=a[l];if(!d.name||!d.type||d.value===void 0||!d.service){r.status(400).json({error:`Entry ${l}: missing required fields (name, type, value, service)`});return}if(!Ot.includes(d.type)){r.status(400).json({error:`Entry ${l}: invalid type "${d.type}", must be counter|gauge|histogram`});return}}let c=n.insertMetricBatch(a);r.json({accepted:c.accepted,errors:c.errors.length>0?c.errors:void 0});}catch{r.status(500).json({error:"Failed to insert metrics"});}}),e.get("/",(s,r)=>{try{let i={name:s.query.name,type:s.query.type,service:s.query.service,tag:s.query.tag,since:s.query.since,until:s.query.until,limit:s.query.limit?parseInt(s.query.limit):100,offset:s.query.offset?parseInt(s.query.offset):0},a=n.queryMetrics(i),c=n.getMetricCount(i);r.json({count:a.length,total:c,metrics:a});}catch{r.status(500).json({error:"Failed to query metrics"});}}),e.get("/aggregate/:name",(s,r)=>{try{let i=n.aggregateMetric(s.params.name,{service:s.query.service,since:s.query.since,until:s.query.until});r.json(i);}catch{r.status(500).json({error:"Failed to aggregate metric"});}}),e}function de(o){let e=Router(),{storage:n}=o;return e.post("/",(t,s)=>{try{let r=t.body;if(!r.traceId||!r.service||!r.symbol||!r.operation){s.status(400).json({error:"Missing required fields: traceId, service, symbol, operation"});return}let i=n.insertSpan(r);s.json({spanId:i,traceId:r.traceId});}catch{s.status(500).json({error:"Failed to insert trace span"});}}),e.get("/",(t,s)=>{try{let r=n.queryTraces({service:t.query.service,symbol:t.query.symbol,since:t.query.since,limit:t.query.limit?parseInt(t.query.limit):20});s.json({count:r.length,traces:r});}catch{s.status(500).json({error:"Failed to query traces"});}}),e.get("/:traceId",(t,s)=>{try{let r=n.getTrace(t.params.traceId);if(!r){s.status(404).json({error:"Trace not found"});return}s.json(r);}catch{s.status(500).json({error:"Failed to get trace"});}}),e}function me(o){let e=Router(),{storage:n}=o;return e.post("/",(t,s)=>{try{let r=t.body;if(!r.id||!r.version||!r.name||!r.scope||!r.eventTypes){s.status(400).json({error:"Missing required fields: id, version, name, scope, eventTypes"});return}if(!r.scope.field||!r.scope.type||!r.scope.label||!r.scope.ordering){s.status(400).json({error:"Invalid scope: requires field, type, label, ordering"});return}if(!Array.isArray(r.eventTypes)||r.eventTypes.length===0){s.status(400).json({error:"eventTypes must be a non-empty array"});return}for(let a=0;a<r.eventTypes.length;a++){let c=r.eventTypes[a];if(!c.type||!c.category){s.status(400).json({error:`eventTypes[${a}]: missing required fields (type, category)`});return}}let i=n.registerSchema(r);s.status(201).json(i);}catch{s.status(500).json({error:"Failed to register schema"});}}),e.get("/",(t,s)=>{try{let r=n.listSchemas();s.json({count:r.length,schemas:r});}catch{s.status(500).json({error:"Failed to list schemas"});}}),e.get("/:id",(t,s)=>{try{let r=n.getSchema(t.params.id);if(!r){s.status(404).json({error:"Schema not found"});return}s.json(r);}catch{s.status(500).json({error:"Failed to get schema"});}}),e}function ge(o){let e=Router(),{storage:n,serverConfig:t,onEventReceived:s}=o,r=0;return e.post("/",(i,a)=>{try{let c=i.body;if(!c.schemaId||!c.service||!Array.isArray(c.events)){a.status(400).json({error:"Expected { schemaId, service, events: [...] }"});return}let{schemaId:l,service:d,events:u}=c,g=n.getSchema(l);if(!g){a.status(404).json({error:`Schema "${l}" not found. Register it first via POST /api/schemas.`});return}if(u.length>t.maxBatchSize){a.status(413).json({error:`Batch too large: ${u.length} events, max ${t.maxBatchSize}`});return}for(let y=0;y<u.length;y++)if(!u[y].type){a.status(400).json({error:`events[${y}]: missing required field "type"`});return}let p=n.insertEventBatch(l,d,u);if(s){let y=new Map;for(let f of g.eventTypes)y.set(f.type,f.category);for(let f of u){let T={id:f.id||"",schemaId:l,eventType:f.type,category:y.get(f.type)||"unknown",timestamp:f.timestamp||new Date().toISOString(),scopeValue:f.scopeValue!=null?String(f.scopeValue):void 0,sessionId:f.sessionId,service:d,data:f.data,severity:f.severity||"info",parentEventId:f.parentEventId,depth:f.depth};s(T);}}r+=p.accepted,t.maxLogs>0&&r>=t.pruneIntervalInserts&&(r=0,n.pruneEvents(t.maxLogs)),a.json({accepted:p.accepted,errors:p.errors.length>0?p.errors:void 0});}catch{a.status(500).json({error:"Failed to ingest events"});}}),e.get("/",(i,a)=>{try{let c={schemaId:i.query.schemaId,eventType:i.query.eventType,category:i.query.category,service:i.query.service,sessionId:i.query.sessionId,scopeValue:i.query.scopeValue,scopeFrom:i.query.scopeFrom,scopeTo:i.query.scopeTo,severity:i.query.severity,since:i.query.since,until:i.query.until,search:i.query.search,limit:i.query.limit?parseInt(i.query.limit):100,offset:i.query.offset?parseInt(i.query.offset):0},l=n.queryEvents(c),d=n.getEventCount(c);a.json({count:l.length,total:d,events:l});}catch{a.status(500).json({error:"Failed to query events"});}}),e.get("/scopes",(i,a)=>{try{let c=i.query.schemaId;if(!c){a.status(400).json({error:"schemaId query parameter is required"});return}let l=n.getEventScopes(c,{limit:i.query.limit?parseInt(i.query.limit):100,offset:i.query.offset?parseInt(i.query.offset):0,sessionId:i.query.sessionId});a.json({count:l.length,scopes:l});}catch{a.status(500).json({error:"Failed to query scopes"});}}),e.get("/scope/:value",(i,a)=>{try{let c=i.query.schemaId;if(!c){a.status(400).json({error:"schemaId query parameter is required"});return}let l=n.queryEventsByScope(c,i.params.value);a.json({count:l.length,events:l});}catch{a.status(500).json({error:"Failed to query scope events"});}}),e}function pe(o){return function(n){return (t,s,r)=>{if(!o.enabled){r();return}let i=t.headers.authorization;if(!i){s.status(401).json({error:"Authentication required. Provide Authorization: Bearer <token>"});return}let a=i.match(/^Bearer\s+(.+)$/i);if(!a){s.status(401).json({error:"Invalid authorization format. Use: Bearer <token>"});return}let c=a[1],l=o.tokens.find(g=>g.token===c);if(!l){s.status(401).json({error:"Invalid token"});return}if(l.expiresAt&&new Date(l.expiresAt)<new Date){s.status(401).json({error:"Token expired"});return}let d={read:1,write:2,admin:3};if(!l.permissions.some(g=>d[g]>=d[n])){s.status(403).json({error:`Insufficient permissions. Required: ${n}`});return}t.authToken=l,r();}}}var fe=new Map,Ct={count:0,windowStart:Date.now()},ye=6e4;function je(o){let e=Date.now();return e-o.windowStart>ye&&(o.count=0,o.windowStart=e),o}function he(o){return (e,n,t)=>{if(!o.enabled){t();return}let s=e.body?.service||e.body?.entries?.[0]?.service||e.query.service||"_unknown",r=o.perService[s]||o.global;if(r.samplingRate<1&&Math.random()>r.samplingRate){n.status(200).json({accepted:0,sampled:true,message:"Request dropped by sampling"});return}let i=je(Ct);if(i.count>=o.global.maxRequestsPerMinute){n.status(429).json({error:"Global rate limit exceeded",retryAfterMs:ye-(Date.now()-i.windowStart)});return}fe.has(s)||fe.set(s,{count:0,windowStart:Date.now()});let a=je(fe.get(s));if(a.count>=r.maxRequestsPerMinute){n.status(429).json({error:`Rate limit exceeded for service: ${s}`,retryAfterMs:ye-(Date.now()-a.windowStart)});return}let c=e.body?.entries?.length||1;if(c>r.maxEntriesPerBatch){n.status(413).json({error:`Batch too large: ${c} entries, max ${r.maxEntriesPerBatch} for service ${s}`});return}i.count++,a.count++,t();}}var At={enabled:false,tokens:[]},Pt={enabled:false,global:{maxRequestsPerMinute:600,maxEntriesPerBatch:500,samplingRate:1},perService:{}},Fe={port:3838,maxLogs:1e4,maxBatchSize:500,wsMaxSubscribers:256,pruneIntervalInserts:100,logRetentionDays:0,auth:At,rateLimit:Pt};var $t=[".sentinel.yaml",".sentinel.yml"];function Me(o){for(let e of $t){let n=S.join(o,e);if(E.existsSync(n)){let t=E.readFileSync(n,"utf-8");return jt(t)}}return null}function De(o,e){let n=S.join(o,".sentinel.yaml"),t=Ft(e);E.writeFileSync(n,t,"utf-8");}function jt(o){let e={version:"1.0",project:""},n=o.split(`
429
+ `),t=null,s=null;for(let r of n){let i=r.trimEnd();if(!i||i.startsWith("#"))continue;let a=i.match(/^(\w+):\s*(.+)$/);if(a){let[,p,y]=a;p==="version"?e.version=y.replace(/['"]/g,""):p==="project"?e.project=y.replace(/['"]/g,""):p==="environment"&&(e.environment=y.replace(/['"]/g,"")),t=null,s=null;continue}let c=i.match(/^(\w+):$/);if(c){t=c[1],s=null,t==="symbols"&&!e.symbols&&(e.symbols={}),t==="routes"&&!e.routes&&(e.routes={}),t==="scrub"&&!e.scrub&&(e.scrub={}),t==="server"&&!e.server&&(e.server={});continue}let l=i.match(/^\s{2}(\w+):$/);if(l&&t){s=l[1],t==="symbols"&&e.symbols&&(e.symbols[s]=[]),t==="scrub"&&e.scrub&&(e.scrub[s]=[]);continue}let d=i.match(/^\s+-\s+(.+)$/);if(d&&t&&s){let p=d[1].replace(/['"]/g,"");if(t==="symbols"&&e.symbols){let y=e.symbols[s];Array.isArray(y)&&y.push(p);}if(t==="scrub"&&e.scrub){let y=e.scrub[s];Array.isArray(y)&&y.push(p);}continue}let u=i.match(/^\s+(['"]?\/[^'"]+['"]?):\s+['"]?([^'"]+)['"]?$/);if(u&&t==="routes"&&e.routes){let p=u[1].replace(/['"]/g,"");e.routes[p]=u[2];continue}let g=i.match(/^\s+(\w+):\s+(\d+)$/);if(g&&t==="server"&&e.server){let p=g[1],y=parseInt(g[2],10);p in{port:1,maxLogs:1,maxBatchSize:1,wsMaxSubscribers:1,pruneIntervalInserts:1,logRetentionDays:1}&&(e.server[p]=y);continue}}return e}function Ft(o){let e=[];if(e.push("# Sentinel Configuration"),e.push("# Auto-generated \u2014 edit freely"),e.push(""),e.push(`version: "${o.version}"`),e.push(`project: "${o.project}"`),o.environment&&e.push(`environment: "${o.environment}"`),o.symbols){e.push(""),e.push("symbols:");for(let[n,t]of Object.entries(o.symbols))if(t&&t.length>0){e.push(` ${n}:`);for(let s of t)e.push(` - ${s}`);}}if(o.routes&&Object.keys(o.routes).length>0){e.push(""),e.push("routes:");for(let[n,t]of Object.entries(o.routes))e.push(` "${n}": ${t}`);}if(o.scrub){if(e.push(""),e.push("scrub:"),o.scrub.headers?.length){e.push(" headers:");for(let n of o.scrub.headers)e.push(` - ${n}`);}if(o.scrub.fields?.length){e.push(" fields:");for(let n of o.scrub.fields)e.push(` - ${n}`);}}if(o.server&&Object.keys(o.server).length>0){e.push(""),e.push("server:");for(let[n,t]of Object.entries(o.server))t!==void 0&&e.push(` ${n}: ${t}`);}return e.push(""),e.join(`
430
+ `)}function ve(o){let e={...Fe},n=o?Me(o):null,t=S.join(process.env.HOME||"~",".paradigm"),s=Me(t);for(let r of [s,n])r?.server&&(r.server.port!==void 0&&(e.port=r.server.port),r.server.maxLogs!==void 0&&(e.maxLogs=r.server.maxLogs),r.server.maxBatchSize!==void 0&&(e.maxBatchSize=r.server.maxBatchSize),r.server.wsMaxSubscribers!==void 0&&(e.wsMaxSubscribers=r.server.wsMaxSubscribers),r.server.pruneIntervalInserts!==void 0&&(e.pruneIntervalInserts=r.server.pruneIntervalInserts),r.server.logRetentionDays!==void 0&&(e.logRetentionDays=r.server.logRetentionDays));return process.env.SENTINEL_PORT&&(e.port=parseInt(process.env.SENTINEL_PORT,10)),process.env.SENTINEL_MAX_LOGS&&(e.maxLogs=parseInt(process.env.SENTINEL_MAX_LOGS,10)),e}var Ee={id:"paradigm-logger",version:"1.0.0",name:"Paradigm Logger",description:"Structured logs from @a-company/paradigm-logger with symbolic context",scope:{field:"correlationId",type:"string",label:"Correlation",ordering:"independent",sessionField:"sessionId"},eventTypes:[{type:"log:debug",category:"logs",label:"Debug Log",severity:"debug",frequency:"high",fields:[{name:"symbol",type:"string",indexed:true,display:true},{name:"symbolType",type:"string",indexed:true,display:true},{name:"message",type:"string",display:true},{name:"service",type:"string",indexed:true,display:true},{name:"durationMs",type:"number",display:true}]},{type:"log:info",category:"logs",label:"Info Log",severity:"info",frequency:"high",fields:[{name:"symbol",type:"string",indexed:true,display:true},{name:"symbolType",type:"string",indexed:true,display:true},{name:"message",type:"string",display:true},{name:"service",type:"string",indexed:true,display:true},{name:"durationMs",type:"number",display:true}]},{type:"log:warn",category:"logs",label:"Warning Log",severity:"warn",frequency:"medium",fields:[{name:"symbol",type:"string",indexed:true,display:true},{name:"symbolType",type:"string",indexed:true,display:true},{name:"message",type:"string",display:true},{name:"service",type:"string",indexed:true,display:true}]},{type:"log:error",category:"logs",label:"Error Log",severity:"error",frequency:"low",fields:[{name:"symbol",type:"string",indexed:true,display:true},{name:"symbolType",type:"string",indexed:true,display:true},{name:"message",type:"string",display:true},{name:"service",type:"string",indexed:true,display:true}]},{type:"metric:counter",category:"metrics",label:"Counter Metric",severity:"info",frequency:"high",fields:[{name:"name",type:"string",indexed:true,display:true},{name:"value",type:"number",display:true},{name:"tags",type:"object"}]},{type:"metric:gauge",category:"metrics",label:"Gauge Metric",severity:"info",frequency:"medium",fields:[{name:"name",type:"string",indexed:true,display:true},{name:"value",type:"number",display:true},{name:"tags",type:"object"}]},{type:"metric:histogram",category:"metrics",label:"Histogram Metric",severity:"info",frequency:"medium",fields:[{name:"name",type:"string",indexed:true,display:true},{name:"value",type:"number",display:true},{name:"tags",type:"object"}]},{type:"trace:span",category:"traces",label:"Trace Span",severity:"info",frequency:"medium",fields:[{name:"traceId",type:"string",indexed:true,display:true},{name:"spanId",type:"string",indexed:true},{name:"operation",type:"string",display:true},{name:"durationMs",type:"number",display:true},{name:"status",type:"string",display:true}]},{type:"incident:recorded",category:"incidents",label:"Incident Recorded",severity:"error",frequency:"low",fields:[{name:"incidentId",type:"string",indexed:true,display:true},{name:"errorMessage",type:"string",display:true},{name:"symbols",type:"object"},{name:"environment",type:"string",display:true}]}],visualization:{defaultView:"table",categoryColors:{logs:"#3b82f6",metrics:"#22c55e",traces:"#a855f7",incidents:"#ef4444"},summaryFields:["symbol","message","service"],defaultExcluded:["log:debug"]},tags:["builtin","paradigm"]};var Te={id:"paradigm-symphony",version:"1.0.0",name:"Symphony Conversations",description:"Agent-to-agent messaging events from The Score protocol",scope:{field:"threadId",type:"string",label:"Thread",ordering:"independent",sessionField:"sessionId"},eventTypes:[{type:"note:question",category:"dialogue",label:"Question",severity:"info",frequency:"high",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:context",category:"dialogue",label:"Context",severity:"info",frequency:"high",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:clarification",category:"dialogue",label:"Clarification",severity:"info",frequency:"medium",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:verification",category:"dialogue",label:"Verification",severity:"info",frequency:"medium",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:reference",category:"dialogue",label:"Reference",severity:"info",frequency:"medium",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:proposal",category:"action",label:"Proposal",severity:"info",frequency:"medium",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"diff",type:"string"},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:action",category:"action",label:"Action",severity:"info",frequency:"medium",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"diff",type:"string"},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:decision",category:"outcome",label:"Decision",severity:"warn",frequency:"low",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"decision",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:approval",category:"outcome",label:"Approval",severity:"info",frequency:"low",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"parentId",type:"string",indexed:true}]},{type:"note:rejection",category:"outcome",label:"Rejection",severity:"warn",frequency:"low",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"parentId",type:"string",indexed:true}]},{type:"note:alert",category:"system",label:"Alert",severity:"error",frequency:"low",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"symbols",type:"object"},{name:"parentId",type:"string",indexed:true}]},{type:"note:handoff",category:"lifecycle",label:"Handoff",severity:"info",frequency:"low",fields:[{name:"sender",type:"string",indexed:true,display:true},{name:"senderRole",type:"string",indexed:true,display:true},{name:"text",type:"string",display:true},{name:"parentId",type:"string",indexed:true}]},{type:"thread:created",category:"lifecycle",label:"Thread Created",severity:"info",frequency:"low",fields:[{name:"topic",type:"string",display:true},{name:"initiator",type:"string",indexed:true,display:true}]},{type:"thread:resolved",category:"lifecycle",label:"Thread Resolved",severity:"info",frequency:"low",fields:[{name:"topic",type:"string",display:true},{name:"decision",type:"string",display:true}]},{type:"participant:joined",category:"lifecycle",label:"Participant Joined",severity:"info",frequency:"low",fields:[{name:"participantId",type:"string",indexed:true,display:true},{name:"participantName",type:"string",display:true},{name:"participantRole",type:"string",display:true}]},{type:"participant:left",category:"lifecycle",label:"Participant Left",severity:"info",frequency:"low",fields:[{name:"participantId",type:"string",indexed:true,display:true},{name:"participantName",type:"string",display:true}]},{type:"file:requested",category:"transfer",label:"File Requested",severity:"info",frequency:"low",fields:[{name:"requestId",type:"string",indexed:true,display:true},{name:"filePath",type:"string",display:true},{name:"requester",type:"string",indexed:true,display:true},{name:"reason",type:"string",display:true},{name:"urgency",type:"string",display:true}]},{type:"file:approved",category:"transfer",label:"File Approved",severity:"info",frequency:"low",fields:[{name:"requestId",type:"string",indexed:true,display:true},{name:"filePath",type:"string",display:true},{name:"size",type:"number",display:true},{name:"hash",type:"string"}]},{type:"file:denied",category:"transfer",label:"File Denied",severity:"warn",frequency:"low",fields:[{name:"requestId",type:"string",indexed:true,display:true},{name:"filePath",type:"string",display:true},{name:"reason",type:"string",display:true}]},{type:"file:delivered",category:"transfer",label:"File Delivered",severity:"info",frequency:"low",fields:[{name:"requestId",type:"string",indexed:true,display:true},{name:"filePath",type:"string",display:true},{name:"size",type:"number",display:true},{name:"hash",type:"string"}]}],visualization:{defaultView:"tree",categoryColors:{dialogue:"#7dd3fc",action:"#86efac",outcome:"#fbbf24",system:"#f87171",lifecycle:"#a78bfa",transfer:"#34d399"},summaryFields:["sender","text","senderRole"],defaultExcluded:[]},tags:["builtin","symphony"]};var Ut=fileURLToPath(import.meta.url),be=S.dirname(Ut),N={component(o){let e=m.magenta(`#${o}`);return {info:(n,t)=>{let s=t?m.gray(` ${Object.entries(t).map(([r,i])=>`${r}=${i}`).join(" ")}`):"";console.log(`${m.blue("\u2139")} ${e} ${n}${s}`);},success:(n,t)=>{let s=t?m.gray(` ${Object.entries(t).map(([r,i])=>`${r}=${i}`).join(" ")}`):"";console.log(`${m.green("\u2714")} ${e} ${n}${s}`);},warn:(n,t)=>{let s=t?m.gray(` ${Object.entries(t).map(([r,i])=>`${r}=${i}`).join(" ")}`):"";console.log(`${m.yellow("\u26A0")} ${e} ${n}${s}`);},error:(n,t)=>{let s=t?m.gray(` ${Object.entries(t).map(([r,i])=>`${r}=${i}`).join(" ")}`):"";console.error(`${m.red("\u2716")} ${e} ${n}${s}`);}}}};function kt(o){let e=Se();if(e.use(Se.json({limit:"5mb"})),e.use((s,r,i)=>{let a=o.serverConfig?.cors?.origin,c=Array.isArray(a)?a.join(", "):a??"*";if(r.header("Access-Control-Allow-Origin",c),r.header("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS"),r.header("Access-Control-Allow-Headers","Content-Type, Authorization"),o.serverConfig?.cors?.credentials&&r.header("Access-Control-Allow-Credentials","true"),s.method==="OPTIONS"){r.sendStatus(204);return}i();}),e.use("/api/symbols",ee(o.projectDir)),e.use("/api/info",te(o.projectDir)),e.use("/api/commits",se(o.projectDir)),e.use("/api/incidents",re()),e.use("/api/patterns",ie()),o.storage&&o.serverConfig){let s=o.serverConfig,r=pe(s.auth),i=he(s.rateLimit);e.use("/api/logs",i,r("write"),ae({storage:o.storage,serverConfig:s,onLogReceived:o.onLogReceived,symbolIndex:o.symbolIndex})),e.use("/api/services",i,r("write"),ce({storage:o.storage})),e.use("/api/state",i,r("write"),le({storage:o.storage})),e.use("/api/metrics",i,r("write"),ue({storage:o.storage,serverConfig:s})),e.use("/api/traces",i,r("write"),de({storage:o.storage})),e.use("/api/schemas",i,r("write"),me({storage:o.storage})),e.use("/api/events",i,r("write"),ge({storage:o.storage,serverConfig:s,onEventReceived:o.onEventReceived}));}e.get("/api/health",(s,r)=>{r.json({status:"ok",timestamp:new Date().toISOString()});});let t=[S.join(be,"sentinel-ui"),S.join(be,"..","..","ui","dist"),S.join(be,"..","ui","dist")].find(s=>E.existsSync(s));return t&&(e.use(Se.static(t)),e.get("{*path}",(s,r)=>{s.path.startsWith("/api")||r.sendFile(S.join(t,"index.html"));})),e}async function ke(o){let e=ve(o.projectDir);o.logPruneLimit!==void 0&&(e.maxLogs=o.logPruneLimit);let n=new _(o.dbPath);await n.ensureReady(),n.registerSchema(Ee),n.registerSchema(Te),N.component("sentinel-server").info("Registered builtin schemas",{schemas:"paradigm-logger, paradigm-symphony"});let t=[];try{t=await $(o.projectDir);}catch{N.component("sentinel-server").warn("Could not load symbol index for validation");}let s=new Set;function r(l){let d=JSON.stringify(l);for(let u of s)u.readyState===WebSocket.OPEN&&u.send(d);}function i(l,d){let u={type:"log",entry:l};d&&!d.known&&(u.validation=d),r(u),(l.symbolType==="signal"||l.symbolType==="gate"||l.symbolType==="flow")&&r({type:"flow_event",flowId:l.symbolType==="flow"?l.symbol:void 0,nodeSymbol:l.symbol,event:l.symbolType,timestamp:l.timestamp,service:l.service});}function a(l){r({type:"event",event:l});}let c=kt({...o,storage:n,serverConfig:e,symbolIndex:t,onLogReceived:i,onEventReceived:a});return N.component("sentinel-server").info("Starting server",{port:o.port}),N.component("sentinel-server").info("Project directory",{path:o.projectDir}),new Promise((l,d)=>{let u=Xe.createServer(c);new WebSocketServer({server:u}).on("connection",p=>{if(s.size>=e.wsMaxSubscribers){p.close(1013,"Max subscribers reached");return}s.add(p),N.component("sentinel-ws").info("Client connected",{total:s.size}),p.on("message",y=>{try{let f=JSON.parse(y.toString());if(f.method==="ping")p.send(JSON.stringify({jsonrpc:"2.0",result:{pong:!0,timestamp:new Date().toISOString()},id:f.id}));else if(f.method==="subscribe")p.send(JSON.stringify({jsonrpc:"2.0",result:{subscribed:!0},id:f.id}));else if(f.method==="query_logs"){let T=n.queryLogs(f.params||{});p.send(JSON.stringify({jsonrpc:"2.0",result:{logs:T},id:f.id}));}else if(f.method==="query_events"){let T=n.queryEvents(f.params||{});p.send(JSON.stringify({jsonrpc:"2.0",result:{events:T},id:f.id}));}else if(f.method==="query_scopes"){let{schemaId:T,...j}=f.params||{},X=T?n.getEventScopes(T,j):[];p.send(JSON.stringify({jsonrpc:"2.0",result:{scopes:X},id:f.id}));}}catch{}}),p.on("close",()=>{s.delete(p),N.component("sentinel-ws").info("Client disconnected",{total:s.size});}),p.on("error",()=>{s.delete(p);});}),u.listen(o.port,()=>{N.component("sentinel-server").success("Server running",{url:`http://localhost:${o.port}`}),N.component("sentinel-ws").success("WebSocket ready",{url:`ws://localhost:${o.port}`}),o.open&&import('open').then(p=>{p.default(`http://localhost:${o.port}`),N.component("sentinel-server").info("Opened browser");}).catch(()=>{N.component("sentinel-server").warn("Could not open browser automatically");}),l();}),u.on("error",p=>{p.code==="EADDRINUSE"?N.component("sentinel-server").error("Port already in use",{port:o.port}):N.component("sentinel-server").error("Server error",{error:p.message}),d(p);});})}var qt=[{dirs:["services","src/services"],prefix:"#",type:"components"},{dirs:["routes","src/routes","api","src/api"],prefix:"#",type:"components"},{dirs:["handlers","src/handlers"],prefix:"#",type:"components"},{dirs:["controllers","src/controllers"],prefix:"#",type:"components"},{dirs:["components","src/components"],prefix:"#",type:"components"},{dirs:["lib","src/lib"],prefix:"#",type:"components"},{dirs:["middleware","src/middleware"],prefix:"^",type:"gates"},{dirs:["guards","src/guards"],prefix:"^",type:"gates"},{dirs:["auth","src/auth"],prefix:"^",type:"gates"},{dirs:["events","src/events"],prefix:"!",type:"signals"},{dirs:["listeners","src/listeners"],prefix:"!",type:"signals"},{dirs:["flows","src/flows"],prefix:"$",type:"flows"},{dirs:["workflows","src/workflows"],prefix:"$",type:"flows"},{dirs:["pipelines","src/pipelines"],prefix:"$",type:"flows"}],qe=new Set([".ts",".js",".tsx",".jsx",".mjs",".mts"]);function zt(o){let e={components:[],gates:[],flows:[],signals:[],routes:{}},n=Bt(o);n&&(e.components.push(...n.components),e.gates.push(...n.gates),e.flows.push(...n.flows),e.signals.push(...n.signals));for(let t of qt)for(let s of t.dirs){let r=S.join(o,s);if(!E.existsSync(r))continue;let i=Be(r);for(let a of i){let c=S.extname(a);if(!qe.has(c))continue;let l=S.basename(a,c);if(l==="index"||l.endsWith(".test")||l.endsWith(".spec"))continue;let d=`${t.prefix}${Ie(l)}`;e[t.type].includes(d)||e[t.type].push(d);}}return Gt(o,e),e}function ze(o){let e=zt(o);return {version:"1.0",project:S.basename(o),symbols:{components:e.components.length>0?e.components:void 0,gates:e.gates.length>0?e.gates:void 0,flows:e.flows.length>0?e.flows:void 0,signals:e.signals.length>0?e.signals:void 0},routes:Object.keys(e.routes).length>0?e.routes:void 0}}function Bt(o){let e=S.join(o,".paradigm");if(!E.existsSync(e))return null;let n={components:[],gates:[],flows:[],signals:[],routes:{}},t=He(o,".purpose");for(let r of t)try{let i=E.readFileSync(r,"utf-8");Ht(i,n);}catch{}return n.components.length>0||n.gates.length>0||n.flows.length>0||n.signals.length>0?n:null}function Ht(o,e){let n=o.split(`
431
+ `),t="";for(let s of n){let r=s.trim();if(r==="components:"||r==="features:"){t="components";continue}if(r==="gates:"){t="gates";continue}if(r==="flows:"){t="flows";continue}if(r==="signals:"){t="signals";continue}if(t&&/^\s{2}\S/.test(s)){let i=r.match(/^([a-zA-Z][\w-]*):$/);if(i){let l=`${{components:"#",gates:"^",flows:"$",signals:"!"}[t]||"#"}${i[1]}`;e[t]?.includes(l)||e[t]?.push(l);}}r&&!s.startsWith(" ")&&!r.endsWith(":")&&(t="");}}function Gt(o,e){let n=["routes","src/routes","api","src/api"];for(let t of n){let s=S.join(o,t);if(!E.existsSync(s))continue;let r=Be(s);for(let i of r){let a=S.extname(i);if(!qe.has(a))continue;let c=S.basename(i,a);if(c==="index")continue;let l=`/api/${Ie(c)}`,d=`#${Ie(c)}`;e.routes[l]=d;}}}function Ie(o){return o.replace(/([a-z])([A-Z])/g,"$1-$2").replace(/[_\s]+/g,"-").replace(/\..*$/,"").toLowerCase()}function Be(o){try{return E.readdirSync(o).filter(e=>{let n=S.join(o,e);try{return E.statSync(n).isFile()}catch{return !1}})}catch{return []}}function He(o,e,n=4,t=0){if(t>n)return [];let s=[],r=new Set(["node_modules","dist",".git","coverage",".next",".nuxt"]);try{let i=E.readdirSync(o,{withFileTypes:!0});for(let a of i)a.isFile()&&a.name===e?s.push(S.join(o,a.name)):a.isDirectory()&&!r.has(a.name)&&s.push(...He(S.join(o,a.name),e,n,t+1));}catch{}return s}function Ge(){return `
432
+ ${m.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")}
433
+ ${m.cyan("\u2551")} ${m.bold.white("SENTINEL TRIAGE")} ${m.cyan("\u2551")}
434
+ ${m.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")}
435
+ `}function We(o){return `${m.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557")}
436
+ ${m.cyan("\u2551")} Open: ${m.yellow(String(o.open).padEnd(4))} \u2502 Investigating: ${m.blue(String(o.investigating).padEnd(3))} \u2502 Resolved: ${m.green(String(o.resolved).padEnd(4))} \u2502 Today: ${m.magenta(`+${o.today}`)} ${m.cyan("\u2551")}
437
+ ${m.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D")}
438
+ `}function Je(o,e){let n=[],t=Ke(o.status);n.push(m.gray("\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510")),n.push(m.gray("\u2502 ")+m.bold(`[${o.id}] `)+t(o.status.toUpperCase().padEnd(12))+m.gray(o.timestamp.substring(0,19).replace("T"," ").padStart(19))+m.gray(" \u2502")),n.push(m.gray("\u251C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2524")),n.push(m.gray("\u2502 ")+m.red("Error: ")+H(o.error.message,55)+m.gray(" \u2502")),n.push(m.gray("\u2502")+" ".repeat(65)+m.gray("\u2502")),n.push(m.gray("\u2502 ")+m.cyan("Symbolic Context:")+" ".repeat(47)+m.gray("\u2502"));let s=Wt(o.symbols);for(let i of s)n.push(m.gray("\u2502 ")+i.padEnd(61)+m.gray(" \u2502"));n.push(m.gray("\u2502")+" ".repeat(65)+m.gray("\u2502"));let r=`Environment: ${m.yellow(o.environment)} \u2502 Service: ${m.yellow(o.service||"N/A")} \u2502 v${o.version||"N/A"}`;if(n.push(m.gray("\u2502 ")+r.substring(0,63).padEnd(63)+m.gray(" \u2502")),e&&e.length>0){n.push(m.gray("\u2502")+" ".repeat(65)+m.gray("\u2502")),n.push(m.gray("\u2502 \u250C\u2500 ")+m.cyan("Matched Patterns")+m.gray(" \u2500".repeat(22)+"\u2510 \u2502"));for(let i=0;i<Math.min(e.length,3);i++){let a=e[i],c=i===0?m.yellow("\u2605"):m.gray("\u25CB"),l=`${a.confidence}% confidence`;n.push(m.gray("\u2502 \u2502 ")+c+" "+m.bold(H(a.pattern.id,30).padEnd(30))+m.gray(l.padStart(15))+m.gray(" \u2502 \u2502")),n.push(m.gray("\u2502 \u2502 ")+m.italic(H(a.pattern.description,45).padEnd(45))+m.gray(" \u2502 \u2502")),n.push(m.gray("\u2502 \u2502 Strategy: ")+m.cyan(a.pattern.resolution.strategy.padEnd(40))+m.gray(" \u2502 \u2502")),i<Math.min(e.length,3)-1&&n.push(m.gray("\u2502 \u2502")+" ".repeat(59)+m.gray("\u2502 \u2502"));}n.push(m.gray("\u2502 \u2514")+"\u2500".repeat(59)+m.gray("\u2518 \u2502"));}return n.push(m.gray("\u2502")+" ".repeat(65)+m.gray("\u2502")),n.push(m.gray("\u2502 ")+m.dim("Actions:")+" ".repeat(56)+m.gray("\u2502")),n.push(m.gray("\u2502 ")+m.dim(`sentinel triage resolve ${o.id}`)+" ".repeat(36-o.id.length)+m.gray("\u2502")),n.push(m.gray("\u2502 ")+m.dim(`sentinel triage show ${o.id} --timeline`)+" ".repeat(29-o.id.length)+m.gray("\u2502")),n.push(m.gray("\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518")),n.join(`
439
+ `)}function Ye(o){let n=Ke(o.status)(o.status.substring(0,4).toUpperCase().padEnd(4)),t=o.timestamp.substring(5,16).replace("T"," "),s=H(o.error.message,40),r=Object.values(o.symbols).filter(Boolean).join(" ");return `${m.bold(o.id)} ${n} ${m.gray(t)} ${s}
440
+ ${m.cyan(H(r,60))}`}function Ve(o){let e=[];e.push(m.bold.cyan(`
441
+ Incident Statistics`)),e.push(m.gray("\u2500".repeat(50))),e.push(` Total: ${m.white(o.incidents.total)}`),e.push(` Open: ${m.yellow(o.incidents.open)}`),e.push(` Resolved: ${m.green(o.incidents.resolved)}`),e.push(""),e.push(m.bold.cyan("By Environment"));for(let[n,t]of Object.entries(o.incidents.byEnvironment))e.push(` ${n}: ${t}`);e.push(""),e.push(m.bold.cyan("Resolution Stats")),e.push(m.gray("\u2500".repeat(50))),e.push(` Resolution Rate: ${m.green(Math.round(o.resolution.resolutionRate)+"%")}`),e.push(` Resolved with Pattern: ${o.resolution.resolvedWithPattern}`),e.push(` Resolved Manually: ${o.resolution.resolvedManually}`),e.push(""),e.push(m.bold.cyan("Top Affected Symbols")),e.push(m.gray("\u2500".repeat(50)));for(let{symbol:n,count:t}of o.symbols.mostIncidents.slice(0,5))e.push(` ${m.cyan(n.padEnd(30))} ${t} incidents`);e.push(""),e.push(m.bold.cyan("Most Effective Patterns")),e.push(m.gray("\u2500".repeat(50)));for(let{patternId:n,resolvedCount:t}of o.patterns.mostEffective.slice(0,5))e.push(` ${n.padEnd(30)} ${t} resolved`);return e.join(`
442
+ `)}function Wt(o){let e=[];for(let[n,t]of Object.entries(o))if(t){let s=Jt(n);e.push(`${s(t.padEnd(20))} ${m.dim(n)}`);}return e}function Ke(o){switch(o){case "open":return m.red;case "investigating":return m.yellow;case "resolved":return m.green;case "wont-fix":return m.gray;default:return m.white}}function Jt(o){switch(o){case "feature":return m.magenta;case "component":return m.blue;case "flow":return m.cyan;case "gate":return m.yellow;case "signal":return m.green;case "state":return m.red;case "integration":return m.white;default:return m.gray}}function H(o,e){return o.length<=e?o:o.substring(0,e-3)+"..."}async function V(){let o=new _;await o.ensureReady();try{let{patterns:e}=Oe();for(let n of e)try{o.addPattern(n);}catch{}}catch{}return o}async function Gs(o){console.log(m.cyan(`
443
+ Sentinel Dashboard
444
+ `)),await ke({port:parseInt(o.port,10),projectDir:process.cwd(),open:o.open});}async function Ws(o){console.log(m.cyan(`
445
+ Initializing Sentinel...
446
+ `));let e=process.cwd(),n=ze(e);if(De(e,n),console.log(m.green(" Created .sentinel.yaml")),n.symbols){let s=(n.symbols.components?.length||0)+(n.symbols.gates?.length||0)+(n.symbols.flows?.length||0)+(n.symbols.signals?.length||0);s>0&&console.log(m.gray(` Detected ${s} symbols`));}let t=new _;await t.ensureReady(),t.close(),console.log(m.green(" Initialized database")),console.log(m.gray("\n Run `sentinel` to launch the dashboard\n"));}async function Js(o){let e=await V(),n=new q(e),t=e.getRecentIncidents({limit:parseInt(o.limit,10),status:o.status||"all",environment:o.env,symbol:o.symbol});if(console.log(Ge()),t.length===0){console.log(m.gray(` No incidents found.
447
+ `)),console.log(m.dim(" Record incidents via the SDK:")),console.log(m.dim(' sentinel.capture(error, { component: "#checkout" })')),console.log(m.dim(" Or via MCP:")),console.log(m.dim(` sentinel_record({ error: { message: "..." }, symbols: { component: "#checkout" }, environment: "production" })
448
+ `)),e.close();return}let s=e.getRecentIncidents({limit:1e4}),r=new Date().toISOString().substring(0,10);console.log(We({open:s.filter(i=>i.status==="open").length,investigating:s.filter(i=>i.status==="investigating").length,resolved:s.filter(i=>i.status==="resolved").length,today:s.filter(i=>i.timestamp.startsWith(r)).length}));for(let i of t){n.match(i,{maxResults:3});console.log(Ye(i));}console.log(""),e.close();}async function Ys(o,e){let n=await V(),t=new q(n),s=n.getIncident(o);if(!s){console.log(m.red(`
449
+ Incident ${o} not found
450
+ `)),n.close();return}let r=t.match(s,{maxResults:5});if(console.log(""),console.log(Je(s,r)),e.timeline&&s.flowPosition){let i=new W,a=i.build(s);a&&console.log(`
451
+ `+i.renderAscii(a));}console.log(""),n.close();}async function Vs(o,e){let n=await V();if(!n.getIncident(o)){console.log(m.red(`
452
+ Incident ${o} not found
453
+ `)),n.close();return}n.recordResolution({incidentId:o,patternId:e.pattern,commitHash:e.commit,notes:e.notes}),console.log(m.green(`
454
+ Incident ${o} resolved
455
+ `)),n.close();}async function Ks(o){let e=await V(),n=new G(e),t=o.period.match(/^(\d+)d$/),s=t?parseInt(t[1],10):7,r=n.getStats(s);console.log(Ve(r)),console.log(""),e.close();}export{Ws as initProject,Gs as launchDashboard,Js as triageList,Vs as triageResolve,Ys as triageShow,Ks as triageStats};